Skip to content

Commit b1fdf5f

Browse files
committed
Invitations, review fixes: staff are no admins of organizations they aren't in (their tools are the admin MCP's, with its audit log); changing or removing a member locks the admin memberships first, so two admins demoting each other can't leave none; accepting re-reads the invitation FOR UPDATE (a withdrawn one or a second click is a 404) and tells the person they joined
1 parent fd4e5d7 commit b1fdf5f

2 files changed

Lines changed: 92 additions & 26 deletions

File tree

‎app/src/auth/invitations.rs‎

Lines changed: 62 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -134,8 +134,8 @@ pub async fn may_send(org_id: i64, address: Option<&str>) -> laravel::Result<Res
134134
Ok(Ok(()))
135135
}
136136

137-
/// The organization by slug and the person's role there; a 404 when they aren't a member (staff see every one as an
138-
/// admin would).
137+
/// The organization by slug and the person's role there; a 404 when they aren't a member. Staff are no exception:
138+
/// their tools are the admin MCP's, with its audit log, never the customer pages.
139139
async fn org_role(user: &User, slug: &str) -> laravel::Result<(i64, String, Role)> {
140140
let user_id = user.id;
141141
let row = db::query!(
@@ -148,7 +148,6 @@ async fn org_role(user: &User, slug: &str) -> laravel::Result<(i64, String, Role
148148
let role = row.try_get::<Option<String>>("role")?.as_deref().and_then(Role::parse);
149149
let role = match role {
150150
Some(r) => r,
151-
None if user.staff => Role::Admin,
152151
None => return Err(laravel::abort(404)),
153152
};
154153
Ok((row.try_get("id")?, row.try_get("name")?, role))
@@ -354,14 +353,24 @@ pub async fn accept(
354353
) -> laravel::Result<Json<Value>> {
355354
let (invitation, org_id, role) = theirs(&user, &id).await?;
356355
let (user_id, role_name) = (user.id, role.as_str());
357-
db::transaction(async |tx| {
356+
let joined = db::transaction(async |tx| {
357+
// Still pending? Withdrawn meanwhile, or accepted by a double click: nothing to do.
358+
let pending: Option<i64> = db::query!(
359+
tx,
360+
"SELECT id FROM invitations WHERE id = {invitation} AND accepted_at IS NULL FOR UPDATE"
361+
)
362+
.scalar()
363+
.await?;
364+
if pending.is_none() {
365+
return Ok(None);
366+
}
358367
let current: Option<String> = db::query!(
359368
tx,
360369
"SELECT role FROM memberships WHERE organization_id = {org_id} AND user_id = {user_id} FOR UPDATE"
361370
)
362371
.scalar()
363372
.await?;
364-
match current.as_deref().and_then(Role::parse) {
373+
let joined = match current.as_deref().and_then(Role::parse) {
365374
None => {
366375
db::query!(
367376
tx,
@@ -370,6 +379,7 @@ pub async fn accept(
370379
)
371380
.insert()
372381
.await?;
382+
true
373383
}
374384
Some(r) if r < role => {
375385
db::query!(
@@ -379,19 +389,25 @@ pub async fn accept(
379389
)
380390
.update()
381391
.await?;
392+
true
382393
}
383-
Some(_) => {}
384-
}
394+
Some(_) => false,
395+
};
385396
db::query!(
386397
tx,
387398
"UPDATE invitations SET accepted_by = {user_id}, accepted_at = now(), updated_at = now() \
388399
WHERE id = {invitation}"
389400
)
390401
.update()
391402
.await?;
392-
Ok(())
403+
Ok(Some(joined))
393404
})
394405
.await?;
406+
let Some(joined) = joined else { return Err(laravel::abort(404)) };
407+
// They're told, as today's grant does, once the membership is there.
408+
if joined {
409+
MembershipChanged::now(org_id, user_id, Some(role)).dispatch().await?;
410+
}
395411
let slug: Option<String> = db::query!("SELECT slug FROM organizations WHERE id = {org_id}").scalar().await?;
396412
Ok(Json(json!({ "slug": slug })))
397413
}
@@ -443,13 +459,41 @@ async fn managed(user: &User, org: &str, pid: &str) -> laravel::Result<(i64, i64
443459
Ok((org_id, row.try_get("user_id")?))
444460
}
445461

446-
async fn other_admins(org_id: i64, except: i64) -> laravel::Result<i64> {
447-
Ok(db::query!(
448-
"SELECT count(*) FROM memberships WHERE organization_id = {org_id} AND role = 'admin' AND user_id <> {except}"
449-
)
450-
.scalar()
451-
.await?
452-
.unwrap_or(0))
462+
/// Change (`Some(role)`) or remove (`None`) a membership, unless that would leave the organization without an admin.
463+
/// The admin memberships are locked first, so two admins demoting or removing each other at once can't both succeed.
464+
/// `false` when it would leave no admin.
465+
async fn change_member(org_id: i64, member: i64, role: Option<Role>) -> laravel::Result<bool> {
466+
db::transaction(async |tx| {
467+
let admins = db::query!(
468+
tx,
469+
"SELECT user_id FROM memberships WHERE organization_id = {org_id} AND role = 'admin' FOR UPDATE"
470+
)
471+
.select()
472+
.await?;
473+
let others = admins.iter().filter(|r| r.try_get::<i64>("user_id").is_ok_and(|id| id != member)).count();
474+
if role != Some(Role::Admin) && others == 0 {
475+
return Ok(false);
476+
}
477+
match role {
478+
Some(role) => {
479+
let role_name = role.as_str();
480+
db::query!(
481+
tx,
482+
"UPDATE memberships SET role = {role_name}, updated_at = now() \
483+
WHERE organization_id = {org_id} AND user_id = {member}"
484+
)
485+
.update()
486+
.await?;
487+
}
488+
None => {
489+
db::query!(tx, "DELETE FROM memberships WHERE organization_id = {org_id} AND user_id = {member}")
490+
.delete()
491+
.await?;
492+
}
493+
}
494+
Ok(true)
495+
})
496+
.await
453497
}
454498

455499
#[laravel::input]
@@ -467,16 +511,9 @@ pub async fn update_member(
467511
) -> laravel::Result<Json<Value>> {
468512
let role = Role::parse(&p.role).ok_or_else(|| laravel::abort_with(422, "role is admin, member or read"))?;
469513
let (org_id, member) = managed(&user, &org, &id).await?;
470-
if role != Role::Admin && other_admins(org_id, member).await? == 0 {
514+
if !change_member(org_id, member, Some(role)).await? {
471515
return Err(laravel::abort_with(422, "the organization needs another admin first"));
472516
}
473-
let role_name = role.as_str();
474-
db::query!(
475-
"UPDATE memberships SET role = {role_name}, updated_at = now() \
476-
WHERE organization_id = {org_id} AND user_id = {member}"
477-
)
478-
.update()
479-
.await?;
480517
Ok(Json(json!({ "members": members_json(org_id, true).await? })))
481518
}
482519

@@ -487,12 +524,11 @@ pub async fn remove_member(
487524
Params((org, id)): Params<(String, String)>,
488525
) -> laravel::Result<Json<Value>> {
489526
let (org_id, member) = managed(&user, &org, &id).await?;
490-
if other_admins(org_id, member).await? == 0 {
527+
if !change_member(org_id, member, None).await? {
491528
return Err(laravel::abort_with(422, "the organization needs another admin first"));
492529
}
493-
db::query!("DELETE FROM memberships WHERE organization_id = {org_id} AND user_id = {member}").delete().await?;
494530
if member != user.id {
495-
MembershipChanged { organization_id: org_id, user_id: member, role: None }.dispatch().await?;
531+
MembershipChanged::now(org_id, member, None).dispatch().await?;
496532
}
497533
Ok(Json(json!({ "members": members_json(org_id, true).await? })))
498534
}

‎app/tests/invitations.rs‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,17 @@ async fn an_invitation_waits_for_its_invitee_to_accept(app: Application) -> lara
8888
.assert_ok()
8989
.assert_json_path("slug", "acme");
9090
assert_eq!(role_of(acme, &ada).await?.as_deref(), Some("member"));
91+
let added: Option<i64> =
92+
db::query!("SELECT count(*) FROM emails WHERE kind = 'added_to_org' AND recipient = 'ada@example.com'")
93+
.scalar()
94+
.await?;
95+
assert_eq!(added, Some(1), "she's told she joined");
96+
// A second click finds nothing to accept.
97+
app.post(format!("/api/ui/invitations/{id}/accept"))
98+
.acting_as(&ada)
99+
.header("sec-fetch-site", "same-origin")
100+
.await
101+
.assert_status(404);
91102
app.get("/api/ui/invitations").acting_as(&ada).await.assert_json_path("invitations", json!([]));
92103
let members = app.get("/api/ui/orgs/acme/members").acting_as(&ada).await;
93104
members.assert_ok().assert_json_path("members.0.name", "Grace").assert_json_path("members.1.name", "Ada");
@@ -233,3 +244,22 @@ async fn invitation_emails_are_limited_per_recipient(app: Application) -> larave
233244
.assert_status(422);
234245
Ok(())
235246
}
247+
248+
#[laravel::test]
249+
async fn staff_are_no_admins_of_organizations_they_are_not_in(app: Application) -> laravel::Result<()> {
250+
let acme = org("acme").await?;
251+
let admin = person("Grace", "grace@example.com").await?;
252+
join(acme, &admin, "admin", "created").await?;
253+
let staff = person("Sam", "sam@example.com").await?;
254+
let staff_id = staff.id;
255+
db::query!("UPDATE users SET staff = true WHERE id = {staff_id}").update().await?;
256+
let staff = User::find_or_fail(staff_id).await?;
257+
app.get("/api/ui/orgs/acme/members").acting_as(&staff).await.assert_status(404);
258+
app.post("/api/ui/orgs/acme/invitations")
259+
.acting_as(&staff)
260+
.header("sec-fetch-site", "same-origin")
261+
.json(json!({ "invitee": "eve@example.com", "role": "admin" }))
262+
.await
263+
.assert_status(404);
264+
Ok(())
265+
}

0 commit comments

Comments
 (0)