steid

@jamesgill /

Rust21.5 KBCode·Blame·History·Raw
1//! Issuing, listing, revoking and authenticating personal access tokens.
2//!
3//! Tokens **authenticate**; they do not authorize. Presenting one says who the actor is,
4//! and every rule about what that actor may do stays where it already lives. See
5//! [0007](../../plans/decisions/0007-tokens-over-http-basic.md).
6
7use std::time::SystemTime;
8
9use crate::domain::{
10 Actor, DomainError, PersonalAccessToken, TokenId, TokenLifetime, TokenSecret,
11 repository::TokenRepository,
12};
13
14use super::error::Result;
15
16/// A token, and the one and only chance to read it.
17///
18/// The secret is not stored anywhere — only its hash is — so a caller that drops this
19/// without showing it has issued a credential nobody will ever be able to use.
20#[derive(Debug)]
21pub struct IssuedToken {
22 pub token: PersonalAccessToken,
23 pub secret: TokenSecret,
24}
25
26/// A token as it appears in a listing.
27///
28/// Carries the prefix rather than anything presentable: a list has to name tokens
29/// without being able to show them.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct TokenSummary {
32 pub id: TokenId,
33 pub name: String,
34 pub prefix: String,
35 pub created_at: SystemTime,
36 /// When it stops working, or `None` for a token that never does.
37 pub expires_at: Option<SystemTime>,
38 /// When it was last used, to the nearest minute, or `None` for one never used.
39 pub last_used_at: Option<SystemTime>,
40 /// Whether it has already stopped working, answered against the clock the listing
41 /// was made with rather than left for the caller to work out — the rule about what
42 /// "expired" means lives in one place.
43 pub expired: bool,
44}
45
46/// Issues a token to the actor, for the actor.
47///
48/// There is no "issue a token for someone else": a credential that acts as a user can
49/// only be minted by that user. An anonymous caller is refused rather than being
50/// silently given nothing.
51pub async fn issue_token(
52 actor: &Actor,
53 name: &str,
54 lifetime: TokenLifetime,
55 now: SystemTime,
56 tokens: &impl TokenRepository,
57) -> Result<IssuedToken> {
58 let Some(user_id) = actor.user_id() else {
59 return Err(DomainError::Forbidden.into());
60 };
61
62 let secret = TokenSecret::generate();
63 let token = PersonalAccessToken::new(
64 TokenId::generate(),
65 user_id.clone(),
66 name,
67 &secret,
68 now,
69 lifetime,
70 )?;
71
72 tokens.save(&token).await?;
73
74 Ok(IssuedToken { token, secret })
75}
76
77/// Every token the actor holds, newest first.
78///
79/// Empty for an anonymous caller rather than an error: there is nothing to hide and
80/// nothing to show.
81///
82/// Expired tokens are listed rather than hidden, and are still revocable. A credential
83/// that stopped working is exactly the one a person wants to see and clear out, and a
84/// list that quietly drops rows reads as data loss.
85pub async fn list_tokens(
86 actor: &Actor,
87 now: SystemTime,
88 tokens: &impl TokenRepository,
89) -> Result<Vec<TokenSummary>> {
90 let Some(user_id) = actor.user_id() else {
91 return Ok(Vec::new());
92 };
93
94 Ok(tokens
95 .list_by_user(user_id)
96 .await?
97 .into_iter()
98 .map(|token| TokenSummary {
99 expired: token.is_expired(now),
100 id: token.id,
101 name: token.name,
102 prefix: token.prefix,
103 created_at: token.created_at,
104 expires_at: token.expires_at,
105 last_used_at: token.last_used_at,
106 })
107 .collect())
108}
109
110/// Revokes one of the actor's own tokens.
111///
112/// A token belonging to someone else answers `NotFound`, not `Forbidden` — the same
113/// reason an invisible repository is absent rather than refused. Telling a caller that
114/// a token id exists but is not theirs is a fact they have no business learning.
115pub async fn revoke_token(
116 actor: &Actor,
117 id: &TokenId,
118 tokens: &impl TokenRepository,
119) -> Result<()> {
120 let Some(user_id) = actor.user_id() else {
121 return Err(not_found());
122 };
123
124 // Found by listing rather than by id: the port has no `find_by_id`, and adding one
125 // would exist solely to be paired with an ownership check that this already makes
126 // impossible to forget.
127 let owned = tokens
128 .list_by_user(user_id)
129 .await?
130 .into_iter()
131 .any(|token| &token.id == id);
132
133 if !owned {
134 return Err(not_found());
135 }
136
137 tokens.delete(id).await?;
138
139 Ok(())
140}
141
142/// Resolves a presented token into the actor it authenticates.
143///
144/// Anything unrecognised resolves to [`Actor::Anonymous`], exactly as
145/// [`resolve_actor`](super::session::resolve_actor) does for sessions: authentication
146/// never fails open, and never errors merely because a credential is wrong.
147///
148/// **An expired token is anonymous, exactly like an unknown one.** Same answer, same
149/// path, nothing in the response saying which — 0007's uniform 401 covers this too, and
150/// "your token expired" is a fact worth learning only to someone who already holds it.
151/// The list is where a person finds out, which is where they can act on it.
152///
153/// Successful authentication records the use, at most once per
154/// [`USE_RESOLUTION`](PersonalAccessToken::USE_RESOLUTION): a clone is several
155/// authenticated requests and a mirror many more, so the record is compared before it is
156/// written. A failed write is swallowed — a last-used timestamp is not worth failing a
157/// clone over.
158pub async fn authenticate_token(
159 presented: &str,
160 now: SystemTime,
161 tokens: &impl TokenRepository,
162) -> Result<Actor> {
163 let presented = TokenSecret::from_presented(presented);
164
165 let Some(token) = tokens.find_by_hash(&presented.hash()).await? else {
166 return Ok(Actor::Anonymous);
167 };
168
169 if token.is_expired(now) {
170 return Ok(Actor::Anonymous);
171 }
172
173 if token.should_record_use(now)
174 && let Err(error) = tokens.touch_last_used(&token.id, now).await
175 {
176 eprintln!("steid: could not record a token's last use: {error}");
177 }
178
179 Ok(Actor::User(token.user_id))
180}
181
182fn not_found() -> super::error::Error {
183 DomainError::NotFound { entity: "token" }.into()
184}
185
186#[cfg(test)]
187mod tests {
188 use std::time::Duration;
189
190 use super::*;
191 use crate::{domain::UserId, infrastructure::repository::InMemoryTokenRepo};
192
193 fn at(seconds: u64) -> SystemTime {
194 SystemTime::UNIX_EPOCH + Duration::from_secs(seconds)
195 }
196
197 struct Fixture {
198 tokens: InMemoryTokenRepo,
199 user: Actor,
200 other: Actor,
201 }
202
203 fn fixture() -> Fixture {
204 Fixture {
205 tokens: InMemoryTokenRepo::new(),
206 user: Actor::User(UserId::generate()),
207 other: Actor::User(UserId::generate()),
208 }
209 }
210
211 // --- issuing ------------------------------------------------------------------
212
213 #[tokio::test]
214 async fn issuing_returns_a_token_that_authenticates_its_owner() {
215 let f = fixture();
216
217 let issued = issue_token(
218 &f.user,
219 "laptop",
220 TokenLifetime::default(),
221 at(1_000),
222 &f.tokens,
223 )
224 .await
225 .expect("should issue");
226
227 let actor = authenticate_token(issued.secret.reveal(), at(1_000), &f.tokens)
228 .await
229 .expect("should authenticate");
230
231 assert_eq!(actor, f.user);
232 }
233
234 #[tokio::test]
235 async fn an_anonymous_caller_cannot_issue_a_token() {
236 // A credential that acts as a user has to be minted by one.
237 let f = fixture();
238
239 let error = issue_token(
240 &Actor::Anonymous,
241 "laptop",
242 TokenLifetime::default(),
243 at(1_000),
244 &f.tokens,
245 )
246 .await
247 .expect_err("should refuse");
248
249 assert!(matches!(
250 error,
251 super::super::Error::Domain(DomainError::Forbidden)
252 ));
253 assert!(
254 list_tokens(&f.user, at(1_000), &f.tokens)
255 .await
256 .expect("list")
257 .is_empty()
258 );
259 }
260
261 #[tokio::test]
262 async fn a_token_needs_a_name() {
263 let f = fixture();
264
265 assert!(
266 issue_token(
267 &f.user,
268 " ",
269 TokenLifetime::default(),
270 at(1_000),
271 &f.tokens
272 )
273 .await
274 .is_err()
275 );
276 }
277
278 #[tokio::test]
279 async fn each_issued_token_is_different() {
280 let f = fixture();
281
282 let first = issue_token(
283 &f.user,
284 "one",
285 TokenLifetime::default(),
286 at(1_000),
287 &f.tokens,
288 )
289 .await
290 .expect("issue");
291 let second = issue_token(
292 &f.user,
293 "two",
294 TokenLifetime::default(),
295 at(2_000),
296 &f.tokens,
297 )
298 .await
299 .expect("issue");
300
301 assert_ne!(first.secret.reveal(), second.secret.reveal());
302 }
303
304 #[tokio::test]
305 async fn the_stored_token_is_not_the_secret() {
306 // The whole point of hashing: a dumped table holds nothing presentable.
307 let f = fixture();
308
309 let issued = issue_token(
310 &f.user,
311 "laptop",
312 TokenLifetime::default(),
313 at(1_000),
314 &f.tokens,
315 )
316 .await
317 .expect("issue");
318
319 assert_ne!(issued.token.token_hash.as_str(), issued.secret.reveal());
320 assert!(
321 !issued
322 .secret
323 .reveal()
324 .contains(issued.token.token_hash.as_str())
325 );
326 }
327
328 // --- authenticating -----------------------------------------------------------
329
330 #[tokio::test]
331 async fn an_unknown_token_is_anonymous_rather_than_an_error() {
332 let f = fixture();
333 issue_token(
334 &f.user,
335 "laptop",
336 TokenLifetime::default(),
337 at(1_000),
338 &f.tokens,
339 )
340 .await
341 .expect("issue");
342
343 for presented in ["", "hunter2", TokenSecret::generate().reveal()] {
344 assert_eq!(
345 authenticate_token(presented, at(1_000), &f.tokens)
346 .await
347 .expect("should not error"),
348 Actor::Anonymous,
349 "{presented:?} should not authenticate"
350 );
351 }
352 }
353
354 #[tokio::test]
355 async fn a_token_authenticates_only_the_user_it_was_issued_to() {
356 let f = fixture();
357 let mine = issue_token(
358 &f.user,
359 "mine",
360 TokenLifetime::default(),
361 at(1_000),
362 &f.tokens,
363 )
364 .await
365 .expect("issue");
366 let theirs = issue_token(
367 &f.other,
368 "theirs",
369 TokenLifetime::default(),
370 at(1_000),
371 &f.tokens,
372 )
373 .await
374 .expect("issue");
375
376 assert_eq!(
377 authenticate_token(mine.secret.reveal(), at(1_000), &f.tokens)
378 .await
379 .expect("authenticate"),
380 f.user
381 );
382 assert_eq!(
383 authenticate_token(theirs.secret.reveal(), at(1_000), &f.tokens)
384 .await
385 .expect("authenticate"),
386 f.other
387 );
388 }
389
390 // --- listing ------------------------------------------------------------------
391
392 #[tokio::test]
393 async fn a_listing_names_tokens_without_showing_them() {
394 let f = fixture();
395 let issued = issue_token(
396 &f.user,
397 "laptop",
398 TokenLifetime::default(),
399 at(1_000),
400 &f.tokens,
401 )
402 .await
403 .expect("issue");
404
405 let listed = list_tokens(&f.user, at(1_000), &f.tokens)
406 .await
407 .expect("list");
408 let summary = listed.first().expect("one token");
409
410 assert_eq!(summary.name, "laptop");
411 assert_eq!(summary.prefix, issued.secret.display_prefix());
412 assert!(
413 !issued.secret.reveal().contains(&format!("{summary:?}")),
414 "a summary must not carry anything presentable"
415 );
416 }
417
418 #[tokio::test]
419 async fn a_listing_covers_only_the_actors_own_tokens() {
420 let f = fixture();
421 issue_token(
422 &f.user,
423 "mine",
424 TokenLifetime::default(),
425 at(1_000),
426 &f.tokens,
427 )
428 .await
429 .expect("issue");
430 issue_token(
431 &f.other,
432 "theirs",
433 TokenLifetime::default(),
434 at(1_000),
435 &f.tokens,
436 )
437 .await
438 .expect("issue");
439
440 let listed = list_tokens(&f.user, at(1_000), &f.tokens)
441 .await
442 .expect("list");
443
444 assert_eq!(listed.len(), 1);
445 assert_eq!(listed[0].name, "mine");
446 }
447
448 #[tokio::test]
449 async fn an_anonymous_caller_lists_nothing() {
450 let f = fixture();
451 issue_token(
452 &f.user,
453 "mine",
454 TokenLifetime::default(),
455 at(1_000),
456 &f.tokens,
457 )
458 .await
459 .expect("issue");
460
461 assert!(
462 list_tokens(&Actor::Anonymous, at(1_000), &f.tokens)
463 .await
464 .expect("list")
465 .is_empty()
466 );
467 }
468
469 // --- revoking -----------------------------------------------------------------
470
471 #[tokio::test]
472 async fn revoking_stops_a_token_authenticating() {
473 let f = fixture();
474 let issued = issue_token(
475 &f.user,
476 "laptop",
477 TokenLifetime::default(),
478 at(1_000),
479 &f.tokens,
480 )
481 .await
482 .expect("issue");
483
484 revoke_token(&f.user, &issued.token.id, &f.tokens)
485 .await
486 .expect("should revoke");
487
488 assert_eq!(
489 authenticate_token(issued.secret.reveal(), at(1_000), &f.tokens)
490 .await
491 .expect("authenticate"),
492 Actor::Anonymous
493 );
494 }
495
496 #[tokio::test]
497 async fn someone_elses_token_cannot_be_revoked_and_still_works() {
498 // Not found rather than forbidden: that a token id exists but belongs to someone
499 // else is not a fact a caller should be able to learn.
500 let f = fixture();
501 let theirs = issue_token(
502 &f.other,
503 "theirs",
504 TokenLifetime::default(),
505 at(1_000),
506 &f.tokens,
507 )
508 .await
509 .expect("issue");
510
511 let error = revoke_token(&f.user, &theirs.token.id, &f.tokens)
512 .await
513 .expect_err("should refuse");
514
515 assert!(matches!(
516 error,
517 super::super::Error::Domain(DomainError::NotFound { entity: "token" })
518 ));
519 assert_eq!(
520 authenticate_token(theirs.secret.reveal(), at(1_000), &f.tokens)
521 .await
522 .expect("authenticate"),
523 f.other,
524 "the token should still work"
525 );
526 }
527
528 #[tokio::test]
529 async fn revoking_an_unknown_token_is_not_found() {
530 let f = fixture();
531
532 let error = revoke_token(&f.user, &TokenId::generate(), &f.tokens)
533 .await
534 .expect_err("should refuse");
535
536 assert!(matches!(
537 error,
538 super::super::Error::Domain(DomainError::NotFound { entity: "token" })
539 ));
540 }
541
542 #[tokio::test]
543 async fn an_anonymous_caller_cannot_revoke_anything() {
544 let f = fixture();
545 let issued = issue_token(
546 &f.user,
547 "laptop",
548 TokenLifetime::default(),
549 at(1_000),
550 &f.tokens,
551 )
552 .await
553 .expect("issue");
554
555 assert!(
556 revoke_token(&Actor::Anonymous, &issued.token.id, &f.tokens)
557 .await
558 .is_err()
559 );
560 assert_eq!(
561 authenticate_token(issued.secret.reveal(), at(1_000), &f.tokens)
562 .await
563 .expect("authenticate"),
564 f.user
565 );
566 }
567
568 // --- expiry and last use ------------------------------------------------------
569
570 /// The stored record behind a secret, so a test can look at what a write did.
571 async fn stored(secret: &TokenSecret, tokens: &InMemoryTokenRepo) -> PersonalAccessToken {
572 tokens
573 .find_by_hash(&secret.hash())
574 .await
575 .expect("read")
576 .expect("the token exists")
577 }
578
579 #[tokio::test]
580 async fn an_expired_token_is_refused_the_same_way_an_unknown_one_is() {
581 // Uniform, per 0007: nothing distinguishes "expired" from "never existed".
582 let f = fixture();
583 let issued = issue_token(
584 &f.user,
585 "laptop",
586 TokenLifetime::Days30,
587 at(1_000),
588 &f.tokens,
589 )
590 .await
591 .expect("issue");
592
593 let expires = at(1_000 + 30 * 86_400);
594
595 assert_eq!(
596 authenticate_token(
597 issued.secret.reveal(),
598 expires - Duration::from_secs(1),
599 &f.tokens
600 )
601 .await
602 .expect("authenticate"),
603 f.user,
604 "it should still work a second before it expires"
605 );
606 assert_eq!(
607 authenticate_token(issued.secret.reveal(), expires, &f.tokens)
608 .await
609 .expect("authenticate"),
610 Actor::Anonymous
611 );
612 }
613
614 #[tokio::test]
615 async fn a_token_issued_with_no_expiry_keeps_working() {
616 let f = fixture();
617 let issued = issue_token(
618 &f.user,
619 "mirror",
620 TokenLifetime::Never,
621 at(1_000),
622 &f.tokens,
623 )
624 .await
625 .expect("issue");
626
627 assert_eq!(
628 authenticate_token(
629 issued.secret.reveal(),
630 at(1_000 + 10 * 365 * 86_400),
631 &f.tokens
632 )
633 .await
634 .expect("authenticate"),
635 f.user
636 );
637 }
638
639 #[tokio::test]
640 async fn an_expired_token_is_still_listed_and_still_revocable() {
641 let f = fixture();
642 let issued = issue_token(&f.user, "old", TokenLifetime::Days30, at(1_000), &f.tokens)
643 .await
644 .expect("issue");
645 let after = at(1_000 + 31 * 86_400);
646
647 let listed = list_tokens(&f.user, after, &f.tokens).await.expect("list");
648 let summary = listed.first().expect("one token");
649
650 assert!(summary.expired);
651 assert_eq!(summary.expires_at, Some(at(1_000 + 30 * 86_400)));
652
653 revoke_token(&f.user, &issued.token.id, &f.tokens)
654 .await
655 .expect("an expired token should still be revocable");
656 assert!(
657 list_tokens(&f.user, after, &f.tokens)
658 .await
659 .expect("list")
660 .is_empty()
661 );
662 }
663
664 #[tokio::test]
665 async fn a_listing_says_a_token_with_no_expiry_has_none() {
666 let f = fixture();
667 issue_token(
668 &f.user,
669 "mirror",
670 TokenLifetime::Never,
671 at(1_000),
672 &f.tokens,
673 )
674 .await
675 .expect("issue");
676
677 let listed = list_tokens(&f.user, at(1_000), &f.tokens)
678 .await
679 .expect("list");
680
681 assert_eq!(listed[0].expires_at, None);
682 assert!(!listed[0].expired);
683 }
684
685 #[tokio::test]
686 async fn authenticating_records_the_use() {
687 let f = fixture();
688 let issued = issue_token(
689 &f.user,
690 "laptop",
691 TokenLifetime::default(),
692 at(1_000),
693 &f.tokens,
694 )
695 .await
696 .expect("issue");
697
698 assert_eq!(stored(&issued.secret, &f.tokens).await.last_used_at, None);
699 assert!(
700 list_tokens(&f.user, at(1_000), &f.tokens)
701 .await
702 .expect("list")[0]
703 .last_used_at
704 .is_none(),
705 "a token that has never been used says so"
706 );
707
708 authenticate_token(issued.secret.reveal(), at(2_000), &f.tokens)
709 .await
710 .expect("authenticate");
711
712 assert_eq!(
713 stored(&issued.secret, &f.tokens).await.last_used_at,
714 Some(at(2_000))
715 );
716 }
717
718 #[tokio::test]
719 async fn a_busy_clone_writes_the_last_use_at_most_once_a_minute() {
720 // A clone is several authenticated requests. Without this, every one of them is
721 // a row write on what is otherwise a read path.
722 let f = fixture();
723 let issued = issue_token(
724 &f.user,
725 "laptop",
726 TokenLifetime::default(),
727 at(1_000),
728 &f.tokens,
729 )
730 .await
731 .expect("issue");
732
733 for second in [2_000, 2_001, 2_030, 2_059] {
734 authenticate_token(issued.secret.reveal(), at(second), &f.tokens)
735 .await
736 .expect("authenticate");
737 }
738
739 assert_eq!(
740 stored(&issued.secret, &f.tokens).await.last_used_at,
741 Some(at(2_000)),
742 "the whole minute should have recorded one use"
743 );
744
745 authenticate_token(issued.secret.reveal(), at(2_060), &f.tokens)
746 .await
747 .expect("authenticate");
748
749 assert_eq!(
750 stored(&issued.secret, &f.tokens).await.last_used_at,
751 Some(at(2_060)),
752 "the next minute moves it"
753 );
754 }
755
756 #[tokio::test]
757 async fn an_expired_token_does_not_record_a_use() {
758 let f = fixture();
759 let issued = issue_token(&f.user, "old", TokenLifetime::Days30, at(1_000), &f.tokens)
760 .await
761 .expect("issue");
762
763 authenticate_token(issued.secret.reveal(), at(1_000 + 40 * 86_400), &f.tokens)
764 .await
765 .expect("authenticate");
766
767 assert_eq!(stored(&issued.secret, &f.tokens).await.last_used_at, None);
768 }
769}