Skip to content
1        10        20        30        40        50        60        70        80        901use anyhow::Result;2use rusqlite::{Connection, OptionalExtension, params};3use serde::{Deserialize, Serialize};4use uuid::Uuid;56use crate::auth::{Principal, Scope, generate_token, hash_token, token_hint};7use crate::db::now;89#[derive(Debug, Clone, Serialize, Deserialize)]10pub struct TokenInfo {11    pub id: String,12    pub name: String,13    pub hint: String,14    pub scopes: Vec<Scope>,15    pub created_at: String,16}1718pub struct Issued {19    pub info: TokenInfo,20    /// The only time the raw secret exists outside the caller; only its hash is stored.21    pub secret: String,22}2324pub fn create(connection: &Connection, name: &str, scopes: &[Scope]) -> Result<Issued> {25    let id = Uuid::new_v4().to_string();26    let secret = generate_token();27    let hint = token_hint(&secret);28    let created_at = now();29    connection.execute(30        "INSERT INTO tokens (id, name, token_hash, token_hint, scopes, created_at)31         VALUES (?1, ?2, ?3, ?4, ?5, ?6)",32        params![33            id,34            name,35            hash_token(&secret),36            hint,37            Scope::join(scopes),38            created_at39        ],40    )?;41    Ok(Issued {42        info: TokenInfo {43            id,44            name: name.to_string(),45            hint,46            scopes: scopes.to_vec(),47            created_at,48        },49        secret,50    })51}5253pub fn find_by_hash(connection: &Connection, hash: &str) -> Result<Option<Principal>> {54    let row = connection55        .query_row(56            "SELECT id, name, scopes FROM tokens WHERE token_hash = ?1",57            [hash],58            |row| {59                Ok((60                    row.get::<_, String>(0)?,61                    row.get::<_, String>(1)?,62                    row.get::<_, String>(2)?,63                ))64            },65        )66        .optional()?;67    Ok(row.map(|(token_id, name, scopes)| Principal {68        token_id,69        name,70        scopes: Scope::parse_list(&scopes),71    }))72}7374pub fn list(connection: &Connection) -> Result<Vec<TokenInfo>> {75    let mut statement = connection.prepare(76        "SELECT id, name, token_hint, scopes, created_at FROM tokens ORDER BY created_at",77    )?;78    let tokens = statement79        .query_map([], |row| {80            Ok(TokenInfo {81                id: row.get(0)?,82                name: row.get(1)?,83                hint: row.get(2)?,84                scopes: Scope::parse_list(&row.get::<_, String>(3)?),85                created_at: row.get(4)?,86            })87        })?88        .collect::<rusqlite::Result<Vec<TokenInfo>>>()?;89    Ok(tokens)90}9192/// Revokes a token by deleting it. Returns whether a token was removed.93pub fn delete(connection: &Connection, id: &str) -> Result<bool> {94    Ok(connection.execute("DELETE FROM tokens WHERE id = ?1", [id])? > 0)95}9697#[cfg(test)]98mod tests {99    use super::*;100    use crate::auth::TOKEN_PREFIX;101    use crate::db::open_in_memory;102103    #[test]104    fn issued_token_resolves_until_deleted() {105        let connection = open_in_memory().unwrap();106        let issued = create(&connection, "agent", &[Scope::Read]).unwrap();107        assert!(issued.secret.starts_with(TOKEN_PREFIX));108        assert_eq!(issued.info.hint, &issued.secret[issued.secret.len() - 4..]);109110        let principal = find_by_hash(&connection, &hash_token(&issued.secret))111            .unwrap()112            .unwrap();113        assert_eq!(principal.name, "agent");114        assert_eq!(principal.scopes, vec![Scope::Read]);115116        assert!(delete(&connection, &issued.info.id).unwrap());117        assert!(118            find_by_hash(&connection, &hash_token(&issued.secret))119                .unwrap()120                .is_none()121        );122        assert!(!delete(&connection, &issued.info.id).unwrap());123    }124125    #[test]126    fn listing_never_includes_the_secret() {127        let connection = open_in_memory().unwrap();128        let issued = create(&connection, "cli", &[Scope::Read, Scope::Write]).unwrap();129        let listed = list(&connection).unwrap();130        assert_eq!(listed.len(), 1);131        assert_eq!(listed[0].id, issued.info.id);132        assert_eq!(listed[0].scopes, vec![Scope::Read, Scope::Write]);133        assert!(134            !serde_json::to_string(&listed)135                .unwrap()136                .contains(&issued.secret)137        );138    }139}