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