steid

@jamesgill /

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