added a way to rotate a token

This commit is contained in:
ari committed 2026-10-20 23:26:10 -04:00
1 parent 5d78004720
commit 020fa4871f
2 files changed
+41 -1

No files matched your search

+9 -1
View File
@@ -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]
+32
View File
@@ -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<Revoked> {
})
}
pub async fn rotate(pool: &SqlitePool, name: &str) -> Result<String> {
let exists: Option<i64> = 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<bool> {
@@ -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(())