Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs
185 lines
5.7 KiB
Rust
185 lines
5.7 KiB
Rust
//! Token CRUD and the `slinuxm token` CLI (WS-D owns this file).
|
|
//!
|
|
//! Tokens have the prefix `slinuxm_` and 32 random bytes. Only the sha256 hex
|
|
//! digest is stored; the plaintext is printed once on create.
|
|
|
|
use anyhow::{bail, Context, Result};
|
|
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
|
use base64::Engine;
|
|
use clap::Subcommand;
|
|
use rand::rngs::SysRng;
|
|
use rand::TryRng;
|
|
use sha2::{Digest, Sha256};
|
|
use sqlx::SqlitePool;
|
|
|
|
use crate::config::Config;
|
|
|
|
pub const TOKEN_PREFIX: &str = "slinuxm_";
|
|
const TS_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";
|
|
|
|
#[derive(Debug, Clone, Subcommand)]
|
|
pub enum TokenCmd {
|
|
/// Create a token and print it once.
|
|
Create {
|
|
/// Unique token name.
|
|
name: String,
|
|
},
|
|
/// List tokens (never prints secrets).
|
|
List,
|
|
/// Revoke a token by name.
|
|
Revoke { name: String },
|
|
}
|
|
|
|
/// A token row without its hash.
|
|
#[derive(Debug, Clone, sqlx::FromRow)]
|
|
pub struct TokenInfo {
|
|
pub name: String,
|
|
pub created_at: String,
|
|
pub revoked_at: Option<String>,
|
|
pub last_used_at: Option<String>,
|
|
}
|
|
|
|
/// Hex sha256 of a token string.
|
|
pub fn hash_token(token: &str) -> String {
|
|
Sha256::digest(token.as_bytes())
|
|
.iter()
|
|
.map(|b| format!("{b:02x}"))
|
|
.collect()
|
|
}
|
|
|
|
/// UTC timestamp in a fixed-width format that sorts lexicographically.
|
|
fn now_string() -> String {
|
|
jiff::Timestamp::now().strftime(TS_FORMAT).to_string()
|
|
}
|
|
|
|
/// Create a token and return the plaintext (shown once, never stored).
|
|
pub async fn create(pool: &SqlitePool, name: &str) -> Result<String> {
|
|
let name = name.trim();
|
|
if name.is_empty() {
|
|
bail!("token name must not be empty");
|
|
}
|
|
if name.chars().any(char::is_control) {
|
|
bail!("token name must not contain control characters");
|
|
}
|
|
let mut bytes = [0u8; 32];
|
|
SysRng
|
|
.try_fill_bytes(&mut bytes)
|
|
.map_err(|e| anyhow::anyhow!("OS RNG failure: {e}"))?;
|
|
let token = format!("{TOKEN_PREFIX}{}", URL_SAFE_NO_PAD.encode(bytes));
|
|
let res = sqlx::query("INSERT INTO tokens (name, token_hash, created_at) VALUES (?, ?, ?)")
|
|
.bind(name)
|
|
.bind(hash_token(&token))
|
|
.bind(now_string())
|
|
.execute(pool)
|
|
.await;
|
|
match res {
|
|
Ok(_) => Ok(token),
|
|
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => {
|
|
bail!("a token named {name:?} already exists")
|
|
}
|
|
Err(e) => Err(e).context("inserting token"),
|
|
}
|
|
}
|
|
|
|
/// List tokens by creation order. Hashes are never selected.
|
|
pub async fn list(pool: &SqlitePool) -> Result<Vec<TokenInfo>> {
|
|
sqlx::query_as::<_, TokenInfo>(
|
|
"SELECT name, created_at, revoked_at, last_used_at FROM tokens ORDER BY id",
|
|
)
|
|
.fetch_all(pool)
|
|
.await
|
|
.context("listing tokens")
|
|
}
|
|
|
|
/// Outcome of [`revoke`].
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Revoked {
|
|
Now,
|
|
Already,
|
|
NotFound,
|
|
}
|
|
|
|
pub async fn revoke(pool: &SqlitePool, name: &str) -> Result<Revoked> {
|
|
let r = sqlx::query("UPDATE tokens SET revoked_at = ? WHERE name = ? AND revoked_at IS NULL")
|
|
.bind(now_string())
|
|
.bind(name)
|
|
.execute(pool)
|
|
.await
|
|
.context("revoking token")?;
|
|
if r.rows_affected() > 0 {
|
|
return Ok(Revoked::Now);
|
|
}
|
|
let exists: Option<i64> = sqlx::query_scalar("SELECT id FROM tokens WHERE name = ?")
|
|
.bind(name)
|
|
.fetch_optional(pool)
|
|
.await
|
|
.context("looking up token")?;
|
|
Ok(if exists.is_some() {
|
|
Revoked::Already
|
|
} else {
|
|
Revoked::NotFound
|
|
})
|
|
}
|
|
|
|
/// 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> {
|
|
if !token.starts_with(TOKEN_PREFIX) {
|
|
return Ok(false);
|
|
}
|
|
let id: Option<i64> =
|
|
sqlx::query_scalar("SELECT id FROM tokens WHERE token_hash = ? AND revoked_at IS NULL")
|
|
.bind(hash_token(token))
|
|
.fetch_optional(pool)
|
|
.await
|
|
.context("token lookup")?;
|
|
let Some(id) = id else { return Ok(false) };
|
|
let cutoff = (jiff::Timestamp::now() - std::time::Duration::from_secs(60))
|
|
.strftime(TS_FORMAT)
|
|
.to_string();
|
|
// Best effort: a failed touch must not reject a valid token.
|
|
let _ = sqlx::query(
|
|
"UPDATE tokens SET last_used_at = ? WHERE id = ? AND (last_used_at IS NULL OR last_used_at < ?)",
|
|
)
|
|
.bind(now_string())
|
|
.bind(id)
|
|
.bind(cutoff)
|
|
.execute(pool)
|
|
.await;
|
|
Ok(true)
|
|
}
|
|
|
|
/// Execute a token subcommand against the DB at `config.auth.db_path`.
|
|
pub async fn run(cmd: TokenCmd, config: &Config) -> Result<()> {
|
|
let pool = crate::db::open(config).await?;
|
|
match cmd {
|
|
TokenCmd::Create { name } => {
|
|
let token = create(&pool, &name).await?;
|
|
println!("{token}");
|
|
eprintln!("Token {name:?} created. Store it now: it cannot be shown again.");
|
|
}
|
|
TokenCmd::List => {
|
|
println!(
|
|
"{:<24} {:<22} {:<22} LAST USED",
|
|
"NAME", "CREATED", "REVOKED"
|
|
);
|
|
for t in list(&pool).await? {
|
|
println!(
|
|
"{:<24} {:<22} {:<22} {}",
|
|
t.name,
|
|
t.created_at,
|
|
t.revoked_at.as_deref().unwrap_or("-"),
|
|
t.last_used_at.as_deref().unwrap_or("-")
|
|
);
|
|
}
|
|
}
|
|
TokenCmd::Revoke { name } => match revoke(&pool, &name).await? {
|
|
Revoked::Now => println!("Token {name:?} revoked."),
|
|
Revoked::Already => println!("Token {name:?} was already revoked."),
|
|
Revoked::NotFound => bail!("no token named {name:?}"),
|
|
},
|
|
}
|
|
pool.close().await;
|
|
Ok(())
|
|
}
|