Skip to content

g1t/services/identity/src/access.rs

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