Skip to main content

datumesh_http/
apikeys.rs

1//! API keys: `Authorization: Bearer dm_<random>`.
2//!
3//! The keys file (mode 0600) holds one line per key: the SHA-256 of the whole key text
4//! (`dm_...`) as 64 lowercase hex digits, the principal id, and optionally the key's own
5//! limit in requests per minute; `#` starts a comment. The plaintext of a key is never stored
6//! by the mesh: [`create_key`] writes it to a file of its own (mode 0600) and nowhere else.
7
8use std::collections::HashMap;
9use std::io::Write;
10use std::path::Path;
11
12use datumesh_core::lexical;
13
14use crate::config::ConfigError;
15
16/// A principal: the owner of an API key.
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct Principal {
19    /// The principal id (letters, digits, `-`, `_`, `.`, `@`; at most 64).
20    pub id: String,
21    /// The key's limit in requests per minute, when it has its own.
22    pub per_minute: Option<u32>,
23}
24
25/// The API keys a mesh accepts, by hash.
26#[derive(Clone, Debug, Default, PartialEq, Eq)]
27pub struct ApiKeys {
28    by_hash: HashMap<String, Principal>,
29}
30
31/// The prefix of every key.
32pub const KEY_PREFIX: &str = "dm_";
33
34fn valid_principal(id: &str) -> bool {
35    !id.is_empty()
36        && id.len() <= 64
37        && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'@'))
38}
39
40impl ApiKeys {
41    /// Parses a keys file.
42    pub fn parse(bytes: &[u8]) -> Result<ApiKeys, ConfigError> {
43        let text = std::str::from_utf8(bytes).map_err(|_| ConfigError::new("API keys", "not UTF-8"))?;
44        let mut by_hash = HashMap::new();
45        for (i, line) in text.lines().enumerate() {
46            let line = line.split('#').next().unwrap_or("").trim();
47            if line.is_empty() {
48                continue;
49            }
50            let bad = || ConfigError::new("API keys", format!("line {}: <sha256> <principal> [per minute]", i + 1));
51            let mut parts = line.split_whitespace();
52            let hash = parts.next().ok_or_else(bad)?;
53            let id = parts.next().ok_or_else(bad)?;
54            let per_minute = match parts.next() {
55                Some(n) => Some(n.parse::<u32>().map_err(|_| bad())?),
56                None => None,
57            };
58            if parts.next().is_some() || lexical::check_hex(hash, 64, "$").is_err() || !valid_principal(id) {
59                return Err(bad());
60            }
61            by_hash.insert(hash.to_string(), Principal { id: id.to_string(), per_minute });
62        }
63        Ok(ApiKeys { by_hash })
64    }
65
66    /// The principal of a presented key, if it is one of these.
67    pub fn principal(&self, key: &str) -> Option<&Principal> {
68        if !key.starts_with(KEY_PREFIX) || key.len() > 256 {
69            return None;
70        }
71        self.by_hash.get(&datumesh_core::sha256_hex(key.as_bytes()))
72    }
73
74    /// Adds a key by its hash (for tests and embedders).
75    pub fn insert_hash(&mut self, sha256: &str, principal: Principal) {
76        self.by_hash.insert(sha256.to_string(), principal);
77    }
78
79    /// The number of keys.
80    pub fn len(&self) -> usize {
81        self.by_hash.len()
82    }
83
84    /// Whether there are none.
85    pub fn is_empty(&self) -> bool {
86        self.by_hash.is_empty()
87    }
88}
89
90/// A new key: `dm_` and 64 hex digits of 256 bits from the operating system's CSPRNG.
91pub fn new_key() -> Result<String, ConfigError> {
92    let mut b = [0u8; 32];
93    getrandom::fill(&mut b).map_err(|e| ConfigError::new("random", e.to_string()))?;
94    Ok(format!("{KEY_PREFIX}{}", lexical::to_hex(&b)))
95}
96
97/// Creates a key for `principal`: appends its hash line to `keys_file` (created with mode
98/// 0600 if missing; refused if it exists with a wider mode) and writes the key itself, with a
99/// final newline, to `out` (created new, mode 0600; refused if it exists). Nothing is printed.
100pub fn create_key(keys_file: &Path, principal: &str, per_minute: Option<u32>, out: &Path) -> Result<(), ConfigError> {
101    if !valid_principal(principal) {
102        return Err(ConfigError::new("principal", "letters, digits, -, _, ., @; at most 64"));
103    }
104    if keys_file.exists() {
105        crate::config::read_secret_file(keys_file)?;
106    }
107    let key = new_key()?;
108    let mut opts = std::fs::OpenOptions::new();
109    opts.write(true).create_new(true);
110    #[cfg(unix)]
111    {
112        use std::os::unix::fs::OpenOptionsExt;
113        opts.mode(0o600);
114    }
115    let mut f = opts.open(out).map_err(|e| ConfigError::new(&out.display().to_string(), e.to_string()))?;
116    f.write_all(format!("{key}\n").as_bytes()).map_err(|e| ConfigError::new("key file", e.to_string()))?;
117    let mut opts = std::fs::OpenOptions::new();
118    opts.append(true).create(true);
119    #[cfg(unix)]
120    {
121        use std::os::unix::fs::OpenOptionsExt;
122        opts.mode(0o600);
123    }
124    let mut k = opts.open(keys_file).map_err(|e| ConfigError::new(&keys_file.display().to_string(), e.to_string()))?;
125    let line = match per_minute {
126        Some(n) => format!("{} {principal} {n}\n", datumesh_core::sha256_hex(key.as_bytes())),
127        None => format!("{} {principal}\n", datumesh_core::sha256_hex(key.as_bytes())),
128    };
129    k.write_all(line.as_bytes()).map_err(|e| ConfigError::new("keys file", e.to_string()))?;
130    Ok(())
131}