Skip to main content

loqui_server/
auth.rs

1//! Bearer tokens.
2//!
3//! Only SHA-256 digests of accepted tokens are held in memory, and a
4//! presented token is compared against each in constant time. Plaintext is
5//! read, hashed and zeroed. A token is accepted only in an
6//! `Authorization: Bearer` header, never in a query string, where it would
7//! land in logs and browser history.
8//!
9//! Where tokens come from, in order: an explicit token file, the
10//! `LOQUI_TOKEN` environment variable (discouraged: other processes of the
11//! same user can read `/proc/<pid>/environ`), and otherwise a token loqui
12//! generates on first run and keeps in a file only the owner can read.
13//! Token files must be regular files owned by the current user with no
14//! group or other permissions; anything else is refused rather than
15//! trusted.
16
17use std::io::Write;
18use std::path::{Path, PathBuf};
19
20use sha2::{Digest, Sha256};
21use subtle::ConstantTimeEq;
22use zeroize::Zeroizing;
23
24use crate::Error;
25
26/// Generated tokens start with this, so a leaked one is recognisable in a
27/// secret scanner.
28pub const TOKEN_PREFIX: &str = "loqui_";
29
30/// Where the accepted token came from, for `loqui doctor` and the startup
31/// log. Never the token itself.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum TokenSource {
34    File(PathBuf),
35    Environment,
36    Generated(PathBuf),
37}
38
39impl std::fmt::Display for TokenSource {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        match self {
42            Self::File(p) => write!(f, "token file {}", p.display()),
43            Self::Environment => f.write_str("LOQUI_TOKEN environment variable"),
44            Self::Generated(p) => write!(f, "generated token in {}", p.display()),
45        }
46    }
47}
48
49/// The set of tokens a server accepts.
50pub struct Tokens {
51    digests: Vec<[u8; 32]>,
52    source: TokenSource,
53}
54
55impl std::fmt::Debug for Tokens {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.debug_struct("Tokens").field("count", &self.digests.len()).field("source", &self.source).finish()
58    }
59}
60
61fn digest(token: &str) -> [u8; 32] {
62    Sha256::digest(token.as_bytes()).into()
63}
64
65impl Tokens {
66    /// Accepts exactly `token`. For tests and embedding.
67    pub fn from_plaintext(token: &str, source: TokenSource) -> Result<Self, Error> {
68        validate(token)?;
69        Ok(Self { digests: vec![digest(token)], source })
70    }
71
72    /// Resolves tokens in precedence order: `file`, then `LOQUI_TOKEN`,
73    /// then the generated token at `generated_path` (created if missing).
74    pub fn resolve(file: Option<&Path>, env: Option<Zeroizing<String>>, generated_path: &Path) -> Result<Self, Error> {
75        if let Some(path) = file {
76            return Self::load_file(path, TokenSource::File(path.to_owned()));
77        }
78        if let Some(token) = env {
79            let token = token.trim();
80            validate(token)?;
81            return Ok(Self { digests: vec![digest(token)], source: TokenSource::Environment });
82        }
83        if !generated_path.exists() {
84            generate_file(generated_path)?;
85        }
86        Self::load_file(generated_path, TokenSource::Generated(generated_path.to_owned()))
87    }
88
89    /// Reads one token per non-empty, non-`#` line, so a file can hold a
90    /// token per client and tokens can be rotated without downtime.
91    fn load_file(path: &Path, source: TokenSource) -> Result<Self, Error> {
92        check_private_file(path)?;
93        let text = Zeroizing::new(std::fs::read_to_string(path).map_err(|e| Error::Token(format!("reading {}: {e}", path.display())))?);
94        let mut digests = Vec::new();
95        for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) {
96            validate(line)?;
97            digests.push(digest(line));
98        }
99        if digests.is_empty() {
100            return Err(Error::Token(format!("{} holds no token", path.display())));
101        }
102        Ok(Self { digests, source })
103    }
104
105    pub fn source(&self) -> &TokenSource {
106        &self.source
107    }
108
109    /// Whether `presented` is an accepted token. Every stored digest is
110    /// compared, in constant time, whichever matches.
111    pub fn accepts(&self, presented: &str) -> bool {
112        let presented = digest(presented);
113        self.digests.iter().fold(subtle::Choice::from(0), |any, d| any | d.ct_eq(&presented)).into()
114    }
115
116    /// Checks an `Authorization` header value.
117    pub fn accepts_header(&self, header: Option<&str>) -> bool {
118        header.and_then(|h| h.strip_prefix("Bearer ").or_else(|| h.strip_prefix("bearer "))).is_some_and(|token| self.accepts(token.trim()))
119    }
120}
121
122/// Tokens must be long enough not to be guessed and printable enough to go
123/// in a header.
124fn validate(token: &str) -> Result<(), Error> {
125    if token.len() < 16 {
126        return Err(Error::Token("a token must be at least 16 characters".into()));
127    }
128    if !token.bytes().all(|b| b.is_ascii_graphic()) {
129        return Err(Error::Token("a token must be printable ASCII without spaces".into()));
130    }
131    Ok(())
132}
133
134/// 256 bits from the operating system's RNG, base64url without padding.
135pub fn generate() -> Result<Zeroizing<String>, Error> {
136    let mut bytes = Zeroizing::new([0u8; 32]);
137    getrandom::fill(bytes.as_mut()).map_err(|e| Error::Token(format!("OS random source failed: {e}")))?;
138    Ok(Zeroizing::new(format!("{TOKEN_PREFIX}{}", base64url(bytes.as_ref()))))
139}
140
141fn base64url(bytes: &[u8]) -> String {
142    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
143    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
144    for chunk in bytes.chunks(3) {
145        let n = chunk.iter().enumerate().fold(0u32, |n, (i, &b)| n | u32::from(b) << (16 - 8 * i));
146        for i in 0..=chunk.len() {
147            out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char);
148        }
149    }
150    out
151}
152
153/// Writes a fresh token to `path` with mode 0600, atomically: it is written
154/// to a temporary file in the same private directory, then renamed, so a
155/// crash never leaves a half-written or world-readable token.
156pub fn generate_file(path: &Path) -> Result<(), Error> {
157    let dir = path.parent().ok_or_else(|| Error::Token(format!("{} has no parent directory", path.display())))?;
158    crate::fs::private_dir(dir)?;
159    let token = generate()?;
160    let tmp = dir.join(format!(".token.{}.tmp", std::process::id()));
161    let mut options = std::fs::OpenOptions::new();
162    options.write(true).create_new(true);
163    #[cfg(unix)]
164    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
165    let result = options.open(&tmp).and_then(|mut f| {
166        writeln!(f, "{}", token.as_str())?;
167        f.sync_all()
168    });
169    if let Err(e) = result {
170        let _ = std::fs::remove_file(&tmp);
171        return Err(Error::Token(format!("writing {}: {e}", tmp.display())));
172    }
173    std::fs::rename(&tmp, path).map_err(|e| Error::Token(format!("installing {}: {e}", path.display())))?;
174    Ok(())
175}
176
177/// Replaces the token file with a new token. Existing clients stop working.
178pub fn rotate(path: &Path) -> Result<(), Error> {
179    if path.exists() {
180        check_private_file(path)?;
181    }
182    let dir = path.parent().ok_or_else(|| Error::Token(format!("{} has no parent directory", path.display())))?;
183    let staged = dir.join(".token.rotate");
184    let _ = std::fs::remove_file(&staged);
185    generate_file(&staged)?;
186    std::fs::rename(&staged, path).map_err(|e| Error::Token(format!("installing {}: {e}", path.display())))
187}
188
189/// Refuses a token file others could read or replace.
190pub fn check_private_file(path: &Path) -> Result<(), Error> {
191    let meta = std::fs::symlink_metadata(path).map_err(|e| Error::Token(format!("{}: {e}", path.display())))?;
192    if !meta.file_type().is_file() {
193        return Err(Error::Token(format!("{} is not a regular file (symlinks are refused)", path.display())));
194    }
195    #[cfg(unix)]
196    {
197        use std::os::unix::fs::MetadataExt;
198        if meta.mode() & 0o077 != 0 {
199            return Err(Error::Token(format!(
200                "{} is readable or writable by others (mode {:o}); run: chmod 600 {}",
201                path.display(),
202                meta.mode() & 0o777,
203                path.display()
204            )));
205        }
206        if meta.uid() != crate::fs::current_uid() {
207            return Err(Error::Token(format!("{} is owned by uid {}, not by this user", path.display(), meta.uid())));
208        }
209    }
210    Ok(())
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    fn temp_dir(name: &str) -> PathBuf {
218        let dir = std::env::temp_dir().join(format!("loqui-auth-{name}-{}", std::process::id()));
219        let _ = std::fs::remove_dir_all(&dir);
220        dir
221    }
222
223    #[test]
224    fn generated_tokens_are_long_prefixed_and_distinct() {
225        let (a, b) = (generate().unwrap(), generate().unwrap());
226        assert!(a.starts_with(TOKEN_PREFIX));
227        assert_eq!(a.len(), TOKEN_PREFIX.len() + 43);
228        assert_ne!(*a, *b);
229    }
230
231    #[test]
232    fn base64url_matches_rfc4648() {
233        assert_eq!(base64url(b"f"), "Zg");
234        assert_eq!(base64url(b"fo"), "Zm8");
235        assert_eq!(base64url(b"foo"), "Zm9v");
236        assert_eq!(base64url(&[0xfb, 0xff]), "-_8");
237    }
238
239    #[test]
240    fn accepts_only_bearer_headers_with_a_known_token() {
241        let tokens = Tokens::from_plaintext("loqui_correct-horse-battery", TokenSource::Environment).unwrap();
242        assert!(tokens.accepts_header(Some("Bearer loqui_correct-horse-battery")));
243        assert!(!tokens.accepts_header(Some("Bearer loqui_correct-horse-batter")));
244        assert!(!tokens.accepts_header(Some("Basic bG9xdWk=")));
245        assert!(!tokens.accepts_header(Some("loqui_correct-horse-battery")));
246        assert!(!tokens.accepts_header(None));
247    }
248
249    #[test]
250    fn short_or_unprintable_tokens_are_rejected() {
251        assert!(Tokens::from_plaintext("short", TokenSource::Environment).is_err());
252        assert!(Tokens::from_plaintext("has a space in it ok", TokenSource::Environment).is_err());
253    }
254
255    #[cfg(unix)]
256    #[test]
257    fn generated_file_is_private_and_reloads() {
258        use std::os::unix::fs::PermissionsExt;
259        let dir = temp_dir("gen");
260        let path = dir.join("token");
261        let tokens = Tokens::resolve(None, None, &path).unwrap();
262        assert_eq!(tokens.source(), &TokenSource::Generated(path.clone()));
263        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
264        assert_eq!(std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700);
265        let token = std::fs::read_to_string(&path).unwrap();
266        assert!(Tokens::resolve(None, None, &path).unwrap().accepts(token.trim()));
267        rotate(&path).unwrap();
268        assert!(!Tokens::resolve(None, None, &path).unwrap().accepts(token.trim()));
269        std::fs::remove_dir_all(&dir).unwrap();
270    }
271
272    #[cfg(unix)]
273    #[test]
274    fn readable_or_linked_token_files_are_refused() {
275        use std::os::unix::fs::PermissionsExt;
276        let dir = temp_dir("perm");
277        std::fs::create_dir_all(&dir).unwrap();
278        let path = dir.join("token");
279        std::fs::write(&path, "loqui_0123456789abcdef\n").unwrap();
280        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
281        let err = Tokens::resolve(Some(&path), None, &dir.join("unused")).unwrap_err().to_string();
282        assert!(err.contains("chmod 600"), "{err}");
283        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
284        assert!(Tokens::resolve(Some(&path), None, &dir.join("unused")).is_ok());
285        let link = dir.join("link");
286        std::os::unix::fs::symlink(&path, &link).unwrap();
287        assert!(Tokens::resolve(Some(&link), None, &dir.join("unused")).is_err());
288        std::fs::remove_dir_all(&dir).unwrap();
289    }
290
291    #[test]
292    fn a_file_can_hold_several_tokens() {
293        let dir = temp_dir("multi");
294        std::fs::create_dir_all(&dir).unwrap();
295        let path = dir.join("tokens");
296        std::fs::write(&path, "# client one\nloqui_aaaaaaaaaaaaaaaa\n\nloqui_bbbbbbbbbbbbbbbb\n").unwrap();
297        #[cfg(unix)]
298        std::fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(0o600)).unwrap();
299        let tokens = Tokens::resolve(Some(&path), None, &dir.join("unused")).unwrap();
300        assert!(tokens.accepts("loqui_aaaaaaaaaaaaaaaa") && tokens.accepts("loqui_bbbbbbbbbbbbbbbb"));
301        std::fs::remove_dir_all(&dir).unwrap();
302    }
303}