diff --git a/docs/self-host/config-reference.md b/docs/self-host/config-reference.md index 0663c1e5b..ca9098e55 100644 --- a/docs/self-host/config-reference.md +++ b/docs/self-host/config-reference.md @@ -83,6 +83,8 @@ See [Model providers](./model-providers.md). Logo in email headers. - **`email.privacyUrl`** *string or null, default `null`*\ A privacy page linked in email footers. +- **`email.transport`** *`"ses"` or `"coderhelm"`, default `"ses"`*\ + How email is sent until an admin changes it in Settings, Emails: this install's own Amazon SES, or CoderHelm's mail service (needs the install registered for hybrid). See [Email](./email.md). @@ -107,8 +109,8 @@ A self-hosted install is one organization: sign-up is closed to everyone else. A The CodeBuild sandbox that runs a repo's build and checks during runs. - **`integrations.logAnalyzer`** *boolean, default `true`*\ Scheduled log analysis for AWS accounts teams connect. -- **`integrations.weeklySummary`** *boolean, default `true`*\ - The Monday summary email. +- **`integrations.weeklySummary`** *boolean, default `false`*\ + The Monday summary email's starting value. An install admin turns it on or off in Settings, Emails; that choice wins. - **`integrations.weeklySummaryListedTeamsOnly`** *boolean, default `false`*\ Only teams with a rollout list get the summary. diff --git a/docs/self-host/email.md b/docs/self-host/email.md index a6290b3e2..9244b440d 100644 --- a/docs/self-host/email.md +++ b/docs/self-host/email.md @@ -4,7 +4,28 @@ description: How CoderHelm sends email from your AWS account with Amazon SES, an order: 7 --- -CoderHelm sends run results, invites, token limit warnings, the weekly summary and account emails through Amazon SES in your account, from `email.from`. +A self-hosted install sends the emails it needs, and nothing else until you turn it on. It sends them through Amazon SES in your account, from `email.from`, or, if you choose, through CoderHelm's mail service (see [Send through CoderHelm](#send-through-coderhelm)). It never emails a CoderHelm address. + +## Which emails it sends + +**Settings, Emails** (install admins) lists them all. + +| Email | Kind | Why | +|---|---|---| +| Sign-up codes and password resets | Essential | Nobody can verify their address or get back in without them. Amazon Cognito makes, sends and checks them inside your install. | +| Team invites | Essential | The only way an invited person learns how to join. | +| Plugin approval requests | Essential | A named approver must approve a plugin draft before it publishes. | +| Knowledge source sign-in alerts | Essential | Tells admins a knowledge source stopped syncing. | +| Token limit warnings | Essential | Tells the team before work stops at the monthly limit. Each person can turn these off. | +| Support ticket updates | Essential | Replies and status changes on tickets someone filed. | +| Webhook endpoint turned off | Essential | Tells a team's admins when CoderHelm stopped sending to an endpoint that failed for days. | +| Two-factor lockout alerts | Essential | Tells admins and owners when someone's two-factor sign-in was paused after too many wrong codes. | +| Update notices | Essential | New releases, finished or failed updates, address changes, to install admins. | +| Test email | Essential | Only when an admin presses **Send test email** in Setup. | +| Weekly summary | Optional, **off** | The Monday email with each team's week. | +| Welcome email | Optional, **off** | A short hello after someone signs up. | + +Optional emails stay off until an install admin turns them on in **Settings, Emails**; no redeploy is needed. `integrations.weeklySummary: true` in the config starts the summary on instead. Each person can still turn emails off for themselves in **Settings, Notifications** or with an email's unsubscribe link. The hosted CoderHelm service is unchanged: its weekly summary goes to everyone who hasn't unsubscribed. ## The identity @@ -40,3 +61,21 @@ The email templates are created by the email stack with your URLs filled in. `em Every link CoderHelm sends from your install points at your install: emails (run results, invites, approvals, the weekly summary and its unsubscribe link), Slack and Teams cards, Jira comments and GitHub comments all use your own address. The header logo loads from your install (`/favicon.svg`) unless you set `email.logoUrl`, so opening an email never calls CoderHelm's servers. Support and "reply to unsubscribe" go to `email.supportInbox` (by default `email.from`), never to CoderHelm support. The only coderhelm.com links left are the public docs on docs.coderhelm.com. If the install doesn't know its own address (no `APP_URL` and `API_URL`, and the CloudFront address not yet readable from SSM), links stay relative rather than pointing anywhere else, the services log an error at start, and **Settings, then Setup** fails **Web address answers** until a deploy sets it. + +## Send through CoderHelm + +If you'd rather not set up SES (verifying a sender and leaving the sandbox), an install registered for [hybrid](./hybrid.md) can send its email through CoderHelm's mail service instead. Choose **Through CoderHelm** in **Settings, Emails**, or in the install guide's **Optional setup**, or set `"email": { "transport": "coderhelm" }`. It is off unless you pick it, and it applies to every email the install sends (invites, approvals, alerts, update notices, and the optional ones you turned on). Sign-up codes stay with Amazon Cognito inside your install: CoderHelm never sees them. + +If CoderHelm's mail service can't be reached, the email fails and shows in **Deliveries** and **Settings, Setup**. Nothing is sent another way instead. + +**What CoderHelm sees:** each recipient's address, the template id and its parameters (names, PR titles and run links in the weekly summary). It keeps only delivery metadata after sending: the template id, a shortened address (`d***@example.com`) and whether it was delivered, for 3 days. It never keeps the email itself. + +**How it works:** + +- Your install sends a template id and its parameters, signed with its registration secret, never a subject or HTML. CoderHelm writes the email from its own templates. +- Mail comes from `notifications@notify.coderhelm.com` with your install's address as the name (`acme.coderhelm.com via CoderHelm`), and no Reply-To. The footer names your install and its admin. +- Every link in the email goes to your install's own verified address (its CloudFront address or its CoderHelm name). An install on its own custom domain should use its own SES for now. +- It only sends to your install's people and pending invites, listed by an install admin, at most 50 new addresses a day, 30 emails a minute and 500 a day. +- An address that bounces or marks an email as spam gets nothing more. Too many bounces or complaints pause email for your install, and your install admins are told. + +See [Threat model](./hybrid.md#email-threat-model) for what each of these protects against. diff --git a/docs/self-host/hybrid.md b/docs/self-host/hybrid.md index 56e9697c9..bb7a91e79 100644 --- a/docs/self-host/hybrid.md +++ b/docs/self-host/hybrid.md @@ -25,6 +25,7 @@ Your code, runs, plans, reviews, memory, knowledge and secrets stay in your AWS | Token broker | the short-lived installation token it mints for your install (scoped to the repositories you chose, never more than the app's permissions) | no tokens; a record of each mint for 14 days | | Jira app relay | each issue event, in transit, unchanged | as for GitHub. The Forge app's secret is checked by your install, so CoderHelm can't make an event up | | Notion, Confluence, Google Drive | the sign-in, once | the provider sign-in, encrypted with a key only CoderHelm's services can use, so it can hand your install access tokens. Disconnecting revokes it. Notion's tokens don't expire by themselves: a copy your install holds stays valid until Notion's own integration page removes it | +| Email through CoderHelm (opt-in, [Email](./email.md#send-through-coderhelm)) | each email's recipient address, template id and parameters (names, PR titles and run links in the weekly summary), in transit; CoderHelm writes the email from its own templates | delivery metadata only: template id, a shortened address and the status, for 3 days. Salted hashes of the addresses your install listed, and your install admins' addresses sealed with a key only CoderHelm's services can use, to tell them if email pauses | | Sharing with support (opt-in) | metadata of failed deliveries, and payload previews only if you also choose that | for 14 days, so support can see what failed | CoderHelm never stores your code, never sees your model calls or your AWS credentials, and can't sign in to your install. @@ -40,6 +41,7 @@ How the pieces are protected: - **Scoped tokens.** The broker mints tokens only for installations linked to your install, narrowed to the repositories you chose and, within those, to the repositories the person who linked it can push to on GitHub. GitHub itself enforces both: they are part of the token request. - **Sign-ins are yours only once your install takes them.** A Notion, Confluence or Google Drive sign-in is held apart until your install redeems it with its secret and its PKCE verifier, so nobody else can put their account in place of yours. - **Revocable.** CoderHelm can turn an install's access off (its name and records go, its GitHub links are removed, the relay and broker refuse it, and the same CloudFront can't register again), and every action is in an audit log. +- **Email only as itself.** See [Email threat model](#email-threat-model) below. - **Same-site safety.** Addresses under coderhelm.com are the same site as app.coderhelm.com and api.coderhelm.com to a browser, so CoderHelm doesn't rely on that: its cookies are host-only (`__Host-`, no Domain attribute), its CORS lists exact origins, and the API refuses any change sent with cookies from another page on the same site. An install's pages can't read or change coderhelm.com sessions. The full threat model, with each attack and what stops it, is in [Security model](./security.md#hybrid-threat-model). @@ -87,3 +89,18 @@ A forward that fails is retried with growing waits for about 24 hours. Both side ## For CoderHelm's operators The hosted side runs in the hosted deployment's API stack when `hybrid.zone` is set in its config (the parent zone is configurable, so moving customer addresses to a separate domain later is a config change). It needs `hybrid_master_key` (32 or more random characters) in the hosted secret, the callback URL `https://api.coderhelm.com/auth/github/callback/hybrid` on CoderHelm's GitHub App, and the GitHub App's setup page (the dashboard's Settings, GitHub) to forward `state=hyb_…` returns. Platform admins see every install and the audit log at `GET /api/admin/hybrid`, and revoke one with `POST /api/admin/hybrid/:install_id/revoke`. + + +## Email threat model + +What CoderHelm's mail service refuses, and how. Each line has a test (`services/common/src/mail`). + +| Threat | What stops it | +|---|---| +| Another install, or someone without the install's secret, sends as your install | Every request is signed with the install's own secret (derived per install on CoderHelm's side), checked within 5 minutes, with a request id that is refused the second time. Only a registered, verified, not revoked install can send; revoking stops it at the next request. | +| An email made to look like it comes from CoderHelm support or security | No subject, HTML, sender or Reply-To can be sent: only a template id and parameters. Subjects are fixed. Parameters are plain text, escaped, length-limited, and refused when they read as CoderHelm itself ("CoderHelm support", "CoderHelm security"). The sender name is built only from the install's verified address, and a name that reads as CoderHelm staff (`support`, `billing`, `c0derhe1m` and other look-alikes) falls back to the CloudFront address. Every email's footer names the install. | +| A phishing link | Link parameters must be `https://` links to the install's own verified address. Links, addresses and look-alike domains in text parameters are removed before the email is written. | +| Mail to people outside the install | Only listed addresses: the install's admins, people and pending invites. Only an install admin can list an invite, at most 50 new addresses a day. CoderHelm's own addresses are never a recipient. | +| Spam or a burst | 30 emails a minute and 500 a day per install. Bounced and complaining addresses get nothing more; too many bounces or complaints pause the install's email and its admins are told. | +| Spoofing CoderHelm's sending domain | Mail comes from its own subdomain, `notify.coderhelm.com`, with Easy DKIM, SPF for a custom MAIL FROM and DMARC `p=reject`, so it can't harm the main domain's reputation and can't be forged from it. | +| Secrets in mail | Sign-up codes never leave the install. Parameters marked secret (signed approval and unsubscribe links) are never logged or stored; nothing is kept but delivery metadata. | diff --git a/docs/self-host/integrations.md b/docs/self-host/integrations.md index c1c464151..c3dd6e6a1 100644 --- a/docs/self-host/integrations.md +++ b/docs/self-host/integrations.md @@ -151,7 +151,7 @@ Needs a domain (Google requires a fixed callback URL). Create an OAuth client in ## Weekly summary email -`integrations.weeklySummary` sends each team's members a Monday summary (13:00 UTC). People can turn it off in their notification settings or with the email's unsubscribe link. +The Monday summary (13:00 UTC) is an optional email: on a self-hosted install it is off until an install admin turns it on in **Settings, Emails**, no redeploy needed. `integrations.weeklySummary: true` in the config starts it on instead. Each person can still turn it off in their notification settings or with the email's unsubscribe link. See [Email](./email.md). ## Scheduled jobs diff --git a/docs/self-host/options.md b/docs/self-host/options.md index 9d4ba3468..3137ba056 100644 --- a/docs/self-host/options.md +++ b/docs/self-host/options.md @@ -35,11 +35,14 @@ One list of everything you can set up, and where. Required items are steps in th *Launch Stack:* `Hostname` (`HostedZone` to pick a zone)\ *Config:* `domain`\ *Checked by:* `domain` -- **Send email from**\ - *Install guide:* More options\ - *Launch Stack:* `EmailFrom`\ - *Config:* `email.from`, `email.identity`\ - *Checked by:* `email`, `email_identity` +- **Send email: your own Amazon SES or through CoderHelm**\ + *Install guide:* More options, Send email\ + *Launch Stack:* `EmailTransport`, `EmailFrom`\ + *Config:* `email.transport`, `email.from`, `email.identity`\ + *Checked by:* `email`, `email_identity`, `optional_emails` +- **Weekly summary email (off; turn on in Settings)**\ + *Config:* `integrations.weeklySummary`\ + *Checked by:* `optional_emails` - **Let people from your company join** (default: only people you invite)\ *Install guide:* More options\ *Launch Stack:* `SignupDomain`\ @@ -85,6 +88,10 @@ One list of everything you can set up, and where. Required items are steps in th - **Sign-up and password emails through SES**\ *Where:* `email.cognitoUsesSes`\ *Guide:* [Email](./email.md) +- **Optional emails (weekly summary, welcome) and how email is sent**\ + *Where:* Settings, Emails\ + *Checked by:* `optional_emails`\ + *Guide:* [Email](./email.md) - **Sign in with Google**\ *Where:* Google Cloud, the secret, `integrations.googleSignIn`\ *Checked by:* `google_sign_in`\ @@ -129,7 +136,7 @@ One list of everything you can set up, and where. Required items are steps in th - **Keep data when stacks are deleted**\ *Where:* `retainData` (on)\ *Guide:* [Config reference](./config-reference.md) -- **The build sandbox, log analysis, weekly summary**\ +- **The build sandbox, log analysis**\ *Where:* `integrations.*`\ *Guide:* [Integrations](./integrations.md) - **Support access for install admins**\ diff --git a/infra/cfn/coderhelm-selfhost-launch.yaml b/infra/cfn/coderhelm-selfhost-launch.yaml index 6e473c91c..ce1cad911 100644 --- a/infra/cfn/coderhelm-selfhost-launch.yaml +++ b/infra/cfn/coderhelm-selfhost-launch.yaml @@ -24,7 +24,7 @@ Metadata: - Label: { default: "Who may join (this install is for one organization; change these later in Settings, Sign-in)" } Parameters: [SignupDomain, RequireTwoFactor] - Label: { default: "Optional" } - Parameters: [EmailFrom, BedrockInferencePrefix, Telemetry] + Parameters: [EmailTransport, EmailFrom, BedrockInferencePrefix, Telemetry] - Label: { default: "Optional: updates (you can change these later in Settings, System)" } Parameters: [AutoUpdate, UpdateWindow, UpdateTimezone] - Label: { default: "Filled in by the install guide (leave as they are)" } @@ -36,6 +36,7 @@ Metadata: Version: { default: "CoderHelm release" } Hostname: { default: "Hostname" } HostedZone: { default: "Route 53 hosted zone" } + EmailTransport: { default: "Send email" } EmailFrom: { default: "Send email from" } SignupDomain: { default: "Let people from your company join" } RequireTwoFactor: { default: "Require two-factor sign-in" } @@ -84,6 +85,11 @@ Parameters: Default: "" Description: Leave empty (the zone is found in this account). Only to pick one, e.g. example.com. AllowedPattern: "^$|^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$" + EmailTransport: + Type: String + Default: ses + AllowedValues: [ses, coderhelm] + Description: "ses: through this account's Amazon SES (the default). coderhelm: through CoderHelm's mail service (hybrid; CoderHelm sees each recipient's address and the email's parameters, and keeps only delivery metadata)." EmailFrom: Type: String Default: "" @@ -210,6 +216,7 @@ Resources: - { Name: STAGE, Value: !Ref Stage } - { Name: ADMIN_EMAIL, Value: !Ref AdminEmail } - { Name: EMAIL_FROM, Value: !Ref EmailFrom } + - { Name: EMAIL_TRANSPORT, Value: !Ref EmailTransport } - { Name: HOSTNAME_ARG, Value: !Ref Hostname } - { Name: HOSTED_ZONE, Value: !Ref HostedZone } - { Name: MODEL_PROVIDER, Value: !Ref ModelProvider } diff --git a/infra/config/selfhost.example.json b/infra/config/selfhost.example.json index 3ccfa2cc0..ec925483d 100644 --- a/infra/config/selfhost.example.json +++ b/infra/config/selfhost.example.json @@ -17,7 +17,7 @@ "googleSignIn": false, "sandbox": true, "logAnalyzer": true, - "weeklySummary": true + "weeklySummary": false }, "telemetry": { "enabled": false diff --git a/infra/lib/api-stack.ts b/infra/lib/api-stack.ts index e47766553..4b988d03a 100644 --- a/infra/lib/api-stack.ts +++ b/infra/lib/api-stack.ts @@ -21,7 +21,8 @@ import { Construct } from "constructs"; import { ResolvedConfig } from "./config"; import { repoPath } from "./paths"; import { Hybrid } from "./hybrid"; -import { serviceEnvironment, modelPolicyStatements, publicUrlReadStatement, recordNameIn, setupEnvironment, setupStatements, updaterInvokeStatement } from "./service-env"; +import { serviceEnvironment, modelPolicyStatements, publicUrlReadStatement, recordNameIn, setupEnvironment, setupStatements, updaterInvokeStatement, weeklySummaryScheduled } from "./service-env"; +import { MailRelay, relaySendStatement } from "./mail-relay"; interface ApiStackProps extends cdk.StackProps { stage: string; @@ -49,6 +50,7 @@ export class ApiStack extends cdk.Stack { public readonly gatewayFunction: lambda.Function; public readonly mcpProxyFunction: lambda.Function; public readonly ticketQueue: sqs.Queue; + /** The mail relay's bounces and complaints (hosted side of hybrid only). */ public readonly ciFixQueue: sqs.Queue; public readonly feedbackQueue: sqs.Queue; /** Outbound webhook events and their retries (common::webhooks). */ @@ -281,6 +283,12 @@ export class ApiStack extends cdk.Stack { deadLetterQueue: { queue: dlq, maxReceiveCount: 3 }, }); + // CoderHelm's mail relay (hosted side of hybrid only): its sending + // subdomain, DNS, configuration set, and bounces to the worker. + if (cfg.mailRelay) { + new MailRelay(this, "MailRelay", { cfg, ticketQueue: this.ticketQueue }); + } + this.ciFixQueue = new sqs.Queue(this, "CiFixQueue", { queueName: `${prefix}-ci-fix`, visibilityTimeout: cdk.Duration.minutes(16), @@ -393,7 +401,9 @@ export class ApiStack extends cdk.Stack { new events.Rule(this, "WeeklySummarySchedule", { ruleName: `${prefix}-weekly-summary`, description: "Weekly summary email (Mondays 13:00 UTC)", - enabled: cfg.integrations.weeklySummary, + // Always there on a self-hosted install: the worker sends nothing + // until an install admin turns the summary on (Settings, Emails). + enabled: weeklySummaryScheduled(cfg), schedule: events.Schedule.cron({ minute: "0", hour: "13", weekDay: "MON" }), targets: [ new targets.SqsQueue(this.ticketQueue, { @@ -559,7 +569,7 @@ export class ApiStack extends cdk.Stack { ...serviceEnvironment(cfg, this.account), }, }); - for (const st of [...modelPolicyStatements(cfg, this), publicUrlReadStatement(cfg, this), updaterInvokeStatement(cfg, this)]) { + for (const st of [...modelPolicyStatements(cfg, this), publicUrlReadStatement(cfg, this), updaterInvokeStatement(cfg, this), relaySendStatement(cfg, this.account)]) { if (st) this.gatewayFunction.addToRolePolicy(st); } // A self-hosted install's GitHub App manifest landing (routes/setup.rs, diff --git a/infra/lib/config.ts b/infra/lib/config.ts index 5688c14f8..2b3a05026 100644 --- a/infra/lib/config.ts +++ b/infra/lib/config.ts @@ -147,6 +147,13 @@ export interface CoderhelmConfig { logoUrl?: string; /** Privacy policy link in email footers. Default: none. */ privacyUrl?: string | null; + /** + * Self-hosted installs: how email leaves until an admin changes it in + * Settings, Emails. `ses` (default): this install's own Amazon SES. + * `coderhelm`: CoderHelm's mail service (hybrid; needs the install + * registered with CoderHelm). + */ + transport?: "ses" | "coderhelm"; }; /** People with admin rights over the whole deployment (the first one is you). */ admins?: string[]; @@ -172,7 +179,11 @@ export interface CoderhelmConfig { sandbox?: boolean; /** The scheduled log analyzer for connected AWS accounts. Default true. */ logAnalyzer?: boolean; - /** The Monday summary email. Default true. */ + /** + * The Monday summary email. Hosted deployment: default true. Self-hosted + * installs: default false, the starting value until an install admin + * turns it on or off in Settings, Emails. + */ weeklySummary?: boolean; /** While true, only teams with a rollout list get the Monday summary. Default false. */ weeklySummaryListedTeamsOnly?: boolean; @@ -271,7 +282,14 @@ export interface ResolvedConfig { cognitoUsesSes: boolean; logoUrl: string | null; privacyUrl: string | null; + transport: "ses" | "coderhelm"; }; + /** + * The hosted side of CoderHelm's mail relay (only with `hybrid`): its own + * sending subdomain, so relayed mail never touches the main domain's + * reputation. null everywhere else. + */ + mailRelay: { domain: string; from: string } | null; admins: string[]; signup: { emails: string[]; domains: string[]; requireTwoFactor: boolean }; integrations: Required>; @@ -484,6 +502,9 @@ export function validateConfig(c: unknown): string[] { const v = e[k]; if (v !== undefined && v !== null && !URL_RE.test(String(v))) p.push(`email.${k}: a URL`); } + if (e.transport !== undefined && e.transport !== "ses" && e.transport !== "coderhelm") { + p.push('email.transport: "ses" or "coderhelm"'); + } } if (cfg.admins !== undefined) { @@ -627,7 +648,14 @@ export function resolveConfig(cfg: CoderhelmConfig, opts: { skipValidation?: boo cognitoUsesSes: e.cognitoUsesSes ?? false, logoUrl: e.logoUrl ?? null, privacyUrl: e.privacyUrl ?? null, + transport: e.transport ?? "ses", }, + mailRelay: cfg.hybrid + ? { + domain: `notify.${cfg.hybrid.zone.toLowerCase()}`, + from: `notifications@notify.${cfg.hybrid.zone.toLowerCase()}`, + } + : null, admins, signup: { emails: [...new Set([...admins, ...(cfg.signup?.emails ?? [])].map((x) => x.toLowerCase()))], @@ -638,7 +666,9 @@ export function resolveConfig(cfg: CoderhelmConfig, opts: { skipValidation?: boo googleSignIn: i.googleSignIn ?? false, sandbox: i.sandbox ?? true, logAnalyzer: i.logAnalyzer ?? true, - weeklySummary: i.weeklySummary ?? true, + // Optional email is opt-in on a self-hosted install, on as before for + // the hosted deployment (split layout). + weeklySummary: i.weeklySummary ?? layout === "split", weeklySummaryListedTeamsOnly: i.weeklySummaryListedTeamsOnly ?? false, }, dashboardAssetDir: cfg.dashboard?.assetDir ?? null, diff --git a/infra/lib/email-stack.ts b/infra/lib/email-stack.ts index f95b840a5..9c23aed40 100644 --- a/infra/lib/email-stack.ts +++ b/infra/lib/email-stack.ts @@ -208,6 +208,7 @@ export class EmailStack extends cdk.Stack { value: this.configSet.configurationSetName, }); } + } // ─── Email templates (Mustache-style {{var}} placeholders for SES) ─── diff --git a/infra/lib/mail-relay.ts b/infra/lib/mail-relay.ts new file mode 100644 index 000000000..82556564f --- /dev/null +++ b/infra/lib/mail-relay.ts @@ -0,0 +1,125 @@ +/** + * CoderHelm's mail relay for hybrid installs (the hosted side only; see + * services/common/src/mail and docs/self-host/hybrid.md). + * + * It sends from its own subdomain (`notify.`) so relayed mail can never + * harm the main domain's reputation: Easy DKIM, a custom MAIL FROM with SPF, + * and a DMARC policy of reject, all written as records in the zone. Its + * configuration set publishes bounces and complaints to a topic that reaches + * the worker raw on the ticket queue. Only the gateway (sending) and the + * worker (pause notices) may send as the relay, and only from its address. + */ +import * as cdk from "aws-cdk-lib"; +import * as iam from "aws-cdk-lib/aws-iam"; +import * as route53 from "aws-cdk-lib/aws-route53"; +import * as ses from "aws-cdk-lib/aws-ses"; +import * as sns from "aws-cdk-lib/aws-sns"; +import * as subs from "aws-cdk-lib/aws-sns-subscriptions"; +import * as sqs from "aws-cdk-lib/aws-sqs"; +import { Construct } from "constructs"; +import { ResolvedConfig } from "./config"; + +/** The relay's configuration set name. */ +export function relayConfigSetName(cfg: ResolvedConfig): string { + return `${cfg.prefix}-relay`; +} + +/** Sending as the relay: its identity, through its configuration set, from its address only. */ +export function relaySendStatement(cfg: ResolvedConfig, account: string): iam.PolicyStatement | undefined { + if (!cfg.mailRelay) return undefined; + return new iam.PolicyStatement({ + sid: "MailRelaySendsOnlyAsTheRelay", + actions: ["ses:SendEmail"], + resources: [ + `arn:aws:ses:${cfg.email.sesRegion}:${account}:identity/${cfg.mailRelay.domain}`, + `arn:aws:ses:${cfg.email.sesRegion}:${account}:configuration-set/${relayConfigSetName(cfg)}`, + ], + conditions: { StringEquals: { "ses:FromAddress": cfg.mailRelay.from } }, + }); +} + +export interface MailRelayProps { + cfg: ResolvedConfig; + /** Where bounces and complaints go (raw), for the worker. */ + ticketQueue: sqs.IQueue; +} + +export class MailRelay extends Construct { + public readonly topic: sns.Topic; + + constructor(scope: Construct, id: string, props: MailRelayProps) { + super(scope, id); + const cfg = props.cfg; + const relay = cfg.mailRelay!; + const zoneName = cfg.hybrid!.zone; + const zone = cfg.hybrid!.zoneId + ? route53.PublicHostedZone.fromPublicHostedZoneAttributes(this, "Zone", { + zoneName, + hostedZoneId: cfg.hybrid!.zoneId, + }) + : route53.PublicHostedZone.fromLookup(this, "Zone", { domainName: zoneName }); + const mailFrom = `bounce.${relay.domain}`; + + this.topic = new sns.Topic(this, "Events", { + topicName: `${cfg.prefix}-relay-mail-events`, + displayName: "CoderHelm mail relay bounces and complaints", + }); + this.topic.addSubscription(new subs.SqsSubscription(props.ticketQueue, { rawMessageDelivery: true })); + + const configSet = new ses.ConfigurationSet(this, "ConfigSet", { + configurationSetName: relayConfigSetName(cfg), + reputationMetrics: true, + sendingEnabled: true, + suppressionReasons: ses.SuppressionReasons.BOUNCES_AND_COMPLAINTS, + }); + configSet.addEventDestination("BouncesAndComplaints", { + destination: ses.EventDestination.snsTopic(this.topic), + events: [ses.EmailSendingEvent.BOUNCE, ses.EmailSendingEvent.COMPLAINT], + }); + + const identity = new ses.EmailIdentity(this, "Identity", { + identity: ses.Identity.domain(relay.domain), + configurationSet: configSet, + dkimSigning: true, + mailFromDomain: mailFrom, + mailFromBehaviorOnMxFailure: ses.MailFromBehaviorOnMxFailure.REJECT_MESSAGE, + }); + // Easy DKIM: the three CNAMEs SES signs with. + identity.dkimRecords.forEach((r, i) => { + new route53.CnameRecord(this, `Dkim${i + 1}`, { + zone, + recordName: r.name, + domainName: r.value, + ttl: cdk.Duration.hours(1), + }); + }); + // MAIL FROM: bounces come back to SES, and SPF names only SES. + new route53.MxRecord(this, "MailFromMx", { + zone, + recordName: mailFrom, + values: [{ priority: 10, hostName: `feedback-smtp.${cfg.email.sesRegion}.amazonses.com` }], + ttl: cdk.Duration.hours(1), + }); + new route53.TxtRecord(this, "MailFromSpf", { + zone, + recordName: mailFrom, + values: ["v=spf1 include:amazonses.com -all"], + ttl: cdk.Duration.hours(1), + }); + // The sending subdomain itself sends only through SES. + new route53.TxtRecord(this, "Spf", { + zone, + recordName: relay.domain, + values: ["v=spf1 include:amazonses.com -all"], + ttl: cdk.Duration.hours(1), + }); + // DMARC for the subdomain: mail not signed by SES as notify. is + // rejected, whatever the main domain's own policy says. + new route53.TxtRecord(this, "Dmarc", { + zone, + recordName: `_dmarc.${relay.domain}`, + values: ["v=DMARC1; p=reject; sp=reject; adkim=s; aspf=r; pct=100"], + ttl: cdk.Duration.hours(1), + }); + } +} diff --git a/infra/lib/service-env.ts b/infra/lib/service-env.ts index 10f520c57..5f4bcc885 100644 --- a/infra/lib/service-env.ts +++ b/infra/lib/service-env.ts @@ -30,6 +30,7 @@ export function serviceEnvironment(cfg: ResolvedConfig, account: string): Record env.LOG_READER_TEMPLATE_URL = logReaderTemplateUrlFor(cfg); env.RESOURCE_PREFIX = cfg.prefix; if (cfg.admins.length) env.PLATFORM_ADMIN_EMAILS = cfg.admins.join(","); + Object.assign(env, emailEnvironment(cfg)); Object.assign(env, modelProviderEnvironment(cfg)); // Self-hosted installs: which release this is (Settings → System), and // the updater the system routes ask. The hosted deployment has neither. @@ -47,8 +48,7 @@ export function serviceEnvironment(cfg: ResolvedConfig, account: string): Record // The default (https://api.coderhelm.com) is built into the services, so a // plain install carries nothing of the hosted deployment; "off" when the // config turns hybrid off. - if (cfg.layout === "single-origin" && cfg.hybridUrl === null) env.HYBRID_URL = "off"; - else if (cfg.hybridUrl && cfg.hybridUrl !== "https://api.coderhelm.com") env.HYBRID_URL = cfg.hybridUrl; + Object.assign(env, hybridUrlEnvironment(cfg)); if (cfg.hybrid) env.HYBRID_ZONE_NAME = cfg.hybrid.zone; // The services read the secret once at start. The installer sets this to // the secret's version after it stores new keys (the GitHub App), so the @@ -72,6 +72,49 @@ export function logReaderTemplateUrlFor(cfg: ResolvedConfig, version: string | n return DEFAULT_LOG_READER_TEMPLATE_URL; } +/** + * HYBRID_URL for a function that may call the hosted side: "off" when the + * config turned hybrid off, a non-default hosted URL, or nothing (the + * default is built into each caller). + */ +export function hybridUrlEnvironment(cfg: ResolvedConfig): Record { + if (cfg.layout === "single-origin" && cfg.hybridUrl === null) return { HYBRID_URL: "off" }; + if (cfg.hybridUrl && cfg.hybridUrl !== "https://api.coderhelm.com") return { HYBRID_URL: cfg.hybridUrl }; + return {}; +} + +/** + * Which emails a deployment sends and how (services/common/src/mail). The + * hosted deployment (split layout) sends every email as before. A + * self-hosted install sends optional emails only once an install admin turns + * them on; OPTIONAL_EMAIL_DEFAULTS is the config's starting value and + * EMAIL_TRANSPORT_DEFAULT how it sends until an admin chooses. The hosted + * side of hybrid also gets its mail relay's sender. + */ +export function emailEnvironment(cfg: ResolvedConfig): Record { + const env: Record = { + DEPLOYMENT_KIND: cfg.layout === "split" ? "hosted" : "self-hosted", + SUPPORT_INBOX: cfg.email.supportInbox, + }; + if (cfg.layout !== "split") { + env.OPTIONAL_EMAIL_DEFAULTS = cfg.integrations.weeklySummary ? "weekly_summary" : ""; + env.EMAIL_TRANSPORT_DEFAULT = cfg.email.transport; + } + if (cfg.mailRelay) { + env.HYBRID_EMAIL_FROM = cfg.mailRelay.from; + env.HYBRID_EMAIL_CONFIG_SET = `${cfg.prefix}-relay`; + } + return env; +} + +/** + * Whether the Monday summary's schedule exists: always on a self-hosted + * install (the install's own setting decides), else the config's switch. + */ +export function weeklySummaryScheduled(cfg: ResolvedConfig): boolean { + return cfg.layout !== "split" || cfg.integrations.weeklySummary; +} + /** * MODEL_PROVIDER and the Bedrock model mapping (nothing for the default * Anthropic API). On a self-hosted install this is only the first-boot diff --git a/infra/lib/updates-stack.ts b/infra/lib/updates-stack.ts index 6cbe14f8b..650e586df 100644 --- a/infra/lib/updates-stack.ts +++ b/infra/lib/updates-stack.ts @@ -31,6 +31,7 @@ import * as logs from "aws-cdk-lib/aws-logs"; import { Construct } from "constructs"; import { ResolvedConfig } from "./config"; import { repoPath } from "./paths"; +import { hybridUrlEnvironment } from "./service-env"; import { releaseStamp, stampEnvironment } from "./release"; import { CHECK_VERSION, CURL, installCosignCommands, RELEASE_BASE, RELEASE_REPO, VERIFY_SUMS } from "./release-verify"; @@ -307,6 +308,14 @@ export class UpdatesStack extends cdk.Stack { WORKER_FUNCTION_NAME: `${prefix}-worker`, RELEASE_CHECK_PROJECT_NAME: `${prefix}-release-check`, CONFIGURED_MODELS: [...new Set([cfg.models.primary, cfg.models.light])].join(","), + // How update notices are emailed: Settings, Emails, else this. + EMAIL_TRANSPORT_DEFAULT: cfg.email.transport, + // The install's hybrid registration, read only to email through + // CoderHelm's mail relay when an admin chose it. + SECRETS_NAME: cfg.secretName, + // Where the hosted side is: "off" when the config turned hybrid + // off, a non-default URL, or nothing (the default). + ...hybridUrlEnvironment(cfg), ...(cfg.updates.webhookUrl ? { UPDATE_WEBHOOK_URL: cfg.updates.webhookUrl } : {}), ...stampEnvironment(stamp), }, @@ -316,6 +325,11 @@ export class UpdatesStack extends cdk.Stack { actions: ["codebuild:StartBuild"], resources: [this.project.projectArn, this.checkProject.projectArn], })); + this.updaterFunction.addToRolePolicy(new iam.PolicyStatement({ + sid: "ReadHybridRegistrationForMail", + actions: ["secretsmanager:GetSecretValue"], + resources: [`arn:aws:secretsmanager:${this.region}:${this.account}:secret:${cfg.secretName}-??????`], + })); this.updaterFunction.addToRolePolicy(new iam.PolicyStatement({ actions: ["ses:SendEmail"], resources: ["*"], diff --git a/infra/lib/worker-stack.ts b/infra/lib/worker-stack.ts index 1d69af39a..c4d732dfd 100644 --- a/infra/lib/worker-stack.ts +++ b/infra/lib/worker-stack.ts @@ -15,7 +15,8 @@ import { Construct } from "constructs"; import { ResolvedConfig } from "./config"; import { repoPath } from "./paths"; import * as path from "path"; -import { serviceEnvironment, modelPolicyStatements, publicUrlReadStatement } from "./service-env"; +import { relaySendStatement } from "./mail-relay"; +import { serviceEnvironment, modelPolicyStatements, publicUrlReadStatement, weeklySummaryScheduled } from "./service-env"; interface WorkerStackProps extends cdk.StackProps { stage: string; @@ -118,7 +119,9 @@ export class WorkerStack extends cdk.Stack { SES_FROM_ADDRESS: cfg.email.from, SES_TEMPLATE_PREFIX: `${props.cfg.prefix}`, // The Monday weekly summary sends nothing unless this is "true". - WEEKLY_SUMMARY_ENABLED: cfg.integrations.weeklySummary ? "true" : "false", + // On a self-hosted install the install's own setting decides + // (Settings, Emails; off until an admin turns it on). + WEEKLY_SUMMARY_ENABLED: weeklySummaryScheduled(cfg) ? "true" : "false", // While "true", only teams with a rollout list get the summary. WEEKLY_SUMMARY_LISTED_TEAMS_ONLY: cfg.integrations.weeklySummaryListedTeamsOnly ? "true" : "false", CI_FIX_QUEUE_URL: props.ciFixQueue.queueUrl, @@ -134,7 +137,7 @@ export class WorkerStack extends cdk.Stack { ...serviceEnvironment(cfg, this.account), }, }); - for (const st of [...modelPolicyStatements(cfg, this), publicUrlReadStatement(cfg, this)]) { + for (const st of [...modelPolicyStatements(cfg, this), publicUrlReadStatement(cfg, this), relaySendStatement(cfg, this.account)]) { if (st) this.workerFunction.addToRolePolicy(st); } diff --git a/infra/test/launch-stack.test.ts b/infra/test/launch-stack.test.ts index 84e8766bc..9ff0a3bfb 100644 --- a/infra/test/launch-stack.test.ts +++ b/infra/test/launch-stack.test.ts @@ -30,6 +30,8 @@ test("parses, with the parameters the install guide fills in", () => { assert.equal(t.Parameters.ModelProvider.Default, "bedrock", "no API key needed to start"); assert.equal(t.Parameters.Hostname.Default, "", "no DNS work by default"); assert.equal(t.Parameters.EmailFrom.Default, "", "the admin's own address by default: no DNS work"); + assert.equal(t.Parameters.EmailTransport.Default, "ses", "email through CoderHelm only when chosen"); + assert.deepEqual(t.Parameters.EmailTransport.AllowedValues, ["ses", "coderhelm"]); assert.equal(t.Parameters.HostedZone.Default, "", "the zone is found in the account"); assert.match(t.Parameters.Hostname.Description, /any other DNS provider/); assert.equal(t.Parameters.AutoUpdate.Default, "off", "updates wait for an admin by default"); diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index 2ddaf3f95..e538ab241 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -12,7 +12,7 @@ import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; import * as cdk from "aws-cdk-lib"; -import { Template } from "aws-cdk-lib/assertions"; +import { Match, Template } from "aws-cdk-lib/assertions"; import { buildApp } from "../lib/app"; import { CoderhelmConfig, loadConfigFile, resolveConfig, ResolvedConfig } from "../lib/config"; import { API_PATHS, STREAM_PATH, runtimeConfigScript } from "../lib/web-stack"; @@ -199,8 +199,11 @@ test("optional parts can be turned off", () => { assert.equal(t["coderhelm-prod-log-analyzer"], undefined); const env = envOf(t["coderhelm-prod-worker"], "coderhelm-prod-worker"); assert.equal(env.SANDBOX_PROJECT_NAME, undefined); - assert.equal(env.WEEKLY_SUMMARY_ENABLED, "false"); - t["coderhelm-prod-api"].hasResourceProperties("AWS::Events::Rule", { Name: "coderhelm-prod-weekly-summary", State: "DISABLED" }); + // The weekly summary is the install admin's choice at runtime (Settings, + // Emails): the schedule stays, and the config starts it off. + assert.equal(env.WEEKLY_SUMMARY_ENABLED, "true"); + assert.equal(env.OPTIONAL_EMAIL_DEFAULTS, ""); + t["coderhelm-prod-api"].hasResourceProperties("AWS::Events::Rule", { Name: "coderhelm-prod-weekly-summary", State: "ENABLED" }); }); test("the sandbox build role has no S3 access: builds use the URLs the worker signs", () => { @@ -727,3 +730,85 @@ test("the update build may run the installer's model check: ask the worker, read assert.deepEqual(read.Action, "dynamodb:GetItem"); assert.deepEqual(read.Condition, { "ForAllValues:StringEquals": { "dynamodb:LeadingKeys": ["SYSTEM"] } }); }); + +// ── Optional email and CoderHelm's mail relay ────────────────────────────── + +test("self-host: optional email starts off, own SES, and nothing that mails CoderHelm", () => { + const cfg = loadConfigFile(path.join(INFRA, "config", "selfhost.example.json"), {}); + assert.equal(cfg.integrations.weeklySummary, false, "the example config starts it off"); + assert.equal(selfHost().integrations.weeklySummary, false, "and so does a config that says nothing"); + assert.equal(cfg.email.transport, "ses"); + assert.equal(cfg.mailRelay, null); + const t = synth(cfg); + for (const fn of ["coderhelm-prod-worker", "coderhelm-prod-gateway"]) { + const stack = fn.endsWith("worker") ? "coderhelm-prod-worker" : "coderhelm-prod-api"; + const env = envOf(t[stack], fn); + assert.equal(env.DEPLOYMENT_KIND, "self-hosted", fn); + assert.equal(env.OPTIONAL_EMAIL_DEFAULTS, "", fn); + assert.equal(env.EMAIL_TRANSPORT_DEFAULT, "ses", fn); + assert.equal(env.HYBRID_EMAIL_FROM, undefined, fn); + // No CoderHelm address anywhere a service could send to. + for (const [k, v] of Object.entries(env)) { + assert.ok(!/@(?:[a-z0-9-]+\.)*coderhelm\.com/i.test(String(v)), `${fn} ${k}=${v} names a CoderHelm address`); + } + } + // The email templates and every stack: no CoderHelm mailbox in a self-hosted install. + for (const [name, tpl] of Object.entries(t)) { + assert.ok(!/@(?:[a-z0-9-]+\.)*coderhelm\.com/i.test(json(tpl)), `${name} names a CoderHelm address`); + assert.equal(Object.keys(tpl.findResources("AWS::SNS::Topic")).filter((k) => k.includes("MailRelay")).length, 0, name); + } + t["coderhelm-prod-api"].hasResourceProperties("AWS::Events::Rule", { Name: "coderhelm-prod-weekly-summary", State: "ENABLED" }); +}); + +test("self-host: a config that turns the weekly summary on, or chooses CoderHelm's mail, starts the install that way", () => { + const t = synth(selfHost({ integrations: { weeklySummary: true }, email: { from: "coderhelm@example.org", transport: "coderhelm" } })); + const env = envOf(t["coderhelm-prod-worker"], "coderhelm-prod-worker"); + assert.equal(env.OPTIONAL_EMAIL_DEFAULTS, "weekly_summary"); + assert.equal(env.EMAIL_TRANSPORT_DEFAULT, "coderhelm"); + assert.throws(() => selfHost({ email: { from: "a@example.org", transport: "smtp" as never } }), /email.transport/); +}); + +test("hosted: the weekly summary stays on for everyone, and the mail relay sends only as notify.coderhelm.com", () => { + const cfg = loadConfigFile(path.join(INFRA, "config", "hosted.prod.json"), { CDK_DEFAULT_ACCOUNT: "654654210434" }); + assert.equal(cfg.integrations.weeklySummary, true); + assert.deepEqual(cfg.mailRelay, { domain: "notify.coderhelm.com", from: "notifications@notify.coderhelm.com" }); + const t = synth(cfg, zoneContext("654654210434", "us-east-1", "coderhelm.com")); + const api = t["coderhelm-prod-api"]; + const worker = envOf(t["coderhelm-prod-worker"], "coderhelm-prod-worker"); + assert.equal(worker.DEPLOYMENT_KIND, "hosted"); + assert.equal(worker.WEEKLY_SUMMARY_ENABLED, "true"); + assert.equal(worker.OPTIONAL_EMAIL_DEFAULTS, undefined); + api.hasResourceProperties("AWS::Events::Rule", { Name: "coderhelm-prod-weekly-summary", State: "ENABLED" }); + const gw = envOf(api, "coderhelm-prod-gateway"); + assert.equal(gw.HYBRID_EMAIL_FROM, "notifications@notify.coderhelm.com"); + assert.equal(gw.HYBRID_EMAIL_CONFIG_SET, "coderhelm-prod-relay"); + // Its own identity with Easy DKIM and a custom MAIL FROM. + api.hasResourceProperties("AWS::SES::EmailIdentity", { + EmailIdentity: "notify.coderhelm.com", + DkimSigningAttributes: Match.absent(), + MailFromAttributes: { MailFromDomain: "bounce.notify.coderhelm.com", BehaviorOnMxFailure: "REJECT_MESSAGE" }, + }); + // SPF, DMARC reject, MAIL FROM MX, three DKIM CNAMEs. + const recs = Object.values(api.findResources("AWS::Route53::RecordSet")).map((r: any) => r.Properties); + const txt = (name: string) => recs.filter((p) => p.Type === "TXT" && p.Name === name).flatMap((p) => p.ResourceRecords); + assert.ok(txt("_dmarc.notify.coderhelm.com.").some((v: string) => v.includes("p=reject")), "DMARC rejects"); + assert.ok(txt("notify.coderhelm.com.").some((v: string) => v.includes("include:amazonses.com -all")), "SPF"); + assert.ok(txt("bounce.notify.coderhelm.com.").some((v: string) => v.includes("include:amazonses.com -all")), "MAIL FROM SPF"); + assert.ok(recs.some((p) => p.Type === "MX" && p.Name === "bounce.notify.coderhelm.com."), "MAIL FROM MX"); + assert.equal(recs.filter((p) => p.Type === "CNAME" && JSON.stringify(p.Name).includes("DkimDNSTokenName")).length, 3, "Easy DKIM"); + // Bounces and complaints reach the worker through SNS, raw. + api.hasResourceProperties("AWS::SES::ConfigurationSetEventDestination", { + ConfigurationSetName: Match.anyValue(), + EventDestination: Match.objectLike({ MatchingEventTypes: Match.arrayWith(["bounce", "complaint"]) }), + }); + api.hasResourceProperties("AWS::SNS::Subscription", { Protocol: "sqs", RawMessageDelivery: true }); + // Sending as the relay: only its identity and configuration set, only from its address. + for (const [stack, role] of [["coderhelm-prod-api", api], ["coderhelm-prod-worker", t["coderhelm-prod-worker"]]] as const) { + const sts = Object.values(role.findResources("AWS::IAM::Policy")).flatMap((p: any) => p.Properties.PolicyDocument.Statement); + const relay = sts.filter((st: any) => st.Sid === "MailRelaySendsOnlyAsTheRelay"); + assert.equal(relay.length, 1, stack); + assert.deepEqual(relay[0].Condition, { StringEquals: { "ses:FromAddress": "notifications@notify.coderhelm.com" } }); + assert.ok(JSON.stringify(relay[0].Resource).includes("identity/notify.coderhelm.com"), stack); + assert.ok(!JSON.stringify(relay[0].Resource).includes("identity/coderhelm.com"), stack); + } +}); diff --git a/lambda/tests/test_updater.py b/lambda/tests/test_updater.py index 2a97eb46f..52c5a6ed3 100644 --- a/lambda/tests/test_updater.py +++ b/lambda/tests/test_updater.py @@ -114,7 +114,7 @@ def setUp(self): self.store = u.Store(self.db, "t") self.builds, self.notices = [], [] u.start_build = lambda env, version, actor, mode, hid, extra=None: self.builds.append((version, actor, mode, hid)) or f"b-{len(self.builds)}" - u.notify = lambda subject, text, env=None: self.notices.append(subject) or 1 + u.notify = lambda subject, text, env=None, **kw: self.notices.append(subject) or 1 # Releases checked by the build and listing no models: nothing to check. real = u.verified_manifest u.verified_manifest = lambda store, version: (True, None) @@ -191,7 +191,7 @@ def setUp(self): self.store = u.Store(self.db, "t") self.builds = [] u.start_build = lambda env, version, actor, mode, hid, extra=None: self.builds.append((version, mode)) or "b" - u.notify = lambda subject, text, env=None: 1 + u.notify = lambda subject, text, env=None, **kw: 1 self.env = {"CODERHELM_VERSION": "v1.2.0", "APP_URL": "https://helm.example.org", "UPDATE_PROJECT_NAME": "p"} self.fetch = lambda _r: [rel("v1.3.0")] # Signed releases that list no models: the model check has nothing to hold. @@ -298,7 +298,7 @@ def setUp(self): self.builds, self.notices, self.texts = [], [], [] real_build, real_notify = u.start_build, u.notify u.start_build = lambda env, version, actor, mode, hid, extra=None: self.builds.append((version, actor, mode)) or "b-1" - u.notify = lambda subject, text, env=None: self.notices.append(subject) or self.texts.append(text) or 1 + u.notify = lambda subject, text, env=None, **kw: self.notices.append(subject) or self.texts.append(text) or 1 self.addCleanup(setattr, u, "start_build", real_build) self.addCleanup(setattr, u, "notify", real_notify) real_check = u.start_check @@ -593,7 +593,7 @@ def setUp(self): self.builds, self.notices = [], [] self._start, self._notify = u.start_build, u.notify u.start_build = lambda env, version, actor, mode, hid, extra=None: self.builds.append((version, actor, mode, extra)) or "b-1" - u.notify = lambda subject, text, env=None: self.notices.append(subject) or 1 + u.notify = lambda subject, text, env=None, **kw: self.notices.append(subject) or 1 self.acm = FakeAcm() self.r53 = FakeRoute53([]) u._clients.update({"acm@us-east-1": self.acm, "route53": self.r53, "ssm": FakeSsm()}) @@ -725,3 +725,91 @@ def test_removing_a_live_domain_redeploys_and_one_never_attached_is_just_forgott self.h({"action": "finished", "status": "succeeded", "history_id": hid}, env=live) self.assertEqual(self.store.get("DOMAIN"), {}) self.assertEqual(self.notices[-1], "CoderHelm is back on its AWS address") + + +class EmailRouteTest(unittest.TestCase): + """Update notices go out the install's chosen way, never both, never to CoderHelm.""" + + def setUp(self): + self.sent = [] + self.posts = [] + test = self + + class Ses: + def send_email(self, **kw): + test.sent.append(kw) + + class Dyn: + def __init__(self, item=None): + self.item = item + + def get_item(self, **kw): + return {"Item": self.item} if self.item else {} + + class Secrets: + def get_secret_value(self, **kw): + return {"SecretString": json.dumps({"hybrid_install_id": "ins_abcdefghijklmnopqrstuvwx", "hybrid_install_secret": "s3cret"})} + + self.Dyn = Dyn + u._clients.clear() + u._clients["sesv2"] = Ses() + u._clients["secretsmanager"] = Secrets() + self.env = {"ADMIN_EMAILS": "admin@example.org,ops@coderhelm.com", "SES_FROM_ADDRESS": "ch@example.org", + "SETTINGS_TABLE_NAME": "t", "SECRETS_NAME": "x", "APP_URL": "https://d1.cloudfront.net", + "HYBRID_URL": "https://hosted.example.test"} + + class Resp: + def close(self): + pass + + def opener(req, timeout=None): + test.posts.append((req.full_url, json.loads(req.data), dict(req.header_items()))) + return Resp() + + self.opener = opener + + def tearDown(self): + u._clients.clear() + + def test_own_ses_by_default_and_never_a_coderhelm_address(self): + u._clients["dynamodb"] = self.Dyn() + u.notify("s", "t", self.env, what="available", version="v1.2.0", opener=self.opener) + self.assertEqual(len(self.sent), 1) + self.assertEqual(self.sent[0]["Destination"]["ToAddresses"], ["admin@example.org"]) + self.assertEqual(self.posts, [], "nothing goes to CoderHelm unless an admin chose it") + + def test_through_coderhelm_only_when_chosen_templates_only_and_signed(self): + u._clients["dynamodb"] = self.Dyn({"data": {"S": json.dumps({"transport": "coderhelm"})}}) + u.notify("s", "t", self.env, what="succeeded", version="v1.2.0", opener=self.opener) + self.assertEqual(self.sent, [], "never both routes") + urls = [p[0] for p in self.posts] + self.assertEqual(urls, ["https://hosted.example.test/hybrid/email/recipients", "https://hosted.example.test/hybrid/email"]) + body = self.posts[1][1] + self.assertEqual(body["template"], "update_notice") + self.assertEqual(set(body), {"request_id", "to", "template", "params", "contact"}) + self.assertNotIn("subject", body["params"]) + self.assertEqual(body["params"]["link"], "https://d1.cloudfront.net/settings/system/") + self.assertEqual(body["to"], "admin@example.org") + headers = {k.lower(): v for k, v in self.posts[1][2].items()} + self.assertTrue(headers["x-coderhelm-signature"].startswith("v1=")) + + def test_the_signature_matches_the_services(self): + # services/common/src/hybrid/sign.rs, the_signature_matches_the_installer_and_a_fixed_vector + self.assertEqual( + u.sign_request("s3cret", 1_800_000_000, "delete", "/hybrid/installs", b""), + "v1=ae93880dea04941037494d54f0116ec78c7f934c8a4fceed86d64fa41d24a769", + ) + + def test_hybrid_turned_off_sends_nothing_through_coderhelm(self): + u._clients["dynamodb"] = self.Dyn({"data": {"S": json.dumps({"transport": "coderhelm"})}}) + u.notify("s", "t", dict(self.env, HYBRID_URL="off"), opener=self.opener) + self.assertEqual((self.sent, self.posts), ([], []), "never SES instead, never the relay") + + def test_unreadable_settings_send_nothing(self): + class Broken: + def get_item(self, **kw): + raise RuntimeError("down") + + u._clients["dynamodb"] = Broken() + u.notify("s", "t", self.env, opener=self.opener) + self.assertEqual((self.sent, self.posts), ([], [])) diff --git a/lambda/updater/handler.py b/lambda/updater/handler.py index c8120143b..e363a4289 100644 --- a/lambda/updater/handler.py +++ b/lambda/updater/handler.py @@ -370,13 +370,94 @@ def ran_versions(store, state, current): return out -def notify(subject, text, env=None): - """Email every install admin, and post to the updates webhook if set.""" +# Hybrid: the hosted API (services/common/src/hybrid/mod.rs), used only once +# an admin chose to send email through CoderHelm. HYBRID_URL overrides it, +# or is "off" when the config turned hybrid off. +DEFAULT_HOSTED_URL = "https://api.coderhelm.com" +CODERHELM_ADDRESS = re.compile(r"@(?:[a-z0-9-]+\.)*coderhelm\.com$", re.I) +UPDATE_WHAT = ("available", "succeeded", "failed", "rolled_back", "blocked", "domain_live", "domain_failed", "domain_removed") +NOTICE_VERSION_RE = re.compile(r"^[A-Za-z0-9.+-]{1,40}$") + + +def email_transport(env): + """How the install sends: Settings, Emails (services/common/src/mail), else + the config's starting value, else its own SES. None when unreadable.""" + try: + r = client("dynamodb").get_item( + TableName=env["SETTINGS_TABLE_NAME"], + Key={"pk": {"S": "SYSTEM"}, "sk": {"S": "SETTINGS#EMAIL_OPTIONAL"}}, + ConsistentRead=True, + ) + data = (r.get("Item") or {}).get("data", {}).get("S") + if data: + t = json.loads(data).get("transport") + if t in ("ses", "coderhelm"): + return t + except Exception as e: + logger.warning(f"Email settings unreadable: {e}") + return None + t = (env.get("EMAIL_TRANSPORT_DEFAULT") or "ses").strip() + return t if t in ("ses", "coderhelm") else "ses" + + +def sign_request(secret, ts, method, path, body): + """The hybrid request signature (services/common/src/hybrid/sign.rs).""" + import hashlib + import hmac + msg = f"{ts}.{method.upper()}.{path}.{hashlib.sha256(body).hexdigest()}" + return "v1=" + hmac.new(secret.encode(), msg.encode(), hashlib.sha256).hexdigest() + + +def relay_call(env, creds, path, payload, opener=None): + url_base = (env.get("HYBRID_URL") or DEFAULT_HOSTED_URL).strip().rstrip("/") + if not url_base.startswith("https://"): + raise RuntimeError("no hosted address for CoderHelm's mail service") + body = json.dumps(payload).encode() + ts = int(time.time()) + req = urllib.request.Request( + url_base + path, + data=body, + method="POST", + headers={ + "content-type": "application/json", + "user-agent": "coderhelm-selfhost", + "x-coderhelm-install": creds["id"], + "x-coderhelm-timestamp": str(ts), + "x-coderhelm-signature": sign_request(creds["secret"], ts, "POST", path, body), + }, + ) + (opener or urllib.request.urlopen)(req, timeout=10).close() + + +def relay_credentials(env): + try: + raw = client("secretsmanager").get_secret_value(SecretId=env["SECRETS_NAME"])["SecretString"] + s = json.loads(raw) + if s.get("hybrid_install_id") and s.get("hybrid_install_secret"): + return {"id": s["hybrid_install_id"], "secret": s["hybrid_install_secret"]} + except Exception as e: + logger.warning(f"Hybrid registration unreadable: {e}") + return None + + +def update_params(what, version, env): + p = {"what": what if what in UPDATE_WHAT else "available", "link": f"{app_url(env)}/settings/system/"} + if version and NOTICE_VERSION_RE.match(str(version)): + p["version"] = str(version) + return p + + +def notify(subject, text, env=None, what="available", version=None, opener=None): + """Email every install admin by the install's route (its own SES, or + CoderHelm's mail relay when an admin chose it, never both), and post to + the updates webhook if set. A CoderHelm address is never emailed.""" env = os.environ if env is None else env admins = [a.strip() for a in (env.get("ADMIN_EMAILS") or "").split(",") if a.strip()] + admins = [a for a in admins if not CODERHELM_ADDRESS.search(a)] sender = env.get("SES_FROM_ADDRESS") sent = 0 - if admins and sender: + transport = email_transport(env) if admins else None + if admins and transport == "ses" and sender: try: client("sesv2").send_email( FromEmailAddress=sender, @@ -386,6 +467,29 @@ def notify(subject, text, env=None): sent += 1 except Exception as e: logger.warning(f"Update email not sent: {e}") + elif admins and transport == "coderhelm": + hosted = (env.get("HYBRID_URL") or DEFAULT_HOSTED_URL).strip() + creds = relay_credentials(env) if hosted.startswith("https://") else None + if not creds: + logger.warning("Update email not sent: email goes through CoderHelm but this install isn't registered") + else: + try: + relay_call(env, creds, "/hybrid/email/recipients", { + "request_id": uuid.uuid4().hex, + "by": admins[0], + "add": [{"email": a, "kind": "admin"} for a in admins], + }, opener) + for a in admins: + relay_call(env, creds, "/hybrid/email", { + "request_id": uuid.uuid4().hex, + "to": a, + "template": "update_notice", + "params": update_params(what, version, env), + "contact": admins[0], + }, opener) + sent += 1 + except Exception as e: + logger.warning(f"Update email not sent through CoderHelm: {e}") hook = env.get("UPDATE_WEBHOOK_URL") if hook and hook.startswith("https://"): try: @@ -673,7 +777,8 @@ def domain_finished(store, env, now, entry, status): dom = dict(dom, state="failed", reason=entry.get("reason") or "the build failed: see its log") store.put("DOMAIN", dom) subject = "CoderHelm could not change its address" - notify(subject, f"{entry.get('reason') or 'Done.'}\nActor: {entry.get('actor', 'auto')}\n{app_url(env)}/settings/system/#domain", env) + what = "domain_failed" if status != "succeeded" else ("domain_removed" if removing else "domain_live") + notify(subject, f"{entry.get('reason') or 'Done.'}\nActor: {entry.get('actor', 'auto')}\n{app_url(env)}/settings/system/#domain", env, what=what) return {"status": status, "domain": dom.get("state") or "none"} @@ -861,7 +966,7 @@ def blocked_text(record, env): def notify_blocked(store, env, record): if record.get("notified") or not failures(record, required=True): return - notify(f"Update to {record['version']} needs your action", blocked_text(record, env), env) + notify(f"Update to {record['version']} needs your action", blocked_text(record, env), env, what="blocked", version=record.get("version")) record["notified"] = True store.put("MODEL_CHECK", record) @@ -1037,6 +1142,8 @@ def handle(event, env, store, now, fetch=fetch_releases, probe=None): f"CoderHelm {words} {version}", f"{entry.get('reason') or 'Done.'}\nActor: {entry.get('actor', 'auto')}\n{app_url(env)}/settings/system/", env, + what=status, + version=version, ) return {"status": status, "version": version} @@ -1071,6 +1178,8 @@ def handle(event, env, store, now, fetch=fetch_releases, probe=None): f"{'This is a major release. ' if latest.get('breaking') else ''}" f"Release notes and Update now: {app_url(env)}/settings/system/", env, + what="available", + version=d["version"], ) state = store.get("UPDATE_STATE", {}) state["notified_version"] = d["version"] diff --git a/selfhost/launch/bootstrap.mjs b/selfhost/launch/bootstrap.mjs index f9a97fe77..7823b8827 100644 --- a/selfhost/launch/bootstrap.mjs +++ b/selfhost/launch/bootstrap.mjs @@ -29,6 +29,7 @@ // STAGE install name (resources start with coderhelm-) // ADMIN_EMAIL the first admin // EMAIL_FROM sender address; empty means ADMIN_EMAIL +// EMAIL_TRANSPORT ses (default) | coderhelm: CoderHelm's mail service // HOSTNAME_ARG optional: your own domain, e.g. coderhelm.example.com // HOSTED_ZONE optional: its Route 53 zone (empty: found in the account, // or another DNS provider) @@ -155,7 +156,10 @@ export function configFromEnv(env, { account, found = null }) { // certificate is issued (the updater moves it along). domain: plan.mode === "route53" ? { hostname, hostedZone, ...(plan.zoneId ? { hostedZoneId: plan.zoneId } : {}) } : null, models, - email: { from, identity: emailIdentity({ from, hostedZone }) }, + email: env.EMAIL_TRANSPORT === "coderhelm" + // Through CoderHelm: no SES identity to verify; Cognito keeps its own sender. + ? { from, identity: null, transport: "coderhelm" } + : { from, identity: emailIdentity({ from, hostedZone }) }, admins: [admin], telemetry: { enabled: env.TELEMETRY === "on" }, }; diff --git a/selfhost/launch/bootstrap.test.mjs b/selfhost/launch/bootstrap.test.mjs index bdf81e34f..7e0a978e4 100644 --- a/selfhost/launch/bootstrap.test.mjs +++ b/selfhost/launch/bootstrap.test.mjs @@ -41,6 +41,13 @@ test("config: a domain in a hosted zone gets a domain identity", () => { assert.equal(configFromEnv({ ...ENV, REQUIRE_TWO_FACTOR: "off" }, { account: "123456789012" }).signup, undefined); }); +test("config: email through CoderHelm only when chosen, with no SES identity to verify", () => { + assert.equal(configFromEnv(ENV, { account: "123456789012" }).email.transport, undefined); + const cfg = configFromEnv({ ...ENV, EMAIL_TRANSPORT: "coderhelm" }, { account: "123456789012" }); + assert.deepEqual(cfg.email, { from: "ada@example.com", identity: null, transport: "coderhelm" }); + assert.equal(configFromEnv({ ...ENV, EMAIL_TRANSPORT: "smtp" }, { account: "123456789012" }).email.transport, undefined); +}); + test("config: anthropic has no Bedrock prefix; explicit prefixes are kept", () => { assert.deepEqual(configFromEnv({ ...ENV, MODEL_PROVIDER: "anthropic" }, { account: "123456789012" }).models, { provider: "anthropic" }); assert.equal(configFromEnv({ ...ENV, BEDROCK_PREFIX: "" }, { account: "123456789012" }).models.bedrockInferencePrefix, ""); diff --git a/services/Cargo.lock b/services/Cargo.lock index a56681bdb..e6e25dba8 100644 --- a/services/Cargo.lock +++ b/services/Cargo.lock @@ -1455,6 +1455,7 @@ dependencies = [ "aws-sdk-redshiftdata", "aws-sdk-s3", "aws-sdk-scheduler", + "aws-sdk-sesv2", "aws-sdk-sqs", "aws-sdk-ssm", "aws-sdk-sts", diff --git a/services/common/Cargo.toml b/services/common/Cargo.toml index 7bf9ff5cb..b9f69c1b4 100644 --- a/services/common/Cargo.toml +++ b/services/common/Cargo.toml @@ -10,6 +10,8 @@ sha2 = "0.10" hmac = "0.12" # memlock: the shared memory fencing lock (worker runs + gateway deletes) aws-sdk-dynamodb = "1" +# mail: one send layer for SES and the hybrid email relay +aws-sdk-sesv2 = "1" chrono = "0.4" ulid = "1" tracing = "0.1" diff --git a/services/common/contract/reserved_names.json b/services/common/contract/reserved_names.json index 1da19f567..98fb7f3c8 100644 --- a/services/common/contract/reserved_names.json +++ b/services/common/contract/reserved_names.json @@ -1,6 +1,6 @@ { "_comment": "Names under the hybrid parent zone (coderhelm.com) that no install may claim. zone_records: every host CoderHelm itself serves there (the CDK stacks' records, plus the dashboard, docs and marketing site deployed elsewhere); infra/test/hybrid.test.ts fails when a hosted stack adds a record that isn't listed. blocklist: names that would mislead or that infrastructure commonly uses.", - "zone_records": ["api", "app", "auth", "docs", "stream", "www", "fallback"], + "zone_records": ["api", "app", "auth", "docs", "stream", "www", "fallback", "notify"], "blocklist": [ "about", "account", "accounts", "admin", "administrator", "alerts", "apps", "assets", "autodiscover", "beta", "billing", "blog", "careers", "cdn", "chat", "coderhelm", "community", "console", "dashboard", diff --git a/services/common/src/deliveries.rs b/services/common/src/deliveries.rs index 10e0bd51d..c2db3ad83 100644 --- a/services/common/src/deliveries.rs +++ b/services/common/src/deliveries.rs @@ -341,6 +341,23 @@ const REASONS: &[Reason] = &[ Reason { code: "email_sandbox", message: "Amazon SES only sends to confirmed addresses on this account (the SES sandbox).", fix: "Request production access in Amazon SES, or confirm the recipient." }, Reason { code: "email_denied", message: "The service isn't allowed to send from this address.", fix: "Confirm the sender in Amazon SES (Settings, System shows how)." }, Reason { code: "email_failed", message: "Amazon SES refused the email.", fix: "Send a test email from Settings, System for the reason." }, + Reason { code: "coderhelm_address", message: "A self-hosted install never emails CoderHelm's own addresses.", fix: "Nothing to do: the email was meant for someone outside this install." }, + Reason { code: "settings_unreadable", message: "The install's email settings couldn't be read, so nothing was sent.", fix: "Usually temporary. Send a test email from Setup." }, + Reason { code: "email_not_configured", message: "This install has no sender address for Amazon SES.", fix: "Set email.from in the install's config, or choose Through CoderHelm in Settings, Emails." }, + Reason { code: "relay_not_registered", message: "Email is set to go through CoderHelm, but this install isn't registered with CoderHelm.", fix: "Register the install in Settings, System, Hybrid, or switch Settings, Emails back to Amazon SES. Nothing is sent another way meanwhile." }, + 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: "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." }, + Reason { code: "email_paused", message: "CoderHelm paused email for this install after too many bounces or complaints.", fix: "Check recent bounces in Deliveries, fix the addresses, then ask CoderHelm support to resume, or switch to Amazon SES." }, + Reason { code: "install_not_verified", message: "CoderHelm sends an install's email only after it proves its address.", fix: "Finish verifying the install in Settings, System, Hybrid." }, + Reason { code: "link_not_own_host", message: "A link in the email didn't point at this install's own address, so CoderHelm's relay refused it.", fix: "Use the install's CloudFront address or its CoderHelm name. A custom domain isn't known to the relay yet." }, + Reason { code: "param_reserved", message: "Part of the email read as CoderHelm itself (support, security, staff), so the relay refused it.", fix: "Rename what was quoted (a team, a ticket subject) so it reads as your install." }, + Reason { code: "email_bounced", message: "The address doesn't exist or refuses mail.", fix: "Fix the address on the team page; CoderHelm's relay won't send to it again." }, + Reason { code: "email_complained", message: "The recipient marked the email as spam.", fix: "Nothing more is sent to them through CoderHelm." }, Reason { code: "broker_not_linked", message: "That GitHub installation isn't linked to this install.", fix: "Link the installation again in Settings, System, Hybrid." }, Reason { code: "broker_repository_not_allowed", message: "That repository isn't one this install was given.", fix: "Add it on GitHub and in Settings, System, Hybrid." }, Reason { code: "broker_refused", message: "CoderHelm's token broker refused the request.", fix: "Open Settings, System, Hybrid: it shows the link's state and how to fix it." }, diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index a7ac198c9..975066090 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -24,6 +24,9 @@ pub mod dlq; /// Hybrid self-hosting: CoderHelm addresses, the event relay, the token /// broker and the signatures between an install and the hosted side. pub mod hybrid; +/// Which emails an install sends, and how: its own SES or CoderHelm's mail +/// relay (templates only, listed recipients, never CoderHelm's addresses). +pub mod mail; /// Outbound webhooks: the event catalog, endpoints, signing and delivery. pub mod webhooks; diff --git a/services/common/src/mail/mod.rs b/services/common/src/mail/mod.rs new file mode 100644 index 000000000..30400d6ca --- /dev/null +++ b/services/common/src/mail/mod.rs @@ -0,0 +1,971 @@ +//! Every email CoderHelm sends goes through here: which emails an install +//! sends at all, and how each one leaves (the install's own Amazon SES, or +//! CoderHelm's mail relay when a self-hosted admin chose it). +//! +//! - Essential emails (invites, approval requests, alerts an admin needs, +//! test emails, update notices) always send. +//! - Optional emails ([`OPTIONAL`]: the weekly summary, the welcome email) +//! send on the hosted deployment as before. On a self-hosted install each +//! is off until an install admin turns it on (Settings, Emails), stored in +//! [`SETTINGS_PK`]/[`SETTINGS_SK`]; the config's starting value +//! (`OPTIONAL_EMAIL_DEFAULTS`) applies until then. +//! - A self-hosted install sends through CoderHelm only when an admin chose +//! "Through CoderHelm" and the install is registered for hybrid. Nothing +//! falls back to another sender: a relay that can't be reached is a failed +//! send, shown in Deliveries. +//! - A self-hosted install never emails a CoderHelm address +//! ([`relay::is_coderhelm_address`]), by either route. +//! +//! Sign-in codes are not here: Amazon Cognito makes, sends and checks them +//! inside the install (its own sender, or the install's SES), so a code never +//! reaches CoderHelm. + +pub mod relay; +pub mod templates; + +use std::collections::BTreeMap; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use aws_sdk_dynamodb::types::AttributeValue; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +/// Where the install's email settings live on the settings table. +pub const SETTINGS_PK: &str = "SYSTEM"; +pub const SETTINGS_SK: &str = "SETTINGS#EMAIL_OPTIONAL"; + +/// What kind of deployment this is (`DEPLOYMENT_KIND`). Anything but +/// `hosted` counts as self-hosted, so a missing value never turns optional +/// email on. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Deployment { + Hosted, + SelfHosted, +} + +pub fn deployment_from(v: Option<&str>) -> Deployment { + match v.map(str::trim) { + Some("hosted") => Deployment::Hosted, + _ => Deployment::SelfHosted, + } +} + +pub fn deployment() -> Deployment { + deployment_from(std::env::var("DEPLOYMENT_KIND").ok().as_deref()) +} + +/// An email the product works without. +#[derive(Debug, Clone, Copy, Serialize)] +pub struct OptionalEmail { + pub id: &'static str, + pub label: &'static str, + pub description: &'static str, +} + +pub const WEEKLY_SUMMARY: &str = "weekly_summary"; +pub const WELCOME: &str = "welcome"; + +pub const OPTIONAL: &[OptionalEmail] = &[ + OptionalEmail { + id: WEEKLY_SUMMARY, + label: "Weekly summary", + description: "A Monday email to each person with their team's week: merged pull requests, runs, reviews and token use.", + }, + OptionalEmail { + id: WELCOME, + label: "Welcome email", + description: "A short hello with a link to get started, sent once when someone signs up.", + }, +]; + +/// An email the install needs, and why. +#[derive(Debug, Clone, Copy, Serialize)] +pub struct EssentialEmail { + pub id: &'static str, + pub label: &'static str, + pub why: &'static str, +} + +pub const ESSENTIAL: &[EssentialEmail] = &[ + EssentialEmail { id: "sign_in", label: "Sign-up codes and password resets", why: "People can't verify their address or get back into their account without them. Amazon Cognito sends these inside your install." }, + EssentialEmail { id: "team_invite", label: "Team invites", why: "The only way an invited person learns how to join." }, + EssentialEmail { id: "plugin_approval", label: "Plugin approval requests", why: "A named approver must approve a plugin draft before it publishes." }, + EssentialEmail { id: "knowledge_signin", label: "Knowledge source sign-in alerts", why: "Tells admins when a knowledge source stopped syncing and needs signing in again." }, + EssentialEmail { id: "token_warning", label: "Token limit warnings", why: "Tells the team before work stops at the monthly limit, and when it does. Each person can turn these off." }, + EssentialEmail { id: "support_update", label: "Support ticket updates", why: "Replies and status changes on tickets someone filed." }, + EssentialEmail { id: "webhook_disabled", label: "Webhook endpoint turned off", why: "Tells a team's admins when CoderHelm stopped sending to an endpoint that failed for days." }, + EssentialEmail { id: "two_factor_lockout", label: "Two-factor lockout alerts", why: "Tells admins and owners when someone's two-factor sign-in was paused after too many wrong codes." }, + EssentialEmail { id: "update_notice", label: "Update notices", why: "Tells install admins about new releases, finished or failed updates and address changes." }, + EssentialEmail { id: "test_email", label: "Test email", why: "Sent only when an admin presses Send test email in Setup." }, +]; + +/// How a self-hosted install sends. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Transport { + /// The install's own Amazon SES (the default). + #[default] + Ses, + /// CoderHelm's mail relay (hybrid). + Coderhelm, +} + +impl Transport { + pub fn as_str(self) -> &'static str { + match self { + Self::Ses => "ses", + Self::Coderhelm => "coderhelm", + } + } + pub fn parse(s: &str) -> Option { + match s { + "ses" => Some(Self::Ses), + "coderhelm" => Some(Self::Coderhelm), + _ => None, + } + } +} + +/// The install's email settings, as stored. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Settings { + /// Optional email id: on or off. Missing: the config's starting value. + #[serde(default)] + pub optional: BTreeMap, + #[serde(default)] + pub transport: Transport, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub updated_by: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub updated_at: String, +} + +/// The optional emails the config turns on from the start +/// (`OPTIONAL_EMAIL_DEFAULTS`, comma separated). Empty on a self-hosted +/// install unless its config says otherwise. +pub fn config_defaults() -> Vec { + defaults_from(std::env::var("OPTIONAL_EMAIL_DEFAULTS").ok().as_deref()) +} + +/// How the install sends until an admin decides (`EMAIL_TRANSPORT_DEFAULT`, +/// from the config's `email.transport`): its own SES unless set. +pub fn transport_default() -> Transport { + std::env::var("EMAIL_TRANSPORT_DEFAULT") + .ok() + .and_then(|v| Transport::parse(v.trim())) + .unwrap_or_default() +} + +/// The transport in force: the stored choice, else the config's. +pub fn transport_of(settings: Option<&Settings>, default: Transport) -> Transport { + settings.map(|s| s.transport).unwrap_or(default) +} + +pub fn defaults_from(v: Option<&str>) -> Vec { + v.unwrap_or("") + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| OPTIONAL.iter().any(|o| o.id == s)) + .collect() +} + +/// Whether optional email `id` is on. +pub fn optional_on( + dep: Deployment, + settings: Option<&Settings>, + defaults: &[String], + id: &str, +) -> bool { + match dep { + Deployment::Hosted => true, + Deployment::SelfHosted => settings + .and_then(|s| s.optional.get(id).copied()) + .unwrap_or_else(|| defaults.iter().any(|d| d == id)), + } +} + +/// How one email leaves. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Route { + Ses, + Relay, +} + +/// The route for a send, or why there is none. The hosted deployment always +/// uses its SES; a self-hosted install uses the relay only when an admin +/// chose it, and then only that. +pub fn route( + dep: Deployment, + transport: Transport, + registered: bool, +) -> Result { + match (dep, transport) { + (Deployment::Hosted, _) | (Deployment::SelfHosted, Transport::Ses) => Ok(Route::Ses), + (Deployment::SelfHosted, Transport::Coderhelm) if crate::hybrid::turned_off() => { + Err("relay_turned_off") + } + (Deployment::SelfHosted, Transport::Coderhelm) if registered => Ok(Route::Relay), + (Deployment::SelfHosted, Transport::Coderhelm) => Err("relay_not_registered"), + } +} + +pub fn from_item(item: &std::collections::HashMap) -> Option { + let data = item.get("data")?.as_s().ok()?; + serde_json::from_str(data).ok() +} + +static CACHE: Mutex)>> = Mutex::new(None); +const CACHE_FOR: Duration = Duration::from_secs(30); + +/// The stored settings (cached 30 seconds). `Err` when the store can't be +/// read: callers send no optional email and no relayed email then. +pub async fn load( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, +) -> Result, String> { + if let Some((at, s)) = CACHE.lock().ok().and_then(|g| g.clone()) { + if at.elapsed() < CACHE_FOR { + return Ok(s); + } + } + let r = dynamo + .get_item() + .table_name(table) + .key("pk", AttributeValue::S(SETTINGS_PK.into())) + .key("sk", AttributeValue::S(SETTINGS_SK.into())) + .consistent_read(true) + .send() + .await + .map_err(|e| format!("email settings: {e}"))?; + let s = r.item().and_then(from_item); + if let Ok(mut g) = CACHE.lock() { + *g = Some((Instant::now(), s.clone())); + } + Ok(s) +} + +/// Drops the cache (after an admin saves). +pub fn forget() { + if let Ok(mut g) = CACHE.lock() { + *g = None; + } +} + +pub async fn save( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + s: &Settings, +) -> Result<(), String> { + dynamo + .put_item() + .table_name(table) + .item("pk", AttributeValue::S(SETTINGS_PK.into())) + .item("sk", AttributeValue::S(SETTINGS_SK.into())) + .item( + "data", + AttributeValue::S(serde_json::to_string(s).unwrap_or_default()), + ) + .send() + .await + .map_err(|e| format!("email settings: {e}"))?; + forget(); + Ok(()) +} + +/// Whether optional email `id` should go out on this deployment now. +pub async fn optional_allowed(dynamo: &aws_sdk_dynamodb::Client, table: &str, id: &str) -> bool { + let dep = deployment(); + if dep == Deployment::Hosted { + return true; + } + match load(dynamo, table).await { + Ok(s) => optional_on(dep, s.as_ref(), &config_defaults(), id), + Err(e) => { + tracing::warn!(error = %e, email = id, "Email settings unreadable: optional email not sent"); + false + } + } +} + +/// The SES form of an email (how it has always been sent). +#[derive(Debug, Clone)] +pub enum SesBody { + Simple { + subject: String, + text: String, + html: Option, + headers: Vec<(String, String)>, + }, + Template { + name: String, + data: String, + }, +} + +/// One email to send. +#[derive(Debug, Clone)] +pub struct Mail { + /// The Deliveries event (`invite`, `weekly_summary`, ...). + pub kind: String, + pub to: String, + /// The relay form: a template id and its parameters. + pub template: &'static str, + pub params: Map, + /// The SES form. + pub ses: SesBody, +} + +/// Where a mail is sent from, and what with. +pub struct Sender<'a> { + pub ses: &'a aws_sdk_sesv2::Client, + pub http: &'a reqwest::Client, + pub dynamo: &'a aws_sdk_dynamodb::Client, + pub settings_table: &'a str, + pub from: &'a str, +} + +/// A failed send, with the reason code Deliveries explains. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SendError { + pub code: String, + pub message: String, +} + +impl std::fmt::Display for SendError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} ({})", self.message, self.code) + } +} + +impl std::error::Error for SendError {} + +fn err(code: &str, message: impl Into) -> SendError { + SendError { + code: code.into(), + message: message.into(), + } +} + +/// Sends one email by the install's route. Never falls back to the other. +pub async fn send(s: &Sender<'_>, mail: &Mail) -> Result { + let dep = deployment(); + if dep == Deployment::SelfHosted && relay::is_coderhelm_address(&mail.to) { + return Err(err( + "coderhelm_address", + "A self-hosted install never emails CoderHelm's own addresses.", + )); + } + let transport = if dep == Deployment::Hosted { + Transport::Ses + } else { + let stored = load(s.dynamo, s.settings_table) + .await + .map_err(|e| err("settings_unreadable", e))?; + transport_of(stored.as_ref(), transport_default()) + }; + let creds = crate::hybrid::client::credentials(); + match route(dep, transport, creds.is_some()) { + Ok(Route::Ses) => send_ses(s, mail).await.map(|_| Route::Ses), + Ok(Route::Relay) => { + let creds = creds.ok_or_else(|| err("relay_not_registered", "Not registered."))?; + send_relay(s.http, &creds, mail).await.map(|_| Route::Relay) + } + Err(code) => Err(err( + code, + match code { + "relay_turned_off" => "Email is set to go through CoderHelm, but this install's config turned hybrid off.", + _ => "Email is set to go through CoderHelm, but this install isn't registered with CoderHelm. Register it in Settings, System, or switch email back to Amazon SES.", + }, + )), + } +} + +async fn send_ses(s: &Sender<'_>, mail: &Mail) -> Result<(), SendError> { + use aws_sdk_sesv2::types::{ + Body, Content, Destination, EmailContent, Message, MessageHeader, Template, + }; + if s.from.is_empty() { + return Err(err("email_not_configured", "No sender address configured.")); + } + let content = match &mail.ses { + SesBody::Simple { + subject, + text, + html, + headers, + } => { + let c = |v: &str| { + Content::builder() + .data(v) + .charset("UTF-8") + .build() + .map_err(|e| err("email_failed", e.to_string())) + }; + let mut body = Body::builder().text(c(text)?); + if let Some(h) = html { + body = body.html(c(h)?); + } + let mut m = Message::builder().subject(c(subject)?).body(body.build()); + for (name, value) in headers { + m = m.headers( + MessageHeader::builder() + .name(name) + .value(value) + .build() + .map_err(|e| err("email_failed", e.to_string()))?, + ); + } + EmailContent::builder().simple(m.build()).build() + } + SesBody::Template { name, data } => EmailContent::builder() + .template( + Template::builder() + .template_name(name) + .template_data(data) + .build(), + ) + .build(), + }; + s.ses + .send_email() + .from_email_address(s.from) + .destination(Destination::builder().to_addresses(&mail.to).build()) + .content(content) + .send() + .await + .map_err(|e| { + let text = aws_sdk_sesv2::error::DisplayErrorContext(&e).to_string(); + let r = text.to_ascii_lowercase(); + let code = if r.contains("not verified") || r.contains("sandbox") { + "email_sandbox" + } else if r.contains("accessdenied") || r.contains("not authorized") { + "email_denied" + } else { + "email_failed" + }; + err(code, text) + })?; + Ok(()) +} + +/// Sends through CoderHelm's relay. An address the relay doesn't know yet is +/// listed once (as a member, vouched for by an install admin) and the send +/// tried again; invites are listed by the invite handler before sending. +async fn send_relay( + http: &reqwest::Client, + creds: &crate::hybrid::client::Credentials, + mail: &Mail, +) -> Result<(), SendError> { + // Checked here too, so a mistake shows on the install with the reason. + let t = templates::get(mail.template) + .ok_or_else(|| err("unknown_template", "No such email template."))?; + let req = |id: String| relay::SendRequest { + request_id: id, + to: mail.to.clone(), + template: t.id.to_string(), + params: mail.params.clone(), + contact: install_admin(), + }; + let call = |r: relay::SendRequest| async move { + let body = serde_json::to_value(&r).unwrap_or(Value::Null); + crate::hybrid::client::call(http, creds, "POST", relay::PATH_SEND, Some(&body)).await + }; + match call(req(relay::new_request_id())).await { + Ok(_) => Ok(()), + Err(e) if e.code == relay::Refusal::NotListed.code() => { + let by = install_admin().ok_or_else(|| { + err( + "recipient_not_listed", + "The recipient isn't listed with CoderHelm and the install has no admin to vouch for them.", + ) + })?; + // The admin is listed too, so the first listing of an install + // whose config chose the relay works without a dashboard visit. + let mut add = vec![relay::NewRecipient { + email: by.clone(), + kind: relay::RecipientKind::Admin, + }]; + if relay::normalize(&mail.to) != relay::normalize(&by) { + add.push(relay::NewRecipient { + email: mail.to.clone(), + kind: relay::RecipientKind::Member, + }); + } + list(http, creds, &by, &add).await?; + call(req(relay::new_request_id())) + .await + .map(|_| ()) + .map_err(|e| err(&e.code, e.message)) + } + Err(e) => Err(err(&e.code, e.message)), + } +} + +/// The first install admin (`PLATFORM_ADMIN_EMAILS`), who stands behind +/// listings the install makes on its own. +pub fn install_admin() -> Option { + std::env::var("PLATFORM_ADMIN_EMAILS") + .ok()? + .split(',') + .map(str::trim) + .find(|e| relay::valid_address(e)) + .map(str::to_string) +} + +/// Lists addresses with the relay. `by` is the install admin behind it. +pub async fn list( + http: &reqwest::Client, + creds: &crate::hybrid::client::Credentials, + by: &str, + add: &[relay::NewRecipient], +) -> Result<(), SendError> { + for chunk in add.chunks(relay::MAX_PER_REQUEST) { + let body = relay::RecipientsRequest { + request_id: relay::new_request_id(), + by: by.to_string(), + add: chunk.to_vec(), + remove: vec![], + }; + let body = serde_json::to_value(&body).unwrap_or(Value::Null); + crate::hybrid::client::call(http, creds, "POST", relay::PATH_RECIPIENTS, Some(&body)) + .await + .map_err(|e| err(&e.code, e.message))?; + } + 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> { + if deployment() == Deployment::Hosted { + return Ok(()); + } + 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 { + return Ok(()); + }; + if transport != Transport::Coderhelm { + return Ok(()); + } + list( + s.http, + &creds, + by, + &[relay::NewRecipient { + email: to.to_string(), + kind: relay::RecipientKind::Invite, + }], + ) + .await +} + +/// The Deliveries record for one send: domain only, never the address, and +/// never a parameter. +pub fn delivery( + kind: &str, + to: &str, + result: &Result, +) -> crate::deliveries::Delivery { + let r = result.as_ref().map(|_| ()).map_err(|e| e.code.clone()); + let mut d = crate::deliveries::email(kind, to, &r); + if let Err(e) = result { + // `email` guessed from the text; the code is known here. + d.reason = e.code.clone(); + } else if let Ok(Route::Relay) = result { + d.outcome = "Sent through CoderHelm".into(); + } + d +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_missing_or_unknown_deployment_kind_is_self_hosted() { + assert_eq!(deployment_from(Some("hosted")), Deployment::Hosted); + assert_eq!(deployment_from(Some("self-hosted")), Deployment::SelfHosted); + assert_eq!(deployment_from(Some("")), Deployment::SelfHosted); + assert_eq!(deployment_from(None), Deployment::SelfHosted); + } + + #[test] + fn self_hosted_sends_no_optional_email_until_an_admin_opts_in() { + let dep = Deployment::SelfHosted; + for o in OPTIONAL { + assert!(!optional_on(dep, None, &[], o.id), "{}", o.id); + assert!(!optional_on(dep, Some(&Settings::default()), &[], o.id)); + } + let mut s = Settings::default(); + s.optional.insert(WEEKLY_SUMMARY.into(), true); + assert!(optional_on(dep, Some(&s), &[], WEEKLY_SUMMARY)); + assert!(!optional_on(dep, Some(&s), &[], WELCOME)); + // The config's starting value, until the admin decides. + let d = defaults_from(Some("weekly_summary, nonsense")); + assert_eq!(d, vec!["weekly_summary".to_string()]); + assert!(optional_on(dep, None, &d, WEEKLY_SUMMARY)); + s.optional.insert(WEEKLY_SUMMARY.into(), false); + assert!(!optional_on(dep, Some(&s), &d, WEEKLY_SUMMARY)); + } + + #[test] + fn hosted_sends_optional_email_as_before() { + for o in OPTIONAL { + assert!(optional_on(Deployment::Hosted, None, &[], o.id)); + let mut s = Settings::default(); + s.optional.insert(o.id.into(), false); + assert!(optional_on(Deployment::Hosted, Some(&s), &[], o.id)); + } + } + + #[test] + fn essential_and_optional_lists_do_not_overlap() { + for e in ESSENTIAL { + assert!(!OPTIONAL.iter().any(|o| o.id == e.id), "{}", e.id); + } + } + + #[test] + fn the_relay_is_used_only_when_a_self_hosted_admin_chose_it() { + use Deployment::*; + assert_eq!(route(Hosted, Transport::Coderhelm, true), Ok(Route::Ses)); + assert_eq!(route(SelfHosted, Transport::Ses, true), Ok(Route::Ses)); + assert_eq!(route(SelfHosted, Transport::Ses, false), Ok(Route::Ses)); + assert_eq!( + route(SelfHosted, Transport::Coderhelm, true), + Ok(Route::Relay) + ); + // Chosen but not registered: refused, never SES instead. + assert_eq!( + route(SelfHosted, Transport::Coderhelm, false), + Err("relay_not_registered") + ); + assert_eq!(Settings::default().transport, Transport::Ses); + let stored: Settings = serde_json::from_str("{}").unwrap(); + assert_eq!(stored.transport, Transport::Ses); + // The config's choice holds until an admin saves one. + assert_eq!( + transport_of(None, Transport::Coderhelm), + Transport::Coderhelm + ); + assert_eq!(transport_of(None, Transport::Ses), Transport::Ses); + assert_eq!( + transport_of(Some(&Settings::default()), Transport::Coderhelm), + Transport::Ses + ); + } + + #[test] + fn settings_round_trip() { + let mut s = Settings { + transport: Transport::Coderhelm, + ..Default::default() + }; + s.optional.insert(WELCOME.into(), true); + let back: Settings = serde_json::from_str(&serde_json::to_string(&s).unwrap()).unwrap(); + assert_eq!(back, s); + assert_eq!(Transport::parse("coderhelm"), Some(Transport::Coderhelm)); + assert_eq!(Transport::parse("smtp"), None); + } + + #[test] + fn deliveries_keep_the_domain_and_the_reason_only() { + let mail = Mail { + kind: "invite".into(), + to: "dev@example.com".into(), + template: "team_invite", + params: Map::new(), + ses: SesBody::Template { + name: "x".into(), + data: "{}".into(), + }, + }; + let d = delivery( + &mail.kind, + &mail.to, + &Err(err("recipient_not_listed", "no")), + ); + assert_eq!(d.target, "example.com"); + assert_eq!(d.reason, "recipient_not_listed"); + let d = delivery(&mail.kind, &mail.to, &Ok(Route::Relay)); + assert_eq!(d.outcome, "Sent through CoderHelm"); + assert!(!serde_json::to_string(&d).unwrap().contains("dev@")); + } +} + +/// The adversarial pass: a self-hosted install (or someone holding its +/// registration secret) trying to use CoderHelm's mail relay to look like +/// CoderHelm, to reach outside people, or to carry a phishing link. Each +/// attempt is refused by the same code the hosted side runs. +#[cfg(test)] +mod adversarial { + use super::relay::{self, Listing, RecipientKind, Refusal}; + use super::templates::{self, check}; + use crate::hybrid::sign; + use serde_json::{json, Map, Value}; + + const MASTER: &str = "0123456789abcdef0123456789abcdef-master"; + const A: &str = "ins_aaaaaaaaaaaaaaaaaaaaaaaa"; + const B: &str = "ins_bbbbbbbbbbbbbbbbbbbbbbbb"; + const NOW: i64 = 1_800_000_000; + + fn hosts() -> Vec { + vec![ + "d1example.cloudfront.net".into(), + "acme.coderhelm.com".into(), + ] + } + + fn obj(v: Value) -> Map { + v.as_object().unwrap().clone() + } + + #[test] + fn an_email_dressed_as_coderhelm_support_is_refused_or_reads_as_the_install() { + // No subject, no HTML, no sender of its own: unknown parameters. + for field in [ + "subject", + "html", + "from", + "reply_to", + "display_name", + "headers", + ] { + let r = check( + "test_email", + &obj(json!({ field: "CoderHelm Support" })), + &hosts(), + true, + ); + assert_eq!( + r.unwrap_err(), + templates::Refusal::UnknownParam(field.into()), + "{field}" + ); + } + // Wording that reads as CoderHelm staff, in any parameter. + let r = check( + "support_update", + &obj(json!({ + "ticket": "CoderHelm Security: verify your account", + "note": "Hello", + "link": "https://acme.coderhelm.com/support/" + })), + &hosts(), + true, + ); + assert_eq!(r.unwrap_err().code(), "param_reserved"); + // A claimed name like support.coderhelm.com can't become the sender name. + assert_eq!( + relay::display_name(Some("support.coderhelm.com"), "d1example.cloudfront.net"), + "d1example.cloudfront.net via CoderHelm" + ); + assert_eq!( + relay::display_name( + Some("coderhelm-security.coderhelm.com"), + "d1example.cloudfront.net" + ), + "d1example.cloudfront.net via CoderHelm" + ); + // The relay's own notices (pause) can't be asked for by an install. + assert_eq!( + check( + "relay_paused", + &obj(json!({"reason": "bounces"})), + &hosts(), + true + ) + .unwrap_err(), + templates::Refusal::NotForInstalls + ); + // Every subject is fixed, and every email says whose install sent it. + let (t, v) = check("test_email", &Map::new(), &hosts(), true).unwrap(); + let r = templates::render(t, &v, "acme.coderhelm.com", None); + assert_eq!(r.subject, "CoderHelm test email"); + assert!(r + .text + .contains("self-hosted CoderHelm install at acme.coderhelm.com")); + assert!(r.text.contains("never asks for your password")); + } + + #[test] + fn an_outside_address_gets_nothing() { + // Not listed: refused. + assert_eq!( + relay::may_send("ceo@victim.example", &Listing::default(), false), + Err(Refusal::NotListed) + ); + // Listing it needs a listed admin behind the request... + let req = relay::RecipientsRequest { + request_id: relay::new_request_id(), + by: "attacker@acme.test".into(), + add: vec![relay::NewRecipient { + email: "ceo@victim.example".into(), + kind: RecipientKind::Invite, + }], + remove: vec![], + }; + assert_eq!(relay::may_list(&req, None, true, 0), Err(Refusal::NotAdmin)); + assert_eq!( + relay::may_list(&req, Some(RecipientKind::Member), true, 0), + Err(Refusal::NotAdmin) + ); + // ...and even an admin lists only a few new addresses a day. + let mut many = req.clone(); + many.by = "admin@acme.test".into(); + many.add = (0..=relay::NEW_RECIPIENTS_PER_DAY) + .map(|i| relay::NewRecipient { + email: format!("p{i}@victim.example"), + kind: RecipientKind::Invite, + }) + .collect(); + assert_eq!( + relay::may_list(&many, Some(RecipientKind::Admin), true, 0), + Err(Refusal::TooManyNew) + ); + // CoderHelm's own mailboxes are never a recipient. + let listed = Listing { + recipient: Some(RecipientKind::Member), + suppressed: false, + }; + assert_eq!( + relay::may_send("security@coderhelm.com", &listed, false), + Err(Refusal::CoderhelmAddress) + ); + // Header injection into the recipient. + assert_eq!( + relay::may_send("a@acme.test\r\nBcc: ceo@victim.example", &listed, false), + Err(Refusal::BadAddress) + ); + } + + #[test] + fn a_phishing_link_never_reaches_the_email() { + // As a link: only the install's own verified host. + for link in [ + "https://coderhelm-login.example/reset", + "https://acme.coderhelm.com.evil.example/", + "https://acme.coderhelm.com@evil.example/", + "https://app.coderhelm.com/settings", + "http://acme.coderhelm.com/", + ] { + let r = check("welcome", &obj(json!({ "link": link })), &hosts(), true); + assert_eq!(r.unwrap_err().code(), "link_not_own_host", "{link}"); + } + // Hidden in text: removed before anything is written. + let (t, v) = check( + "knowledge_signin", + &obj(json!({ + "source": "Docs", + "problem": "Sign in again at https://evil.example/login or evil.com/login or www.evil.example", + "link": "https://acme.coderhelm.com/settings/knowledge/" + })), + &hosts(), + true, + ) + .unwrap(); + let r = templates::render(t, &v, "acme.coderhelm.com", None); + for bad in ["evil.example", "evil.com"] { + assert!( + !r.text.contains(bad) && !r.html.contains(bad), + "{bad} survived" + ); + } + // The only anchors are the template's buttons, to the install. + let hrefs: Vec<&str> = r + .html + .match_indices("href=\"") + .map(|(i, _)| &r.html[i + 6..]) + .collect(); + assert!( + hrefs + .iter() + .all(|h| h.starts_with("https://acme.coderhelm.com/")), + "{hrefs:?}" + ); + } + + #[test] + fn one_install_cannot_sign_as_another_or_replay() { + let secret_a = sign::install_secret(MASTER, A); + let secret_b = sign::install_secret(MASTER, B); + assert_ne!(secret_a, secret_b); + let body = br#"{"request_id":"01JABCDEFGHJKMNPQRSTVWXYZ0","to":"x@acme.test","template":"test_email","params":{}}"#; + let sig = sign::sign_request(&secret_a, NOW, "POST", relay::PATH_SEND, body); + let ts = NOW.to_string(); + // A's own signature, checked as A: fine. + assert!(sign::verify_request( + &secret_a, + Some(&ts), + Some(&sig), + "POST", + relay::PATH_SEND, + body, + NOW + ) + .is_ok()); + // Sent with B's id: the hosted side derives B's secret, and it fails. + assert!(sign::verify_request( + &secret_b, + Some(&ts), + Some(&sig), + "POST", + relay::PATH_SEND, + body, + NOW + ) + .is_err()); + // Old: outside the five-minute window. + assert!(sign::verify_request( + &secret_a, + Some(&ts), + Some(&sig), + "POST", + relay::PATH_SEND, + body, + NOW + 3600 + ) + .is_err()); + // Changed body (another recipient) under the same signature. + let other = br#"{"request_id":"01JABCDEFGHJKMNPQRSTVWXYZ0","to":"ceo@victim.example","template":"test_email","params":{}}"#; + assert!(sign::verify_request( + &secret_a, + Some(&ts), + Some(&sig), + "POST", + relay::PATH_SEND, + other, + NOW + ) + .is_err()); + // The request id is signed (it's in the body) and remembered for + // longer than the signature window, so a replay inside the window is + // refused by the store (`EMAILREQ#`, attribute_not_exists). + const { assert!(relay::REPLAY_TTL_SECS > 2 * sign::TOLERANCE_SECS) }; + assert!(relay::valid_request_id("01JABCDEFGHJKMNPQRSTVWXYZ0")); + } + + #[test] + fn secret_parameters_never_reach_a_record() { + let t = templates::get("plugin_approval").unwrap(); + let p = obj(json!({ + "plugin": "p", "title": "t", "excerpt": "e", "version": 3, + "approve_link": "https://acme.coderhelm.com/approve?t=TOKEN", + "review_link": "https://acme.coderhelm.com/plugins/draft/?id=1" + })); + assert!(!serde_json::to_string(&templates::without_secrets(t, &p)) + .unwrap() + .contains("TOKEN")); + let d = super::delivery( + "plugin_approval", + "approver@acme.test", + &Ok(super::Route::Relay), + ); + let all = serde_json::to_string(&d).unwrap(); + assert!(!all.contains("TOKEN") && !all.contains("approver@")); + } +} diff --git a/services/common/src/mail/relay.rs b/services/common/src/mail/relay.rs new file mode 100644 index 000000000..74ef759ca --- /dev/null +++ b/services/common/src/mail/relay.rs @@ -0,0 +1,806 @@ +//! CoderHelm's mail relay for hybrid installs: the rules both sides follow. +//! +//! A self-hosted install that chose "Send email through CoderHelm" posts +//! `POST /hybrid/email` signed with its registration secret (the same +//! signature as every hybrid call, `hybrid::sign`). The body names a +//! request id (replay protection), one recipient, a template and its +//! parameters ([`super::templates`]). The hosted side sends only when: +//! +//! - the install is registered, verified and not revoked; +//! - the request id is new (kept for [`REPLAY_TTL_SECS`]); +//! - the recipient is on the install's list (members, admins and pending +//! invites the install registered, [`Recipients`]) and not suppressed; +//! - the install is within its per-minute rate and daily quota, and email +//! isn't paused for it (bounces or complaints, [`should_pause`]). +//! +//! The hosted side keeps a salted hash of each listed address, never the +//! address, except admins' addresses sealed with KMS so the relay can tell +//! them when it pauses. After sending it keeps delivery metadata only +//! (template id, a redacted address, status) for [`DELIVERY_TTL_SECS`]. + +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use sha2::{Digest, Sha256}; + +/// Sends per install per minute. +pub const PER_MINUTE: u64 = 30; +/// Sends per install per UTC day. +pub const PER_DAY: u64 = 500; +/// New addresses an install may list per UTC day. +pub const NEW_RECIPIENTS_PER_DAY: u64 = 50; +/// The first listing (turning the relay on) may bring the install's +/// current people at once, up to this many. +pub const BOOTSTRAP_RECIPIENTS: usize = 200; +/// Most addresses one request may list. +pub const MAX_PER_REQUEST: usize = 200; +/// How long a request id is remembered. +pub const REPLAY_TTL_SECS: i64 = 2 * crate::hybrid::sign::TOLERANCE_SECS + 60; +/// How long a relayed email's delivery record is kept. +pub const DELIVERY_TTL_SECS: i64 = 3 * 86_400; +/// The window bounce and complaint rates are measured over (days). +pub const RATE_WINDOW_DAYS: i64 = 7; + +pub const PATH_SEND: &str = "/hybrid/email"; +pub const PATH_RECIPIENTS: &str = "/hybrid/email/recipients"; +pub const PATH_STATUS: &str = "/hybrid/email/status"; + +/// The settings-table sort keys under `HYBRID#`. +pub fn recipient_sk(hash: &str) -> String { + format!("EMAILTO#{hash}") +} +pub fn suppressed_sk(hash: &str) -> String { + format!("EMAILSUPPRESS#{hash}") +} +pub fn request_sk(id: &str) -> String { + format!("EMAILREQ#{id}") +} +pub fn day_sk(day: &str) -> String { + format!("EMAILDAY#{day}") +} +pub fn minute_sk(minute: &str) -> String { + format!("EMAILMIN#{minute}") +} +pub const PAUSE_SK: &str = "EMAILPAUSE"; + +pub fn normalize(email: &str) -> String { + email.trim().to_ascii_lowercase() +} + +/// A salted hash of an address, per install: the same address on two +/// installs gives two unrelated hashes. +pub fn recipient_hash(install_id: &str, email: &str) -> String { + let mut h = Sha256::new(); + h.update(b"coderhelm/email-relay/v1\n"); + h.update(install_id.as_bytes()); + h.update(b"\n"); + h.update(normalize(email).as_bytes()); + hex::encode(h.finalize()) +} + +/// `a***@example.com`: what a delivery record keeps. +pub fn redact(email: &str) -> String { + let e = normalize(email); + match e.split_once('@') { + Some((local, domain)) => { + let first: String = local.chars().take(1).collect(); + format!("{first}***@{domain}") + } + None => "***".to_string(), + } +} + +/// A plausible single address (no lists, no display names, no header tricks). +pub fn valid_address(email: &str) -> bool { + let e = email.trim(); + if e.len() > 254 || e.is_empty() { + return false; + } + if e.chars().any(|c| { + c.is_whitespace() + || c.is_control() + || matches!( + c, + ',' | ';' | '<' | '>' | '"' | '(' | ')' | '[' | ']' | '\\' + ) + }) { + return false; + } + let Some((local, domain)) = e.split_once('@') else { + return false; + }; + !local.is_empty() + && !domain.contains('@') + && domain.contains('.') + && !domain.starts_with('.') + && !domain.ends_with('.') + && domain.is_ascii() +} + +/// Whether an address is CoderHelm's own (`coderhelm.com` or below). A +/// self-hosted install never emails these, by any route. +pub fn is_coderhelm_address(email: &str) -> bool { + let e = normalize(email); + let Some((_, domain)) = e.rsplit_once('@') else { + return false; + }; + let domain = domain.trim_end_matches('.'); + domain == "coderhelm.com" || domain.ends_with(".coderhelm.com") +} + +/// What a listed address is to the install. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum RecipientKind { + Admin, + Member, + Invite, +} + +impl RecipientKind { + pub fn as_str(self) -> &'static str { + match self { + Self::Admin => "admin", + Self::Member => "member", + Self::Invite => "invite", + } + } + pub fn parse(s: &str) -> Option { + match s { + "admin" => Some(Self::Admin), + "member" => Some(Self::Member), + "invite" => Some(Self::Invite), + _ => None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct NewRecipient { + pub email: String, + pub kind: RecipientKind, +} + +/// `POST /hybrid/email/recipients`: list addresses. `by` is the install +/// admin who stands behind the request (an invite's sender, or the admin +/// who turned the relay on). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RecipientsRequest { + pub request_id: String, + pub by: String, + #[serde(default)] + pub add: Vec, + #[serde(default)] + pub remove: Vec, +} + +/// `POST /hybrid/email`: one email. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SendRequest { + pub request_id: String, + pub to: String, + pub template: String, + #[serde(default)] + pub params: Map, + /// The install admin named in the footer. The relay names them only + /// when they are a listed admin. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub contact: Option, +} + +/// A request id: 16 to 64 letters, digits, `-` or `_`. +pub fn valid_request_id(id: &str) -> bool { + (16..=64).contains(&id.len()) + && id + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') +} + +pub fn new_request_id() -> String { + ulid::Ulid::new().to_string() +} + +/// Why the relay refused, as the install's Deliveries page explains it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refusal { + BadRequest, + Replayed, + NotVerified, + BadAddress, + CoderhelmAddress, + NotListed, + Suppressed, + NotAdmin, + TooManyNew, + RateLimited, + QuotaReached, + Paused, +} + +impl Refusal { + pub fn code(self) -> &'static str { + match self { + Self::BadRequest => "bad_request", + Self::Replayed => "request_replayed", + Self::NotVerified => "install_not_verified", + Self::BadAddress => "bad_address", + Self::CoderhelmAddress => "coderhelm_address", + Self::NotListed => "recipient_not_listed", + Self::Suppressed => "recipient_suppressed", + Self::NotAdmin => "inviter_not_admin", + Self::TooManyNew => "too_many_new_recipients", + Self::RateLimited => "email_rate_limited", + Self::QuotaReached => "email_quota_reached", + Self::Paused => "email_paused", + } + } + + pub fn message(self) -> &'static str { + match self { + Self::BadRequest => "The email request isn't in the expected shape.", + Self::Replayed => "This request id was already used.", + Self::NotVerified => "The install must finish verifying its address before CoderHelm sends its email.", + Self::BadAddress => "That isn't a single email address.", + Self::CoderhelmAddress => "CoderHelm's mail service doesn't send to CoderHelm's own addresses.", + Self::NotListed => "The recipient isn't one of the install's people or pending invites.", + Self::Suppressed => "This address bounced or marked CoderHelm email as spam, so nothing more is sent to it.", + Self::NotAdmin => "Only an install admin can add people to the email list.", + Self::TooManyNew => "The install added too many new addresses today.", + Self::RateLimited => "Too many emails this minute.", + Self::QuotaReached => "The install reached today's email quota.", + Self::Paused => "Email through CoderHelm is paused for this install after bounces or complaints.", + } + } + + pub fn status(self) -> u16 { + match self { + Self::BadRequest | Self::BadAddress => 400, + Self::Replayed => 409, + Self::RateLimited | Self::QuotaReached | Self::TooManyNew => 429, + _ => 403, + } + } +} + +/// What the hosted side knows about the install's list, for one decision. +#[derive(Debug, Clone, Default)] +pub struct Listing { + /// The hash's kind, when the address is listed. + pub recipient: Option, + pub suppressed: bool, +} + +/// May this one email go out? Pure: the caller loaded what it needs. +pub fn may_send(to: &str, listing: &Listing, paused: bool) -> Result<(), Refusal> { + if !valid_address(to) { + return Err(Refusal::BadAddress); + } + if is_coderhelm_address(to) { + return Err(Refusal::CoderhelmAddress); + } + if paused { + return Err(Refusal::Paused); + } + if listing.recipient.is_none() { + return Err(Refusal::NotListed); + } + if listing.suppressed { + return Err(Refusal::Suppressed); + } + Ok(()) +} + +/// May this listing request change the list? `by_kind` is what `by` is on +/// the list now; `admins_listed` whether the list has any admin yet. +/// `new_today` is how many addresses were added today before this request. +pub fn may_list( + req: &RecipientsRequest, + by_kind: Option, + admins_listed: bool, + new_today: u64, +) -> Result<(), Refusal> { + if req.add.len() + req.remove.len() > MAX_PER_REQUEST || !valid_address(&req.by) { + return Err(Refusal::BadRequest); + } + for r in &req.add { + if !valid_address(&r.email) { + return Err(Refusal::BadAddress); + } + if is_coderhelm_address(&r.email) { + return Err(Refusal::CoderhelmAddress); + } + } + let by_is_admin = by_kind == Some(RecipientKind::Admin); + // The first listing: the admin who turns the relay on lists themself. + let bootstrap = !admins_listed + && req + .add + .iter() + .any(|r| r.kind == RecipientKind::Admin && normalize(&r.email) == normalize(&req.by)); + if !by_is_admin && !bootstrap { + return Err(Refusal::NotAdmin); + } + let limit = if bootstrap { + BOOTSTRAP_RECIPIENTS as u64 + } else { + NEW_RECIPIENTS_PER_DAY + }; + if new_today + req.add.len() as u64 > limit { + return Err(Refusal::TooManyNew); + } + Ok(()) +} + +/// The day's send counters for one install. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Counts { + pub sent: u64, + pub bounced: u64, + pub complained: u64, +} + +/// Whether bounces or complaints over the window call for a pause: more +/// than 5% hard bounces, or more than 0.5% complaints (and at least two), +/// once there are at least 20 sends to judge by. Amazon SES reviews an +/// account at 5% and 0.1%; pausing one install early keeps the shared +/// sender healthy for everyone. +pub fn should_pause(window: Counts) -> Option<&'static str> { + if window.complained >= 2 && window.complained * 200 > window.sent { + return Some("complaints"); + } + if window.sent >= 20 && window.bounced * 20 > window.sent { + return Some("bounces"); + } + if window.complained >= 5 { + return Some("complaints"); + } + None +} + +/// The From line: the install's verified address and "via CoderHelm", +/// never words the install chose. A claimed name that reads as CoderHelm +/// staff falls back to the CloudFront address. +pub fn display_name(name_host: Option<&str>, cloudfront: &str) -> String { + let clean = |h: &str| -> String { + h.chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '.' || *c == '-') + .take(80) + .collect::() + .to_ascii_lowercase() + }; + let name_ok = |h: &str| { + let first = h.split('.').next().unwrap_or(""); + // The same rule names follow (`names::looks_like_coderhelm`), and + // stricter: any staff word anywhere, both readings of `1`. + !first.is_empty() + && !crate::hybrid::names::looks_like_coderhelm(first) + && unconfuse(first).iter().all(|plain| { + !STAFF_WORDS + .iter() + .any(|w| plain.contains(w) || plain.replace('-', "").contains(w)) + && !super::templates::uses_reserved_wording(&plain.replace('-', " ")) + }) + }; + let host = match name_host.map(clean) { + Some(h) if name_ok(&h) => h, + _ => clean(cloudfront), + }; + format!("{host} via CoderHelm") +} + +/// A name with look-alike characters read as letters (`c0derhe1m`, +/// `5upp0rt`), so a staff word can't hide behind digits. `1`, `!` and `|` +/// read as either `l` or `i`, so both readings come back. +pub fn unconfuse(s: &str) -> Vec { + let read = |one: char| { + s.chars() + .map(|c| match c.to_ascii_lowercase() { + '0' => 'o', + '1' | '!' | '|' => one, + '3' => 'e', + '4' | '@' => 'a', + '5' | '$' => 's', + '7' => 't', + '8' => 'b', + '9' => 'g', + c => c, + }) + .collect::() + // "rn" reads as "m" and "vv" as "w" in many fonts. + .replace("rn", "m") + .replace("vv", "w") + }; + vec![read('l'), read('i')] +} + +/// Words a sender name may not carry: they would read as CoderHelm itself. +const STAFF_WORDS: &[&str] = &[ + "app", + "api", + "auth", + "mail", + "payment", + "invoice", + "status", + "support", + "security", + "secure", + "billing", + "admin", + "help", + "official", + "staff", + "team", + "verify", + "account", + "login", + "signin", + "password", + "noreply", + "no-reply", + "coderhelm", + "trust", + "abuse", + "postmaster", + "notify", + "notifications", + "service", +]; + +/// `"name"
` with the name quoted safely. +pub fn from_header(display: &str, address: &str) -> String { + let d: String = display + .chars() + .filter(|c| !matches!(c, '"' | '\\' | '\r' | '\n' | '<' | '>')) + .collect(); + format!("\"{d}\" <{address}>") +} + +/// A bounce or complaint, read from the SES event the topic delivers. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MailEvent { + pub install_id: String, + pub kind: EventKind, + pub recipients: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EventKind { + /// A permanent bounce: the address doesn't exist or refuses mail. + Bounce, + Complaint, +} + +/// The KMS encryption context an admin's sealed address is bound to: one +/// install, this purpose only. +pub fn admin_context(install: &str) -> std::collections::HashMap { + std::collections::HashMap::from([ + ("install".to_string(), install.to_string()), + ("purpose".to_string(), "email-relay-admin".to_string()), + ]) +} + +/// The message tag that names the install on every relayed email. +pub const INSTALL_TAG: &str = "install"; +pub const TEMPLATE_TAG: &str = "template"; + +/// Reads an SES event (raw SNS delivery to the queue). `None` for anything +/// else, for transient bounces, and for mail without an install tag. +pub fn parse_event(v: &Value) -> Option { + let kind = v + .get("eventType") + .or_else(|| v.get("notificationType"))? + .as_str()?; + let install_id = v + .pointer("/mail/tags") + .and_then(|t| t.get(INSTALL_TAG)) + .and_then(|l| l.as_array()) + .and_then(|l| l.first()) + .and_then(|x| x.as_str()) + .filter(|id| crate::hybrid::sign::is_install_id(id))? + .to_string(); + let (kind, list) = match kind { + "Bounce" => { + if v.pointer("/bounce/bounceType").and_then(Value::as_str) != Some("Permanent") { + return None; + } + (EventKind::Bounce, v.pointer("/bounce/bouncedRecipients")?) + } + "Complaint" => ( + EventKind::Complaint, + v.pointer("/complaint/complainedRecipients")?, + ), + _ => return None, + }; + let recipients = list + .as_array()? + .iter() + .filter_map(|r| r.get("emailAddress").and_then(Value::as_str)) + .map(normalize) + .collect::>(); + if recipients.is_empty() { + return None; + } + Some(MailEvent { + install_id, + kind, + recipients, + }) +} + +/// Whether a queued message is an SES event (and not worker work). +pub fn is_ses_event(v: &Value) -> bool { + v.get("type").is_none() + && v.get("mail").is_some() + && (v.get("eventType").is_some() || v.get("notificationType").is_some()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn req(by: &str, add: &[(&str, RecipientKind)]) -> RecipientsRequest { + RecipientsRequest { + request_id: new_request_id(), + by: by.into(), + add: add + .iter() + .map(|(e, k)| NewRecipient { + email: (*e).into(), + kind: *k, + }) + .collect(), + remove: vec![], + } + } + + #[test] + fn hashes_are_per_install_and_ignore_case() { + let a = recipient_hash("ins_a", "Dev@Example.com"); + assert_eq!(a, recipient_hash("ins_a", " dev@example.com ")); + assert_ne!(a, recipient_hash("ins_b", "dev@example.com")); + assert!(!a.contains("example")); + } + + #[test] + fn only_listed_unsuppressed_outside_addresses_get_email() { + let listed = Listing { + recipient: Some(RecipientKind::Member), + suppressed: false, + }; + assert_eq!(may_send("dev@example.com", &listed, false), Ok(())); + assert_eq!( + may_send("stranger@example.org", &Listing::default(), false), + Err(Refusal::NotListed) + ); + assert_eq!( + may_send("support@coderhelm.com", &listed, false), + Err(Refusal::CoderhelmAddress) + ); + assert_eq!( + may_send("x@mail.coderhelm.com", &listed, false), + Err(Refusal::CoderhelmAddress) + ); + assert_eq!( + may_send( + "dev@example.com", + &Listing { + suppressed: true, + ..listed.clone() + }, + false + ), + Err(Refusal::Suppressed) + ); + assert_eq!( + may_send("dev@example.com", &listed, true), + Err(Refusal::Paused) + ); + for bad in [ + "a@b.com, c@d.com", + "\"x\" ", + "a@b.com\r\nBcc: c@d.com", + "nope", + ] { + assert_eq!( + may_send(bad, &listed, false), + Err(Refusal::BadAddress), + "{bad}" + ); + } + } + + #[test] + fn only_a_listed_admin_adds_people_after_the_first_listing() { + use RecipientKind::*; + // The first listing: the admin lists themself and the install's people. + let first = req( + "admin@acme.test", + &[("admin@acme.test", Admin), ("dev@acme.test", Member)], + ); + assert_eq!(may_list(&first, None, false, 0), Ok(())); + // Not a bootstrap once an admin is listed: `by` must be that admin. + assert_eq!(may_list(&first, None, true, 0), Err(Refusal::NotAdmin)); + let invite = req("dev@acme.test", &[("new@acme.test", Invite)]); + assert_eq!( + may_list(&invite, Some(Member), true, 0), + Err(Refusal::NotAdmin) + ); + assert_eq!(may_list(&invite, None, true, 0), Err(Refusal::NotAdmin)); + let invite = req("admin@acme.test", &[("new@acme.test", Invite)]); + assert_eq!(may_list(&invite, Some(Admin), true, 0), Ok(())); + // A bootstrap can't name someone else as the admin behind it. + let sneaky = req("admin@acme.test", &[("other@acme.test", Admin)]); + assert_eq!(may_list(&sneaky, None, false, 0), Err(Refusal::NotAdmin)); + // Never CoderHelm's own addresses. + let ch = req("admin@acme.test", &[("security@coderhelm.com", Invite)]); + assert_eq!( + may_list(&ch, Some(Admin), true, 0), + Err(Refusal::CoderhelmAddress) + ); + } + + #[test] + fn new_addresses_per_day_are_limited() { + use RecipientKind::*; + let one = req("admin@acme.test", &[("n@acme.test", Invite)]); + assert_eq!( + may_list(&one, Some(Admin), true, NEW_RECIPIENTS_PER_DAY - 1), + Ok(()) + ); + assert_eq!( + may_list(&one, Some(Admin), true, NEW_RECIPIENTS_PER_DAY), + Err(Refusal::TooManyNew) + ); + let many: Vec<(String, RecipientKind)> = (0..BOOTSTRAP_RECIPIENTS) + .map(|i| (format!("p{i}@acme.test"), Member)) + .collect(); + let mut boot = req("admin@acme.test", &[("admin@acme.test", Admin)]); + boot.add.extend(many.iter().map(|(e, k)| NewRecipient { + email: e.clone(), + kind: *k, + })); + assert_eq!(may_list(&boot, None, false, 0), Err(Refusal::BadRequest)); + boot.add.truncate(BOOTSTRAP_RECIPIENTS); + assert_eq!(may_list(&boot, None, false, 0), Ok(())); + } + + #[test] + fn pauses_on_bounce_or_complaint_rates() { + assert_eq!( + should_pause(Counts { + sent: 100, + bounced: 5, + complained: 0 + }), + None + ); + assert_eq!( + should_pause(Counts { + sent: 100, + bounced: 6, + complained: 0 + }), + Some("bounces") + ); + assert_eq!( + should_pause(Counts { + sent: 10, + bounced: 3, + complained: 0 + }), + None + ); + assert_eq!( + should_pause(Counts { + sent: 100, + bounced: 0, + complained: 2 + }), + Some("complaints") + ); + assert_eq!( + should_pause(Counts { + sent: 1000, + bounced: 0, + complained: 2 + }), + None + ); + assert_eq!( + should_pause(Counts { + sent: 5000, + bounced: 0, + complained: 5 + }), + Some("complaints") + ); + } + + #[test] + fn the_sender_name_is_the_verified_address_never_staff_wording() { + assert_eq!( + display_name(Some("acme.coderhelm.com"), "d1.cloudfront.net"), + "acme.coderhelm.com via CoderHelm" + ); + for bad in [ + "support.coderhelm.com", + "coderhelm-security.coderhelm.com", + "billing-team.coderhelm.com", + "noreply.coderhelm.com", + "acme-help.coderhelm.com", + "c0derhe1m.coderhelm.com", + "5upp0rt.coderhelm.com", + "c0der-he1m-team.coderhelm.com", + "app.coderhelm.com", + "api-acme.coderhelm.com", + "acme-login.coderhelm.com", + "acme-b1lling.coderhelm.com", + "coderhelrn.coderhelm.com", + ] { + assert_eq!( + display_name(Some(bad), "d1.cloudfront.net"), + "d1.cloudfront.net via CoderHelm", + "{bad}" + ); + } + assert_eq!( + display_name(None, "d1.cloudfront.net"), + "d1.cloudfront.net via CoderHelm" + ); + // Nothing outside letters, digits, dots and dashes survives. + assert_eq!(display_name(Some("a\"\r\nc"), "x"), "abc via CoderHelm"); + assert_eq!( + from_header("a\"b", "notifications@notify.coderhelm.com"), + "\"ab\" " + ); + } + + #[test] + fn request_ids_are_checked() { + assert!(valid_request_id(&new_request_id())); + assert!(!valid_request_id("short")); + assert!(!valid_request_id(&"a".repeat(65))); + assert!(!valid_request_id("01HXXXXXXXXXXXXXXXXXXXXXX/../")); + } + + #[test] + fn redacted_addresses_keep_only_the_first_letter_and_domain() { + assert_eq!(redact("Dev@Example.com"), "d***@example.com"); + assert_eq!(redact("nope"), "***"); + } + + #[test] + fn reads_permanent_bounces_and_complaints_with_the_install_tag() { + let id = "ins_abcdefghijklmnopqrstuvwx"; + let bounce = json!({ + "eventType": "Bounce", + "mail": {"tags": {"install": [id], "template": ["welcome"]}}, + "bounce": {"bounceType": "Permanent", "bouncedRecipients": [{"emailAddress": "Gone@Example.com"}]} + }); + assert!(is_ses_event(&bounce)); + let e = parse_event(&bounce).unwrap(); + assert_eq!(e.install_id, id); + assert_eq!(e.kind, EventKind::Bounce); + assert_eq!(e.recipients, vec!["gone@example.com"]); + let transient = json!({ + "eventType": "Bounce", + "mail": {"tags": {"install": [id]}}, + "bounce": {"bounceType": "Transient", "bouncedRecipients": [{"emailAddress": "a@b.com"}]} + }); + assert!(parse_event(&transient).is_none()); + let complaint = json!({ + "eventType": "Complaint", + "mail": {"tags": {"install": [id]}}, + "complaint": {"complainedRecipients": [{"emailAddress": "a@b.com"}]} + }); + assert_eq!(parse_event(&complaint).unwrap().kind, EventKind::Complaint); + let untagged = json!({ + "eventType": "Complaint", + "mail": {"tags": {}}, + "complaint": {"complainedRecipients": [{"emailAddress": "a@b.com"}]} + }); + assert!(parse_event(&untagged).is_none()); + assert!(!is_ses_event(&json!({"type": "ticket", "mail": {}}))); + } +} diff --git a/services/common/src/mail/templates.rs b/services/common/src/mail/templates.rs new file mode 100644 index 000000000..66a2fb654 --- /dev/null +++ b/services/common/src/mail/templates.rs @@ -0,0 +1,1018 @@ +//! The emails CoderHelm's mail relay may carry, and how it writes them. +//! +//! A self-hosted install that sends its email through CoderHelm names a +//! template and fills in its parameters; it never sends a subject, HTML or +//! free text of its own. Every subject is fixed here. Every parameter has a +//! type and a length limit, is plain text, and is escaped when written into +//! the email. Text parameters lose anything that looks like a link or an +//! address, and a link parameter must point at the install's own verified +//! address. Parameters marked `secret` (signed approval and unsubscribe +//! links) are never logged or stored. +//! +//! The same definitions check a request on the install (before it is sent) +//! and on the hosted side (before anything is written), so the two can't +//! drift. + +use serde_json::{Map, Value}; +use std::collections::BTreeMap; + +/// What a parameter may hold. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + /// One line of plain text, at most this many characters. + Line(usize), + /// Plain text that may span lines, at most this many characters. + Text(usize), + /// A whole number. + Number, + /// A release name such as `v1.4.0` or `1.4.0-rc.1`. + Version, + /// One of these words. + OneOf(&'static [&'static str]), + /// An `https://` link to the install's own verified address. + Link, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Param { + pub name: &'static str, + pub kind: Kind, + /// Kept out of every log, record and preview (signed links). + pub secret: bool, + pub required: bool, +} + +const fn p(name: &'static str, kind: Kind) -> Param { + Param { + name, + kind, + secret: false, + required: true, + } +} + +const fn secret(name: &'static str, kind: Kind) -> Param { + Param { + name, + kind, + secret: true, + required: true, + } +} + +const fn optional(name: &'static str, kind: Kind) -> Param { + Param { + name, + kind, + secret: false, + required: false, + } +} + +/// One piece of an email body. +#[derive(Debug, Clone, Copy)] +pub enum Part { + /// A paragraph; `{name}` is replaced by that parameter, escaped. + Para(&'static str), + /// A parameter's text set apart as a quote. + Quote(&'static str), + /// A button: label and the link parameter it opens. + Button(&'static str, &'static str), +} + +#[derive(Debug, Clone, Copy)] +pub struct Template { + pub id: &'static str, + /// The whole subject. Never filled from a parameter. + pub subject: &'static str, + pub params: &'static [Param], + pub body: &'static [Part], + /// Whether an install may ask for it (false: the relay's own notices). + pub install_may_send: bool, +} + +pub const UPDATE_WHAT: &[&str] = &[ + "available", + "succeeded", + "failed", + "rolled_back", + "blocked", + "domain_live", + "domain_failed", + "domain_removed", +]; + +pub const TEMPLATES: &[Template] = &[ + Template { + id: "test_email", + subject: "CoderHelm test email", + params: &[], + body: &[Part::Para( + "Email from your CoderHelm install works. Run results, invites and update notices will arrive like this one.", + )], + install_may_send: true, + }, + Template { + id: "team_invite", + subject: "You're invited to a CoderHelm workspace", + params: &[ + p("team", Kind::Line(80)), + p("inviter", Kind::Line(80)), + p("role", Kind::OneOf(&["viewer", "member", "billing", "admin", "owner"])), + p("link", Kind::Link), + ], + body: &[ + Part::Para("{inviter} invited you to the {team} workspace as {role}."), + Part::Button("Accept the invite", "link"), + ], + install_may_send: true, + }, + Template { + id: "welcome", + subject: "Welcome to CoderHelm", + params: &[p("link", Kind::Link)], + body: &[ + Part::Para("Your account is ready. Connect a repository and CoderHelm starts on your next ticket."), + Part::Button("Open CoderHelm", "link"), + ], + install_may_send: true, + }, + Template { + id: "plugin_approval", + subject: "A plugin draft is waiting for your approval", + params: &[ + p("plugin", Kind::Line(80)), + p("title", Kind::Line(200)), + p("excerpt", Kind::Text(1200)), + p("version", Kind::Number), + secret("approve_link", Kind::Link), + p("review_link", Kind::Link), + ], + body: &[ + Part::Para("A draft from the {plugin} plugin is waiting for your approval: {title}"), + Part::Quote("excerpt"), + Part::Para("Approve or reject this exact version (version {version}). The link works for three days and only for you."), + Part::Button("Approve or reject", "approve_link"), + Part::Button("Review it in CoderHelm", "review_link"), + ], + install_may_send: true, + }, + Template { + id: "knowledge_signin", + subject: "A knowledge source needs signing in again", + params: &[ + p("source", Kind::Line(80)), + p("problem", Kind::Text(300)), + p("link", Kind::Link), + ], + body: &[ + Part::Para("CoderHelm can't read the {source} knowledge source any more."), + Part::Quote("problem"), + Part::Button("Sign in again", "link"), + ], + install_may_send: true, + }, + Template { + id: "token_warning", + subject: "Your team is near its monthly token limit", + params: &[ + p("limit_name", Kind::Line(40)), + p("month", Kind::Line(20)), + p("used", Kind::Line(20)), + p("limit", Kind::Line(20)), + p("pct", Kind::Number), + p("link", Kind::Link), + ], + body: &[ + Part::Para("Your team has used {pct}% of its monthly {limit_name} limit for {month}: {used} of {limit}."), + Part::Button("See usage", "link"), + ], + install_may_send: true, + }, + Template { + id: "token_limit_reached", + subject: "Your team reached its monthly token limit", + params: &[ + p("limit_name", Kind::Line(40)), + p("month", Kind::Line(20)), + p("used", Kind::Line(20)), + p("limit", Kind::Line(20)), + p("link", Kind::Link), + ], + body: &[ + Part::Para("Your team reached its monthly {limit_name} limit for {month}: {used} of {limit}. New work waits until an admin raises the limit or the month ends."), + Part::Button("See usage", "link"), + ], + install_may_send: true, + }, + Template { + id: "support_update", + subject: "Update on a support ticket", + params: &[ + p("ticket", Kind::Line(200)), + p("note", Kind::Text(2000)), + p("link", Kind::Link), + ], + body: &[ + Part::Para("There is news on the ticket \"{ticket}\"."), + Part::Quote("note"), + Part::Button("Open the ticket", "link"), + ], + install_may_send: true, + }, + Template { + id: "update_notice", + subject: "Your CoderHelm install has an update notice", + params: &[ + p("what", Kind::OneOf(UPDATE_WHAT)), + optional("version", Kind::Version), + p("link", Kind::Link), + ], + body: &[ + Part::Para("Update notice: {what} {version}."), + Part::Button("Open Settings, System", "link"), + ], + install_may_send: true, + }, + Template { + id: "weekly_summary", + subject: "Your CoderHelm weekly summary", + params: &[ + p("team", Kind::Line(80)), + p("period", Kind::Line(40)), + p("merged", Kind::Number), + p("runs", Kind::Number), + p("reviews", Kind::Number), + p("waiting", Kind::Number), + optional("highlights", Kind::Text(1500)), + p("link", Kind::Link), + secret("unsubscribe", Kind::Link), + ], + body: &[ + Part::Para("{team}, {period}: {merged} pull requests merged, {runs} runs finished, {reviews} reviews written, {waiting} waiting on someone."), + Part::Quote("highlights"), + Part::Button("Open CoderHelm", "link"), + Part::Button("Stop these emails", "unsubscribe"), + ], + install_may_send: true, + }, + Template { + id: "webhook_disabled", + subject: "CoderHelm turned off a webhook endpoint", + // No endpoint URL or host: the address can carry a secret, and + // the relay never needs it. + params: &[p("days", Kind::Number), p("link", Kind::Link)], + body: &[ + Part::Para("Every delivery to one of your team's webhook endpoints failed for {days} days, so CoderHelm stopped sending to it. Fix it, turn it back on in Settings, Webhooks, and replay what it missed."), + Part::Button("Open Webhooks", "link"), + ], + install_may_send: true, + }, + Template { + id: "two_factor_lockout", + subject: "Two-factor sign-in paused after wrong codes", + // No name or address: the install's own SES email carries those. + params: &[p("minutes", Kind::Number), p("link", Kind::Link)], + body: &[ + Part::Para("Two-factor sign-in was paused for {minutes} minutes for someone in your organization after too many wrong codes. If they lost their phone, check it's really them, then reset their two-factor sign-in in Settings, Sign-in. If it wasn't them, someone may know their password: ask them to change it."), + Part::Button("Open Settings", "link"), + ], + install_may_send: true, + }, + // The relay's own notice to an install's admins. Installs can't ask for it. + Template { + id: "relay_paused", + subject: "CoderHelm paused email for your install", + params: &[p("reason", Kind::OneOf(&["bounces", "complaints"]))], + body: &[Part::Para( + "CoderHelm stopped sending email for your self-hosted install because too many recent emails {reason}. Check the recipients in Settings, Emails, then ask CoderHelm to resume, or switch the install to its own Amazon SES.", + )], + install_may_send: false, + }, +]; + +pub fn get(id: &str) -> Option<&'static Template> { + TEMPLATES.iter().find(|t| t.id == id) +} + +/// Why a request was refused. `code()` is what the install's Deliveries +/// page explains. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Refusal { + UnknownTemplate, + NotForInstalls, + UnknownParam(String), + MissingParam(String), + BadParam(String), + TooLong(String), + LinkNotOwnHost(String), + Reserved(String), +} + +impl Refusal { + pub fn code(&self) -> &'static str { + match self { + Self::UnknownTemplate => "unknown_template", + Self::NotForInstalls => "template_not_allowed", + Self::UnknownParam(_) => "unknown_param", + Self::MissingParam(_) => "missing_param", + Self::BadParam(_) => "bad_param", + Self::TooLong(_) => "param_too_long", + Self::LinkNotOwnHost(_) => "link_not_own_host", + Self::Reserved(_) => "param_reserved", + } + } + + pub fn message(&self) -> String { + match self { + Self::UnknownTemplate => "No such email template.".into(), + Self::NotForInstalls => "Installs can't send this template.".into(), + Self::UnknownParam(n) => format!("The template has no parameter {n}."), + Self::MissingParam(n) => format!("The parameter {n} is required."), + Self::BadParam(n) => format!("The parameter {n} has the wrong type."), + Self::TooLong(n) => format!("The parameter {n} is too long."), + Self::LinkNotOwnHost(n) => { + format!("The link {n} must point at this install's own verified address.") + } + Self::Reserved(n) => { + format!("The parameter {n} uses wording reserved for CoderHelm itself.") + } + } + } +} + +/// Checked parameter values, ready to render. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Values(pub BTreeMap); + +impl Values { + pub fn get(&self, k: &str) -> &str { + self.0.get(k).map(String::as_str).unwrap_or("") + } +} + +/// The parameters with every secret one taken out (for logs and previews). +pub fn without_secrets(t: &Template, params: &Map) -> Map { + params + .iter() + .filter(|(k, _)| t.params.iter().any(|p| p.name == k.as_str() && !p.secret)) + .map(|(k, v)| (k.clone(), v.clone())) + .collect() +} + +/// Wording a parameter may not use: it would read as CoderHelm itself +/// speaking (support, security, billing), not as the install. +const RESERVED_PHRASES: &[&str] = &[ + "coderhelm support", + "coderhelm security", + "coderhelm team", + "coderhelm staff", + "coderhelm billing", + "coderhelm trust", + "coderhelm admin", + "from coderhelm", + "coderhelm account", +]; + +fn squash(s: &str) -> String { + let mut out = String::new(); + let mut last_space = true; + for c in s.chars() { + let c = c.to_ascii_lowercase(); + if c.is_ascii_alphanumeric() { + out.push(c); + last_space = false; + } else if !last_space { + out.push(' '); + last_space = true; + } + } + out.trim().to_string() +} + +pub fn uses_reserved_wording(s: &str) -> bool { + let sq = squash(s); + // "Coder Helm" and "Coder-Helm" read the same. + let joined = sq.replace("coder helm", "coderhelm"); + RESERVED_PHRASES.iter().any(|p| joined.contains(p)) +} + +/// Top-level domains that turn a word into a link in mail apps. File +/// extensions that are also country domains (`.md`, `.rs`, `.py`, `.sh`) are +/// left out so PR titles keep their file names. +const TLDS: &[&str] = &[ + "com", "net", "org", "io", "co", "ai", "app", "dev", "xyz", "info", "biz", "me", "us", "uk", + "ru", "cn", "link", "click", "top", "site", "online", "live", "support", "help", "security", + "page", "cc", "tk", "ly", "gl", "gg", "de", "fr", "nl", "eu", "in", "jp", "br", "au", "ca", + "tv", "ws", "su", "ml", "ga", "cf", "gq", "icu", "buzz", "shop", "store", "email", "mail", + "login", "account", "cloud", "tech", "zip", "mov", "work", "today", "run", "website", "space", + "fun", "pw", "ink", "bank", "pro", "es", "it", "ch", "se", "no", "fi", "pl", "kr", "tw", "hk", + "sg", "nz", "za", "mx", "ar", "cl", "id", "vn", "th", "my", "ph", "tr", "ir", "ua", "ro", +]; + +const LINK_REMOVED: &str = "[link removed]"; + +fn looks_like_link(token: &str) -> bool { + let t = token.trim_matches(|c: char| { + !c.is_alphanumeric() && c != '/' && c != ':' && c != '@' && c != '.' && c != '-' + }); + if t.is_empty() { + return false; + } + let lower = t.to_lowercase(); + if lower.contains("://") || lower.starts_with("www.") { + return true; + } + for scheme in [ + "javascript:", + "data:", + "mailto:", + "tel:", + "vbscript:", + "file:", + "sms:", + ] { + if lower.contains(scheme) { + return true; + } + } + // An address (`someone@host.tld`). + if let Some((_, host)) = lower.split_once('@') { + if host.contains('.') { + return true; + } + } + let host = lower + .split(['/', '?', '#']) + .next() + .unwrap_or("") + .trim_end_matches('.'); + if !host.contains('.') { + return false; + } + // A host written with letters from another alphabet. + if !host.is_ascii() { + return true; + } + // An IP address. + if host.split('.').count() == 4 && host.split('.').all(|o| o.parse::().is_ok()) { + return true; + } + let tld = host.rsplit('.').next().unwrap_or(""); + let labels_ok = host + .split('.') + .all(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')); + labels_ok && TLDS.contains(&tld) +} + +/// Plain text with every link-looking word taken out, and no control +/// characters. `one_line` also turns line breaks into spaces. +pub fn plain(s: &str, one_line: bool) -> String { + let mut lines = Vec::new(); + for line in s.lines() { + let words: Vec = line + .split_whitespace() + .map(|w| { + let w: String = w.chars().filter(|c| !c.is_control()).collect(); + // Bidirectional overrides and zero-width characters hide + // what a word says. + let w: String = w + .chars() + .filter(|c| { + !matches!( + *c, + '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{FEFF}' + ) + }) + .collect(); + if looks_like_link(&w) { + LINK_REMOVED.to_string() + } else { + w + } + }) + .collect(); + lines.push(words.join(" ")); + } + if one_line { + lines.join(" ").trim().to_string() + } else { + lines.join("\n").trim().to_string() + } +} + +/// Whether `link` is an `https://` link to one of `own_hosts`, with no +/// user, password or port. +pub fn link_on_own_host(link: &str, own_hosts: &[String]) -> bool { + let Ok(u) = url::Url::parse(link) else { + return false; + }; + if u.scheme() != "https" || !u.username().is_empty() || u.password().is_some() { + return false; + } + if u.port().is_some() { + return false; + } + let Some(host) = u.host_str() else { + return false; + }; + let host = host.to_ascii_lowercase(); + own_hosts + .iter() + .any(|h| !h.is_empty() && h.eq_ignore_ascii_case(&host)) +} + +fn as_text(v: &Value) -> Option { + match v { + Value::String(s) => Some(s.clone()), + Value::Number(n) => Some(n.to_string()), + _ => None, + } +} + +/// Checks a request's parameters against its template. `own_hosts` are +/// the install's verified addresses (its CloudFront host and its name). +pub fn check( + template_id: &str, + params: &Map, + own_hosts: &[String], + from_install: bool, +) -> Result<(&'static Template, Values), Refusal> { + let t = get(template_id).ok_or(Refusal::UnknownTemplate)?; + if from_install && !t.install_may_send { + return Err(Refusal::NotForInstalls); + } + if let Some(k) = params + .keys() + .find(|k| !t.params.iter().any(|p| p.name == k.as_str())) + { + return Err(Refusal::UnknownParam(k.clone())); + } + let mut out = BTreeMap::new(); + for spec in t.params { + let Some(raw) = params.get(spec.name).filter(|v| !v.is_null()) else { + if spec.required { + return Err(Refusal::MissingParam(spec.name.into())); + } + continue; + }; + let bad = || Refusal::BadParam(spec.name.into()); + let value = match spec.kind { + Kind::Line(max) | Kind::Text(max) => { + let s = raw.as_str().ok_or_else(bad)?; + if s.chars().count() > max { + return Err(Refusal::TooLong(spec.name.into())); + } + let clean = plain(s, matches!(spec.kind, Kind::Line(_))); + if uses_reserved_wording(&clean) { + return Err(Refusal::Reserved(spec.name.into())); + } + clean + } + Kind::Number => { + let s = as_text(raw).ok_or_else(bad)?; + if s.is_empty() || s.len() > 12 || !s.chars().all(|c| c.is_ascii_digit()) { + return Err(bad()); + } + s + } + Kind::Version => { + let s = raw.as_str().ok_or_else(bad)?; + let ok = !s.is_empty() + && s.len() <= 40 + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '+') + && s.chars().any(|c| c.is_ascii_digit()) + && !looks_like_link(s); + if !ok { + return Err(bad()); + } + s.to_string() + } + Kind::OneOf(words) => { + let s = raw.as_str().ok_or_else(bad)?; + if !words.contains(&s) { + return Err(bad()); + } + s.to_string() + } + Kind::Link => { + let s = raw.as_str().ok_or_else(bad)?; + if s.len() > 2048 { + return Err(Refusal::TooLong(spec.name.into())); + } + if !link_on_own_host(s, own_hosts) { + return Err(Refusal::LinkNotOwnHost(spec.name.into())); + } + s.to_string() + } + }; + out.insert(spec.name.to_string(), value); + } + Ok((t, Values(out))) +} + +/// Cuts text to at most `max` characters (the install side, before it asks). +pub fn fit(s: &str, max: usize) -> String { + if s.chars().count() <= max { + return s.to_string(); + } + let mut out: String = s.chars().take(max.saturating_sub(1)).collect(); + out.push('…'); + out +} + +/// A written email. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Rendered { + pub subject: String, + pub text: String, + pub html: String, +} + +pub fn escape(v: &str) -> String { + let mut out = String::with_capacity(v.len()); + for c in v.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + _ => out.push(c), + } + } + out +} + +fn fill(pattern: &str, v: &Values, html: bool) -> String { + let mut out = String::new(); + let mut rest = pattern; + while let Some(start) = rest.find('{') { + out.push_str(&if html { + escape(&rest[..start]) + } else { + rest[..start].to_string() + }); + let after = &rest[start + 1..]; + let Some(end) = after.find('}') else { + out.push_str(&rest[start..]); + return out; + }; + let name = &after[..end]; + let value = v.get(name); + out.push_str(&if html { + escape(value) + } else { + value.to_string() + }); + rest = &after[end + 1..]; + } + out.push_str(&if html { escape(rest) } else { rest.to_string() }); + out +} + +/// Writes the email. `install_host` is the install's verified address, +/// named in the footer so a reader knows whose email this is; `contact` is +/// the install admin people can ask (the relay checks it is one). +pub fn render(t: &Template, v: &Values, install_host: &str, contact: Option<&str>) -> Rendered { + let mut text = Vec::new(); + let mut html = String::new(); + for part in t.body { + match part { + Part::Para(p) => { + text.push(fill(p, v, false)); + html.push_str(&format!( + "

{}

", + fill(p, v, true) + )); + } + Part::Quote(name) => { + let q = v.get(name); + if q.is_empty() { + continue; + } + text.push( + q.lines() + .map(|l| format!("> {l}")) + .collect::>() + .join("\n"), + ); + html.push_str(&format!( + "
{}
", + escape(q) + )); + } + Part::Button(label, name) => { + let link = v.get(name); + if link.is_empty() { + continue; + } + text.push(format!("{label}: {link}")); + html.push_str(&format!( + "

{}

", + escape(link), + escape(label) + )); + } + } + } + let footer = footer(install_host, contact); + text.push(String::new()); + text.push(footer.clone()); + html.push_str(&format!( + "

{}

", + escape(&footer) + )); + Rendered { + subject: t.subject.to_string(), + text: text.join("\n\n"), + html: format!( + "{html}" + ), + } +} + +/// Every relayed email ends with this: whose install sent it, and that +/// CoderHelm never asks for passwords or codes. +pub fn footer(install_host: &str, contact: Option<&str>) -> String { + let ask = match contact { + Some(c) if !c.is_empty() => format!(" Questions about it go to the install's admin, {c}."), + _ => " Questions about it go to the install's admins.".to_string(), + }; + format!( + "Sent through CoderHelm's mail service for the self-hosted CoderHelm install at {install_host}. Links in this email go only to that install.{ask} CoderHelm never asks for your password or sign-in codes by email." + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn hosts() -> Vec { + vec![ + "d111.cloudfront.net".to_string(), + "acme.coderhelm.com".to_string(), + ] + } + + fn obj(v: Value) -> Map { + v.as_object().unwrap().clone() + } + + #[test] + fn every_template_has_a_fixed_subject_and_known_parameters() { + for t in TEMPLATES { + assert!( + !t.subject.contains('{'), + "{} subject takes a parameter", + t.id + ); + for part in t.body { + let names: Vec<&str> = match part { + Part::Para(s) => s + .split('{') + .skip(1) + .filter_map(|x| x.split('}').next()) + .collect(), + Part::Quote(n) | Part::Button(_, n) => vec![n], + }; + for n in names { + assert!( + t.params.iter().any(|p| p.name == n), + "{} uses {n} without declaring it", + t.id + ); + } + } + for part in t.body { + if let Part::Button(_, n) = part { + let spec = t.params.iter().find(|p| p.name == *n).unwrap(); + assert_eq!(spec.kind, Kind::Link, "{}: a button opens a link", t.id); + } + } + } + } + + #[test] + fn a_link_must_point_at_the_installs_own_verified_host() { + let ok = check( + "welcome", + &obj(json!({"link": "https://acme.coderhelm.com/runs/1"})), + &hosts(), + true, + ); + assert!(ok.is_ok()); + for bad in [ + "https://evil.example/runs/1", + "http://acme.coderhelm.com/", + "https://acme.coderhelm.com.evil.example/", + "https://user@acme.coderhelm.com/", + "https://acme.coderhelm.com:8443/", + "javascript:alert(1)", + "https://coderhelm.com/login", + "https://app.coderhelm.com/settings", + ] { + let r = check("welcome", &obj(json!({ "link": bad })), &hosts(), true); + assert_eq!( + r.unwrap_err(), + Refusal::LinkNotOwnHost("link".into()), + "{bad}" + ); + } + } + + #[test] + fn text_parameters_lose_links_and_addresses() { + for (raw, want) in [ + ( + "Fix login at https://evil.example/x", + "Fix login at [link removed]", + ), + ("see www.evil.example now", "see [link removed] now"), + ("mail help@evil.example", "mail [link removed]"), + ("go to evil.com/reset", "go to [link removed]"), + ("ping 10.0.0.1", "ping [link removed]"), + ("visit сoderhelm.com", "visit [link removed]"), + ("click javascript:alert(1)", "click [link removed]"), + ( + "Update README.md and main.rs", + "Update README.md and main.rs", + ), + ] { + assert_eq!(plain(raw, true), want, "{raw}"); + } + assert_eq!(plain("a\u{202E}b\u{200B}c", true), "abc"); + assert_eq!(plain("one\ntwo", true), "one two"); + assert_eq!(plain("one\ntwo", false), "one\ntwo"); + } + + #[test] + fn parameters_are_escaped_when_written() { + let (t, v) = check( + "support_update", + &obj(json!({ + "ticket": "Hi", + "note": " & y", + "link": "https://acme.coderhelm.com/support/ticket/?id=1" + })), + &hosts(), + true, + ) + .unwrap(); + let r = render(t, &v, "acme.coderhelm.com", Some("admin@acme.test")); + assert!(r.text.contains("admin@acme.test")); + assert!(!r.html.contains("