Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion apps/labrinth/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down
15 changes: 10 additions & 5 deletions apps/labrinth/src/auth/oauth/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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()
{
Expand Down Expand Up @@ -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"
}
Expand Down
8 changes: 8 additions & 0 deletions apps/labrinth/src/auth/oauth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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?;

Expand Down Expand Up @@ -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 { .. }),
Expand Down
221 changes: 143 additions & 78 deletions apps/labrinth/src/auth/validate.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -144,6 +147,49 @@ where
})
}

enum BearerToken {
Session(DBSession),
PersonalAccessToken(DBPersonalAccessToken),
OAuthAccessToken(DBOAuthAccessToken),
}

impl BearerToken {
fn timestamps(&self) -> (chrono::DateTime<Utc>, chrono::DateTime<Utc>) {
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<BearerToken, AuthenticationError>
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>,
Expand All @@ -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?;
Expand All @@ -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()
Expand All @@ -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> {
Expand Down
3 changes: 2 additions & 1 deletion apps/labrinth/src/database/models/flow_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -22,6 +22,7 @@ pub enum DBFlow {
url: Url,
provider: AuthProvider,
existing_user_id: Option<DBUserId>,
session_id: Option<DBSessionId>,
},
OAuthPending {
url: Url,
Expand Down
Loading
Loading