eclipse-core 0.13.4

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! The dashboard's human door: a username and a password, and the hash that stands in for the
//! password on disk.
//!
//! The dashboard used to have exactly one credential — a 64-character token you found in a config
//! file and pasted into a field labelled "password". That is a key, not a login. This module is the
//! login: `ECLIPSE_WEB_USER` and `ECLIPSE_WEB_PASSWORD_HASH` in `.env`, the second one stored so
//! the file never holds the password itself.
//!
//! **Why PBKDF2 and not a plain hash.** A password is a low-entropy secret a person can guess; the
//! whole defence is making each guess cost something. SHA-256 costs a microsecond, so a stolen
//! `.env` is a wordlist away from the password. PBKDF2-HMAC-SHA256 at 600,000 iterations costs
//! some hundreds of milliseconds per guess here — enough that a stolen file is a problem to think
//! about rather than a problem already solved.
//!
//! **Why the string carries its parameters.** `pbkdf2-sha256$600000$<salt>$<digest>` can be raised
//! later — 600,000 will not be the number in five years — and a login hashes the password with the
//! *stored* iteration count to check it, so raising [`ITERATIONS`] only affects hashes made after
//! the change. A new password is a re-run of `eclipse web passwd`, not a migration.
//!
//! **Why `ring`.** It is already in the tree (via `rustls`), it is a direct dependency of this
//! crate, and `cargo build --offline` resolves it — no new crate is available offline.
//! `ring::pbkdf2::verify` compares in constant time, and the username goes through
//! [`crate::token::constant_time_eq`], so an unknown user and a wrong password take the same work
//! and the same time.

use crate::error::{Error, Result};

/// The variable names. Fixed, not configurable: the file a person edits is `.env`, and a
/// `web.auth_user_env` that named a variable would only add a second place to be wrong. The docs
/// name these two, `doctor` names them when they are missing, and `eclipse web passwd` writes them.
pub const USER_VAR: &str = "ECLIPSE_WEB_USER";
pub const HASH_VAR: &str = "ECLIPSE_WEB_PASSWORD_HASH";

/// How many PBKDF2-HMAC-SHA256 rounds a **new** hash gets. 600,000 is the figure OWASP names for
/// this construction; the number lives in each stored hash, so an old hash keeps working at its own
/// count and raising this is a re-run of `eclipse web passwd`.
pub const ITERATIONS: u32 = 600_000;

/// The scheme tag at the front of a stored hash. Anything else — `sha256$`, `$argon2id$`, a bare
/// digest — is refused rather than approximated: a hash this build cannot read must fail loudly,
/// not fall back to something weaker.
pub const SCHEME: &str = "pbkdf2-sha256";

/// A password hash, parsed from or destined for `.env`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stored {
    /// The rounds *this* hash was made with — not [`ITERATIONS`], unless it was just made.
    pub iterations: u32,
    pub salt: Vec<u8>,
    pub digest: Vec<u8>,
}

impl Stored {
    /// Hash a password with a fresh 16-byte salt and [`ITERATIONS`] rounds.
    pub fn hash(password: &str) -> Result<Stored> {
        let mut salt = vec![0u8; 16];
        getrandom::getrandom(&mut salt)
            .map_err(|e| Error::Config(format!("cannot read a random salt: {e}")))?;
        let digest = derive(password, &salt, ITERATIONS)?;
        Ok(Stored {
            iterations: ITERATIONS,
            salt,
            digest,
        })
    }

    /// Parse `pbkdf2-sha256$<iterations>$<salt-hex>$<digest-hex>`.
    ///
    /// Strict on purpose: four fields, the scheme tag, decimal iterations in a sane range, and two
    /// even-length hex strings. A lenient parser here would turn a typo in `.env` into "wrong
    /// password" for every attempt, which is the least debuggable failure a login has.
    pub fn parse(text: &str) -> std::result::Result<Stored, String> {
        let text = text.trim();
        let mut parts = text.split('$');
        let (Some(scheme), Some(iterations), Some(salt), Some(digest), None) = (
            parts.next(),
            parts.next(),
            parts.next(),
            parts.next(),
            parts.next(),
        ) else {
            return Err(format!(
                "expected {SCHEME}$<iterations>$<salt>$<digest>, got {} field(s)",
                text.split('$').count()
            ));
        };
        if scheme != SCHEME {
            return Err(format!(
                "unknown scheme {scheme:?}: this build only reads {SCHEME}"
            ));
        }
        let iterations: u32 = iterations
            .parse()
            .map_err(|_| format!("iterations {iterations:?} is not a number"))?;
        // Below a thousand rounds the hash is not doing the one thing it exists for; above a
        // hundred million it is a denial of service aimed at whoever restarts the dashboard.
        if !(1_000..=100_000_000).contains(&iterations) {
            return Err(format!(
                "iterations {iterations} is outside 1,000–100,000,000: a hash nobody can afford to \
                 check, or one nobody needs to"
            ));
        }
        let salt = unhex(salt).map_err(|e| format!("salt: {e}"))?;
        let digest = unhex(digest).map_err(|e| format!("digest: {e}"))?;
        if salt.is_empty() {
            return Err(
                "salt is empty: a hash without one is a rainbow table with extra steps".into(),
            );
        }
        if digest.len() != 32 {
            return Err(format!(
                "digest is {} bytes, and PBKDF2-HMAC-SHA256 produces 32",
                digest.len()
            ));
        }
        Ok(Stored {
            iterations,
            salt,
            digest,
        })
    }

    /// Does this password produce this digest? Constant time inside `ring`, and it always does the
    /// full work — no early return on a short password, no comparison of plaintexts.
    pub fn verify(&self, password: &str) -> bool {
        let Some(count) = std::num::NonZeroU32::new(self.iterations) else {
            return false;
        };
        ring::pbkdf2::verify(
            ring::pbkdf2::PBKDF2_HMAC_SHA256,
            count,
            &self.salt,
            password.as_bytes(),
            &self.digest,
        )
        .is_ok()
    }
}

impl std::fmt::Display for Stored {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{SCHEME}${}${}${}",
            self.iterations,
            hex(&self.salt),
            hex(&self.digest)
        )
    }
}

/// Hash a password into the string `.env` holds.
pub fn hash_password(password: &str) -> Result<String> {
    Ok(Stored::hash(password)?.to_string())
}

/// Check a password against a stored hash string. A string this build cannot parse is `false`:
/// the caller has already refused to start on one (see [`Credentials::resolve`]), so an
/// unparsable value reaching here means something rewrote `.env` under a running process, and
/// refusing every password is the safe half of that.
pub fn verify_password(password: &str, stored: &str) -> bool {
    match Stored::parse(stored) {
        Ok(stored) => stored.verify(password),
        Err(_) => false,
    }
}

/// What a sign-in is checked against.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Credentials {
    /// `ECLIPSE_WEB_USER` and `ECLIPSE_WEB_PASSWORD_HASH` are both set.
    Password { user: String, hash: Stored },
    /// No hash: the dashboard's shared token is still the only human door. This is the migration
    /// case — every install that predates the password form — and it must keep signing in until
    /// somebody runs `eclipse web passwd`.
    Token,
}

impl Credentials {
    /// Decide from the environment. `lookup` is asked for each name, so the caller decides where
    /// values come from (process environment first, then `.env` — the same order the config loader
    /// uses).
    ///
    /// A hash that does not parse is an **error**, not a fallback: a dashboard that quietly
    /// downgraded to the token because one line of `.env` had a typo would be a security decision
    /// taken by accident.
    pub fn resolve(lookup: impl Fn(&str) -> Option<String>) -> std::result::Result<Self, String> {
        let hash = lookup(HASH_VAR).filter(|v| !v.trim().is_empty());
        let user = lookup(USER_VAR).filter(|v| !v.trim().is_empty());
        match (user, hash) {
            (None, None) => Ok(Credentials::Token),
            (None, Some(_)) => Err(format!(
                "{HASH_VAR} is set but {USER_VAR} is not: a password with no username is half a \
                 login. Run `eclipse web passwd <name>`."
            )),
            (Some(user), None) => Err(format!(
                "{USER_VAR} is {:?} but {HASH_VAR} is not set, so there is no password to check \
                 it against. Run `eclipse web passwd`.",
                user.trim()
            )),
            (Some(user), Some(hash)) => Ok(Credentials::Password {
                user: user.trim().to_string(),
                hash: Stored::parse(&hash).map_err(|e| format!("{HASH_VAR}: {e}"))?,
            }),
        }
    }

    /// The mode name the page draws: `password` or `token`.
    pub fn mode(&self) -> &'static str {
        match self {
            Credentials::Password { .. } => "password",
            Credentials::Token => "token",
        }
    }

    /// Does this pair sign in?
    ///
    /// Both halves are computed before either is looked at, so an unknown username costs a PBKDF2
    /// derivation exactly like a wrong password does — otherwise the fastest way to learn a valid
    /// username would be a stopwatch. `token` is the dashboard's shared secret, used only in
    /// [`Credentials::Token`].
    pub fn check(&self, user: &str, secret: &str, token: &str) -> bool {
        if secret.is_empty() {
            return false;
        }
        match self {
            Credentials::Password {
                user: expected,
                hash,
            } => {
                let user_ok = crate::token::constant_time_eq(user.trim(), expected);
                let pass_ok = hash.verify(secret);
                user_ok & pass_ok
            }
            Credentials::Token => crate::token::constant_time_eq(secret.trim(), token),
        }
    }
}

fn hex(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        out.push(char::from_digit((b >> 4) as u32, 16).unwrap_or('0'));
        out.push(char::from_digit((b & 0xf) as u32, 16).unwrap_or('0'));
    }
    out
}

fn unhex(text: &str) -> std::result::Result<Vec<u8>, String> {
    let chars: Vec<char> = text.chars().collect();
    if !chars.len().is_multiple_of(2) {
        return Err(format!(
            "{} hex digits is not a whole number of bytes",
            chars.len()
        ));
    }
    let mut out = Vec::with_capacity(chars.len() / 2);
    for pair in chars.chunks(2) {
        let hi = pair[0]
            .to_digit(16)
            .ok_or_else(|| format!("{:?} is not hex", pair[0]))?;
        let lo = pair[1]
            .to_digit(16)
            .ok_or_else(|| format!("{:?} is not hex", pair[1]))?;
        out.push((hi * 16 + lo) as u8);
    }
    Ok(out)
}

/// Set variables in the `.env` the loader reads, keeping everything else in the file.
///
/// A rewrite of the *whole* file is not an option: `.env` holds this install's other secrets, and
/// `config init` already refuses to overwrite one for exactly that reason. So the file is read,
/// the named keys are replaced in place (every occurrence: the loader takes the last, and a file
/// with two values for one key is a file somebody will read wrong), and anything else is left
/// byte for byte. The write goes through the same `0600` path as `config init`.
pub fn write_env_vars(path: &std::path::Path, pairs: &[(&str, &str)]) -> Result<()> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
    }
    let existing = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(Error::io(path, e)),
    };
    let mut lines: Vec<String> = existing.lines().map(|l| l.to_string()).collect();
    for (key, value) in pairs {
        let prefix = format!("{key}=");
        let mut found = false;
        for line in lines.iter_mut() {
            let body = line.trim_start();
            let body = body.strip_prefix("export ").unwrap_or(body);
            if body.starts_with(&prefix) {
                *line = format!("{key}={value}");
                found = true;
            }
        }
        if !found {
            // Appended, not inserted: the file's own order is somebody's reading order.
            lines.push(format!("{key}={value}"));
        }
    }
    let mut body = lines.join("\n");
    if !body.ends_with('\n') {
        body.push('\n');
    }
    crate::config::write_private(path, &body)
}

/// PBKDF2-HMAC-SHA256, `iterations` rounds, into a 32-byte digest.
fn derive(password: &str, salt: &[u8], iterations: u32) -> Result<Vec<u8>> {
    let count = std::num::NonZeroU32::new(iterations)
        .ok_or_else(|| Error::Config("zero iterations is not a hash".into()))?;
    let mut digest = vec![0u8; 32];
    ring::pbkdf2::derive(
        ring::pbkdf2::PBKDF2_HMAC_SHA256,
        count,
        salt,
        password.as_bytes(),
        &mut digest,
    );
    Ok(digest)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;

    fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
        let map: BTreeMap<String, String> = pairs
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect();
        move |name| map.get(name).cloned()
    }

    /// The whole point of the format: a hash made at one iteration count is still checked at it,
    /// so raising the number is a re-run of `web passwd` rather than a flag day.
    #[test]
    fn a_hash_carries_its_own_parameters_and_reads_back() {
        let mut stored = Stored::hash("correct horse").unwrap();
        assert_eq!(stored.iterations, ITERATIONS);
        let text = stored.to_string();
        assert!(text.starts_with("pbkdf2-sha256$600000$"), "{text}");
        let parsed = Stored::parse(&text).unwrap();
        assert_eq!(parsed, stored);
        assert!(parsed.verify("correct horse"));
        assert!(
            !parsed.verify("correct horse "),
            "never trimmed, never normalised"
        );

        // A hash from an older build keeps working: four rounds is absurd, but the point is that
        // the *stored* number decides, not `ITERATIONS`.
        stored.iterations = 1_000;
        let older = Stored {
            digest: derive("hunter2", &stored.salt, 1_000).unwrap(),
            ..stored
        };
        assert!(Stored::parse(&older.to_string()).unwrap().verify("hunter2"));
        assert!(!Stored::parse(&older.to_string())
            .unwrap()
            .verify("hunter2!"));
    }

    #[test]
    fn a_salt_makes_two_identical_passwords_hash_differently() {
        let a = Stored::hash("same password").unwrap();
        let b = Stored::hash("same password").unwrap();
        assert_ne!(a.salt, b.salt, "a fresh salt every time");
        assert_ne!(a.to_string(), b.to_string());
        assert!(a.verify("same password") && b.verify("same password"));
    }

    /// Every way a stored hash can be wrong, and what each one is called. None of them may be
    /// read as a working hash: a lenient parser turns a typo into "wrong password" forever.
    #[test]
    fn a_hash_this_build_cannot_read_is_refused_by_name() {
        let cases = [
            ("", "field"),
            ("pbkdf2-sha256$600000$abcd", "field"),
            ("sha256$600000$aabb$ccdd", "unknown scheme"),
            ("pbkdf2-sha256$lots$aabb$ccdd", "not a number"),
            ("pbkdf2-sha256$10$aabb$ccdd", "outside"),
            ("pbkdf2-sha256$600000$$ccdd", "empty"),
            ("pbkdf2-sha256$600000$aabb$ccdd", "32"),
            ("pbkdf2-sha256$600000$aazb$ccdd", "not hex"),
            ("pbkdf2-sha256$600000$aabb$ccdd$ee", "field"),
        ];
        for (text, needle) in cases {
            let err = Stored::parse(text).unwrap_err();
            assert!(err.contains(needle), "{text:?} → {err}");
            assert!(!verify_password("whatever", text), "{text:?}");
        }
    }

    /// The three states `.env` can be in, and the migration one is not an error: an install that
    /// predates the password form keeps the token door until somebody sets a password.
    #[test]
    fn credentials_are_password_or_the_old_token_never_a_downgrade() {
        assert_eq!(Credentials::resolve(env(&[])).unwrap(), Credentials::Token);
        let half = Credentials::resolve(env(&[(USER_VAR, " max ")])).unwrap_err();
        assert!(
            half.contains(USER_VAR) && half.contains(HASH_VAR) && half.contains("web passwd"),
            "{half}"
        );
        assert!(
            half.contains("\"max\""),
            "the name is named, and trimmed: {half}"
        );
        assert!(
            Credentials::resolve(env(&[(HASH_VAR, "pbkdf2-sha256$600000$aabb$ccdd")]))
                .unwrap_err()
                .contains(USER_VAR)
        );

        let hash = hash_password("s3cret").unwrap();
        let creds = Credentials::resolve(env(&[(USER_VAR, "max"), (HASH_VAR, &hash)])).unwrap();
        assert_eq!(creds.mode(), "password");
        assert_eq!(
            creds,
            Credentials::Password {
                user: "max".into(),
                hash: Stored::parse(&hash).unwrap()
            }
        );

        // A hash that does not parse is an error, not "fall back to the token": a dashboard that
        // downgraded itself because of a typo would be a security decision taken by accident.
        let bad = Credentials::resolve(env(&[(USER_VAR, "max"), (HASH_VAR, "nonsense")]));
        assert!(bad.unwrap_err().contains(HASH_VAR));
    }

    #[test]
    fn a_right_pair_signs_in_and_nothing_else_does() {
        let hash = hash_password("open sesame").unwrap();
        let creds = Credentials::resolve(env(&[(USER_VAR, "max"), (HASH_VAR, &hash)])).unwrap();
        assert!(creds.check("max", "open sesame", "token"));
        assert!(!creds.check("max", "open sesam", "token"));
        assert!(!creds.check("mor", "open sesame", "token"));
        assert!(!creds.check("", "open sesame", "token"));
        // An empty secret never signs in, whatever the stored hash says.
        assert!(!creds.check("max", "", "token"));

        let token = Credentials::Token;
        assert!(token.check("", "the-token", "the-token"));
        assert!(token.check("ignored", "the-token", "the-token"));
        assert!(!token.check("", "the-toke", "the-token"));

        assert_eq!(token.mode(), "token");
    }
}