use rho_providers::credentials::CredentialStore;
use serde::{Deserialize, Serialize};
use crate::app::{
http_guard::{find_by_secret, new_secret, sha256_hex, validate_name},
mcp_server::token_store::{self, StoredSet},
};
pub(crate) const ACCOUNT: &str = "daemon-http-tokens";
const LOCK_FILE: &str = ".rho-daemon-tokens.lock";
const SECRET_PREFIX: &str = "rho_daemon_";
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct DaemonTokenSet {
pub(crate) tokens: Vec<DaemonTokenRecord>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct DaemonTokenRecord {
pub(crate) name: String,
sha256: String,
}
impl StoredSet for DaemonTokenSet {
const ACCOUNT: &'static str = ACCOUNT;
const WHAT: &'static str = "daemon HTTP tokens";
const LOCK_FILE: &'static str = LOCK_FILE;
const GUARDED: &'static str = "daemon HTTP tokens";
}
impl DaemonTokenSet {
pub(crate) fn load(store: &dyn CredentialStore) -> anyhow::Result<Self> {
token_store::load(store)
}
pub(crate) fn rotate(&mut self, name: &str) -> anyhow::Result<String> {
validate_name("token", name)?;
let secret = new_secret(SECRET_PREFIX);
let sha256 = sha256_hex(&secret);
match self.tokens.iter_mut().find(|token| token.name == name) {
Some(token) => token.sha256 = sha256,
None => self.tokens.push(DaemonTokenRecord {
name: name.to_owned(),
sha256,
}),
}
Ok(secret)
}
pub(crate) fn revoke(&mut self, name: &str) -> bool {
let before = self.tokens.len();
self.tokens.retain(|token| token.name != name);
self.tokens.len() != before
}
pub(crate) fn authenticate(&self, presented: &str) -> Option<&DaemonTokenRecord> {
find_by_secret(&self.tokens, presented, |token| &token.sha256)
}
}
#[cfg(test)]
#[path = "tokens_tests.rs"]
mod tests;