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.

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