| 1 | use crate::domain::{ |
| 2 | Actor, DomainError, Email, Membership, MembershipId, OrgId, OrgName, Organization, Password, |
| 3 | Role, SetupToken, User, UserId, |
| 4 | repository::{MembershipRepository, OrgRepository, UserRepository}, |
| 5 | }; |
| 6 | |
| 7 | use super::{error::Result, port::PasswordHasher}; |
| 8 | |
| 9 | |
| 10 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 11 | pub struct OwnerSpec { |
| 12 | pub handle: String, |
| 13 | pub email: String, |
| 14 | pub password: String, |
| 15 | } |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | pub async fn is_claimed(users: &impl UserRepository) -> Result<bool> { |
| 21 | Ok(users.any_exist().await?) |
| 22 | } |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | pub async fn sole_owner_handle( |
| 34 | users: &impl UserRepository, |
| 35 | orgs: &impl OrgRepository, |
| 36 | ) -> Result<Option<OrgName>> { |
| 37 | let Some(user) = users.sole_user().await? else { |
| 38 | return Ok(None); |
| 39 | }; |
| 40 | |
| 41 | Ok(orgs |
| 42 | .find_by_id(&user.personal_org_id) |
| 43 | .await? |
| 44 | .map(|org| org.name)) |
| 45 | } |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | pub async fn claim_instance( |
| 55 | presented_token: &str, |
| 56 | setup_token: &SetupToken, |
| 57 | spec: &OwnerSpec, |
| 58 | users: &impl UserRepository, |
| 59 | orgs: &impl OrgRepository, |
| 60 | memberships: &impl MembershipRepository, |
| 61 | hasher: &impl PasswordHasher, |
| 62 | ) -> Result<Actor> { |
| 63 | if !setup_token.matches(presented_token) { |
| 64 | return Err(DomainError::InvalidCredentials.into()); |
| 65 | } |
| 66 | |
| 67 | |
| 68 | |
| 69 | if is_claimed(users).await? { |
| 70 | return Err(DomainError::AlreadyExists { entity: "owner" }.into()); |
| 71 | } |
| 72 | |
| 73 | let email = Email::new(&spec.email)?; |
| 74 | let org = Organization::new(OrgId::generate(), &spec.handle, None)?; |
| 75 | |
| 76 | |
| 77 | let password = Password::new(&spec.password)?; |
| 78 | let password_hash = hasher.hash(password.expose())?; |
| 79 | |
| 80 | let user = User::new(UserId::generate(), email, password_hash, org.id.clone()); |
| 81 | let membership = Membership::new( |
| 82 | MembershipId::generate(), |
| 83 | org.id.clone(), |
| 84 | user.id.clone(), |
| 85 | Role::Owner, |
| 86 | ); |
| 87 | |
| 88 | |
| 89 | |
| 90 | orgs.save(&org).await?; |
| 91 | users.save(&user).await?; |
| 92 | memberships.save(&membership).await?; |
| 93 | |
| 94 | Ok(Actor::User(user.id)) |
| 95 | } |
| 96 | |
| 97 | #[cfg(test)] |
| 98 | mod tests { |
| 99 | use super::*; |
| 100 | use crate::{ |
| 101 | application::error::Error, |
| 102 | domain::OrgName, |
| 103 | infrastructure::{ |
| 104 | password::StubHasher, |
| 105 | repository::{InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryUserRepo}, |
| 106 | }, |
| 107 | }; |
| 108 | |
| 109 | struct Fixture { |
| 110 | token: SetupToken, |
| 111 | users: InMemoryUserRepo, |
| 112 | orgs: InMemoryOrgRepo, |
| 113 | memberships: InMemoryMembershipRepo, |
| 114 | hasher: StubHasher, |
| 115 | } |
| 116 | |
| 117 | impl Fixture { |
| 118 | fn new() -> Self { |
| 119 | Self { |
| 120 | token: SetupToken::generate(), |
| 121 | users: InMemoryUserRepo::new(), |
| 122 | orgs: InMemoryOrgRepo::new(), |
| 123 | memberships: InMemoryMembershipRepo::new(), |
| 124 | hasher: StubHasher::new(), |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | async fn claim_with(&self, presented: &str, spec: &OwnerSpec) -> Result<Actor> { |
| 129 | claim_instance( |
| 130 | presented, |
| 131 | &self.token, |
| 132 | spec, |
| 133 | &self.users, |
| 134 | &self.orgs, |
| 135 | &self.memberships, |
| 136 | &self.hasher, |
| 137 | ) |
| 138 | .await |
| 139 | } |
| 140 | |
| 141 | async fn claim(&self, spec: &OwnerSpec) -> Result<Actor> { |
| 142 | self.claim_with(self.token.reveal(), spec).await |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | fn spec() -> OwnerSpec { |
| 147 | OwnerSpec { |
| 148 | handle: "james".to_owned(), |
| 149 | email: "dev@example.com".to_owned(), |
| 150 | password: "correcthorsebattery".to_owned(), |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | #[tokio::test] |
| 155 | async fn claiming_creates_org_user_and_owner_membership() { |
| 156 | let fixture = Fixture::new(); |
| 157 | |
| 158 | let actor = fixture.claim(&spec()).await.expect("claim"); |
| 159 | |
| 160 | let org = fixture |
| 161 | .orgs |
| 162 | .find_by_name(&OrgName::new("james").unwrap()) |
| 163 | .await |
| 164 | .expect("lookup") |
| 165 | .expect("org should exist"); |
| 166 | let user = fixture |
| 167 | .users |
| 168 | .find_by_email(&Email::new("dev@example.com").unwrap()) |
| 169 | .await |
| 170 | .expect("lookup") |
| 171 | .expect("user should exist"); |
| 172 | let membership = fixture |
| 173 | .memberships |
| 174 | .find(&org.id, &user.id) |
| 175 | .await |
| 176 | .expect("lookup") |
| 177 | .expect("membership should exist"); |
| 178 | |
| 179 | assert_eq!(actor, Actor::User(user.id.clone())); |
| 180 | assert_eq!(user.personal_org_id, org.id); |
| 181 | assert_eq!(membership.role, Role::Owner); |
| 182 | assert!(membership.can_write()); |
| 183 | } |
| 184 | |
| 185 | #[tokio::test] |
| 186 | async fn the_owner_is_returned_signed_in() { |
| 187 | let fixture = Fixture::new(); |
| 188 | |
| 189 | let actor = fixture.claim(&spec()).await.expect("claim"); |
| 190 | |
| 191 | assert!( |
| 192 | actor.is_authenticated(), |
| 193 | "claiming should hand back a session-able actor, not require a second login" |
| 194 | ); |
| 195 | } |
| 196 | |
| 197 | #[tokio::test] |
| 198 | async fn stores_a_hash_never_the_plaintext() { |
| 199 | let fixture = Fixture::new(); |
| 200 | fixture.claim(&spec()).await.expect("claim"); |
| 201 | |
| 202 | let user = fixture |
| 203 | .users |
| 204 | .find_by_email(&Email::new("dev@example.com").unwrap()) |
| 205 | .await |
| 206 | .expect("lookup") |
| 207 | .expect("user should exist"); |
| 208 | |
| 209 | assert_ne!(user.password_hash.as_str(), "correcthorsebattery"); |
| 210 | assert!( |
| 211 | fixture |
| 212 | .hasher |
| 213 | .verify("correcthorsebattery", &user.password_hash) |
| 214 | .expect("verify") |
| 215 | ); |
| 216 | } |
| 217 | |
| 218 | #[tokio::test] |
| 219 | async fn a_claim_with_a_short_password_is_refused_and_writes_nothing() { |
| 220 | |
| 221 | |
| 222 | let fixture = Fixture::new(); |
| 223 | |
| 224 | let error = fixture |
| 225 | .claim(&OwnerSpec { |
| 226 | password: "hunter2".to_owned(), |
| 227 | ..spec() |
| 228 | }) |
| 229 | .await |
| 230 | .expect_err("should refuse"); |
| 231 | |
| 232 | assert!(matches!( |
| 233 | error, |
| 234 | Error::Domain(DomainError::Validation { ref field, .. }) if field == "password" |
| 235 | )); |
| 236 | assert!( |
| 237 | !fixture.users.any_exist().await.expect("any_exist"), |
| 238 | "a refused password leaves an unclaimed instance" |
| 239 | ); |
| 240 | assert!( |
| 241 | fixture |
| 242 | .orgs |
| 243 | .find_by_name(&OrgName::new("james").unwrap()) |
| 244 | .await |
| 245 | .expect("lookup") |
| 246 | .is_none(), |
| 247 | "and no organisation behind it" |
| 248 | ); |
| 249 | } |
| 250 | |
| 251 | #[tokio::test] |
| 252 | async fn a_wrong_token_is_rejected_and_writes_nothing() { |
| 253 | let fixture = Fixture::new(); |
| 254 | |
| 255 | let error = fixture |
| 256 | .claim_with(SetupToken::generate().reveal(), &spec()) |
| 257 | .await |
| 258 | .expect_err("should reject"); |
| 259 | |
| 260 | assert!(matches!( |
| 261 | error, |
| 262 | Error::Domain(DomainError::InvalidCredentials) |
| 263 | )); |
| 264 | assert!(!fixture.users.any_exist().await.expect("any_exist")); |
| 265 | } |
| 266 | |
| 267 | #[tokio::test] |
| 268 | async fn an_empty_token_is_rejected() { |
| 269 | let fixture = Fixture::new(); |
| 270 | |
| 271 | let error = fixture |
| 272 | .claim_with("", &spec()) |
| 273 | .await |
| 274 | .expect_err("should reject"); |
| 275 | |
| 276 | assert!(matches!( |
| 277 | error, |
| 278 | Error::Domain(DomainError::InvalidCredentials) |
| 279 | )); |
| 280 | } |
| 281 | |
| 282 | #[tokio::test] |
| 283 | async fn a_claimed_instance_cannot_be_claimed_again() { |
| 284 | let fixture = Fixture::new(); |
| 285 | fixture.claim(&spec()).await.expect("first claim"); |
| 286 | |
| 287 | let intruder = OwnerSpec { |
| 288 | handle: "intruder".to_owned(), |
| 289 | email: "intruder@example.com".to_owned(), |
| 290 | password: "letmeinplease".to_owned(), |
| 291 | }; |
| 292 | let error = fixture.claim(&intruder).await.expect_err("should reject"); |
| 293 | |
| 294 | assert!(matches!( |
| 295 | error, |
| 296 | Error::Domain(DomainError::AlreadyExists { entity: "owner" }) |
| 297 | )); |
| 298 | } |
| 299 | |
| 300 | #[tokio::test] |
| 301 | async fn a_wrong_token_cannot_probe_whether_the_instance_is_claimed() { |
| 302 | let unclaimed = Fixture::new(); |
| 303 | let claimed = Fixture::new(); |
| 304 | claimed.claim(&spec()).await.expect("claim"); |
| 305 | |
| 306 | let wrong = SetupToken::generate(); |
| 307 | let from_unclaimed = unclaimed |
| 308 | .claim_with(wrong.reveal(), &spec()) |
| 309 | .await |
| 310 | .expect_err("should reject"); |
| 311 | let from_claimed = claimed |
| 312 | .claim_with(wrong.reveal(), &spec()) |
| 313 | .await |
| 314 | .expect_err("should reject"); |
| 315 | |
| 316 | |
| 317 | |
| 318 | assert!(matches!( |
| 319 | from_unclaimed, |
| 320 | Error::Domain(DomainError::InvalidCredentials) |
| 321 | )); |
| 322 | assert!(matches!( |
| 323 | from_claimed, |
| 324 | Error::Domain(DomainError::InvalidCredentials) |
| 325 | )); |
| 326 | } |
| 327 | |
| 328 | #[tokio::test] |
| 329 | async fn rejects_an_invalid_handle_without_writing_anything() { |
| 330 | let fixture = Fixture::new(); |
| 331 | let bad = OwnerSpec { |
| 332 | handle: "not a handle".to_owned(), |
| 333 | ..spec() |
| 334 | }; |
| 335 | |
| 336 | let error = fixture.claim(&bad).await.expect_err("should reject"); |
| 337 | |
| 338 | assert!(matches!( |
| 339 | error, |
| 340 | Error::Domain(DomainError::Validation { .. }) |
| 341 | )); |
| 342 | assert!( |
| 343 | !fixture.users.any_exist().await.expect("any_exist"), |
| 344 | "nothing should be written when validation fails" |
| 345 | ); |
| 346 | } |
| 347 | |
| 348 | #[tokio::test] |
| 349 | async fn rejects_an_invalid_email_without_writing_anything() { |
| 350 | let fixture = Fixture::new(); |
| 351 | let bad = OwnerSpec { |
| 352 | email: "not-an-email".to_owned(), |
| 353 | ..spec() |
| 354 | }; |
| 355 | |
| 356 | let error = fixture.claim(&bad).await.expect_err("should reject"); |
| 357 | |
| 358 | assert!(matches!( |
| 359 | error, |
| 360 | Error::Domain(DomainError::Validation { .. }) |
| 361 | )); |
| 362 | assert!(!fixture.users.any_exist().await.expect("any_exist")); |
| 363 | } |
| 364 | |
| 365 | #[tokio::test] |
| 366 | async fn is_claimed_reports_the_installation_state() { |
| 367 | let fixture = Fixture::new(); |
| 368 | assert!(!is_claimed(&fixture.users).await.expect("is_claimed")); |
| 369 | |
| 370 | fixture.claim(&spec()).await.expect("claim"); |
| 371 | |
| 372 | assert!(is_claimed(&fixture.users).await.expect("is_claimed")); |
| 373 | } |
| 374 | } |