Skip to main content

subspace_core/
mcp_token.rs

1//! MCP bearer tokens live outside config.json and never appear in diagnostics.
2use std::path::{Path, PathBuf};
3use std::{fs, io};
4
5use crate::{Secret, private_file, state};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum TokenStatus {
9    Missing,
10    Private,
11    NotPrivate,
12}
13
14/// Where an MCP process reads a token from besides a file.
15pub const TOKEN_VARIABLE: &str = "SUBSPACE_MCP_TOKEN";
16
17pub fn path(config_dir: &Path) -> PathBuf {
18    config_dir.join("mcp-token")
19}
20
21/// Creates a new 256-bit token. The value is not returned to the UI.
22pub fn create_or_replace(path: &Path) -> io::Result<()> {
23    state::write_atomic(path, generate().expose())
24}
25
26/// 256 bits.
27const TOKEN_BYTES: usize = 32;
28
29/// A new 256-bit token, as hex, kept only in memory.
30pub fn generate() -> Secret {
31    let bytes: [u8; TOKEN_BYTES] = rand::random();
32    Secret::new(hex::encode(bytes))
33}
34
35pub fn status(path: &Path) -> io::Result<TokenStatus> {
36    match private_file::is_owner_only(path) {
37        Ok(true) => Ok(TokenStatus::Private),
38        Ok(false) => Ok(TokenStatus::NotPrivate),
39        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(TokenStatus::Missing),
40        Err(error) => Err(error),
41    }
42}
43
44/// Refuses non-private, missing and empty token files.
45pub fn read(path: &Path) -> io::Result<Secret> {
46    if status(path)? != TokenStatus::Private {
47        return Err(io::Error::new(
48            io::ErrorKind::PermissionDenied,
49            "MCP token file is missing or not private",
50        ));
51    }
52    let token = fs::read_to_string(path)?;
53    if token.trim().is_empty() {
54        return Err(io::Error::new(
55            io::ErrorKind::InvalidData,
56            "MCP token file is empty",
57        ));
58    }
59    Ok(Secret::new(token.trim()))
60}
61
62#[cfg(test)]
63mod tests {
64    use super::{TokenStatus, create_or_replace, path, read, status};
65
66    #[test]
67    fn token_is_private_random_hex_and_replaced_atomically() {
68        let dir = tempfile::tempdir().unwrap();
69        let file = path(dir.path());
70        assert_eq!(status(&file).unwrap(), TokenStatus::Missing);
71        create_or_replace(&file).unwrap();
72        assert_eq!(status(&file).unwrap(), TokenStatus::Private);
73        let first = read(&file).unwrap();
74        assert_eq!(first.expose().len(), 64);
75        assert!(first.expose().bytes().all(|byte| byte.is_ascii_hexdigit()));
76        create_or_replace(&file).unwrap();
77        assert_ne!(first, read(&file).unwrap());
78        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
79    }
80
81    #[test]
82    #[cfg(unix)]
83    fn readable_by_others_and_symlinks_are_not_private() {
84        use std::os::unix::fs::{PermissionsExt as _, symlink};
85        let dir = tempfile::tempdir().unwrap();
86        let file = path(dir.path());
87        create_or_replace(&file).unwrap();
88        assert_eq!(
89            std::fs::metadata(&file).unwrap().permissions().mode() & 0o777,
90            0o600
91        );
92        let link = dir.path().join("link");
93        symlink(&file, &link).unwrap();
94        assert_eq!(status(&link).unwrap(), TokenStatus::NotPrivate);
95        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
96        assert_eq!(status(&file).unwrap(), TokenStatus::NotPrivate);
97        assert!(read(&file).is_err());
98    }
99}