steid

@jamesgill /

steid/src/domain/password.rs
Rust6.0 KBCode·Blame·History·Raw
1use std::fmt;
2
3use super::DomainError;
4
5/// A plaintext password that has passed the one rule Steid has.
6///
7/// **The rule is length and nothing else: at least 12 characters.** No required digit,
8/// no required symbol, no forbidden dictionary word. Length is the property that
9/// measurably makes a password harder to guess; composition rules mostly make people
10/// write theirs down, or turn `password` into `Password1!`, which is not stronger.
11///
12/// The ceiling is a different kind of rule. Argon2 hashes whatever it is given, so an
13/// unbounded password is an unbounded amount of work for one unauthenticated request —
14/// [`MAX_BYTES`](Self::MAX_BYTES) bounds it. Nobody reaches it by typing.
15///
16/// **This applies to passwords being set, never to passwords being checked.** Signing in
17/// does not construct one, so an account created before the rule keeps working; its owner
18/// meets the rule the next time they change it.
19#[derive(Clone, PartialEq, Eq)]
20pub struct Password(String);
21
22impl Password {
23 /// The minimum, in characters rather than bytes, so a password made of emoji or
24 /// non-Latin script is measured the way its owner typed it.
25 pub const MIN_LEN: usize = 12;
26
27 /// The maximum, in bytes, because it exists to bound Argon2's work rather than to
28 /// say anything about the password.
29 pub const MAX_BYTES: usize = 512;
30
31 /// The one sentence every surface shows when a password is refused for its length.
32 ///
33 /// A constant so the setup form, the reset page and the settings page cannot drift
34 /// into three different accounts of the same rule.
35 pub const RULE: &'static str = "Passwords must be at least 12 characters. That is the only rule — length is what makes one hard to guess.";
36
37 /// Validates a password someone is trying to set.
38 ///
39 /// Not trimmed: leading and trailing spaces are part of a password, and silently
40 /// removing them would make a password that cannot be typed back.
41 pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
42 let value = value.into();
43
44 if value.chars().count() < Self::MIN_LEN {
45 return Err(DomainError::validation("password", Self::RULE));
46 }
47
48 if value.len() > Self::MAX_BYTES {
49 return Err(DomainError::validation(
50 "password",
51 format!("must be at most {} bytes", Self::MAX_BYTES),
52 ));
53 }
54
55 Ok(Self(value))
56 }
57
58 /// Exposes the plaintext, for hashing and nothing else.
59 pub fn expose(&self) -> &str {
60 &self.0
61 }
62}
63
64impl fmt::Debug for Password {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 f.write_str("Password(redacted)")
67 }
68}
69
70/// An opaque password hash.
71///
72/// `Debug` is implemented by hand to redact the digest: the whole point of this type
73/// is that a hash can never reach a log line by accident. There is deliberately no
74/// `Display`.
75#[derive(Clone, PartialEq, Eq)]
76pub struct PasswordHash(String);
77
78impl PasswordHash {
79 /// Wraps a hash produced by a [`PasswordHasher`](crate::application::port::PasswordHasher).
80 ///
81 /// Takes a hash, never a plaintext password. Hashing belongs to the adapter.
82 pub fn from_trusted(value: impl Into<String>) -> Self {
83 Self(value.into())
84 }
85
86 /// Exposes the encoded hash, for storage or verification only.
87 pub fn as_str(&self) -> &str {
88 &self.0
89 }
90}
91
92impl fmt::Debug for PasswordHash {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 f.write_str("PasswordHash(redacted)")
95 }
96}
97
98#[cfg(test)]
99mod tests {
100 use super::*;
101
102 #[test]
103 fn a_password_shorter_than_twelve_characters_is_refused() {
104 for short in ["", "hunter2", "elevenchars"] {
105 let error = Password::new(short).expect_err("should refuse");
106
107 assert!(matches!(
108 error,
109 DomainError::Validation { ref field, .. } if field == "password"
110 ));
111 assert_eq!(
112 error.to_string(),
113 format!("invalid password: {}", Password::RULE)
114 );
115 }
116 }
117
118 #[test]
119 fn twelve_characters_is_enough_and_nothing_else_is_required() {
120 // The whole point of the rule: no digit, no symbol, no mixed case.
121 let password = Password::new("correcthorse").expect("twelve lowercase letters");
122
123 assert_eq!(password.expose(), "correcthorse");
124 assert!(Password::new("aaaaaaaaaaaa").is_ok());
125 }
126
127 #[test]
128 fn length_is_counted_in_characters_not_bytes() {
129 // Twelve emoji are four bytes each. Measuring bytes here would let a shorter
130 // password through in one script and refuse a longer one in another.
131 assert!(Password::new("🔑🔑🔑🔑🔑🔑🔑🔑🔑🔑🔑🔑").is_ok());
132 assert!(Password::new("🔑🔑🔑🔑🔑🔑🔑🔑🔑🔑🔑").is_err());
133 }
134
135 #[test]
136 fn spaces_are_part_of_the_password() {
137 let password = Password::new(" twelve ok ").expect("thirteen characters");
138
139 assert_eq!(password.expose(), " twelve ok ");
140 }
141
142 #[test]
143 fn a_password_past_the_argon2_ceiling_is_refused() {
144 assert!(Password::new("a".repeat(Password::MAX_BYTES)).is_ok());
145
146 let error = Password::new("a".repeat(Password::MAX_BYTES + 1)).expect_err("should refuse");
147
148 assert!(error.to_string().contains("512 bytes"));
149 }
150
151 #[test]
152 fn debug_output_redacts_the_plaintext() {
153 let password = Password::new("correcthorsebattery").expect("valid");
154
155 assert_eq!(format!("{password:?}"), "Password(redacted)");
156 }
157
158 #[test]
159 fn debug_output_redacts_the_hash() {
160 let hash = PasswordHash::from_trusted("$argon2id$v=19$m=19456,t=2,p=1$abc$def");
161
162 let rendered = format!("{hash:?}");
163
164 assert_eq!(rendered, "PasswordHash(redacted)");
165 assert!(!rendered.contains("argon2"));
166 assert!(!rendered.contains("def"));
167 }
168
169 #[test]
170 fn the_hash_is_still_reachable_for_storage() {
171 let hash = PasswordHash::from_trusted("$argon2id$stored");
172
173 assert_eq!(hash.as_str(), "$argon2id$stored");
174 }
175}