forked from jmug/stoatchat
feat: update to rAuth v1
This commit is contained in:
@@ -1,8 +1,7 @@
|
||||
use std::env;
|
||||
use std::ops::Deref;
|
||||
|
||||
use crate::r#impl::dummy::DummyDb;
|
||||
use crate::r#impl::mongo::MongoDb;
|
||||
use crate::r#impl::{DummyDb, MongoDb};
|
||||
use crate::AbstractDatabase;
|
||||
|
||||
/// Database information to use to create a client
|
||||
@@ -61,3 +60,14 @@ impl Deref for Database {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Database> for rauth::Database {
|
||||
fn from(val: Database) -> Self {
|
||||
match val {
|
||||
Database::Dummy(_) => rauth::Database::default(),
|
||||
Database::MongoDb(MongoDb(client)) => {
|
||||
rauth::Database::MongoDb(rauth::database::MongoDb(client.database("revolt")))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,6 @@ use crate::{perms, Database, Error, Result};
|
||||
|
||||
use futures::try_join;
|
||||
use impl_ops::impl_op_ex_commutative;
|
||||
use okapi::openapi3::{SecurityScheme, SecuritySchemeData};
|
||||
use rocket_okapi::gen::OpenApiGenerator;
|
||||
use rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
|
||||
use std::ops;
|
||||
|
||||
impl_op_ex_commutative!(+ |a: &i32, b: &Badges| -> i32 { *a | *b as i32 });
|
||||
@@ -359,72 +356,3 @@ impl User {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use rauth::entities::Session;
|
||||
use rocket::http::Status;
|
||||
use rocket::request::{self, FromRequest, Outcome, Request};
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for User {
|
||||
type Error = rauth::util::Error;
|
||||
|
||||
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
||||
let user: &Option<User> = request
|
||||
.local_cache_async(async {
|
||||
let db = request
|
||||
.rocket()
|
||||
.state::<Database>()
|
||||
.expect("Database state not reachable!");
|
||||
|
||||
let header_bot_token = request
|
||||
.headers()
|
||||
.get("x-bot-token")
|
||||
.next()
|
||||
.map(|x| x.to_string());
|
||||
|
||||
if let Some(bot_token) = header_bot_token {
|
||||
if let Ok(user) = User::from_token(db, &bot_token, UserHint::Bot).await {
|
||||
return Some(user);
|
||||
}
|
||||
} else if let Outcome::Success(session) = request.guard::<Session>().await {
|
||||
// This uses a guard so can't really easily be refactored into from_token at this stage.
|
||||
if let Ok(user) = db.fetch_user(&session.user_id).await {
|
||||
return Some(user);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
})
|
||||
.await;
|
||||
|
||||
if let Some(user) = user {
|
||||
Outcome::Success(user.clone())
|
||||
} else {
|
||||
Outcome::Failure((Status::Unauthorized, rauth::util::Error::InvalidSession))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> OpenApiFromRequest<'r> for User {
|
||||
fn from_request_input(
|
||||
_gen: &mut OpenApiGenerator,
|
||||
_name: String,
|
||||
_required: bool,
|
||||
) -> rocket_okapi::Result<RequestHeaderInput> {
|
||||
let mut requirements = schemars::Map::new();
|
||||
requirements.insert("Api Key".to_owned(), vec![]);
|
||||
|
||||
Ok(RequestHeaderInput::Security(
|
||||
"Api Key".to_owned(),
|
||||
SecurityScheme {
|
||||
data: SecuritySchemeData::ApiKey {
|
||||
name: "x-session-token".to_owned(),
|
||||
location: "header".to_owned(),
|
||||
},
|
||||
description: Some("Session Token".to_owned()),
|
||||
extensions: schemars::Map::new(),
|
||||
},
|
||||
requirements,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
pub mod dummy;
|
||||
pub mod generic;
|
||||
pub mod mongo;
|
||||
mod dummy;
|
||||
mod generic;
|
||||
mod mongo;
|
||||
|
||||
#[cfg(feature = "rocket_impl")]
|
||||
mod rocket;
|
||||
|
||||
pub use self::generic::users::user_settings::UserSettingsImpl;
|
||||
pub use dummy::DummyDb;
|
||||
pub use mongo::MongoDb;
|
||||
|
||||
@@ -17,7 +17,7 @@ struct MigrationInfo {
|
||||
revision: i32,
|
||||
}
|
||||
|
||||
pub const LATEST_REVISION: i32 = 15;
|
||||
pub const LATEST_REVISION: i32 = 16;
|
||||
|
||||
pub async fn migrate_database(db: &MongoDb) {
|
||||
let migrations = db.col::<Document>("migrations");
|
||||
@@ -603,6 +603,15 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
if revision <= 15 {
|
||||
info!("Running migration [revision 15 / 04-06-2022]: Migrate rAuth to latest version.");
|
||||
|
||||
let db = rauth::Database::MongoDb(rauth::database::MongoDb(db.db()));
|
||||
db.run_migration(rauth::Migration::M2022_06_03EnsureUpToSpec)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// Need to migrate fields on attachments, change `user_id`, `object_id`, etc to `parent`.
|
||||
|
||||
// Reminder to update LATEST_REVISION when adding new migrations.
|
||||
|
||||
73
crates/quark/src/impl/rocket.rs
Normal file
73
crates/quark/src/impl/rocket.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
use okapi::openapi3::{SecurityScheme, SecuritySchemeData};
|
||||
use rauth::models::Session;
|
||||
use rocket_okapi::gen::OpenApiGenerator;
|
||||
use rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
|
||||
|
||||
use rocket::http::Status;
|
||||
use rocket::request::{self, FromRequest, Outcome, Request};
|
||||
|
||||
use crate::models::user::UserHint;
|
||||
use crate::models::User;
|
||||
use crate::Database;
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for User {
|
||||
type Error = rauth::Error;
|
||||
|
||||
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
||||
let user: &Option<User> = request
|
||||
.local_cache_async(async {
|
||||
let db = request.rocket().state::<Database>().expect("`Database`");
|
||||
|
||||
let header_bot_token = request
|
||||
.headers()
|
||||
.get("x-bot-token")
|
||||
.next()
|
||||
.map(|x| x.to_string());
|
||||
|
||||
if let Some(bot_token) = header_bot_token {
|
||||
if let Ok(user) = User::from_token(db, &bot_token, UserHint::Bot).await {
|
||||
return Some(user);
|
||||
}
|
||||
} else if let Outcome::Success(session) = request.guard::<Session>().await {
|
||||
// This uses a guard so can't really easily be refactored into from_token at this stage.
|
||||
if let Ok(user) = db.fetch_user(&session.user_id).await {
|
||||
return Some(user);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
})
|
||||
.await;
|
||||
|
||||
if let Some(user) = user {
|
||||
Outcome::Success(user.clone())
|
||||
} else {
|
||||
Outcome::Failure((Status::Unauthorized, rauth::Error::InvalidSession))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> OpenApiFromRequest<'r> for User {
|
||||
fn from_request_input(
|
||||
_gen: &mut OpenApiGenerator,
|
||||
_name: String,
|
||||
_required: bool,
|
||||
) -> rocket_okapi::Result<RequestHeaderInput> {
|
||||
let mut requirements = schemars::Map::new();
|
||||
requirements.insert("Api Key".to_owned(), vec![]);
|
||||
|
||||
Ok(RequestHeaderInput::Security(
|
||||
"Api Key".to_owned(),
|
||||
SecurityScheme {
|
||||
data: SecuritySchemeData::ApiKey {
|
||||
name: "x-session-token".to_owned(),
|
||||
location: "header".to_owned(),
|
||||
},
|
||||
description: Some("Session Token".to_owned()),
|
||||
extensions: schemars::Map::new(),
|
||||
},
|
||||
requirements,
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ extern crate bitfield;
|
||||
pub extern crate bson;
|
||||
|
||||
pub use iso8601_timestamp::Timestamp;
|
||||
pub use rauth;
|
||||
pub use redis_kiss;
|
||||
|
||||
pub mod events;
|
||||
@@ -27,6 +28,9 @@ pub mod presence;
|
||||
pub mod tasks;
|
||||
pub mod types;
|
||||
|
||||
#[cfg(feature = "rocket_impl")]
|
||||
pub mod web;
|
||||
|
||||
mod database;
|
||||
mod permissions;
|
||||
mod traits;
|
||||
@@ -38,38 +42,11 @@ pub use traits::*;
|
||||
pub use permissions::defn::*;
|
||||
pub use permissions::{get_relationship, perms};
|
||||
|
||||
pub use util::r#ref::Ref;
|
||||
pub use util::result::{Error, Result};
|
||||
pub use util::variables;
|
||||
pub use util::{
|
||||
log::setup_logging,
|
||||
r#ref::Ref,
|
||||
result::{Error, Result},
|
||||
variables,
|
||||
};
|
||||
|
||||
#[cfg(feature = "rocket_impl")]
|
||||
pub use rocket_empty::EmptyResponse;
|
||||
|
||||
#[cfg(feature = "rocket_impl")]
|
||||
use rocket::State;
|
||||
|
||||
#[cfg(feature = "rocket_impl")]
|
||||
pub type Db = State<Database>;
|
||||
|
||||
/// Configure logging and common Rust variables
|
||||
pub fn setup_logging() -> sentry::ClientInitGuard {
|
||||
dotenv::dotenv().ok();
|
||||
|
||||
if std::env::var("RUST_LOG").is_err() {
|
||||
std::env::set_var("RUST_LOG", "info");
|
||||
}
|
||||
|
||||
if std::env::var("ROCKET_ADDRESS").is_err() {
|
||||
std::env::set_var("ROCKET_ADDRESS", "0.0.0.0");
|
||||
}
|
||||
|
||||
pretty_env_logger::init();
|
||||
|
||||
sentry::init((
|
||||
"https://62fd0e02c5354905b4e286757f4beb16@sentry.insert.moe/4",
|
||||
sentry::ClientOptions {
|
||||
release: sentry::release_name!(),
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
}
|
||||
pub use web::{Db, EmptyResponse};
|
||||
|
||||
@@ -18,7 +18,7 @@ pub async fn start_workers(db: Database) {
|
||||
task::spawn(ack::worker(db.clone()));
|
||||
task::spawn(last_message_id::worker(db.clone()));
|
||||
task::spawn(process_embeds::worker(db.clone()));
|
||||
task::spawn(web_push::worker(db.clone()));
|
||||
task::spawn(web_push::worker(db.clone().into()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
use crate::bson::doc;
|
||||
use crate::util::variables::delta::VAPID_PRIVATE_KEY;
|
||||
use crate::{bson::doc, r#impl::mongo::MongoDb, Database};
|
||||
|
||||
use deadqueue::limited::Queue;
|
||||
use futures::StreamExt;
|
||||
use rauth::entities::Session;
|
||||
use rauth::Database;
|
||||
use web_push::{
|
||||
ContentEncoding, SubscriptionInfo, SubscriptionKeys, VapidSignatureBuilder, WebPushClient,
|
||||
WebPushMessageBuilder,
|
||||
@@ -43,90 +42,69 @@ pub async fn worker(db: Database) {
|
||||
let key = base64::decode_config(VAPID_PRIVATE_KEY.clone(), base64::URL_SAFE)
|
||||
.expect("valid `VAPID_PRIVATE_KEY`");
|
||||
|
||||
if let Database::MongoDb(MongoDb(db)) = db {
|
||||
loop {
|
||||
let task = Q.pop().await;
|
||||
loop {
|
||||
let task = Q.pop().await;
|
||||
|
||||
// ! FIXME: this is hard-coded until rauth is merged into quark
|
||||
if let Ok(mut cursor) = db
|
||||
.database("revolt")
|
||||
.collection::<Session>("sessions")
|
||||
.find(
|
||||
doc! {
|
||||
"user_id": {
|
||||
"$in": task.recipients
|
||||
if let Ok(sessions) = db.find_sessions_with_subscription(&task.recipients).await {
|
||||
for session in sessions {
|
||||
if let Some(sub) = session.subscription {
|
||||
let subscription = SubscriptionInfo {
|
||||
endpoint: sub.endpoint,
|
||||
keys: SubscriptionKeys {
|
||||
auth: sub.auth,
|
||||
p256dh: sub.p256dh,
|
||||
},
|
||||
"subscription": {
|
||||
"$exists": true
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
while let Some(Ok(session)) = cursor.next().await {
|
||||
if let Some(sub) = session.subscription {
|
||||
let subscription = SubscriptionInfo {
|
||||
endpoint: sub.endpoint,
|
||||
keys: SubscriptionKeys {
|
||||
auth: sub.auth,
|
||||
p256dh: sub.p256dh,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
match WebPushMessageBuilder::new(&subscription) {
|
||||
Ok(mut builder) => {
|
||||
match VapidSignatureBuilder::from_pem(
|
||||
std::io::Cursor::new(&key),
|
||||
&subscription,
|
||||
) {
|
||||
Ok(sig_builder) => match sig_builder.build() {
|
||||
Ok(signature) => {
|
||||
builder.set_vapid_signature(signature);
|
||||
builder.set_payload(
|
||||
ContentEncoding::AesGcm,
|
||||
task.payload.as_bytes(),
|
||||
);
|
||||
match WebPushMessageBuilder::new(&subscription) {
|
||||
Ok(mut builder) => {
|
||||
match VapidSignatureBuilder::from_pem(
|
||||
std::io::Cursor::new(&key),
|
||||
&subscription,
|
||||
) {
|
||||
Ok(sig_builder) => match sig_builder.build() {
|
||||
Ok(signature) => {
|
||||
builder.set_vapid_signature(signature);
|
||||
builder.set_payload(
|
||||
ContentEncoding::AesGcm,
|
||||
task.payload.as_bytes(),
|
||||
);
|
||||
|
||||
match builder.build() {
|
||||
Ok(msg) => match client.send(msg).await {
|
||||
Ok(_) => {
|
||||
info!(
|
||||
"Sent Web Push notification to {:?}.",
|
||||
session.id
|
||||
)
|
||||
}
|
||||
Err(err) => {
|
||||
error!(
|
||||
"Hit error sending Web Push! {:?}",
|
||||
err
|
||||
)
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
error!(
|
||||
"Failed to build message for {}! {:?}",
|
||||
session.user_id, err
|
||||
match builder.build() {
|
||||
Ok(msg) => match client.send(msg).await {
|
||||
Ok(_) => {
|
||||
info!(
|
||||
"Sent Web Push notification to {:?}.",
|
||||
session.id
|
||||
)
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Hit error sending Web Push! {:?}", err)
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
error!(
|
||||
"Failed to build message for {}! {:?}",
|
||||
session.user_id, err
|
||||
)
|
||||
}
|
||||
}
|
||||
Err(err) => error!(
|
||||
"Failed to build signature for {}! {:?}",
|
||||
session.user_id, err
|
||||
),
|
||||
},
|
||||
}
|
||||
Err(err) => error!(
|
||||
"Failed to create signature builder for {}! {:?}",
|
||||
"Failed to build signature for {}! {:?}",
|
||||
session.user_id, err
|
||||
),
|
||||
}
|
||||
},
|
||||
Err(err) => error!(
|
||||
"Failed to create signature builder for {}! {:?}",
|
||||
session.user_id, err
|
||||
),
|
||||
}
|
||||
Err(err) => error!(
|
||||
"Invalid subscription information for {}! {:?}",
|
||||
session.user_id, err
|
||||
),
|
||||
}
|
||||
Err(err) => error!(
|
||||
"Invalid subscription information for {}! {:?}",
|
||||
session.user_id, err
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
22
crates/quark/src/util/log.rs
Normal file
22
crates/quark/src/util/log.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
/// Configure logging and common Rust variables
|
||||
pub fn setup_logging() -> sentry::ClientInitGuard {
|
||||
dotenv::dotenv().ok();
|
||||
|
||||
if std::env::var("RUST_LOG").is_err() {
|
||||
std::env::set_var("RUST_LOG", "info");
|
||||
}
|
||||
|
||||
if std::env::var("ROCKET_ADDRESS").is_err() {
|
||||
std::env::set_var("ROCKET_ADDRESS", "0.0.0.0");
|
||||
}
|
||||
|
||||
pretty_env_logger::init();
|
||||
|
||||
sentry::init((
|
||||
"https://62fd0e02c5354905b4e286757f4beb16@sentry.insert.moe/4",
|
||||
sentry::ClientOptions {
|
||||
release: sentry::release_name!(),
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod log;
|
||||
pub mod manipulation;
|
||||
pub mod r#ref;
|
||||
pub mod result;
|
||||
|
||||
5
crates/quark/src/web/mod.rs
Normal file
5
crates/quark/src/web/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
use crate::Database;
|
||||
use rocket::State;
|
||||
|
||||
pub use rocket_empty::EmptyResponse;
|
||||
pub type Db = State<Database>;
|
||||
Reference in New Issue
Block a user