Skip to main content

eclipse_core/
auth.rs

1//! The dashboard's human door: a username and a password, and the hash that stands in for the
2//! password on disk.
3//!
4//! The dashboard used to have exactly one credential — a 64-character token you found in a config
5//! file and pasted into a field labelled "password". That is a key, not a login. This module is the
6//! login: `ECLIPSE_WEB_USER` and `ECLIPSE_WEB_PASSWORD_HASH` in `.env`, the second one stored so
7//! the file never holds the password itself.
8//!
9//! **Why PBKDF2 and not a plain hash.** A password is a low-entropy secret a person can guess; the
10//! whole defence is making each guess cost something. SHA-256 costs a microsecond, so a stolen
11//! `.env` is a wordlist away from the password. PBKDF2-HMAC-SHA256 at 600,000 iterations costs
12//! some hundreds of milliseconds per guess here — enough that a stolen file is a problem to think
13//! about rather than a problem already solved.
14//!
15//! **Why the string carries its parameters.** `pbkdf2-sha256$600000$<salt>$<digest>` can be raised
16//! later — 600,000 will not be the number in five years — and a login hashes the password with the
17//! *stored* iteration count to check it, so raising [`ITERATIONS`] only affects hashes made after
18//! the change. A new password is a re-run of `eclipse web passwd`, not a migration.
19//!
20//! **Why `ring`.** It is already in the tree (via `rustls`), it is a direct dependency of this
21//! crate, and `cargo build --offline` resolves it — no new crate is available offline.
22//! `ring::pbkdf2::verify` compares in constant time, and the username goes through
23//! [`crate::token::constant_time_eq`], so an unknown user and a wrong password take the same work
24//! and the same time.
25
26use crate::error::{Error, Result};
27
28/// The variable names. Fixed, not configurable: the file a person edits is `.env`, and a
29/// `web.auth_user_env` that named a variable would only add a second place to be wrong. The docs
30/// name these two, `doctor` names them when they are missing, and `eclipse web passwd` writes them.
31pub const USER_VAR: &str = "ECLIPSE_WEB_USER";
32pub const HASH_VAR: &str = "ECLIPSE_WEB_PASSWORD_HASH";
33
34/// How many PBKDF2-HMAC-SHA256 rounds a **new** hash gets. 600,000 is the figure OWASP names for
35/// this construction; the number lives in each stored hash, so an old hash keeps working at its own
36/// count and raising this is a re-run of `eclipse web passwd`.
37pub const ITERATIONS: u32 = 600_000;
38
39/// The scheme tag at the front of a stored hash. Anything else — `sha256$`, `$argon2id$`, a bare
40/// digest — is refused rather than approximated: a hash this build cannot read must fail loudly,
41/// not fall back to something weaker.
42pub const SCHEME: &str = "pbkdf2-sha256";
43
44/// A password hash, parsed from or destined for `.env`.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct Stored {
47    /// The rounds *this* hash was made with — not [`ITERATIONS`], unless it was just made.
48    pub iterations: u32,
49    pub salt: Vec<u8>,
50    pub digest: Vec<u8>,
51}
52
53impl Stored {
54    /// Hash a password with a fresh 16-byte salt and [`ITERATIONS`] rounds.
55    pub fn hash(password: &str) -> Result<Stored> {
56        let mut salt = vec![0u8; 16];
57        getrandom::getrandom(&mut salt)
58            .map_err(|e| Error::Config(format!("cannot read a random salt: {e}")))?;
59        let digest = derive(password, &salt, ITERATIONS)?;
60        Ok(Stored {
61            iterations: ITERATIONS,
62            salt,
63            digest,
64        })
65    }
66
67    /// Parse `pbkdf2-sha256$<iterations>$<salt-hex>$<digest-hex>`.
68    ///
69    /// Strict on purpose: four fields, the scheme tag, decimal iterations in a sane range, and two
70    /// even-length hex strings. A lenient parser here would turn a typo in `.env` into "wrong
71    /// password" for every attempt, which is the least debuggable failure a login has.
72    pub fn parse(text: &str) -> std::result::Result<Stored, String> {
73        let text = text.trim();
74        let mut parts = text.split('$');
75        let (Some(scheme), Some(iterations), Some(salt), Some(digest), None) = (
76            parts.next(),
77            parts.next(),
78            parts.next(),
79            parts.next(),
80            parts.next(),
81        ) else {
82            return Err(format!(
83                "expected {SCHEME}$<iterations>$<salt>$<digest>, got {} field(s)",
84                text.split('$').count()
85            ));
86        };
87        if scheme != SCHEME {
88            return Err(format!(
89                "unknown scheme {scheme:?}: this build only reads {SCHEME}"
90            ));
91        }
92        let iterations: u32 = iterations
93            .parse()
94            .map_err(|_| format!("iterations {iterations:?} is not a number"))?;
95        // Below a thousand rounds the hash is not doing the one thing it exists for; above a
96        // hundred million it is a denial of service aimed at whoever restarts the dashboard.
97        if !(1_000..=100_000_000).contains(&iterations) {
98            return Err(format!(
99                "iterations {iterations} is outside 1,000–100,000,000: a hash nobody can afford to \
100                 check, or one nobody needs to"
101            ));
102        }
103        let salt = unhex(salt).map_err(|e| format!("salt: {e}"))?;
104        let digest = unhex(digest).map_err(|e| format!("digest: {e}"))?;
105        if salt.is_empty() {
106            return Err(
107                "salt is empty: a hash without one is a rainbow table with extra steps".into(),
108            );
109        }
110        if digest.len() != 32 {
111            return Err(format!(
112                "digest is {} bytes, and PBKDF2-HMAC-SHA256 produces 32",
113                digest.len()
114            ));
115        }
116        Ok(Stored {
117            iterations,
118            salt,
119            digest,
120        })
121    }
122
123    /// Does this password produce this digest? Constant time inside `ring`, and it always does the
124    /// full work — no early return on a short password, no comparison of plaintexts.
125    pub fn verify(&self, password: &str) -> bool {
126        let Some(count) = std::num::NonZeroU32::new(self.iterations) else {
127            return false;
128        };
129        ring::pbkdf2::verify(
130            ring::pbkdf2::PBKDF2_HMAC_SHA256,
131            count,
132            &self.salt,
133            password.as_bytes(),
134            &self.digest,
135        )
136        .is_ok()
137    }
138}
139
140impl std::fmt::Display for Stored {
141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142        write!(
143            f,
144            "{SCHEME}${}${}${}",
145            self.iterations,
146            hex(&self.salt),
147            hex(&self.digest)
148        )
149    }
150}
151
152/// Hash a password into the string `.env` holds.
153pub fn hash_password(password: &str) -> Result<String> {
154    Ok(Stored::hash(password)?.to_string())
155}
156
157/// Check a password against a stored hash string. A string this build cannot parse is `false`:
158/// the caller has already refused to start on one (see [`Credentials::resolve`]), so an
159/// unparsable value reaching here means something rewrote `.env` under a running process, and
160/// refusing every password is the safe half of that.
161pub fn verify_password(password: &str, stored: &str) -> bool {
162    match Stored::parse(stored) {
163        Ok(stored) => stored.verify(password),
164        Err(_) => false,
165    }
166}
167
168/// What a sign-in is checked against.
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub enum Credentials {
171    /// `ECLIPSE_WEB_USER` and `ECLIPSE_WEB_PASSWORD_HASH` are both set.
172    Password { user: String, hash: Stored },
173    /// No hash: the dashboard's shared token is still the only human door. This is the migration
174    /// case — every install that predates the password form — and it must keep signing in until
175    /// somebody runs `eclipse web passwd`.
176    Token,
177}
178
179impl Credentials {
180    /// Decide from the environment. `lookup` is asked for each name, so the caller decides where
181    /// values come from (process environment first, then `.env` — the same order the config loader
182    /// uses).
183    ///
184    /// A hash that does not parse is an **error**, not a fallback: a dashboard that quietly
185    /// downgraded to the token because one line of `.env` had a typo would be a security decision
186    /// taken by accident.
187    pub fn resolve(lookup: impl Fn(&str) -> Option<String>) -> std::result::Result<Self, String> {
188        let hash = lookup(HASH_VAR).filter(|v| !v.trim().is_empty());
189        let user = lookup(USER_VAR).filter(|v| !v.trim().is_empty());
190        match (user, hash) {
191            (None, None) => Ok(Credentials::Token),
192            (None, Some(_)) => Err(format!(
193                "{HASH_VAR} is set but {USER_VAR} is not: a password with no username is half a \
194                 login. Run `eclipse web passwd <name>`."
195            )),
196            (Some(user), None) => Err(format!(
197                "{USER_VAR} is {:?} but {HASH_VAR} is not set, so there is no password to check \
198                 it against. Run `eclipse web passwd`.",
199                user.trim()
200            )),
201            (Some(user), Some(hash)) => Ok(Credentials::Password {
202                user: user.trim().to_string(),
203                hash: Stored::parse(&hash).map_err(|e| format!("{HASH_VAR}: {e}"))?,
204            }),
205        }
206    }
207
208    /// The mode name the page draws: `password` or `token`.
209    pub fn mode(&self) -> &'static str {
210        match self {
211            Credentials::Password { .. } => "password",
212            Credentials::Token => "token",
213        }
214    }
215
216    /// Does this pair sign in?
217    ///
218    /// Both halves are computed before either is looked at, so an unknown username costs a PBKDF2
219    /// derivation exactly like a wrong password does — otherwise the fastest way to learn a valid
220    /// username would be a stopwatch. `token` is the dashboard's shared secret, used only in
221    /// [`Credentials::Token`].
222    pub fn check(&self, user: &str, secret: &str, token: &str) -> bool {
223        if secret.is_empty() {
224            return false;
225        }
226        match self {
227            Credentials::Password {
228                user: expected,
229                hash,
230            } => {
231                let user_ok = crate::token::constant_time_eq(user.trim(), expected);
232                let pass_ok = hash.verify(secret);
233                user_ok & pass_ok
234            }
235            Credentials::Token => crate::token::constant_time_eq(secret.trim(), token),
236        }
237    }
238}
239
240fn hex(bytes: &[u8]) -> String {
241    let mut out = String::with_capacity(bytes.len() * 2);
242    for b in bytes {
243        out.push(char::from_digit((b >> 4) as u32, 16).unwrap_or('0'));
244        out.push(char::from_digit((b & 0xf) as u32, 16).unwrap_or('0'));
245    }
246    out
247}
248
249fn unhex(text: &str) -> std::result::Result<Vec<u8>, String> {
250    let chars: Vec<char> = text.chars().collect();
251    if !chars.len().is_multiple_of(2) {
252        return Err(format!(
253            "{} hex digits is not a whole number of bytes",
254            chars.len()
255        ));
256    }
257    let mut out = Vec::with_capacity(chars.len() / 2);
258    for pair in chars.chunks(2) {
259        let hi = pair[0]
260            .to_digit(16)
261            .ok_or_else(|| format!("{:?} is not hex", pair[0]))?;
262        let lo = pair[1]
263            .to_digit(16)
264            .ok_or_else(|| format!("{:?} is not hex", pair[1]))?;
265        out.push((hi * 16 + lo) as u8);
266    }
267    Ok(out)
268}
269
270/// Set variables in the `.env` the loader reads, keeping everything else in the file.
271///
272/// A rewrite of the *whole* file is not an option: `.env` holds this install's other secrets, and
273/// `config init` already refuses to overwrite one for exactly that reason. So the file is read,
274/// the named keys are replaced in place (every occurrence: the loader takes the last, and a file
275/// with two values for one key is a file somebody will read wrong), and anything else is left
276/// byte for byte. The write goes through the same `0600` path as `config init`.
277pub fn write_env_vars(path: &std::path::Path, pairs: &[(&str, &str)]) -> Result<()> {
278    if let Some(dir) = path.parent() {
279        std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
280    }
281    let existing = match std::fs::read_to_string(path) {
282        Ok(text) => text,
283        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
284        Err(e) => return Err(Error::io(path, e)),
285    };
286    let mut lines: Vec<String> = existing.lines().map(|l| l.to_string()).collect();
287    for (key, value) in pairs {
288        let prefix = format!("{key}=");
289        let mut found = false;
290        for line in lines.iter_mut() {
291            let body = line.trim_start();
292            let body = body.strip_prefix("export ").unwrap_or(body);
293            if body.starts_with(&prefix) {
294                *line = format!("{key}={value}");
295                found = true;
296            }
297        }
298        if !found {
299            // Appended, not inserted: the file's own order is somebody's reading order.
300            lines.push(format!("{key}={value}"));
301        }
302    }
303    let mut body = lines.join("\n");
304    if !body.ends_with('\n') {
305        body.push('\n');
306    }
307    crate::config::write_private(path, &body)
308}
309
310/// PBKDF2-HMAC-SHA256, `iterations` rounds, into a 32-byte digest.
311fn derive(password: &str, salt: &[u8], iterations: u32) -> Result<Vec<u8>> {
312    let count = std::num::NonZeroU32::new(iterations)
313        .ok_or_else(|| Error::Config("zero iterations is not a hash".into()))?;
314    let mut digest = vec![0u8; 32];
315    ring::pbkdf2::derive(
316        ring::pbkdf2::PBKDF2_HMAC_SHA256,
317        count,
318        salt,
319        password.as_bytes(),
320        &mut digest,
321    );
322    Ok(digest)
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328    use std::collections::BTreeMap;
329
330    fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
331        let map: BTreeMap<String, String> = pairs
332            .iter()
333            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
334            .collect();
335        move |name| map.get(name).cloned()
336    }
337
338    /// The whole point of the format: a hash made at one iteration count is still checked at it,
339    /// so raising the number is a re-run of `web passwd` rather than a flag day.
340    #[test]
341    fn a_hash_carries_its_own_parameters_and_reads_back() {
342        let mut stored = Stored::hash("correct horse").unwrap();
343        assert_eq!(stored.iterations, ITERATIONS);
344        let text = stored.to_string();
345        assert!(text.starts_with("pbkdf2-sha256$600000$"), "{text}");
346        let parsed = Stored::parse(&text).unwrap();
347        assert_eq!(parsed, stored);
348        assert!(parsed.verify("correct horse"));
349        assert!(
350            !parsed.verify("correct horse "),
351            "never trimmed, never normalised"
352        );
353
354        // A hash from an older build keeps working: four rounds is absurd, but the point is that
355        // the *stored* number decides, not `ITERATIONS`.
356        stored.iterations = 1_000;
357        let older = Stored {
358            digest: derive("hunter2", &stored.salt, 1_000).unwrap(),
359            ..stored
360        };
361        assert!(Stored::parse(&older.to_string()).unwrap().verify("hunter2"));
362        assert!(!Stored::parse(&older.to_string())
363            .unwrap()
364            .verify("hunter2!"));
365    }
366
367    #[test]
368    fn a_salt_makes_two_identical_passwords_hash_differently() {
369        let a = Stored::hash("same password").unwrap();
370        let b = Stored::hash("same password").unwrap();
371        assert_ne!(a.salt, b.salt, "a fresh salt every time");
372        assert_ne!(a.to_string(), b.to_string());
373        assert!(a.verify("same password") && b.verify("same password"));
374    }
375
376    /// Every way a stored hash can be wrong, and what each one is called. None of them may be
377    /// read as a working hash: a lenient parser turns a typo into "wrong password" forever.
378    #[test]
379    fn a_hash_this_build_cannot_read_is_refused_by_name() {
380        let cases = [
381            ("", "field"),
382            ("pbkdf2-sha256$600000$abcd", "field"),
383            ("sha256$600000$aabb$ccdd", "unknown scheme"),
384            ("pbkdf2-sha256$lots$aabb$ccdd", "not a number"),
385            ("pbkdf2-sha256$10$aabb$ccdd", "outside"),
386            ("pbkdf2-sha256$600000$$ccdd", "empty"),
387            ("pbkdf2-sha256$600000$aabb$ccdd", "32"),
388            ("pbkdf2-sha256$600000$aazb$ccdd", "not hex"),
389            ("pbkdf2-sha256$600000$aabb$ccdd$ee", "field"),
390        ];
391        for (text, needle) in cases {
392            let err = Stored::parse(text).unwrap_err();
393            assert!(err.contains(needle), "{text:?} → {err}");
394            assert!(!verify_password("whatever", text), "{text:?}");
395        }
396    }
397
398    /// The three states `.env` can be in, and the migration one is not an error: an install that
399    /// predates the password form keeps the token door until somebody sets a password.
400    #[test]
401    fn credentials_are_password_or_the_old_token_never_a_downgrade() {
402        assert_eq!(Credentials::resolve(env(&[])).unwrap(), Credentials::Token);
403        let half = Credentials::resolve(env(&[(USER_VAR, " max ")])).unwrap_err();
404        assert!(
405            half.contains(USER_VAR) && half.contains(HASH_VAR) && half.contains("web passwd"),
406            "{half}"
407        );
408        assert!(
409            half.contains("\"max\""),
410            "the name is named, and trimmed: {half}"
411        );
412        assert!(
413            Credentials::resolve(env(&[(HASH_VAR, "pbkdf2-sha256$600000$aabb$ccdd")]))
414                .unwrap_err()
415                .contains(USER_VAR)
416        );
417
418        let hash = hash_password("s3cret").unwrap();
419        let creds = Credentials::resolve(env(&[(USER_VAR, "max"), (HASH_VAR, &hash)])).unwrap();
420        assert_eq!(creds.mode(), "password");
421        assert_eq!(
422            creds,
423            Credentials::Password {
424                user: "max".into(),
425                hash: Stored::parse(&hash).unwrap()
426            }
427        );
428
429        // A hash that does not parse is an error, not "fall back to the token": a dashboard that
430        // downgraded itself because of a typo would be a security decision taken by accident.
431        let bad = Credentials::resolve(env(&[(USER_VAR, "max"), (HASH_VAR, "nonsense")]));
432        assert!(bad.unwrap_err().contains(HASH_VAR));
433    }
434
435    #[test]
436    fn a_right_pair_signs_in_and_nothing_else_does() {
437        let hash = hash_password("open sesame").unwrap();
438        let creds = Credentials::resolve(env(&[(USER_VAR, "max"), (HASH_VAR, &hash)])).unwrap();
439        assert!(creds.check("max", "open sesame", "token"));
440        assert!(!creds.check("max", "open sesam", "token"));
441        assert!(!creds.check("mor", "open sesame", "token"));
442        assert!(!creds.check("", "open sesame", "token"));
443        // An empty secret never signs in, whatever the stored hash says.
444        assert!(!creds.check("max", "", "token"));
445
446        let token = Credentials::Token;
447        assert!(token.check("", "the-token", "the-token"));
448        assert!(token.check("ignored", "the-token", "the-token"));
449        assert!(!token.check("", "the-toke", "the-token"));
450
451        assert_eq!(token.mode(), "token");
452    }
453}