Email for professionals and teams
Show the IAM policy when a save is refused for missing SES permissions (#98)
yi111f90de963d695
diff --git a/src/app/(admin)/domains/AwsCredentialsPanel.tsx b/src/app/(admin)/domains/AwsCredentialsPanel.tsxindex 6f6dd50..734317d 100644--- a/src/app/(admin)/domains/AwsCredentialsPanel.tsx+++ b/src/app/(admin)/domains/AwsCredentialsPanel.tsx@@ -5,7 +5,7 @@ import { useLanguage } from "@/components/language-provider";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import type { AwsCapabilityReport, AwsConfigStatus } from "@/lib/aws/aws-types";-import { requestJson } from "./api";+import { ApiError, requestJson } from "./api";import { StatusRow } from "./status-row";type Props = {@@ -18,6 +18,11 @@ type PanelResponse = { status: AwsConfigStatus; policy: unknown };const REGION_HINTS = ["us-east-1", "us-east-2", "us-west-2", "eu-west-1", "eu-west-2", "eu-central-1", "ap-southeast-2", "ap-northeast-1", "ca-central-1"];+/** Whether an error body carries the capability report the panel renders. */+function isCapabilityReport(value: unknown): value is AwsCapabilityReport {+ return typeof value === "object" && value !== null && Array.isArray((value as AwsCapabilityReport).missing);+}+/*** AWS credentials shared by SES sending and receiving. Saving validates them* with AWS (identity, then a harmless call per service) and lists any permission@@ -34,6 +39,8 @@ export default function AwsCredentialsPanel({ need, onChanged }: Props) {const [region, setRegion] = useState("us-east-1");const [busy, setBusy] = useState<"save" | "check" | "remove" | null>(null);const [error, setError] = useState("");+ /** Capabilities of credentials a save refused, kept so their IAM policy can be shown next to the message. */+ const [rejected, setRejected] = useState<AwsCapabilityReport | null>(null);useEffect(() => {let active = true;@@ -59,9 +66,23 @@ export default function AwsCredentialsPanel({ need, onChanged }: Props) {}const save = () => run("save", async () => {- const data = await requestJson<{ status: AwsConfigStatus; report: AwsCapabilityReport }>("/api/admin/aws", "PUT", { accessKeyId, secretAccessKey, region });+ let data: { status: AwsConfigStatus; report: AwsCapabilityReport };+ try {+ data = await requestJson<{ status: AwsConfigStatus; report: AwsCapabilityReport }>("/api/admin/aws", "PUT", { accessKeyId, secretAccessKey, region });+ } catch (err) {+ // The server refuses to save credentials that lack SES permissions, and answers with the report+ // and the policy that would fix it. Keep both so the panel can show them under the message.+ const body = err instanceof ApiError ? err.data as { report?: unknown; policy?: unknown } | undefined : undefined;+ if (body && isCapabilityReport(body.report)) {+ setReport(null);+ setRejected(body.report);+ if (body.policy) setPolicy(body.policy);+ }+ throw err;+ }setStatus(data.status);setReport(data.report);+ setRejected(null);setEditing(false);setSecretAccessKey("");setAccessKeyId("");@@ -70,6 +91,7 @@ export default function AwsCredentialsPanel({ need, onChanged }: Props) {const check = () => run("check", async () => {const data = await requestJson<{ report: AwsCapabilityReport }>("/api/admin/aws", "POST", {});setReport(data.report);+ setRejected(null);onChanged?.(true, data.report);});const remove = () => run("remove", async () => {@@ -77,12 +99,15 @@ export default function AwsCredentialsPanel({ need, onChanged }: Props) {const data = await requestJson<{ status: AwsConfigStatus }>("/api/admin/aws", "DELETE", {});setStatus(data.status);setReport(null);+ setRejected(null);onChanged?.(false, null);});const configured = !!status?.configured;const showForm = status !== null && (!configured || editing);const fromEnvironment = status?.source === "environment";+ // A save the server refused is not configured credentials, so its report drives the missing-permission block on its own.+ const missingReport = rejected ?? (configured && !editing ? report : null);return (<div className="space-y-2">@@ -94,7 +119,7 @@ export default function AwsCredentialsPanel({ need, onChanged }: Props) {action={configured && !editing ? (<><Button size="sm" variant="outline" className="bg-white" disabled={busy !== null} onClick={() => void check()}>{busy === "check" ? t("domains.checking") : t("aws.recheck")}</Button>- {!fromEnvironment && <Button size="sm" variant="outline" className="bg-white" disabled={busy !== null} onClick={() => setEditing(true)}>{t("resend.replace")}</Button>}+ {!fromEnvironment && <Button size="sm" variant="outline" className="bg-white" disabled={busy !== null} onClick={() => { setEditing(true); setError(""); setRejected(null); }}>{t("resend.replace")}</Button>}{!fromEnvironment && <Button size="sm" variant="outline" className="bg-white" disabled={busy !== null} onClick={() => void remove()}>{t("resend.remove")}</Button>}</>) : undefined}@@ -107,7 +132,7 @@ export default function AwsCredentialsPanel({ need, onChanged }: Props) {<datalist id="aws-regions">{REGION_HINTS.map((hint) => <option key={hint} value={hint} />)}</datalist><span className="flex gap-2"><Button type="submit" size="sm" disabled={!accessKeyId.trim() || !secretAccessKey.trim() || !region.trim() || busy !== null}>{busy === "save" ? t("aws.validating") : t("aws.validateSave")}</Button>- {editing && <Button type="button" size="sm" variant="outline" className="bg-white" onClick={() => { setEditing(false); setError(""); }}>{t("common.cancel")}</Button>}+ {editing && <Button type="button" size="sm" variant="outline" className="bg-white" onClick={() => { setEditing(false); setError(""); setRejected(null); }}>{t("common.cancel")}</Button>}</span></form>) : configured ? `${t("aws.keySummary", { hint: status?.accessKeyHint, region: status?.region })}${status?.accountId ? t("aws.accountSuffix", { id: status.accountId }) : ""}${fromEnvironment ? t("aws.envSuffix") : ""}` : t("domains.checking")}@@ -133,10 +158,11 @@ export default function AwsCredentialsPanel({ need, onChanged }: Props) {</>)}</ul>- {configured && !editing && report && report.missing.length > 0 && (- <details className="rounded-lg bg-white px-3 py-2 text-xs text-neutral-600">+ {error && <p role="alert" className="text-xs text-red-600">{error}</p>}+ {missingReport && missingReport.missing.length > 0 && (+ <details open={rejected !== null} className="rounded-lg bg-white px-3 py-2 text-xs text-neutral-600"><summary className="cursor-pointer font-medium text-neutral-800">{t("aws.missingSummary")}</summary>- <p className="mt-2">{t("aws.missingList", { list: report.missing.join(", ") })}</p>+ <p className="mt-2">{t("aws.missingList", { list: missingReport.missing.join(", ") })}</p><pre className="mt-2 max-h-64 overflow-auto rounded bg-neutral-50 p-2">{JSON.stringify(policy, null, 2)}</pre></details>)}@@ -145,7 +171,6 @@ export default function AwsCredentialsPanel({ need, onChanged }: Props) {{t("aws.createUserHint")}</p>)}- {error && <p role="alert" className="text-xs text-red-600">{error}</p>}</div>);}diff --git a/src/app/(admin)/domains/api.ts b/src/app/(admin)/domains/api.tsindex 422a8c7..c5fc98b 100644--- a/src/app/(admin)/domains/api.ts+++ b/src/app/(admin)/domains/api.ts@@ -1,6 +1,14 @@import { defaultTranslator } from "@/lib/i18n/utils";import { authFetch } from "@/lib/auth/client";+/** A rejected response, keeping the parsed body so callers can read fields beyond `error`. */+export class ApiError extends Error {+ constructor(message: string, readonly data: unknown) {+ super(message);+ this.name = "ApiError";+ }+}+export async function requestJson<T>(url: string, method: string, body?: unknown): Promise<T> {const response = await authFetch(url, {method,@@ -9,7 +17,7 @@ export async function requestJson<T>(url: string, method: string, body?: unknowncache: "no-store",});const data = (await response.json()) as T & { error?: string };- if (!response.ok) throw new Error(data.error ?? defaultTranslator("domains.requestFailed"));+ if (!response.ok) throw new ApiError(data.error ?? defaultTranslator("domains.requestFailed"), data);return data;}diff --git a/src/app/api/admin/aws/route.ts b/src/app/api/admin/aws/route.tsindex 3e75aa7..5df5f07 100644--- a/src/app/api/admin/aws/route.ts+++ b/src/app/api/admin/aws/route.ts@@ -38,7 +38,7 @@ export async function PUT(request: Request) {try {const report = await validateAwsConfig(parsed.data);if (!report.sending && !report.receiving) {- return Response.json({ error: "These credentials work but have no SES permissions. Attach the policy shown below.", report }, { status: 400 });+ return Response.json({ error: "These credentials work but have no SES permissions. Attach the policy shown below.", report, policy: AWS_IAM_POLICY }, { status: 400 });}await saveAwsConfig(access.env, parsed.data, report.accountId);return Response.json({ status: await getAwsConfigStatus(access.env), report }, { headers: noStore });diff --git a/tests/aws-credentials-panel.test.mjs b/tests/aws-credentials-panel.test.mjsnew file mode 100644index 0000000..cc042c9--- /dev/null+++ b/tests/aws-credentials-panel.test.mjs@@ -0,0 +1,178 @@+import assert from "node:assert/strict";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { dirname, join } from "node:path";+import test, { after } from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";+import { build } from "esbuild";+import { JSDOM } from "jsdom";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const outDir = mkdtempSync(join(root, "tests", ".tmp-aws-credentials-panel-"));+const outfile = join(outDir, "panel.mjs");+after(() => rmSync(outDir, { recursive: true, force: true }));++const dom = new JSDOM("<!doctype html><html><body></body></html>", { url: "https://mail.example/" });+globalThis.window = dom.window;+globalThis.document = dom.window.document;+globalThis.HTMLElement = dom.window.HTMLElement;+globalThis.HTMLInputElement = dom.window.HTMLInputElement;+globalThis.Element = dom.window.Element;+globalThis.Node = dom.window.Node;+globalThis.Event = dom.window.Event;+globalThis.localStorage = dom.window.localStorage;+globalThis.sessionStorage = dom.window.sessionStorage;+globalThis.IS_REACT_ACT_ENVIRONMENT = true;+globalThis.testDom = dom;++await build({+ stdin: {+ contents: `+ import { createElement } from "react";+ import { createRoot } from "react-dom/client";+ import { act } from "react";+ import { LanguageProvider } from "./src/components/language-provider";+ import Panel from "./src/app/(admin)/domains/AwsCredentialsPanel";+ import { ApiError, requestJson } from "./src/app/(admin)/domains/api";+ export { ApiError, requestJson };+ const dom = globalThis.testDom;+ export async function renderPanel() {+ // Each test gets its own mount, so panel state never leaks between them.+ document.body.replaceChildren();+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ await act(async () => {+ root.render(createElement(LanguageProvider, { initialLocale: "en" }, createElement(Panel, { need: "sending" })));+ });+ return async function fillAndSave() {+ const inputs = container.querySelectorAll("input");+ const setValue = (input, value) => {+ const setter = Object.getOwnPropertyDescriptor(dom.window.HTMLInputElement.prototype, "value").set;+ setter.call(input, value);+ input.dispatchEvent(new dom.window.Event("input", { bubbles: true }));+ };+ await act(async () => {+ setValue(inputs[0], "AKIAIOSFODNN7EXAMPLE");+ setValue(inputs[1], "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY");+ setValue(inputs[2], "us-east-1");+ });+ await act(async () => {+ container.querySelector("form").dispatchEvent(new dom.window.Event("submit", { bubbles: true, cancelable: true }));+ });+ };+ }+ `,+ resolveDir: root,+ loader: "tsx",+ },+ outfile,+ bundle: true,+ platform: "browser",+ format: "esm",+ target: "es2022",+ tsconfig: join(root, "tsconfig.json"),+ external: ["react", "react-dom", "react-dom/client", "jsdom"],+ logLevel: "silent",+ alias: { "@": join(root, "src") },+ banner: { js: 'import { createRequire } from "node:module"; const require = createRequire(import.meta.url);' },+ loader: { ".js": "jsx" },+ plugins: [{+ name: "runtime-stubs",+ setup(builder) {+ builder.onLoad({ filter: /\.css$/ }, () => ({ contents: "", loader: "js" }));+ },+ }],+});++const { renderPanel, requestJson, ApiError } = await import(pathToFileURL(outfile).href);+const en = JSON.parse(readFileSync(join(root, "src/lib/i18n/en.json"), "utf8"));+const AWS_IAM_POLICY_SOURCE = readFileSync(join(root, "src/lib/aws/validate.ts"), "utf8");++/** Answers the panel's calls from a queue of canned responses, recording what it was asked. */+function stubApi(responses) {+ const calls = [];+ globalThis.fetch = async (url, init) => {+ calls.push({ url: String(url), method: init?.method ?? "GET" });+ const next = responses.shift();+ if (!next) throw new Error(`unexpected ${init?.method ?? "GET"} ${url}`);+ return Response.json(next.body, { status: next.status ?? 200 });+ };+ return calls;+}++const NOT_CONFIGURED = {+ status: { configured: false, source: null, region: null, accessKeyHint: null, accountId: null },+ policy: { Version: "2012-10-17", Statement: [{ Effect: "Allow", Action: ["ses:GetAccount"], Resource: "*" }] },+};++const REFUSAL = {+ error: "These credentials work but have no SES permissions. Attach the policy shown below.",+ report: {+ accountId: "123456789012",+ arn: "arn:aws:iam::123456789012:user/mailflare",+ region: "us-east-1",+ sending: false,+ productionAccess: null,+ receivingRegion: true,+ receiving: false,+ sns: false,+ s3: false,+ missing: ["ses:GetAccount", "ses:SendEmail", "ses:DescribeActiveReceiptRuleSet"],+ },+ policy: { Version: "2012-10-17", Statement: [{ Effect: "Allow", Action: ["ses:GetAccount", "ses:SendEmail"], Resource: "*" }] },+};++test("a save the server refuses shows the missing permissions and the IAM policy", async () => {+ stubApi([{ body: NOT_CONFIGURED }, { body: REFUSAL, status: 400 }]);+ const save = await renderPanel();+ await save();++ const details = document.querySelector("body details");+ assert.ok(details, "the missing-permission block is rendered");+ assert.equal(details.open, true, "the block is expanded so the policy is readable without a click");+ assert.match(details.textContent, /ses:GetAccount, ses:SendEmail, ses:DescribeActiveReceiptRuleSet/);+ assert.match(details.querySelector("pre").textContent, /"ses:SendEmail"/);+ assert.match(document.querySelector("body [role=alert]").textContent, /no SES permissions/);+});++test("a refusal body that carries no report leaves the panel as it was", async () => {+ stubApi([{ body: NOT_CONFIGURED }, { body: { error: "AWS rejected these credentials. Check the access key ID and secret." }, status: 400 }]);+ const save = await renderPanel();+ await save();++ assert.equal(document.querySelector("body details"), null);+ assert.match(document.querySelector("body [role=alert]").textContent, /AWS rejected these credentials/);+});++test("a successful save keeps the credentials row and drops the refusal block", async () => {+ const configured = { configured: true, source: "settings", region: "us-east-1", accessKeyHint: "…MPLE", accountId: "123456789012" };+ stubApi([+ { body: NOT_CONFIGURED },+ { body: REFUSAL, status: 400 },+ { body: { status: configured, report: { ...REFUSAL.report, sending: true, productionAccess: true, missing: [] } } },+ ]);+ const save = await renderPanel();+ await save();+ assert.ok(document.querySelector("body details"));+ await save();++ assert.equal(document.querySelector("body details"), null, "the refused report is cleared once the credentials save");+ assert.equal(document.querySelector("body [role=alert]"), null);+});++test("the admin API answers a refused save with the policy it tells the admin to attach", async () => {+ const route = readFileSync(join(root, "src/app/api/admin/aws/route.ts"), "utf8");+ const refusal = route.slice(route.indexOf("!report.sending && !report.receiving"));+ assert.match(refusal, /policy: AWS_IAM_POLICY/, "the 400 body carries the policy");+ assert.match(AWS_IAM_POLICY_SOURCE, /export const AWS_IAM_POLICY = \{/, "the policy the route sends is the one validate.ts defines");+});++test("requestJson keeps the parsed body on a rejected response", async () => {+ stubApi([{ body: { error: "nope", report: REFUSAL.report }, status: 400 }]);+ const error = await requestJson("/api/admin/aws", "PUT", {}).then(() => null, (err) => err);++ assert.ok(error instanceof ApiError);+ assert.equal(error.message, "nope");+ assert.deepEqual(error.data.report, REFUSAL.report);+ assert.equal(typeof en["aws.missingSummary"], "string");+});\ No newline at end of file