use std::path::{Path, PathBuf};
use anyhow::Context;
use rho_providers::credentials::CredentialStore;
use serde::{Deserialize, Serialize};
use super::token_store::{self, StoredSet};
use crate::{
app::{
http_guard::{find_by_secret, new_secret, sha256_hex, validate_name},
session_control::{Grant, Holder},
},
caller_context::{Access, Scope, Workspaces},
};
pub(crate) const ACCOUNT: &str = "mcp-serve-tokens";
const SECRET_PREFIX: &str = "rho_mcp_";
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct TokenSet {
pub(crate) tokens: Vec<TokenRecord>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct TokenRecord {
pub(crate) name: String,
pub(crate) access: Access,
pub(crate) workspaces: Vec<PathBuf>,
sha256: String,
}
impl TokenRecord {
pub(crate) fn grant(&self) -> Grant {
Grant {
holder: Holder::Token(self.name.clone()),
scope: Scope {
access: self.access,
workspaces: Workspaces::Only(self.workspaces.clone()),
},
}
}
}
pub(crate) struct Rotation {
pub(crate) access: Option<Access>,
pub(crate) workspaces: Vec<PathBuf>,
}
impl StoredSet for TokenSet {
const ACCOUNT: &'static str = ACCOUNT;
const WHAT: &'static str = "MCP server tokens";
}
impl TokenSet {
pub(crate) fn load(store: &dyn CredentialStore) -> anyhow::Result<Self> {
token_store::load(store)
}
#[cfg(test)]
pub(crate) fn save(&self, store: &dyn CredentialStore) -> anyhow::Result<()> {
token_store::save(self, store)
}
pub(crate) fn rotate(&mut self, name: &str, rotation: Rotation) -> anyhow::Result<String> {
validate_name("token", name)?;
let workspaces = rotation
.workspaces
.iter()
.map(|path| canonical_dir(path))
.collect::<anyhow::Result<Vec<_>>>()?;
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;
if let Some(access) = rotation.access {
token.access = access;
}
if !workspaces.is_empty() {
token.workspaces = workspaces;
}
}
None => {
if workspaces.is_empty() {
anyhow::bail!(
"a new token needs at least one --workspace: the directories whose sessions it may reach"
);
}
self.tokens.push(TokenRecord {
name: name.to_owned(),
access: rotation.access.unwrap_or(Access::Read),
workspaces,
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<&TokenRecord> {
find_by_secret(&self.tokens, presented, |token| &token.sha256)
}
}
fn canonical_dir(path: &Path) -> anyhow::Result<PathBuf> {
let resolved = path
.canonicalize()
.with_context(|| format!("workspace {}", path.display()))?;
if !resolved.is_dir() {
anyhow::bail!("workspace {} is not a directory", path.display());
}
Ok(resolved)
}
#[cfg(test)]
#[path = "tokens_tests.rs"]
mod tests;