diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 51d7e0be3..0d32ad721 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -129,6 +129,7 @@ jobs: - run: python3 -m unittest discover -s lambda/tests # The Cognito pre-sign-up trigger, against the cases the gateway uses. - run: node --test lambda/pre-signup/handler.test.js + - run: node --test lambda/custom-message/handler.test.js mcp-proxy: name: MCP Proxy (Node) diff --git a/lambda/custom-message/handler.js b/lambda/custom-message/handler.js index a8e302fb5..7ff79a521 100644 --- a/lambda/custom-message/handler.js +++ b/lambda/custom-message/handler.js @@ -1,48 +1,65 @@ -const { SESv2Client, GetEmailTemplateCommand } = require("@aws-sdk/client-sesv2"); +// Cognito custom-message trigger: the sign-up, resend and reset-password +// codes in the install's own SES templates. Any problem loading a template +// leaves Cognito's default message, so a code always goes out. -const ses = new SESv2Client({}); const PREFIX = process.env.SES_TEMPLATE_PREFIX; -const FROM = process.env.SES_FROM_ADDRESS; -exports.handler = async (event) => { - const { triggerSource, request, userName } = event; +let real; - const code = request.codeParameter; - const email = request.userAttributes?.email || ""; - - let templateName; - let subject; +/** SES v2 (the Lambda runtime's SDK), made on first use. */ +function sesClient() { + if (!real) { + const { SESv2Client, GetEmailTemplateCommand } = require("@aws-sdk/client-sesv2"); + const c = new SESv2Client({}); + real = { getTemplate: (name) => c.send(new GetEmailTemplateCommand({ TemplateName: name })) }; + } + return real; +} +/** The template and subject for a trigger, or null for Cognito's own. */ +function pick(triggerSource) { switch (triggerSource) { case "CustomMessage_SignUp": case "CustomMessage_ResendCode": - templateName = `${PREFIX}-verify-email`; - subject = "Verify your Coderhelm email"; - break; + return { template: `${PREFIX}-verify-email`, subject: "Verify your Coderhelm email" }; case "CustomMessage_ForgotPassword": - templateName = `${PREFIX}-reset-password`; - subject = "Reset your Coderhelm password"; - break; + return { template: `${PREFIX}-reset-password`, subject: "Reset your Coderhelm password" }; default: - // For unhandled triggers, return default Cognito behavior - return event; + return null; } +} - try { - const { Template } = await ses.send( - new GetEmailTemplateCommand({ TemplateName: templateName }) - ); - - // Replace {{code}} placeholder with the actual code - const html = Template.Content.Html.Data.replace(/\{\{code\}\}/g, code); - const text = Template.Content.Text.Data.replace(/\{\{code\}\}/g, code); +/** + * The email body from a GetEmailTemplate answer. SES v2 answers + * `{ TemplateContent: { Subject, Text, Html } }` (strings). Null when it has + * no HTML or no place for the code: Cognito refuses a message without it. + */ +function messageFrom(answer, code) { + const html = answer && answer.TemplateContent && answer.TemplateContent.Html; + if (typeof html !== "string" || !html.includes("{{code}}")) return null; + return html.replace(/\{\{code\}\}/g, code); +} - event.response.emailSubject = subject; - event.response.emailMessage = html; +async function run(event, ses) { + const chosen = pick(event.triggerSource); + if (!chosen) return event; + const code = event.request.codeParameter; + try { + const message = messageFrom(await ses.getTemplate(chosen.template), code); + if (message) { + event.response.emailSubject = chosen.subject; + event.response.emailMessage = message; + } else { + console.error(`SES template ${chosen.template} has no HTML with {{code}}; Cognito's default message goes out`); + } } catch (err) { - console.error("Failed to load SES template, falling back to default:", err); - // Fall through — Cognito will use its default message + console.error(`SES template ${chosen.template} not loaded; Cognito's default message goes out:`, err); } - return event; -}; +} + +/** Lambda's entry point: only `event` is read (the runtime passes more). */ +exports.handler = async (event) => run(event, sesClient()); +exports.run = run; +exports.messageFrom = messageFrom; +exports.pick = pick; diff --git a/lambda/custom-message/handler.test.js b/lambda/custom-message/handler.test.js new file mode 100644 index 000000000..2e900bb69 --- /dev/null +++ b/lambda/custom-message/handler.test.js @@ -0,0 +1,57 @@ +// node --test lambda/custom-message/handler.test.js +process.env.SES_TEMPLATE_PREFIX = "coderhelm-test"; +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { run, messageFrom } = require("./handler.js"); + +const event = (triggerSource) => ({ + triggerSource, + request: { codeParameter: "{####}", userAttributes: { email: "a@example.com" } }, + response: {}, +}); + +// What SES v2 GetEmailTemplate really answers. +const sesAnswer = { + TemplateName: "coderhelm-test-verify-email", + TemplateContent: { Subject: "Verify", Text: "Code {{code}}", Html: "

Code {{code}}

" }, +}; + +test("the SES v2 template answer becomes the message, with Cognito's code placeholder", async () => { + // The failure: the handler read Template.Content, which SES v2 never + // returns, so every code went out as Cognito's default text. + let asked; + const ses = { getTemplate: async (name) => ((asked = name), sesAnswer) }; + const out = await run(event("CustomMessage_ResendCode"), ses); + assert.equal(asked, "coderhelm-test-verify-email"); + assert.equal(out.response.emailMessage, "

Code {####}

"); + assert.equal(out.response.emailSubject, "Verify your Coderhelm email"); + const reset = await run(event("CustomMessage_ForgotPassword"), { getTemplate: async (n) => ((asked = n), sesAnswer) }); + assert.equal(asked, "coderhelm-test-reset-password"); + assert.equal(reset.response.emailSubject, "Reset your Coderhelm password"); +}); + +test("a missing or broken template leaves Cognito's default message", async () => { + const quiet = console.error; + console.error = () => {}; + try { + const missing = await run(event("CustomMessage_SignUp"), { + getTemplate: async () => { + throw new Error("NotFoundException"); + }, + }); + assert.deepEqual(missing.response, {}); + const noCode = await run(event("CustomMessage_SignUp"), { + getTemplate: async () => ({ TemplateContent: { Html: "

no code

" } }), + }); + assert.deepEqual(noCode.response, {}); + } finally { + console.error = quiet; + } + assert.equal(messageFrom({ Template: { Content: {} } }, "{####}"), null); +}); + +test("other triggers are left to Cognito", async () => { + const ses = { getTemplate: async () => assert.fail("not asked") }; + const out = await run(event("CustomMessage_AdminCreateUser"), ses); + assert.deepEqual(out.response, {}); +}); diff --git a/services/common/src/deliveries.rs b/services/common/src/deliveries.rs index 5de502f6e..af29a6ec2 100644 --- a/services/common/src/deliveries.rs +++ b/services/common/src/deliveries.rs @@ -428,7 +428,7 @@ const REASONS: &[Reason] = &[ Reason { code: "relay_turned_off", message: "Email is set to go through CoderHelm, but the install's config turned hybrid off.", fix: "Switch Settings, Emails back to Amazon SES, or remove hybridUrl: null from the config." }, Reason { code: "recipient_not_listed", message: "CoderHelm's mail relay only emails this install's people and pending invites.", fix: "Invite the person from the team page; the relay learns invites as they are sent." }, Reason { code: "recipient_suppressed", message: "This address bounced or marked an earlier email as spam, so CoderHelm's relay sends nothing more to it.", fix: "Check the address on the team page. Ask CoderHelm support to clear it once it works again." }, - Reason { code: "inviter_not_admin", message: "Only an install admin can add people to the relay's list.", fix: "Send the invite as an install admin." }, + Reason { code: "inviter_not_admin", message: "Only an install admin can add people to the relay's list.", fix: "The install lists its admins with CoderHelm and tries once more by itself. If this stays, check that the person sending has the admin role on the team page." }, Reason { code: "too_many_new_recipients", message: "The install added more new addresses today than the relay allows.", fix: "Wait until tomorrow (UTC), or send through the install's own Amazon SES." }, Reason { code: "email_rate_limited", message: "Too many emails through CoderHelm this minute.", fix: "Usually passes on its own; the next email goes out." }, Reason { code: "email_quota_reached", message: "The install reached today's email quota through CoderHelm.", fix: "Wait until tomorrow (UTC), or send through the install's own Amazon SES." }, diff --git a/services/common/src/mail/mod.rs b/services/common/src/mail/mod.rs index d8f8166db..3751d5ebf 100644 --- a/services/common/src/mail/mod.rs +++ b/services/common/src/mail/mod.rs @@ -608,22 +608,29 @@ pub async fn list( Ok(()) } -/// Lists one address as a pending invite, when the install sends through -/// CoderHelm (nothing to do otherwise). `by` is the admin sending it. -pub async fn list_invite(s: &Sender<'_>, by: &str, to: &str) -> Result<(), SendError> { +/// The relay's credentials when this install sends through CoderHelm, else +/// `None` (hosted, its own SES, or not registered). +pub async fn relay_in_use( + s: &Sender<'_>, +) -> Result, SendError> { if deployment() == Deployment::Hosted { - return Ok(()); + return Ok(None); } let stored = load(s.dynamo, s.settings_table) .await .map_err(|e| err("settings_unreadable", e))?; - let transport = transport_of(stored.as_ref(), transport_default()); - let Some(creds) = crate::hybrid::client::credentials() else { + if transport_of(stored.as_ref(), transport_default()) != Transport::Coderhelm { + return Ok(None); + } + Ok(crate::hybrid::client::credentials()) +} + +/// Lists one address as a pending invite, when the install sends through +/// CoderHelm (nothing to do otherwise). `by` is the admin sending it. +pub async fn list_invite(s: &Sender<'_>, by: &str, to: &str) -> Result<(), SendError> { + let Some(creds) = relay_in_use(s).await? else { return Ok(()); }; - if transport != Transport::Coderhelm { - return Ok(()); - } list( s.http, &creds, @@ -636,6 +643,40 @@ pub async fn list_invite(s: &Sender<'_>, by: &str, to: &str) -> Result<(), SendE .await } +/// The addresses an admin sync names: valid, not CoderHelm's, each once, +/// at most [`relay::MAX_ADMINS`]. `None` when there is none to name. +pub fn admins_to_sync<'a>(admins: impl IntoIterator) -> Option> { + let mut out: Vec = admins + .into_iter() + .map(relay::normalize) + .filter(|a| relay::valid_address(a) && !relay::is_coderhelm_address(a)) + .collect(); + out.sort(); + out.dedup(); + out.truncate(relay::MAX_ADMINS); + (!out.is_empty()).then_some(out) +} + +/// Tells the relay who the install's admins are now ([`relay::AdminsRequest`]), +/// when the install sends through CoderHelm (nothing to do otherwise). +pub async fn sync_admins(s: &Sender<'_>, admins: &[String]) -> Result<(), SendError> { + let Some(creds) = relay_in_use(s).await? else { + return Ok(()); + }; + let Some(admins) = admins_to_sync(admins.iter().map(String::as_str)) else { + return Ok(()); + }; + let body = relay::AdminsRequest { + request_id: relay::new_request_id(), + admins, + }; + let body = serde_json::to_value(&body).unwrap_or(Value::Null); + crate::hybrid::client::call(s.http, &creds, "POST", relay::PATH_ADMINS, Some(&body)) + .await + .map(|_| ()) + .map_err(|e| err(&e.code, e.message)) +} + /// The Deliveries record for one send: domain only, never the address, and /// never a parameter. `send_ms` is how long [`send`] took (time it with a /// [`crate::deliveries::Clock`] started just before the call). @@ -747,6 +788,27 @@ mod tests { assert_eq!(Transport::parse("smtp"), None); } + #[test] + fn an_admin_sync_names_each_real_admin_once() { + let got = admins_to_sync([ + "Owner@Acme.test", + "owner@acme.test", + "", + "ops@coderhelm.com", + "admin@acme.test", + ]); + assert_eq!( + got, + Some(vec!["admin@acme.test".into(), "owner@acme.test".into()]) + ); + assert_eq!(admins_to_sync(["", "nope"]), None); + let many: Vec = (0..80).map(|i| format!("a{i}@acme.test")).collect(); + assert_eq!( + admins_to_sync(many.iter().map(String::as_str)).map(|v| v.len()), + Some(relay::MAX_ADMINS) + ); + } + #[test] fn deliveries_keep_the_domain_and_the_reason_only() { let mail = Mail { diff --git a/services/common/src/mail/relay.rs b/services/common/src/mail/relay.rs index f78fe419f..d6a3397b6 100644 --- a/services/common/src/mail/relay.rs +++ b/services/common/src/mail/relay.rs @@ -58,6 +58,9 @@ pub const RATE_WINDOW_DAYS: i64 = 7; pub const PATH_SEND: &str = "/hybrid/email"; pub const PATH_RECIPIENTS: &str = "/hybrid/email/recipients"; +/// The install's admins, in full: the relay lists each as an admin and +/// stops counting anyone else as one ([`AdminsRequest`]). +pub const PATH_ADMINS: &str = "/hybrid/email/admins"; pub const PATH_STATUS: &str = "/hybrid/email/status"; /// The install's email counts by kind, `{from, to}` days (signed POST). pub const PATH_STATS: &str = "/hybrid/email/stats"; @@ -191,6 +194,22 @@ pub struct RecipientsRequest { pub remove: Vec, } +/// Most admins one install may name ([`AdminsRequest`]). +pub const MAX_ADMINS: usize = 50; + +/// `POST /hybrid/email/admins`: every address that is an install admin now +/// (the install's admin-role users and its config's admins). The install is +/// the only one who knows who its admins are, so its signed word decides: +/// each is listed as an admin (a new address counts against the day's new +/// addresses), and a listed admin it no longer names becomes a member. This +/// is how an admin added after the first listing, or one copied from the +/// hosted CoderHelm, can vouch for invites, and how a demoted one stops. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AdminsRequest { + pub request_id: String, + pub admins: Vec, +} + /// `POST /hybrid/email`: one email. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SendRequest { @@ -242,6 +261,9 @@ pub enum Refusal { NotApproved, /// That address got all the email it may get today. RecipientLimit, + /// The install hasn't listed its people with the relay yet (nothing to + /// sync admins into). + NotStarted, } impl Refusal { @@ -261,6 +283,7 @@ impl Refusal { Self::Paused => "email_paused", Self::NotApproved => "relay_not_approved", Self::RecipientLimit => "recipient_daily_limit", + Self::NotStarted => "relay_not_started", } } @@ -280,13 +303,14 @@ impl Refusal { Self::Paused => "Email through CoderHelm is paused for this install after bounces or complaints.", Self::NotApproved => "CoderHelm's mail service sends for installs linked to a GitHub organization through CoderHelm, or approved by CoderHelm. Until then, send with your own Amazon SES (Settings, Email).", Self::RecipientLimit => "That address already got today's share of email from CoderHelm.", + Self::NotStarted => "The install hasn't listed its people with CoderHelm's mail service yet.", } } pub fn status(self) -> u16 { match self { Self::BadRequest | Self::BadAddress => 400, - Self::Replayed => 409, + Self::Replayed | Self::NotStarted => 409, Self::RateLimited | Self::QuotaReached | Self::TooManyNew | Self::RecipientLimit => 429, _ => 403, } @@ -374,6 +398,40 @@ pub fn may_list( Ok(()) } +/// May this admin sync change the list? `bootstrap_spent` as for +/// [`may_list`]: before the first listing there is nothing to sync, and the +/// first listing (which lists the admins) must not be used up by a sync. +/// The new addresses it brings are counted by the caller against the day's +/// limit, like any listing. +pub fn may_sync_admins(req: &AdminsRequest, bootstrap_spent: bool) -> Result<(), Refusal> { + if req.admins.is_empty() || req.admins.len() > MAX_ADMINS { + return Err(Refusal::BadRequest); + } + for a in &req.admins { + if !valid_address(a) { + return Err(Refusal::BadAddress); + } + if is_coderhelm_address(a) { + return Err(Refusal::CoderhelmAddress); + } + } + if !bootstrap_spent { + return Err(Refusal::NotStarted); + } + Ok(()) +} + +/// What an admin sync does to the list: `listed_admins` are the hashes +/// listed as admins now, `named` the hashes the install named. Returns the +/// hashes to demote to member (listed admins it no longer names). +pub fn admins_to_demote(listed_admins: &[String], named: &[String]) -> Vec { + listed_admins + .iter() + .filter(|h| !named.contains(h)) + .cloned() + .collect() +} + /// Whether an install that proved its address at `verified_at` (epoch /// seconds) is still new. Unknown counts as new. pub fn is_new_install(verified_at: Option, now: i64) -> bool { @@ -761,6 +819,63 @@ mod tests { ); } + #[test] + fn an_install_admin_listed_only_as_an_invite_cannot_vouch_until_synced() { + use RecipientKind::*; + // The failure: the install's owner and a copied-over admin were + // listed as invites (by their set-up emails), so an invite they + // send is refused. + let resend = req("owner@acme.test", &[("person@acme.test", Invite)]); + assert_eq!( + may_list(&resend, Some(Invite), true, 0, false), + Err(Refusal::NotAdmin) + ); + // The install names its admins; the relay then counts them as admins. + let sync = AdminsRequest { + request_id: new_request_id(), + admins: vec!["first@acme.test".into(), "owner@acme.test".into()], + }; + assert_eq!(may_sync_admins(&sync, true), Ok(())); + assert_eq!(may_list(&resend, Some(Admin), true, 0, false), Ok(())); + // A listed admin the install no longer names is demoted. + let listed = vec!["h-first".to_string(), "h-gone".to_string()]; + let named = vec!["h-first".to_string(), "h-owner".to_string()]; + assert_eq!( + admins_to_demote(&listed, &named), + vec!["h-gone".to_string()] + ); + } + + #[test] + fn an_admin_sync_is_checked() { + let sync = |admins: Vec| AdminsRequest { + request_id: new_request_id(), + admins, + }; + // Before the first listing: nothing to sync, and the first listing + // stays free for the install's people. + assert_eq!( + may_sync_admins(&sync(vec!["a@acme.test".into()]), false), + Err(Refusal::NotStarted) + ); + assert_eq!( + may_sync_admins(&sync(vec![]), true), + Err(Refusal::BadRequest) + ); + let many = (0..=MAX_ADMINS) + .map(|i| format!("a{i}@acme.test")) + .collect(); + assert_eq!(may_sync_admins(&sync(many), true), Err(Refusal::BadRequest)); + assert_eq!( + may_sync_admins(&sync(vec!["a@b.com, c@d.com".into()]), true), + Err(Refusal::BadAddress) + ); + assert_eq!( + may_sync_admins(&sync(vec!["security@coderhelm.com".into()]), true), + Err(Refusal::CoderhelmAddress) + ); + } + #[test] fn a_new_install_starts_with_a_lower_daily_quota() { let now = 1_800_000_000; diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index d96dd438c..be93a557a 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -1862,6 +1862,7 @@ fn hybrid_routes() -> Router> { // (routes::hybrid_email). .route("/email", post(routes::hybrid_email::send)) .route("/email/recipients", post(routes::hybrid_email::recipients)) + .route("/email/admins", post(routes::hybrid_email::admins)) .route("/email/domain", post(routes::hybrid_email::domain)) .route("/email/status", get(routes::hybrid_email::status)) .route("/email/stats", post(routes::hybrid_email::stats_route)) diff --git a/services/gateway/src/routes/auth.rs b/services/gateway/src/routes/auth.rs index 1cfc67b4e..9a46042f9 100644 --- a/services/gateway/src/routes/auth.rs +++ b/services/gateway/src/routes/auth.rs @@ -183,26 +183,7 @@ pub async fn signup( info!(email = %email, cognito_sub = %sub, "User signed up, verification pending") } Err(e) if e.contains("UsernameExistsException") => { - // Signed up before but never confirmed: a fresh code. Cognito - // refuses it for a confirmed account, and nothing is sent. - let hash = cognito_secret_hash( - &state.cognito_client_secret, - &email, - &state.config.cognito_client_id, - ); - let resent = state - .cognito - .resend_confirmation_code() - .client_id(&state.config.cognito_client_id) - .secret_hash(&hash) - .username(&email) - .send() - .await - .is_ok(); - info!( - resent, - "Self-hosted sign-up for an email that has an account" - ) + signed_up_again(&state, &email, &body).await; } Err(e) if e.contains("UserLambdaValidationException") => { info!("Self-hosted sign-up refused by the pre-sign-up trigger") @@ -297,6 +278,57 @@ pub fn signup_answer() -> Response { .into_response() } +/// What a second sign-up for an email that is already in the user pool does. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SignUpAgain { + /// Never confirmed: the old sign-up goes and this one takes its place, + /// with the password just chosen and a fresh code. Nothing of theirs + /// hangs on it (their record is found by email at sign-in). + Replace, + /// A working account: nothing is sent (the answer is the same anyway). + Nothing, +} + +pub fn sign_up_again(p: super::users::PoolUser) -> SignUpAgain { + match p { + super::users::PoolUser::Unconfirmed | super::users::PoolUser::None => SignUpAgain::Replace, + super::users::PoolUser::Account => SignUpAgain::Nothing, + } +} + +/// A self-hosted sign-up for an email the pool already has +/// ([`sign_up_again`]). Logged, never answered differently. +async fn signed_up_again(state: &AppState, email: &str, body: &SignupRequest) { + let pool = match super::users::pool_user(state, email).await { + Ok(p) => p, + Err(e) => { + error!(error = %e, "Sign-up: sign-in not checked"); + return; + } + }; + if sign_up_again(pool) == SignUpAgain::Nothing { + info!("Self-hosted sign-up for an email that has an account"); + return; + } + if pool == super::users::PoolUser::Unconfirmed { + if let Err(e) = state + .cognito + .admin_delete_user() + .user_pool_id(&state.config.cognito_user_pool_id) + .username(email) + .send() + .await + { + error!(error = %e, "Sign-up: unconfirmed sign-in not replaced"); + return; + } + } + match cognito_sign_up(state, email, body).await { + Ok(sub) => info!(cognito_sub = %sub, "Unconfirmed sign-up replaced, verification pending"), + Err(e) => error!("Cognito signup failed: {e}"), + } +} + /// Cognito sign-up: the new user's sub, or Cognito's error (Debug form). async fn cognito_sign_up( state: &AppState, @@ -763,8 +795,8 @@ pub async fn mfa_verify( if resp.status().is_success() { let sub = format!("USER#{}", user.username()); if sign_in::applies() { - if let Some(team) = cognito_member_team(&state, &email, &sub).await { - sign_in::note_factor(&state, &team, &sub, &email, Some("cognito")).await; + if let Some((team, user_id)) = cognito_member_record(&state, &email, &sub).await { + sign_in::note_factor(&state, &team, &user_id, &email, Some("cognito")).await; } } else { // Hosted: the person's own record, by email. @@ -774,10 +806,17 @@ pub async fn mfa_verify( Ok(resp) } -/// The organization team a Cognito user's own record is in, if any. -async fn cognito_member_team(state: &AppState, email: &str, sub: &str) -> Option { +/// The organization record a Cognito user signs in to: `(team, user id)`. +/// Their own record (keyed by this sign-in's sub), else the member record +/// for their email, as sign-in lands them: a record copied over from the +/// hosted CoderHelm keeps the sub it had there. +async fn cognito_member_record( + state: &AppState, + email: &str, + sub: &str, +) -> Option<(String, String)> { let org = sign_in::load_org(state).await.ok()??; - state + let own = state .dynamo .get_item() .table_name(&state.config.users_table_name) @@ -792,8 +831,15 @@ async fn cognito_member_team(state: &AppState, email: &str, sub: &str) -> Option .and_then(|v| v.as_s().ok()) .map(|e| normalize_email(e)) == Some(normalize_email(email)) - }) - .map(|_| org.team_id) + }); + if own.is_some() { + return Some((org.team_id, sub.to_string())); + } + let facts = sign_in::facts_for(state, email).await.ok()?; + match sign_in::decide_join(&facts, chrono::Utc::now()) { + Join::Member { team_id, user_id } => Some((team_id, user_id)), + _ => None, + } } /// The answer to someone a self-hosted install won't let in. @@ -1073,16 +1119,11 @@ async fn forgot_work(state: Arc, email: String) -> Forgot { } return Forgot::ResetCode; } - 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, + // An unconfirmed sign-up has no verified email, so Cognito can't send it + // a reset code: it counts as no account (a member gets the set-up email, + // and signing up again replaces it). + let in_pool = match super::users::pool_user(&state, &email).await { + Ok(p) => p.has_account(), Err(e) => { error!(error = %e, "Forgot password: sign-in not checked"); return Forgot::NoAccount; @@ -1134,6 +1175,9 @@ async fn forgot_work(state: Arc, email: String) -> Forgot { Err(super::users::SetupSend::Failed(e)) => { warn!(%team_id, error = %e, "Set-up email not sent from the sign-in page"); } + Err(super::users::SetupSend::NotRecorded(e)) => { + warn!(%team_id, error = %e, "Set-up email sent from the sign-in page, not recorded"); + } } } _ => {} @@ -3877,3 +3921,44 @@ mod github_link_tests { assert!(c.contains("HttpOnly") && c.contains("Secure") && c.contains("Path=/auth")); } } + +#[cfg(test)] +mod unconfirmed_tests { + use super::*; + use crate::routes::users::PoolUser; + + #[test] + fn a_copied_over_member_with_an_unconfirmed_sign_up_gets_the_set_up_email() { + // The failure: they signed up but the code never reached them, so + // forgot-password asked Cognito for a reset code it can't send (no + // verified email) and nothing went out. + let mut item = HashMap::new(); + item.insert("email".to_string(), attr_s("person@acme.test")); + item.insert("sk".to_string(), attr_s("USER#copied")); + let join = Join::Member { + team_id: "TEAM#t".into(), + user_id: "USER#copied".into(), + }; + let now = chrono::Utc::now(); + assert_eq!( + plan_forgot(PoolUser::Unconfirmed.has_account(), &join, Some(&item), now), + Forgot::SetUp { + team_id: "TEAM#t".into(), + sk: "USER#copied".into(), + } + ); + // A working account still gets a reset code. + assert_eq!( + plan_forgot(PoolUser::Account.has_account(), &join, Some(&item), now), + Forgot::ResetCode + ); + } + + #[test] + fn signing_up_again_replaces_an_unconfirmed_sign_up_only() { + // Replaced, so the password chosen now is the one that works after + // the code; their record is found by email, never duplicated. + assert_eq!(sign_up_again(PoolUser::Unconfirmed), SignUpAgain::Replace); + assert_eq!(sign_up_again(PoolUser::Account), SignUpAgain::Nothing); + } +} diff --git a/services/gateway/src/routes/email_settings.rs b/services/gateway/src/routes/email_settings.rs index 3598d9ade..3fc40218e 100644 --- a/services/gateway/src/routes/email_settings.rs +++ b/services/gateway/src/routes/email_settings.rs @@ -186,8 +186,22 @@ pub async fn get( ))) } -/// Everyone the install may email: install admins, members, pending invites. -async fn people(state: &AppState, actor: &str) -> Vec { +/// What one user record is on the relay's list: an owner or admin who has +/// joined is an admin (they vouch for invites), an invite is an invite, +/// anyone else a member. +pub fn relay_kind(role: &str, status: &str) -> relay::RecipientKind { + if status == "invited" { + relay::RecipientKind::Invite + } else if matches!(role, "owner" | "admin") { + relay::RecipientKind::Admin + } else { + relay::RecipientKind::Member + } +} + +/// Every user record on the install, as (email, kind), and the config's +/// admins as admins. Copied-over records count like any other. +async fn everyone(state: &AppState) -> BTreeMap { let mut out: BTreeMap = BTreeMap::new(); let mut start = None; for _ in 0..50 { @@ -197,8 +211,9 @@ async fn people(state: &AppState, actor: &str) -> Vec { .table_name(&state.config.users_table_name) .filter_expression("begins_with(sk, :u)") .expression_attribute_values(":u", AttributeValue::S("USER#".into())) - .projection_expression("email, #st") + .projection_expression("email, #st, #ro") .expression_attribute_names("#st", "status") + .expression_attribute_names("#ro", "role") .set_exclusive_start_key(start.take()) .send() .await; @@ -210,16 +225,17 @@ async fn people(state: &AppState, actor: &str) -> Vec { if !relay::valid_address(e) || relay::is_coderhelm_address(e) { continue; } - let invited = i - .get("status") - .and_then(|v| v.as_s().ok()) - .map(String::as_str) - == Some("invited"); - out.entry(relay::normalize(e)).or_insert(if invited { - relay::RecipientKind::Invite - } else { - relay::RecipientKind::Member - }); + let g = |k: &str| i.get(k).and_then(|v| v.as_s().ok()).map(String::as_str); + let kind = relay_kind(g("role").unwrap_or(""), g("status").unwrap_or("")); + // An admin on any team stays an admin; else the first seen. + let slot = out + .entry(relay::normalize(e)) + .or_insert(relay::RecipientKind::Invite); + if kind == relay::RecipientKind::Admin + || (*slot == relay::RecipientKind::Invite && kind == relay::RecipientKind::Member) + { + *slot = kind; + } } match r.last_evaluated_key() { Some(k) => start = Some(k.clone()), @@ -227,11 +243,20 @@ async fn people(state: &AppState, actor: &str) -> Vec { } } let admins = std::env::var("PLATFORM_ADMIN_EMAILS").unwrap_or_default(); - for a in admins.split(',').map(str::trim).chain([actor]) { + for a in admins.split(',').map(str::trim) { if relay::valid_address(a) && !relay::is_coderhelm_address(a) { out.insert(relay::normalize(a), relay::RecipientKind::Admin); } } + out +} + +/// Everyone the install may email: install admins, members, pending invites. +async fn people(state: &AppState, actor: &str) -> Vec { + let mut out = everyone(state).await; + if relay::valid_address(actor) && !relay::is_coderhelm_address(actor) { + out.insert(relay::normalize(actor), relay::RecipientKind::Admin); + } // The admin who turns it on comes first (the relay's first listing). let actor = relay::normalize(actor); let mut list: Vec = out @@ -243,6 +268,33 @@ async fn people(state: &AppState, actor: &str) -> Vec { list } +/// The install's admins now: owner- and admin-role users who have joined, +/// and the config's admins. +pub async fn install_admins(state: &AppState) -> Vec { + everyone(state) + .await + .into_iter() + .filter(|(_, k)| *k == relay::RecipientKind::Admin) + .map(|(e, _)| e) + .collect() +} + +/// Tells CoderHelm's relay who the install's admins are now, when the +/// install sends through it (nothing to do otherwise). Called when a role +/// changes or someone is removed, and when the relay refuses an admin. +pub async fn sync_relay_admins(state: &AppState) -> Result<(), mail::SendError> { + let admins = install_admins(state).await; + mail::sync_admins(&sender(state), &admins).await +} + +/// [`sync_relay_admins`], logging a failure: for changes whose own answer +/// doesn't depend on the relay (the next refusal syncs again). +pub async fn sync_relay_admins_quietly(state: &AppState) { + if let Err(e) = sync_relay_admins(state).await { + warn!(error = %e, "relay admins not synced"); + } +} + /// PUT /api/system/emails `{optional?: {id: bool}, transport?: "ses"|"coderhelm"}` pub async fn put( State(state): State>, @@ -530,6 +582,19 @@ pub async fn put_sender( mod tests { use super::*; + #[test] + fn an_owner_or_admin_who_joined_is_listed_as_a_relay_admin() { + use relay::RecipientKind::*; + // Before: the first listing named only the config's admins as + // admins, so the team's owner and other admins (copied over from + // the hosted CoderHelm, or made admin later) couldn't vouch. + assert_eq!(relay_kind("owner", ""), Admin); + assert_eq!(relay_kind("admin", "active"), Admin); + assert_eq!(relay_kind("member", ""), Member); + assert_eq!(relay_kind("admin", "invited"), Invite); + assert_eq!(relay_kind("", ""), Member); + } + #[test] fn optional_emails_start_off_and_the_install_sends_through_its_own_ses() { let v = view(None, &[], false, false, "ch@example.com", None); diff --git a/services/gateway/src/routes/hybrid_email.rs b/services/gateway/src/routes/hybrid_email.rs index 91227f56d..d6f6a6bc5 100644 --- a/services/gateway/src/routes/hybrid_email.rs +++ b/services/gateway/src/routes/hybrid_email.rs @@ -615,7 +615,11 @@ pub async fn recipients( .ok() .map(|t| t.timestamp()); let new_install = relay::is_new_install(verified_at, epoch()); - relay::may_list(&req, by_kind, spent, new_today, new_install).map_err(refuse)?; + relay::may_list(&req, by_kind, spent, new_today, new_install).map_err(|r| { + // Logged, so a refusal can be found from this side too (no address). + info!(install = %install.id, code = r.code(), "email relay: listing refused"); + refuse(r) + })?; let mut bootstrap = !spent && relay::bootstrap_request(&req); if bootstrap && !claim_bootstrap(&state, &install.id).await? { // Another request took the first listing meanwhile: this one is an @@ -751,6 +755,169 @@ pub async fn recipients( )) } +/// POST /hybrid/email/admins (signed): the install's admins, in full. Each +/// becomes a listed admin; a listed admin it no longer names becomes a +/// member. New addresses count against the day's new-address limit. +pub async fn admins( + State(state): State>, + method: Method, + uri: OriginalUri, + headers: HeaderMap, + body: Bytes, +) -> Reply { + let (install, _) = verified(&state, &headers, &method, &uri, &body).await?; + let req: relay::AdminsRequest = + serde_json::from_slice(&body).map_err(|_| refuse(relay::Refusal::BadRequest))?; + first_use(&state, &install.id, &req.request_id).await?; + let list_meta = get(&state, &install.id, LIST_SK).await?; + relay::may_sync_admins(&req, bootstrap_spent(list_meta.as_ref())).map_err(|r| { + info!(install = %install.id, code = r.code(), "email relay: admin sync refused"); + refuse(r) + })?; + let mut named: Vec<(String, String)> = req + .admins + .iter() + .map(|a| (relay::recipient_hash(&install.id, a), relay::normalize(a))) + .collect(); + named.sort(); + named.dedup_by(|a, b| a.0 == b.0); + + // What is listed now, in one pass over the install's list. + let listed = listed_kinds(&state, &install.id).await?; + let fresh = named + .iter() + .filter(|(h, _)| !listed.contains_key(h)) + .count() as u64; + if fresh > 0 + && !count_up( + &state, + &install.id, + &relay::day_sk(&today()), + "new_recipients", + fresh, + Some(relay::NEW_RECIPIENTS_PER_DAY), + 40 * 86_400, + ) + .await? + { + return Err(refuse(relay::Refusal::TooManyNew)); + } + + let cipher = common::mcp_credentials::Kms { + client: &state.kms, + key_id: &state.config.secrets_key_id, + }; + let mut promoted = 0u64; + for (hash, email) in &named { + if listed.get(hash) == Some(&relay::RecipientKind::Admin) { + continue; + } + let mut put = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", s(&hybrid_relay::install_pk(&install.id))) + .item("sk", s(&relay::recipient_sk(hash))) + .item("kind", s(relay::RecipientKind::Admin.as_str())) + .item("added_at", s(&chrono::Utc::now().to_rfc3339())); + if let Ok(sealed) = seal_admin(&cipher, &install.id, email).await { + put = put.item("sealed", s(&sealed)); + } + put.send().await.map_err(|e| { + warn!(error = %e, "email relay: admin write failed"); + unavailable() + })?; + promoted += 1; + } + let listed_admins: Vec = listed + .iter() + .filter(|(_, k)| **k == relay::RecipientKind::Admin) + .map(|(h, _)| h.clone()) + .collect(); + let hashes: Vec = named.iter().map(|(h, _)| h.clone()).collect(); + let demote = relay::admins_to_demote(&listed_admins, &hashes); + for hash in &demote { + state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", s(&hybrid_relay::install_pk(&install.id))) + .key("sk", s(&relay::recipient_sk(hash))) + .update_expression("SET kind = :m REMOVE sealed") + .expression_attribute_values(":m", s(relay::RecipientKind::Member.as_str())) + .send() + .await + .map_err(|e| { + warn!(error = %e, "email relay: admin demote failed"); + unavailable() + })?; + } + let _ = state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", s(&hybrid_relay::install_pk(&install.id))) + .key("sk", s(LIST_SK)) + .update_expression("SET admins = :n") + .expression_attribute_values(":n", n(named.len() as i64)) + .send() + .await; + audit( + &state, + &install.id, + "email_admins", + json!({ "admins": named.len(), "promoted": promoted, "demoted": demote.len() }), + ) + .await; + Ok(Json(json!({ + "ok": true, + "admins": named.len(), + "promoted": promoted, + "demoted": demote.len(), + }))) +} + +/// Every listed address's kind, by hash. +async fn listed_kinds( + state: &AppState, + install: &str, +) -> Result, (StatusCode, Json)> { + let mut out = HashMap::new(); + let mut start = None; + loop { + let r = state + .dynamo + .query() + .table_name(&state.config.settings_table_name) + .key_condition_expression("pk = :p AND begins_with(sk, :s)") + .expression_attribute_values(":p", s(&hybrid_relay::install_pk(install))) + .expression_attribute_values(":s", s(&relay::recipient_sk(""))) + .consistent_read(true) + .set_exclusive_start_key(start.take()) + .send() + .await + .map_err(|e| { + warn!(error = %e, "email relay: list read failed"); + unavailable() + })?; + for i in r.items() { + let hash = i + .get("sk") + .and_then(|v| v.as_s().ok()) + .and_then(|sk| sk.strip_prefix(&relay::recipient_sk(""))) + .map(str::to_string); + if let (Some(h), Some(k)) = (hash, kind_of(Some(i))) { + out.insert(h, k); + } + } + match r.last_evaluated_key() { + Some(k) => start = Some(k.clone()), + None => break, + } + } + Ok(out) +} + /// The install's list record: admin count, when it opted in, and when its /// one first listing happened. const LIST_SK: &str = "EMAILLIST"; diff --git a/services/gateway/src/routes/users.rs b/services/gateway/src/routes/users.rs index 4590a6b85..23a66d805 100644 --- a/services/gateway/src/routes/users.rs +++ b/services/gateway/src/routes/users.rs @@ -614,16 +614,10 @@ pub(crate) async fn pool_emails( emails: Vec, ) -> Result, String> { let checks = emails.into_iter().map(|email| async move { - let r = state - .cognito - .admin_get_user() - .user_pool_id(&state.config.cognito_user_pool_id) - .username(&email) - .send() - .await; - match r { - Err(e) if format!("{e:?}").contains("UserNotFound") => None, - _ => Some(email), + match pool_user(state, &email).await { + // An error counts as an account: nobody is emailed on a guess. + Ok(PoolUser::Account) | Err(_) => Some(email), + Ok(PoolUser::None | PoolUser::Unconfirmed) => None, } }); Ok(futures::future::join_all(checks) @@ -633,6 +627,51 @@ pub(crate) async fn pool_emails( .collect()) } +/// What the user pool has for an email. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum PoolUser { + /// No sign-in here. + None, + /// Signed up but never entered the code: no way in yet. Counts as no + /// account (a set-up email, and signing up again replaces it). + Unconfirmed, + /// A sign-in that works. + Account, +} + +impl PoolUser { + pub(crate) fn of( + status: Option<&aws_sdk_cognitoidentityprovider::types::UserStatusType>, + ) -> Self { + use aws_sdk_cognitoidentityprovider::types::UserStatusType; + match status { + Some(UserStatusType::Unconfirmed) => PoolUser::Unconfirmed, + _ => PoolUser::Account, + } + } + + /// Whether they can sign in (or reset a password) with it. + pub(crate) fn has_account(self) -> bool { + self == PoolUser::Account + } +} + +/// The user pool's word on `email`. +pub(crate) async fn pool_user(state: &AppState, email: &str) -> Result { + match state + .cognito + .admin_get_user() + .user_pool_id(&state.config.cognito_user_pool_id) + .username(email) + .send() + .await + { + Ok(u) => Ok(PoolUser::of(u.user_status())), + Err(e) if format!("{e:?}").contains("UserNotFound") => Ok(PoolUser::None), + Err(e) => Err(format!("{e:?}")), + } +} + /// A member (not an invite) with an email who has no sign-in on this install. pub(crate) fn needs_setup( status: &str, @@ -849,7 +888,7 @@ pub async fn resend_invite( role, ) .await - .map_err(|_| internal("Failed to resend invite", "email send failed"))?; + .map_err(|e| not_sent("Invite not resent", &e))?; // The email went out, so the invite is good again from now (this is also // how an expired invite is renewed). Only while it is still an invite: if @@ -962,28 +1001,24 @@ pub async fn send_setup_email( } let item = get_member(&state, &claims.team_id, &user_id).await?; let email = check_setup_email(&item)?.to_string(); - match state - .cognito - .admin_get_user() - .user_pool_id(&state.config.cognito_user_pool_id) - .username(&email) - .send() - .await - { - Ok(_) => { + // Signed up but never confirmed counts as not set up: the email's link + // takes them to sign-up, which replaces that unconfirmed sign-in. + match pool_user(&state, &email).await { + Ok(PoolUser::Account) => { return Err(fail( StatusCode::CONFLICT, "They've already signed in on this install.", )) } - Err(e) if format!("{e:?}").contains("UserNotFound") => {} + Ok(PoolUser::None | PoolUser::Unconfirmed) => {} 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), + SetupSend::Failed(e) => not_sent("Set-up email not sent", &e), + SetupSend::NotRecorded(e) => internal("Set-up email sent but not recorded", e), })?; info!(team_id = %claims.team_id, "Set-up email sent"); Ok(Json( @@ -996,7 +1031,10 @@ pub async fn send_setup_email( pub(crate) enum SetupSend { /// One went less than an hour ago, or five this week: the sentence says which. Wait(&'static str), - Failed(String), + /// It wasn't sent: the reason code and its words. + Failed(common::mail::SendError), + /// It went, but the record of it wasn't written. + NotRecorded(String), } /// Sends `item` (a member with an email, checked by the caller) the set-up email, at most @@ -1017,7 +1055,7 @@ pub(crate) async fn deliver_setup_email( 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()))?; + .map_err(SetupSend::Failed)?; let stamp = now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true); let mut kept: Vec = log @@ -1038,7 +1076,7 @@ pub(crate) async fn deliver_setup_email( .expression_attribute_values(":log", AttributeValue::L(kept)) .send() .await - .map_err(|e| SetupSend::Failed(format!("record: {e}")))?; + .map_err(|e| SetupSend::NotRecorded(e.to_string()))?; Ok(stamp) } @@ -1141,6 +1179,13 @@ pub async fn send_setup_emails_all( error!(error = %e, "Set-up email not sent"); failed += 1; } + Err(SetupSend::NotRecorded(e)) => { + error!(error = %e, "Set-up email sent but not recorded"); + sent.insert( + bare_id(s(item, "sk")).to_string(), + Value::String(now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)), + ); + } } } info!(team_id = %claims.team_id, sent = sent.len(), skipped, failed, "Set-up emails sent to all"); @@ -1272,6 +1317,8 @@ pub async fn update_role( })?; info!(user_id = %sk, new_role = %body.role, team_id = %claims.team_id, "Role updated"); + // The relay's list of who may vouch for invites follows the role. + super::email_settings::sync_relay_admins_quietly(&state).await; Ok(Json(json!({ "status": "updated", "role": body.role }))) } @@ -1323,6 +1370,9 @@ pub async fn remove_user( { super::plugin_pkgs::member_removed(&state, &claims.team_id, email, &claims.email).await; } + if matches!(role_of(target), "owner" | "admin") { + super::email_settings::sync_relay_admins_quietly(&state).await; + } Ok(Json(json!({ "status": "removed" }))) } @@ -1806,7 +1856,7 @@ async fn send_invite_email( inviter: &str, org: &str, role: &str, -) -> Result<(), StatusCode> { +) -> Result<(), common::mail::SendError> { use common::mail::{self, templates::fit}; let template_name = format!("{}-team-invite", state.config.ses_template_prefix); let template_data = serde_json::to_string(&json!({ @@ -1818,7 +1868,7 @@ async fn send_invite_email( let sender = super::email_settings::sender(state); // Through CoderHelm, the invite is listed first, vouched for by the // admin sending it (the gateway only lets admins invite). - let listed = mail::list_invite(&sender, inviter, to).await; + let listed = list_vouched(state, &sender, inviter, to).await; // Nothing was sent when the listing failed: that record stays untimed. let (result, send_ms) = match listed { Err(e) => (Err(e), None), @@ -1848,15 +1898,171 @@ async fn send_invite_email( } }; super::deliveries::record_mail(state, team, "invite", to, &result, send_ms).await; - result.map(|_| ()).map_err(|e| { + result.map(|_| ()).inspect_err(|e| { error!("Failed to send invite email: {e}"); - StatusCode::INTERNAL_SERVER_ERROR }) } +/// What to do when the relay won't take an admin's word for an address. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Vouch { + /// Listed: send. + Done, + /// The relay doesn't count `by` as an admin: tell it who the install's + /// admins are, then ask again. + SyncThenRetry, + /// Still refused after the sync: the config's first admin (the one the + /// relay listed as an admin first) vouches instead. + AskConfigAdmin(String), + /// Nothing more to try: the refusal stands. + GiveUp, +} + +/// The next step after a listing attempt. `attempt` counts from 0. +pub(crate) fn next_vouch( + result: &Result<(), common::mail::SendError>, + attempt: u8, + by: &str, + config_admin: Option<&str>, +) -> Vouch { + use common::mail::relay; + match result { + Ok(()) => Vouch::Done, + Err(e) if e.code == relay::Refusal::NotAdmin.code() => match attempt { + 0 => Vouch::SyncThenRetry, + 1 => match config_admin { + Some(a) if relay::normalize(a) != relay::normalize(by) => { + Vouch::AskConfigAdmin(a.to_string()) + } + _ => Vouch::GiveUp, + }, + _ => Vouch::GiveUp, + }, + Err(_) => Vouch::GiveUp, + } +} + +/// Lists `to` with the relay on `by`'s word ([`common::mail::list_invite`]). +/// An admin the relay doesn't know as one yet (added after the relay was +/// turned on, or copied over from the hosted CoderHelm) isn't refused for +/// it: the install tells the relay who its admins are and asks again. +async fn list_vouched( + state: &AppState, + sender: &common::mail::Sender<'_>, + by: &str, + to: &str, +) -> Result<(), common::mail::SendError> { + let config_admin = common::mail::install_admin(); + let mut result = common::mail::list_invite(sender, by, to).await; + for attempt in 0..3u8 { + match next_vouch(&result, attempt, by, config_admin.as_deref()) { + Vouch::Done | Vouch::GiveUp => break, + Vouch::SyncThenRetry => { + if let Err(e) = super::email_settings::sync_relay_admins(state).await { + tracing::warn!(error = %e, "relay admins not synced"); + } + result = common::mail::list_invite(sender, by, to).await; + } + Vouch::AskConfigAdmin(a) => { + result = common::mail::list_invite(sender, &a, to).await; + } + } + } + result +} + +/// The answer when an email wasn't sent: the true reason and its fix, never +/// "something went wrong" (only admins send these). +pub(crate) fn not_sent(context: &str, e: &common::mail::SendError) -> ApiError { + error!("{context}: {e}"); + let r = common::deliveries::reason(&e.code); + let text = if r.code == "unknown" { + format!("The email wasn't sent: {}", e.message) + } else { + format!("The email wasn't sent. {} {}", r.message, r.fix) + }; + ( + StatusCode::BAD_GATEWAY, + Json(json!({ "error": text, "code": e.code })), + ) +} + #[cfg(test)] mod tests { + fn refused(code: &str) -> Result<(), common::mail::SendError> { + Err(common::mail::SendError { + code: code.into(), + message: "no".into(), + }) + } + + #[test] + fn an_admin_the_relay_does_not_know_yet_is_synced_not_refused() { + // The failure: an admin's resend was refused (inviter_not_admin) + // and the install gave up at once. + let r = refused("inviter_not_admin"); + assert_eq!( + next_vouch(&r, 0, "owner@acme.test", Some("first@acme.test")), + Vouch::SyncThenRetry + ); + // Still refused after the sync (a relay from before it): the + // config's first admin vouches. + assert_eq!( + next_vouch(&r, 1, "owner@acme.test", Some("first@acme.test")), + Vouch::AskConfigAdmin("first@acme.test".into()) + ); + // Never the same admin twice, never a loop, and other refusals stand. + assert_eq!( + next_vouch(&r, 1, "First@acme.test", Some("first@acme.test")), + Vouch::GiveUp + ); + assert_eq!( + next_vouch(&r, 2, "o@acme.test", Some("f@acme.test")), + Vouch::GiveUp + ); + assert_eq!( + next_vouch(&refused("email_paused"), 0, "o@acme.test", None), + Vouch::GiveUp + ); + assert_eq!(next_vouch(&Ok(()), 0, "o@acme.test", None), Vouch::Done); + } + + #[test] + fn a_refused_email_says_why_instead_of_something_went_wrong() { + let e = common::mail::SendError { + code: "inviter_not_admin".into(), + message: "Only an install admin can add people to the email list.".into(), + }; + let (status, Json(body)) = not_sent("test", &e); + assert_eq!(status, StatusCode::BAD_GATEWAY); + let text = body["error"].as_str().unwrap(); + assert!(!text.contains("Something went wrong"), "{text}"); + assert!(text.contains("Only an install admin"), "{text}"); + assert_eq!(body["code"], "inviter_not_admin"); + let other = common::mail::SendError { + code: "brand_new".into(), + message: "The relay said no.".into(), + }; + let (_, Json(body)) = not_sent("test", &other); + assert_eq!(body["error"], "The email wasn't sent: The relay said no."); + } + + #[test] + fn an_unconfirmed_sign_up_is_not_an_account() { + use aws_sdk_cognitoidentityprovider::types::UserStatusType; + // The failure: a copied-over member who signed up but never got the + // code was "already signed in", so no set-up email could go and a + // reset code was asked of Cognito for a sign-in with no verified email. + let p = PoolUser::of(Some(&UserStatusType::Unconfirmed)); + assert_eq!(p, PoolUser::Unconfirmed); + assert!(!p.has_account()); + assert!(PoolUser::of(Some(&UserStatusType::Confirmed)).has_account()); + assert!(PoolUser::of(Some(&UserStatusType::ResetRequired)).has_account()); + assert!(PoolUser::of(None).has_account()); + assert!(!PoolUser::None.has_account()); + } + #[test] fn a_setup_email_waits_an_hour_and_five_a_week() { let now = chrono::DateTime::parse_from_rfc3339("2026-11-10T12:00:00Z")