diff --git a/apps/labrinth/.sqlx/query-914f186afcc80dcbaed00a2cb16d398ba57e653c1a2d896201ccc39b2912cae2.json b/apps/labrinth/.sqlx/query-4d9c93a745ef80cd2513dd1b9064e2faed17c2326a35addeeb49ee07d49c8713.json similarity index 57% rename from apps/labrinth/.sqlx/query-914f186afcc80dcbaed00a2cb16d398ba57e653c1a2d896201ccc39b2912cae2.json rename to apps/labrinth/.sqlx/query-4d9c93a745ef80cd2513dd1b9064e2faed17c2326a35addeeb49ee07d49c8713.json index 0a22e52207f..4f0cdfc48f5 100644 --- a/apps/labrinth/.sqlx/query-914f186afcc80dcbaed00a2cb16d398ba57e653c1a2d896201ccc39b2912cae2.json +++ b/apps/labrinth/.sqlx/query-4d9c93a745ef80cd2513dd1b9064e2faed17c2326a35addeeb49ee07d49c8713.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n INSERT INTO sessions (\n id, session, user_id, os, platform,\n city, country, ip, user_agent,\n expires, refresh_expires\n )\n VALUES (\n $1, $2, $3, $4, $5,\n $6, $7, $8, $9,\n $10, $11\n )\n ", + "query": "\n INSERT INTO sessions (\n id, session, user_id, os, platform,\n city, country, ip, user_agent,\n expires, refresh_expires, created\n )\n VALUES (\n $1, $2, $3, $4, $5,\n $6, $7, $8, $9,\n $10, $11, COALESCE($12, NOW())\n )\n ", "describe": { "columns": [], "parameters": { @@ -15,10 +15,11 @@ "Varchar", "Varchar", "Timestamptz", + "Timestamptz", "Timestamptz" ] }, "nullable": [] }, - "hash": "914f186afcc80dcbaed00a2cb16d398ba57e653c1a2d896201ccc39b2912cae2" + "hash": "4d9c93a745ef80cd2513dd1b9064e2faed17c2326a35addeeb49ee07d49c8713" } diff --git a/apps/labrinth/src/auth/mod.rs b/apps/labrinth/src/auth/mod.rs index a63ff2970c9..67e70840faf 100644 --- a/apps/labrinth/src/auth/mod.rs +++ b/apps/labrinth/src/auth/mod.rs @@ -36,6 +36,8 @@ pub enum AuthenticationError { Mail(#[from] crate::queue::email::MailError), #[error("Invalid Authentication Credentials")] InvalidCredentials, + #[error("you must reauthenticate to perform this action")] + PrivilegedTokenExpired, #[error("Authentication method was not valid")] InvalidAuthMethod, #[error("GitHub Token from incorrect Client ID")] @@ -73,7 +75,10 @@ impl actix_web::ResponseError for AuthenticationError { AuthenticationError::Reqwest(..) => { StatusCode::INTERNAL_SERVER_ERROR } - AuthenticationError::InvalidCredentials => StatusCode::UNAUTHORIZED, + AuthenticationError::InvalidCredentials + | AuthenticationError::PrivilegedTokenExpired => { + StatusCode::UNAUTHORIZED + } AuthenticationError::Decoding(..) => StatusCode::BAD_REQUEST, AuthenticationError::Mail(..) => StatusCode::INTERNAL_SERVER_ERROR, AuthenticationError::InvalidAuthMethod => StatusCode::UNAUTHORIZED, @@ -110,6 +115,9 @@ impl AuthenticationError { AuthenticationError::SerDe(..) => "invalid_input", AuthenticationError::Reqwest(..) => "network_error", AuthenticationError::InvalidCredentials => "invalid_credentials", + AuthenticationError::PrivilegedTokenExpired => { + "privileged_token_expired" + } AuthenticationError::Decoding(..) => "decoding_error", AuthenticationError::Mail(..) => "mail_error", AuthenticationError::InvalidAuthMethod => "invalid_auth_method", diff --git a/apps/labrinth/src/auth/oauth/errors.rs b/apps/labrinth/src/auth/oauth/errors.rs index e178c9f6829..6c1ae54a563 100644 --- a/apps/labrinth/src/auth/oauth/errors.rs +++ b/apps/labrinth/src/auth/oauth/errors.rs @@ -58,8 +58,10 @@ impl OAuthError { impl actix_web::ResponseError for OAuthError { fn status_code(&self) -> StatusCode { match *self.error_type { - OAuthErrorType::AuthenticationError(_) - | OAuthErrorType::FailedScopeParse(_) + OAuthErrorType::AuthenticationError(ref error) => { + error.status_code() + } + OAuthErrorType::FailedScopeParse(_) | OAuthErrorType::ScopesTooBroad | OAuthErrorType::AccessDenied => { if self.valid_redirect_uri.is_some() { @@ -84,6 +86,10 @@ impl actix_web::ResponseError for OAuthError { } fn error_response(&self) -> HttpResponse { + if let OAuthErrorType::AuthenticationError(error) = &*self.error_type { + return error.error_response(); + } + if let Some(ValidatedRedirectUri(mut redirect_uri)) = self.valid_redirect_uri.clone() { @@ -174,9 +180,8 @@ impl OAuthErrorType { match self { Self::RedirectUriNotConfigured(_) | Self::ClientMissingRedirectURI { client_id: _ } => "invalid_uri", - Self::AuthenticationError(_) | Self::InvalidAcceptFlowId => { - "server_error" - } + Self::AuthenticationError(error) => error.error_name(), + Self::InvalidAcceptFlowId => "server_error", Self::RedirectUriChanged(_) | Self::MalformedId(_) => { "invalid_request" } diff --git a/apps/labrinth/src/auth/oauth/mod.rs b/apps/labrinth/src/auth/oauth/mod.rs index 1663023649f..56b0f174b88 100644 --- a/apps/labrinth/src/auth/oauth/mod.rs +++ b/apps/labrinth/src/auth/oauth/mod.rs @@ -87,6 +87,9 @@ pub async fn init_oauth( .await? .user; + crate::auth::validate::require_privileged_token(&req, &**pool, &redis) + .await?; + let client_id = oauth_info.client_id.into(); let client = DBOAuthClient::get(client_id, &**pool).await?; @@ -354,6 +357,11 @@ pub async fn accept_or_reject_client_scopes( .await? .user; + if accept { + crate::auth::validate::require_privileged_token(&req, &**pool, &redis) + .await?; + } + let flow = DBFlow::take_if( &body.flow, |f| matches!(f, DBFlow::InitOAuthAppApproval { .. }), diff --git a/apps/labrinth/src/auth/validate.rs b/apps/labrinth/src/auth/validate.rs index 5610c5b2d40..4d90677f63c 100644 --- a/apps/labrinth/src/auth/validate.rs +++ b/apps/labrinth/src/auth/validate.rs @@ -1,6 +1,9 @@ use super::AuthProvider; use crate::auth::AuthenticationError; -use crate::database::models::{DBUser, user_item}; +use crate::database::models::{ + DBUser, oauth_token_item::DBOAuthAccessToken, + pat_item::DBPersonalAccessToken, session_item::DBSession, user_item, +}; use crate::env::ENV; use crate::models::pats::Scopes; use crate::models::users::{Role, User}; @@ -144,6 +147,49 @@ where }) } +enum BearerToken { + Session(DBSession), + PersonalAccessToken(DBPersonalAccessToken), + OAuthAccessToken(DBOAuthAccessToken), +} + +impl BearerToken { + fn timestamps(&self) -> (chrono::DateTime, chrono::DateTime) { + match self { + Self::Session(token) => (token.created, token.expires), + Self::PersonalAccessToken(token) => (token.created, token.expires), + Self::OAuthAccessToken(token) => (token.created, token.expires), + } + } +} + +/// Resolves a first-party bearer credential without loading its user or recording usage. +async fn resolve_bearer_token<'a, E>( + token: &str, + executor: E, + redis: &RedisPool, +) -> Result +where + E: crate::database::Executor<'a, Database = sqlx::Postgres>, +{ + let token = match token.split_once('_') { + Some(("mra", _)) => DBSession::get(token, executor, redis) + .await? + .map(BearerToken::Session), + Some(("mrp", _)) => DBPersonalAccessToken::get(token, executor, redis) + .await? + .map(BearerToken::PersonalAccessToken), + Some(("mro", _)) => DBOAuthAccessToken::get( + DBOAuthAccessToken::hash_token(token), + executor, + ) + .await? + .map(BearerToken::OAuthAccessToken), + _ => return Err(AuthenticationError::InvalidAuthMethod), + }; + token.ok_or(AuthenticationError::InvalidCredentials) +} + pub async fn get_user_record_from_bearer_token<'a, 'b, E>( req: &HttpRequest, token: Option<&str>, @@ -161,80 +207,9 @@ where extract_authorization_header(req)? }; - let possible_user = match token.split_once('_') { - Some(("mrp", _)) => { - let pat = - crate::database::models::pat_item::DBPersonalAccessToken::get( - token, executor, redis, - ) - .await? - .ok_or_else(|| AuthenticationError::InvalidCredentials)?; - - if !allow_expired && pat.expires < Utc::now() { - return Err(AuthenticationError::InvalidCredentials); - } - - let user = - user_item::DBUser::get_id(pat.user_id, executor, redis).await?; - - session_queue.add_pat(pat.id).await; - - user.map(|x| (pat.scopes, x)) - } - Some(("mra", _)) => { - let session = - crate::database::models::session_item::DBSession::get( - token, executor, redis, - ) - .await? - .ok_or_else(|| AuthenticationError::InvalidCredentials)?; - - if !allow_expired && session.expires < Utc::now() { - return Err(AuthenticationError::InvalidCredentials); - } - - let user = - user_item::DBUser::get_id(session.user_id, executor, redis) - .await?; - - let rate_limit_ignore = &ENV.RATE_LIMIT_IGNORE_KEY; - if req - .headers() - .get("x-ratelimit-key") - .and_then(|x| x.to_str().ok()) - .is_none_or(|x| x != rate_limit_ignore) - { - let metadata = get_session_metadata(req).await?; - session_queue.add_session(session.id, metadata).await; - } - - user.map(|x| (Scopes::all(), x)) - } - Some(("mro", _)) => { - use crate::database::models::oauth_token_item::DBOAuthAccessToken; - - let hash = DBOAuthAccessToken::hash_token(token); - let access_token = - crate::database::models::oauth_token_item::DBOAuthAccessToken::get(hash, executor) - .await? - .ok_or(AuthenticationError::InvalidCredentials)?; - - if !allow_expired && access_token.expires < Utc::now() { - return Err(AuthenticationError::InvalidCredentials); - } - - let user = user_item::DBUser::get_id( - access_token.user_id, - executor, - redis, - ) - .await?; - - session_queue.add_oauth_access_token(access_token.id).await; - - user.map(|u| (access_token.scopes - Scopes::staff(), u)) - } - Some(("github" | "gho" | "ghp", _)) => { + let possible_user = + if matches!(token.split_once('_'), Some(("github" | "gho" | "ghp", _))) + { let user = AuthProvider::GitHub.get_user(token).await?; let id = AuthProvider::GitHub.get_user_id(&user.id, executor).await?; @@ -249,9 +224,54 @@ where user.map(|x| { (Scopes::all() - Scopes::restricted() - Scopes::staff(), x) }) - } - _ => return Err(AuthenticationError::InvalidAuthMethod), - }; + } else { + let token = resolve_bearer_token(token, executor, redis).await?; + if !allow_expired && token.timestamps().1 < Utc::now() { + return Err(AuthenticationError::InvalidCredentials); + } + match token { + BearerToken::PersonalAccessToken(pat) => { + let user = + user_item::DBUser::get_id(pat.user_id, executor, redis) + .await?; + session_queue.add_pat(pat.id).await; + user.map(|user| (pat.scopes, user)) + } + BearerToken::Session(session) => { + let user = user_item::DBUser::get_id( + session.user_id, + executor, + redis, + ) + .await?; + + let rate_limit_ignore = &ENV.RATE_LIMIT_IGNORE_KEY; + if req + .headers() + .get("x-ratelimit-key") + .and_then(|x| x.to_str().ok()) + .is_none_or(|x| x != rate_limit_ignore) + { + let metadata = get_session_metadata(req).await?; + session_queue.add_session(session.id, metadata).await; + } + + user.map(|x| (Scopes::all(), x)) + } + BearerToken::OAuthAccessToken(access_token) => { + let user = user_item::DBUser::get_id( + access_token.user_id, + executor, + redis, + ) + .await?; + session_queue.add_oauth_access_token(access_token.id).await; + user.map(|user| { + (access_token.scopes - Scopes::staff(), user) + }) + } + } + }; if possible_user .as_ref() @@ -270,6 +290,51 @@ where })) } +/// Requires a token issued recently enough to perform a privileged action. +/// This supplements, rather than replaces, authentication and scope checks. +pub async fn require_privileged_token<'a, E>( + req: &HttpRequest, + executor: E, + redis: &RedisPool, +) -> Result<(), AuthenticationError> +where + E: crate::database::Executor<'a, Database = sqlx::Postgres>, +{ + require_privileged_bearer_token( + extract_authorization_header(req)?, + executor, + redis, + ) + .await +} + +/// Checks the creation time of a bearer token without requiring an HTTP header. +pub async fn require_privileged_bearer_token<'a, E>( + token: &str, + executor: E, + redis: &RedisPool, +) -> Result<(), AuthenticationError> +where + E: crate::database::Executor<'a, Database = sqlx::Postgres>, +{ + let (created, expires) = resolve_bearer_token(token, executor, redis) + .await? + .timestamps(); + let now = Utc::now(); + if expires <= now { + return Err(AuthenticationError::InvalidCredentials); + } + let age = (now - created) + .to_std() + .map_err(|_| AuthenticationError::PrivilegedTokenExpired)?; + if age + >= std::time::Duration::from_secs(ENV.PRIVILEGED_TOKEN_INVALID_IN_SEC) + { + return Err(AuthenticationError::PrivilegedTokenExpired); + } + Ok(()) +} + pub fn extract_authorization_header( req: &HttpRequest, ) -> Result<&str, AuthenticationError> { diff --git a/apps/labrinth/src/database/models/flow_item.rs b/apps/labrinth/src/database/models/flow_item.rs index 0257ec6d0a2..7706da4548e 100644 --- a/apps/labrinth/src/database/models/flow_item.rs +++ b/apps/labrinth/src/database/models/flow_item.rs @@ -13,7 +13,7 @@ use url::Url; use webauthn_rs::prelude::{DiscoverableAuthentication, PasskeyRegistration}; use xredis::RedisPool; -const FLOWS_NAMESPACE: &str = "flows:v4"; +const FLOWS_NAMESPACE: &str = "flows:v5"; #[serde_binhum] pub enum DBFlow { @@ -22,6 +22,7 @@ pub enum DBFlow { url: Url, provider: AuthProvider, existing_user_id: Option, + session_id: Option, }, OAuthPending { url: Url, diff --git a/apps/labrinth/src/database/models/session_item.rs b/apps/labrinth/src/database/models/session_item.rs index 1c8084ae68c..65eaaa68475 100644 --- a/apps/labrinth/src/database/models/session_item.rs +++ b/apps/labrinth/src/database/models/session_item.rs @@ -28,6 +28,8 @@ pub struct SessionBuilder { pub ip: String, pub user_agent: String, + pub created: Option>, + // When None, database default of 14 days will be used pub expires: Option>, // When None, database default of 60 days will be used @@ -48,12 +50,12 @@ impl SessionBuilder { INSERT INTO sessions ( id, session, user_id, os, platform, city, country, ip, user_agent, - expires, refresh_expires + expires, refresh_expires, created ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, - $10, $11 + $10, $11, COALESCE($12, NOW()) ) ", id as DBSessionId, @@ -69,6 +71,7 @@ impl SessionBuilder { .unwrap_or_else(|| Utc::now() + chrono::Duration::days(14)), self.session_expires .unwrap_or_else(|| Utc::now() + chrono::Duration::days(60)), + self.created, ) .execute(&mut *transaction) .await diff --git a/apps/labrinth/src/env.rs b/apps/labrinth/src/env.rs index e3daaedbc9b..d07f958580a 100644 --- a/apps/labrinth/src/env.rs +++ b/apps/labrinth/src/env.rs @@ -134,6 +134,7 @@ vars! { LABRINTH_EXTERNAL_NOTIFICATION_KEY: String = ""; LABRINTH_SUBSCRIPTIONS_KEY: String = ""; RATE_LIMIT_IGNORE_KEY: String = ""; + PRIVILEGED_TOKEN_INVALID_IN_SEC: u64 = 15u64 * 60; DATABASE_URL: String = "postgresql://labrinth:labrinth@localhost/labrinth"; MINECRAFT_META_DATABASE_URL: Url; diff --git a/apps/labrinth/src/routes/internal/flows.rs b/apps/labrinth/src/routes/internal/flows.rs index 060565cc7bb..5f9a920668a 100644 --- a/apps/labrinth/src/routes/internal/flows.rs +++ b/apps/labrinth/src/routes/internal/flows.rs @@ -1,5 +1,6 @@ use crate::auth::validate::{ get_full_user_from_headers, get_user_record_from_bearer_token, + require_privileged_bearer_token, require_privileged_token, }; use crate::auth::{AuthProvider, AuthenticationError, get_user_from_headers}; use crate::database::PgPool; @@ -1176,6 +1177,8 @@ pub async fn init( return Err(AuthenticationError::InvalidCredentials); } + require_privileged_bearer_token(auth_token, &**client, &redis).await?; + let (scopes, user) = get_user_record_from_bearer_token( &req, Some(auth_token), @@ -1213,7 +1216,7 @@ pub async fn init( return Err(AuthenticationError::Url); } - let user_id = if let Some(token) = info.token { + let user_id = if let Some(token) = &info.token { // Linking a new auth provider changes how the account can be accessed, // so only first-party session tokens may authorize this flow. OAuth and // PAT tokens can be delegated or stored outside an interactive login. @@ -1221,9 +1224,11 @@ pub async fn init( return Err(AuthenticationError::InvalidCredentials); } + require_privileged_bearer_token(token, &**client, &redis).await?; + let (scopes, user) = get_user_record_from_bearer_token( &req, - Some(&token), + Some(token), &**client, &redis, &session_queue, @@ -1241,11 +1246,26 @@ pub async fn init( None }; + let session_id = if let Some(token) = + if info.provider == AuthProvider::PayPal { + info.auth_token.as_ref() + } else { + info.token.as_ref() + } { + let session = DBSession::get(token, &**client, &redis) + .await? + .ok_or(AuthenticationError::InvalidCredentials)?; + Some(session.id) + } else { + None + }; + let state = DBFlow::OAuth { user_id, url, provider: info.provider, existing_user_id, + session_id, } .insert(Duration::minutes(30), &redis) .await?; @@ -1331,6 +1351,7 @@ pub async fn auth_callback( provider, url, existing_user_id, + session_id, } = flow else { return Err(AuthenticationError::Internal(eyre!( @@ -1343,6 +1364,28 @@ pub async fn auth_callback( redis: redis.clone(), }; + let linking_user_id = if provider == AuthProvider::PayPal { + existing_user_id + } else { + user_id + }; + if let Some(linking_user_id) = linking_user_id { + let session_id = + session_id.ok_or(AuthenticationError::InvalidCredentials)?; + let session = DBSession::get_id(session_id, &**client, &redis) + .await? + .ok_or(AuthenticationError::InvalidCredentials)?; + if session.user_id != linking_user_id { + return Err(AuthenticationError::InvalidCredentials); + } + require_privileged_bearer_token( + &session.session, + &**client, + &redis, + ) + .await?; + } + let token = provider .get_token(query) .await @@ -1847,6 +1890,10 @@ pub async fn delete_auth_provider( delete_provider: web::Json, session_queue: Data, ) -> Result { + require_privileged_token(&req, &**pool, &redis) + .await + .wrap_api_err("checking privileged token age")?; + let user = get_user_from_headers( &req, &**pool, @@ -2606,6 +2653,10 @@ pub async fn begin_2fa_flow( redis: Data, session_queue: Data, ) -> Result { + require_privileged_token(&req, &**pool, &redis) + .await + .wrap_api_err("checking privileged token age")?; + let user = get_user_from_headers( &req, &**pool, @@ -2660,6 +2711,10 @@ pub async fn finish_2fa_flow( login: web::Json, session_queue: Data, ) -> Result { + require_privileged_token(&req, &**pool, &redis) + .await + .wrap_api_err("checking privileged token age")?; + let flow = DBFlow::get(&login.flow, &redis) .await .wrap_internal_err("fetching 2FA initialization flow from Redis")? @@ -2814,6 +2869,10 @@ pub async fn remove_2fa( login: web::Json, session_queue: Data, ) -> Result { + require_privileged_token(&req, &**pool, &redis) + .await + .wrap_api_err("checking privileged token age")?; + let (scopes, user) = get_user_record_from_bearer_token( &req, None, @@ -3080,6 +3139,10 @@ pub async fn change_password( let user = if let Some(user) = user { user } else { + require_privileged_token(&req, &**pool, &redis) + .await + .wrap_api_err("checking privileged token age")?; + let (scopes, user) = get_user_record_from_bearer_token( &req, None, @@ -3273,6 +3336,12 @@ pub async fn set_email( .wrap_auth_err("authenticating API request")? .user; + if user.email.is_some() { + require_privileged_token(&req, &**pool, &redis) + .await + .wrap_api_err("checking privileged token age")?; + } + if !crate::database::models::DBUser::get_by_case_insensitive_email( &email_address.email, &**pool, @@ -3657,6 +3726,10 @@ pub async fn register_passkey_start( session_queue: Data, webauthn: Data, ) -> Result, ApiError> { + require_privileged_token(&req, &**pool, &redis) + .await + .wrap_api_err("checking privileged token age")?; + let user = get_user_from_headers( &req, &**pool, @@ -3760,6 +3833,10 @@ pub async fn register_passkey_finish( webauthn: Data, response: web::Json, ) -> Result<(web::Json, StatusCode), ApiError> { + require_privileged_token(&req, &**pool, &redis) + .await + .wrap_api_err("checking privileged token age")?; + let user = get_user_from_headers( &req, &**pool, @@ -4150,6 +4227,10 @@ pub async fn delete_passkey( session_queue: Data, info: web::Path<(String,)>, ) -> Result { + require_privileged_token(&req, &**pool, &redis) + .await + .wrap_api_err("checking privileged token age")?; + let user = get_user_from_headers( &req, &**pool, diff --git a/apps/labrinth/src/routes/internal/pats.rs b/apps/labrinth/src/routes/internal/pats.rs index c2876be93ea..d421c4403b7 100644 --- a/apps/labrinth/src/routes/internal/pats.rs +++ b/apps/labrinth/src/routes/internal/pats.rs @@ -1,8 +1,9 @@ use crate::database; use crate::database::models::generate_pat_id; +use crate::util::error::ApiContext as _; use crate::util::error::Context as _; -use crate::auth::get_user_from_headers; +use crate::auth::{get_user_from_headers, validate::require_privileged_token}; use crate::routes::ApiError; use actix_web::web::{self, Data}; @@ -29,7 +30,7 @@ pub fn config(cfg: &mut actix_web::web::ServiceConfig) { cfg.service(delete_pat); } -/// List personal access tokens. +/// List personal access tokens. #[utoipa::path( tag = "personal access tokens", get, @@ -87,7 +88,7 @@ pub struct NewPersonalAccessToken { pub expires: DateTime, } -/// Create a personal access token. +/// Create a personal access token. #[utoipa::path( tag = "personal access tokens", post, @@ -140,6 +141,10 @@ pub async fn create_pat( } let user = user.user; + require_privileged_token(&req, &**pool, &redis) + .await + .wrap_api_err("checking privileged token age")?; + let mut transaction = pool .begin() .await @@ -211,7 +216,7 @@ pub struct ModifyPersonalAccessToken { pub expires: Option>, } -/// Update a personal access token. +/// Update a personal access token. #[utoipa::path( tag = "personal access tokens", patch, @@ -259,6 +264,10 @@ pub async fn edit_pat( } let user = user.user; + require_privileged_token(&req, &**pool, &redis) + .await + .wrap_api_err("checking privileged token age")?; + let id = id.into_inner().0; let pat = database::models::pat_item::DBPersonalAccessToken::get( &id, &**pool, &redis, @@ -344,7 +353,7 @@ pub async fn edit_pat( Ok(HttpResponse::NoContent().finish()) } -/// Delete a personal access token. +/// Delete a personal access token. #[utoipa::path( tag = "personal access tokens", delete, @@ -376,6 +385,9 @@ pub async fn delete_pat( .await .wrap_auth_err("authenticating API request")? .user; + require_privileged_token(&req, &**pool, &redis) + .await + .wrap_api_err("checking privileged token age")?; let id = id.into_inner().0; let pat = database::models::pat_item::DBPersonalAccessToken::get( &id, &**pool, &redis, diff --git a/apps/labrinth/src/routes/internal/session.rs b/apps/labrinth/src/routes/internal/session.rs index 5e1f7e81c08..c80518ba18d 100644 --- a/apps/labrinth/src/routes/internal/session.rs +++ b/apps/labrinth/src/routes/internal/session.rs @@ -95,6 +95,25 @@ pub async fn issue_session( transaction: &mut PgTransaction<'_>, redis: &RedisPool, session_expires: Option>, +) -> Result { + issue_session_with_created( + req, + user_id, + transaction, + redis, + session_expires, + None, + ) + .await +} + +async fn issue_session_with_created( + req: HttpRequest, + user_id: DBUserId, + transaction: &mut PgTransaction<'_>, + redis: &RedisPool, + session_expires: Option>, + created: Option>, ) -> Result { if DBUserLock::exists(user_id, &mut *transaction).await? { return Err(AuthenticationError::AccountLocked); @@ -121,6 +140,7 @@ pub async fn issue_session( user_agent: metadata.user_agent, expires: None, session_expires, + created, } .insert(transaction) .await?; @@ -175,7 +195,7 @@ pub async fn issue_auth_sessions( }) } -/// List sessions. +/// List sessions. #[utoipa::path( context_path = "/session", tag = "sessions", @@ -223,7 +243,7 @@ pub async fn list( Ok(HttpResponse::Ok().json(sessions)) } -/// Delete a session. +/// Delete a session. #[utoipa::path( context_path = "/session", tag = "sessions", @@ -290,7 +310,7 @@ pub async fn delete( Ok(HttpResponse::NoContent().body("")) } -/// Refresh a session. +/// Refresh a session. #[utoipa::path( context_path = "/session", tag = "sessions", @@ -355,12 +375,13 @@ pub async fn refresh( DBSession::remove(session.id, &mut transaction) .await .wrap_internal_err("deleting session from database")?; - let new_session = issue_session( + let new_session = issue_session_with_created( req, session.user_id, &mut transaction, &redis, Some(session.refresh_expires), + Some(session.created), ) .await .wrap_auth_err("authenticating API request")?; diff --git a/apps/labrinth/src/routes/mod.rs b/apps/labrinth/src/routes/mod.rs index cdab98ca305..7f24717c197 100644 --- a/apps/labrinth/src/routes/mod.rs +++ b/apps/labrinth/src/routes/mod.rs @@ -645,11 +645,14 @@ impl ApiError { let validation = report .downcast_ref::(); - let standing = self.account_standing_error(); + let authentication = match self { + Self::Auth(report) => report.downcast_ref::(), + _ => None, + }; crate::models::error::ApiError { error: match self { - _ if let Some(error) = standing => error.error_name(), + _ if let Some(error) = authentication => error.error_name(), Self::Internal(..) => "internal_error", Self::Request(..) => "request_error", Self::Auth(..) => "auth_error", @@ -660,7 +663,7 @@ impl ApiError { Self::PreconditionFailed(..) => "precondition_failed", Self::RateLimit(..) => "ratelimit_error", }, - description: standing + description: authentication .map_or_else(|| report.to_string(), ToString::to_string), details: validation .map(|error| serde_json::json!({ "nags": error.0 })) @@ -676,10 +679,12 @@ impl actix_web::ResponseError for ApiError { match self { Self::Internal(..) => StatusCode::INTERNAL_SERVER_ERROR, Self::Request(..) => StatusCode::BAD_REQUEST, - Self::Auth(..) if self.account_standing_error().is_some() => { - StatusCode::FORBIDDEN + Self::Auth(report) => { + report.downcast_ref::().map_or( + StatusCode::UNAUTHORIZED, + actix_web::ResponseError::status_code, + ) } - Self::Auth(..) => StatusCode::UNAUTHORIZED, Self::NotFound(..) => StatusCode::NOT_FOUND, Self::Conflict(..) => StatusCode::CONFLICT, Self::FailedDependency(..) => StatusCode::FAILED_DEPENDENCY, @@ -712,6 +717,27 @@ mod tests { assert_eq!(error.as_api_error().error, "account_locked"); } + #[test] + fn api_error_preserves_reauthentication_error_through_context() { + use crate::util::error::ApiContext as _; + + let result: Result<(), AuthenticationError> = + Err(AuthenticationError::PrivilegedTokenExpired); + let error = result + .wrap_api_err("checking privileged token age") + .unwrap_err() + .wrap_err("performing sensitive action"); + + assert_eq!(error.status_code(), StatusCode::UNAUTHORIZED); + assert_eq!(error.error_response().status(), StatusCode::UNAUTHORIZED); + let response = error.as_api_error(); + assert_eq!(response.error, "privileged_token_expired"); + assert_eq!( + response.description, + AuthenticationError::PrivilegedTokenExpired.to_string() + ); + } + #[test] fn api_error_serializes_source_chain_as_details() { let error = ApiError::Request( diff --git a/apps/labrinth/src/routes/v3/oauth_clients.rs b/apps/labrinth/src/routes/v3/oauth_clients.rs index c5816eb8c31..ee5bdc7c705 100644 --- a/apps/labrinth/src/routes/v3/oauth_clients.rs +++ b/apps/labrinth/src/routes/v3/oauth_clients.rs @@ -203,6 +203,9 @@ pub async fn oauth_client_create( ) .await?; + crate::auth::validate::require_privileged_token(&req, &**pool, &redis) + .await?; + new_oauth_app.validate().map_err(|e| { CreateError::ValidationError(validation_errors_to_string(e, None)) })?; diff --git a/apps/labrinth/src/routes/v3/payouts.rs b/apps/labrinth/src/routes/v3/payouts.rs index 57ab1b93028..5980d02af3a 100644 --- a/apps/labrinth/src/routes/v3/payouts.rs +++ b/apps/labrinth/src/routes/v3/payouts.rs @@ -586,6 +586,14 @@ pub async fn create_payout( .await .wrap_internal_err("failed to fetch user balance")?; + crate::auth::validate::require_privileged_token( + &req, + &mut transaction, + &redis, + ) + .await + .wrap_api_err("checking privileged token age")?; + let balance = get_user_balance(user.id, &pool) .await .wrap_internal_err("failed to calculate user balance")?; diff --git a/apps/labrinth/src/routes/v3/projects/mod.rs b/apps/labrinth/src/routes/v3/projects/mod.rs index 763b8e2add6..73d092b6fbf 100644 --- a/apps/labrinth/src/routes/v3/projects/mod.rs +++ b/apps/labrinth/src/routes/v3/projects/mod.rs @@ -3538,6 +3538,16 @@ pub async fn project_delete_internal( let original_status = ProjectStatus::from_string(&locked_project.status); let original_slug = locked_project.slug; + if original_status.is_approved() { + crate::auth::validate::require_privileged_token( + &req, + &mut transaction, + &redis, + ) + .await + .wrap_api_err("checking privileged token age")?; + } + delphi::tech_review_queue::remove_projects( &[project.inner.id], delphi::tech_review_queue::TechReviewRemovalReason::FileDeleted, diff --git a/apps/labrinth/src/routes/v3/users.rs b/apps/labrinth/src/routes/v3/users.rs index cd0fe35b7b4..ef537cbcb6e 100644 --- a/apps/labrinth/src/routes/v3/users.rs +++ b/apps/labrinth/src/routes/v3/users.rs @@ -1026,6 +1026,14 @@ pub async fn user_edit( .wrap_internal_err("starting database transaction")?; if let Some(username) = &new_user.username { + crate::auth::validate::require_privileged_token( + &req, + &mut transaction, + &redis, + ) + .await + .wrap_api_err("checking privileged token age")?; + let existing_user_id_option = DBUser::get(username, &**pool, &redis) .await @@ -1415,6 +1423,14 @@ pub async fn user_delete( .await .wrap_internal_err("failed to begin transaction")?; + crate::auth::validate::require_privileged_token( + &req, + &mut transaction, + &redis, + ) + .await + .wrap_api_err("checking privileged token age")?; + let result = DBUser::remove(id, &mut transaction, &redis) .await .wrap_internal_err("failed to remove user")?; diff --git a/apps/labrinth/src/util/error.rs b/apps/labrinth/src/util/error.rs index 8b52a20c7b1..017aded5c11 100644 --- a/apps/labrinth/src/util/error.rs +++ b/apps/labrinth/src/util/error.rs @@ -30,6 +30,17 @@ impl ApiContext for Result { } } +impl ApiContext for Result { + fn wrap_api_err_with(self, f: impl FnOnce() -> D) -> Result + where + D: Send + Sync + Debug + Display + 'static, + { + self.map_err(|error| { + ApiError::Auth(eyre::Report::new(error).wrap_err(f())) + }) + } +} + /// Allows wrapping [`Result`]s and [`Option`]s into [`Result`]s. #[allow( clippy::missing_errors_doc, @@ -470,6 +481,29 @@ mod tests { )); } + #[test] + fn test_api_context_preserves_authentication_error_kind() { + use crate::auth::AuthenticationError; + + for source in [ + AuthenticationError::PrivilegedTokenExpired, + AuthenticationError::InvalidCredentials, + AuthenticationError::AccountLocked, + AuthenticationError::DuplicateEmail, + ] { + let status = source.status_code(); + let name = source.error_name(); + let description = source.to_string(); + let result: Result<(), AuthenticationError> = Err(source); + let error = + result.wrap_api_err("checking authentication").unwrap_err(); + + assert_eq!(error.status_code(), status); + assert_eq!(error.as_api_error().error, name); + assert_eq!(error.as_api_error().description, description); + } + } + #[test] fn test_api_context_preserves_status_variant() { let result: Result<(), ApiError> =