From 3938702ff5eeca5af139ac27c2b9f2f69fedc226 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Wed, 4 Nov 2026 14:03:44 -0500 Subject: [PATCH] Forgot password says what happened, and sends the set-up email to people with no account here On a self-hosted install, forgot-password now tells the person which case it was: a reset code went out, they have no account here yet and a set-up link went instead, they have an invite to use, or the email isn't on this install. Per-IP and per-email limits keep it from being used to check addresses quickly. The sign-in methods endpoint names who sends each email (the install's own sender, and Cognito's from the pool's EmailConfiguration), so the page can tell a person what to ask IT to allow. Admins get a bulk set-up email that skips anyone sent one in the last hour, and every member sees who hasn't signed in here yet. --- docs/self-host/sign-in.md | 32 +- infra/lib/api-stack.ts | 2 + services/gateway/src/main.rs | 4 + services/gateway/src/permissions.rs | 1 + services/gateway/src/routes/auth.rs | 553 ++++++++++++++++++++++++++- services/gateway/src/routes/users.rs | 242 ++++++++++-- 6 files changed, 789 insertions(+), 45 deletions(-) diff --git a/docs/self-host/sign-in.md b/docs/self-host/sign-in.md index 96646da30..c1ee00c5d 100644 --- a/docs/self-host/sign-in.md +++ b/docs/self-host/sign-in.md @@ -20,7 +20,37 @@ The first admin is the address you gave the install (the Launch Stack's **Your e ### People moved from another CoderHelm -A team moved from CoderHelm's hosted service arrives with its people already on it. Someone who hasn't signed in on the install yet shows **Hasn't set up an account here yet** in **Settings, Team**. An admin opens the row's menu and picks **Send set-up email**: it's the invite email, with the link to set up their account (at most once an hour and five times a week per person). The row then shows when it went. Once they've signed in, it's gone. +A team moved from CoderHelm's hosted service arrives with its people already on it, but not their passwords: each person sets one up here. Until they do, **Settings, Members and roles** shows them as **Hasn't signed in here yet** (any activity time on their row is from the previous CoderHelm, and says so). The counts at the top of the page include how many haven't signed in here yet. Someone with a linked GitHub account, on an install where GitHub sign-in works, also shows **Can sign in with GitHub**. + +There are three ways for them to get the set-up email, the invite email with the link to set up their account: + +- **An admin sends it to one person:** the row's **Send set-up email** button. +- **An admin sends it to everyone at once:** the banner **N people haven't set up an account here yet**, **Send set-up emails to all**. Anyone sent one in the last hour is skipped. An admin can press it three times an hour. +- **The person asks for it themselves:** **Forgot password** on the sign-in page, with their email (see below). + +Each person gets at most one set-up email an hour and five a week, however it was asked for. The row shows when the last one went. Once they've signed in, it's gone. + +### Forgot password + +**Forgot password** on the sign-in page says plainly what happened for the email typed in: + +| The email | What happens | What the page says | +|---|---|---| +| Has an account here | Amazon Cognito sends a reset code | We sent a reset code to the email. | +| On the team, no account here yet (moved from another CoderHelm) | The set-up email goes instead | You don't have an account here yet. We sent you a set-up link instead. | +| Invited, not signed up yet | Nothing is sent | Use the link in the invite email, or ask an admin to send it again. | +| Not on this install | Nothing is sent | There's no account for the email on this CoderHelm. Ask an admin to add you. | + +Because the page says whether an email has an account, it's limited so it can't be used to check addresses quickly: ten asks an hour from one network address, and five an hour for one email. + +### Where these emails come from + +The emails come from two different senders. After sending, the sign-in page names the one to look for, so a person can ask IT to let it through a mail filter (Mimecast, Proofpoint, Microsoft Defender and so on): + +- **Reset codes** come from Amazon Cognito: `no-reply@verificationemail.com` while the user pool sends its own email (the default), or the install's own address once `email.cognitoUsesSes` is on (see [Email](./email.md#sign-up-and-password-emails)). CoderHelm reads this from the user pool's email settings. +- **Set-up and invite emails** come from the install's own email: its Amazon SES address, or the address of CoderHelm's mail relay when the install sends through it (**Settings, Email**). + +If someone says the email never came, check **Settings, Deliveries** for set-up emails, then ask IT to search for, and allow, the sender above. ### At install time diff --git a/infra/lib/api-stack.ts b/infra/lib/api-stack.ts index 78d4e77be..012742b9f 100644 --- a/infra/lib/api-stack.ts +++ b/infra/lib/api-stack.ts @@ -776,6 +776,8 @@ export class ApiStack extends cdk.Stack { "cognito-idp:AssociateSoftwareToken", "cognito-idp:VerifySoftwareToken", "cognito-idp:DescribeUserPoolClient", + // Who sends reset codes (EmailConfiguration), shown on the sign-in page. + "cognito-idp:DescribeUserPool", ], resources: [userPool.userPoolArn], }) diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 412427e79..c253b9914 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -629,6 +629,10 @@ async fn main() -> Result<(), Error> { put(routes::roles::update_role).delete(routes::roles::delete_role), ) .route("/users/invite", post(routes::users::invite_user)) + .route( + "/users/setup-emails", + post(routes::users::send_setup_emails_all), + ) .route("/users/:user_id/role", put(routes::users::update_role)) .route("/users/:user_id/resend", post(routes::users::resend_invite)) .route( diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index f9a0e3ed7..cf417011d 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -375,6 +375,7 @@ pub const CAPABILITIES: &[Capability] = &[ "users::invite_user", "users::resend_invite", "users::send_setup_email", + "users::send_setup_emails_all", "users::update_role", "users::remove_user", "users::link_github", diff --git a/services/gateway/src/routes/auth.rs b/services/gateway/src/routes/auth.rs index 3cb013b28..447b84c95 100644 --- a/services/gateway/src/routes/auth.rs +++ b/services/gateway/src/routes/auth.rs @@ -792,32 +792,256 @@ fn landing_parts( // ── Forgot password ────────────────────────────────────────────────── -/// POST /auth/forgot-password — Send password reset code. +/// Forgot-password asks from one address: ten an hour (on top of the sign-in routes' limit). +const FORGOT_PER_IP_PER_HOUR: u64 = 10; +/// Forgot-password asks for one email: five an hour, from anywhere. +const FORGOT_PER_EMAIL_PER_HOUR: u64 = 5; + +/// What forgot-password does for an email on a self-hosted install, which says plainly what +/// happened (an install is one organization; its admins add people). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Forgot { + /// They have an account here: Cognito sends a reset code. + ResetCode, + /// On the team (copied from another CoderHelm) but with no account here: the set-up email + /// goes instead, from this team record (`pk`, `sk`). + SetUp { team_id: String, sk: String }, + /// As [`Forgot::SetUp`], but one went less than an hour ago (or five this week). + SetUpRecent, + /// Invited and not signed up yet: their invite email has the link. + Invited, + /// Not on this install. + NoAccount, +} + +impl Forgot { + /// Whether this case sends an email (only these two ever do). + pub fn sends(&self) -> bool { + matches!(self, Forgot::ResetCode | Forgot::SetUp { .. }) + } +} + +/// The one place the case is decided. Pure: `in_pool` is whether the user pool has the email, +/// `join` the install's word on it, `member` that member's record when `join` is one. +pub fn plan_forgot( + in_pool: bool, + join: &Join, + member: Option<&HashMap>, + now: chrono::DateTime, +) -> Forgot { + if in_pool { + return Forgot::ResetCode; + } + match (join, member) { + (Join::Member { team_id, user_id }, Some(item)) + if item + .get("email") + .and_then(|v| v.as_s().ok()) + .is_some_and(|e| !e.is_empty()) => + { + if super::users::setup_email_due(item, now) { + Forgot::SetUp { + team_id: team_id.clone(), + sk: user_id.clone(), + } + } else { + Forgot::SetUpRecent + } + } + (Join::Invite, _) => Forgot::Invited, + _ => Forgot::NoAccount, + } +} + +/// What the sign-in page shows for each case: `status` and a plain sentence. +pub fn forgot_reply(case: &Forgot, email: &str) -> serde_json::Value { + let (status, message) = match case { + Forgot::ResetCode => ("code_sent", format!("We sent a reset code to {email}.")), + Forgot::SetUp { .. } => ( + "setup_sent", + "You don't have an account here yet. We sent you a set-up link instead.".to_string(), + ), + Forgot::SetUpRecent => ( + "setup_recent", + "You don't have an account here yet. We sent you a set-up link less than an hour ago: look for that email, or try again later.".to_string(), + ), + Forgot::Invited => ( + "invited", + format!("{email} has an invite here but no account yet. Use the link in the invite email, or ask an admin to send it again."), + ), + Forgot::NoAccount => ( + "no_account", + format!("There's no account for {email} on this CoderHelm. Ask an admin to add you."), + ), + }; + serde_json::json!({ "status": status, "message": message, "email": email }) +} + +fn too_many_forgot() -> (StatusCode, Json) { + ( + StatusCode::TOO_MANY_REQUESTS, + Json(serde_json::json!({ + "error": "Too many password resets asked for just now. Try again in an hour." + })), + ) +} + +/// The key a per-email count is kept under: a hash, so the counter table holds no addresses. +fn email_key(email: &str) -> String { + use sha2::Digest; + let d = Sha256::digest(email.as_bytes()); + d.iter().take(16).map(|b| format!("{b:02x}")).collect() +} + +/// POST /auth/forgot-password — a reset code, or on a self-hosted install for someone on the +/// team with no account here, the set-up email. A self-hosted install says which (or that the +/// email has no account there); the hosted service answers the same for every email. pub async fn forgot_password( State(state): State>, + ip: crate::middleware::rate_limit::ClientIp, Json(body): Json, -) -> Result, StatusCode> { - let email = body.email.trim().to_lowercase(); +) -> Result, (StatusCode, Json)> { + use crate::middleware::rate_limit::allow_shared; + let email = normalize_email(&body.email); + if sign_in::email_domain(&email).is_none() { + return Err(( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "Enter the email you sign in with." })), + )); + } + allow_shared(&state, "forgot_ip", &ip.0, FORGOT_PER_IP_PER_HOUR, 3600) + .await + .map_err(|_| too_many_forgot())?; + allow_shared( + &state, + "forgot_email", + &email_key(&email), + FORGOT_PER_EMAIL_PER_HOUR, + 3600, + ) + .await + .map_err(|_| too_many_forgot())?; + + if !sign_in::applies() { + // The hosted service: the same answer for every email. + let _ = send_reset_code(&state, &email).await; + return Ok(Json(serde_json::json!({ + "status": "sent", + "message": "If an account exists, a reset code was sent" + }))); + } + + let unavailable = |what: &str, e: String| { + error!(error = %e, "{what}"); + ( + StatusCode::SERVICE_UNAVAILABLE, + Json( + serde_json::json!({ "error": "Password reset is unavailable just now. Try again shortly." }), + ), + ) + }; + let in_pool = match state + .cognito + .admin_get_user() + .user_pool_id(&state.config.cognito_user_pool_id) + .username(&email) + .send() + .await + { + Ok(_) => true, + Err(e) if format!("{e:?}").contains("UserNotFound") => false, + Err(e) => { + return Err(unavailable( + "Forgot password: sign-in not checked", + format!("{e}"), + )) + } + }; + let (join, member) = if in_pool { + (Join::Refused, None) + } else { + let facts = sign_in::facts_for(&state, &email) + .await + .map_err(|e| unavailable("Forgot password: join not checked", e))?; + let join = sign_in::decide_join(&facts, chrono::Utc::now()); + let member = match &join { + Join::Member { team_id, user_id } => facts.records.iter().find(|i| { + let g = |k: &str| i.get(k).and_then(|v| v.as_s().ok()).map(String::as_str); + g("pk") == Some(team_id.as_str()) && g("sk") == Some(user_id.as_str()) + }), + _ => None, + } + .cloned(); + (join, member) + }; + let case = plan_forgot(in_pool, &join, member.as_ref(), chrono::Utc::now()); + match &case { + Forgot::ResetCode => { + if let Err(e) = send_reset_code(&state, &email).await { + warn!(error = %e, "Reset code not sent"); + let limited = e.contains("LimitExceeded") || e.contains("TooManyRequests"); + return Err(( + if limited { + StatusCode::TOO_MANY_REQUESTS + } else { + StatusCode::BAD_GATEWAY + }, + Json(serde_json::json!({ + "error": if limited { + "Too many reset codes for this email just now. Try again in a few minutes." + } else { + "We couldn't send a reset code just now. Try again shortly." + } + })), + )); + } + } + Forgot::SetUp { team_id, .. } => { + let Some(item) = member.as_ref() else { + return Err(unavailable("Forgot password: no record", String::new())); + }; + let team = super::users::team_items(&state, team_id) + .await + .map_err(|_| unavailable("Forgot password: team not read", String::new()))?; + let by = super::users::standing_admin(&team).unwrap_or_else(|| email.clone()); + match super::users::deliver_setup_email(&state, team_id, item, &by).await { + Ok(_) => info!(%team_id, "Set-up email sent from the sign-in page"), + Err(super::users::SetupSend::Wait(_)) => { + return Ok(Json(forgot_reply(&Forgot::SetUpRecent, &email))); + } + Err(super::users::SetupSend::Failed(e)) => { + return Err(( + StatusCode::BAD_GATEWAY, + Json(serde_json::json!({ + "error": format!("You don't have an account here yet, and we couldn't send you a set-up link just now ({e}). Ask an admin to send it from Settings, Members and roles.") + })), + )); + } + } + } + _ => {} + } + info!(outcome = ?std::mem::discriminant(&case), sends = case.sends(), "Forgot password"); + Ok(Json(forgot_reply(&case, &email))) +} + +/// Asks Cognito to send `email` a reset code. +async fn send_reset_code(state: &AppState, email: &str) -> Result<(), String> { let hash = cognito_secret_hash( &state.cognito_client_secret, - &email, + email, &state.config.cognito_client_id, ); - - // Always return success to prevent email enumeration - let _ = state + state .cognito .forgot_password() .client_id(&state.config.cognito_client_id) .secret_hash(&hash) - .username(&email) + .username(email) .send() - .await; - - Ok(Json(serde_json::json!({ - "status": "sent", - "message": "If an account exists, a reset code was sent" - }))) + .await + .map(|_| ()) + .map_err(|e| format!("{e:?}")) } /// POST /auth/confirm-reset — Reset password with code. @@ -1238,8 +1462,111 @@ async fn google_callback_inner( /// (public, no session). The sign-in page shows these and no others. pub async fn methods(State(state): State>) -> Response { let github = own_github_client(&state) || super::github_hybrid::available(); - let m = oauth_signin::sign_in_methods(super::setup_checks::self_hosted(), github); - Json(m).into_response() + let self_hosted = super::setup_checks::self_hosted(); + let m = oauth_signin::sign_in_methods(self_hosted, github); + let mut v = serde_json::to_value(m).unwrap_or_default(); + if self_hosted { + // Where the sign-in page's emails come from, so a person can ask IT to let them in. + v["senders"] = senders(&state).await; + } + Json(v).into_response() +} + +/// Amazon Cognito's own sender, when the pool sends its emails itself. +pub const COGNITO_DEFAULT_SENDER: &str = "no-reply@verificationemail.com"; + +/// The address in a From line ("Acme " or a bare address). +pub fn address_of(from: &str) -> Option { + let from = from.trim(); + let addr = match (from.rfind('<'), from.rfind('>')) { + (Some(a), Some(b)) if a < b => &from[a + 1..b], + _ => from, + }; + let addr = addr.trim().to_lowercase(); + (addr.contains('@') && !addr.contains(char::is_whitespace)).then_some(addr) +} + +/// Who sends the pool's reset codes, from its EmailConfiguration: Cognito's own address +/// (COGNITO_DEFAULT, or none set), else the pool's From address, else its SES identity when +/// that is an address. +pub fn cognito_sender( + account: Option<&str>, + from: Option<&str>, + source_arn: Option<&str>, +) -> Option { + if account.is_none_or(|a| a == "COGNITO_DEFAULT") { + return Some(COGNITO_DEFAULT_SENDER.to_string()); + } + from.and_then(address_of).or_else(|| { + source_arn + .and_then(|a| a.rsplit_once("identity/")) + .and_then(|(_, id)| address_of(id)) + }) +} + +/// `{setup, reset_codes}`: the install's own sender (the set-up email) and Cognito's (reset +/// codes). Either is null when it can't be read just now. Kept five minutes per instance. +async fn senders(state: &AppState) -> serde_json::Value { + use std::sync::Mutex; + static CACHE: Mutex> = Mutex::new(None); + let now = chrono::Utc::now().timestamp(); + if let Some((at, v)) = CACHE.lock().ok().and_then(|c| c.clone()) { + if now - at < 300 { + return v; + } + } + let (setup, reset) = tokio::join!(install_sender(state), pool_sender(state)); + let v = serde_json::json!({ "setup": setup, "reset_codes": reset }); + if let Ok(mut c) = CACHE.lock() { + *c = Some((now, v.clone())); + } + v +} + +/// The address the install's own email goes out from: its SES address, or the relay's. +async fn install_sender(state: &AppState) -> Option { + use common::mail::{self, Transport}; + let settings = mail::load(&state.dynamo, &state.config.settings_table_name) + .await + .ok()?; + match mail::transport_of(settings.as_ref(), mail::transport_default()) { + Transport::Coderhelm => { + let creds = common::hybrid::client::credentials()?; + let status = common::hybrid::client::call( + &state.http, + &creds, + "GET", + mail::relay::PATH_STATUS, + None, + ) + .await + .ok()?; + status + .get("from") + .and_then(serde_json::Value::as_str) + .and_then(address_of) + } + _ => address_of(&state.config.ses_from_address), + } +} + +/// Who sends the pool's reset codes, read from the pool. +async fn pool_sender(state: &AppState) -> Option { + let out = state + .cognito + .describe_user_pool() + .user_pool_id(&state.config.cognito_user_pool_id) + .send() + .await + .map_err(|e| warn!(error = %e, "User pool not described")) + .ok()?; + let cfg = out.user_pool().and_then(|p| p.email_configuration()); + cognito_sender( + cfg.and_then(|c| c.email_sending_account()) + .map(|a| a.as_str()), + cfg.and_then(|c| c.from()), + cfg.and_then(|c| c.source_arn()), + ) } /// This deployment's own GitHub OAuth client (id and secret both stored). @@ -2915,3 +3242,197 @@ mod first_sign_in_tests { ); } } + +#[cfg(test)] +mod forgot_tests { + use super::*; + + fn now() -> chrono::DateTime { + chrono::DateTime::parse_from_rfc3339("2026-11-04T12:00:00Z") + .unwrap() + .with_timezone(&chrono::Utc) + } + + fn member(email: &str, sent: &[&str]) -> HashMap { + let mut m = HashMap::new(); + m.insert("pk".into(), AttributeValue::S("TEAM#acme".into())); + m.insert("sk".into(), AttributeValue::S("USER#u1".into())); + m.insert("email".into(), AttributeValue::S(email.into())); + m.insert("status".into(), AttributeValue::S("active".into())); + if !sent.is_empty() { + m.insert( + "setup_email_log".into(), + AttributeValue::L( + sent.iter() + .map(|t| AttributeValue::S(t.to_string())) + .collect(), + ), + ); + } + m + } + + fn joined() -> Join { + Join::Member { + team_id: "TEAM#acme".into(), + user_id: "USER#u1".into(), + } + } + + #[test] + fn a_member_with_no_account_here_gets_the_set_up_email() { + let m = member("jo@acme.dev", &[]); + let case = plan_forgot(false, &joined(), Some(&m), now()); + assert_eq!( + case, + Forgot::SetUp { + team_id: "TEAM#acme".into(), + sk: "USER#u1".into() + } + ); + assert!(case.sends()); + let r = forgot_reply(&case, "jo@acme.dev"); + assert_eq!(r["status"], "setup_sent"); + assert_eq!( + r["message"], + "You don't have an account here yet. We sent you a set-up link instead." + ); + } + + #[test] + fn a_set_up_email_waits_an_hour_even_from_the_sign_in_page() { + let m = member("jo@acme.dev", &["2026-11-04T11:30:00Z"]); + let case = plan_forgot(false, &joined(), Some(&m), now()); + assert_eq!(case, Forgot::SetUpRecent); + assert!(!case.sends()); + let m = member("jo@acme.dev", &["2026-11-04T10:30:00Z"]); + assert!(plan_forgot(false, &joined(), Some(&m), now()).sends()); + } + + #[test] + fn an_email_not_on_the_install_sends_nothing() { + for join in [Join::Refused, Join::Domain, Join::Listed, Join::FirstAdmin] { + let case = plan_forgot(false, &join, None, now()); + assert_eq!(case, Forgot::NoAccount, "{join:?}"); + assert!(!case.sends()); + } + let r = forgot_reply(&Forgot::NoAccount, "who@else.dev"); + assert_eq!(r["status"], "no_account"); + assert_eq!( + r["message"], + "There's no account for who@else.dev on this CoderHelm. Ask an admin to add you." + ); + } + + #[test] + fn an_account_here_gets_a_reset_code_whatever_the_team_says() { + let m = member("jo@acme.dev", &[]); + for join in [joined(), Join::Refused, Join::Invite] { + assert_eq!(plan_forgot(true, &join, Some(&m), now()), Forgot::ResetCode); + } + let r = forgot_reply(&Forgot::ResetCode, "jo@acme.dev"); + assert_eq!(r["status"], "code_sent"); + assert_eq!(r["message"], "We sent a reset code to jo@acme.dev."); + } + + #[test] + fn an_invite_points_at_the_invite_email_and_sends_nothing() { + let case = plan_forgot(false, &Join::Invite, None, now()); + assert_eq!(case, Forgot::Invited); + assert!(!case.sends()); + } + + #[test] + fn a_member_record_with_no_email_is_no_account() { + let m = member("", &[]); + assert_eq!( + plan_forgot(false, &joined(), Some(&m), now()), + Forgot::NoAccount + ); + } + + #[test] + fn each_case_reads_differently() { + let cases = [ + Forgot::ResetCode, + Forgot::SetUp { + team_id: "t".into(), + sk: "s".into(), + }, + Forgot::SetUpRecent, + Forgot::Invited, + Forgot::NoAccount, + ]; + let statuses: std::collections::HashSet = cases + .iter() + .map(|c| { + forgot_reply(c, "a@acme.dev")["status"] + .as_str() + .unwrap() + .to_string() + }) + .collect(); + assert_eq!(statuses.len(), cases.len()); + } + + #[test] + fn the_per_email_counter_holds_no_address() { + let k = email_key("jo@acme.dev"); + assert_eq!(k.len(), 32); + assert!(!k.contains("acme")); + assert_eq!(k, email_key("jo@acme.dev")); + assert_ne!(k, email_key("al@acme.dev")); + } + + #[test] + fn reset_codes_come_from_cognito_or_the_pools_own_address() { + assert_eq!( + cognito_sender(Some("COGNITO_DEFAULT"), None, None).as_deref(), + Some("no-reply@verificationemail.com") + ); + assert_eq!( + cognito_sender(None, None, None).as_deref(), + Some(COGNITO_DEFAULT_SENDER) + ); + assert_eq!( + cognito_sender( + Some("DEVELOPER"), + Some("Acme CoderHelm "), + Some("arn:aws:ses:us-east-1:111122223333:identity/acme.dev") + ) + .as_deref(), + Some("noreply@acme.dev") + ); + assert_eq!( + cognito_sender( + Some("DEVELOPER"), + None, + Some("arn:aws:ses:us-east-1:111122223333:identity/coderhelm@acme.dev") + ) + .as_deref(), + Some("coderhelm@acme.dev") + ); + assert_eq!( + cognito_sender( + Some("DEVELOPER"), + None, + Some("arn:aws:ses:us-east-1:111122223333:identity/acme.dev") + ), + None + ); + } + + #[test] + fn from_lines_give_their_address() { + assert_eq!( + address_of("noreply@acme.dev").as_deref(), + Some("noreply@acme.dev") + ); + assert_eq!( + address_of("Acme ").as_deref(), + Some("noreply@acme.dev") + ); + assert_eq!(address_of("acme.dev"), None); + assert_eq!(address_of(""), None); + } +} diff --git a/services/gateway/src/routes/users.rs b/services/gateway/src/routes/users.rs index ee9af8c31..7c95fcb2f 100644 --- a/services/gateway/src/routes/users.rs +++ b/services/gateway/src/routes/users.rs @@ -96,7 +96,7 @@ fn role_of(item: &Item) -> &str { } } -fn status_of(item: &Item) -> &'static str { +pub(crate) fn status_of(item: &Item) -> &'static str { if s(item, "status") == "invited" { "invited" } else { @@ -465,7 +465,7 @@ fn valid_email(email: &str) -> bool { && email.len() <= 254 } -async fn team_items(state: &AppState, team_id: &str) -> Result, ApiError> { +pub(crate) async fn team_items(state: &AppState, team_id: &str) -> Result, ApiError> { let mut items = Vec::new(); let mut start: Option = None; loop { @@ -579,9 +579,10 @@ pub async fn list_users( .filter(|i| show_invites || status_of(i) != "invited") .map(|i| member_view(i, &claims.sub, now)) .collect(); - // On a self-hosted install, admins see who is on the team but has never signed in here (a - // member copied from another CoderHelm): they get a set-up email instead of an invite. - if show_invites && super::sign_in::applies() { + // On a self-hosted install, everyone sees who is on the team but has never signed in here + // (a member copied from another CoderHelm), so their activity there doesn't read as use of + // this install. Admins can send them a set-up email instead of an invite. + if super::sign_in::applies() { let emails: Vec = users .iter() .filter(|u| u["status"] != "invited") @@ -608,7 +609,7 @@ pub async fn list_users( /// Which of these emails can sign in on this install (Cognito has them). An email whose lookup /// fails is counted as signed in, so no set-up email is offered on a guess. -async fn pool_emails( +pub(crate) async fn pool_emails( state: &AppState, emails: Vec, ) -> Result, String> { @@ -633,7 +634,11 @@ async fn pool_emails( } /// A member (not an invite) with an email who has no sign-in on this install. -fn needs_setup(status: &str, email: &str, pool: &std::collections::HashSet) -> bool { +pub(crate) fn needs_setup( + status: &str, + email: &str, + pool: &std::collections::HashSet, +) -> bool { status != "invited" && !email.is_empty() && !pool.contains(email) } @@ -974,21 +979,45 @@ pub async fn send_setup_email( Err(e) if format!("{e:?}").contains("UserNotFound") => {} Err(e) => return Err(internal("Sign-in not checked", e)), } + let stamp = deliver_setup_email(&state, &claims.team_id, &item, &claims.email) + .await + .map_err(|e| match e { + SetupSend::Wait(m) => fail(StatusCode::TOO_MANY_REQUESTS, m), + SetupSend::Failed(e) => internal("Failed to send the set-up email", e), + })?; + info!(team_id = %claims.team_id, "Set-up email sent"); + Ok(Json( + json!({ "status": "sent", "setup_email_sent_at": stamp }), + )) +} + +/// Why a set-up email didn't go. +#[derive(Debug)] +pub(crate) enum SetupSend { + /// One went less than an hour ago, or five this week: the sentence says which. + Wait(&'static str), + Failed(String), +} + +/// Sends `item` (a member with an email, checked by the caller) the set-up email, at most +/// once an hour and five times a week, and records it on their record. `by` is the admin who +/// stands behind it: the one who pressed the button, or for a person who asked from the +/// sign-in page, one of the team's owners or admins. Returns when it went. +pub(crate) async fn deliver_setup_email( + state: &AppState, + team_id: &str, + item: &Item, + by: &str, +) -> Result { + let email = s(item, "email"); let now = chrono::Utc::now(); - let log = setup_email_log(&item); - setup_email_allowed(&log, now).map_err(|m| fail(StatusCode::TOO_MANY_REQUESTS, m))?; + let log = setup_email_log(item); + setup_email_allowed(&log, now).map_err(SetupSend::Wait)?; - let team_name = get_team_name(state.clone(), &claims).await; - send_invite_email( - &state, - &claims.team_id, - &email, - &claims.email, - &team_name, - role_of(&item), - ) - .await - .map_err(|_| internal("Failed to send the set-up email", "email send failed"))?; + let team_name = team_name(state, team_id).await; + send_invite_email(state, team_id, email, by, &team_name, role_of(item)) + .await + .map_err(|_| SetupSend::Failed("email send failed".into()))?; let stamp = now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true); let mut kept: Vec = log @@ -1001,20 +1030,126 @@ pub async fn send_setup_email( .dynamo .update_item() .table_name(&state.config.users_table_name) - .key("pk", attr_s(&claims.team_id)) - .key("sk", attr_s(s(&item, "sk"))) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(s(item, "sk"))) .update_expression("SET setup_email_sent_at = :now, setup_email_log = :log") .condition_expression("attribute_exists(pk)") .expression_attribute_values(":now", attr_s(&stamp)) .expression_attribute_values(":log", AttributeValue::L(kept)) .send() .await - .map_err(|e| internal("Failed to record the set-up email", e))?; + .map_err(|e| SetupSend::Failed(format!("record: {e}")))?; + Ok(stamp) +} - info!(team_id = %claims.team_id, "Set-up email sent"); - Ok(Json( - json!({ "status": "sent", "setup_email_sent_at": stamp }), - )) +/// Whether a set-up email may go to this record now (an hour since the last one, five a week). +pub(crate) fn setup_email_due(item: &Item, now: chrono::DateTime) -> bool { + setup_email_allowed(&setup_email_log(item), now).is_ok() +} + +/// The admin a self-service set-up email is sent in the name of: an owner, else an admin, +/// with an email and an account on the team (the relay lists recipients only on an admin's word). +pub(crate) fn standing_admin(items: &[Item]) -> Option { + let pick = |role: &str| { + items + .iter() + .filter(|i| status_of(i) == "active" && role_of(i) == role) + .map(|i| s(i, "email")) + .filter(|e| !e.is_empty()) + .min() + .map(str::to_string) + }; + pick("owner").or_else(|| pick("admin")) +} + +/// Set-up emails for the whole team at once: three presses an hour per team. +const BULK_SETUP_PER_HOUR: u32 = 3; + +/// What the bulk send did for one person. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum BulkStep { + Send, + /// A set-up email went less than an hour ago (or five this week). + SkipRecent, +} + +pub(crate) fn bulk_step(item: &Item, now: chrono::DateTime) -> BulkStep { + if setup_email_due(item, now) { + BulkStep::Send + } else { + BulkStep::SkipRecent + } +} + +/// POST /api/users/setup-emails — on a self-hosted install, send the set-up email to everyone +/// on the team who hasn't set up an account here yet, skipping anyone who got one in the last +/// hour (or five this week). +pub async fn send_setup_emails_all( + State(state): State>, + Extension(claims): Extension, +) -> Result, ApiError> { + require_admin(&claims)?; + if !super::sign_in::applies() { + return Err(fail( + StatusCode::NOT_FOUND, + "Set-up emails are for self-hosted installs.", + )); + } + let now = chrono::Utc::now(); + if !take_counter( + &state, + &claims.team_id, + &format!("SETUP_BULK#{}", now.format("%Y-%m-%dT%H")), + BULK_SETUP_PER_HOUR, + now.timestamp() + 2 * 3600, + ) + .await + .map_err(|e| internal("Failed to count bulk set-up emails", e))? + { + return Err(fail( + StatusCode::TOO_MANY_REQUESTS, + "Set-up emails went to everyone three times this hour. Try again later.", + )); + } + let items = team_items(&state, &claims.team_id).await?; + let emails: Vec = items + .iter() + .filter(|i| status_of(i) == "active") + .map(|i| normalize_email(s(i, "email"))) + .filter(|e| !e.is_empty()) + .collect(); + let pool = pool_emails(&state, emails) + .await + .map_err(|e| internal("Sign-ins not checked", e))?; + let mut sent = serde_json::Map::new(); + let (mut skipped, mut failed) = (0usize, 0usize); + for item in &items { + let email = normalize_email(s(item, "email")); + if !needs_setup(status_of(item), &email, &pool) { + continue; + } + if bulk_step(item, now) == BulkStep::SkipRecent { + skipped += 1; + continue; + } + match deliver_setup_email(&state, &claims.team_id, item, &claims.email).await { + Ok(stamp) => { + sent.insert(bare_id(s(item, "sk")).to_string(), Value::String(stamp)); + } + Err(SetupSend::Wait(_)) => skipped += 1, + Err(SetupSend::Failed(e)) => { + error!(error = %e, "Set-up email not sent"); + failed += 1; + } + } + } + info!(team_id = %claims.team_id, sent = sent.len(), skipped, failed, "Set-up emails sent to all"); + Ok(Json(json!({ + "sent": sent.len(), + "skipped_recent": skipped, + "failed": failed, + "sent_at": sent, + }))) } /// What resending needs from the record: still an invite, with an email. @@ -1582,11 +1717,16 @@ fn attr_s(val: &str) -> AttributeValue { } async fn get_team_name(state: Arc, claims: &Claims) -> String { + team_name(&state, &claims.team_id).await +} + +/// The team's name for an email, never anything a person typed freely. +pub(crate) async fn team_name(state: &AppState, team_id: &str) -> String { state .dynamo .get_item() .table_name(&state.config.table_name) - .key("pk", attr_s(&claims.team_id)) + .key("pk", attr_s(team_id)) .key("sk", attr_s("META")) .send() .await @@ -1743,6 +1883,52 @@ mod tests { assert!(check_setup_email(&none).is_err()); } + #[test] + fn send_to_all_skips_anyone_sent_one_in_the_last_hour() { + let now = chrono::DateTime::parse_from_rfc3339("2026-11-10T12:00:00Z") + .unwrap() + .with_timezone(&chrono::Utc); + let with_log = |sent: &[&str]| { + let mut m: Item = HashMap::new(); + m.insert("email".into(), attr_s("a@acme.dev")); + m.insert( + "setup_email_log".into(), + AttributeValue::L(sent.iter().map(|t| attr_s(t)).collect()), + ); + m + }; + assert_eq!(bulk_step(&with_log(&[]), now), BulkStep::Send); + assert_eq!( + bulk_step(&with_log(&["2026-11-10T11:15:00Z"]), now), + BulkStep::SkipRecent + ); + assert_eq!( + bulk_step(&with_log(&["2026-11-10T10:59:00Z"]), now), + BulkStep::Send + ); + } + + #[test] + fn a_self_service_set_up_email_stands_on_an_owner_else_an_admin() { + let person = |sk: &str, role: &str, email: &str, status: &str| { + let mut m: Item = HashMap::new(); + m.insert("sk".into(), attr_s(sk)); + m.insert("role".into(), attr_s(role)); + m.insert("email".into(), attr_s(email)); + m.insert("status".into(), attr_s(status)); + m + }; + let team = vec![ + person("USER#1", "member", "m@acme.dev", "active"), + person("USER#2", "admin", "ad@acme.dev", "active"), + person("USER#3", "owner", "own@acme.dev", "active"), + person("USER#4", "owner", "inv@acme.dev", "invited"), + ]; + assert_eq!(standing_admin(&team).as_deref(), Some("own@acme.dev")); + assert_eq!(standing_admin(&team[..2]).as_deref(), Some("ad@acme.dev")); + assert_eq!(standing_admin(&team[..1]), None); + } + #[test] fn needs_setup_means_a_member_with_no_sign_in_here() { let pool: std::collections::HashSet = ["in@example.com".to_string()].into();