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,183 linesCodeBlameRaw
1//! The identity service: accounts, sessions, SSH keys and access tokens.
2//!
3//! Reached only through service bindings; see `g1t_contracts::identity` for
4//! the methods and their arguments.
5
6mod access;
7mod account_deletion;
8mod admin;
9mod aliases;
10mod ask_tokens;
11mod avatars;
12mod crypto;
13mod deletion;
14mod deploy_keys;
15mod device;
16mod directory;
17mod dock;
18mod email;
19mod emails;
20mod github;
21mod invites;
22mod members;
23mod oauth;
24mod onboarding;
25mod paid;
26mod people;
27mod privacy;
28mod profiles;
29mod purge_jobs;
30mod rename;
31mod job_tokens;
32mod run_credentials;
33mod security;
34mod shared_invites;
35mod sounds;
36mod suspension;
37mod teams;
38mod throttle;
39mod token_reach;
40mod tokens;
41mod two_factor;
42mod workspaces;
43
44use g1t_contracts::identity::*;
45use g1t_contracts::time::{SQL_NOW, rfc3339, sql_after};
46use g1t_contracts::{FailureCode, Outcome, User, Viewer, claimable_username, new_id};
47use g1t_kit::{args, now_ms, reply, rpc_method};
48use serde::Deserialize;
49use tokens::TOKEN_PREFIX;
50use worker::wasm_bindgen::JsValue;
51use worker::{Context, D1Database, Env, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
52
53const SESSION_TTL_SECONDS: u64 = 30 * 24 * 60 * 60;
54const RESET_TTL_SECONDS: u64 = 60 * 60;
55const MIN_PASSWORD_LENGTH: usize = 10;
56const PASSWORD_TOO_SHORT: &str = "Use a password of at least 10 characters.";
57
58/// A user as selected from the database; `verified` arrives as 0 or 1.
59/// What a username may be, as registration and GitHub sign-up say when one is refused.
60pub(crate) const USERNAME_RULES: &str =
61 "Usernames use letters of either case, digits and single hyphens, up to 39 characters, not starting or ending with a hyphen, and cannot be a reserved word.";
62
63#[derive(Deserialize)]
64struct Account {
65 id: String,
66 username: String,
67 /// Selected where the person is shown: their username as they wrote it.
68 #[serde(default)]
69 display_username: Option<String>,
70 verified: u8,
71 /// Selected only where the person is being shown to themselves.
72 #[serde(default)]
73 avatar: Option<String>,
74}
75
76impl From<Account> for User {
77 fn from(row: Account) -> Self {
78 User {
79 id: row.id,
80 username: row.username,
81 display_username: row.display_username,
82 verified: row.verified != 0,
83 avatar: row.avatar,
84 ..User::default()
85 }
86 }
87}
88
89#[derive(Deserialize)]
90struct UserRow {
91 id: String,
92 username: String,
93 password_hash: String,
94 verified: u8,
95}
96
97/// The owner of an emailed token.
98#[derive(Deserialize)]
99struct TokenOwner {
100 id: String,
101 username: String,
102 /// The address a link was sent to; null on links from before accounts
103 /// had several, which are for the primary.
104 #[serde(default)]
105 email_id: Option<String>,
106}
107
108#[derive(Deserialize)]
109struct KeyRow {
110 id: String,
111 title: String,
112 fingerprint: String,
113 created_at: String,
114 #[serde(default)]
115 last_used_at: Option<String>,
116}
117
118impl From<KeyRow> for SshKey {
119 fn from(row: KeyRow) -> Self {
120 SshKey {
121 id: row.id,
122 title: row.title,
123 fingerprint: row.fingerprint,
124 created_at: row.created_at,
125 last_used_at: row.last_used_at,
126 }
127 }
128}
129
130struct Identity {
131 db: D1Database,
132 env: Env,
133}
134
135impl Identity {
136 /// Runs a query that returns at most one user, for showing to others:
137 /// without their workspaces.
138 async fn find_public_user(&self, sql: &str, param: &str) -> Result<Viewer> {
139 Ok(self
140 .db
141 .prepare(sql)
142 .bind(&[JsValue::from(param)])?
143 .first::<Account>(None)
144 .await?
145 .map(User::from))
146 }
147
148 /// Attaches the workspaces a user belongs to, so that any service can
149 /// authorize them without asking again.
150 async fn with_workspaces(&self, user: Viewer) -> Result<Viewer> {
151 let Some(mut user) = user else {
152 return Ok(None);
153 };
154 // A suspended account is nobody, however it is presented
155 // (suspension.rs): its sessions, tokens, keys and password.
156 if self.user_suspension(&user.id).await?.is_some() {
157 return Ok(None);
158 }
159 let memberships = self.memberships_and_policies(&user.id).await?;
160 // Roles on single repositories, under the same policy (access.rs).
161 let grants = self.grants_of(&user.id).await?;
162 // Access to a workspace is used only within its policy; see security.rs.
163 let within = self.within_policy(&user.id, memberships, grants).await?;
164 user.workspaces = within.memberships;
165 user.grants = within.grants;
166 user.held = within.held;
167 Ok(Some(user))
168 }
169
170 /// Runs a query that resolves credentials to at most one user.
171 async fn find_user(&self, sql: &str, param: &str) -> Result<Viewer> {
172 let user = self.find_public_user(sql, param).await?;
173 self.with_workspaces(user).await
174 }
175
176 /// Consumes a token of `kind`, returning its owner if it was valid.
177 async fn redeem_email_token(&self, token: &str, kind: &str) -> Result<Option<TokenOwner>> {
178 let id = crypto::sha256_hex(token);
179 let owner = self
180 .db
181 .prepare(format!(
182 "SELECT users.id, users.username, email_tokens.email_id FROM email_tokens
183 JOIN users ON users.id = email_tokens.user_id
184 WHERE email_tokens.id = ? AND email_tokens.kind = ? AND users.deleted_at IS NULL
185 AND email_tokens.expires_at > {SQL_NOW}"
186 ))
187 .bind(&[id.as_str().into(), kind.into()])?
188 .first::<TokenOwner>(None)
189 .await?;
190 if let Some(owner) = &owner {
191 // Every outstanding token of this kind dies with the one used:
192 // every reset link, and every confirmation link for the same
193 // address (another address's links still work).
194 self.db
195 .prepare(
196 "DELETE FROM email_tokens WHERE user_id = ?1 AND kind = ?2
197 AND (?2 = 'reset' OR email_id IS ?3)",
198 )
199 .bind(&[
200 owner.id.as_str().into(),
201 kind.into(),
202 owner.email_id.as_deref().map_or(JsValue::NULL, Into::into),
203 ])?
204 .run()
205 .await?;
206 }
207 Ok(owner)
208 }
209
210 async fn resend_verification(&self, a: UserArgs) -> Result<Outcome<bool>> {
211 if !self.allow(throttle::CONFIRM_ACCOUNT, &a.user.id).await? {
212 return Ok(Outcome::fail(FailureCode::Conflict, "Too many confirmation emails this hour. Check your inbox, or try again later."));
213 }
214 self.resend_primary(&a.user).await
215 }
216
217 /// The link in a confirmation email, followed: signed in or not. It
218 /// ends the code sent with it (emails.rs).
219 async fn verify_email(&self, a: EmailTokenArgs) -> Result<Outcome<g1t_contracts::accounts::EmailConfirmed>> {
220 let Some(owner) = self.redeem_email_token(&a.token, "verify").await? else {
221 return Ok(Outcome::fail(
222 FailureCode::Invalid,
223 "This confirmation link is not valid or has expired.",
224 ));
225 };
226 self.confirm_address(&owner.id, owner.email_id.as_deref()).await
227 }
228
229 /// Any confirmed address of an account can ask for a reset; so can the
230 /// unconfirmed address a new account signed up with. See emails.rs.
231 async fn request_password_reset(&self, a: EmailArgs) -> Result<bool> {
232 let allowed = self.allow(throttle::RESET_EMAIL, &a.email).await?
233 && match a.client.as_deref() {
234 Some(client) => self.allow(throttle::RESET_CLIENT, client).await?,
235 None => true,
236 };
237 if allowed && let Some(target) = self.reset_target(&a.email).await? {
238 // A failure from here on happens only for a real account, so it
239 // is logged, never answered: the reply below stays the same.
240 if let Err(error) = self.send_reset(&target).await {
241 worker::console_error!("password reset for a known address failed: {error}");
242 }
243 }
244 // The same answer either way, so addresses cannot be probed.
245 Ok(true)
246 }
247
248 /// Saves a reset link for `target` and mails it, telling the account's
249 /// other addresses.
250 async fn send_reset(&self, target: &emails::ResetTarget) -> Result<()> {
251 {
252 let token = crypto::random_hex(32);
253 self.db
254 .prepare(format!(
255 "INSERT INTO email_tokens (id, user_id, kind, expires_at, email_id)
256 VALUES (?, ?, 'reset', {}, ?)",
257 sql_after(RESET_TTL_SECONDS)
258 ))
259 .bind(&[
260 crypto::sha256_hex(&token).into(),
261 target.user_id.as_str().into(),
262 target.email_id.as_str().into(),
263 ])?
264 .run()
265 .await?;
266 email::send_password_reset(&self.env, &target.display, &target.username, &token).await?;
267 // The primary and the backup hear of it when it went elsewhere.
268 let elsewhere = self.notice_recipients(&target.user_id, false).await?;
269 for address in elsewhere.iter().filter(|address| !address.eq_ignore_ascii_case(&target.display)) {
270 let change = format!("A password reset was asked for through {}", target.display);
271 if let Err(error) = email::send_security_notice(&self.env, address, &target.username, &change).await {
272 worker::console_error!("security notice failed: {error}");
273 }
274 }
275 }
276 Ok(())
277 }
278
279 async fn reset_password(&self, a: ResetPasswordArgs) -> Result<Outcome<User>> {
280 if a.password.chars().count() < MIN_PASSWORD_LENGTH {
281 return Ok(Outcome::fail(FailureCode::Invalid, PASSWORD_TOO_SHORT));
282 }
283 let Some(owner) = self.redeem_email_token(&a.token, "reset").await? else {
284 return Ok(Outcome::fail(
285 FailureCode::Invalid,
286 "This reset link is not valid or has expired.",
287 ));
288 };
289 self.db
290 .prepare("UPDATE users SET password_hash = ? WHERE id = ?")
291 .bind(&[
292 crypto::hash_password(&a.password).into(),
293 owner.id.as_str().into(),
294 ])?
295 .run()
296 .await?;
297 // Following an emailed link also proves the address it went to
298 // (unless another account confirmed it first).
299 let _ = self.confirm_address(&owner.id, owner.email_id.as_deref()).await?;
300 // Anyone signed in with the old password is signed out, and nobody
301 // stays locked out by the wrong guesses before it.
302 self.db
303 .prepare("DELETE FROM sessions WHERE user_id = ?")
304 .bind(&[owner.id.as_str().into()])?
305 .run()
306 .await?;
307 self.clear(&throttle::key(throttle::PASSWORD_ACCOUNT, &owner.id)).await?;
308 self.log_security(&owner.id, "password_changed", None, None).await;
309 self.tell_primary_and_backup(&owner.id, &owner.username, "Your password was changed").await;
310 let verified = self
311 .find_public_user(
312 "SELECT id, username, email_verified_at IS NOT NULL AS verified FROM users WHERE id = ?",
313 &owner.id,
314 )
315 .await?
316 .is_some_and(|user| user.verified);
317 Ok(Outcome::Ok(User {
318 id: owner.id,
319 username: owner.username,
320 verified,
321 ..User::default()
322 }))
323 }
324
325 /// The account a login names: a username, or any confirmed address.
326 async fn password_row(&self, login: &str) -> Result<Option<UserRow>> {
327 let login = login.trim().to_lowercase();
328 let (column, value) = if login.contains('@') {
329 match self.user_with_verified_email(&login).await? {
330 Some(id) => ("id", id),
331 None => return Ok(None),
332 }
333 } else {
334 ("username", login)
335 };
336 self.db
337 .prepare(format!(
338 "SELECT id, username, password_hash, email_verified_at IS NOT NULL AS verified FROM users
339 WHERE {column} = ? AND deleted_at IS NULL"
340 ))
341 .bind(&[JsValue::from(value)])?
342 .first::<UserRow>(None)
343 .await
344 }
345
346 /// Checks a password for a login, throttled (see throttle.rs). The
347 /// refusal is one of two messages, the same for every account.
348 async fn checked_password(
349 &self,
350 login: &str,
351 password: &str,
352 client: Option<&str>,
353 ) -> Result<std::result::Result<User, &'static str>> {
354 let row = self.password_row(login).await?;
355 let subject = row.as_ref().map_or_else(|| login.trim().to_lowercase(), |row| row.id.clone());
356 let (account_key, client_key) = Identity::password_keys(&subject, client);
357 if self.password_locked(&account_key, client_key.as_deref()).await? {
358 return Ok(Err(throttle::THROTTLED));
359 }
360 let owner = row.as_ref().map(|row| (row.id.clone(), row.username.clone()));
361 match row.filter(|row| !row.password_hash.is_empty() && crypto::verify_password(password, &row.password_hash)) {
362 Some(row) => {
363 self.clear(&account_key).await?;
364 Ok(Ok(User {
365 id: row.id,
366 username: row.username,
367 verified: row.verified != 0,
368 ..User::default()
369 }))
370 }
371 None => {
372 let owner = owner.as_ref().map(|(id, name)| (id.as_str(), name.as_str()));
373 self.password_failed(&account_key, client_key.as_deref(), owner).await?;
374 Ok(Err("Incorrect username or password."))
375 }
376 }
377 }
378
379 /// Git over HTTPS with the account's password. With two-factor
380 /// authentication on, a password alone is never enough: use an access
381 /// token (two_factor.rs).
382 async fn user_for_password(&self, login: &str, password: &str) -> Result<Viewer> {
383 let user = self.checked_password(login, password, None).await?.ok();
384 if let Some(user) = &user
385 && self.two_factor_enabled(&user.id).await?
386 {
387 return Ok(None);
388 }
389 self.with_workspaces(user).await
390 }
391
392 async fn register(&self, a: RegisterArgs) -> Result<Outcome<SignedIn>> {
393 // Kept as typed for showing; found, linked and mentioned lowercased.
394 let chosen = claimable_username(&a.username);
395 let username = chosen.as_ref().map_or_else(|| a.username.trim().to_lowercase(), |name| name.canonical.clone());
396 let claimable = chosen.is_some();
397 let email = a.email.trim().to_lowercase();
398 let invalid = |message: &str| Ok(Outcome::fail(FailureCode::Invalid, message));
399 let invite_code = a.invite_code.as_deref().map(str::trim).filter(|code| !code.is_empty());
400 if !claimable {
401 return invalid(USERNAME_RULES);
402 }
403 let well_formed_email = email
404 .split_once('@')
405 .is_some_and(|(local, domain)| !local.is_empty() && domain.contains('.'))
406 && !email.contains(char::is_whitespace);
407 if !well_formed_email {
408 return invalid("Enter a valid email address.");
409 }
410 if a.password.chars().count() < MIN_PASSWORD_LENGTH {
411 return invalid(PASSWORD_TOO_SHORT);
412 }
413 // Anyone may sign up, so many accounts from one address is the
414 // abuse to stop: counted once the form is well formed, before
415 // anything is looked up or written.
416 if !self.sign_up_allowed(a.client.as_deref()).await? {
417 return Ok(Identity::too_many_sign_ups());
418 }
419 if self.email_blocked(&email).await? {
420 return Ok(Outcome::fail(FailureCode::Forbidden, suspension::BLOCKED));
421 }
422 let taken = self
423 .db
424 // Usernames and workspaces share one namespace, so that a name
425 // means the same thing wherever it appears.
426 // An address is taken once an account has confirmed it; an
427 // unconfirmed one goes to whoever confirms it first (emails.rs).
428 .prepare(
429 "SELECT username FROM users WHERE username = ?
430 UNION ALL SELECT email FROM user_emails WHERE email = ? AND verified_at IS NOT NULL
431 UNION ALL SELECT slug FROM workspaces WHERE slug = ?",
432 )
433 .bind(&[
434 username.as_str().into(),
435 email.as_str().into(),
436 username.as_str().into(),
437 ])?
438 .first::<serde_json::Value>(None)
439 .await?;
440 // A renamed workspace's old slug stays reserved for it a while, and
441 // a deleted workspace's for good.
442 if taken.is_some() || self.slug_held(&username).await? || self.slug_deleted(&username).await? {
443 return Ok(Outcome::fail(
444 FailureCode::Conflict,
445 "That username or email is already registered.",
446 ));
447 }
448 let password_hash = crypto::hash_password(&a.password);
449 let user = match self
450 .create_account(invites::NewAccount {
451 username: &username,
452 display_username: chosen.as_ref().and_then(|name| name.display_if_cased()),
453 email: &email,
454 password_hash: &password_hash,
455 verified: false,
456 invite_code,
457 email_proof: a.email_proof.as_deref(),
458 })
459 .await?
460 {
461 Outcome::Ok(user) => user,
462 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
463 };
464 // The account exists either way; the email can be sent again from
465 // the confirmation page. It carries a code and a link (emails.rs).
466 if !user.verified
467 && let Err(error) = self.send_primary_confirmation(&user.id, &user.username).await
468 {
469 worker::console_error!("confirmation email failed: {error}");
470 }
471 self.start_session(user).await
472 }
473
474 async fn sign_in(&self, a: SignInArgs) -> Result<Outcome<SignedIn>> {
475 let user = match self.checked_password(&a.username, &a.password, a.client.as_deref()).await? {
476 Ok(user) => user,
477 Err(message) => return Ok(Outcome::fail(FailureCode::Unauthenticated, message)),
478 };
479 if self.user_suspension(&user.id).await?.is_some() {
480 return Ok(Outcome::fail(FailureCode::Forbidden, suspension::SUSPENDED));
481 }
482 let user = self.with_workspaces(Some(user)).await?.unwrap_or_default();
483 self.start_session(user).await
484 }
485
486 /// Starts a session for someone who just proved their password (or
487 /// GitHub account). With two-factor authentication on, it starts none:
488 /// it returns a challenge for `two_factor_sign_in` (two_factor.rs).
489 async fn start_session(&self, user: User) -> Result<Outcome<SignedIn>> {
490 if self.two_factor_enabled(&user.id).await? {
491 let challenge = self.issue_challenge(&user.id).await?;
492 return Ok(Outcome::Ok(SignedIn {
493 user: User { workspaces: Vec::new(), grants: Vec::new(), held: Vec::new(), ..user },
494 session_token: String::new(),
495 two_factor_challenge: Some(challenge),
496 }));
497 }
498 self.session_for(user).await
499 }
500
501 /// A new session for `user`, who has proved who they are in full.
502 async fn session_for(&self, user: User) -> Result<Outcome<SignedIn>> {
503 // Whichever way it was proved, a deleted account starts none
504 // (account_deletion.rs).
505 if !self.account_live(&user.id).await? {
506 return Ok(Outcome::fail(FailureCode::Unauthenticated, "Incorrect username or password."));
507 }
508 // Nor a suspended one, however it was proved (suspension.rs).
509 if self.user_suspension(&user.id).await?.is_some() {
510 return Ok(Outcome::fail(FailureCode::Forbidden, suspension::SUSPENDED));
511 }
512 let session_token = crypto::random_hex(32);
513 self.db
514 .prepare(format!(
515 // Signing in is proof it is the person: see security.rs.
516 "INSERT INTO sessions (id, user_id, expires_at, authenticated_at) VALUES (?, ?, {}, {SQL_NOW})",
517 sql_after(SESSION_TTL_SECONDS)
518 ))
519 .bind(&[
520 crypto::sha256_hex(&session_token).into(),
521 user.id.as_str().into(),
522 ])?
523 .run()
524 .await?;
525 Ok(Outcome::Ok(SignedIn {
526 user,
527 session_token,
528 two_factor_challenge: None,
529 }))
530 }
531
532 async fn sign_out(&self, a: SessionArgs) -> Result<()> {
533 self.db
534 .prepare("DELETE FROM sessions WHERE id = ?")
535 .bind(&[crypto::sha256_hex(&a.session_token).into()])?
536 .run()
537 .await?;
538 Ok(())
539 }
540
541 async fn user_for_session(&self, a: SessionArgs) -> Result<Viewer> {
542 self.find_user(
543 &format!(
544 "SELECT users.id, users.username, users.display_username, users.email_verified_at IS NOT NULL AS verified,
545 users.avatar
546 FROM sessions JOIN users ON users.id = sessions.user_id
547 WHERE sessions.id = ? AND sessions.expires_at > {SQL_NOW} AND users.deleted_at IS NULL"
548 ),
549 &crypto::sha256_hex(&a.session_token),
550 )
551 .await
552 }
553
554 async fn user_for_git_credentials(&self, a: GitCredentialsArgs) -> Result<Viewer> {
555 // Like GitHub, a token alone identifies its user.
556 if a.secret.starts_with(TOKEN_PREFIX) {
557 self.user_for_access_token(&a.secret).await
558 } else {
559 self.user_for_password(&a.username, &a.secret).await
560 }
561 }
562
563 async fn user_for_ssh_key(&self, a: FingerprintArgs) -> Result<Viewer> {
564 self.find_user(
565 "SELECT users.id, users.username, users.email_verified_at IS NOT NULL AS verified FROM ssh_keys
566 JOIN users ON users.id = ssh_keys.user_id
567 WHERE fingerprint = ? AND users.deleted_at IS NULL",
568 &a.fingerprint,
569 )
570 .await
571 }
572
573 async fn current_user(&self, a: g1t_contracts::identity::UserIdArgs) -> Result<Viewer> {
574 self.find_user(
575 "SELECT id, username, display_username, email_verified_at IS NOT NULL AS verified, avatar FROM users WHERE id = ? AND deleted_at IS NULL",
576 &a.id,
577 )
578 .await
579 }
580
581 async fn user_by_username(&self, a: UsernameArgs) -> Result<Viewer> {
582 self.find_public_user(
583 // A deleted account is nobody's to find, mention or add.
584 "SELECT id, username, display_username, email_verified_at IS NOT NULL AS verified FROM users WHERE username = ? AND deleted_at IS NULL",
585 &a.username.to_lowercase(),
586 )
587 .await
588 }
589
590 /// `notify_by_email`: an inbox item, emailed to the person it is for,
591 /// only at a confirmed address and only while they can still read the
592 /// repository it is about. Returns whether it was sent.
593 async fn notify_by_email(&self, a: g1t_contracts::inbox::NotifyByEmailArgs) -> Result<bool> {
594 #[derive(Deserialize)]
595 struct Address {
596 email: Option<String>,
597 }
598 let user = self
599 .find_user(
600 "SELECT id, username, email_verified_at IS NOT NULL AS verified FROM users WHERE username = ? AND deleted_at IS NULL",
601 &a.username.to_lowercase(),
602 )
603 .await?;
604 let Some(user) = user.filter(|user| user.verified) else {
605 return Ok(false);
606 };
607 let readable: Vec<g1t_contracts::repos::Repo> = g1t_kit::call(
608 &self.env.service("REPOS")?,
609 "readable",
610 &g1t_contracts::repos::ReadableArgs {
611 ids: vec![a.repo_id.clone()],
612 viewer: Some(user.clone()),
613 },
614 )
615 .await?;
616 if readable.is_empty() {
617 return Ok(false);
618 }
619 let address = self
620 .db
621 .prepare("SELECT email FROM users WHERE id = ?")
622 .bind(&[user.id.as_str().into()])?
623 .first::<Address>(None)
624 .await?
625 .and_then(|row| row.email)
626 .filter(|email| !email.trim().is_empty());
627 let Some(address) = address else {
628 return Ok(false);
629 };
630 email::send_notification(&self.env, &address, &a).await?;
631 Ok(true)
632 }
633
634 async fn usernames(&self, a: UsernamesArgs) -> Result<std::collections::HashMap<String, String>> {
635 #[derive(serde::Deserialize)]
636 struct Named {
637 id: String,
638 name: String,
639 }
640 let ids: Vec<String> = a.ids.into_iter().take(200).collect();
641 let mut names = std::collections::HashMap::new();
642 if ids.is_empty() {
643 return Ok(names);
644 }
645 let marks = vec!["?"; ids.len()].join(", ");
646 let bind: Vec<worker::wasm_bindgen::JsValue> = ids.iter().map(|id| id.as_str().into()).collect();
647 for sql in [
648 format!("SELECT id, username AS name FROM users WHERE id IN ({marks})"),
649 format!("SELECT id, slug AS name FROM workspaces WHERE id IN ({marks})"),
650 ] {
651 for row in self.db.prepare(sql).bind(&bind)?.all().await?.results::<Named>()? {
652 names.insert(row.id, row.name);
653 }
654 }
655 Ok(names)
656 }
657
658 /// `users_for_audience`: the people behind these ids (at most 50), each
659 /// with their workspaces, roles, base permissions and repository
660 /// grants, under each workspace's policy, as a signed-in viewer would
661 /// have them. For services that answer only with what every person
662 /// who will read the answer may see. Ids of no live account are left out, so the caller can tell
663 /// someone it could not resolve. Reached only by service binding.
664 async fn users_for_audience(&self, a: UsernamesArgs) -> Result<Vec<User>> {
665 let mut found = Vec::new();
666 for id in a.ids.iter().take(50) {
667 let user = self
668 .find_user(
669 "SELECT id, username, email_verified_at IS NOT NULL AS verified FROM users WHERE id = ? AND deleted_at IS NULL",
670 id,
671 )
672 .await?;
673 if let Some(user) = user {
674 found.push(user);
675 }
676 }
677 Ok(found)
678 }
679
680 /// `accounts`: the accounts behind these ids (at most 200), each with
681 /// its username and avatar, for lists that keep ids, such as who
682 /// starred a repository. Ids of no account are left out.
683 /// `display_usernames`: each lowercased username's chosen case, for the
684 /// API, which shows it beside every username it answers with.
685 async fn display_usernames(&self, a: DisplayUsernamesArgs) -> Result<std::collections::HashMap<String, String>> {
686 #[derive(serde::Deserialize)]
687 struct Row {
688 username: String,
689 display_username: String,
690 }
691 let mut names: Vec<String> = a.usernames.iter().map(|name| name.trim().to_lowercase()).filter(|name| !name.is_empty()).collect();
692 names.sort();
693 names.dedup();
694 names.truncate(200);
695 let mut found = std::collections::HashMap::new();
696 if names.is_empty() {
697 return Ok(found);
698 }
699 let marks = vec!["?"; names.len()].join(", ");
700 let bind: Vec<worker::wasm_bindgen::JsValue> = names.iter().map(|name| name.as_str().into()).collect();
701 let rows = self
702 .db
703 .prepare(format!(
704 "SELECT username, display_username FROM users WHERE username IN ({marks}) AND display_username IS NOT NULL AND deleted_at IS NULL"
705 ))
706 .bind(&bind)?
707 .all()
708 .await?
709 .results::<Row>()?;
710 for row in rows {
711 if row.display_username.eq_ignore_ascii_case(&row.username) && row.display_username != row.username {
712 found.insert(row.username, row.display_username);
713 }
714 }
715 Ok(found)
716 }
717
718 async fn accounts(&self, a: UsernamesArgs) -> Result<std::collections::HashMap<String, g1t_contracts::accounts::EmailOwner>> {
719 #[derive(serde::Deserialize)]
720 struct Row {
721 id: String,
722 username: String,
723 avatar: Option<String>,
724 }
725 let ids: Vec<String> = a.ids.into_iter().take(200).collect();
726 let mut found = std::collections::HashMap::new();
727 if ids.is_empty() {
728 return Ok(found);
729 }
730 let marks = vec!["?"; ids.len()].join(", ");
731 let bind: Vec<worker::wasm_bindgen::JsValue> = ids.iter().map(|id| id.as_str().into()).collect();
732 let rows = self
733 .db
734 .prepare(format!("SELECT id, username, avatar FROM users WHERE id IN ({marks})"))
735 .bind(&bind)?
736 .all()
737 .await?
738 .results::<Row>()?;
739 for row in rows {
740 found.insert(row.id.clone(), g1t_contracts::accounts::EmailOwner { id: row.id, username: row.username, avatar: row.avatar });
741 }
742 Ok(found)
743 }
744
745 async fn list_ssh_keys(&self, a: UserArgs) -> Result<Vec<SshKey>> {
746 let rows = self
747 .db
748 .prepare("SELECT id, title, fingerprint, created_at, last_used_at FROM ssh_keys WHERE user_id = ? ORDER BY id")
749 .bind(&[a.user.id.into()])?
750 .all()
751 .await?
752 .results::<KeyRow>()?;
753 Ok(rows.into_iter().map(SshKey::from).collect())
754 }
755
756 /// The account (user id) that registered each key, by fingerprint
757 /// (`SHA256:…`). At most 100; unknown keys are left out.
758 async fn ssh_key_owners(&self, a: SshKeyOwnersArgs) -> Result<std::collections::HashMap<String, String>> {
759 #[derive(serde::Deserialize)]
760 struct Row {
761 fingerprint: String,
762 user_id: String,
763 }
764 let fingerprints: Vec<&String> = a.fingerprints.iter().take(100).collect();
765 if fingerprints.is_empty() {
766 return Ok(std::collections::HashMap::new());
767 }
768 let marks = vec!["?"; fingerprints.len()].join(", ");
769 let binds: Vec<JsValue> = fingerprints.iter().map(|fingerprint| fingerprint.as_str().into()).collect();
770 Ok(self
771 .db
772 .prepare(format!("SELECT fingerprint, user_id FROM ssh_keys WHERE fingerprint IN ({marks})"))
773 .bind(&binds)?
774 .all()
775 .await?
776 .results::<Row>()?
777 .into_iter()
778 .map(|row| (row.fingerprint, row.user_id))
779 .collect())
780 }
781
782 async fn add_ssh_key(&self, a: AddSshKeyArgs) -> Result<Outcome<SshKey>> {
783 let Some(key) = crypto::parse_ssh_key(&a.public_key) else {
784 return Ok(Outcome::fail(
785 FailureCode::Invalid,
786 "That is not a valid OpenSSH public key.",
787 ));
788 };
789 // Someone's SSH key, or a repository's deploy key (deploy_keys.rs).
790 if self.key_in_use(&key.fingerprint).await? {
791 return Ok(Outcome::fail(FailureCode::Conflict, g1t_contracts::deploy_keys::KEY_IN_USE));
792 }
793 let now = now_ms();
794 let title = [a.title.trim(), key.comment.as_str(), "SSH key"]
795 .into_iter()
796 .find(|candidate| !candidate.is_empty())
797 .unwrap_or_default()
798 .to_owned();
799 let row = KeyRow {
800 id: new_id("key", now),
801 title,
802 fingerprint: key.fingerprint,
803 created_at: rfc3339(now),
804 last_used_at: None,
805 };
806 let inserted = self.db
807 .prepare(
808 "INSERT INTO ssh_keys (id, user_id, title, public_key, fingerprint, created_at)
809 VALUES (?, ?, ?, ?, ?, ?)",
810 )
811 .bind(&[
812 row.id.as_str().into(),
813 a.user.id.as_str().into(),
814 row.title.as_str().into(),
815 key.public_key.into(),
816 row.fingerprint.as_str().into(),
817 row.created_at.as_str().into(),
818 ])?
819 .run()
820 .await;
821 // Added at the same moment elsewhere: the trigger or the unique
822 // index refused it.
823 if let Err(error) = inserted {
824 if self.key_in_use(&row.fingerprint).await? {
825 return Ok(Outcome::fail(FailureCode::Conflict, g1t_contracts::deploy_keys::KEY_IN_USE));
826 }
827 return Err(error);
828 }
829 let shown = format!("{} ({})", row.title, row.fingerprint);
830 self.log_security(&a.user.id, "ssh_key_added", Some(&shown), None).await;
831 self.audit_account(&a.user, "ssh_key.added", &format!("Added SSH key {shown}")).await;
832 Ok(Outcome::Ok(row.into()))
833 }
834
835 /// Deletes one of the person's SSH keys.
836 async fn remove_ssh_key(&self, a: RemoveArgs) -> Result<()> {
837 #[derive(Deserialize)]
838 struct Removed {
839 title: String,
840 fingerprint: String,
841 }
842 let removed = self
843 .db
844 .prepare("DELETE FROM ssh_keys WHERE id = ? AND user_id = ? RETURNING title, fingerprint")
845 .bind(&[a.id.as_str().into(), a.user.id.as_str().into()])?
846 .first::<Removed>(None)
847 .await?;
848 if let Some(removed) = removed {
849 let shown = format!("{} ({})", removed.title, removed.fingerprint);
850 self.log_security(&a.user.id, "ssh_key_removed", Some(&shown), None).await;
851 self.audit_account(&a.user, "ssh_key.removed", &format!("Removed SSH key {shown}")).await;
852 }
853 Ok(())
854 }
855}
856
857/// Every 15 minutes: deleted workspaces and accounts past their restore
858/// window are purged (deletion.rs, account_deletion.rs).
859#[event(scheduled)]
860async fn scheduled(_event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
861 let Ok(db) = env.d1("DB") else { return };
862 let identity = Identity { db, env };
863 if let Err(error) = identity.purge_due_workspaces().await {
864 worker::console_error!("workspace purge: {error}");
865 }
866 // And deleted accounts past theirs (account_deletion.rs).
867 if let Err(error) = identity.purge_due_accounts().await {
868 worker::console_error!("account purge: {error}");
869 }
870 if let Err(error) = identity.run_purge_jobs().await {
871 worker::console_error!("purge jobs: {error}");
872 }
873 // Once: creators of repositories made before they got Admin (members.rs).
874 if let Err(error) = identity.backfill_creator_grants().await {
875 worker::console_error!("creator grants: {error}");
876 }
877}
878
879#[event(fetch)]
880async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
881 let Some(method) = rpc_method(&request) else {
882 return Response::error("Not found", 404);
883 };
884 // A replica near the caller when it asks for one (crates/kit/src/d1.rs).
885 let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?;
886 let body: serde_json::Value = request.json().await?;
887 let identity = Identity { db, env };
888
889 let answered = match method.as_str() {
890 "register" => {
891 let outcome = identity.register(args(body)?).await?;
892 if let Outcome::Ok(signed_in) = &outcome {
893 identity.announce_user(&signed_in.user.username, Some(&signed_in.user.id)).await;
894 }
895 reply(&outcome)
896 }
897 "sign_in" => reply(&identity.sign_in(args(body)?).await?),
898 "create_workspace" => {
899 let outcome = identity.create_workspace(args(body)?).await?;
900 if let Outcome::Ok(workspace) = &outcome {
901 identity.announce_workspace(&workspace.id, &workspace.slug, None).await;
902 }
903 reply(&outcome)
904 }
905 "get_workspace" => reply(&identity.get_workspace(args(body)?).await?),
906 "list_members" => reply(&identity.list_members(args(body)?).await?),
907 "add_member" => reply(&identity.add_member(args(body)?).await?),
908 "remove_member" => reply(&identity.remove_member(args(body)?).await?),
909 // Owners, roles, leaving and member privileges; see members.rs.
910 "update_member" => reply(&identity.update_member(args(body)?).await?),
911 "transfer_ownership" => reply(&identity.transfer_ownership(args(body)?).await?),
912 "leave_workspace" => reply(&identity.leave_workspace(args(body)?).await?),
913 "set_member_privileges" => reply(&identity.set_member_privileges(args(body)?).await?),
914 "set_two_factor_requirement" => reply(&identity.set_two_factor_requirement(args(body)?).await?),
915 "grant_creator" => reply(&identity.grant_creator(args(body)?).await?),
916 "update_workspace" => {
917 let outcome = identity.update_workspace(args(body)?).await?;
918 if let Outcome::Ok(workspace) = &outcome {
919 identity.announce_workspace(&workspace.id, &workspace.slug, None).await;
920 }
921 reply(&outcome)
922 }
923 "rename_workspace" => reply(&identity.rename_workspace(args(body)?).await?),
924 "check_workspace_rename" => reply(&identity.check_workspace_rename(args(body)?).await?),
925 "resolve_slug" => reply(&identity.resolve_slug(args(body)?).await?),
926 "resolve_alias" => reply(&identity.resolve_alias(args(body)?).await?),
927 "check_workspace_deletion" => reply(&identity.check_workspace_deletion(args(body)?).await?),
928 "delete_workspace" => reply(&identity.delete_workspace(args(body)?).await?),
929 "transfer_repo_scopes" => reply(&identity.transfer_repo_scopes(args(body)?).await?),
930 "set_workspace_avatar" => {
931 let outcome = identity.set_workspace_avatar(args(body)?).await?;
932 if let Outcome::Ok(workspace) = &outcome {
933 identity.announce_workspace(&workspace.id, &workspace.slug, None).await;
934 }
935 reply(&outcome)
936 }
937 "set_user_avatar" => {
938 let a: SetUserAvatarArgs = args(body)?;
939 let (username, id) = (a.user.username.clone(), a.user.id.clone());
940 let outcome = identity.set_user_avatar(a).await?;
941 if matches!(outcome, Outcome::Ok(_)) {
942 identity.announce_user(&username, Some(&id)).await;
943 }
944 reply(&outcome)
945 }
946 "list_workspace_tokens" => reply(&identity.list_workspace_tokens(args(body)?).await?),
947 "remove_workspace_token" => reply(&identity.remove_workspace_token(args(body)?).await?),
948 // Signing in with GitHub; see github.rs.
949 "github_enabled" => reply(&identity.github_enabled()),
950 "github_start" => reply(&identity.github_start(args(body)?).await?),
951 "github_finish" => reply(&identity.github_finish(args(body)?).await?),
952 "github_pending" => reply(&identity.github_pending(args(body)?).await?),
953 "github_sign_up" => reply(&identity.github_sign_up(args(body)?).await?),
954 "github_claim" => reply(&identity.github_claim(args(body)?).await?),
955 "github_account" => reply(&identity.github_account(args(body)?).await?),
956 "github_unlink" => reply(&identity.github_unlink(args(body)?).await?),
957 "github_user_token" => reply(&identity.github_user_token(args(body)?).await?),
958 "github_revoked" => reply(&identity.github_revoked(args(body)?).await?),
959 "github_usernames" => reply(&identity.github_usernames(args(body)?).await?),
960 "oauth_authorize" => reply(&identity.oauth_authorize(args(body)?).await?),
961 "oauth_exchange" => reply(&identity.oauth_exchange(args(body)?).await?),
962 "oauth_refresh" => reply(&identity.oauth_refresh(args(body)?).await?),
963 "list_oauth_grants" => reply(&identity.list_oauth_grants(args(body)?).await?),
964 "revoke_oauth_grant" => reply(&identity.revoke_oauth_grant(args(body)?).await?),
965 "update_oauth_grant" => reply(&identity.update_oauth_grant(args(body)?).await?),
966 "device_start" => reply(&identity.device_start(args(body)?).await?),
967 "device_lookup" => reply(&identity.device_lookup(args(body)?).await?),
968 "device_resolve" => reply(&identity.device_resolve(args(body)?).await?),
969 "device_claim" => reply(&identity.device_claim(args(body)?).await?),
970 "resend_verification" => reply(&identity.resend_verification(args(body)?).await?),
971 "verify_email" => reply(&identity.verify_email(args(body)?).await?),
972 "confirm_email_code" => reply(&identity.confirm_email_code(args(body)?).await?),
973 "change_pending_email" => reply(&identity.change_pending_email(args(body)?).await?),
974 "request_password_reset" => reply(&identity.request_password_reset(args(body)?).await?),
975 "reset_password" => reply(&identity.reset_password(args(body)?).await?),
976 // A person's email addresses; see emails.rs and security.rs.
977 "list_emails" => reply(&identity.list_emails(args(body)?).await?),
978 "add_email" => reply(&identity.add_email(args(body)?).await?),
979 "remove_email" => reply(&identity.remove_email(args(body)?).await?),
980 "resend_email_verification" => reply(&identity.resend_email_verification(args(body)?).await?),
981 "update_email_settings" => reply(&identity.update_email_settings(args(body)?).await?),
982 "reauthenticate" => reply(&identity.reauthenticate(args(body)?).await?),
983 // Two-factor authentication; see two_factor.rs.
984 "two_factor_status" => reply(&identity.two_factor_status(args(body)?).await?),
985 "two_factor_start" => reply(&identity.two_factor_start(args(body)?).await?),
986 "two_factor_enable" => reply(&identity.two_factor_enable(args(body)?).await?),
987 "two_factor_disable" => reply(&identity.two_factor_disable(args(body)?).await?),
988 "two_factor_recovery_codes" => reply(&identity.two_factor_recovery_codes(args(body)?).await?),
989 "two_factor_sign_in" => reply(&identity.two_factor_sign_in(args(body)?).await?),
990 "security_log" => reply(&identity.security_log(args(body)?).await?),
991 "email_owners" => reply(&identity.email_owners(args(body)?).await?),
992 "commit_identity" => reply(&identity.commit_identity(args(body)?).await?),
993 "push_email_guard" => reply(&identity.push_email_guard(args(body)?).await?),
994 "admin_user" => reply(&identity.admin_user(args(body)?).await?),
995 "admin_remove_email" => reply(&identity.admin_remove_email(args(body)?).await?),
996 "sign_out" => reply(&identity.sign_out(args(body)?).await?),
997 "user_for_session" => reply(&identity.user_for_session(args(body)?).await?),
998 "user_for_git_credentials" => reply(&identity.user_for_git_credentials(args(body)?).await?),
999 "user_for_access_token" => {
1000 let a: TokenArgs = args(body)?;
1001 reply(&identity.user_for_access_token(&a.token).await?)
1002 }
1003 "user_for_ssh_key" => reply(&identity.user_for_ssh_key(args(body)?).await?),
1004 "user_by_username" => reply(&identity.user_by_username(args(body)?).await?),
1005 "user_by_id" => reply(&identity.current_user(args(body)?).await?),
1006 "usernames" => reply(&identity.usernames(args(body)?).await?),
1007 // The API: each username's chosen case, shown beside it.
1008 "display_usernames" => reply(&identity.display_usernames(args(body)?).await?),
1009 "accounts" => reply(&identity.accounts(args(body)?).await?),
1010 "users_for_audience" => reply(&identity.users_for_audience(args(body)?).await?),
1011 "notify_by_email" => reply(&identity.notify_by_email(args(body)?).await?),
1012 "profile" => reply(&identity.profile(args(body)?).await?),
1013 "update_profile" => {
1014 let outcome = identity.update_profile(args(body)?).await?;
1015 if let Outcome::Ok(profile) = &outcome {
1016 identity.announce_user(&profile.username, None).await;
1017 }
1018 reply(&outcome)
1019 }
1020 "directory" => reply(&identity.directory(args(body)?).await?),
1021 "profile_workspaces" => reply(&identity.profile_workspaces(args(body)?).await?),
1022 // Each person's dock pins, per workspace; see dock.rs.
1023 "dock_pins" => reply(&identity.dock_pins(args(body)?).await?),
1024 "set_dock_pins" => reply(&identity.set_dock_pins(args(body)?).await?),
1025 // Each person's own state of a workspace's Getting started; see onboarding.rs.
1026 "onboarding" => reply(&identity.onboarding(args(body)?).await?),
1027 "set_onboarding" => reply(&identity.set_onboarding(args(body)?).await?),
1028 // Each person's chat sounds and desktop notifications; see sounds.rs.
1029 "sound_settings" => reply(&identity.sound_settings(args(body)?).await?),
1030 "set_sound_settings" => reply(&identity.set_sound_settings(args(body)?).await?),
1031 "list_ssh_keys" => reply(&identity.list_ssh_keys(args(body)?).await?),
1032 // Services only: who registered each key, for verifying commit
1033 // signatures (repos' signatures.rs).
1034 "ssh_key_owners" => reply(&identity.ssh_key_owners(args(body)?).await?),
1035 "add_ssh_key" => reply(&identity.add_ssh_key(args(body)?).await?),
1036 "remove_ssh_key" => reply(&identity.remove_ssh_key(args(body)?).await?),
1037 // A repository's deploy keys, and who an SSH key signs in as; see
1038 // deploy_keys.rs.
1039 "list_deploy_keys" => reply(&identity.list_deploy_keys(args(body)?).await?),
1040 "get_deploy_key" => reply(&identity.get_deploy_key(args(body)?).await?),
1041 "add_deploy_key" => reply(&identity.add_deploy_key(args(body)?).await?),
1042 "remove_deploy_key" => reply(&identity.remove_deploy_key(args(body)?).await?),
1043 "principal_for_ssh_key" => reply(&identity.principal_for_ssh_key(args(body)?).await?),
1044 "list_access_tokens" => reply(&identity.list_access_tokens(args(body)?).await?),
1045 "create_access_token" => reply(&identity.create_access_token(args(body)?).await?),
1046 // Making and changing a person's or a workspace's token, and
1047 // workspaces' rules for tokens; see token_reach.rs.
1048 "create_token" => reply(&identity.create_token(args(body)?).await?),
1049 "update_token" => reply(&identity.update_token(args(body)?).await?),
1050 "regenerate_token" => reply(&identity.regenerate_token(args(body)?).await?),
1051 "get_token_policy" => reply(&identity.get_token_policy(args(body)?).await?),
1052 "set_token_policy" => reply(&identity.set_token_policy(args(body)?).await?),
1053 "list_member_tokens" => reply(&identity.list_member_tokens(args(body)?).await?),
1054 "review_token_request" => reply(&identity.review_token_request(args(body)?).await?),
1055 "revoke_member_token" => reply(&identity.revoke_member_token(args(body)?).await?),
1056 "create_run_credential" => reply(&identity.create_run_credential(args(body)?).await?),
1057 "bind_run_credentials" => reply(&identity.bind_run_credentials(args(body)?).await?),
1058 "revoke_run_credentials" => reply(&identity.revoke_run_credentials(args(body)?).await?),
1059 "create_job_token" => reply(&identity.create_job_token(args(body)?).await?),
1060 "revoke_job_tokens" => reply(&identity.revoke_job_tokens(args(body)?).await?),
1061 // Ask g1t's per-answer, read-only credential (ask_tokens.rs). Only
1062 // the integrations service calls these.
1063 "create_ask_token" => reply(&identity.create_ask_token(args(body)?).await?),
1064 "revoke_ask_token" => reply(&identity.revoke_ask_token(args(body)?).await?),
1065 "remove_access_token" => reply(&identity.remove_access_token(args(body)?).await?),
1066 // Invites; see invites.rs.
1067 // Invites to g1t from Invite a friend; see invites/friends.rs.
1068 "list_invites" => reply(&identity.list_invites(args(body)?).await?),
1069 "create_invite" => reply(&identity.create_invite(args(body)?).await?),
1070 "revoke_invite" => reply(&identity.revoke_invite(args(body)?).await?),
1071 "resend_invite" => reply(&identity.resend_invite(args(body)?).await?),
1072 "check_invite" => reply(&identity.check_invite(args(body)?).await?),
1073 "accept_invite" => reply(&identity.accept_invite(args(body)?).await?),
1074 "invite_member" => reply(&identity.invite_member(args(body)?).await?),
1075 "list_invitations" => reply(&identity.list_invitations(args(body)?).await?),
1076 "accept_invitation" => reply(&identity.accept_invitation(args(body)?).await?),
1077 "decline_invitation" => reply(&identity.decline_invitation(args(body)?).await?),
1078 "find_people" => reply(&identity.find_people(args(body)?).await?),
1079 "workspace_invites" => reply(&identity.workspace_invites(args(body)?).await?),
1080 "revoke_workspace_invite" => reply(&identity.revoke_workspace_invite(args(body)?).await?),
1081 "resend_workspace_invite" => reply(&identity.resend_workspace_invite(args(body)?).await?),
1082 // Who has access to a repository; see access.rs.
1083 "repo_access" => reply(&identity.repo_access(args(body)?).await?),
1084 "add_collaborator" => reply(&identity.add_collaborator(args(body)?).await?),
1085 "set_collaborator_role" => reply(&identity.set_collaborator_role(args(body)?).await?),
1086 "remove_collaborator" => reply(&identity.remove_collaborator(args(body)?).await?),
1087 "collaborator_permission" => reply(&identity.collaborator_permission(args(body)?).await?),
1088 "can_read_repo" => reply(&identity.can_read_repo(args(body)?).await?),
1089 "my_repo_invitations" => reply(&identity.my_repo_invitations(args(body)?).await?),
1090 "respond_repo_invitation" => reply(&identity.respond_repo_invitation(args(body)?).await?),
1091 "revoke_repo_invitation" => reply(&identity.revoke_repo_invitation(args(body)?).await?),
1092 "set_base_permission" => reply(&identity.set_base_permission(args(body)?).await?),
1093 // Where a workspace keeps its repositories' git data (EU residency).
1094 "workspace_residency" => reply(&identity.workspace_residency(args(body)?).await?),
1095 "set_workspace_residency" => reply(&identity.set_workspace_residency(args(body)?).await?),
1096 "outside_collaborators" => reply(&identity.outside_collaborators(args(body)?).await?),
1097 "forget_repo_access" => {
1098 let a: g1t_contracts::access::ForgetRepoAccessArgs = args(body)?;
1099 // A purged repository's deploy keys go with its access.
1100 identity.forget_deploy_keys(&a.repo_id).await?;
1101 reply(&identity.forget_repo_access(a).await?)
1102 }
1103 // Teams (teams.rs).
1104 "list_teams" => reply(&identity.list_teams(args(body)?).await?),
1105 "get_team" => reply(&identity.get_team(args(body)?).await?),
1106 "create_team" => reply(&identity.create_team(args(body)?).await?),
1107 "set_team_creation" => reply(&identity.set_team_creation(args(body)?).await?),
1108 "update_team" => reply(&identity.update_team(args(body)?).await?),
1109 "delete_team" => reply(&identity.delete_team(args(body)?).await?),
1110 "team_members" => reply(&identity.team_members(args(body)?).await?),
1111 "set_team_member" => reply(&identity.set_team_member(args(body)?).await?),
1112 "remove_team_member" => reply(&identity.remove_team_member(args(body)?).await?),
1113 "child_teams" => reply(&identity.child_teams(args(body)?).await?),
1114 "team_repos" => reply(&identity.team_repos(args(body)?).await?),
1115 "set_team_repo" => reply(&identity.set_team_repo(args(body)?).await?),
1116 "remove_team_repo" => reply(&identity.remove_team_repo(args(body)?).await?),
1117 "user_teams" => reply(&identity.user_teams(args(body)?).await?),
1118 "team_memberships" => reply(&identity.team_memberships(args(body)?).await?),
1119 "resolve_teams" => reply(&identity.resolve_teams(args(body)?).await?),
1120 // The people directory (people.rs).
1121 "people_directory" => reply(&identity.people_directory(args(body)?).await?),
1122 "set_member_profile" => reply(&identity.set_member_profile(args(body)?).await?),
1123 "resolve_owners" => reply(&identity.resolve_owners(args(body)?).await?),
1124 // Staff only: sudo.g1t.sh, over its service binding. See admin.rs.
1125 "notify_owners" => reply(&identity.notify_owners(args(body)?).await?),
1126 "admin_workspaces" => reply(&identity.admin_workspaces(args(body)?).await?),
1127 "admin_workspace" => reply(&identity.admin_workspace(args(body)?).await?),
1128 "admin_invites" => reply(&identity.admin_invites(args(body)?).await?),
1129 "admin_revoke_invite" => reply(&identity.admin_revoke_invite(args(body)?).await?),
1130 "admin_grant_invites" => reply(&identity.admin_grant_invites(args(body)?).await?),
1131 // Suspending accounts and workspaces, blocking email domains; see suspension.rs.
1132 "admin_suspend_user" => reply(&identity.admin_suspend_user(args(body)?).await?),
1133 "admin_suspend_workspace" => reply(&identity.admin_suspend_workspace(args(body)?).await?),
1134 "admin_blocked_domains" => reply(&identity.admin_blocked_domains().await?),
1135 "admin_block_domain" => reply(&identity.admin_block_domain(args(body)?).await?),
1136 // Deleted workspaces, restored or purged by staff; see deletion.rs.
1137 "admin_deleted_workspaces" => reply(&identity.admin_deleted_workspaces().await?),
1138 "admin_restore_workspace" => reply(&identity.admin_restore_workspace(args(body)?).await?),
1139 "admin_purge_workspace" => reply(&identity.admin_purge_workspace(args(body)?).await?),
1140 // Deleting accounts (account_deletion.rs): the person from the
1141 // site, staff from sudo. There is no API route for it.
1142 "check_account_deletion" => reply(&identity.check_account_deletion(args(body)?).await?),
1143 "delete_account" => reply(&identity.delete_account(args(body)?).await?),
1144 "admin_delete_account" => reply(&identity.admin_delete_account(args(body)?).await?),
1145 "request_erasure" => reply(&identity.request_erasure(args(body)?).await?),
1146 "my_erasure" => reply(&identity.my_erasure(args(body)?).await?),
1147 "admin_intake_erasure" => reply(&identity.intake_erasure(args(body)?).await?),
1148 "admin_erasure_requests" => reply(&identity.erasure_requests().await?),
1149 "admin_review_erasure" => reply(&identity.review_erasure(args(body)?).await?),
1150 "admin_pending_purges" => reply(&identity.pending_purge_jobs().await?),
1151 "admin_deleted_accounts" => reply(&identity.admin_deleted_accounts().await?),
1152 "admin_restore_account" => reply(&identity.admin_restore_account(args(body)?).await?),
1153 "admin_purge_account" => reply(&identity.admin_purge_account(args(body)?).await?),
1154 // Workspace aliases, set by staff only; see aliases.rs.
1155 "admin_aliases" => reply(&identity.admin_aliases().await?),
1156 "admin_set_alias" => reply(&identity.admin_set_alias(args(body)?).await?),
1157 "admin_remove_alias" => reply(&identity.admin_remove_alias(args(body)?).await?),
1158 _ => Response::error("Unknown method", 404),
1159 };
1160 served.finish(answered)
1161}
1162
1163#[cfg(test)]
1164mod register_tests {
1165 use super::*;
1166
1167 #[test]
1168 fn nobody_registers_as_g1t() {
1169 // What register checks the username with, whatever its case.
1170 for username in ["g1t", "G1T", "g1t-agent", "G1t-Agent"] {
1171 assert!(claimable_username(username).is_none(), "{username}");
1172 }
1173 assert_eq!(claimable_username("ana").map(|name| name.canonical).as_deref(), Some("ana"));
1174 }
1175
1176 #[test]
1177 fn a_username_keeps_the_case_it_was_chosen_in() {
1178 let name = claimable_username("Ana-Lopez").unwrap();
1179 assert_eq!(name.canonical, "ana-lopez");
1180 assert_eq!(name.display_if_cased(), Some("Ana-Lopez"));
1181 assert!(USERNAME_RULES.contains("either case"));
1182 }
1183}