steid

@jamesgill /

Rust27.7 KBCode·Blame·History·Raw
1use rand::Rng;
2
3use crate::domain::{
4 Actor, DomainError, Email, Membership, MembershipId, OrgId, OrgName, Organization, Password,
5 Role, SetupToken, User, UserId,
6 repository::{InstanceSettingsRepository, MembershipRepository, OrgRepository, UserRepository},
7};
8
9use super::{
10 error::Result,
11 org::{NewOrganisation, create_organization, set_home},
12 port::PasswordHasher,
13};
14
15/// The owner account a visitor is asking to create.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct OwnerSpec {
18 pub handle: String,
19 pub email: String,
20 pub password: String,
21}
22
23/// Whether an installation has an owner yet.
24///
25/// Drives whether `/setup` is served and whether other routes redirect to it.
26pub async fn is_claimed(users: &impl UserRepository) -> Result<bool> {
27 Ok(users.any_exist().await?)
28}
29
30/// The handle of the sole user, when this instance has exactly one.
31///
32/// What makes a personal instance's front door work: `jpgill.dev` should be the
33/// owner's profile, not a sign-in prompt, and the root needs to know whose profile that
34/// is without anyone being signed in.
35///
36/// `None` for an unclaimed instance and — deliberately — for one with more than one
37/// user, because "the owner" stops being well defined the moment registration exists.
38/// The root then falls back to a generic landing rather than picking someone.
39pub async fn sole_owner_handle(
40 users: &impl UserRepository,
41 orgs: &impl OrgRepository,
42) -> Result<Option<OrgName>> {
43 let Some(user) = users.sole_user().await? else {
44 return Ok(None);
45 };
46
47 Ok(orgs
48 .find_by_id(&user.personal_org_id)
49 .await?
50 .map(|org| org.name))
51}
52
53/// Creates the owner of an unclaimed installation and returns them as an actor.
54///
55/// Gated on the one-time setup token printed at boot — see `plans/decisions/0002`.
56/// Both the token check and the unclaimed check happen before any write.
57///
58/// The password goes through [`Password::new`], which is the same rule the reset and
59/// change flows apply: a claim with fewer than twelve characters is refused.
60pub async fn claim_instance(
61 presented_token: &str,
62 setup_token: &SetupToken,
63 spec: &OwnerSpec,
64 users: &impl UserRepository,
65 orgs: &impl OrgRepository,
66 memberships: &impl MembershipRepository,
67 hasher: &impl PasswordHasher,
68) -> Result<Actor> {
69 if !setup_token.matches(presented_token) {
70 return Err(DomainError::InvalidCredentials.into());
71 }
72
73 // Checked after the token, so a wrong token cannot be used to probe whether an
74 // instance has been claimed.
75 if is_claimed(users).await? {
76 return Err(DomainError::AlreadyExists { entity: "owner" }.into());
77 }
78
79 create_owner(spec, users, orgs, memberships, hasher).await
80}
81
82/// The owner an operator asked for in the environment, before it has been validated.
83///
84/// Plain strings because they arrive from configuration: the rules — the email's shape,
85/// the handle's, and the reserved list — belong to [`seed_owner`], which is where the
86/// refusal that stops the process is decided.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct OwnerSeed {
89 pub handle: String,
90 pub email: String,
91 /// The organisation this instance is for, when the operator named one.
92 ///
93 /// `None` leaves the instance without a home, so the root falls back to the seeded
94 /// owner's own page — the same place the setup wizard's "Skip for now" leaves it.
95 /// `Some` is what makes an unattended install come up as *a company's* Steid rather
96 /// than one person's, and it is why the wizard's second screen can be skipped
97 /// entirely on a provisioned machine: home is already set, so the screen has nothing
98 /// to ask.
99 pub organisation: Option<OrganisationSeed>,
100}
101
102/// The organisation an operator asked for in the environment.
103///
104/// Plain strings for the same reason the owner's are: the handle's rules, the reserved
105/// list among them, belong to the use case that refuses.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct OrganisationSeed {
108 pub handle: String,
109 pub display_name: Option<String>,
110}
111
112/// Creates the owner of an unclaimed installation from configuration, at boot.
113///
114/// The headless half of [`claim_instance`]: no token, because there is no person to
115/// read one, and no password, because there is nobody to choose one. It exists so a
116/// scripted, unattended install comes up **already owned** rather than sitting
117/// unclaimed on the internet with a setup page — see the control plane's ADR 0008,
118/// which is the operator this was written for, though nothing here knows about it.
119///
120/// **The seeded owner has no usable password.** The hash stored is a real Argon2 hash
121/// of 32 random bytes generated here and dropped before this returns, so
122/// [`login`](super::login::login) verifies it through exactly the normal path and
123/// answers `Ok(false)` in the same time as any wrong password. No sentinel value, no
124/// second code path, nothing for a future change to forget: the way in is
125/// `steid reset-password <handle>`, or Milestone 7's identity when it lands.
126///
127/// Refuses a claimed instance, so the variables are inert once an owner exists.
128pub async fn seed_owner(
129 seed: &OwnerSeed,
130 users: &impl UserRepository,
131 orgs: &impl OrgRepository,
132 memberships: &impl MembershipRepository,
133 settings: &impl InstanceSettingsRepository,
134 hasher: &impl PasswordHasher,
135) -> Result<Actor> {
136 if is_claimed(users).await? {
137 return Err(DomainError::AlreadyExists { entity: "owner" }.into());
138 }
139
140 let spec = OwnerSpec {
141 handle: seed.handle.clone(),
142 email: seed.email.clone(),
143 password: unusable_password(),
144 };
145
146 let actor = create_owner(&spec, users, orgs, memberships, hasher).await?;
147
148 // After the owner, because the organisation's owner membership needs a user to
149 // point at. A refusal here — a reserved or duplicate handle — propagates, and
150 // `main` exits 4 on it: an operator who named an organisation and did not get one
151 // must learn at boot rather than find the root landing somewhere they did not mean.
152 if let Some(organisation) = &seed.organisation {
153 let org = create_organization(
154 &actor,
155 &NewOrganisation {
156 handle: organisation.handle.clone(),
157 display_name: organisation.display_name.clone(),
158 },
159 orgs,
160 memberships,
161 )
162 .await?;
163
164 set_home(&actor, &org.id, orgs, memberships, users, settings).await?;
165 }
166
167 Ok(actor)
168}
169
170/// A password nobody holds: 32 random bytes, hex, generated and then dropped.
171///
172/// Hex rather than raw bytes so it is a `String` that satisfies [`Password::new`]'s
173/// length rule without any special case — the seeded owner goes through the same
174/// validation and the same hasher as one who chose their own.
175fn unusable_password() -> String {
176 let mut bytes = [0u8; 32];
177 rand::rng().fill_bytes(&mut bytes);
178
179 bytes.iter().map(|byte| format!("{byte:02x}")).collect()
180}
181
182/// The three saves that make an owner, shared by the claim form and the boot seed.
183///
184/// Factored out rather than copied: the order below is a foreign-key constraint that
185/// attempt #2 had to fix once already, and a second copy is a second place to get it
186/// wrong. The caller decides *whether* it may run — a token, a claimed check — and this
187/// decides what an owner is.
188async fn create_owner(
189 spec: &OwnerSpec,
190 users: &impl UserRepository,
191 orgs: &impl OrgRepository,
192 memberships: &impl MembershipRepository,
193 hasher: &impl PasswordHasher,
194) -> Result<Actor> {
195 let email = Email::new(&spec.email)?;
196 let org = Organization::new(OrgId::generate(), &spec.handle, None)?;
197 // The same rule a reset and a change enforce — see `Password`. Validated before
198 // hashing, so a refused password costs nothing.
199 let password = Password::new(&spec.password)?;
200 let password_hash = hasher.hash(password.expose())?;
201
202 let user = User::new(UserId::generate(), email, password_hash, org.id.clone());
203 let membership = Membership::new(
204 MembershipId::generate(),
205 org.id.clone(),
206 user.id.clone(),
207 Role::Owner,
208 );
209
210 // Order matters: the user references the org and the membership references both,
211 // so anything else trips the foreign keys. Attempt #2 had to fix exactly this.
212 orgs.save(&org).await?;
213 users.save(&user).await?;
214 memberships.save(&membership).await?;
215
216 Ok(Actor::User(user.id))
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222 use crate::{
223 application::error::Error,
224 domain::{OrgName, repository::InstanceSettingsRepository},
225 infrastructure::{
226 password::{Argon2Hasher, StubHasher},
227 repository::{
228 InMemoryInstanceSettingsRepo, InMemoryMembershipRepo, InMemoryOrgRepo,
229 InMemoryUserRepo,
230 },
231 },
232 };
233
234 struct Fixture {
235 token: SetupToken,
236 users: InMemoryUserRepo,
237 orgs: InMemoryOrgRepo,
238 memberships: InMemoryMembershipRepo,
239 settings: InMemoryInstanceSettingsRepo,
240 hasher: StubHasher,
241 }
242
243 impl Fixture {
244 fn new() -> Self {
245 Self {
246 token: SetupToken::generate(),
247 users: InMemoryUserRepo::new(),
248 orgs: InMemoryOrgRepo::new(),
249 memberships: InMemoryMembershipRepo::new(),
250 settings: InMemoryInstanceSettingsRepo::new(),
251 hasher: StubHasher::new(),
252 }
253 }
254
255 async fn claim_with(&self, presented: &str, spec: &OwnerSpec) -> Result<Actor> {
256 claim_instance(
257 presented,
258 &self.token,
259 spec,
260 &self.users,
261 &self.orgs,
262 &self.memberships,
263 &self.hasher,
264 )
265 .await
266 }
267
268 async fn claim(&self, spec: &OwnerSpec) -> Result<Actor> {
269 self.claim_with(self.token.reveal(), spec).await
270 }
271 }
272
273 /// The configured owner, as the two environment variables would give it.
274 fn seed() -> OwnerSeed {
275 OwnerSeed {
276 handle: "james".to_owned(),
277 email: "dev@example.com".to_owned(),
278 organisation: None,
279 }
280 }
281
282 fn spec() -> OwnerSpec {
283 OwnerSpec {
284 handle: "james".to_owned(),
285 email: "dev@example.com".to_owned(),
286 password: "correcthorsebattery".to_owned(),
287 }
288 }
289
290 #[tokio::test]
291 async fn claiming_creates_org_user_and_owner_membership() {
292 let fixture = Fixture::new();
293
294 let actor = fixture.claim(&spec()).await.expect("claim");
295
296 let org = fixture
297 .orgs
298 .find_by_name(&OrgName::new("james").unwrap())
299 .await
300 .expect("lookup")
301 .expect("org should exist");
302 let user = fixture
303 .users
304 .find_by_email(&Email::new("dev@example.com").unwrap())
305 .await
306 .expect("lookup")
307 .expect("user should exist");
308 let membership = fixture
309 .memberships
310 .find(&org.id, &user.id)
311 .await
312 .expect("lookup")
313 .expect("membership should exist");
314
315 assert_eq!(actor, Actor::User(user.id.clone()));
316 assert_eq!(user.personal_org_id, org.id);
317 assert_eq!(membership.role, Role::Owner);
318 assert!(membership.can_write());
319 }
320
321 #[tokio::test]
322 async fn the_owner_is_returned_signed_in() {
323 let fixture = Fixture::new();
324
325 let actor = fixture.claim(&spec()).await.expect("claim");
326
327 assert!(
328 actor.is_authenticated(),
329 "claiming should hand back a session-able actor, not require a second login"
330 );
331 }
332
333 #[tokio::test]
334 async fn stores_a_hash_never_the_plaintext() {
335 let fixture = Fixture::new();
336 fixture.claim(&spec()).await.expect("claim");
337
338 let user = fixture
339 .users
340 .find_by_email(&Email::new("dev@example.com").unwrap())
341 .await
342 .expect("lookup")
343 .expect("user should exist");
344
345 assert_ne!(user.password_hash.as_str(), "correcthorsebattery");
346 assert!(
347 fixture
348 .hasher
349 .verify("correcthorsebattery", &user.password_hash)
350 .expect("verify")
351 );
352 }
353
354 #[tokio::test]
355 async fn a_claim_with_a_short_password_is_refused_and_writes_nothing() {
356 // The behaviour change: setup used to accept anything non-empty, which meant a
357 // password that could be set here and never changed to. Same rule both ways now.
358 let fixture = Fixture::new();
359
360 let error = fixture
361 .claim(&OwnerSpec {
362 password: "hunter2".to_owned(),
363 ..spec()
364 })
365 .await
366 .expect_err("should refuse");
367
368 assert!(matches!(
369 error,
370 Error::Domain(DomainError::Validation { ref field, .. }) if field == "password"
371 ));
372 assert!(
373 !fixture.users.any_exist().await.expect("any_exist"),
374 "a refused password leaves an unclaimed instance"
375 );
376 assert!(
377 fixture
378 .orgs
379 .find_by_name(&OrgName::new("james").unwrap())
380 .await
381 .expect("lookup")
382 .is_none(),
383 "and no organisation behind it"
384 );
385 }
386
387 #[tokio::test]
388 async fn a_wrong_token_is_rejected_and_writes_nothing() {
389 let fixture = Fixture::new();
390
391 let error = fixture
392 .claim_with(SetupToken::generate().reveal(), &spec())
393 .await
394 .expect_err("should reject");
395
396 assert!(matches!(
397 error,
398 Error::Domain(DomainError::InvalidCredentials)
399 ));
400 assert!(!fixture.users.any_exist().await.expect("any_exist"));
401 }
402
403 #[tokio::test]
404 async fn an_empty_token_is_rejected() {
405 let fixture = Fixture::new();
406
407 let error = fixture
408 .claim_with("", &spec())
409 .await
410 .expect_err("should reject");
411
412 assert!(matches!(
413 error,
414 Error::Domain(DomainError::InvalidCredentials)
415 ));
416 }
417
418 #[tokio::test]
419 async fn a_claimed_instance_cannot_be_claimed_again() {
420 let fixture = Fixture::new();
421 fixture.claim(&spec()).await.expect("first claim");
422
423 let intruder = OwnerSpec {
424 handle: "intruder".to_owned(),
425 email: "intruder@example.com".to_owned(),
426 password: "letmeinplease".to_owned(),
427 };
428 let error = fixture.claim(&intruder).await.expect_err("should reject");
429
430 assert!(matches!(
431 error,
432 Error::Domain(DomainError::AlreadyExists { entity: "owner" })
433 ));
434 }
435
436 #[tokio::test]
437 async fn a_wrong_token_cannot_probe_whether_the_instance_is_claimed() {
438 let unclaimed = Fixture::new();
439 let claimed = Fixture::new();
440 claimed.claim(&spec()).await.expect("claim");
441
442 let wrong = SetupToken::generate();
443 let from_unclaimed = unclaimed
444 .claim_with(wrong.reveal(), &spec())
445 .await
446 .expect_err("should reject");
447 let from_claimed = claimed
448 .claim_with(wrong.reveal(), &spec())
449 .await
450 .expect_err("should reject");
451
452 // Both must be InvalidCredentials. If the claimed instance answered
453 // AlreadyExists, a wrong token would reveal the installation's state.
454 assert!(matches!(
455 from_unclaimed,
456 Error::Domain(DomainError::InvalidCredentials)
457 ));
458 assert!(matches!(
459 from_claimed,
460 Error::Domain(DomainError::InvalidCredentials)
461 ));
462 }
463
464 #[tokio::test]
465 async fn rejects_an_invalid_handle_without_writing_anything() {
466 let fixture = Fixture::new();
467 let bad = OwnerSpec {
468 handle: "not a handle".to_owned(),
469 ..spec()
470 };
471
472 let error = fixture.claim(&bad).await.expect_err("should reject");
473
474 assert!(matches!(
475 error,
476 Error::Domain(DomainError::Validation { .. })
477 ));
478 assert!(
479 !fixture.users.any_exist().await.expect("any_exist"),
480 "nothing should be written when validation fails"
481 );
482 }
483
484 #[tokio::test]
485 async fn rejects_an_invalid_email_without_writing_anything() {
486 let fixture = Fixture::new();
487 let bad = OwnerSpec {
488 email: "not-an-email".to_owned(),
489 ..spec()
490 };
491
492 let error = fixture.claim(&bad).await.expect_err("should reject");
493
494 assert!(matches!(
495 error,
496 Error::Domain(DomainError::Validation { .. })
497 ));
498 assert!(!fixture.users.any_exist().await.expect("any_exist"));
499 }
500
501 #[tokio::test]
502 async fn seeding_creates_the_owner_from_configuration_alone() {
503 let fixture = Fixture::new();
504
505 let actor = seed_owner(
506 &seed(),
507 &fixture.users,
508 &fixture.orgs,
509 &fixture.memberships,
510 &fixture.settings,
511 &fixture.hasher,
512 )
513 .await
514 .expect("seed");
515
516 let org = fixture
517 .orgs
518 .find_by_name(&OrgName::new("james").unwrap())
519 .await
520 .expect("lookup")
521 .expect("org should exist");
522 let user = fixture
523 .users
524 .find_by_email(&Email::new("dev@example.com").unwrap())
525 .await
526 .expect("lookup")
527 .expect("user should exist");
528 let membership = fixture
529 .memberships
530 .find(&org.id, &user.id)
531 .await
532 .expect("lookup")
533 .expect("membership should exist");
534
535 assert_eq!(actor, Actor::User(user.id.clone()));
536 assert_eq!(user.personal_org_id, org.id);
537 assert_eq!(membership.role, Role::Owner);
538 assert!(is_claimed(&fixture.users).await.expect("is_claimed"));
539 }
540
541 #[tokio::test]
542 async fn a_seeded_organisation_owns_the_instance() {
543 // What makes an unattended install come up as a company's Steid: the
544 // organisation exists, the seeded owner owns it, and the root lands on it — so
545 // the wizard's second screen has nothing left to ask.
546 let fixture = Fixture::new();
547 let seed = OwnerSeed {
548 organisation: Some(OrganisationSeed {
549 handle: "acme".to_owned(),
550 display_name: Some("Acme Inc".to_owned()),
551 }),
552 ..seed()
553 };
554
555 let actor = seed_owner(
556 &seed,
557 &fixture.users,
558 &fixture.orgs,
559 &fixture.memberships,
560 &fixture.settings,
561 &fixture.hasher,
562 )
563 .await
564 .expect("seed");
565
566 let acme = fixture
567 .orgs
568 .find_by_name(&OrgName::new("acme").unwrap())
569 .await
570 .expect("lookup")
571 .expect("the organisation should exist");
572
573 assert_eq!(acme.label(), "Acme Inc");
574 assert_eq!(
575 fixture
576 .memberships
577 .find(&acme.id, actor.user_id().expect("a user"))
578 .await
579 .expect("lookup")
580 .map(|membership| membership.role),
581 Some(Role::Owner)
582 );
583 assert_eq!(
584 crate::application::home_handle(&fixture.settings, &fixture.users, &fixture.orgs)
585 .await
586 .expect("home")
587 .map(|name| name.to_string()),
588 Some("acme".to_owned())
589 );
590 }
591
592 #[tokio::test]
593 async fn a_seed_with_no_organisation_leaves_the_owner_as_the_front_door() {
594 let fixture = Fixture::new();
595
596 seed_owner(
597 &seed(),
598 &fixture.users,
599 &fixture.orgs,
600 &fixture.memberships,
601 &fixture.settings,
602 &fixture.hasher,
603 )
604 .await
605 .expect("seed");
606
607 assert!(!fixture.settings.load().await.expect("load").has_home());
608 assert_eq!(
609 crate::application::home_handle(&fixture.settings, &fixture.users, &fixture.orgs)
610 .await
611 .expect("home")
612 .map(|name| name.to_string()),
613 Some("james".to_owned())
614 );
615 }
616
617 #[tokio::test]
618 async fn a_reserved_organisation_handle_stops_the_boot() {
619 // The operator learns at boot rather than finding the root landing somewhere
620 // they did not mean. The owner is created first and stays — `main` exits 4, so
621 // nothing serves either way.
622 let fixture = Fixture::new();
623 let seed = OwnerSeed {
624 organisation: Some(OrganisationSeed {
625 handle: "admin".to_owned(),
626 display_name: None,
627 }),
628 ..seed()
629 };
630
631 let error = seed_owner(
632 &seed,
633 &fixture.users,
634 &fixture.orgs,
635 &fixture.memberships,
636 &fixture.settings,
637 &fixture.hasher,
638 )
639 .await
640 .expect_err("should refuse");
641
642 assert!(matches!(
643 error,
644 Error::Domain(DomainError::Validation { .. })
645 ));
646 assert!(!fixture.settings.load().await.expect("load").has_home());
647 }
648
649 #[tokio::test]
650 async fn an_organisation_may_not_take_the_owners_own_handle() {
651 let fixture = Fixture::new();
652 let seed = OwnerSeed {
653 organisation: Some(OrganisationSeed {
654 handle: "james".to_owned(),
655 display_name: None,
656 }),
657 ..seed()
658 };
659
660 let error = seed_owner(
661 &seed,
662 &fixture.users,
663 &fixture.orgs,
664 &fixture.memberships,
665 &fixture.settings,
666 &fixture.hasher,
667 )
668 .await
669 .expect_err("should refuse");
670
671 assert!(matches!(
672 error,
673 Error::Domain(DomainError::AlreadyExists { .. })
674 ));
675 }
676
677 #[tokio::test]
678 async fn a_claimed_instance_is_never_seeded_again() {
679 // What makes the two variables inert once an owner exists: a restart with them
680 // still set must not try to create a second owner, or fail the boot.
681 let fixture = Fixture::new();
682 fixture.claim(&spec()).await.expect("claim");
683
684 let error = seed_owner(
685 &seed(),
686 &fixture.users,
687 &fixture.orgs,
688 &fixture.memberships,
689 &fixture.settings,
690 &fixture.hasher,
691 )
692 .await
693 .expect_err("should refuse");
694
695 assert!(matches!(
696 error,
697 Error::Domain(DomainError::AlreadyExists { entity: "owner" })
698 ));
699 }
700
701 #[tokio::test]
702 async fn seeding_twice_is_refused() {
703 let fixture = Fixture::new();
704 seed_owner(
705 &seed(),
706 &fixture.users,
707 &fixture.orgs,
708 &fixture.memberships,
709 &fixture.settings,
710 &fixture.hasher,
711 )
712 .await
713 .expect("first seed");
714
715 let error = seed_owner(
716 &seed(),
717 &fixture.users,
718 &fixture.orgs,
719 &fixture.memberships,
720 &fixture.settings,
721 &fixture.hasher,
722 )
723 .await
724 .expect_err("should refuse");
725
726 assert!(matches!(
727 error,
728 Error::Domain(DomainError::AlreadyExists { entity: "owner" })
729 ));
730 }
731
732 #[tokio::test]
733 async fn a_reserved_handle_is_refused_and_writes_nothing() {
734 // `admin` is on the reserved list, and the whole point of refusing here is that
735 // the operator learns at boot rather than ending up with an instance nobody can
736 // own. The control plane's ADR 0008 names this as one of the two lockouts.
737 let fixture = Fixture::new();
738 let reserved = OwnerSeed {
739 handle: "admin".to_owned(),
740 ..seed()
741 };
742
743 let error = seed_owner(
744 &reserved,
745 &fixture.users,
746 &fixture.orgs,
747 &fixture.memberships,
748 &fixture.settings,
749 &fixture.hasher,
750 )
751 .await
752 .expect_err("should refuse");
753
754 assert!(matches!(
755 error,
756 Error::Domain(DomainError::Validation { .. })
757 ));
758 assert!(!fixture.users.any_exist().await.expect("any_exist"));
759 }
760
761 #[tokio::test]
762 async fn a_bad_email_is_refused_and_writes_nothing() {
763 let fixture = Fixture::new();
764 let bad = OwnerSeed {
765 email: "not-an-email".to_owned(),
766 ..seed()
767 };
768
769 let error = seed_owner(
770 &bad,
771 &fixture.users,
772 &fixture.orgs,
773 &fixture.memberships,
774 &fixture.settings,
775 &fixture.hasher,
776 )
777 .await
778 .expect_err("should refuse");
779
780 assert!(matches!(
781 error,
782 Error::Domain(DomainError::Validation { .. })
783 ));
784 assert!(!fixture.users.any_exist().await.expect("any_exist"));
785 }
786
787 #[tokio::test]
788 async fn the_seeded_owner_cannot_sign_in_with_any_password() {
789 // The stub hasher stores `stub:<plaintext>`, so this is also the one place that
790 // would notice a seeded password becoming predictable: every guess below would
791 // have to match the 32 random bytes seeding generated and dropped.
792 let fixture = Fixture::new();
793 seed_owner(
794 &seed(),
795 &fixture.users,
796 &fixture.orgs,
797 &fixture.memberships,
798 &fixture.settings,
799 &fixture.hasher,
800 )
801 .await
802 .expect("seed");
803
804 for guess in ["", "password", "correcthorsebattery", "james"] {
805 let error = crate::application::login::login(
806 "dev@example.com",
807 guess,
808 &fixture.users,
809 &fixture.hasher,
810 )
811 .await
812 .expect_err("should reject");
813
814 assert!(
815 matches!(error, Error::Domain(DomainError::InvalidCredentials)),
816 "{guess:?} produced {error:?}"
817 );
818 }
819 }
820
821 #[tokio::test]
822 async fn the_discarded_password_verifies_as_false_under_the_real_hasher() {
823 // Argon2 rather than the stub, because the claim being made is about the stored
824 // hash: it is a real one, so `verify` answers `Ok(false)` — a wrong password, not
825 // an unreadable hash and not an error. That is what keeps `login` on its normal
826 // path, with the timing of any other refusal.
827 let fixture = Fixture::new();
828 let hasher = Argon2Hasher::new();
829
830 seed_owner(
831 &seed(),
832 &fixture.users,
833 &fixture.orgs,
834 &fixture.memberships,
835 &fixture.settings,
836 &hasher,
837 )
838 .await
839 .expect("seed");
840
841 let user = fixture
842 .users
843 .find_by_email(&Email::new("dev@example.com").unwrap())
844 .await
845 .expect("lookup")
846 .expect("user should exist");
847
848 assert!(
849 user.password_hash.as_str().starts_with("$argon2id$"),
850 "the seeded hash should be a real Argon2 hash"
851 );
852 assert!(
853 !hasher
854 .verify("correcthorsebattery", &user.password_hash)
855 .expect("verify answers rather than erroring"),
856 "a guess must be a plain no"
857 );
858 }
859
860 #[tokio::test]
861 async fn is_claimed_reports_the_installation_state() {
862 let fixture = Fixture::new();
863 assert!(!is_claimed(&fixture.users).await.expect("is_claimed"));
864
865 fixture.claim(&spec()).await.expect("claim");
866
867 assert!(is_claimed(&fixture.users).await.expect("is_claimed"));
868 }
869}