steid

@jamesgill /

Rust20.6 KBCode·Blame·History·Raw
1//! Organisations, and which one the instance calls home.
2//!
3//! Steid's owner is a person or an organisation
4//! ([0010](../../plans/decisions/0010-single-tenant-vcs-not-portfolio.md)), and both
5//! are `Organization` rows — a person's handle is the name of the personal
6//! organisation created alongside their account. What makes one *the* owner is
7//! [`InstanceSettings::home`], which this module reads and writes.
8//!
9//! **Personal is derived, not stored.** An organisation is personal exactly when some
10//! user's `personal_org_id` points at it — see [`is_personal_org`]. A `kind` column was
11//! dropped from milestone 2 for routing reasons
12//! ([0004](../../plans/decisions/0004-root-handles-grouped-routes.md)) and is not being
13//! reintroduced for display: a derived answer cannot disagree with the foreign key,
14//! and a stored one eventually would.
15
16use crate::domain::{
17 Actor, DomainError, Membership, MembershipId, OrgId, OrgName, Organization, Role,
18 repository::{InstanceSettingsRepository, MembershipRepository, OrgRepository, UserRepository},
19};
20
21use super::{access::is_org_owner, claim::sole_owner_handle, error::Result};
22
23/// The organisation a signed-in user is asking to create.
24///
25/// Plain strings, like [`OwnerSpec`](super::OwnerSpec): the rules — the handle's shape
26/// and the reserved list — belong to the domain, and a form that has already validated
27/// them would be a second place for them to live.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct NewOrganisation {
30 pub handle: String,
31 pub display_name: Option<String>,
32}
33
34/// Creates an organisation and makes the actor its owner.
35///
36/// **Any signed-in user may create one, and an instance may hold several.** That is not
37/// multi-tenancy: every organisation here lives in the same database, under the same
38/// owner, reachable by the same people. What makes the instance single tenant is that
39/// exactly one of them is [home](home_handle).
40///
41/// The two saves are ordered the way [`claim`](super::claim) orders its three — the
42/// membership references the organisation, so the organisation goes first. A duplicate
43/// handle is refused before either, and the `orgs.name` unique index is what actually
44/// serialises two simultaneous creations of the same one.
45pub async fn create_organization(
46 actor: &Actor,
47 spec: &NewOrganisation,
48 orgs: &impl OrgRepository,
49 memberships: &impl MembershipRepository,
50) -> Result<Organization> {
51 let Some(user_id) = actor.user_id() else {
52 return Err(DomainError::Forbidden.into());
53 };
54
55 // Validated before the duplicate check, so a reserved or malformed handle is a
56 // validation failure rather than a lookup that finds nothing and then succeeds.
57 let org = Organization::new(OrgId::generate(), &spec.handle, spec.display_name.clone())?;
58
59 if orgs.find_by_name(&org.name).await?.is_some() {
60 return Err(DomainError::AlreadyExists {
61 entity: "organisation",
62 }
63 .into());
64 }
65
66 orgs.save(&org).await?;
67 memberships
68 .save(&Membership::new(
69 MembershipId::generate(),
70 org.id.clone(),
71 user_id.clone(),
72 Role::Owner,
73 ))
74 .await?;
75
76 Ok(org)
77}
78
79/// Whether this organisation is somebody's personal one.
80///
81/// The whole of the personal/organisation distinction, derived rather than stored.
82/// A personal organisation has no settings pages of its own — the person's existing
83/// `/{handle}/settings` is where its profile is edited — and `/orgs/new` cannot make
84/// one, because the only thing that makes an organisation personal is a user pointing
85/// at it, and that only happens at registration.
86pub async fn is_personal_org(org_id: &OrgId, users: &impl UserRepository) -> Result<bool> {
87 Ok(users.find_by_personal_org(org_id).await?.is_some())
88}
89
90/// Whether anybody has chosen a home page for this instance.
91///
92/// Distinct from `home_handle(..).is_some()`, which is also true for an instance that
93/// never chose and is falling back to its sole owner. The wizard and the "make this the
94/// home page" checkbox both want the *choice*, not the effect.
95pub async fn home_is_set(settings: &impl InstanceSettingsRepository) -> Result<bool> {
96 Ok(settings.load().await?.has_home())
97}
98
99/// Whether the organisation behind a handle is somebody's personal one.
100///
101/// [`is_personal_org`] addressed the way a page has it. A handle nobody holds answers
102/// `false`, which is the harmless direction: the caller is about to 404 anyway.
103pub async fn is_personal_handle(
104 handle: &OrgName,
105 orgs: &impl OrgRepository,
106 users: &impl UserRepository,
107) -> Result<bool> {
108 let Some(org) = orgs.find_by_name(handle).await? else {
109 return Ok(false);
110 };
111
112 is_personal_org(&org.id, users).await
113}
114
115/// The handle the root URL lands on.
116///
117/// `Some(home)` when somebody has chosen one, and otherwise the old rule —
118/// [`sole_owner_handle`](super::sole_owner_handle), the handle of the only user when
119/// there is exactly one. The fallback is what makes this safe to ship to instances that
120/// already exist: nobody has a home set, and every one of them keeps the front door it
121/// had.
122///
123/// `None` for an unclaimed instance, and for a multi-user one that never chose. The
124/// root serves its generic landing rather than electing somebody.
125///
126/// A home pointing at an organisation that is gone falls back too. The foreign key is
127/// `on delete set null`, so it should be unreachable — but the root URL is the one page
128/// that must not 500, and falling back costs a lookup that has already happened.
129pub async fn home_handle(
130 settings: &impl InstanceSettingsRepository,
131 users: &impl UserRepository,
132 orgs: &impl OrgRepository,
133) -> Result<Option<OrgName>> {
134 if let Some(home) = settings.load().await?.home
135 && let Some(org) = orgs.find_by_id(&home).await?
136 {
137 return Ok(Some(org.name));
138 }
139
140 sole_owner_handle(users, orgs).await
141}
142
143/// Points the root URL at an organisation.
144///
145/// **Owner of that organisation only.** Home is an instance-level setting, so the
146/// temptation is to gate it on owning the instance — but
147/// [`instance_owner`](super::instance_owner) answers `false` for everybody the moment a
148/// second user exists, which would make the front door unsettable on exactly the
149/// instances that most need to set it. Owning the organisation you are pointing at is
150/// the weaker rule and the one that still works; when milestone 7 gives the instance a
151/// real admin role, this is one of the bodies that changes.
152///
153/// A personal organisation is owned by the person whose it is, which the owner
154/// membership created at claim time already says — so there is no separate case here,
155/// only the `users` lookup that tells a caller *why* the answer was yes.
156pub async fn set_home(
157 actor: &Actor,
158 org_id: &OrgId,
159 orgs: &impl OrgRepository,
160 memberships: &impl MembershipRepository,
161 users: &impl UserRepository,
162 settings: &impl InstanceSettingsRepository,
163) -> Result<()> {
164 let Some(org) = orgs.find_by_id(org_id).await? else {
165 return Err(DomainError::NotFound {
166 entity: "organisation",
167 }
168 .into());
169 };
170
171 if !may_set_home(&org, actor, memberships, users).await? {
172 return Err(DomainError::Forbidden.into());
173 }
174
175 let mut stored = settings.load().await?;
176 stored.set_home(org.id.clone());
177 settings.save(&stored).await?;
178
179 Ok(())
180}
181
182/// [`set_home`] addressed the way a page has it: by handle.
183///
184/// The pages work in handles because that is what a URL carries; the use case works in
185/// ids because that is what the setting stores. One lookup bridges them, in the
186/// application layer rather than in a page reaching for a repository port.
187pub async fn set_home_by_handle(
188 actor: &Actor,
189 handle: &OrgName,
190 orgs: &impl OrgRepository,
191 memberships: &impl MembershipRepository,
192 users: &impl UserRepository,
193 settings: &impl InstanceSettingsRepository,
194) -> Result<()> {
195 let Some(org) = orgs.find_by_name(handle).await? else {
196 return Err(DomainError::NotFound {
197 entity: "organisation",
198 }
199 .into());
200 };
201
202 set_home(actor, &org.id, orgs, memberships, users, settings).await
203}
204
205/// Whether this actor may make this organisation the home page.
206///
207/// An owner membership, or — for a personal organisation — being the person it belongs
208/// to. The second arm is belt and braces: claiming creates the owner membership, so the
209/// first arm already answers yes today. It is written down because an account created
210/// by some future registration path that forgets the membership must not end up unable
211/// to point the root at itself.
212async fn may_set_home(
213 org: &Organization,
214 actor: &Actor,
215 memberships: &impl MembershipRepository,
216 users: &impl UserRepository,
217) -> Result<bool> {
218 if is_org_owner(org, actor, memberships).await? {
219 return Ok(true);
220 }
221
222 let Some(acting) = actor.user_id() else {
223 return Ok(false);
224 };
225
226 Ok(users
227 .find_by_personal_org(&org.id)
228 .await?
229 .is_some_and(|owner| &owner.id == acting))
230}
231
232#[cfg(test)]
233mod tests {
234 use super::*;
235 use crate::{
236 application::error::Error,
237 domain::{Email, InstanceSettings, PasswordHash, User, UserId},
238 infrastructure::repository::{
239 InMemoryInstanceSettingsRepo, InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryUserRepo,
240 },
241 };
242
243 struct Fixture {
244 orgs: InMemoryOrgRepo,
245 memberships: InMemoryMembershipRepo,
246 users: InMemoryUserRepo,
247 settings: InMemoryInstanceSettingsRepo,
248 }
249
250 impl Fixture {
251 fn new() -> Self {
252 Self {
253 orgs: InMemoryOrgRepo::new(),
254 memberships: InMemoryMembershipRepo::new(),
255 users: InMemoryUserRepo::new(),
256 settings: InMemoryInstanceSettingsRepo::new(),
257 }
258 }
259
260 /// A user and the personal organisation whose name is their handle, saved in
261 /// the order the foreign keys want — the same order `create_owner` uses.
262 async fn person(&self, handle: &str) -> (User, Organization) {
263 let org = Organization::new(OrgId::generate(), handle, None).expect("valid org");
264 self.orgs.save(&org).await.expect("save org");
265
266 let user = User::new(
267 UserId::generate(),
268 Email::new(format!("{handle}@example.com")).expect("valid email"),
269 PasswordHash::from_trusted("$argon2id$test"),
270 org.id.clone(),
271 );
272 self.users.save(&user).await.expect("save user");
273 self.memberships
274 .save(&Membership::new(
275 MembershipId::generate(),
276 org.id.clone(),
277 user.id.clone(),
278 Role::Owner,
279 ))
280 .await
281 .expect("save membership");
282
283 (user, org)
284 }
285
286 async fn create(&self, actor: &Actor, handle: &str) -> Result<Organization> {
287 create_organization(
288 actor,
289 &NewOrganisation {
290 handle: handle.to_owned(),
291 display_name: None,
292 },
293 &self.orgs,
294 &self.memberships,
295 )
296 .await
297 }
298
299 async fn home(&self) -> Option<OrgName> {
300 home_handle(&self.settings, &self.users, &self.orgs)
301 .await
302 .expect("home")
303 }
304 }
305
306 #[tokio::test]
307 async fn creating_an_organisation_makes_the_actor_its_owner() {
308 let f = Fixture::new();
309 let (user, _) = f.person("ada").await;
310 let actor = Actor::User(user.id.clone());
311
312 let org = f.create(&actor, "acme").await.expect("create");
313
314 assert_eq!(org.name.as_str(), "acme");
315 let membership = f
316 .memberships
317 .find(&org.id, &user.id)
318 .await
319 .expect("lookup")
320 .expect("membership should exist");
321 assert_eq!(membership.role, Role::Owner);
322 }
323
324 #[tokio::test]
325 async fn an_organisation_keeps_its_display_name() {
326 let f = Fixture::new();
327 let (user, _) = f.person("ada").await;
328
329 let org = create_organization(
330 &Actor::User(user.id),
331 &NewOrganisation {
332 handle: "acme".to_owned(),
333 display_name: Some("Acme Inc".to_owned()),
334 },
335 &f.orgs,
336 &f.memberships,
337 )
338 .await
339 .expect("create");
340
341 assert_eq!(org.label(), "Acme Inc");
342 }
343
344 #[tokio::test]
345 async fn an_anonymous_visitor_cannot_create_one() {
346 let f = Fixture::new();
347
348 let error = f
349 .create(&Actor::Anonymous, "acme")
350 .await
351 .expect_err("should refuse");
352
353 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
354 assert!(
355 f.orgs
356 .find_by_name(&OrgName::new("acme").unwrap())
357 .await
358 .expect("lookup")
359 .is_none()
360 );
361 }
362
363 #[tokio::test]
364 async fn a_duplicate_handle_is_refused() {
365 let f = Fixture::new();
366 let (user, _) = f.person("ada").await;
367 let actor = Actor::User(user.id);
368 f.create(&actor, "acme").await.expect("first");
369
370 let error = f.create(&actor, "Acme").await.expect_err("should refuse");
371
372 assert!(matches!(
373 error,
374 Error::Domain(DomainError::AlreadyExists {
375 entity: "organisation"
376 })
377 ));
378 }
379
380 #[tokio::test]
381 async fn a_persons_own_handle_is_a_duplicate_too() {
382 // Personal organisations and shared ones share one namespace, which is what
383 // `/{handle}` being the only shape of URL means.
384 let f = Fixture::new();
385 let (user, _) = f.person("ada").await;
386
387 let error = f
388 .create(&Actor::User(user.id), "ada")
389 .await
390 .expect_err("should refuse");
391
392 assert!(matches!(
393 error,
394 Error::Domain(DomainError::AlreadyExists { .. })
395 ));
396 }
397
398 #[tokio::test]
399 async fn a_reserved_handle_is_refused_and_writes_nothing() {
400 let f = Fixture::new();
401 let (user, _) = f.person("ada").await;
402
403 for reserved in ["orgs", "organizations", "auth"] {
404 let error = f
405 .create(&Actor::User(user.id.clone()), reserved)
406 .await
407 .expect_err("should refuse");
408
409 assert!(
410 matches!(error, Error::Domain(DomainError::Validation { .. })),
411 "{reserved:?} produced {error:?}"
412 );
413 }
414 }
415
416 #[tokio::test]
417 async fn personal_is_derived_from_the_user_pointing_at_it() {
418 let f = Fixture::new();
419 let (user, personal) = f.person("ada").await;
420 let shared = f
421 .create(&Actor::User(user.id), "acme")
422 .await
423 .expect("create");
424
425 assert!(is_personal_org(&personal.id, &f.users).await.expect("ask"));
426 assert!(!is_personal_org(&shared.id, &f.users).await.expect("ask"));
427 }
428
429 #[tokio::test]
430 async fn with_no_home_set_the_sole_owner_is_the_front_door() {
431 // The fallback that lets this ship to instances that already exist.
432 let f = Fixture::new();
433 f.person("ada").await;
434
435 assert_eq!(
436 f.home().await.map(|name| name.to_string()),
437 Some("ada".to_owned())
438 );
439 }
440
441 #[tokio::test]
442 async fn an_unclaimed_instance_has_no_home() {
443 let f = Fixture::new();
444
445 assert_eq!(f.home().await, None);
446 }
447
448 #[tokio::test]
449 async fn setting_home_overrides_the_fallback() {
450 let f = Fixture::new();
451 let (user, _) = f.person("ada").await;
452 let actor = Actor::User(user.id);
453 let acme = f.create(&actor, "acme").await.expect("create");
454
455 set_home(
456 &actor,
457 &acme.id,
458 &f.orgs,
459 &f.memberships,
460 &f.users,
461 &f.settings,
462 )
463 .await
464 .expect("set home");
465
466 assert_eq!(
467 f.home().await.map(|name| name.to_string()),
468 Some("acme".to_owned())
469 );
470 }
471
472 #[tokio::test]
473 async fn a_person_may_make_their_own_page_the_home() {
474 let f = Fixture::new();
475 let (user, personal) = f.person("ada").await;
476
477 set_home(
478 &Actor::User(user.id),
479 &personal.id,
480 &f.orgs,
481 &f.memberships,
482 &f.users,
483 &f.settings,
484 )
485 .await
486 .expect("set home");
487
488 assert_eq!(
489 f.settings.load().await.expect("load").home,
490 Some(personal.id)
491 );
492 }
493
494 #[tokio::test]
495 async fn a_member_who_is_not_an_owner_may_not_set_home() {
496 let f = Fixture::new();
497 let (owner, _) = f.person("ada").await;
498 let (outsider, _) = f.person("bob").await;
499 let acme = f
500 .create(&Actor::User(owner.id), "acme")
501 .await
502 .expect("create");
503 f.memberships
504 .save(&Membership::new(
505 MembershipId::generate(),
506 acme.id.clone(),
507 outsider.id.clone(),
508 Role::Member,
509 ))
510 .await
511 .expect("save membership");
512
513 let error = set_home(
514 &Actor::User(outsider.id),
515 &acme.id,
516 &f.orgs,
517 &f.memberships,
518 &f.users,
519 &f.settings,
520 )
521 .await
522 .expect_err("should refuse");
523
524 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
525 assert!(!f.settings.load().await.expect("load").has_home());
526 }
527
528 #[tokio::test]
529 async fn an_organisation_that_does_not_exist_cannot_be_home() {
530 let f = Fixture::new();
531 let (user, _) = f.person("ada").await;
532
533 let error = set_home(
534 &Actor::User(user.id),
535 &OrgId::generate(),
536 &f.orgs,
537 &f.memberships,
538 &f.users,
539 &f.settings,
540 )
541 .await
542 .expect_err("should refuse");
543
544 assert!(matches!(
545 error,
546 Error::Domain(DomainError::NotFound {
547 entity: "organisation"
548 })
549 ));
550 }
551
552 #[tokio::test]
553 async fn a_choice_is_not_the_same_as_a_fallback() {
554 let f = Fixture::new();
555 let (user, personal) = f.person("ada").await;
556
557 // Falling back, so there is a handle but no choice.
558 assert!(f.home().await.is_some());
559 assert!(!home_is_set(&f.settings).await.expect("ask"));
560
561 set_home(
562 &Actor::User(user.id),
563 &personal.id,
564 &f.orgs,
565 &f.memberships,
566 &f.users,
567 &f.settings,
568 )
569 .await
570 .expect("set home");
571
572 assert!(home_is_set(&f.settings).await.expect("ask"));
573 }
574
575 #[tokio::test]
576 async fn a_handle_can_be_asked_whether_it_is_personal() {
577 let f = Fixture::new();
578 let (user, _) = f.person("ada").await;
579 f.create(&Actor::User(user.id), "acme")
580 .await
581 .expect("create");
582
583 let ask = async |handle: &str| {
584 is_personal_handle(&OrgName::new(handle).unwrap(), &f.orgs, &f.users)
585 .await
586 .expect("ask")
587 };
588
589 assert!(ask("ada").await);
590 assert!(!ask("acme").await);
591 // A handle nobody holds: the caller is about to 404 either way.
592 assert!(!ask("nobody").await);
593 }
594
595 #[tokio::test]
596 async fn home_can_be_set_by_handle() {
597 let f = Fixture::new();
598 let (user, _) = f.person("ada").await;
599 let actor = Actor::User(user.id);
600 f.create(&actor, "acme").await.expect("create");
601
602 set_home_by_handle(
603 &actor,
604 &OrgName::new("acme").unwrap(),
605 &f.orgs,
606 &f.memberships,
607 &f.users,
608 &f.settings,
609 )
610 .await
611 .expect("set home");
612
613 assert_eq!(
614 f.home().await.map(|name| name.to_string()),
615 Some("acme".to_owned())
616 );
617 }
618
619 #[tokio::test]
620 async fn a_home_pointing_nowhere_falls_back_rather_than_failing() {
621 // Unreachable through the ports — the foreign key is `on delete set null` — but
622 // `/` is the one page that must not 500.
623 let f = Fixture::new();
624 f.person("ada").await;
625 f.settings
626 .save(&InstanceSettings::from_trusted(Some(OrgId::generate())))
627 .await
628 .expect("save");
629
630 assert_eq!(
631 f.home().await.map(|name| name.to_string()),
632 Some("ada".to_owned())
633 );
634 }
635}