steid

@jamesgill /

steid/src/domain/token.rs
Rust17.8 KBCode·Blame·History·Raw
1//! Personal access tokens — the credential a git client presents over HTTP Basic.
2
3use std::{
4 fmt,
5 str::FromStr,
6 time::{Duration, SystemTime},
7};
8
9use sha2::{Digest, Sha256};
10use subtle::ConstantTimeEq;
11
12use super::{DomainError, TokenId, UserId};
13
14/// The prefix every Steid token carries.
15///
16/// Present so a leaked token is recognisable as one — secret scanners key off exactly
17/// this — and so a value pasted into the wrong field is obviously a Steid credential.
18const TOKEN_PREFIX: &str = "steid_pat_";
19
20/// How much of a token is kept in the clear to identify it afterwards.
21///
22/// Enough for a person to tell two tokens apart in a list, far short of enough to
23/// guess the rest: the remaining 56 hex characters are still 224 bits.
24const DISPLAY_CHARS: usize = 8;
25
26/// A token in the clear.
27///
28/// Exists for exactly as long as it takes to show it to whoever asked for it. Nothing
29/// stores this — the database holds only a [`TokenHash`] — so a token that is lost is
30/// gone, which is the property that makes the hash worth keeping.
31#[derive(Clone)]
32pub struct TokenSecret(String);
33
34impl TokenSecret {
35 /// Bytes of entropy, matching [`SetupToken`](super::SetupToken).
36 const BYTES: usize = 32;
37
38 /// Mints a fresh token from the OS random source.
39 pub fn generate() -> Self {
40 use rand::Rng;
41
42 let mut bytes = [0u8; Self::BYTES];
43 rand::rng().fill_bytes(&mut bytes);
44
45 let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
46
47 Self(format!("{TOKEN_PREFIX}{random}"))
48 }
49
50 /// Wraps a value presented by a client, which may be anything at all.
51 pub fn from_presented(value: impl Into<String>) -> Self {
52 Self(value.into())
53 }
54
55 /// The token's hash, as stored.
56 pub fn hash(&self) -> TokenHash {
57 TokenHash::of(&self.0)
58 }
59
60 /// The leading characters kept in the clear, for naming the token in a list.
61 ///
62 /// Empty for a value that is not a Steid token at all, which only ever happens for
63 /// something a client presented — and nothing displays those.
64 pub fn display_prefix(&self) -> String {
65 self.0
66 .strip_prefix(TOKEN_PREFIX)
67 .unwrap_or_default()
68 .chars()
69 .take(DISPLAY_CHARS)
70 .collect()
71 }
72
73 /// The token itself, to be shown exactly once.
74 pub fn reveal(&self) -> &str {
75 &self.0
76 }
77}
78
79/// Redacted, so a token cannot reach a log line except through [`reveal`](Self::reveal).
80impl fmt::Debug for TokenSecret {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 f.write_str("TokenSecret(redacted)")
83 }
84}
85
86/// The SHA-256 of a token, hex-encoded.
87///
88/// SHA-256 rather than Argon2 deliberately: a token is 256 bits from the OS random
89/// source, so there is no dictionary to slow an attacker down through, and this
90/// credential is verified on every request of every clone. See
91/// [0007](../../plans/decisions/0007-tokens-over-http-basic.md).
92#[derive(Clone, PartialEq, Eq, Hash)]
93pub struct TokenHash(String);
94
95impl TokenHash {
96 /// Hashes a token.
97 pub fn of(plaintext: &str) -> Self {
98 let digest = Sha256::digest(plaintext.as_bytes());
99
100 Self(digest.iter().map(|byte| format!("{byte:02x}")).collect())
101 }
102
103 /// Wraps an already-computed hash, typically one loaded from the database.
104 pub fn from_trusted(value: impl Into<String>) -> Self {
105 Self(value.into())
106 }
107
108 pub fn as_str(&self) -> &str {
109 &self.0
110 }
111
112 /// Whether two hashes are the same, compared in constant time.
113 ///
114 /// Belt and braces: recovering a token from a timing signal on its *hash* would
115 /// need a preimage attack. It costs nothing, and the day this is compared against
116 /// something that is secret, the habit is already in place.
117 pub fn matches(&self, other: &Self) -> bool {
118 self.0.as_bytes().ct_eq(other.0.as_bytes()).into()
119 }
120}
121
122/// Redacted for the same reason as [`TokenSecret`]: a hash in a log is a hash an
123/// attacker can compare against.
124impl fmt::Debug for TokenHash {
125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126 f.write_str("TokenHash(redacted)")
127 }
128}
129
130/// How long a freshly issued token lives.
131///
132/// A closed set rather than a duration, because the form offers a choice and an
133/// arbitrary number of seconds is not a thing anyone wants to type. Ninety days is the
134/// default: long enough that a laptop's credential is not a monthly chore, short enough
135/// that a token pasted into a machine that was thrown away years ago stops working.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
137pub enum TokenLifetime {
138 Days30,
139 #[default]
140 Days90,
141 Year,
142 /// No expiry at all. Still offered, because a token driving a long-lived mirror
143 /// that nobody will be around to rotate is a real case, and one that silently stops
144 /// working is worse than one that was chosen deliberately.
145 Never,
146}
147
148impl TokenLifetime {
149 /// Every choice, in the order the form offers them.
150 pub const ALL: [Self; 4] = [Self::Days30, Self::Days90, Self::Year, Self::Never];
151
152 /// The form value, and what [`from_str`](Self::from_str) reads back.
153 pub fn as_str(&self) -> &'static str {
154 match self {
155 Self::Days30 => "30d",
156 Self::Days90 => "90d",
157 Self::Year => "1y",
158 Self::Never => "never",
159 }
160 }
161
162 /// What the choice is called on screen.
163 pub fn label(&self) -> &'static str {
164 match self {
165 Self::Days30 => "30 days",
166 Self::Days90 => "90 days",
167 Self::Year => "1 year",
168 Self::Never => "No expiry",
169 }
170 }
171
172 /// When a token issued at `from` under this lifetime stops working.
173 ///
174 /// Days are 86 400 seconds — no calendar, no leap seconds. An expiry a few seconds
175 /// off after a year is not a fact anyone can act on, and the alternative is a date
176 /// library for one arithmetic.
177 pub fn expires_at(&self, from: SystemTime) -> Option<SystemTime> {
178 let days = match self {
179 Self::Days30 => 30,
180 Self::Days90 => 90,
181 Self::Year => 365,
182 Self::Never => return None,
183 };
184
185 Some(from + Duration::from_secs(days * 86_400))
186 }
187}
188
189/// `Result`, never `Option`: a lifetime that silently defaulted would issue a token
190/// that outlives what the person chose.
191impl FromStr for TokenLifetime {
192 type Err = DomainError;
193
194 fn from_str(value: &str) -> Result<Self, Self::Err> {
195 Self::ALL
196 .into_iter()
197 .find(|lifetime| lifetime.as_str() == value)
198 .ok_or_else(|| DomainError::validation("expiry", "choose one of the offered periods"))
199 }
200}
201
202/// A personal access token, as recorded.
203///
204/// Carries no scope. A token acts as the user who issued it, which is what one owner
205/// means; narrowing that is a change to make when something actually needs it, behind
206/// an unchanged port.
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct PersonalAccessToken {
209 pub id: TokenId,
210 pub user_id: UserId,
211 /// What the person called it, so they can tell which one to revoke.
212 pub name: String,
213 /// The leading characters of the token, kept so a list can name one it cannot show.
214 pub prefix: String,
215 pub token_hash: TokenHash,
216 pub created_at: SystemTime,
217 /// When the token stops authenticating, or `None` for one that never does.
218 pub expires_at: Option<SystemTime>,
219 /// When the token last authenticated something, to the nearest
220 /// [`USE_RESOLUTION`](Self::USE_RESOLUTION), or `None` for one never used.
221 pub last_used_at: Option<SystemTime>,
222}
223
224impl PersonalAccessToken {
225 /// Longer than any label a person will type, short enough to bound a row.
226 const MAX_NAME: usize = 100;
227
228 /// How precisely a token's last use is recorded.
229 ///
230 /// A clone is several authenticated requests and a busy mirror is many more, so
231 /// writing a row per authentication would turn a read path into a write path. The
232 /// list says "2 hours ago"; a minute's resolution is far finer than anything it
233 /// shows.
234 pub const USE_RESOLUTION: Duration = Duration::from_secs(60);
235
236 /// Validates a new token record.
237 pub fn new(
238 id: TokenId,
239 user_id: UserId,
240 name: impl AsRef<str>,
241 secret: &TokenSecret,
242 created_at: SystemTime,
243 lifetime: TokenLifetime,
244 ) -> Result<Self, DomainError> {
245 let name = name.as_ref().trim();
246
247 if name.is_empty() {
248 return Err(DomainError::validation(
249 "name",
250 "give the token a name so you can tell it apart later",
251 ));
252 }
253
254 if name.chars().count() > Self::MAX_NAME {
255 return Err(DomainError::validation(
256 "name",
257 format!("a token name is at most {} characters", Self::MAX_NAME),
258 ));
259 }
260
261 Ok(Self {
262 id,
263 user_id,
264 name: name.to_owned(),
265 prefix: secret.display_prefix(),
266 token_hash: secret.hash(),
267 created_at,
268 expires_at: lifetime.expires_at(created_at),
269 last_used_at: None,
270 })
271 }
272
273 /// Rebuilds a record from storage without revalidating it.
274 ///
275 /// Eight arguments because the row has eight columns. Grouping them into a struct
276 /// would be a second shape of the same aggregate, kept in step by hand.
277 #[allow(clippy::too_many_arguments)]
278 pub fn from_trusted(
279 id: TokenId,
280 user_id: UserId,
281 name: impl Into<String>,
282 prefix: impl Into<String>,
283 token_hash: TokenHash,
284 created_at: SystemTime,
285 expires_at: Option<SystemTime>,
286 last_used_at: Option<SystemTime>,
287 ) -> Self {
288 Self {
289 id,
290 user_id,
291 name: name.into(),
292 prefix: prefix.into(),
293 token_hash,
294 created_at,
295 expires_at,
296 last_used_at,
297 }
298 }
299
300 /// Whether the token has stopped authenticating.
301 ///
302 /// Expiry is a fact about the record, not about the credential presented, so it is
303 /// asked here rather than in the use case — and the answer is the same whether the
304 /// question comes from authentication or from the list.
305 pub fn is_expired(&self, now: SystemTime) -> bool {
306 self.expires_at.is_some_and(|expires| now >= expires)
307 }
308
309 /// Whether a use at `now` is worth writing down.
310 ///
311 /// False for a use within [`USE_RESOLUTION`](Self::USE_RESOLUTION) of the one
312 /// already recorded, which is what keeps a clone from writing a row per request.
313 /// Also false for a recorded use in the *future* — a clock that went backwards
314 /// should not make every request a write until it catches up.
315 pub fn should_record_use(&self, now: SystemTime) -> bool {
316 let Some(last) = self.last_used_at else {
317 return true;
318 };
319
320 now.duration_since(last)
321 .is_ok_and(|since| since >= Self::USE_RESOLUTION)
322 }
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 fn token(name: &str) -> Result<PersonalAccessToken, DomainError> {
330 PersonalAccessToken::new(
331 TokenId::generate(),
332 UserId::generate(),
333 name,
334 &TokenSecret::generate(),
335 SystemTime::UNIX_EPOCH,
336 TokenLifetime::default(),
337 )
338 }
339
340 fn at(seconds: u64) -> SystemTime {
341 SystemTime::UNIX_EPOCH + Duration::from_secs(seconds)
342 }
343
344 fn issued(lifetime: TokenLifetime) -> PersonalAccessToken {
345 PersonalAccessToken::new(
346 TokenId::generate(),
347 UserId::generate(),
348 "laptop",
349 &TokenSecret::generate(),
350 at(1_000),
351 lifetime,
352 )
353 .expect("valid")
354 }
355
356 #[test]
357 fn a_generated_token_is_recognisable_and_full_width() {
358 let secret = TokenSecret::generate();
359
360 assert!(secret.reveal().starts_with("steid_pat_"));
361 assert_eq!(
362 secret.reveal().len(),
363 "steid_pat_".len() + TokenSecret::BYTES * 2
364 );
365 }
366
367 #[test]
368 fn tokens_are_unique_per_generation() {
369 assert_ne!(
370 TokenSecret::generate().reveal(),
371 TokenSecret::generate().reveal()
372 );
373 }
374
375 #[test]
376 fn a_token_hashes_to_the_same_value_every_time() {
377 let secret = TokenSecret::generate();
378
379 assert!(secret.hash().matches(&secret.hash()));
380 }
381
382 #[test]
383 fn different_tokens_hash_differently() {
384 let first = TokenSecret::generate();
385 let second = TokenSecret::generate();
386
387 assert!(!first.hash().matches(&second.hash()));
388 }
389
390 #[test]
391 fn a_presented_value_hashes_the_same_as_the_token_it_copies() {
392 // This is the whole authentication path: what arrives over Basic is hashed and
393 // compared against what was stored.
394 let secret = TokenSecret::generate();
395 let presented = TokenSecret::from_presented(secret.reveal());
396
397 assert!(presented.hash().matches(&secret.hash()));
398 }
399
400 #[test]
401 fn the_hash_is_not_the_token() {
402 let secret = TokenSecret::generate();
403
404 assert_ne!(secret.hash().as_str(), secret.reveal());
405 assert_eq!(secret.hash().as_str().len(), 64);
406 }
407
408 #[test]
409 fn the_display_prefix_identifies_without_revealing() {
410 let secret = TokenSecret::generate();
411 let prefix = secret.display_prefix();
412
413 assert_eq!(prefix.len(), 8);
414 assert!(secret.reveal().contains(&prefix));
415 assert!(
416 !prefix.starts_with("steid_pat_"),
417 "the prefix should identify the token, not the product"
418 );
419 }
420
421 #[test]
422 fn a_value_that_is_not_a_steid_token_has_no_prefix() {
423 assert_eq!(TokenSecret::from_presented("hunter2").display_prefix(), "");
424 }
425
426 #[test]
427 fn debug_output_redacts_both_the_token_and_its_hash() {
428 let secret = TokenSecret::generate();
429
430 assert_eq!(format!("{secret:?}"), "TokenSecret(redacted)");
431 assert_eq!(format!("{:?}", secret.hash()), "TokenHash(redacted)");
432 assert!(!format!("{:?}", token("laptop").expect("valid")).contains(secret.reveal()));
433 }
434
435 #[test]
436 fn a_token_records_its_prefix_and_hash() {
437 let secret = TokenSecret::generate();
438 let record = PersonalAccessToken::new(
439 TokenId::generate(),
440 UserId::generate(),
441 " laptop ",
442 &secret,
443 SystemTime::UNIX_EPOCH,
444 TokenLifetime::default(),
445 )
446 .expect("valid");
447
448 assert_eq!(record.name, "laptop", "the name should be trimmed");
449 assert_eq!(record.prefix, secret.display_prefix());
450 assert!(record.token_hash.matches(&secret.hash()));
451 }
452
453 #[test]
454 fn a_token_needs_a_name() {
455 assert!(token("").is_err());
456 assert!(token(" ").is_err());
457 }
458
459 #[test]
460 fn a_name_has_a_limit() {
461 assert!(token(&"a".repeat(PersonalAccessToken::MAX_NAME)).is_ok());
462 assert!(token(&"a".repeat(PersonalAccessToken::MAX_NAME + 1)).is_err());
463 }
464
465 // --- expiry -------------------------------------------------------------------
466
467 #[test]
468 fn a_lifetime_round_trips_through_its_form_value() {
469 for lifetime in TokenLifetime::ALL {
470 assert_eq!(
471 lifetime.as_str().parse::<TokenLifetime>().expect("known"),
472 lifetime
473 );
474 }
475 }
476
477 #[test]
478 fn an_unknown_lifetime_is_an_error_rather_than_a_default() {
479 // Defaulting silently would issue a token that outlives what was chosen.
480 assert!("".parse::<TokenLifetime>().is_err());
481 assert!("forever".parse::<TokenLifetime>().is_err());
482 assert!("30".parse::<TokenLifetime>().is_err());
483 }
484
485 #[test]
486 fn the_default_lifetime_is_ninety_days() {
487 assert_eq!(TokenLifetime::default(), TokenLifetime::Days90);
488 assert_eq!(
489 TokenLifetime::Days90.expires_at(at(0)),
490 Some(at(90 * 86_400))
491 );
492 }
493
494 #[test]
495 fn a_token_records_the_expiry_its_lifetime_implies() {
496 assert_eq!(
497 issued(TokenLifetime::Days30).expires_at,
498 Some(at(1_000 + 30 * 86_400))
499 );
500 assert_eq!(
501 issued(TokenLifetime::Year).expires_at,
502 Some(at(1_000 + 365 * 86_400))
503 );
504 assert_eq!(issued(TokenLifetime::Never).expires_at, None);
505 }
506
507 #[test]
508 fn a_token_expires_at_its_expiry_and_not_before() {
509 let token = issued(TokenLifetime::Days30);
510 let expires = at(1_000 + 30 * 86_400);
511
512 assert!(!token.is_expired(expires - Duration::from_secs(1)));
513 assert!(token.is_expired(expires));
514 assert!(token.is_expired(expires + Duration::from_secs(1)));
515 }
516
517 #[test]
518 fn a_token_with_no_expiry_never_expires() {
519 assert!(!issued(TokenLifetime::Never).is_expired(at(u32::MAX as u64)));
520 }
521
522 // --- last used ----------------------------------------------------------------
523
524 #[test]
525 fn a_token_starts_never_used() {
526 let token = issued(TokenLifetime::Days90);
527
528 assert_eq!(token.last_used_at, None);
529 assert!(token.should_record_use(at(1_000)));
530 }
531
532 #[test]
533 fn a_use_within_the_minute_is_not_worth_writing_down() {
534 let mut token = issued(TokenLifetime::Days90);
535 token.last_used_at = Some(at(1_000));
536
537 assert!(!token.should_record_use(at(1_000)));
538 assert!(!token.should_record_use(at(1_059)));
539 assert!(token.should_record_use(at(1_060)));
540 }
541
542 #[test]
543 fn a_recorded_use_in_the_future_does_not_make_every_request_a_write() {
544 // A clock that went backwards. Writing here would mean a row per request until
545 // it caught up, which is the cost the resolution exists to avoid.
546 let mut token = issued(TokenLifetime::Days90);
547 token.last_used_at = Some(at(10_000));
548
549 assert!(!token.should_record_use(at(1_000)));
550 }
551}