//! Authorization codes and access-token persistence. use rusqlite::{Connection, OptionalExtension, params}; use crate::domain::oauth::AuthorizationRequest; use crate::{ domain::{account::Account, oauth::AuthenticatedToken}, error::{Error, Result}, }; use super::{Database, now, sql_row}; impl Database { /// Store a hashed, short-lived OAuth authorization code. /// /// # Errors /// /// Returns an error when the code cannot be persisted. pub fn store_authorization_code( &self, code_hash: &str, did: &str, request: &AuthorizationRequest>, expires_at: i64, ) -> Result<()> { let client_id = request.client_id.as_ref(); let redirect_uri = request.redirect_uri.as_ref(); self.transaction(|transaction| { purge_expired_oauth(transaction, now())?; transaction.execute( "INSERT INTO oauth_codes (code_hash, did, client_id, redirect_uri, code_challenge, scope, expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", params![ code_hash, did, client_id, redirect_uri, request.code_challenge, request.scope, expires_at, ], )?; Ok(()) }) } /// Atomically consume an authorization code and issue its access token. /// /// # Errors /// /// Returns `Authorization` for missing, expired, used, or mismatched codes, /// and a database error when the transaction fails. pub(crate) fn redeem_authorization_code( &self, code_hash: &str, client_id: &str, redirect_uri: &str, presented_challenge: &str, token_hash: &str, token_expires_at: i64, ) -> Result<(String, String)> { self.transaction(|transaction| { let timestamp = now(); purge_expired_oauth(transaction, timestamp)?; let (did, stored_client_id, stored_redirect_uri, code_challenge, scope) = load_authorization_code(transaction, code_hash, timestamp)?; if stored_client_id != client_id || stored_redirect_uri != redirect_uri || code_challenge != presented_challenge { return Err(Error::Authorization( "authorization code is not valid for this token request".to_owned(), )); } transaction.execute( "INSERT INTO access_tokens (token_hash, did, client_id, scope, expires_at, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", params![ token_hash, did, stored_client_id, scope, token_expires_at, timestamp ], )?; transaction.execute("DELETE FROM oauth_codes WHERE code_hash = ?1", [code_hash])?; Ok((did, scope)) }) } /// Resolve a non-expired access token with its granted client and scopes. pub(crate) fn access_token(&self, token_hash: &str) -> Result { load_access_token(&*self.connection()?, token_hash, now()) } } fn load_authorization_code( connection: &Connection, code_hash: &str, timestamp: i64, ) -> Result<(String, String, String, String, String)> { connection .query_row( "SELECT did, client_id, redirect_uri, code_challenge, scope FROM oauth_codes WHERE code_hash = ?1 AND expires_at > ?2 AND used_at IS NULL", params![code_hash, timestamp], |row| row.try_into(), ) .optional()? .ok_or_else(|| { Error::Authorization( "authorization code is invalid, expired, or already used".to_owned(), ) }) } fn load_access_token( connection: &Connection, token_hash: &str, timestamp: i64, ) -> Result { connection .query_row( "SELECT accounts.did, accounts.handle, access_tokens.client_id, access_tokens.scope FROM access_tokens JOIN accounts ON accounts.did = access_tokens.did WHERE access_tokens.token_hash = ?1 AND access_tokens.expires_at > ?2", params![token_hash, timestamp], |row| { Ok(AuthenticatedToken { account: sql_row!(row => Account { did: 0, handle: 1 }), client_id: row.get(2)?, scope: row.get(3)?, }) }, ) .optional()? .ok_or(Error::AuthenticationRequired) } fn purge_expired_oauth(connection: &Connection, timestamp: i64) -> Result<()> { connection.execute( "DELETE FROM oauth_codes WHERE expires_at <= ?1", [timestamp], )?; connection.execute( "DELETE FROM access_tokens WHERE expires_at <= ?1", [timestamp], )?; Ok(()) } #[cfg(test)] mod tests;