1use std::collections::HashMap;
9use std::io::Write;
10use std::path::Path;
11
12use datumesh_core::lexical;
13
14use crate::config::ConfigError;
15
16#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct Principal {
19 pub id: String,
21 pub per_minute: Option<u32>,
23}
24
25#[derive(Clone, Debug, Default, PartialEq, Eq)]
27pub struct ApiKeys {
28 by_hash: HashMap<String, Principal>,
29}
30
31pub 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 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 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 pub fn insert_hash(&mut self, sha256: &str, principal: Principal) {
76 self.by_hash.insert(sha256.to_string(), principal);
77 }
78
79 pub fn len(&self) -> usize {
81 self.by_hash.len()
82 }
83
84 pub fn is_empty(&self) -> bool {
86 self.by_hash.is_empty()
87 }
88}
89
90pub 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
97pub 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}