|
| 1 | +//! Memberships that follow the forge (sc-8900, the auth side), ported from today's `access::after_sign_in` and |
| 2 | +//! `memberships::apply_forge`. When someone signs in, the repositories the forge says they can reach decide their |
| 3 | +//! memberships in the organizations whose projects link those repositories: their highest permission across an |
| 4 | +//! organization's linked repositories becomes their role there. Only memberships the forge granted |
| 5 | +//! (`source = github|gitlab`) are changed or removed; one made by an invitation, at sign-up or by staff stays. |
| 6 | +//! An organization whose projects of this forge are on another site (gitlab.com and a self-managed GitLab) keeps the |
| 7 | +//! memberships that site decides. |
| 8 | +
|
| 9 | +use std::collections::{HashMap, HashSet}; |
| 10 | + |
| 11 | +use laravel::db; |
| 12 | +use laravel::event::{Event, listener}; |
| 13 | + |
| 14 | +use super::Role; |
| 15 | +use super::sign_in::SignedIn; |
| 16 | +use crate::forge::{ForgeKind, Permission, Repository}; |
| 17 | + |
| 18 | +/// A membership was added, changed or removed (role `None`), for the member's notice (emails, sc-8900). |
| 19 | +#[derive(laravel::event::Event, Clone, Debug)] |
| 20 | +pub struct MembershipChanged { |
| 21 | + pub organization_id: i64, |
| 22 | + pub user_id: i64, |
| 23 | + pub role: Option<Role>, |
| 24 | +} |
| 25 | + |
| 26 | +#[derive(Debug)] |
| 27 | +struct LinkedProject { |
| 28 | + organization_id: i64, |
| 29 | + repository_url: String, |
| 30 | + site: String, |
| 31 | +} |
| 32 | + |
| 33 | +/// The projects linked to a repository on `forge`, with the site each is on ('' for github.com and VisualCI's own |
| 34 | +/// GitLab, a self-managed instance's base URL otherwise). |
| 35 | +async fn linked_projects(forge: ForgeKind, own_gitlab: &str) -> laravel::Result<Vec<LinkedProject>> { |
| 36 | + let forge_name = forge.as_str(); |
| 37 | + let rows = db::query!( |
| 38 | + "SELECT organization_id, repository_url FROM projects \ |
| 39 | + WHERE forge = {forge_name} AND repository_url IS NOT NULL AND forge_installation IS NOT NULL" |
| 40 | + ) |
| 41 | + .select() |
| 42 | + .await?; |
| 43 | + let own = own_gitlab.trim_end_matches('/').to_ascii_lowercase(); |
| 44 | + let mut out = Vec::new(); |
| 45 | + for row in rows { |
| 46 | + let (organization_id, repository_url): (i64, String) = |
| 47 | + (row.try_get("organization_id")?, row.try_get("repository_url")?); |
| 48 | + let site = match forge { |
| 49 | + ForgeKind::Github => String::new(), |
| 50 | + ForgeKind::Gitlab => match Repository::parse_gitlab(&repository_url) { |
| 51 | + Some(r) if r.site_url().to_ascii_lowercase() != own => r.site_url().to_ascii_lowercase(), |
| 52 | + Some(_) => String::new(), |
| 53 | + None => continue, |
| 54 | + }, |
| 55 | + }; |
| 56 | + out.push(LinkedProject { organization_id, repository_url, site }); |
| 57 | + } |
| 58 | + Ok(out) |
| 59 | +} |
| 60 | + |
| 61 | +/// Each organization's role from the person's permissions on its linked repositories: the highest one wins. |
| 62 | +fn grants_from(projects: &[&LinkedProject], permissions: &HashMap<String, Permission>) -> HashMap<i64, Role> { |
| 63 | + let mut grants: HashMap<i64, Role> = HashMap::new(); |
| 64 | + for p in projects { |
| 65 | + if let Some(permission) = permissions.get(&p.repository_url.to_lowercase()) { |
| 66 | + let role = permission.role(); |
| 67 | + let entry = grants.entry(p.organization_id).or_insert(role); |
| 68 | + *entry = (*entry).max(role); |
| 69 | + } |
| 70 | + } |
| 71 | + grants |
| 72 | +} |
| 73 | + |
| 74 | +/// Apply a sign-in's grants: add or change the forge's memberships, and remove the forge's memberships in scope that |
| 75 | +/// it no longer grants. Returns how many changed. |
| 76 | +/// |
| 77 | +/// # Errors |
| 78 | +/// On a database error. |
| 79 | +pub async fn apply( |
| 80 | + user_id: i64, |
| 81 | + forge: ForgeKind, |
| 82 | + site: &str, |
| 83 | + repositories: &[(Repository, Permission)], |
| 84 | + own_gitlab: &str, |
| 85 | +) -> laravel::Result<usize> { |
| 86 | + let permissions: HashMap<String, Permission> = |
| 87 | + repositories.iter().map(|(r, p)| (r.url.to_lowercase(), *p)).collect(); |
| 88 | + let all = linked_projects(forge, own_gitlab).await?; |
| 89 | + let here: Vec<&LinkedProject> = all.iter().filter(|p| p.site == site).collect(); |
| 90 | + let elsewhere: HashSet<i64> = all.iter().filter(|p| p.site != site).map(|p| p.organization_id).collect(); |
| 91 | + let grants = grants_from(&here, &permissions); |
| 92 | + |
| 93 | + let source = forge.as_str(); |
| 94 | + let rows = |
| 95 | + db::query!("SELECT organization_id, role, source FROM memberships WHERE user_id = {user_id}").select().await?; |
| 96 | + let mut existing: HashMap<i64, (String, String)> = HashMap::new(); |
| 97 | + for row in rows { |
| 98 | + existing.insert(row.try_get("organization_id")?, (row.try_get("role")?, row.try_get("source")?)); |
| 99 | + } |
| 100 | + let mut changed = 0; |
| 101 | + for (org, role) in &grants { |
| 102 | + let (org, role_name) = (*org, role.as_str()); |
| 103 | + match existing.get(&org) { |
| 104 | + Some((current, src)) if src == source => { |
| 105 | + db::query!( |
| 106 | + "UPDATE memberships SET role = {role_name}, synced_at = now(), updated_at = now() \ |
| 107 | + WHERE organization_id = {org} AND user_id = {user_id}" |
| 108 | + ) |
| 109 | + .update() |
| 110 | + .await?; |
| 111 | + if current != role_name { |
| 112 | + changed += 1; |
| 113 | + MembershipChanged { organization_id: org, user_id, role: Some(*role) }.dispatch().await?; |
| 114 | + } |
| 115 | + } |
| 116 | + // Invited, made at sign-up, or added by staff: the forge doesn't change it |
| 117 | + Some(_) => {} |
| 118 | + None => { |
| 119 | + db::query!( |
| 120 | + "INSERT INTO memberships (organization_id, user_id, role, source, synced_at, created_at, updated_at) \ |
| 121 | + VALUES ({org}, {user_id}, {role_name}, {source}, now(), now(), now())" |
| 122 | + ) |
| 123 | + .insert() |
| 124 | + .await?; |
| 125 | + changed += 1; |
| 126 | + MembershipChanged { organization_id: org, user_id, role: Some(*role) }.dispatch().await?; |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + for (org, (_, src)) in &existing { |
| 131 | + let org = *org; |
| 132 | + if src == source && !elsewhere.contains(&org) && !grants.contains_key(&org) { |
| 133 | + db::query!("DELETE FROM memberships WHERE organization_id = {org} AND user_id = {user_id}") |
| 134 | + .delete() |
| 135 | + .await?; |
| 136 | + changed += 1; |
| 137 | + MembershipChanged { organization_id: org, user_id, role: None }.dispatch().await?; |
| 138 | + } |
| 139 | + } |
| 140 | + Ok(changed) |
| 141 | +} |
| 142 | + |
| 143 | +/// VisualCI's own GitLab (`VISUALCI_GITLAB_URL`, default gitlab.com): its projects' memberships are decided by |
| 144 | +/// sign-ins there, like github.com's. |
| 145 | +#[derive(Clone, Debug, laravel::config::Section)] |
| 146 | +pub struct OwnGitlab { |
| 147 | + #[env("VISUALCI_GITLAB_URL", default = "https://gitlab.com")] |
| 148 | + pub url: String, |
| 149 | +} |
| 150 | + |
| 151 | +/// After a sign-in: memberships follow the repositories the forge says they can reach. |
| 152 | +#[listener] |
| 153 | +pub async fn follow_the_forge( |
| 154 | + event: Event<SignedIn>, |
| 155 | + gitlab: laravel::config::Section<OwnGitlab>, |
| 156 | +) -> laravel::Result<()> { |
| 157 | + apply(event.user_id, event.forge, &event.site, &event.repositories, &gitlab.url).await?; |
| 158 | + Ok(()) |
| 159 | +} |
0 commit comments