diff --git a/app/src/auth/memberships.rs b/app/src/auth/memberships.rs new file mode 100644 index 00000000..38ac485e --- /dev/null +++ b/app/src/auth/memberships.rs @@ -0,0 +1,164 @@ +//! Memberships that follow the forge (sc-8900, the auth side), ported from today's `access::after_sign_in` and +//! `memberships::apply_forge`. When someone signs in, the repositories the forge says they can reach decide their +//! memberships in the organizations whose projects link those repositories: their highest permission across an +//! organization's linked repositories becomes their role there. Only memberships the forge granted +//! (`source = github|gitlab`) are changed or removed; one made by an invitation, at sign-up or by staff stays. +//! An organization whose projects of this forge are on another site (gitlab.com and a self-managed GitLab) keeps the +//! memberships that site decides. + +use std::collections::{HashMap, HashSet}; + +use laravel::db; +use laravel::event::{Event, listener}; + +use super::Role; +use super::sign_in::SignedIn; +use crate::forge::{ForgeKind, Permission, Repository}; + +/// A membership was added, changed or removed (role `None`), for the member's notice (emails, sc-8900). +#[derive(laravel::event::Event, Clone, Debug)] +pub struct MembershipChanged { + pub organization_id: i64, + pub user_id: i64, + pub role: Option, +} + +#[derive(Debug)] +struct LinkedProject { + organization_id: i64, + /// The forge's permanent ID for the repository. A link without one grants nothing until it's backfilled. + repository_id: String, + site: String, +} + +/// The projects linked to a repository on `forge` whose repository ID is known, with the site each is on: '' for +/// github.com and gitlab.com, and a self-managed GitLab's base URL otherwise, as a sign-in's identity names it. +async fn linked_projects(forge: ForgeKind) -> laravel::Result> { + let forge_name = forge.as_str(); + let rows = db::query!( + "SELECT organization_id, repository_url, repository_id FROM projects \ + WHERE forge = {forge_name} AND repository_url IS NOT NULL AND repository_id IS NOT NULL \ + AND forge_installation IS NOT NULL" + ) + .select() + .await?; + let mut out = Vec::new(); + for row in rows { + let (organization_id, repository_url, repository_id): (i64, String, String) = + (row.try_get("organization_id")?, row.try_get("repository_url")?, row.try_get("repository_id")?); + let site = match forge { + ForgeKind::Github => String::new(), + ForgeKind::Gitlab => match Repository::parse_gitlab(&repository_url) { + Some(r) if r.site_url().eq_ignore_ascii_case("https://gitlab.com") => String::new(), + Some(r) => r.site_url().to_ascii_lowercase(), + None => continue, + }, + }; + out.push(LinkedProject { organization_id, repository_id, site }); + } + Ok(out) +} + +/// Each organization's role from the person's permissions on its linked repositories, matched by the forge's +/// repository ID and never by URL: a renamed repository's old URL can be taken by someone else's new repository, +/// whose owner mustn't get a role in the organization that linked the old one. The highest permission wins. +fn grants_from(projects: &[&LinkedProject], permissions: &HashMap) -> HashMap { + let mut grants: HashMap = HashMap::new(); + for p in projects { + if let Some(permission) = permissions.get(&p.repository_id) { + let role = permission.role(); + let entry = grants.entry(p.organization_id).or_insert(role); + *entry = (*entry).max(role); + } + } + grants +} + +/// Apply a sign-in's grants: add or change the forge's memberships, and remove the forge's memberships in scope that +/// it no longer grants. `repositories` are the ones the forge lists the person as having explicit access to (a +/// collaborator, a team member or an organization member; never the read-for-everyone of a public repository); one +/// without the forge's ID grants nothing. It all happens in one transaction with the person's memberships locked, +/// so two sign-ins at once can't interleave, and the notices go after it commits. Returns how many changed. +/// +/// # Errors +/// On a database error. +pub async fn apply( + user_id: i64, + forge: ForgeKind, + site: &str, + repositories: &[(Repository, Permission)], +) -> laravel::Result { + let permissions: HashMap = + repositories.iter().filter_map(|(r, p)| r.id.clone().map(|id| (id, *p))).collect(); + let all = linked_projects(forge).await?; + let here: Vec<&LinkedProject> = all.iter().filter(|p| p.site == site).collect(); + let elsewhere: HashSet = all.iter().filter(|p| p.site != site).map(|p| p.organization_id).collect(); + let grants = grants_from(&here, &permissions); + let source = forge.as_str(); + + let notices = db::transaction(async |tx| { + let rows = db::query!( + tx, + "SELECT organization_id, role, source FROM memberships WHERE user_id = {user_id} FOR UPDATE" + ) + .select() + .await?; + let mut existing: HashMap = HashMap::new(); + for row in rows { + existing.insert(row.try_get("organization_id")?, (row.try_get("role")?, row.try_get("source")?)); + } + let mut notices: Vec<(i64, Option)> = Vec::new(); + for (org, role) in &grants { + let (org, role_name) = (*org, role.as_str()); + match existing.get(&org) { + Some((current, src)) if src == source => { + db::query!( + tx, + "UPDATE memberships SET role = {role_name}, synced_at = now(), updated_at = now() \ + WHERE organization_id = {org} AND user_id = {user_id}" + ) + .update() + .await?; + if current != role_name { + notices.push((org, Some(*role))); + } + } + // Invited, made at sign-up, or added by staff: the forge doesn't change it + Some(_) => {} + None => { + db::query!( + tx, + "INSERT INTO memberships (organization_id, user_id, role, source, synced_at, created_at, updated_at) \ + VALUES ({org}, {user_id}, {role_name}, {source}, now(), now(), now()) \ + ON CONFLICT DO NOTHING" + ) + .insert() + .await?; + notices.push((org, Some(*role))); + } + } + } + for (org, (_, src)) in &existing { + let org = *org; + if src == source && !elsewhere.contains(&org) && !grants.contains_key(&org) { + db::query!(tx, "DELETE FROM memberships WHERE organization_id = {org} AND user_id = {user_id}") + .delete() + .await?; + notices.push((org, None)); + } + } + Ok(notices) + }) + .await?; + for (org, role) in ¬ices { + MembershipChanged { organization_id: *org, user_id, role: *role }.dispatch().await?; + } + Ok(notices.len()) +} + +/// After a sign-in: memberships follow the repositories the forge says they can reach. +#[listener] +pub async fn follow_the_forge(event: Event) -> laravel::Result<()> { + apply(event.user_id, event.forge, &event.site, &event.repositories).await?; + Ok(()) +} diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index ae775820..6e1edfa9 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -8,6 +8,7 @@ //! //! Nobody found: `401`. +pub mod memberships; pub mod oauth; pub mod sign_in; diff --git a/app/tests/memberships.rs b/app/tests/memberships.rs new file mode 100644 index 00000000..f4fe3b74 --- /dev/null +++ b/app/tests/memberships.rs @@ -0,0 +1,132 @@ +//! Memberships follow the forge: a sign-in's repositories decide the person's memberships in the organizations that +//! link them, and only the forge's own memberships change. + +use app::auth::memberships::apply; +use app::forge::{ForgeKind, Permission, Repository}; +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +async fn org(slug: &str) -> laravel::Result { + Ok(db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) VALUES (gen_random_uuid(), {slug}, {slug}, now(), now()) RETURNING id" + ) + .scalar::() + .await? + .expect("an id")) +} + +/// A project linking `url`, whose repository GitHub knows as `id` (the tests use the path). +async fn project(org: i64, slug: &str, url: &str) -> laravel::Result<()> { + let id = url.trim_start_matches("https://github.com/"); + project_with_id(org, slug, url, Some(id)).await +} + +async fn project_with_id(org: i64, slug: &str, url: &str, id: Option<&str>) -> laravel::Result<()> { + db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, forge_installation, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, {slug}, {slug}, 'github', {url}, {id}, '1', now(), now())" + ) + .insert() + .await?; + Ok(()) +} + +async fn role(org: i64, user: i64) -> laravel::Result> { + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {user}").scalar().await +} + +/// A repository from a sign-in, with GitHub's ID for it (the tests use the path). +fn repo(path: &str) -> Repository { + Repository::parse(path).expect("a repository").with_id(Some(path.to_string())) +} + +#[laravel::test] +async fn sign_ins_add_change_and_remove_the_forges_memberships(_app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let (acme, globex, invited) = (org("acme").await?, org("globex").await?, org("initech").await?); + project(acme, "web", "https://github.com/acme/web").await?; + project(acme, "api", "https://github.com/acme/api").await?; + project(globex, "app", "https://github.com/globex/app").await?; + project(invited, "x", "https://github.com/initech/x").await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({invited}, {ada_id}, 'admin', 'invite', now(), now())" + ) + .insert() + .await?; + + // Write on one of acme's repositories and admin on the other: admin wins. Read on globex's. + let reach = vec![ + (repo("acme/web"), Permission::Write), + (repo("acme/api"), Permission::Admin), + (repo("globex/app"), Permission::Read), + (repo("initech/x"), Permission::Read), + ]; + assert_eq!(apply(ada.id, ForgeKind::Github, "", &reach).await?, 2); + assert_eq!(role(acme, ada.id).await?.as_deref(), Some("admin")); + assert_eq!(role(globex, ada.id).await?.as_deref(), Some("read")); + assert_eq!(role(invited, ada.id).await?.as_deref(), Some("admin"), "an invitation's membership stays as it is"); + + // Next sign-in: write on acme's web only, nothing at globex + let reach = vec![(repo("acme/web"), Permission::Write)]; + assert_eq!(apply(ada.id, ForgeKind::Github, "", &reach).await?, 2); + assert_eq!(role(acme, ada.id).await?.as_deref(), Some("member")); + assert_eq!(role(globex, ada.id).await?, None, "the forge's membership goes"); + assert_eq!(role(invited, ada.id).await?.as_deref(), Some("admin"), "the invited one doesn't"); + Ok(()) +} + +#[laravel::test] +async fn a_repository_at_the_same_url_but_another_id_grants_nothing(_app: Application) -> laravel::Result<()> { + // acme linked acme/web, then renamed it; someone else made a new acme/web and signs in as its admin + let eve = create!(User { pid: laravel::str::uuid7(), name: "Eve", email: "eve@example.com", staff: false }).await?; + let acme = org("acme").await?; + project_with_id(acme, "web", "https://github.com/acme/web", Some("1001")).await?; + // And a link whose ID isn't known yet grants nothing until it's backfilled + let other = org("other").await?; + project_with_id(other, "app", "https://github.com/other/app", None).await?; + let new_repo = Repository::parse("acme/web").unwrap().with_id(Some("2002".into())); + let other_repo = Repository::parse("other/app").unwrap().with_id(Some("3003".into())); + let changed = + apply(eve.id, ForgeKind::Github, "", &[(new_repo, Permission::Admin), (other_repo, Permission::Admin)]).await?; + assert_eq!(changed, 0); + assert_eq!(role(acme, eve.id).await?, None); + assert_eq!(role(other, eve.id).await?, None); + // Without an ID from the forge, a repository grants nothing either + let unknown = Repository::parse("acme/web").unwrap(); + assert_eq!(apply(eve.id, ForgeKind::Github, "", &[(unknown, Permission::Admin)]).await?, 0); + Ok(()) +} + +/// A sign-in's repositories are the ones GitHub lists for the person through the App's installations, which are only +/// those they have explicit access to (owner, collaborator, team or organization member). A public repository they can +/// merely read isn't listed, so the organization linking it gets no member. +#[laravel::test] +async fn only_explicit_access_through_the_installation_grants_a_membership(app: Application) -> laravel::Result<()> { + use laravel::auth::social::{self, Provider}; + use laravel::http::client; + let _github = client::fake() + .with("api.github.com/user/emails*", json!([{ "email": "ada@example.com", "primary": true, "verified": true }])) + .with( + "api.github.com/user/installations/*/repositories*", + json!({ "repositories": [ + { "id": 9, "full_name": "acme/web", "permissions": { "admin": false, "push": true, "pull": true } }, + ] }), + ) + .with("api.github.com/user/installations*", json!({ "installations": [{ "id": 1 }] })); + let _social = social::fake().with( + Provider::GITHUB, + social::User::fake("gh-1").name("Ada").raw(json!({ "login": "ada" })).verified_email("ada@example.com"), + ); + let (acme, public) = (org("acme").await?, org("public").await?); + project_with_id(acme, "web", "https://github.com/acme/web", Some("9")).await?; + project_with_id(public, "lib", "https://github.com/public/lib", Some("77")).await?; + app.get("/auth/github/callback").await.assert_redirect(); + let ada = User::first_where(User::email.eq("ada@example.com")).await?.expect("an account"); + assert_eq!(role(acme, ada.id).await?.as_deref(), Some("member")); + assert_eq!(role(public, ada.id).await?, None, "reading a public repository makes nobody a member"); + Ok(()) +}