1use crate::error::{Error, Result};
27
28pub const USER_VAR: &str = "ECLIPSE_WEB_USER";
32pub const HASH_VAR: &str = "ECLIPSE_WEB_PASSWORD_HASH";
33
34pub const ITERATIONS: u32 = 600_000;
38
39pub const SCHEME: &str = "pbkdf2-sha256";
43
44#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct Stored {
47 pub iterations: u32,
49 pub salt: Vec<u8>,
50 pub digest: Vec<u8>,
51}
52
53impl Stored {
54 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 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 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 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
152pub fn hash_password(password: &str) -> Result<String> {
154 Ok(Stored::hash(password)?.to_string())
155}
156
157pub 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#[derive(Debug, Clone, PartialEq, Eq)]
170pub enum Credentials {
171 Password { user: String, hash: Stored },
173 Token,
177}
178
179impl Credentials {
180 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 pub fn mode(&self) -> &'static str {
210 match self {
211 Credentials::Password { .. } => "password",
212 Credentials::Token => "token",
213 }
214 }
215
216 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
270pub 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 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
310fn 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 #[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 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 #[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 #[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 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 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}