g1t/services/identity/src/lib.rs
| 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 | |
| 6 | mod access; |
| 7 | mod admin; |
| 8 | mod avatars; |
| 9 | mod crypto; |
| 10 | mod deletion; |
| 11 | mod device; |
| 12 | mod directory; |
| 13 | mod email; |
| 14 | mod emails; |
| 15 | mod github; |
| 16 | mod invites; |
| 17 | mod oauth; |
| 18 | mod profiles; |
| 19 | mod rename; |
| 20 | mod run_credentials; |
| 21 | mod security; |
| 22 | mod throttle; |
| 23 | mod tokens; |
| 24 | mod workspaces; |
| 25 | |
| 26 | use g1t_contracts::identity::*; |
| 27 | use g1t_contracts::time::{SQL_NOW, rfc3339, sql_after}; |
| 28 | use g1t_contracts::{FailureCode, Outcome, User, Viewer, is_valid_namespace, new_id}; |
| 29 | use g1t_kit::{args, now_ms, reply, rpc_method}; |
| 30 | use serde::Deserialize; |
| 31 | use tokens::TOKEN_PREFIX; |
| 32 | use worker::wasm_bindgen::JsValue; |
| 33 | use worker::{Context, D1Database, Env, Request, Response, Result, ScheduleContext, ScheduledEvent, event}; |
| 34 | |
| 35 | const SESSION_TTL_SECONDS: u64 = 30 * 24 * 60 * 60; |
| 36 | const VERIFY_TTL_SECONDS: u64 = 24 * 60 * 60; |
| 37 | const RESET_TTL_SECONDS: u64 = 60 * 60; |
| 38 | const MIN_PASSWORD_LENGTH: usize = 10; |
| 39 | const PASSWORD_TOO_SHORT: &str = "Use a password of at least 10 characters."; |
| 40 | |
| 41 | /// A user as selected from the database; `verified` arrives as 0 or 1. |
| 42 | #[derive(Deserialize)] |
| 43 | struct Account { |
| 44 | id: String, |
| 45 | username: String, |
| 46 | verified: u8, |
| 47 | /// Selected only where the person is being shown to themselves. |
| 48 | #[serde(default)] |
| 49 | avatar: Option<String>, |
| 50 | } |
| 51 | |
| 52 | impl From<Account> for User { |
| 53 | fn from(row: Account) -> Self { |
| 54 | User { |
| 55 | id: row.id, |
| 56 | username: row.username, |
| 57 | verified: row.verified != 0, |
| 58 | avatar: row.avatar, |
| 59 | ..User::default() |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | #[derive(Deserialize)] |
| 65 | struct UserRow { |
| 66 | id: String, |
| 67 | username: String, |
| 68 | password_hash: String, |
| 69 | verified: u8, |
| 70 | } |
| 71 | |
| 72 | /// The owner of an emailed token. |
| 73 | #[derive(Deserialize)] |
| 74 | struct TokenOwner { |
| 75 | id: String, |
| 76 | username: String, |
| 77 | /// The address a link was sent to; null on links from before accounts |
| 78 | /// had several, which are for the primary. |
| 79 | #[serde(default)] |
| 80 | email_id: Option<String>, |
| 81 | } |
| 82 | |
| 83 | #[derive(Deserialize)] |
| 84 | struct KeyRow { |
| 85 | id: String, |
| 86 | title: String, |
| 87 | fingerprint: String, |
| 88 | created_at: String, |
| 89 | } |
| 90 | |
| 91 | impl From<KeyRow> for SshKey { |
| 92 | fn from(row: KeyRow) -> Self { |
| 93 | SshKey { |
| 94 | id: row.id, |
| 95 | title: row.title, |
| 96 | fingerprint: row.fingerprint, |
| 97 | created_at: row.created_at, |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | struct Identity { |
| 103 | db: D1Database, |
| 104 | env: Env, |
| 105 | } |
| 106 | |
| 107 | impl Identity { |
| 108 | /// Runs a query that returns at most one user, for showing to others: |
| 109 | /// without their workspaces. |
| 110 | async fn find_public_user(&self, sql: &str, param: &str) -> Result<Viewer> { |
| 111 | Ok(self |
| 112 | .db |
| 113 | .prepare(sql) |
| 114 | .bind(&[JsValue::from(param)])? |
| 115 | .first::<Account>(None) |
| 116 | .await? |
| 117 | .map(User::from)) |
| 118 | } |
| 119 | |
| 120 | /// Attaches the workspaces a user belongs to, so that any service can |
| 121 | /// authorize them without asking again. |
| 122 | async fn with_workspaces(&self, user: Viewer) -> Result<Viewer> { |
| 123 | let Some(mut user) = user else { |
| 124 | return Ok(None); |
| 125 | }; |
| 126 | let memberships = self.memberships(&user.id).await?; |
| 127 | // Access to a workspace is used only within its policy; see security.rs. |
| 128 | user.workspaces = self.within_policy(&user.id, memberships).await?; |
| 129 | // Roles on single repositories, under the same policy (access.rs). |
| 130 | let grants = self.grants_of(&user.id).await?; |
| 131 | user.grants = self.grants_within_policy(&user.id, grants).await?; |
| 132 | Ok(Some(user)) |
| 133 | } |
| 134 | |
| 135 | /// Runs a query that resolves credentials to at most one user. |
| 136 | async fn find_user(&self, sql: &str, param: &str) -> Result<Viewer> { |
| 137 | let user = self.find_public_user(sql, param).await?; |
| 138 | self.with_workspaces(user).await |
| 139 | } |
| 140 | |
| 141 | /// Stores a one-time token of `kind` for the user and returns it. |
| 142 | async fn issue_email_token(&self, user_id: &str, kind: &str, ttl: u64) -> Result<String> { |
| 143 | let token = crypto::random_hex(32); |
| 144 | self.db |
| 145 | .prepare(format!( |
| 146 | "INSERT INTO email_tokens (id, user_id, kind, expires_at) |
| 147 | VALUES (?, ?, ?, {})", |
| 148 | sql_after(ttl) |
| 149 | )) |
| 150 | .bind(&[ |
| 151 | crypto::sha256_hex(&token).into(), |
| 152 | user_id.into(), |
| 153 | kind.into(), |
| 154 | ])? |
| 155 | .run() |
| 156 | .await?; |
| 157 | Ok(token) |
| 158 | } |
| 159 | |
| 160 | /// Consumes a token of `kind`, returning its owner if it was valid. |
| 161 | async fn redeem_email_token(&self, token: &str, kind: &str) -> Result<Option<TokenOwner>> { |
| 162 | let id = crypto::sha256_hex(token); |
| 163 | let owner = self |
| 164 | .db |
| 165 | .prepare(format!( |
| 166 | "SELECT users.id, users.username, email_tokens.email_id FROM email_tokens |
| 167 | JOIN users ON users.id = email_tokens.user_id |
| 168 | WHERE email_tokens.id = ? AND email_tokens.kind = ? |
| 169 | AND email_tokens.expires_at > {SQL_NOW}" |
| 170 | )) |
| 171 | .bind(&[id.as_str().into(), kind.into()])? |
| 172 | .first::<TokenOwner>(None) |
| 173 | .await?; |
| 174 | if let Some(owner) = &owner { |
| 175 | // Every outstanding token of this kind dies with the one used: |
| 176 | // every reset link, and every confirmation link for the same |
| 177 | // address (another address's links still work). |
| 178 | self.db |
| 179 | .prepare( |
| 180 | "DELETE FROM email_tokens WHERE user_id = ?1 AND kind = ?2 |
| 181 | AND (?2 = 'reset' OR email_id IS ?3)", |
| 182 | ) |
| 183 | .bind(&[ |
| 184 | owner.id.as_str().into(), |
| 185 | kind.into(), |
| 186 | owner.email_id.as_deref().map_or(JsValue::NULL, Into::into), |
| 187 | ])? |
| 188 | .run() |
| 189 | .await?; |
| 190 | } |
| 191 | Ok(owner) |
| 192 | } |
| 193 | |
| 194 | async fn send_verification(&self, user: &User, email: &str) -> Result<()> { |
| 195 | let token = self |
| 196 | .issue_email_token(&user.id, "verify", VERIFY_TTL_SECONDS) |
| 197 | .await?; |
| 198 | email::send_verification(&self.env, email, &user.username, &token).await |
| 199 | } |
| 200 | |
| 201 | async fn resend_verification(&self, a: UserArgs) -> Result<Outcome<bool>> { |
| 202 | if !self.allow(throttle::CONFIRM_ACCOUNT, &a.user.id).await? { |
| 203 | return Ok(Outcome::fail(FailureCode::Conflict, "Too many confirmation emails this hour. Check your inbox, or try again later.")); |
| 204 | } |
| 205 | self.resend_primary(&a.user).await |
| 206 | } |
| 207 | |
| 208 | async fn verify_email(&self, a: EmailTokenArgs) -> Result<Outcome<User>> { |
| 209 | let Some(owner) = self.redeem_email_token(&a.token, "verify").await? else { |
| 210 | return Ok(Outcome::fail( |
| 211 | FailureCode::Invalid, |
| 212 | "This confirmation link is not valid or has expired.", |
| 213 | )); |
| 214 | }; |
| 215 | if let Outcome::Fail(failure) = self.confirm_address(&owner.id, owner.email_id.as_deref()).await? { |
| 216 | return Ok(Outcome::Fail(failure)); |
| 217 | } |
| 218 | // Whether the account is confirmed: whether its primary is. |
| 219 | let verified = self |
| 220 | .find_public_user( |
| 221 | "SELECT id, username, email_verified_at IS NOT NULL AS verified FROM users WHERE id = ?", |
| 222 | &owner.id, |
| 223 | ) |
| 224 | .await? |
| 225 | .is_some_and(|user| user.verified); |
| 226 | Ok(Outcome::Ok(User { |
| 227 | id: owner.id, |
| 228 | username: owner.username, |
| 229 | verified, |
| 230 | ..User::default() |
| 231 | })) |
| 232 | } |
| 233 | |
| 234 | /// Any confirmed address of an account can ask for a reset; so can the |
| 235 | /// unconfirmed address a new account signed up with. See emails.rs. |
| 236 | async fn request_password_reset(&self, a: EmailArgs) -> Result<bool> { |
| 237 | let allowed = self.allow(throttle::RESET_EMAIL, &a.email).await? |
| 238 | && match a.client.as_deref() { |
| 239 | Some(client) => self.allow(throttle::RESET_CLIENT, client).await?, |
| 240 | None => true, |
| 241 | }; |
| 242 | if allowed && let Some(target) = self.reset_target(&a.email).await? { |
| 243 | let token = crypto::random_hex(32); |
| 244 | self.db |
| 245 | .prepare(format!( |
| 246 | "INSERT INTO email_tokens (id, user_id, kind, expires_at, email_id) |
| 247 | VALUES (?, ?, 'reset', {}, ?)", |
| 248 | sql_after(RESET_TTL_SECONDS) |
| 249 | )) |
| 250 | .bind(&[ |
| 251 | crypto::sha256_hex(&token).into(), |
| 252 | target.user_id.as_str().into(), |
| 253 | target.email_id.as_str().into(), |
| 254 | ])? |
| 255 | .run() |
| 256 | .await?; |
| 257 | email::send_password_reset(&self.env, &target.display, &target.username, &token).await?; |
| 258 | // The primary and the backup hear of it when it went elsewhere. |
| 259 | let elsewhere = self.notice_recipients(&target.user_id, false).await?; |
| 260 | for address in elsewhere.iter().filter(|address| !address.eq_ignore_ascii_case(&target.display)) { |
| 261 | let change = format!("A password reset was asked for through {}", target.display); |
| 262 | if let Err(error) = email::send_security_notice(&self.env, address, &target.username, &change).await { |
| 263 | worker::console_error!("security notice failed: {error}"); |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | // The same answer either way, so addresses cannot be probed. |
| 268 | Ok(true) |
| 269 | } |
| 270 | |
| 271 | async fn reset_password(&self, a: ResetPasswordArgs) -> Result<Outcome<User>> { |
| 272 | if a.password.chars().count() < MIN_PASSWORD_LENGTH { |
| 273 | return Ok(Outcome::fail(FailureCode::Invalid, PASSWORD_TOO_SHORT)); |
| 274 | } |
| 275 | let Some(owner) = self.redeem_email_token(&a.token, "reset").await? else { |
| 276 | return Ok(Outcome::fail( |
| 277 | FailureCode::Invalid, |
| 278 | "This reset link is not valid or has expired.", |
| 279 | )); |
| 280 | }; |
| 281 | self.db |
| 282 | .prepare("UPDATE users SET password_hash = ? WHERE id = ?") |
| 283 | .bind(&[ |
| 284 | crypto::hash_password(&a.password).into(), |
| 285 | owner.id.as_str().into(), |
| 286 | ])? |
| 287 | .run() |
| 288 | .await?; |
| 289 | // Following an emailed link also proves the address it went to |
| 290 | // (unless another account confirmed it first). |
| 291 | let _ = self.confirm_address(&owner.id, owner.email_id.as_deref()).await?; |
| 292 | // Anyone signed in with the old password is signed out, and nobody |
| 293 | // stays locked out by the wrong guesses before it. |
| 294 | self.db |
| 295 | .prepare("DELETE FROM sessions WHERE user_id = ?") |
| 296 | .bind(&[owner.id.as_str().into()])? |
| 297 | .run() |
| 298 | .await?; |
| 299 | self.clear(&throttle::key(throttle::PASSWORD_ACCOUNT, &owner.id)).await?; |
| 300 | self.log_security(&owner.id, "password_changed", None, None).await; |
| 301 | self.tell_primary_and_backup(&owner.id, &owner.username, "Your password was changed").await; |
| 302 | let verified = self |
| 303 | .find_public_user( |
| 304 | "SELECT id, username, email_verified_at IS NOT NULL AS verified FROM users WHERE id = ?", |
| 305 | &owner.id, |
| 306 | ) |
| 307 | .await? |
| 308 | .is_some_and(|user| user.verified); |
| 309 | Ok(Outcome::Ok(User { |
| 310 | id: owner.id, |
| 311 | username: owner.username, |
| 312 | verified, |
| 313 | ..User::default() |
| 314 | })) |
| 315 | } |
| 316 | |
| 317 | /// The account a login names: a username, or any confirmed address. |
| 318 | async fn password_row(&self, login: &str) -> Result<Option<UserRow>> { |
| 319 | let login = login.trim().to_lowercase(); |
| 320 | let (column, value) = if login.contains('@') { |
| 321 | match self.user_with_verified_email(&login).await? { |
| 322 | Some(id) => ("id", id), |
| 323 | None => return Ok(None), |
| 324 | } |
| 325 | } else { |
| 326 | ("username", login) |
| 327 | }; |
| 328 | self.db |
| 329 | .prepare(format!( |
| 330 | "SELECT id, username, password_hash, email_verified_at IS NOT NULL AS verified FROM users WHERE {column} = ?" |
| 331 | )) |
| 332 | .bind(&[JsValue::from(value)])? |
| 333 | .first::<UserRow>(None) |
| 334 | .await |
| 335 | } |
| 336 | |
| 337 | /// Checks a password for a login, throttled (see throttle.rs). The |
| 338 | /// refusal is one of two messages, the same for every account. |
| 339 | async fn checked_password( |
| 340 | &self, |
| 341 | login: &str, |
| 342 | password: &str, |
| 343 | client: Option<&str>, |
| 344 | ) -> Result<std::result::Result<User, &'static str>> { |
| 345 | let row = self.password_row(login).await?; |
| 346 | let subject = row.as_ref().map_or_else(|| login.trim().to_lowercase(), |row| row.id.clone()); |
| 347 | let (account_key, client_key) = Identity::password_keys(&subject, client); |
| 348 | if self.password_locked(&account_key, client_key.as_deref()).await? { |
| 349 | return Ok(Err(throttle::THROTTLED)); |
| 350 | } |
| 351 | let owner = row.as_ref().map(|row| (row.id.clone(), row.username.clone())); |
| 352 | match row.filter(|row| !row.password_hash.is_empty() && crypto::verify_password(password, &row.password_hash)) { |
| 353 | Some(row) => { |
| 354 | self.clear(&account_key).await?; |
| 355 | Ok(Ok(User { |
| 356 | id: row.id, |
| 357 | username: row.username, |
| 358 | verified: row.verified != 0, |
| 359 | ..User::default() |
| 360 | })) |
| 361 | } |
| 362 | None => { |
| 363 | let owner = owner.as_ref().map(|(id, name)| (id.as_str(), name.as_str())); |
| 364 | self.password_failed(&account_key, client_key.as_deref(), owner).await?; |
| 365 | Ok(Err("Incorrect username or password.")) |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | async fn user_for_password(&self, login: &str, password: &str) -> Result<Viewer> { |
| 371 | let user = self.checked_password(login, password, None).await?.ok(); |
| 372 | self.with_workspaces(user).await |
| 373 | } |
| 374 | |
| 375 | async fn register(&self, a: RegisterArgs) -> Result<Outcome<SignedIn>> { |
| 376 | let username = a.username.trim().to_lowercase(); |
| 377 | let email = a.email.trim().to_lowercase(); |
| 378 | let invalid = |message: &str| Ok(Outcome::fail(FailureCode::Invalid, message)); |
| 379 | let invite_code = a.invite_code.as_deref().map(str::trim).filter(|code| !code.is_empty()); |
| 380 | // The invite first: without one, nothing else on the form matters. |
| 381 | if self.invites_required() && invite_code.is_none() { |
| 382 | return Ok(Outcome::fail(FailureCode::Forbidden, invites::MISSING)); |
| 383 | } |
| 384 | if !is_valid_namespace(&username) { |
| 385 | return invalid( |
| 386 | "Usernames use lowercase letters, digits and single hyphens, up to 39 characters.", |
| 387 | ); |
| 388 | } |
| 389 | let well_formed_email = email |
| 390 | .split_once('@') |
| 391 | .is_some_and(|(local, domain)| !local.is_empty() && domain.contains('.')) |
| 392 | && !email.contains(char::is_whitespace); |
| 393 | if !well_formed_email { |
| 394 | return invalid("Enter a valid email address."); |
| 395 | } |
| 396 | if a.password.chars().count() < MIN_PASSWORD_LENGTH { |
| 397 | return invalid(PASSWORD_TOO_SHORT); |
| 398 | } |
| 399 | let taken = self |
| 400 | .db |
| 401 | // Usernames and workspaces share one namespace, so that a name |
| 402 | // means the same thing wherever it appears. |
| 403 | // An address is taken once an account has confirmed it; an |
| 404 | // unconfirmed one goes to whoever confirms it first (emails.rs). |
| 405 | .prepare( |
| 406 | "SELECT username FROM users WHERE username = ? |
| 407 | UNION ALL SELECT email FROM user_emails WHERE email = ? AND verified_at IS NOT NULL |
| 408 | UNION ALL SELECT slug FROM workspaces WHERE slug = ?", |
| 409 | ) |
| 410 | .bind(&[ |
| 411 | username.as_str().into(), |
| 412 | email.as_str().into(), |
| 413 | username.as_str().into(), |
| 414 | ])? |
| 415 | .first::<serde_json::Value>(None) |
| 416 | .await?; |
| 417 | // A renamed workspace's old slug stays reserved for it a while, and |
| 418 | // a deleted workspace's for good. |
| 419 | if taken.is_some() || self.slug_held(&username).await? || self.slug_deleted(&username).await? { |
| 420 | return Ok(Outcome::fail( |
| 421 | FailureCode::Conflict, |
| 422 | "That username or email is already registered.", |
| 423 | )); |
| 424 | } |
| 425 | let password_hash = crypto::hash_password(&a.password); |
| 426 | let user = match self |
| 427 | .create_account(invites::NewAccount { |
| 428 | username: &username, |
| 429 | email: &email, |
| 430 | password_hash: &password_hash, |
| 431 | verified: false, |
| 432 | invite_code, |
| 433 | client: a.client.as_deref(), |
| 434 | }) |
| 435 | .await? |
| 436 | { |
| 437 | Outcome::Ok(user) => user, |
| 438 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), |
| 439 | }; |
| 440 | // The account exists either way; the email can be sent again later. |
| 441 | // An invite sent to this address confirmed it already (invites.rs). |
| 442 | if !user.verified |
| 443 | && let Err(error) = self.send_verification(&user, &email).await |
| 444 | { |
| 445 | worker::console_error!("verification email failed: {error}"); |
| 446 | } |
| 447 | self.start_session(user).await |
| 448 | } |
| 449 | |
| 450 | async fn sign_in(&self, a: SignInArgs) -> Result<Outcome<SignedIn>> { |
| 451 | let user = match self.checked_password(&a.username, &a.password, a.client.as_deref()).await? { |
| 452 | Ok(user) => user, |
| 453 | Err(message) => return Ok(Outcome::fail(FailureCode::Unauthenticated, message)), |
| 454 | }; |
| 455 | let user = self.with_workspaces(Some(user)).await?.unwrap_or_default(); |
| 456 | self.start_session(user).await |
| 457 | } |
| 458 | |
| 459 | async fn start_session(&self, user: User) -> Result<Outcome<SignedIn>> { |
| 460 | let session_token = crypto::random_hex(32); |
| 461 | self.db |
| 462 | .prepare(format!( |
| 463 | // Signing in is proof it is the person: see security.rs. |
| 464 | "INSERT INTO sessions (id, user_id, expires_at, authenticated_at) VALUES (?, ?, {}, {SQL_NOW})", |
| 465 | sql_after(SESSION_TTL_SECONDS) |
| 466 | )) |
| 467 | .bind(&[ |
| 468 | crypto::sha256_hex(&session_token).into(), |
| 469 | user.id.as_str().into(), |
| 470 | ])? |
| 471 | .run() |
| 472 | .await?; |
| 473 | Ok(Outcome::Ok(SignedIn { |
| 474 | user, |
| 475 | session_token, |
| 476 | })) |
| 477 | } |
| 478 | |
| 479 | async fn sign_out(&self, a: SessionArgs) -> Result<()> { |
| 480 | self.db |
| 481 | .prepare("DELETE FROM sessions WHERE id = ?") |
| 482 | .bind(&[crypto::sha256_hex(&a.session_token).into()])? |
| 483 | .run() |
| 484 | .await?; |
| 485 | Ok(()) |
| 486 | } |
| 487 | |
| 488 | async fn user_for_session(&self, a: SessionArgs) -> Result<Viewer> { |
| 489 | self.find_user( |
| 490 | &format!( |
| 491 | "SELECT users.id, users.username, users.email_verified_at IS NOT NULL AS verified, |
| 492 | users.avatar |
| 493 | FROM sessions JOIN users ON users.id = sessions.user_id |
| 494 | WHERE sessions.id = ? AND sessions.expires_at > {SQL_NOW}" |
| 495 | ), |
| 496 | &crypto::sha256_hex(&a.session_token), |
| 497 | ) |
| 498 | .await |
| 499 | } |
| 500 | |
| 501 | async fn user_for_git_credentials(&self, a: GitCredentialsArgs) -> Result<Viewer> { |
| 502 | // Like GitHub, a token alone identifies its user. |
| 503 | if a.secret.starts_with(TOKEN_PREFIX) { |
| 504 | self.user_for_access_token(&a.secret).await |
| 505 | } else { |
| 506 | self.user_for_password(&a.username, &a.secret).await |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | async fn user_for_ssh_key(&self, a: FingerprintArgs) -> Result<Viewer> { |
| 511 | self.find_user( |
| 512 | "SELECT users.id, users.username, users.email_verified_at IS NOT NULL AS verified FROM ssh_keys |
| 513 | JOIN users ON users.id = ssh_keys.user_id |
| 514 | WHERE fingerprint = ?", |
| 515 | &a.fingerprint, |
| 516 | ) |
| 517 | .await |
| 518 | } |
| 519 | |
| 520 | async fn user_by_username(&self, a: UsernameArgs) -> Result<Viewer> { |
| 521 | self.find_public_user( |
| 522 | "SELECT id, username, email_verified_at IS NOT NULL AS verified FROM users WHERE username = ?", |
| 523 | &a.username.to_lowercase(), |
| 524 | ) |
| 525 | .await |
| 526 | } |
| 527 | |
| 528 | async fn usernames(&self, a: UsernamesArgs) -> Result<std::collections::HashMap<String, String>> { |
| 529 | #[derive(serde::Deserialize)] |
| 530 | struct Named { |
| 531 | id: String, |
| 532 | name: String, |
| 533 | } |
| 534 | let ids: Vec<String> = a.ids.into_iter().take(200).collect(); |
| 535 | let mut names = std::collections::HashMap::new(); |
| 536 | if ids.is_empty() { |
| 537 | return Ok(names); |
| 538 | } |
| 539 | let marks = vec!["?"; ids.len()].join(", "); |
| 540 | let bind: Vec<worker::wasm_bindgen::JsValue> = ids.iter().map(|id| id.as_str().into()).collect(); |
| 541 | for sql in [ |
| 542 | format!("SELECT id, username AS name FROM users WHERE id IN ({marks})"), |
| 543 | format!("SELECT id, slug AS name FROM workspaces WHERE id IN ({marks})"), |
| 544 | ] { |
| 545 | for row in self.db.prepare(sql).bind(&bind)?.all().await?.results::<Named>()? { |
| 546 | names.insert(row.id, row.name); |
| 547 | } |
| 548 | } |
| 549 | Ok(names) |
| 550 | } |
| 551 | |
| 552 | async fn list_ssh_keys(&self, a: UserArgs) -> Result<Vec<SshKey>> { |
| 553 | let rows = self |
| 554 | .db |
| 555 | .prepare("SELECT id, title, fingerprint, created_at FROM ssh_keys WHERE user_id = ? ORDER BY id") |
| 556 | .bind(&[a.user.id.into()])? |
| 557 | .all() |
| 558 | .await? |
| 559 | .results::<KeyRow>()?; |
| 560 | Ok(rows.into_iter().map(SshKey::from).collect()) |
| 561 | } |
| 562 | |
| 563 | async fn add_ssh_key(&self, a: AddSshKeyArgs) -> Result<Outcome<SshKey>> { |
| 564 | let Some(key) = crypto::parse_ssh_key(&a.public_key) else { |
| 565 | return Ok(Outcome::fail( |
| 566 | FailureCode::Invalid, |
| 567 | "That is not a valid OpenSSH public key.", |
| 568 | )); |
| 569 | }; |
| 570 | let taken = self |
| 571 | .db |
| 572 | .prepare("SELECT id FROM ssh_keys WHERE fingerprint = ?") |
| 573 | .bind(&[key.fingerprint.as_str().into()])? |
| 574 | .first::<serde_json::Value>(None) |
| 575 | .await?; |
| 576 | if taken.is_some() { |
| 577 | return Ok(Outcome::fail( |
| 578 | FailureCode::Conflict, |
| 579 | "That key is already registered.", |
| 580 | )); |
| 581 | } |
| 582 | let now = now_ms(); |
| 583 | let title = [a.title.trim(), key.comment.as_str(), "SSH key"] |
| 584 | .into_iter() |
| 585 | .find(|candidate| !candidate.is_empty()) |
| 586 | .unwrap_or_default() |
| 587 | .to_owned(); |
| 588 | let row = KeyRow { |
| 589 | id: new_id("key", now), |
| 590 | title, |
| 591 | fingerprint: key.fingerprint, |
| 592 | created_at: rfc3339(now), |
| 593 | }; |
| 594 | self.db |
| 595 | .prepare( |
| 596 | "INSERT INTO ssh_keys (id, user_id, title, public_key, fingerprint, created_at) |
| 597 | VALUES (?, ?, ?, ?, ?, ?)", |
| 598 | ) |
| 599 | .bind(&[ |
| 600 | row.id.as_str().into(), |
| 601 | a.user.id.into(), |
| 602 | row.title.as_str().into(), |
| 603 | key.public_key.into(), |
| 604 | row.fingerprint.as_str().into(), |
| 605 | row.created_at.as_str().into(), |
| 606 | ])? |
| 607 | .run() |
| 608 | .await?; |
| 609 | Ok(Outcome::Ok(row.into())) |
| 610 | } |
| 611 | |
| 612 | /// Deletes a row the user owns from `table`. |
| 613 | async fn remove(&self, table: &str, a: RemoveArgs) -> Result<()> { |
| 614 | self.db |
| 615 | .prepare(format!("DELETE FROM {table} WHERE id = ? AND user_id = ?")) |
| 616 | .bind(&[a.id.into(), a.user.id.into()])? |
| 617 | .run() |
| 618 | .await?; |
| 619 | Ok(()) |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | /// Every 15 minutes: staff hear about waitlist requests that arrived while |
| 624 | /// the last summary's window was still open, so none waits on a later one. |
| 625 | #[event(scheduled)] |
| 626 | async fn scheduled(_event: ScheduledEvent, env: Env, _ctx: ScheduleContext) { |
| 627 | let Ok(db) = env.d1("DB") else { return }; |
| 628 | let identity = Identity { db, env }; |
| 629 | if let Err(error) = identity.notify_staff_of_requests().await { |
| 630 | worker::console_error!("waitlist summary: {error}"); |
| 631 | } |
| 632 | } |
| 633 | |
| 634 | #[event(fetch)] |
| 635 | async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> { |
| 636 | let Some(method) = rpc_method(&request) else { |
| 637 | return Response::error("Not found", 404); |
| 638 | }; |
| 639 | // A replica near the caller when it asks for one (crates/kit/src/d1.rs). |
| 640 | let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?; |
| 641 | let body: serde_json::Value = request.json().await?; |
| 642 | let identity = Identity { db, env }; |
| 643 | |
| 644 | let answered = match method.as_str() { |
| 645 | "register" => { |
| 646 | let outcome = identity.register(args(body)?).await?; |
| 647 | if let Outcome::Ok(signed_in) = &outcome { |
| 648 | identity.announce_user(&signed_in.user.username, Some(&signed_in.user.id)).await; |
| 649 | } |
| 650 | reply(&outcome) |
| 651 | } |
| 652 | "sign_in" => reply(&identity.sign_in(args(body)?).await?), |
| 653 | "create_workspace" => { |
| 654 | let outcome = identity.create_workspace(args(body)?).await?; |
| 655 | if let Outcome::Ok(workspace) = &outcome { |
| 656 | identity.announce_workspace(&workspace.id, &workspace.slug, None).await; |
| 657 | } |
| 658 | reply(&outcome) |
| 659 | } |
| 660 | "get_workspace" => reply(&identity.get_workspace(args(body)?).await?), |
| 661 | "list_members" => reply(&identity.list_members(args(body)?).await?), |
| 662 | "add_member" => reply(&identity.add_member(args(body)?).await?), |
| 663 | "remove_member" => reply(&identity.remove_member(args(body)?).await?), |
| 664 | "update_workspace" => { |
| 665 | let outcome = identity.update_workspace(args(body)?).await?; |
| 666 | if let Outcome::Ok(workspace) = &outcome { |
| 667 | identity.announce_workspace(&workspace.id, &workspace.slug, None).await; |
| 668 | } |
| 669 | reply(&outcome) |
| 670 | } |
| 671 | "rename_workspace" => reply(&identity.rename_workspace(args(body)?).await?), |
| 672 | "check_workspace_rename" => reply(&identity.check_workspace_rename(args(body)?).await?), |
| 673 | "resolve_slug" => reply(&identity.resolve_slug(args(body)?).await?), |
| 674 | "check_workspace_deletion" => reply(&identity.check_workspace_deletion(args(body)?).await?), |
| 675 | "delete_workspace" => reply(&identity.delete_workspace(args(body)?).await?), |
| 676 | "transfer_repo_scopes" => reply(&identity.transfer_repo_scopes(args(body)?).await?), |
| 677 | "set_workspace_avatar" => { |
| 678 | let outcome = identity.set_workspace_avatar(args(body)?).await?; |
| 679 | if let Outcome::Ok(workspace) = &outcome { |
| 680 | identity.announce_workspace(&workspace.id, &workspace.slug, None).await; |
| 681 | } |
| 682 | reply(&outcome) |
| 683 | } |
| 684 | "set_user_avatar" => { |
| 685 | let a: SetUserAvatarArgs = args(body)?; |
| 686 | let (username, id) = (a.user.username.clone(), a.user.id.clone()); |
| 687 | let outcome = identity.set_user_avatar(a).await?; |
| 688 | if matches!(outcome, Outcome::Ok(_)) { |
| 689 | identity.announce_user(&username, Some(&id)).await; |
| 690 | } |
| 691 | reply(&outcome) |
| 692 | } |
| 693 | "list_workspace_tokens" => reply(&identity.list_workspace_tokens(args(body)?).await?), |
| 694 | "create_workspace_token" => reply(&identity.create_workspace_token(args(body)?).await?), |
| 695 | "remove_workspace_token" => reply(&identity.remove_workspace_token(args(body)?).await?), |
| 696 | // Signing in with GitHub; see github.rs. |
| 697 | "github_enabled" => reply(&identity.github_enabled()), |
| 698 | "github_start" => reply(&identity.github_start(args(body)?).await?), |
| 699 | "github_finish" => reply(&identity.github_finish(args(body)?).await?), |
| 700 | "github_pending" => reply(&identity.github_pending(args(body)?).await?), |
| 701 | "github_sign_up" => reply(&identity.github_sign_up(args(body)?).await?), |
| 702 | "github_claim" => reply(&identity.github_claim(args(body)?).await?), |
| 703 | "github_account" => reply(&identity.github_account(args(body)?).await?), |
| 704 | "github_unlink" => reply(&identity.github_unlink(args(body)?).await?), |
| 705 | "github_user_token" => reply(&identity.github_user_token(args(body)?).await?), |
| 706 | "github_revoked" => reply(&identity.github_revoked(args(body)?).await?), |
| 707 | "github_usernames" => reply(&identity.github_usernames(args(body)?).await?), |
| 708 | "oauth_authorize" => reply(&identity.oauth_authorize(args(body)?).await?), |
| 709 | "oauth_exchange" => reply(&identity.oauth_exchange(args(body)?).await?), |
| 710 | "oauth_refresh" => reply(&identity.oauth_refresh(args(body)?).await?), |
| 711 | "list_oauth_grants" => reply(&identity.list_oauth_grants(args(body)?).await?), |
| 712 | "revoke_oauth_grant" => reply(&identity.revoke_oauth_grant(args(body)?).await?), |
| 713 | "update_oauth_grant" => reply(&identity.update_oauth_grant(args(body)?).await?), |
| 714 | "device_start" => reply(&identity.device_start(args(body)?).await?), |
| 715 | "device_lookup" => reply(&identity.device_lookup(args(body)?).await?), |
| 716 | "device_resolve" => reply(&identity.device_resolve(args(body)?).await?), |
| 717 | "device_claim" => reply(&identity.device_claim(args(body)?).await?), |
| 718 | "resend_verification" => reply(&identity.resend_verification(args(body)?).await?), |
| 719 | "verify_email" => reply(&identity.verify_email(args(body)?).await?), |
| 720 | "request_password_reset" => reply(&identity.request_password_reset(args(body)?).await?), |
| 721 | "reset_password" => reply(&identity.reset_password(args(body)?).await?), |
| 722 | // A person's email addresses; see emails.rs and security.rs. |
| 723 | "list_emails" => reply(&identity.list_emails(args(body)?).await?), |
| 724 | "add_email" => reply(&identity.add_email(args(body)?).await?), |
| 725 | "remove_email" => reply(&identity.remove_email(args(body)?).await?), |
| 726 | "resend_email_verification" => reply(&identity.resend_email_verification(args(body)?).await?), |
| 727 | "update_email_settings" => reply(&identity.update_email_settings(args(body)?).await?), |
| 728 | "reauthenticate" => reply(&identity.reauthenticate(args(body)?).await?), |
| 729 | "security_log" => reply(&identity.security_log(args(body)?).await?), |
| 730 | "email_owners" => reply(&identity.email_owners(args(body)?).await?), |
| 731 | "commit_identity" => reply(&identity.commit_identity(args(body)?).await?), |
| 732 | "push_email_guard" => reply(&identity.push_email_guard(args(body)?).await?), |
| 733 | "admin_user" => reply(&identity.admin_user(args(body)?).await?), |
| 734 | "admin_remove_email" => reply(&identity.admin_remove_email(args(body)?).await?), |
| 735 | "sign_out" => reply(&identity.sign_out(args(body)?).await?), |
| 736 | "user_for_session" => reply(&identity.user_for_session(args(body)?).await?), |
| 737 | "user_for_git_credentials" => reply(&identity.user_for_git_credentials(args(body)?).await?), |
| 738 | "user_for_access_token" => { |
| 739 | let a: TokenArgs = args(body)?; |
| 740 | reply(&identity.user_for_access_token(&a.token).await?) |
| 741 | } |
| 742 | "user_for_ssh_key" => reply(&identity.user_for_ssh_key(args(body)?).await?), |
| 743 | "user_by_username" => reply(&identity.user_by_username(args(body)?).await?), |
| 744 | "usernames" => reply(&identity.usernames(args(body)?).await?), |
| 745 | "profile" => reply(&identity.profile(args(body)?).await?), |
| 746 | "update_profile" => { |
| 747 | let outcome = identity.update_profile(args(body)?).await?; |
| 748 | if let Outcome::Ok(profile) = &outcome { |
| 749 | identity.announce_user(&profile.username, None).await; |
| 750 | } |
| 751 | reply(&outcome) |
| 752 | } |
| 753 | "directory" => reply(&identity.directory(args(body)?).await?), |
| 754 | "profile_workspaces" => reply(&identity.profile_workspaces(args(body)?).await?), |
| 755 | "list_ssh_keys" => reply(&identity.list_ssh_keys(args(body)?).await?), |
| 756 | "add_ssh_key" => reply(&identity.add_ssh_key(args(body)?).await?), |
| 757 | "remove_ssh_key" => reply(&identity.remove("ssh_keys", args(body)?).await?), |
| 758 | "list_access_tokens" => reply(&identity.list_access_tokens(args(body)?).await?), |
| 759 | "create_access_token" => reply(&identity.create_access_token(args(body)?).await?), |
| 760 | "update_access_token" => reply(&identity.update_access_token(args(body)?).await?), |
| 761 | "create_agent_token" => reply(&identity.create_agent_token(args(body)?).await?), |
| 762 | "agent_scope" => reply(&identity.agent_scope(args(body)?).await?), |
| 763 | "create_run_credential" => reply(&identity.create_run_credential(args(body)?).await?), |
| 764 | "bind_run_credentials" => reply(&identity.bind_run_credentials(args(body)?).await?), |
| 765 | "revoke_run_credentials" => reply(&identity.revoke_run_credentials(args(body)?).await?), |
| 766 | "remove_access_token" => reply(&identity.remove("access_tokens", args(body)?).await?), |
| 767 | // Invites and the waitlist; see invites.rs. |
| 768 | "registration" => reply(&identity.registration_mode()), |
| 769 | "list_invites" => reply(&identity.list_invites(args(body)?).await?), |
| 770 | "create_invite" => reply(&identity.create_invite(args(body)?).await?), |
| 771 | "revoke_invite" => reply(&identity.revoke_invite(args(body)?).await?), |
| 772 | "check_invite" => reply(&identity.check_invite(args(body)?).await?), |
| 773 | "accept_invite" => reply(&identity.accept_invite(args(body)?).await?), |
| 774 | "invite_member" => reply(&identity.invite_member(args(body)?).await?), |
| 775 | "workspace_invites" => reply(&identity.workspace_invites(args(body)?).await?), |
| 776 | "revoke_workspace_invite" => reply(&identity.revoke_workspace_invite(args(body)?).await?), |
| 777 | "request_access" => reply(&identity.request_access(args(body)?).await?), |
| 778 | // Who has access to a repository; see access.rs. |
| 779 | "repo_access" => reply(&identity.repo_access(args(body)?).await?), |
| 780 | "add_collaborator" => reply(&identity.add_collaborator(args(body)?).await?), |
| 781 | "set_collaborator_role" => reply(&identity.set_collaborator_role(args(body)?).await?), |
| 782 | "remove_collaborator" => reply(&identity.remove_collaborator(args(body)?).await?), |
| 783 | "collaborator_permission" => reply(&identity.collaborator_permission(args(body)?).await?), |
| 784 | "my_repo_invitations" => reply(&identity.my_repo_invitations(args(body)?).await?), |
| 785 | "respond_repo_invitation" => reply(&identity.respond_repo_invitation(args(body)?).await?), |
| 786 | "revoke_repo_invitation" => reply(&identity.revoke_repo_invitation(args(body)?).await?), |
| 787 | "set_base_permission" => reply(&identity.set_base_permission(args(body)?).await?), |
| 788 | "outside_collaborators" => reply(&identity.outside_collaborators(args(body)?).await?), |
| 789 | "forget_repo_access" => reply(&identity.forget_repo_access(args(body)?).await?), |
| 790 | // Staff only: sudo.g1t.sh, over its service binding. See admin.rs. |
| 791 | "notify_owners" => reply(&identity.notify_owners(args(body)?).await?), |
| 792 | "admin_workspaces" => reply(&identity.admin_workspaces(args(body)?).await?), |
| 793 | "admin_workspace" => reply(&identity.admin_workspace(args(body)?).await?), |
| 794 | "admin_waitlist" => reply(&identity.admin_waitlist(args(body)?).await?), |
| 795 | "admin_decide_waitlist" => reply(&identity.admin_decide_waitlist(args(body)?).await?), |
| 796 | "admin_waitlist_pending" => reply(&identity.admin_waitlist_pending().await?), |
| 797 | "admin_invites" => reply(&identity.admin_invites(args(body)?).await?), |
| 798 | "admin_revoke_invite" => reply(&identity.admin_revoke_invite(args(body)?).await?), |
| 799 | "admin_mint_invite" => reply(&identity.admin_mint_invite(args(body)?).await?), |
| 800 | "admin_grant_invites" => reply(&identity.admin_grant_invites(args(body)?).await?), |
| 801 | "admin_invite_tree" => reply(&identity.admin_invite_tree(args(body)?).await?), |
| 802 | "admin_workspace_invites" => reply(&identity.admin_workspace_invites(args(body)?).await?), |
| 803 | _ => Response::error("Unknown method", 404), |
| 804 | }; |
| 805 | served.finish(answered) |
| 806 | } |