steid

@jamesgill /

Rust33.4 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.
128///
129/// **The whole seed is checked before the first write** ([`check_seed`]). The owner has
130/// to be saved before the organisation, whose owner membership points at it, so a seed
131/// checked piece by piece could commit the owner and then refuse the organisation. The
132/// next boot would find an owner, call the instance claimed, and serve it with no
133/// organisation and no home (launch 2.14). Checked whole, a refusal writes nothing, and
134/// every boot refuses the same way until the configuration is fixed.
135pub async fn seed_owner(
136 seed: &OwnerSeed,
137 users: &impl UserRepository,
138 orgs: &impl OrgRepository,
139 memberships: &impl MembershipRepository,
140 settings: &impl InstanceSettingsRepository,
141 hasher: &impl PasswordHasher,
142) -> Result<Actor> {
143 if is_claimed(users).await? {
144 return Err(DomainError::AlreadyExists { entity: "owner" }.into());
145 }
146
147 check_seed(seed, orgs).await?;
148
149 let spec = OwnerSpec {
150 handle: seed.handle.clone(),
151 email: seed.email.clone(),
152 password: unusable_password(),
153 };
154
155 let actor = create_owner(&spec, users, orgs, memberships, hasher).await?;
156
157 // After the owner, because the organisation's owner membership needs a user to
158 // point at. Everything that could refuse it — the handle's shape, the reserved
159 // list, a handle already held, the owner's own — was refused by `check_seed`
160 // before the owner was written. What can still fail here is storage, between
161 // writes that share no transaction (launch 2.20).
162 if let Some(organisation) = &seed.organisation {
163 let org = create_organization(
164 &actor,
165 &NewOrganisation {
166 handle: organisation.handle.clone(),
167 display_name: organisation.display_name.clone(),
168 },
169 orgs,
170 memberships,
171 )
172 .await?;
173
174 set_home(&actor, &org.id, orgs, memberships, users, settings).await?;
175 }
176
177 Ok(actor)
178}
179
180/// Everything [`seed_owner`] could refuse, checked before it writes anything.
181///
182/// The same validators the writes run — [`Email::new`] and [`Organization::new`] — so
183/// this cannot pass a seed that `create_owner` or `create_organization` would then
184/// refuse. Then the two refusals that need the database: a handle somebody already
185/// holds, and an organisation asking for the owner's own handle, which is the same
186/// thing one write later.
187///
188/// The password is not checked: [`unusable_password`] is 64 hex characters, which
189/// [`Password::new`] always accepts.
190async fn check_seed(seed: &OwnerSeed, orgs: &impl OrgRepository) -> Result<()> {
191 Email::new(&seed.email)?;
192 let owner = Organization::new(OrgId::generate(), &seed.handle, None)?;
193 let organisation = match &seed.organisation {
194 Some(organisation) => Some(Organization::new(
195 OrgId::generate(),
196 &organisation.handle,
197 organisation.display_name.clone(),
198 )?),
199 None => None,
200 };
201
202 let taken = || DomainError::AlreadyExists {
203 entity: "organisation",
204 };
205
206 if organisation
207 .as_ref()
208 .is_some_and(|organisation| organisation.name == owner.name)
209 {
210 return Err(taken().into());
211 }
212
213 for org in std::iter::once(&owner).chain(organisation.as_ref()) {
214 if orgs.find_by_name(&org.name).await?.is_some() {
215 return Err(taken().into());
216 }
217 }
218
219 Ok(())
220}
221
222/// A password nobody holds: 32 random bytes, hex, generated and then dropped.
223///
224/// Hex rather than raw bytes so it is a `String` that satisfies [`Password::new`]'s
225/// length rule without any special case — the seeded owner goes through the same
226/// validation and the same hasher as one who chose their own.
227fn unusable_password() -> String {
228 let mut bytes = [0u8; 32];
229 rand::rng().fill_bytes(&mut bytes);
230
231 bytes.iter().map(|byte| format!("{byte:02x}")).collect()
232}
233
234/// The three saves that make an owner, shared by the claim form and the boot seed.
235///
236/// Factored out rather than copied: the order below is a foreign-key constraint that
237/// attempt #2 had to fix once already, and a second copy is a second place to get it
238/// wrong. The caller decides *whether* it may run — a token, a claimed check — and this
239/// decides what an owner is.
240async fn create_owner(
241 spec: &OwnerSpec,
242 users: &impl UserRepository,
243 orgs: &impl OrgRepository,
244 memberships: &impl MembershipRepository,
245 hasher: &impl PasswordHasher,
246) -> Result<Actor> {
247 let email = Email::new(&spec.email)?;
248 let org = Organization::new(OrgId::generate(), &spec.handle, None)?;
249 // The same rule a reset and a change enforce — see `Password`. Validated before
250 // hashing, so a refused password costs nothing.
251 let password = Password::new(&spec.password)?;
252 let password_hash = hasher.hash(password.expose())?;
253
254 let user = User::new(UserId::generate(), email, password_hash, org.id.clone());
255 let membership = Membership::new(
256 MembershipId::generate(),
257 org.id.clone(),
258 user.id.clone(),
259 Role::Owner,
260 );
261
262 // Order matters: the user references the org and the membership references both,
263 // so anything else trips the foreign keys. Attempt #2 had to fix exactly this.
264 orgs.save(&org).await?;
265 users.save(&user).await?;
266 memberships.save(&membership).await?;
267
268 Ok(Actor::User(user.id))
269}
270
271#[cfg(test)]
272mod tests {
273 use super::*;
274 use crate::{
275 application::error::Error,
276 domain::{OrgName, repository::InstanceSettingsRepository},
277 infrastructure::{
278 password::{Argon2Hasher, StubHasher},
279 repository::{
280 InMemoryInstanceSettingsRepo, InMemoryMembershipRepo, InMemoryOrgRepo,
281 InMemoryUserRepo,
282 },
283 },
284 };
285
286 struct Fixture {
287 token: SetupToken,
288 users: InMemoryUserRepo,
289 orgs: InMemoryOrgRepo,
290 memberships: InMemoryMembershipRepo,
291 settings: InMemoryInstanceSettingsRepo,
292 hasher: StubHasher,
293 }
294
295 impl Fixture {
296 fn new() -> Self {
297 Self {
298 token: SetupToken::generate(),
299 users: InMemoryUserRepo::new(),
300 orgs: InMemoryOrgRepo::new(),
301 memberships: InMemoryMembershipRepo::new(),
302 settings: InMemoryInstanceSettingsRepo::new(),
303 hasher: StubHasher::new(),
304 }
305 }
306
307 async fn claim_with(&self, presented: &str, spec: &OwnerSpec) -> Result<Actor> {
308 claim_instance(
309 presented,
310 &self.token,
311 spec,
312 &self.users,
313 &self.orgs,
314 &self.memberships,
315 &self.hasher,
316 )
317 .await
318 }
319
320 async fn claim(&self, spec: &OwnerSpec) -> Result<Actor> {
321 self.claim_with(self.token.reveal(), spec).await
322 }
323
324 async fn seed(&self, seed: &OwnerSeed) -> Result<Actor> {
325 seed_owner(
326 seed,
327 &self.users,
328 &self.orgs,
329 &self.memberships,
330 &self.settings,
331 &self.hasher,
332 )
333 .await
334 }
335
336 /// Asserts a refused seed left the instance as it found it: no user, no new
337 /// organisation, no home — so the next boot is still unclaimed and refuses
338 /// again, rather than finding an owner and serving (launch 2.14).
339 async fn assert_untouched(&self, orgs_before: u64) {
340 assert!(
341 !self.users.any_exist().await.expect("any_exist"),
342 "a refused seed wrote a user"
343 );
344 assert_eq!(
345 self.orgs.count().await.expect("count"),
346 orgs_before,
347 "a refused seed wrote an organisation"
348 );
349 assert!(
350 !self.settings.load().await.expect("load").has_home(),
351 "a refused seed set a home"
352 );
353 }
354 }
355
356 /// The configured owner with an organisation of this handle.
357 fn seed_with_org(handle: &str) -> OwnerSeed {
358 OwnerSeed {
359 organisation: Some(OrganisationSeed {
360 handle: handle.to_owned(),
361 display_name: None,
362 }),
363 ..seed()
364 }
365 }
366
367 /// The configured owner, as the two environment variables would give it.
368 fn seed() -> OwnerSeed {
369 OwnerSeed {
370 handle: "james".to_owned(),
371 email: "dev@example.com".to_owned(),
372 organisation: None,
373 }
374 }
375
376 fn spec() -> OwnerSpec {
377 OwnerSpec {
378 handle: "james".to_owned(),
379 email: "dev@example.com".to_owned(),
380 password: "correcthorsebattery".to_owned(),
381 }
382 }
383
384 #[tokio::test]
385 async fn claiming_creates_org_user_and_owner_membership() {
386 let fixture = Fixture::new();
387
388 let actor = fixture.claim(&spec()).await.expect("claim");
389
390 let org = fixture
391 .orgs
392 .find_by_name(&OrgName::new("james").unwrap())
393 .await
394 .expect("lookup")
395 .expect("org should exist");
396 let user = fixture
397 .users
398 .find_by_email(&Email::new("dev@example.com").unwrap())
399 .await
400 .expect("lookup")
401 .expect("user should exist");
402 let membership = fixture
403 .memberships
404 .find(&org.id, &user.id)
405 .await
406 .expect("lookup")
407 .expect("membership should exist");
408
409 assert_eq!(actor, Actor::User(user.id.clone()));
410 assert_eq!(user.personal_org_id, org.id);
411 assert_eq!(membership.role, Role::Owner);
412 assert!(membership.can_write());
413 }
414
415 #[tokio::test]
416 async fn the_owner_is_returned_signed_in() {
417 let fixture = Fixture::new();
418
419 let actor = fixture.claim(&spec()).await.expect("claim");
420
421 assert!(
422 actor.is_authenticated(),
423 "claiming should hand back a session-able actor, not require a second login"
424 );
425 }
426
427 #[tokio::test]
428 async fn stores_a_hash_never_the_plaintext() {
429 let fixture = Fixture::new();
430 fixture.claim(&spec()).await.expect("claim");
431
432 let user = fixture
433 .users
434 .find_by_email(&Email::new("dev@example.com").unwrap())
435 .await
436 .expect("lookup")
437 .expect("user should exist");
438
439 assert_ne!(user.password_hash.as_str(), "correcthorsebattery");
440 assert!(
441 fixture
442 .hasher
443 .verify("correcthorsebattery", &user.password_hash)
444 .expect("verify")
445 );
446 }
447
448 #[tokio::test]
449 async fn a_claim_with_a_short_password_is_refused_and_writes_nothing() {
450 // The behaviour change: setup used to accept anything non-empty, which meant a
451 // password that could be set here and never changed to. Same rule both ways now.
452 let fixture = Fixture::new();
453
454 let error = fixture
455 .claim(&OwnerSpec {
456 password: "hunter2".to_owned(),
457 ..spec()
458 })
459 .await
460 .expect_err("should refuse");
461
462 assert!(matches!(
463 error,
464 Error::Domain(DomainError::Validation { ref field, .. }) if field == "password"
465 ));
466 assert!(
467 !fixture.users.any_exist().await.expect("any_exist"),
468 "a refused password leaves an unclaimed instance"
469 );
470 assert!(
471 fixture
472 .orgs
473 .find_by_name(&OrgName::new("james").unwrap())
474 .await
475 .expect("lookup")
476 .is_none(),
477 "and no organisation behind it"
478 );
479 }
480
481 #[tokio::test]
482 async fn a_wrong_token_is_rejected_and_writes_nothing() {
483 let fixture = Fixture::new();
484
485 let error = fixture
486 .claim_with(SetupToken::generate().reveal(), &spec())
487 .await
488 .expect_err("should reject");
489
490 assert!(matches!(
491 error,
492 Error::Domain(DomainError::InvalidCredentials)
493 ));
494 assert!(!fixture.users.any_exist().await.expect("any_exist"));
495 }
496
497 #[tokio::test]
498 async fn an_empty_token_is_rejected() {
499 let fixture = Fixture::new();
500
501 let error = fixture
502 .claim_with("", &spec())
503 .await
504 .expect_err("should reject");
505
506 assert!(matches!(
507 error,
508 Error::Domain(DomainError::InvalidCredentials)
509 ));
510 }
511
512 #[tokio::test]
513 async fn a_claimed_instance_cannot_be_claimed_again() {
514 let fixture = Fixture::new();
515 fixture.claim(&spec()).await.expect("first claim");
516
517 let intruder = OwnerSpec {
518 handle: "intruder".to_owned(),
519 email: "intruder@example.com".to_owned(),
520 password: "letmeinplease".to_owned(),
521 };
522 let error = fixture.claim(&intruder).await.expect_err("should reject");
523
524 assert!(matches!(
525 error,
526 Error::Domain(DomainError::AlreadyExists { entity: "owner" })
527 ));
528 }
529
530 #[tokio::test]
531 async fn a_wrong_token_cannot_probe_whether_the_instance_is_claimed() {
532 let unclaimed = Fixture::new();
533 let claimed = Fixture::new();
534 claimed.claim(&spec()).await.expect("claim");
535
536 let wrong = SetupToken::generate();
537 let from_unclaimed = unclaimed
538 .claim_with(wrong.reveal(), &spec())
539 .await
540 .expect_err("should reject");
541 let from_claimed = claimed
542 .claim_with(wrong.reveal(), &spec())
543 .await
544 .expect_err("should reject");
545
546 // Both must be InvalidCredentials. If the claimed instance answered
547 // AlreadyExists, a wrong token would reveal the installation's state.
548 assert!(matches!(
549 from_unclaimed,
550 Error::Domain(DomainError::InvalidCredentials)
551 ));
552 assert!(matches!(
553 from_claimed,
554 Error::Domain(DomainError::InvalidCredentials)
555 ));
556 }
557
558 #[tokio::test]
559 async fn rejects_an_invalid_handle_without_writing_anything() {
560 let fixture = Fixture::new();
561 let bad = OwnerSpec {
562 handle: "not a handle".to_owned(),
563 ..spec()
564 };
565
566 let error = fixture.claim(&bad).await.expect_err("should reject");
567
568 assert!(matches!(
569 error,
570 Error::Domain(DomainError::Validation { .. })
571 ));
572 assert!(
573 !fixture.users.any_exist().await.expect("any_exist"),
574 "nothing should be written when validation fails"
575 );
576 }
577
578 #[tokio::test]
579 async fn rejects_an_invalid_email_without_writing_anything() {
580 let fixture = Fixture::new();
581 let bad = OwnerSpec {
582 email: "not-an-email".to_owned(),
583 ..spec()
584 };
585
586 let error = fixture.claim(&bad).await.expect_err("should reject");
587
588 assert!(matches!(
589 error,
590 Error::Domain(DomainError::Validation { .. })
591 ));
592 assert!(!fixture.users.any_exist().await.expect("any_exist"));
593 }
594
595 #[tokio::test]
596 async fn seeding_creates_the_owner_from_configuration_alone() {
597 let fixture = Fixture::new();
598
599 let actor = seed_owner(
600 &seed(),
601 &fixture.users,
602 &fixture.orgs,
603 &fixture.memberships,
604 &fixture.settings,
605 &fixture.hasher,
606 )
607 .await
608 .expect("seed");
609
610 let org = fixture
611 .orgs
612 .find_by_name(&OrgName::new("james").unwrap())
613 .await
614 .expect("lookup")
615 .expect("org should exist");
616 let user = fixture
617 .users
618 .find_by_email(&Email::new("dev@example.com").unwrap())
619 .await
620 .expect("lookup")
621 .expect("user should exist");
622 let membership = fixture
623 .memberships
624 .find(&org.id, &user.id)
625 .await
626 .expect("lookup")
627 .expect("membership should exist");
628
629 assert_eq!(actor, Actor::User(user.id.clone()));
630 assert_eq!(user.personal_org_id, org.id);
631 assert_eq!(membership.role, Role::Owner);
632 assert!(is_claimed(&fixture.users).await.expect("is_claimed"));
633 }
634
635 #[tokio::test]
636 async fn a_seeded_organisation_owns_the_instance() {
637 // What makes an unattended install come up as a company's Steid: the
638 // organisation exists, the seeded owner owns it, and the root lands on it — so
639 // the wizard's second screen has nothing left to ask.
640 let fixture = Fixture::new();
641 let seed = OwnerSeed {
642 organisation: Some(OrganisationSeed {
643 handle: "acme".to_owned(),
644 display_name: Some("Acme Inc".to_owned()),
645 }),
646 ..seed()
647 };
648
649 let actor = seed_owner(
650 &seed,
651 &fixture.users,
652 &fixture.orgs,
653 &fixture.memberships,
654 &fixture.settings,
655 &fixture.hasher,
656 )
657 .await
658 .expect("seed");
659
660 let acme = fixture
661 .orgs
662 .find_by_name(&OrgName::new("acme").unwrap())
663 .await
664 .expect("lookup")
665 .expect("the organisation should exist");
666
667 assert_eq!(acme.label(), "Acme Inc");
668 assert_eq!(
669 fixture
670 .memberships
671 .find(&acme.id, actor.user_id().expect("a user"))
672 .await
673 .expect("lookup")
674 .map(|membership| membership.role),
675 Some(Role::Owner)
676 );
677 assert_eq!(
678 crate::application::home_handle(&fixture.settings, &fixture.users, &fixture.orgs)
679 .await
680 .expect("home")
681 .map(|name| name.to_string()),
682 Some("acme".to_owned())
683 );
684 }
685
686 #[tokio::test]
687 async fn a_seed_with_no_organisation_leaves_the_owner_as_the_front_door() {
688 let fixture = Fixture::new();
689
690 seed_owner(
691 &seed(),
692 &fixture.users,
693 &fixture.orgs,
694 &fixture.memberships,
695 &fixture.settings,
696 &fixture.hasher,
697 )
698 .await
699 .expect("seed");
700
701 assert!(!fixture.settings.load().await.expect("load").has_home());
702 assert_eq!(
703 crate::application::home_handle(&fixture.settings, &fixture.users, &fixture.orgs)
704 .await
705 .expect("home")
706 .map(|name| name.to_string()),
707 Some("james".to_owned())
708 );
709 }
710
711 #[tokio::test]
712 async fn a_reserved_organisation_handle_is_refused_and_writes_nothing() {
713 // The operator learns at boot rather than finding the root landing somewhere
714 // they did not mean. Until 0.8.2 the owner was written first and stayed, so
715 // `main`'s exit 4 was followed by a second boot that found an owner and served
716 // with no organisation and no home.
717 let fixture = Fixture::new();
718
719 let error = fixture
720 .seed(&seed_with_org("admin"))
721 .await
722 .expect_err("should refuse");
723
724 assert!(matches!(
725 error,
726 Error::Domain(DomainError::Validation { .. })
727 ));
728 fixture.assert_untouched(0).await;
729 }
730
731 #[tokio::test]
732 async fn a_malformed_organisation_handle_is_refused_and_writes_nothing() {
733 let fixture = Fixture::new();
734
735 for handle in ["not a handle", "-acme", "acme!"] {
736 let error = fixture
737 .seed(&seed_with_org(handle))
738 .await
739 .expect_err("should refuse");
740
741 assert!(
742 matches!(error, Error::Domain(DomainError::Validation { .. })),
743 "{handle:?} produced {error:?}"
744 );
745 fixture.assert_untouched(0).await;
746 }
747 }
748
749 #[tokio::test]
750 async fn an_organisation_may_not_take_the_owners_own_handle() {
751 // `JAMES` as well as `james`: handles are compared after normalising, which is
752 // what `create_organization` would have found one write later.
753 let fixture = Fixture::new();
754
755 for handle in ["james", "JAMES"] {
756 let error = fixture
757 .seed(&seed_with_org(handle))
758 .await
759 .expect_err("should refuse");
760
761 assert!(
762 matches!(error, Error::Domain(DomainError::AlreadyExists { .. })),
763 "{handle:?} produced {error:?}"
764 );
765 fixture.assert_untouched(0).await;
766 }
767 }
768
769 #[tokio::test]
770 async fn an_organisation_handle_already_held_is_refused_and_writes_nothing() {
771 // An unclaimed instance holding an organisation is not a state anything aims
772 // for, but `create_owner` writes the organisation before the user, so a save
773 // that failed between the two leaves exactly this.
774 let fixture = Fixture::new();
775 fixture
776 .orgs
777 .save(&Organization::new(OrgId::generate(), "acme", None).unwrap())
778 .await
779 .expect("save");
780
781 let error = fixture
782 .seed(&seed_with_org("acme"))
783 .await
784 .expect_err("should refuse");
785
786 assert!(matches!(
787 error,
788 Error::Domain(DomainError::AlreadyExists { .. })
789 ));
790 fixture.assert_untouched(1).await;
791 }
792
793 #[tokio::test]
794 async fn an_owner_handle_already_held_is_refused_and_writes_nothing() {
795 let fixture = Fixture::new();
796 fixture
797 .orgs
798 .save(&Organization::new(OrgId::generate(), "james", None).unwrap())
799 .await
800 .expect("save");
801
802 let error = fixture
803 .seed(&seed_with_org("acme"))
804 .await
805 .expect_err("should refuse");
806
807 assert!(matches!(
808 error,
809 Error::Domain(DomainError::AlreadyExists { .. })
810 ));
811 fixture.assert_untouched(1).await;
812 }
813
814 #[tokio::test]
815 async fn a_bad_email_is_refused_before_the_organisation_is_looked_at() {
816 // The whole seed, not the owner alone: a bad email beside a good organisation
817 // still writes nothing.
818 let fixture = Fixture::new();
819
820 let error = fixture
821 .seed(&OwnerSeed {
822 email: "not-an-email".to_owned(),
823 ..seed_with_org("acme")
824 })
825 .await
826 .expect_err("should refuse");
827
828 assert!(matches!(
829 error,
830 Error::Domain(DomainError::Validation { .. })
831 ));
832 fixture.assert_untouched(0).await;
833 }
834
835 #[tokio::test]
836 async fn a_claimed_instance_is_never_seeded_again() {
837 // What makes the two variables inert once an owner exists: a restart with them
838 // still set must not try to create a second owner, or fail the boot.
839 let fixture = Fixture::new();
840 fixture.claim(&spec()).await.expect("claim");
841
842 let error = seed_owner(
843 &seed(),
844 &fixture.users,
845 &fixture.orgs,
846 &fixture.memberships,
847 &fixture.settings,
848 &fixture.hasher,
849 )
850 .await
851 .expect_err("should refuse");
852
853 assert!(matches!(
854 error,
855 Error::Domain(DomainError::AlreadyExists { entity: "owner" })
856 ));
857 }
858
859 #[tokio::test]
860 async fn seeding_twice_is_refused() {
861 let fixture = Fixture::new();
862 seed_owner(
863 &seed(),
864 &fixture.users,
865 &fixture.orgs,
866 &fixture.memberships,
867 &fixture.settings,
868 &fixture.hasher,
869 )
870 .await
871 .expect("first seed");
872
873 let error = seed_owner(
874 &seed(),
875 &fixture.users,
876 &fixture.orgs,
877 &fixture.memberships,
878 &fixture.settings,
879 &fixture.hasher,
880 )
881 .await
882 .expect_err("should refuse");
883
884 assert!(matches!(
885 error,
886 Error::Domain(DomainError::AlreadyExists { entity: "owner" })
887 ));
888 }
889
890 #[tokio::test]
891 async fn a_reserved_handle_is_refused_and_writes_nothing() {
892 // `admin` is on the reserved list, and the whole point of refusing here is that
893 // the operator learns at boot rather than ending up with an instance nobody can
894 // own. The control plane's ADR 0008 names this as one of the two lockouts.
895 let fixture = Fixture::new();
896 let reserved = OwnerSeed {
897 handle: "admin".to_owned(),
898 ..seed()
899 };
900
901 let error = seed_owner(
902 &reserved,
903 &fixture.users,
904 &fixture.orgs,
905 &fixture.memberships,
906 &fixture.settings,
907 &fixture.hasher,
908 )
909 .await
910 .expect_err("should refuse");
911
912 assert!(matches!(
913 error,
914 Error::Domain(DomainError::Validation { .. })
915 ));
916 assert!(!fixture.users.any_exist().await.expect("any_exist"));
917 }
918
919 #[tokio::test]
920 async fn a_bad_email_is_refused_and_writes_nothing() {
921 let fixture = Fixture::new();
922 let bad = OwnerSeed {
923 email: "not-an-email".to_owned(),
924 ..seed()
925 };
926
927 let error = seed_owner(
928 &bad,
929 &fixture.users,
930 &fixture.orgs,
931 &fixture.memberships,
932 &fixture.settings,
933 &fixture.hasher,
934 )
935 .await
936 .expect_err("should refuse");
937
938 assert!(matches!(
939 error,
940 Error::Domain(DomainError::Validation { .. })
941 ));
942 assert!(!fixture.users.any_exist().await.expect("any_exist"));
943 }
944
945 #[tokio::test]
946 async fn the_seeded_owner_cannot_sign_in_with_any_password() {
947 // The stub hasher stores `stub:<plaintext>`, so this is also the one place that
948 // would notice a seeded password becoming predictable: every guess below would
949 // have to match the 32 random bytes seeding generated and dropped.
950 let fixture = Fixture::new();
951 seed_owner(
952 &seed(),
953 &fixture.users,
954 &fixture.orgs,
955 &fixture.memberships,
956 &fixture.settings,
957 &fixture.hasher,
958 )
959 .await
960 .expect("seed");
961
962 for guess in ["", "password", "correcthorsebattery", "james"] {
963 let error = crate::application::login::login(
964 "dev@example.com",
965 guess,
966 &fixture.users,
967 &fixture.hasher,
968 )
969 .await
970 .expect_err("should reject");
971
972 assert!(
973 matches!(error, Error::Domain(DomainError::InvalidCredentials)),
974 "{guess:?} produced {error:?}"
975 );
976 }
977 }
978
979 #[tokio::test]
980 async fn the_discarded_password_verifies_as_false_under_the_real_hasher() {
981 // Argon2 rather than the stub, because the claim being made is about the stored
982 // hash: it is a real one, so `verify` answers `Ok(false)` — a wrong password, not
983 // an unreadable hash and not an error. That is what keeps `login` on its normal
984 // path, with the timing of any other refusal.
985 let fixture = Fixture::new();
986 let hasher = Argon2Hasher::new();
987
988 seed_owner(
989 &seed(),
990 &fixture.users,
991 &fixture.orgs,
992 &fixture.memberships,
993 &fixture.settings,
994 &hasher,
995 )
996 .await
997 .expect("seed");
998
999 let user = fixture
1000 .users
1001 .find_by_email(&Email::new("dev@example.com").unwrap())
1002 .await
1003 .expect("lookup")
1004 .expect("user should exist");
1005
1006 assert!(
1007 user.password_hash.as_str().starts_with("$argon2id$"),
1008 "the seeded hash should be a real Argon2 hash"
1009 );
1010 assert!(
1011 !hasher
1012 .verify("correcthorsebattery", &user.password_hash)
1013 .expect("verify answers rather than erroring"),
1014 "a guess must be a plain no"
1015 );
1016 }
1017
1018 #[tokio::test]
1019 async fn is_claimed_reports_the_installation_state() {
1020 let fixture = Fixture::new();
1021 assert!(!is_claimed(&fixture.users).await.expect("is_claimed"));
1022
1023 fixture.claim(&spec()).await.expect("claim");
1024
1025 assert!(is_claimed(&fixture.users).await.expect("is_claimed"));
1026 }
1027}