Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
81 changes: 49 additions & 32 deletions lambda/custom-message/handler.js
Original file line number Diff line number Diff line change
@@ -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;
57 changes: 57 additions & 0 deletions lambda/custom-message/handler.test.js
Original file line number Diff line number Diff line change
@@ -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: "<p>Code {{code}}</p>" },
};

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, "<p>Code {####}</p>");
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: "<p>no code</p>" } }),
});
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, {});
});
2 changes: 1 addition & 1 deletion services/common/src/deliveries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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." },
Expand Down
80 changes: 71 additions & 9 deletions services/common/src/mail/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<crate::hybrid::client::Credentials>, 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,
Expand All @@ -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<Item = &'a str>) -> Option<Vec<String>> {
let mut out: Vec<String> = 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).
Expand Down Expand Up @@ -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<String> = (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 {
Expand Down
Loading
Loading