forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

builder.rs136 lines, 5.4 KiBHistoryRawDownload
1//! Builder workflows: the boot-time seed and the lookups the web layer
2//! resolves cookies and logins with. The control-database queries live in
3//! [`crate::db::builder`]; the school-provisioning routes never come through
4//! here — they speak to [`crate::tenant::Tenants`] directly.
5
6use crate::database::Database;
7use crate::db::builder;
8use crate::domain::builder::{Builder, BuilderId, BuilderSession};
9use crate::domain::user::{Password, Username};
10use crate::error::AppError;
11
12/// Idempotent startup seed: guarantee an account with this username in the
13/// control database. Missing → created. Already present → nothing to do (the
14/// stored password stays whatever it is — the seed never rewrites a
15/// credential, so rotating `BUILDER_PASSWORD` in the environment does not
16/// silently re-key a live account; delete the row to re-seed). There is no
17/// role to promote here, so this cannot have
18/// [`crate::service::user::ensure_admin`]'s create-then-promote hole.
19pub async fn ensure(db: &Database, username: Username, password: Password) -> Result<(), AppError> {
20 if builder::find_by_username(db, username.as_str())
21 .await?
22 .is_some()
23 {
24 return Ok(());
25 }
26 let builder = Builder {
27 id: BuilderId::generate(),
28 password_hash: password.hash_async().await?,
29 username,
30 };
31 // A rival boot that seeded the same username between the read above and
32 // this insert loses the race silently — `create` reports "already there"
33 // instead of raising, so the second container of a fresh deployment boots
34 // instead of dying on a duplicate key. The winner's credential stands.
35 if builder::create(db, builder).await? {
36 // The account name stays out of the event: exported log records must
37 // name no person (see `telemetry`).
38 tracing::info!("seeded the builder account named by BUILDER_USERNAME");
39 }
40 Ok(())
41}
42
43/// The login lookup. Usernames are stored trimmed; callers trim the same way
44/// so a padded attempt matches the canonical name.
45pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<Builder>, AppError> {
46 builder::find_by_username(db, username).await
47}
48
49pub async fn read(db: &Database, id: &BuilderId) -> Result<Option<Builder>, AppError> {
50 builder::read(db, id).await
51}
52
53pub async fn create_session(
54 db: &Database,
55 builder_id: &BuilderId,
56) -> Result<BuilderSession, AppError> {
57 builder::create_session(db, builder_id).await
58}
59
60pub async fn find_by_token(db: &Database, token: &str) -> Result<Option<BuilderSession>, AppError> {
61 builder::find_by_token(db, token).await
62}
63
64pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> {
65 builder::delete_by_token(db, token).await
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71
72 #[tokio::test]
73 async fn the_seed_is_idempotent_and_never_rewrites_a_credential() {
74 let tenants = crate::database::init_test_tenants().await;
75 let control = tenants.control();
76 let name = Username::try_new("builder1").unwrap();
77 ensure(control, name.clone(), Password::try_new("secret1").unwrap())
78 .await
79 .unwrap();
80 let first = find_by_username(control, "builder1")
81 .await
82 .unwrap()
83 .expect("seeded");
84
85 // A second boot with a *different* password must leave the row alone:
86 // an environment edit is not a password reset.
87 ensure(control, name, Password::try_new("secret2").unwrap())
88 .await
89 .unwrap();
90 let again = find_by_username(control, "builder1")
91 .await
92 .unwrap()
93 .expect("still there");
94 assert_eq!(again.get_id(), first.get_id());
95 assert_eq!(
96 again.get_password_hash().as_str(),
97 first.get_password_hash().as_str()
98 );
99 }
100
101 /// Two boots of one deployment seed the same username in the same instant.
102 /// The loser must adopt the winner's row instead of dying on its own
103 /// insert — measured on a fresh control database: four boots racing, three
104 /// died on `23505 builder_username` and only the winner stayed up.
105 #[tokio::test]
106 async fn a_racing_seed_adopts_the_row_it_lost_to() {
107 let tenants = crate::database::init_test_tenants().await;
108 let control = tenants.control();
109 let name = Username::try_new("builder_race").unwrap();
110 let (first, second) = tokio::join!(
111 ensure(control, name.clone(), Password::try_new("secret1").unwrap()),
112 ensure(control, name.clone(), Password::try_new("secret2").unwrap()),
113 );
114 first.expect("the first seed");
115 second.expect("the racing seed adopts the account the winner seeded");
116
117 // One account, and the credential is whichever writer won the insert —
118 // neither seed rewrites the other's row.
119 let row = find_by_username(control, "builder_race")
120 .await
121 .unwrap()
122 .expect("seeded");
123 let matches_offered = row
124 .get_password_hash()
125 .verify_async(&Password::try_new("secret1").unwrap())
126 .await
127 || row
128 .get_password_hash()
129 .verify_async(&Password::try_new("secret2").unwrap())
130 .await;
131 assert!(
132 matches_offered,
133 "the stored hash belongs to no offered password"
134 );
135 }
136}