Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
1,605 linesCodeBlameRaw
1//! Who has access to a repository: roles given on one repository, the
2//! invitations that offer them, and each workspace's base permission.
3//!
4//! The rules (which role may do what, and how a person's role is worked
5//! out) live in `g1t_contracts::access`; this is where the roles are kept.
6//! Every user identity resolves carries their grants ([`Identity::grants_of`],
7//! under the workspace's policy) beside their memberships, so services
8//! decide with `access::can` and never call here to authorize.
9//!
10//! **Adding someone** to a repository (Admin only, a person, never an
11//! agent's or a workspace's token):
12//!
13//! - a member of its workspace gets the role at once: it only matters when
14//! it is higher than the base permission;
15//! - anyone else with an account (by username, or a confirmed address) is
16//! sent an invitation, which they accept or decline; it lasts
17//! [`INVITATION_DAYS`];
18//! - an address without an account is sent an invite code (invites.rs,
19//! charged as a workspace invite is) that makes the account and accepts.
20//!
21//! Accepting is checked against the workspace's policy (security.rs), as
22//! joining it is. Removing someone from a workspace takes away their roles
23//! on its repositories (workspaces.rs); a repository that is purged takes
24//! its grants and invitations with it (`forget_repo_access`); a transfer or
25//! rename keeps them (deletion.rs, `transfer_repo_scopes`).
26//!
27//! **Teams** are another `principal_kind` in `repo_grants` (teams.rs):
28//! [`Identity::grants_of`] resolves a team's grants into the same
29//! `RepoGrant`s for each person in the team and in its child teams, and
30//! the access list shows where such a role comes from.
31
32use g1t_contracts::access::*;
33use g1t_contracts::audit::{AuditActor, AuditOutcome, AuditTarget, NewAuditEntry, RecordAuditArgs, Surface};
34use g1t_contracts::events::{NewEvent, Publish, RepoCollaborator};
35use g1t_contracts::repos::{GetArgs, Repo, RepoPath};
36use g1t_contracts::time::{SQL_NOW, rfc3339};
37use g1t_contracts::{FailureCode, Outcome, PrincipalKind, Role, User, Viewer, new_id};
38use g1t_kit::now_ms;
39use serde::{Deserialize, Serialize};
40use worker::Result;
41use worker::wasm_bindgen::JsValue;
42
43use crate::Identity;
44use crate::invites::normalize_email;
45
46/// How long an invitation to someone with an account waits for an answer.
47pub const INVITATION_DAYS: u64 = 7;
48/// The most direct grants one person carries on every request.
49const MAX_GRANTS: u32 = 1000;
50/// The most people or invitations one list shows.
51const LIST_LIMIT: u32 = 500;
52
53const PEOPLE_ONLY: &str =
54 "Only a person can change who has access to a repository, signed in as themselves; never an agent's or a workspace's token.";
55const CONFIRM_FIRST: &str = "Confirm your email address before changing who has access.";
56const NO_SUCH_USER: &str = "There is no account with that username.";
57
58/// What was typed into "Add people".
59#[derive(Debug, PartialEq, Eq)]
60pub enum Invitee {
61 Username(String),
62 Email(String),
63}
64
65/// A username, or an email address, as typed; `None` if it is neither.
66pub fn invitee(text: &str) -> Option<Invitee> {
67 let text = text.trim().trim_start_matches('@');
68 if text.contains('@') {
69 return normalize_email(text).map(Invitee::Email);
70 }
71 let name = text.to_lowercase();
72 g1t_contracts::is_valid_namespace(&name).then_some(Invitee::Username(name))
73}
74
75/// A person's role on a repository, and where it comes from: ownership,
76/// the base permission, a team's grant, or a direct grant. The highest
77/// wins; on a tie a direct grant is shown first, then a team's, so a role
78/// is shown where it can be changed.
79pub fn effective(
80 owner: bool,
81 base: Option<RepoRole>,
82 direct: Option<RepoRole>,
83 team: Option<RepoRole>,
84) -> Option<(RepoRole, AccessSource)> {
85 if owner {
86 return Some((RepoRole::Admin, AccessSource::Owner));
87 }
88 let mut best = base.map(|role| (role, AccessSource::Base));
89 for (role, source) in [(team, AccessSource::Team), (direct, AccessSource::Direct)] {
90 if let Some(role) = role
91 && best.is_none_or(|(had, _)| role >= had)
92 {
93 best = Some((role, source));
94 }
95 }
96 best
97}
98
99/// Where an invitation stands at `now`.
100pub fn invitation_status(row: &InvitationRow, now: &str) -> RepoInvitationStatus {
101 if row.accepted_at.is_some() {
102 RepoInvitationStatus::Accepted
103 } else if row.declined_at.is_some() {
104 RepoInvitationStatus::Declined
105 } else if row.revoked_at.is_some() {
106 RepoInvitationStatus::Revoked
107 } else if row.expires_at.as_str() <= now {
108 RepoInvitationStatus::Expired
109 } else {
110 RepoInvitationStatus::Pending
111 }
112}
113
114#[derive(Deserialize)]
115struct GrantRow {
116 repo_id: String,
117 workspace: String,
118 role: String,
119 #[serde(default)]
120 team: Option<String>,
121 /// Whether the grant's workspace requires two-factor authentication.
122 #[serde(default)]
123 require_two_factor: u8,
124}
125
126/// The highest role a team gives each person on a repository, and that
127/// team's slug, by user id.
128pub(crate) type TeamRoles = std::collections::HashMap<String, (RepoRole, String)>;
129
130/// Folds (user id, role, team slug) rows into each person's highest; on a
131/// tie, the first slug, so the answer never flips.
132pub(crate) fn highest_team_roles(rows: impl IntoIterator<Item = (String, RepoRole, String)>) -> TeamRoles {
133 let mut roles = TeamRoles::new();
134 for (user_id, role, team) in rows {
135 let entry = roles.entry(user_id).or_insert((role, team.clone()));
136 if role > entry.0 || (role == entry.0 && team < entry.1) {
137 *entry = (role, team);
138 }
139 }
140 roles
141}
142
143#[derive(Clone, Debug, Default, Deserialize)]
144pub struct InvitationRow {
145 pub id: String,
146 pub repo_id: String,
147 pub workspace: String,
148 pub workspace_id: String,
149 pub repo_name: String,
150 pub invitee: Option<String>,
151 pub email: Option<String>,
152 pub invite_id: Option<String>,
153 pub role: String,
154 pub inviter_id: Option<String>,
155 pub inviter: Option<String>,
156 #[serde(default)]
157 pub inviter_avatar: Option<String>,
158 pub created_at: String,
159 pub expires_at: String,
160 pub accepted_at: Option<String>,
161 pub declined_at: Option<String>,
162 pub revoked_at: Option<String>,
163}
164
165impl InvitationRow {
166 fn role(&self) -> RepoRole {
167 RepoRole::parse(&self.role).unwrap_or(RepoRole::Read)
168 }
169
170 fn shown(&self, now: &str, with_email: bool) -> RepoInvitation {
171 RepoInvitation {
172 id: self.id.clone(),
173 repo: format!("{}/{}", self.workspace, self.repo_name),
174 repo_id: self.repo_id.clone(),
175 invitee: self.invitee.clone(),
176 email: if with_email { self.email.clone() } else { None },
177 role: self.role(),
178 invited_by: self.inviter.clone(),
179 inviter_avatar: self.inviter_avatar.clone(),
180 status: invitation_status(self, now),
181 created_at: self.created_at.clone(),
182 expires_at: self.expires_at.clone(),
183 }
184 }
185}
186
187const INVITATION_COLUMNS: &str = "ri.id, ri.repo_id, w.slug AS workspace, ri.workspace_id, ri.repo_name,
188 ri.invitee_id, invitee.username AS invitee, ri.email, ri.invite_id, ri.role, ri.inviter_id, inviter.username AS inviter, inviter.avatar AS inviter_avatar,
189 ri.created_at, ri.expires_at, ri.accepted_at, ri.declined_at, ri.revoked_at
190 FROM repo_invitations ri
191 JOIN workspaces w ON w.id = ri.workspace_id AND w.deleted_at IS NULL
192 LEFT JOIN users invitee ON invitee.id = ri.invitee_id
193 LEFT JOIN users inviter ON inviter.id = ri.inviter_id";
194
195/// A person as an access list shows them.
196#[derive(Deserialize)]
197struct PersonRow {
198 id: String,
199 username: String,
200 name: Option<String>,
201 avatar: Option<String>,
202 /// `owner` or `member`; null when they are not in the workspace.
203 #[serde(default)]
204 workspace_role: Option<String>,
205 /// Their direct grant on the repository, if any.
206 #[serde(default)]
207 direct: Option<String>,
208}
209
210#[derive(Deserialize)]
211struct Id {
212 id: String,
213}
214
215#[derive(Deserialize)]
216struct Base {
217 base_permission: String,
218}
219
220/// A repository by id and path: what events and the audit log name.
221#[derive(Clone, Copy)]
222pub(crate) struct Named<'a> {
223 pub id: &'a str,
224 pub namespace: &'a str,
225 pub name: &'a str,
226}
227
228impl<'a> From<&'a Repo> for Named<'a> {
229 fn from(repo: &'a Repo) -> Self {
230 Named {
231 id: &repo.id,
232 namespace: &repo.namespace,
233 name: &repo.name,
234 }
235 }
236}
237
238/// A repository someone may manage the access of, with its workspace's id.
239pub(crate) struct Target {
240 pub repo: Repo,
241 pub workspace_id: String,
242}
243
244fn opt(value: Option<&str>) -> JsValue {
245 value.map_or(JsValue::NULL, JsValue::from)
246}
247
248fn full_name(repo: &Repo) -> String {
249 format!("{}/{}", repo.namespace, repo.name)
250}
251
252impl Identity {
253 /// Every repository `user_id` has a role on, directly or through a
254 /// team they are in (or through that team's parents, whose roles child
255 /// teams inherit), with the slug of its workspace now. Attached to
256 /// every user resolved from credentials.
257 ///
258 /// Each comes with whether its workspace requires two-factor
259 /// authentication (security.rs).
260 pub async fn grants_of(&self, user_id: &str) -> Result<Vec<(RepoGrant, bool)>> {
261 let rows = self
262 .db
263 .prepare(format!(
264 "WITH RECURSIVE mine(id) AS (
265 SELECT team_id FROM team_members WHERE user_id = ?1
266 UNION
267 SELECT t.parent_id FROM teams t JOIN mine ON t.id = mine.id WHERE t.parent_id IS NOT NULL
268 )
269 SELECT g.repo_id, w.slug AS workspace, g.role, NULL AS team, w.require_two_factor FROM repo_grants g
270 JOIN workspaces w ON w.id = g.workspace_id AND w.deleted_at IS NULL
271 WHERE g.principal_kind = 'user' AND g.principal_id = ?1
272 UNION ALL
273 SELECT g.repo_id, w.slug AS workspace, g.role, t.slug AS team, w.require_two_factor FROM repo_grants g
274 JOIN mine ON g.principal_kind = 'team' AND g.principal_id = mine.id
275 JOIN teams t ON t.id = g.principal_id
276 JOIN workspaces w ON w.id = g.workspace_id AND w.deleted_at IS NULL
277 LIMIT {MAX_GRANTS}"
278 ))
279 .bind(&[user_id.into()])?
280 .all()
281 .await?
282 .results::<GrantRow>()?;
283 Ok(rows
284 .into_iter()
285 .filter_map(|row| {
286 Some((
287 RepoGrant {
288 repo_id: row.repo_id,
289 workspace: row.workspace,
290 role: RepoRole::parse(&row.role)?,
291 team: row.team,
292 },
293 row.require_two_factor != 0,
294 ))
295 })
296 .collect())
297 }
298
299 /// The repository at `path` as `viewer` sees it: missing when they
300 /// cannot read it. Asked of repos, which owns visibility.
301 pub(crate) async fn repo_for(&self, path: &RepoPath, viewer: &Viewer) -> Result<Option<Repo>> {
302 let repos = self.env.service("REPOS")?;
303 let found: Outcome<Repo> = g1t_kit::call(
304 &repos,
305 "get",
306 &GetArgs {
307 path: path.clone(),
308 viewer: viewer.clone(),
309 },
310 )
311 .await?;
312 Ok(match found {
313 // A pull request's working copy has no access of its own.
314 Outcome::Ok(repo) if repo.fork_of.is_none() => Some(repo),
315 _ => None,
316 })
317 }
318
319 /// The highest role a team gives each person on a repository: the
320 /// teams with a grant on it, and their child teams, whose people
321 /// inherit it. `user_id` narrows it to one person.
322 pub(crate) async fn team_roles_on(&self, repo_id: &str, user_id: Option<&str>) -> Result<TeamRoles> {
323 #[derive(Deserialize)]
324 struct Row {
325 user_id: String,
326 role: String,
327 via: String,
328 }
329 let rows = self
330 .db
331 .prepare(
332 "WITH RECURSIVE reach(id, role, via) AS (
333 SELECT g.principal_id, g.role, t.slug FROM repo_grants g JOIN teams t ON t.id = g.principal_id
334 WHERE g.repo_id = ?1 AND g.principal_kind = 'team'
335 UNION
336 SELECT c.id, reach.role, reach.via FROM teams c JOIN reach ON c.parent_id = reach.id
337 )
338 SELECT tm.user_id, reach.role, reach.via FROM reach JOIN team_members tm ON tm.team_id = reach.id
339 WHERE ?2 IS NULL OR tm.user_id = ?2",
340 )
341 .bind(&[repo_id.into(), opt(user_id)])?
342 .all()
343 .await?
344 .results::<Row>()?;
345 Ok(highest_team_roles(
346 rows.into_iter()
347 .filter_map(|row| Some((row.user_id, RepoRole::parse(&row.role)?, row.via))),
348 ))
349 }
350
351 /// The teams with a role of their own on a repository.
352 pub(crate) async fn teams_on(&self, repo_id: &str) -> Result<Vec<g1t_contracts::teams::RepoTeam>> {
353 #[derive(Deserialize)]
354 struct Row {
355 slug: String,
356 name: String,
357 role: String,
358 visibility: String,
359 members_count: u32,
360 }
361 let rows = self
362 .db
363 .prepare(format!(
364 "SELECT t.slug, t.name, g.role, t.visibility,
365 (SELECT count(*) FROM team_members tm WHERE tm.team_id = t.id) AS members_count
366 FROM repo_grants g JOIN teams t ON t.id = g.principal_id
367 WHERE g.repo_id = ? AND g.principal_kind = 'team'
368 ORDER BY t.name LIMIT {LIST_LIMIT}"
369 ))
370 .bind(&[repo_id.into()])?
371 .all()
372 .await?
373 .results::<Row>()?;
374 Ok(rows
375 .into_iter()
376 .filter_map(|row| {
377 Some(g1t_contracts::teams::RepoTeam {
378 slug: row.slug,
379 name: row.name,
380 role: RepoRole::parse(&row.role)?,
381 members_count: row.members_count,
382 visibility: g1t_contracts::teams::TeamVisibility::parse(&row.visibility).unwrap_or_default(),
383 })
384 })
385 .collect())
386 }
387
388 pub(crate) async fn workspace_id_of(&self, slug: &str) -> Result<Option<String>> {
389 Ok(self
390 .db
391 // A deleted workspace's repositories are nobody's to share.
392 .prepare("SELECT id FROM workspaces WHERE slug = ? AND deleted_at IS NULL")
393 .bind(&[slug.to_lowercase().into()])?
394 .first::<Id>(None)
395 .await?
396 .map(|row| row.id))
397 }
398
399 pub(crate) async fn base_of(&self, workspace_id: &str) -> Result<BasePermission> {
400 Ok(self
401 .db
402 .prepare("SELECT base_permission FROM workspaces WHERE id = ?")
403 .bind(&[workspace_id.into()])?
404 .first::<Base>(None)
405 .await?
406 .and_then(|row| BasePermission::parse(&row.base_permission))
407 .unwrap_or_default())
408 }
409
410 /// The repository at `path`, if `actor` may change who has access to it.
411 pub(crate) async fn manageable(&self, actor: &User, path: &RepoPath) -> Result<Outcome<Target>> {
412 if !crate::security::is_person(actor) {
413 return Ok(Outcome::fail(FailureCode::Forbidden, PEOPLE_ONLY));
414 }
415 let viewer = Some(actor.clone());
416 let Some(repo) = self.repo_for(path, &viewer).await? else {
417 return Ok(Outcome::fail(FailureCode::NotFound, "Repository not found."));
418 };
419 if !can(Some(actor), &repo, Capability::ManageAccess) {
420 return Ok(Outcome::fail(
421 FailureCode::Forbidden,
422 needs(Capability::ManageAccess, &full_name(&repo)),
423 ));
424 }
425 if !actor.verified {
426 return Ok(Outcome::fail(FailureCode::Forbidden, CONFIRM_FIRST));
427 }
428 let Some(workspace_id) = self.workspace_id_of(&repo.namespace).await? else {
429 return Ok(Outcome::fail(FailureCode::NotFound, "Repository not found."));
430 };
431 Ok(Outcome::Ok(Target { repo, workspace_id }))
432 }
433
434 /// The members of the repository's workspace and the people with a
435 /// direct grant on it, each once.
436 async fn people_rows(&self, repo_id: &str, workspace_id: &str) -> Result<Vec<PersonRow>> {
437 self.db
438 .prepare(format!(
439 "SELECT u.id, u.username, u.display_name AS name, u.avatar,
440 m.role AS workspace_role, g.role AS direct
441 FROM users u
442 LEFT JOIN workspace_members m ON m.user_id = u.id AND m.workspace_id = ?2
443 LEFT JOIN repo_grants g ON g.principal_kind = 'user' AND g.principal_id = u.id AND g.repo_id = ?1
444 WHERE m.user_id IS NOT NULL OR g.principal_id IS NOT NULL
445 ORDER BY u.username LIMIT {LIST_LIMIT}"
446 ))
447 .bind(&[repo_id.into(), workspace_id.into()])?
448 .all()
449 .await?
450 .results::<PersonRow>()
451 }
452
453 fn collaborator(row: PersonRow, base: BasePermission, teams: &TeamRoles) -> Option<Collaborator> {
454 let workspace_role = match row.workspace_role.as_deref() {
455 Some("owner") => Some(Role::Owner),
456 Some(_) => Some(Role::Member),
457 None => None,
458 };
459 let direct = row.direct.as_deref().and_then(RepoRole::parse);
460 let base_role = workspace_role.and(base.role());
461 let team = teams.get(&row.id).cloned();
462 let (role, source) = effective(
463 workspace_role == Some(Role::Owner),
464 base_role,
465 direct,
466 team.as_ref().map(|(role, _)| *role),
467 )?;
468 Some(Collaborator {
469 username: row.username,
470 name: row.name,
471 avatar: row.avatar,
472 role,
473 source,
474 direct,
475 workspace_role,
476 team_role: team.as_ref().map(|(role, _)| *role),
477 team: team.map(|(_, slug)| slug),
478 })
479 }
480
481 async fn invitations(&self, filter: &str, binds: &[JsValue]) -> Result<Vec<InvitationRow>> {
482 self.db
483 .prepare(format!("SELECT {INVITATION_COLUMNS} {filter} ORDER BY ri.created_at DESC LIMIT {LIST_LIMIT}"))
484 .bind(binds)?
485 .all()
486 .await?
487 .results::<InvitationRow>()
488 }
489
490 async fn pending_invitations(&self, filter: &str, binds: &[JsValue]) -> Result<Vec<InvitationRow>> {
491 let filter = format!(
492 "{filter} AND ri.accepted_at IS NULL AND ri.declined_at IS NULL AND ri.revoked_at IS NULL
493 AND ri.expires_at > {SQL_NOW}"
494 );
495 self.invitations(&filter, binds).await
496 }
497
498 pub async fn repo_access(&self, a: RepoAccessArgs) -> Result<Outcome<RepoAccess>> {
499 let Some(repo) = self.repo_for(&a.path, &a.viewer).await? else {
500 return Ok(Outcome::fail(FailureCode::NotFound, "Repository not found."));
501 };
502 let viewer_role = a.viewer.as_ref().and_then(|viewer| granted(viewer, (&repo).into()));
503 // Like the list of collaborators: for those who can push.
504 if !viewer_role.is_some_and(|role| role >= RepoRole::Write) {
505 return Ok(Outcome::fail(
506 FailureCode::Forbidden,
507 format!("You need the Write role or higher on {} to see who has access.", full_name(&repo)),
508 ));
509 }
510 let can_manage = can(a.viewer.as_ref(), &repo, Capability::ManageAccess);
511 let Some(workspace_id) = self.workspace_id_of(&repo.namespace).await? else {
512 return Ok(Outcome::fail(FailureCode::NotFound, "Repository not found."));
513 };
514 let base = self.base_of(&workspace_id).await?;
515 let rows = self.people_rows(&repo.id, &workspace_id).await?;
516 let team_roles = self.team_roles_on(&repo.id, None).await?;
517 let teams = self.teams_on(&repo.id).await?;
518 let mut people: Vec<Collaborator> = rows
519 .into_iter()
520 .filter_map(|row| Self::collaborator(row, base, &team_roles))
521 .collect();
522 people.sort_by(|a, b| b.role.cmp(&a.role).then_with(|| a.username.cmp(&b.username)));
523 let invitations = if can_manage {
524 let now = rfc3339(now_ms());
525 self.pending_invitations("WHERE ri.repo_id = ?", &[repo.id.as_str().into()])
526 .await?
527 .iter()
528 .map(|row| row.shown(&now, true))
529 .collect()
530 } else {
531 Vec::new()
532 };
533 Ok(Outcome::Ok(RepoAccess {
534 repo: full_name(&repo),
535 base_permission: base,
536 people,
537 teams,
538 invitations,
539 viewer_role,
540 can_manage,
541 }))
542 }
543
544 /// `can_read_repo`: see `CanReadRepoArgs`.
545 pub(crate) async fn can_read_repo(&self, a: g1t_contracts::access::CanReadRepoArgs) -> Result<bool> {
546 if !a.repo.is_private {
547 return Ok(true);
548 }
549 let Some(workspace_id) = self.workspace_id_of(&a.repo.namespace).await? else {
550 return Ok(false);
551 };
552 if self.policy_refusal(&a.user_id, &a.repo.namespace).await?.is_some() {
553 return Ok(false);
554 }
555 Ok(self.collaborator_on(&a.repo, &workspace_id, &a.user_id).await?.is_some())
556 }
557
558 /// One person's place on the repository, as the access list shows it.
559 pub(crate) async fn collaborator_on(&self, repo: &Repo, workspace_id: &str, user_id: &str) -> Result<Option<Collaborator>> {
560 let base = self.base_of(workspace_id).await?;
561 let teams = self.team_roles_on(&repo.id, Some(user_id)).await?;
562 let row = self
563 .db
564 .prepare(
565 "SELECT u.id, u.username, u.display_name AS name, u.avatar,
566 m.role AS workspace_role, g.role AS direct
567 FROM users u
568 LEFT JOIN workspace_members m ON m.user_id = u.id AND m.workspace_id = ?2
569 LEFT JOIN repo_grants g ON g.principal_kind = 'user' AND g.principal_id = u.id AND g.repo_id = ?1
570 WHERE u.id = ?3",
571 )
572 .bind(&[repo.id.as_str().into(), workspace_id.into(), user_id.into()])?
573 .first::<PersonRow>(None)
574 .await?;
575 Ok(row.and_then(|row| Self::collaborator(row, base, &teams)))
576 }
577
578 pub(crate) async fn person_by_username(&self, username: &str) -> Result<Option<(String, String)>> {
579 #[derive(Deserialize)]
580 struct Person {
581 id: String,
582 username: String,
583 }
584 Ok(self
585 .db
586 .prepare("SELECT id, username FROM users WHERE username = ? AND deleted_at IS NULL")
587 .bind(&[username.trim().trim_start_matches('@').to_lowercase().into()])?
588 .first::<Person>(None)
589 .await?
590 .map(|person| (person.id, person.username)))
591 }
592
593 pub(crate) async fn is_member_of(&self, workspace_id: &str, user_id: &str) -> Result<bool> {
594 Ok(self
595 .db
596 .prepare("SELECT user_id AS id FROM workspace_members WHERE workspace_id = ? AND user_id = ?")
597 .bind(&[workspace_id.into(), user_id.into()])?
598 .first::<Id>(None)
599 .await?
600 .is_some())
601 }
602
603 async fn direct_role(&self, repo_id: &str, user_id: &str) -> Result<Option<RepoRole>> {
604 #[derive(Deserialize)]
605 struct RoleRow {
606 role: String,
607 }
608 Ok(self
609 .db
610 .prepare("SELECT role FROM repo_grants WHERE repo_id = ? AND principal_kind = 'user' AND principal_id = ?")
611 .bind(&[repo_id.into(), user_id.into()])?
612 .first::<RoleRow>(None)
613 .await?
614 .and_then(|row| RepoRole::parse(&row.role)))
615 }
616
617 /// Gives `user_id` `role` on the repository, or changes the role they
618 /// have; returns the role they had before.
619 async fn put_grant(
620 &self,
621 repo_id: &str,
622 workspace_id: &str,
623 repo_name: &str,
624 user_id: &str,
625 role: RepoRole,
626 granted_by: Option<&str>,
627 ) -> Result<Option<RepoRole>> {
628 let previous = self.direct_role(repo_id, user_id).await?;
629 let now = rfc3339(now_ms());
630 self.db
631 .prepare(
632 "INSERT INTO repo_grants
633 (repo_id, principal_kind, principal_id, workspace_id, repo_name, role, granted_by, created_at, updated_at)
634 VALUES (?1, 'user', ?2, ?3, ?4, ?5, ?6, ?7, ?7)
635 ON CONFLICT (repo_id, principal_kind, principal_id)
636 DO UPDATE SET role = excluded.role, workspace_id = excluded.workspace_id,
637 repo_name = excluded.repo_name, updated_at = excluded.updated_at",
638 )
639 .bind(&[
640 repo_id.into(),
641 user_id.into(),
642 workspace_id.into(),
643 repo_name.into(),
644 role.as_str().into(),
645 opt(granted_by),
646 now.as_str().into(),
647 ])?
648 .run()
649 .await?;
650 Ok(previous)
651 }
652
653 /// Why `actor` may not give someone outside the workspace a role on one
654 /// of its repositories: its member privileges leave that to owners
655 /// (`members_can_invite_outside_collaborators`). Read from the workspace
656 /// itself, so an outside collaborator with Admin is held to it too.
657 async fn outside_refusal<T>(&self, actor: &User, namespace: &str, workspace_id: &str) -> Result<Option<Outcome<T>>> {
658 if actor.role_in(&namespace.to_lowercase()) == Some(Role::Owner) || actor.kind == PrincipalKind::Workspace {
659 return Ok(None);
660 }
661 if self.privileges_of(workspace_id).await?.members_can_invite_outside_collaborators {
662 return Ok(None);
663 }
664 Ok(Some(Outcome::fail(
665 FailureCode::Forbidden,
666 format!("Only owners of {namespace} can add people from outside the workspace to its repositories."),
667 )))
668 }
669
670 pub async fn add_collaborator(&self, a: AddCollaboratorArgs) -> Result<Outcome<Added>> {
671 let Target { repo, workspace_id } = match self.manageable(&a.actor, &a.path).await? {
672 Outcome::Ok(target) => target,
673 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
674 };
675 let surface = a.surface.unwrap_or(Surface::Web);
676 let invitee = match invitee(&a.invitee) {
677 Some(invitee) => invitee,
678 None => return Ok(Outcome::fail(FailureCode::Invalid, "Enter a username or an email address.")),
679 };
680 // Who it names: an account by username, or by a confirmed address.
681 let person = match &invitee {
682 Invitee::Username(name) => match self.person_by_username(name).await? {
683 Some(person) => Some(person),
684 None => return Ok(Outcome::fail(FailureCode::NotFound, NO_SUCH_USER)),
685 },
686 Invitee::Email(email) => match self.user_with_verified_email(email).await? {
687 Some(id) => self
688 .find_public_user(
689 "SELECT id, username, email_verified_at IS NOT NULL AS verified FROM users WHERE id = ?",
690 &id,
691 )
692 .await?
693 .map(|user| (user.id, user.username)),
694 None => None,
695 },
696 };
697 let Some((user_id, username)) = person else {
698 let Invitee::Email(email) = invitee else {
699 return Ok(Outcome::fail(FailureCode::NotFound, NO_SUCH_USER));
700 };
701 if let Some(refused) = self.outside_refusal(&a.actor, &repo.namespace, &workspace_id).await? {
702 return Ok(refused);
703 }
704 // An address is always someone from outside: a free workspace
705 // invites no one (paid.rs).
706 if let Some(refused) = self.free_workspace_refusal(&repo.namespace).await? {
707 return Ok(refused);
708 }
709 return self.invite_address(&a.actor, &repo, &workspace_id, &email, a.role, surface).await;
710 };
711 // What the workspace asks of anyone with access to it (security.rs).
712 if let Some(why) = self.policy_refusal(&user_id, &repo.namespace).await? {
713 return Ok(Outcome::fail(FailureCode::Forbidden, why));
714 }
715 if self.is_member_of(&workspace_id, &user_id).await? {
716 let previous = self
717 .put_grant(&repo.id, &workspace_id, &repo.name, &user_id, a.role, Some(&a.actor.id))
718 .await?;
719 self.changed(&a.actor, (&repo).into(), &username, Some(a.role), previous, surface).await;
720 let Some(collaborator) = self.collaborator_on(&repo, &workspace_id, &user_id).await? else {
721 return Ok(Outcome::fail(FailureCode::NotFound, NO_SUCH_USER));
722 };
723 return Ok(Outcome::Ok(Added::Granted { collaborator }));
724 }
725 if self.direct_role(&repo.id, &user_id).await?.is_some() {
726 return Ok(Outcome::fail(
727 FailureCode::Conflict,
728 format!("{username} already has access to {}. Change their role instead.", full_name(&repo)),
729 ));
730 }
731 if let Some(refused) = self.outside_refusal(&a.actor, &repo.namespace, &workspace_id).await? {
732 return Ok(refused);
733 }
734 // An outside collaborator is someone added: a free workspace adds
735 // no one (paid.rs). Its members' roles above are its own business,
736 // and g1t's agent is never someone added.
737 if !crate::paid::is_g1t(&username)
738 && let Some(refused) = self.free_workspace_refusal(&repo.namespace).await?
739 {
740 return Ok(refused);
741 }
742 let pending = self
743 .pending_invitations(
744 "WHERE ri.repo_id = ? AND ri.invitee_id = ?",
745 &[repo.id.as_str().into(), user_id.as_str().into()],
746 )
747 .await?;
748 if !pending.is_empty() {
749 return Ok(Outcome::fail(
750 FailureCode::Conflict,
751 format!("{username} already has a pending invitation to {}. Change its role, or revoke it to send a new one.", full_name(&repo)),
752 ));
753 }
754 let id = self
755 .insert_invitation(&repo, &workspace_id, Some(&user_id), None, None, a.role, &a.actor.id, INVITATION_DAYS)
756 .await?;
757 let now = rfc3339(now_ms());
758 let Some(row) = self.invitation_by_id(&id).await? else {
759 return Ok(Outcome::fail(FailureCode::NotFound, "Invitation not found."));
760 };
761 // Told by email, at their primary address and the one typed.
762 let mut to = self.notice_recipients(&user_id, false).await.unwrap_or_default();
763 if let Invitee::Email(email) = &invitee
764 && !to.iter().any(|address| address.eq_ignore_ascii_case(email))
765 {
766 to.push(email.clone());
767 }
768 for address in to.iter().take(2) {
769 if let Err(error) = crate::email::send_repo_invite(
770 &self.env,
771 address,
772 &a.actor.username,
773 &full_name(&repo),
774 a.role.label(),
775 None,
776 None,
777 INVITATION_DAYS,
778 )
779 .await
780 {
781 worker::console_error!("repository invitation email failed: {error}");
782 }
783 }
784 self.audit(&a.actor, "repo.invitation_created", (&repo).into(), surface, format!("Invited {username} as {}", a.role.label()))
785 .await;
786 Ok(Outcome::Ok(Added::Invited {
787 invitation: row.shown(&now, true),
788 }))
789 }
790
791 /// An address without an account: an invite code that makes it and
792 /// accepts (invites.rs).
793 async fn invite_address(
794 &self,
795 actor: &User,
796 repo: &Repo,
797 workspace_id: &str,
798 email: &str,
799 role: RepoRole,
800 surface: Surface,
801 ) -> Result<Outcome<Added>> {
802 let pending = self
803 .pending_invitations(
804 "WHERE ri.repo_id = ? AND ri.email = ?",
805 &[repo.id.as_str().into(), email.into()],
806 )
807 .await?;
808 if !pending.is_empty() {
809 return Ok(Outcome::fail(
810 FailureCode::Conflict,
811 "That address already has a pending invitation to this repository. Revoke it to send a new one.",
812 ));
813 }
814 let invite = match self.repo_invite_code(actor, email).await? {
815 Outcome::Ok(invite) => invite,
816 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
817 };
818 let days = self.invite_days();
819 let id = self
820 .insert_invitation(repo, workspace_id, None, Some(email), Some(&invite.id), role, &actor.id, days)
821 .await?;
822 // The email's link proves the address, as any invite email's does.
823 let proof = self.email_proof_for(&invite.id, email);
824 if let Some(code) = &invite.code
825 && let Err(error) = crate::email::send_repo_invite(
826 &self.env,
827 email,
828 &actor.username,
829 &full_name(repo),
830 role.label(),
831 Some(code),
832 proof.as_deref(),
833 days,
834 )
835 .await
836 {
837 worker::console_error!("repository invitation email failed: {error}");
838 }
839 self.audit(
840 actor,
841 "repo.invitation_created",
842 repo.into(),
843 surface,
844 format!("Invited {} as {}", crate::invites::mask_email(email), role.label()),
845 )
846 .await;
847 let now = rfc3339(now_ms());
848 Ok(match self.invitation_by_id(&id).await? {
849 Some(row) => Outcome::Ok(Added::Invited {
850 invitation: row.shown(&now, true),
851 }),
852 None => Outcome::fail(FailureCode::NotFound, "Invitation not found."),
853 })
854 }
855
856 #[allow(clippy::too_many_arguments)]
857 async fn insert_invitation(
858 &self,
859 repo: &Repo,
860 workspace_id: &str,
861 invitee_id: Option<&str>,
862 email: Option<&str>,
863 invite_id: Option<&str>,
864 role: RepoRole,
865 inviter_id: &str,
866 days: u64,
867 ) -> Result<String> {
868 let now = now_ms();
869 let id = new_id("rin", now);
870 self.db
871 .prepare(
872 "INSERT INTO repo_invitations
873 (id, repo_id, workspace_id, repo_name, invitee_id, email, invite_id, role, inviter_id, created_at, expires_at)
874 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
875 )
876 .bind(&[
877 id.as_str().into(),
878 repo.id.as_str().into(),
879 workspace_id.into(),
880 repo.name.as_str().into(),
881 opt(invitee_id),
882 opt(email),
883 opt(invite_id),
884 role.as_str().into(),
885 inviter_id.into(),
886 rfc3339(now).into(),
887 rfc3339(now + days * 86_400_000).into(),
888 ])?
889 .run()
890 .await?;
891 Ok(id)
892 }
893
894 async fn invitation_by_id(&self, id: &str) -> Result<Option<InvitationRow>> {
895 Ok(self
896 .invitations("WHERE ri.id = ?", &[id.into()])
897 .await?
898 .into_iter()
899 .next())
900 }
901
902 fn invite_days(&self) -> u64 {
903 self.env
904 .var("INVITE_TTL_DAYS")
905 .ok()
906 .and_then(|value| value.to_string().parse().ok())
907 .unwrap_or(g1t_contracts::identity::INVITE_TTL_DAYS)
908 }
909
910 pub async fn set_collaborator_role(&self, a: SetCollaboratorRoleArgs) -> Result<Outcome<Collaborator>> {
911 let Target { repo, workspace_id } = match self.manageable(&a.actor, &a.path).await? {
912 Outcome::Ok(target) => target,
913 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
914 };
915 let Some((user_id, username)) = self.person_by_username(&a.username).await? else {
916 return Ok(Outcome::fail(FailureCode::NotFound, NO_SUCH_USER));
917 };
918 let surface = a.surface.unwrap_or(Surface::Web);
919 match self.direct_role(&repo.id, &user_id).await? {
920 Some(previous) => {
921 self.put_grant(&repo.id, &workspace_id, &repo.name, &user_id, a.role, Some(&a.actor.id))
922 .await?;
923 if previous != a.role {
924 self.changed(&a.actor, (&repo).into(), &username, Some(a.role), Some(previous), surface).await;
925 }
926 }
927 None => {
928 // A pending invitation's role changes until it is answered.
929 let changed = self
930 .db
931 .prepare(format!(
932 "UPDATE repo_invitations SET role = ?1
933 WHERE repo_id = ?2 AND invitee_id = ?3 AND accepted_at IS NULL AND declined_at IS NULL
934 AND revoked_at IS NULL AND expires_at > {SQL_NOW}
935 RETURNING id"
936 ))
937 .bind(&[a.role.as_str().into(), repo.id.as_str().into(), user_id.as_str().into()])?
938 .first::<Id>(None)
939 .await?;
940 if changed.is_none() {
941 return Ok(Outcome::fail(
942 FailureCode::NotFound,
943 format!(
944 "{username} has no role of their own on {}. Owners have Admin, and members the base permission; add them to give them more.",
945 full_name(&repo)
946 ),
947 ));
948 }
949 }
950 }
951 Ok(match self.collaborator_on(&repo, &workspace_id, &user_id).await? {
952 Some(collaborator) => Outcome::Ok(collaborator),
953 // Invited, not yet a collaborator: say what they will be.
954 None => Outcome::Ok(Collaborator {
955 username,
956 name: None,
957 avatar: None,
958 role: a.role,
959 source: AccessSource::Direct,
960 direct: Some(a.role),
961 workspace_role: None,
962 team_role: None,
963 team: None,
964 }),
965 })
966 }
967
968 pub async fn remove_collaborator(&self, a: RemoveCollaboratorArgs) -> Result<Outcome<bool>> {
969 let Some((user_id, username)) = self.person_by_username(&a.username).await? else {
970 return Ok(Outcome::fail(FailureCode::NotFound, NO_SUCH_USER));
971 };
972 let surface = a.surface.unwrap_or(Surface::Web);
973 // Anyone may give up their own role; otherwise, Admin only.
974 let leaving = crate::security::is_person(&a.actor) && a.actor.id == user_id;
975 let repo = if leaving {
976 match self.repo_for(&a.path, &Some(a.actor.clone())).await? {
977 Some(repo) => repo,
978 None => return Ok(Outcome::fail(FailureCode::NotFound, "Repository not found.")),
979 }
980 } else {
981 match self.manageable(&a.actor, &a.path).await? {
982 Outcome::Ok(target) => target.repo,
983 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
984 }
985 };
986 let Some(previous) = self.direct_role(&repo.id, &user_id).await? else {
987 return Ok(Outcome::fail(
988 FailureCode::NotFound,
989 format!(
990 "{username} has no role of their own on {}. To take away a member's access, change the base permission or remove them from the workspace.",
991 full_name(&repo)
992 ),
993 ));
994 };
995 self.db
996 .batch(vec![
997 self.db
998 .prepare("DELETE FROM repo_grants WHERE repo_id = ? AND principal_kind = 'user' AND principal_id = ?")
999 .bind(&[repo.id.as_str().into(), user_id.as_str().into()])?,
1000 self.db
1001 .prepare(format!(
1002 "UPDATE repo_invitations SET revoked_at = {SQL_NOW}
1003 WHERE repo_id = ? AND invitee_id = ? AND accepted_at IS NULL AND declined_at IS NULL AND revoked_at IS NULL"
1004 ))
1005 .bind(&[repo.id.as_str().into(), user_id.as_str().into()])?,
1006 ])
1007 .await?;
1008 self.changed(&a.actor, (&repo).into(), &username, None, Some(previous), surface).await;
1009 Ok(Outcome::Ok(true))
1010 }
1011
1012 pub async fn collaborator_permission(&self, a: CollaboratorPermissionArgs) -> Result<Outcome<PermissionInfo>> {
1013 let Some(repo) = self.repo_for(&a.path, &a.viewer).await? else {
1014 return Ok(Outcome::fail(FailureCode::NotFound, "Repository not found."));
1015 };
1016 let asking_about_self = a
1017 .viewer
1018 .as_ref()
1019 .is_some_and(|viewer| viewer.username.eq_ignore_ascii_case(a.username.trim()));
1020 if !asking_about_self && !can(a.viewer.as_ref(), &repo, Capability::Push) {
1021 return Ok(Outcome::fail(
1022 FailureCode::Forbidden,
1023 format!("You need the Write role or higher on {} to see others' permissions.", full_name(&repo)),
1024 ));
1025 }
1026 let Some((user_id, username)) = self.person_by_username(&a.username).await? else {
1027 return Ok(Outcome::fail(FailureCode::NotFound, NO_SUCH_USER));
1028 };
1029 let Some(workspace_id) = self.workspace_id_of(&repo.namespace).await? else {
1030 return Ok(Outcome::fail(FailureCode::NotFound, "Repository not found."));
1031 };
1032 // Held to the workspace's policy as their requests are.
1033 let within = self.policy_refusal(&user_id, &repo.namespace).await?.is_none();
1034 let place = if within {
1035 self.collaborator_on(&repo, &workspace_id, &user_id).await?
1036 } else {
1037 None
1038 };
1039 let role = place.as_ref().map(|place| place.role);
1040 Ok(Outcome::Ok(PermissionInfo {
1041 username,
1042 role,
1043 source: place.map(|place| place.source),
1044 capabilities: capabilities_of(role),
1045 }))
1046 }
1047
1048 pub async fn my_repo_invitations(&self, a: MyRepoInvitationsArgs) -> Result<Vec<RepoInvitation>> {
1049 if !crate::security::is_person(&a.user) {
1050 return Ok(Vec::new());
1051 }
1052 let now = rfc3339(now_ms());
1053 Ok(self
1054 .invitations_for(&a.user, None)
1055 .await?
1056 .iter()
1057 .map(|row| row.shown(&now, false))
1058 .collect())
1059 }
1060
1061 /// The pending invitations for `user`: sent to them, or to one of
1062 /// their confirmed addresses before they had an account (and made it
1063 /// some other way than with the code). `id` narrows it to one.
1064 async fn invitations_for(&self, user: &User, id: Option<&str>) -> Result<Vec<InvitationRow>> {
1065 let emails = serde_json::to_string(&self.verified_emails(&user.id).await?)?;
1066 let mut filter = "WHERE (ri.invitee_id = ? OR (ri.invitee_id IS NULL AND ri.email IN (SELECT value FROM json_each(?))))".to_owned();
1067 let mut binds = vec![JsValue::from(user.id.as_str()), emails.into()];
1068 if let Some(id) = id {
1069 filter.push_str(" AND ri.id = ?");
1070 binds.push(id.into());
1071 }
1072 self.pending_invitations(&filter, &binds).await
1073 }
1074
1075 pub async fn respond_repo_invitation(&self, a: RespondRepoInvitationArgs) -> Result<Outcome<RepoInvitation>> {
1076 if !crate::security::is_person(&a.user) {
1077 return Ok(Outcome::fail(FailureCode::Forbidden, "Only a person can answer an invitation."));
1078 }
1079 let now = rfc3339(now_ms());
1080 let row = self
1081 .invitations_for(&a.user, Some(&a.id))
1082 .await?
1083 .into_iter()
1084 .next();
1085 let Some(row) = row else {
1086 return Ok(Outcome::fail(
1087 FailureCode::NotFound,
1088 "There is no pending invitation of yours with that id. It may have expired or been revoked.",
1089 ));
1090 };
1091 if !a.accept {
1092 self.db
1093 .prepare(format!("UPDATE repo_invitations SET declined_at = {SQL_NOW} WHERE id = ?"))
1094 .bind(&[row.id.as_str().into()])?
1095 .run()
1096 .await?;
1097 let mut shown = row.shown(&now, false);
1098 shown.status = RepoInvitationStatus::Declined;
1099 return Ok(Outcome::Ok(shown));
1100 }
1101 if let Some(why) = self.policy_refusal(&a.user.id, &row.workspace).await? {
1102 return Ok(Outcome::fail(FailureCode::Forbidden, why));
1103 }
1104 // Sent before the workspace was free, or before this rule: it waits
1105 // until the workspace starts the plan (paid.rs).
1106 if let Some(refused) = self.free_workspace_refusal(&row.workspace).await? {
1107 return Ok(refused);
1108 }
1109 self.accept(&row, &a.user).await?;
1110 let mut shown = row.shown(&now, false);
1111 shown.status = RepoInvitationStatus::Accepted;
1112 Ok(Outcome::Ok(shown))
1113 }
1114
1115 /// Turns an invitation into a grant, once.
1116 async fn accept(&self, row: &InvitationRow, user: &User) -> Result<()> {
1117 let claimed = self
1118 .db
1119 .prepare(format!(
1120 "UPDATE repo_invitations SET accepted_at = {SQL_NOW}, invitee_id = ?1
1121 WHERE id = ?2 AND accepted_at IS NULL AND declined_at IS NULL AND revoked_at IS NULL
1122 RETURNING id"
1123 ))
1124 .bind(&[user.id.as_str().into(), row.id.as_str().into()])?
1125 .first::<Id>(None)
1126 .await?;
1127 if claimed.is_none() {
1128 return Ok(());
1129 }
1130 let role = row.role();
1131 // Never lowers a role they already have.
1132 let current = self.direct_role(&row.repo_id, &user.id).await?;
1133 let role = current.map_or(role, |current| current.max(role));
1134 let previous = self
1135 .put_grant(&row.repo_id, &row.workspace_id, &row.repo_name, &user.id, role, row.inviter_id.as_deref())
1136 .await?;
1137 let repo = Named {
1138 id: &row.repo_id,
1139 namespace: &row.workspace,
1140 name: &row.repo_name,
1141 };
1142 self.changed(user, repo, &user.username, Some(role), previous, Surface::Web).await;
1143 Ok(())
1144 }
1145
1146 /// The repository an invite code was sent with, for the invite's page
1147 /// (invites.rs): whatever became of the invitation since.
1148 pub(crate) async fn repository_of_code(
1149 &self,
1150 invite_id: &str,
1151 ) -> Result<Option<g1t_contracts::identity::InviteRepository>> {
1152 Ok(self
1153 .invitations("WHERE ri.invite_id = ?", &[invite_id.into()])
1154 .await?
1155 .into_iter()
1156 .next()
1157 .map(|row| g1t_contracts::identity::InviteRepository {
1158 name: format!("{}/{}", row.workspace, row.repo_name),
1159 role: row.role().as_str().to_owned(),
1160 }))
1161 }
1162
1163 /// Accepts the repository invitations sent with an invite code, once
1164 /// the code made `user`'s account (invites.rs).
1165 pub(crate) async fn accept_invitations_of_code(&self, invite_id: &str, user: &User) -> Result<()> {
1166 let rows = self
1167 .pending_invitations("WHERE ri.invite_id = ?", &[invite_id.into()])
1168 .await?;
1169 for row in rows {
1170 if self.policy_refusal(&user.id, &row.workspace).await?.is_some() {
1171 continue;
1172 }
1173 // A free workspace adds no one (paid.rs): the invitation stays
1174 // pending until it starts the plan.
1175 if self.is_free_workspace(&row.workspace).await {
1176 continue;
1177 }
1178 self.accept(&row, user).await?;
1179 }
1180 Ok(())
1181 }
1182
1183 pub async fn revoke_repo_invitation(&self, a: RevokeRepoInvitationArgs) -> Result<Outcome<RepoInvitation>> {
1184 let Target { repo, .. } = match self.manageable(&a.actor, &a.path).await? {
1185 Outcome::Ok(target) => target,
1186 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
1187 };
1188 let revoked = self
1189 .db
1190 .prepare(format!(
1191 "UPDATE repo_invitations SET revoked_at = {SQL_NOW}
1192 WHERE id = ? AND repo_id = ? AND accepted_at IS NULL AND declined_at IS NULL AND revoked_at IS NULL
1193 RETURNING id"
1194 ))
1195 .bind(&[a.id.as_str().into(), repo.id.as_str().into()])?
1196 .first::<Id>(None)
1197 .await?;
1198 if revoked.is_none() {
1199 return Ok(Outcome::fail(FailureCode::NotFound, "There is no pending invitation with that id."));
1200 }
1201 let Some(row) = self.invitation_by_id(&a.id).await? else {
1202 return Ok(Outcome::fail(FailureCode::NotFound, "Invitation not found."));
1203 };
1204 if let Some(invite_id) = &row.invite_id {
1205 self.revoke_code(invite_id).await?;
1206 }
1207 let who = row
1208 .invitee
1209 .clone()
1210 .or_else(|| row.email.as_deref().map(crate::invites::mask_email))
1211 .unwrap_or_default();
1212 self.audit(
1213 &a.actor,
1214 "repo.invitation_revoked",
1215 (&repo).into(),
1216 a.surface.unwrap_or(Surface::Web),
1217 format!("Revoked the invitation to {who}"),
1218 )
1219 .await;
1220 Ok(Outcome::Ok(row.shown(&rfc3339(now_ms()), true)))
1221 }
1222
1223 pub async fn set_base_permission(&self, a: SetBasePermissionArgs) -> Result<Outcome<BasePermission>> {
1224 let slug = a.slug.trim().to_lowercase();
1225 if !crate::security::is_person(&a.actor) || a.actor.role_in(&slug) != Some(Role::Owner) {
1226 return Ok(Outcome::fail(
1227 FailureCode::Forbidden,
1228 "Only an owner can change what members get on every repository.",
1229 ));
1230 }
1231 if !a.actor.verified {
1232 return Ok(Outcome::fail(FailureCode::Forbidden, CONFIRM_FIRST));
1233 }
1234 let Some(workspace_id) = self.workspace_id_of(&slug).await? else {
1235 return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found."));
1236 };
1237 let previous = self.base_of(&workspace_id).await?;
1238 self.db
1239 .prepare("UPDATE workspaces SET base_permission = ? WHERE id = ?")
1240 .bind(&[a.base_permission.as_str().into(), workspace_id.as_str().into()])?
1241 .run()
1242 .await?;
1243 if previous != a.base_permission {
1244 self.audit_workspace(
1245 &a.actor,
1246 "workspace.base_permission_changed",
1247 &slug,
1248 a.surface.unwrap_or(Surface::Web),
1249 format!(
1250 "Changed the base permission from {} to {}",
1251 previous.as_str(),
1252 a.base_permission.as_str()
1253 ),
1254 )
1255 .await;
1256 self.announce_workspace(&workspace_id, &slug, Some(&a.actor.id)).await;
1257 }
1258 Ok(Outcome::Ok(a.base_permission))
1259 }
1260
1261 /// `workspace_residency`: where a workspace keeps its repositories'
1262 /// git data, for the repos service as it places a new one, and for its
1263 /// settings page. Null when there is no such workspace.
1264 pub async fn workspace_residency(&self, a: g1t_contracts::identity::SlugArgs) -> Result<Option<g1t_contracts::identity::DataResidency>> {
1265 #[derive(Deserialize)]
1266 struct Row {
1267 #[serde(default)]
1268 data_residency: Option<String>,
1269 }
1270 let row = self
1271 .db
1272 .prepare("SELECT data_residency FROM workspaces WHERE slug = ? AND deleted_at IS NULL")
1273 .bind(&[a.slug.trim().to_lowercase().into()])?
1274 .first::<Row>(None)
1275 .await?;
1276 Ok(row.map(|row| {
1277 row.data_residency
1278 .as_deref()
1279 .and_then(g1t_contracts::identity::DataResidency::parse)
1280 .unwrap_or_default()
1281 }))
1282 }
1283
1284 /// `set_workspace_residency`: owners only. Applies to repositories
1285 /// made from then on; those it has stay where they are. Whether the EU
1286 /// can be chosen is the repos service's to say (`storage_options`);
1287 /// the site offers it only then, and the repos service refuses to
1288 /// place an EU workspace's repository anywhere else.
1289 pub async fn set_workspace_residency(
1290 &self,
1291 a: g1t_contracts::identity::SetResidencyArgs,
1292 ) -> Result<Outcome<g1t_contracts::identity::DataResidency>> {
1293 let slug = a.slug.trim().to_lowercase();
1294 if !crate::security::is_person(&a.actor) || a.actor.role_in(&slug) != Some(Role::Owner) {
1295 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can change where a workspace keeps its data."));
1296 }
1297 if !a.actor.verified {
1298 return Ok(Outcome::fail(FailureCode::Forbidden, "Confirm your email address before changing where the workspace keeps its data."));
1299 }
1300 let Some(previous) = self.workspace_residency(g1t_contracts::identity::SlugArgs { slug: slug.clone() }).await? else {
1301 return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found."));
1302 };
1303 if previous == a.residency {
1304 return Ok(Outcome::Ok(previous));
1305 }
1306 let stored = match a.residency {
1307 g1t_contracts::identity::DataResidency::Anywhere => JsValue::NULL,
1308 other => other.as_str().into(),
1309 };
1310 self.db
1311 .prepare("UPDATE workspaces SET data_residency = ? WHERE slug = ? AND deleted_at IS NULL")
1312 .bind(&[stored, slug.as_str().into()])?
1313 .run()
1314 .await?;
1315 self.audit_workspace(
1316 &a.actor,
1317 "workspace.residency_changed",
1318 &slug,
1319 Surface::Web,
1320 format!("Changed where new repositories keep their data from {} to {}", previous.as_str(), a.residency.as_str()),
1321 )
1322 .await;
1323 Ok(Outcome::Ok(a.residency))
1324 }
1325
1326 pub async fn outside_collaborators(&self, a: OutsideCollaboratorsArgs) -> Result<Outcome<Vec<OutsideCollaborator>>> {
1327 let slug = a.slug.trim().to_lowercase();
1328 if !a.viewer.as_ref().is_some_and(|viewer| viewer.role_in(&slug) == Some(Role::Owner)) {
1329 return Ok(Outcome::fail(FailureCode::Forbidden, "Only owners can see a workspace's outside collaborators."));
1330 }
1331 let Some(workspace_id) = self.workspace_id_of(&slug).await? else {
1332 return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found."));
1333 };
1334 #[derive(Deserialize)]
1335 struct Row {
1336 username: String,
1337 name: Option<String>,
1338 avatar: Option<String>,
1339 repo_name: String,
1340 role: String,
1341 }
1342 let rows = self
1343 .db
1344 .prepare(format!(
1345 "SELECT u.username, u.display_name AS name, u.avatar, g.repo_name, g.role
1346 FROM repo_grants g JOIN users u ON u.id = g.principal_id
1347 WHERE g.workspace_id = ?1 AND g.principal_kind = 'user'
1348 AND NOT EXISTS (SELECT 1 FROM workspace_members m WHERE m.workspace_id = ?1 AND m.user_id = g.principal_id)
1349 ORDER BY u.username, g.repo_name LIMIT {LIST_LIMIT}"
1350 ))
1351 .bind(&[workspace_id.as_str().into()])?
1352 .all()
1353 .await?
1354 .results::<Row>()?;
1355 let mut people: Vec<OutsideCollaborator> = Vec::new();
1356 for row in rows {
1357 let Some(role) = RepoRole::parse(&row.role) else {
1358 continue;
1359 };
1360 let repo = CollaboratorRepo {
1361 repo: format!("{slug}/{}", row.repo_name),
1362 role,
1363 };
1364 match people.last_mut().filter(|person| person.username == row.username) {
1365 Some(person) => person.repos.push(repo),
1366 None => people.push(OutsideCollaborator {
1367 username: row.username,
1368 name: row.name,
1369 avatar: row.avatar,
1370 repos: vec![repo],
1371 }),
1372 }
1373 }
1374 Ok(Outcome::Ok(people))
1375 }
1376
1377 pub async fn forget_repo_access(&self, a: ForgetRepoAccessArgs) -> Result<bool> {
1378 self.db
1379 .batch(vec![
1380 self.db
1381 .prepare("DELETE FROM repo_grants WHERE repo_id = ?")
1382 .bind(&[a.repo_id.as_str().into()])?,
1383 self.db
1384 .prepare("DELETE FROM repo_invitations WHERE repo_id = ?")
1385 .bind(&[a.repo_id.as_str().into()])?,
1386 ])
1387 .await?;
1388 Ok(true)
1389 }
1390
1391 /// A repository moved or was renamed: its grants and invitations follow
1392 /// it (deletion.rs, `transfer_repo_scopes`).
1393 pub(crate) async fn move_repo_access(&self, from: &RepoPath, to: &RepoPath) -> Result<()> {
1394 let (Some(from_id), Some(to_id)) = (
1395 self.workspace_id_of(&from.namespace).await?,
1396 self.workspace_id_of(&to.namespace).await?,
1397 ) else {
1398 return Ok(());
1399 };
1400 let binds = [
1401 JsValue::from(to_id.as_str()),
1402 to.name.to_lowercase().into(),
1403 from_id.as_str().into(),
1404 from.name.to_lowercase().into(),
1405 ];
1406 self.db
1407 .batch(vec![
1408 self.db
1409 .prepare("UPDATE repo_grants SET workspace_id = ?1, repo_name = ?2 WHERE workspace_id = ?3 AND repo_name = ?4")
1410 .bind(&binds)?,
1411 self.db
1412 .prepare("UPDATE repo_invitations SET workspace_id = ?1, repo_name = ?2 WHERE workspace_id = ?3 AND repo_name = ?4")
1413 .bind(&binds)?,
1414 ])
1415 .await?;
1416 Ok(())
1417 }
1418
1419 // --- Telling others ---
1420
1421 /// Publishes the change of a person's own role, and records it in the
1422 /// workspace's audit log.
1423 async fn changed(
1424 &self,
1425 actor: &User,
1426 repo: Named<'_>,
1427 username: &str,
1428 role: Option<RepoRole>,
1429 previous: Option<RepoRole>,
1430 surface: Surface,
1431 ) {
1432 let (kind, message) = match (previous, role) {
1433 (None, Some(role)) => ("repo.collaborator_added", format!("Gave {username} the {} role", role.label())),
1434 (Some(previous), Some(role)) => (
1435 "repo.collaborator_role_changed",
1436 format!("Changed {username}'s role from {} to {}", previous.label(), role.label()),
1437 ),
1438 (Some(previous), None) => ("repo.collaborator_removed", format!("Removed {username}'s {} role", previous.label())),
1439 (None, None) => return,
1440 };
1441 self.publish_repo(
1442 kind,
1443 repo.id,
1444 &actor.id,
1445 RepoCollaborator {
1446 repo_id: repo.id.to_owned(),
1447 namespace: repo.namespace.to_owned(),
1448 name: repo.name.to_owned(),
1449 username: username.to_owned(),
1450 role,
1451 previous_role: previous,
1452 },
1453 )
1454 .await;
1455 self.audit(actor, kind, repo, surface, message).await;
1456 }
1457
1458 pub(crate) async fn publish_repo<T: Serialize>(&self, kind: &'static str, repo_id: &str, actor: &str, data: T) {
1459 let Ok(events) = self.env.service("EVENTS") else {
1460 return;
1461 };
1462 let publish = Publish {
1463 events: vec![NewEvent {
1464 kind,
1465 source: "identity",
1466 repo_id: Some(repo_id.to_owned()),
1467 actor: Some(actor.to_owned()),
1468 data,
1469 }],
1470 };
1471 if let Err(error) = g1t_kit::call::<_, serde_json::Value>(&events, "publish", &publish).await {
1472 worker::console_error!("{kind} not published: {error}");
1473 }
1474 }
1475
1476 pub(crate) async fn audit(&self, actor: &User, action: &str, repo: Named<'_>, surface: Surface, message: String) {
1477 let full = format!("{}/{}", repo.namespace, repo.name);
1478 self.record(actor, action, repo.namespace, Some(full), surface, message).await;
1479 }
1480
1481 pub(crate) async fn audit_workspace(&self, actor: &User, action: &str, slug: &str, surface: Surface, message: String) {
1482 self.record(actor, action, slug, None, surface, message).await;
1483 }
1484
1485 async fn record(&self, actor: &User, action: &str, workspace: &str, repo: Option<String>, surface: Surface, message: String) {
1486 let Ok(events) = self.env.service("EVENTS") else {
1487 return;
1488 };
1489 let entry = NewAuditEntry {
1490 actor: AuditActor::of(actor),
1491 action: action.to_owned(),
1492 surface,
1493 target: AuditTarget {
1494 workspace: workspace.to_lowercase(),
1495 repo,
1496 ..AuditTarget::default()
1497 },
1498 outcome: AuditOutcome::Allowed,
1499 rule: if actor.kind == PrincipalKind::User { "access" } else { "access:token" }.to_owned(),
1500 result: Some("ok".to_owned()),
1501 message: Some(message),
1502 request_id: new_id("req", now_ms()),
1503 };
1504 let recorded: Result<u32> =
1505 g1t_kit::call(&events, "audit_record", &RecordAuditArgs { entries: vec![entry] }).await;
1506 if let Err(error) = recorded {
1507 worker::console_error!("{action} not recorded: {error}");
1508 }
1509 }
1510}
1511
1512#[cfg(test)]
1513mod tests {
1514 use super::*;
1515
1516 #[test]
1517 fn people_are_added_by_username_or_address() {
1518 assert_eq!(invitee(" Ada "), Some(Invitee::Username("ada".into())));
1519 assert_eq!(invitee("@ada"), Some(Invitee::Username("ada".into())));
1520 assert_eq!(invitee("Ada@Example.com"), Some(Invitee::Email("ada@example.com".into())));
1521 assert_eq!(invitee("not a name"), None);
1522 assert_eq!(invitee("ada@"), None);
1523 }
1524
1525 #[test]
1526 fn a_role_comes_from_ownership_the_base_or_a_grant() {
1527 use AccessSource::*;
1528 use RepoRole::*;
1529 assert_eq!(effective(true, Some(Read), Some(Write), None), Some((Admin, Owner)));
1530 assert_eq!(effective(false, Some(Write), None, None), Some((Write, Base)));
1531 assert_eq!(effective(false, Some(Write), Some(Maintain), None), Some((Maintain, Direct)));
1532 // A grant as high as the base is shown as direct, where it can be changed.
1533 assert_eq!(effective(false, Some(Write), Some(Write), None), Some((Write, Direct)));
1534 assert_eq!(effective(false, Some(Admin), Some(Read), None), Some((Admin, Base)));
1535 // An outside collaborator.
1536 assert_eq!(effective(false, None, Some(Triage), None), Some((Triage, Direct)));
1537 // A member of a workspace whose base is none, with no grant.
1538 assert_eq!(effective(false, None, None, None), None);
1539 }
1540
1541 #[test]
1542 fn a_teams_role_counts_where_it_is_the_highest() {
1543 use AccessSource::*;
1544 use RepoRole::*;
1545 assert_eq!(effective(false, Some(Read), None, Some(Maintain)), Some((Maintain, Team)));
1546 assert_eq!(effective(false, None, None, Some(Triage)), Some((Triage, Team)));
1547 // Lower than the base: the base.
1548 assert_eq!(effective(false, Some(Write), None, Some(Read)), Some((Write, Base)));
1549 // As high as the base: shown as the team's, where it can be changed.
1550 assert_eq!(effective(false, Some(Write), None, Some(Write)), Some((Write, Team)));
1551 // A direct grant as high as the team's is shown as direct.
1552 assert_eq!(effective(false, Some(Read), Some(Admin), Some(Admin)), Some((Admin, Direct)));
1553 assert_eq!(effective(false, Some(Read), Some(Write), Some(Admin)), Some((Admin, Team)));
1554 // Owners are owners.
1555 assert_eq!(effective(true, None, None, Some(Write)), Some((Admin, Owner)));
1556 }
1557
1558 #[test]
1559 fn each_person_keeps_the_highest_role_any_team_gives() {
1560 let roles = highest_team_roles([
1561 ("usr_a".to_owned(), RepoRole::Read, "docs".to_owned()),
1562 ("usr_a".to_owned(), RepoRole::Maintain, "platform".to_owned()),
1563 ("usr_a".to_owned(), RepoRole::Write, "backend".to_owned()),
1564 ("usr_b".to_owned(), RepoRole::Write, "web".to_owned()),
1565 ("usr_b".to_owned(), RepoRole::Write, "api".to_owned()),
1566 ]);
1567 assert_eq!(roles["usr_a"], (RepoRole::Maintain, "platform".to_owned()));
1568 assert_eq!(roles["usr_b"], (RepoRole::Write, "api".to_owned()));
1569 }
1570
1571 #[test]
1572 fn an_invitation_is_pending_until_answered_revoked_or_expired() {
1573 let row = InvitationRow {
1574 expires_at: "2026-10-12T00:00:00.000Z".into(),
1575 ..InvitationRow::default()
1576 };
1577 let now = "2026-10-05T00:00:00.000Z";
1578 assert_eq!(invitation_status(&row, now), RepoInvitationStatus::Pending);
1579 assert_eq!(invitation_status(&row, "2026-10-12T00:00:00.000Z"), RepoInvitationStatus::Expired);
1580 let accepted = InvitationRow { accepted_at: Some(now.into()), ..row.clone() };
1581 assert_eq!(invitation_status(&accepted, now), RepoInvitationStatus::Accepted);
1582 let declined = InvitationRow { declined_at: Some(now.into()), ..row.clone() };
1583 assert_eq!(invitation_status(&declined, now), RepoInvitationStatus::Declined);
1584 let revoked = InvitationRow { revoked_at: Some(now.into()), ..row };
1585 assert_eq!(invitation_status(&revoked, now), RepoInvitationStatus::Revoked);
1586 }
1587
1588 #[test]
1589 fn invitations_show_addresses_only_to_those_who_manage_access() {
1590 let row = InvitationRow {
1591 id: "rin_1".into(),
1592 workspace: "acme".into(),
1593 repo_name: "rocket".into(),
1594 email: Some("ada@example.com".into()),
1595 role: "triage".into(),
1596 expires_at: "2099-01-01T00:00:00.000Z".into(),
1597 ..InvitationRow::default()
1598 };
1599 let now = "2026-10-05T00:00:00.000Z";
1600 assert_eq!(row.shown(now, true).email.as_deref(), Some("ada@example.com"));
1601 assert_eq!(row.shown(now, false).email, None);
1602 assert_eq!(row.shown(now, false).repo, "acme/rocket");
1603 assert_eq!(row.shown(now, false).role, RepoRole::Triage);
1604 }
1605}