From 020fa4871fac5517490fd51e914d539cffbf8afd Mon Sep 17 00:00:00 2001 From: Ari Sosnovsky Date: Tue, 20 Oct 2026 23:26:10 -0400 Subject: [PATCH] added a way to rotate a token --- src/auth/mod_tests.rs | 10 +++++++++- src/auth/tokens.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/auth/mod_tests.rs b/src/auth/mod_tests.rs index c350255..2abfd0b 100644 --- a/src/auth/mod_tests.rs +++ b/src/auth/mod_tests.rs @@ -42,7 +42,7 @@ async fn status(app: &Router, path: &str, auth: Option<&str>) -> (StatusCode, bo } #[tokio::test] -async fn create_accept_revoke_reject() { +async fn create_accept_revoke_reject_rotate() { let pool = pool().await; let mut state = fake_state(Config::default()); state.db = Some(pool.clone()); @@ -76,6 +76,14 @@ async fn create_accept_revoke_reject() { status(&app, "/api/v1/x", Some(&bearer)).await, (StatusCode::UNAUTHORIZED, true) ); + + let new_token = tokens::rotate(&pool, "ci").await.unwrap(); + assert!(new_token.starts_with("slinuxm_")); + let bearer = format!("Bearer {new_token}"); + assert_eq!( + status(&app, "/api/v1/x", Some(&bearer)).await.0, + StatusCode::OK + ); } #[tokio::test] diff --git a/src/auth/tokens.rs b/src/auth/tokens.rs index c670765..3b998bc 100644 --- a/src/auth/tokens.rs +++ b/src/auth/tokens.rs @@ -28,6 +28,8 @@ pub enum TokenCmd { List, /// Revoke a token by name. Revoke { name: String }, + /// Rotate a token by name and restore it if revoked. + Rotate { name: String }, } #[derive(Debug, Clone, sqlx::FromRow)] @@ -125,6 +127,32 @@ pub async fn revoke(pool: &SqlitePool, name: &str) -> Result { }) } +pub async fn rotate(pool: &SqlitePool, name: &str) -> Result { + let exists: Option = sqlx::query_scalar("SELECT id FROM tokens WHERE name = ?") + .bind(name) + .fetch_optional(pool) + .await + .context("looking up token")?; + match exists { + Some(token_id) => { + let token = mint_token()?; + let r = sqlx::query("UPDATE tokens SET revoked_at = NULL, token_hash = ? WHERE id = ?") + .bind(hash_token(&token)) + .bind(token_id) + .execute(pool) + .await + .context("rotating token")?; + if r.rows_affected() > 0 { + return Ok(token); + } + bail!("Token was not found"); + } + None => { + bail!("Token was not found"); + } + } +} + /// Check a presented token. The DB matches on the hash (the secret itself is /// never compared), and `last_used_at` is touched at most once a minute. pub async fn verify(pool: &SqlitePool, token: &str) -> Result { @@ -183,6 +211,10 @@ pub async fn run(cmd: TokenCmd, config: &Config) -> Result<()> { Revoked::Already => println!("Token {name:?} was already revoked."), Revoked::NotFound => bail!("no token named {name:?}"), }, + TokenCmd::Rotate { name } => { + let token = rotate(&pool, &name).await?; + println!("{token}"); + } } pool.close().await; Ok(())