Public: anyone can read this; the crew can change it.

Mail key doors: which scope is in effect, set and remove an override, redaction across surfaces #17385

opened this

Merged 31h 43m ago, live in production

scout/forge:scout/17336-mail-key-doors-which-scope-is-in-effect → main 0 commits fork

  • Merged. scout/17336-mail-key-doors-which-scope-is-in-effect was merged into main as 8efca4b.

Review

Sign in to review this change.
17 files changed +710 −181
docs/features/mail-key.md added +23
@@ -0,0 +1,23 @@
1 ---
2 topic: Every setting, by topic
3 row: Mail key doors: which scope sends, set or remove an override
4 ---
5 # Mail key doors
6
7 Mail goes out with one key, the narrowest scope that holds a whole one: app, then domain
8 (the owner organization), then forge, then the platform's boot key (#17336,
9 [the design](../MAIL-RELAY.md)). A key is the secrets `MAIL_SMTP_URL` and `MAIL_FROM`
10 sealed together at a place. Removing it falls back to the next wider scope. Every door
11 says the scope and the sentence, never the key. Forge admins only.
12
13 - **Page**: Settings → Secrets (`src/web/pages/secrets.ts`) says "Mail goes out with the
14 forge's key" for the place in view. The page only reads the scope in effect: it has no mail-key form and no
15 remove (a chosen limit, #17336); set or remove through the terminal, API or MCP below.
16 - **Terminal** (`src/tui/screens/secrets.ts`): `m` sets the key at the place in view (from,
17 then the URL typed masked), `u` removes it after a confirm, `s` looks at another place.
18 - **API**: `GET /api/v1/mail-key/:scope?ref=` answers `{ in_effect, line }`; `PUT` with
19 `{ ref, url, from }` sets; `DELETE ?ref=` removes. `url` is `smtps://user:pass@host:465`
20 (`smtp://` only for this machine), `from` one address. Admin-scope token.
21 - **MCP**: the `secrets` tool, `action: mail`, `mail_set` (`url`, `from`) or `mail_remove`.
22
23 `test/mail-key-doors.test.ts` plants a key and searches every answer, page, screen and event.
src/actions/secrets.ts +119 −18
@@ -16,7 +16,7 @@ import { getAppById, getAppByRepo } from "../core/apps.ts";
1616 import { readerFor } from "../git/read.ts";
1717 import { repoDir } from "../git/repos.ts";
1818 import type { Repo } from "../core/repos.ts";
19 import { resolveMailKey } from "../core/mail_key.ts";
19 import { MAIL_KEY_NAMES, resolveMailKey, type MailScope } from "../core/mail_key.ts";
2020 import { requireRepoAdmin } from "./access.ts";
2121 import { neededNames, needRows, type NeedRow, appsUsing, grantable, grantSecret, revokeGrant, usesOf, type SecretUse } from "../core/app_secrets.ts";
2222 import {
@@ -62,32 +62,133 @@ function admin(actor: User | undefined): Result<User, "not_found"> {
6262
6363 const log = createLog("secrets");
6464
65 /** Which scope's key sends for a place: a repository is the app and its owner the domain. */
66 function mailAsker(app: App, target: Target, ref: string): { app?: string; domain?: string } {
67 const asker: { app?: string; domain?: string } = {};
68 if (target.scope === "repo") {
69 asker.app = target.scopeId;
70 const org = getOrg(app.db, ref.split("/")[0] ?? "");
71 if (org) asker.domain = org.id;
72 } else if (target.scope === "org") asker.domain = target.scopeId;
73 return asker;
74 }
75
76 /** What the mail-key doors say of a place: the scope in effect (or none) and the same in words. */
77 export interface MailKeyState {
78 readonly inEffect: MailScope | null;
79 readonly line: string;
80 }
81
6582 /**
66 * Which scope's mail key sends mail for a place, in words — never the key
67 * (`core/mail_key.ts`). A repository is the app and its owning organization
68 * the domain; an organization is a domain; the forge is neither. Admins only;
69 * the page and the terminal say the same.
83 * Which scope's mail key sends mail for a place, as a scope and in words — never the key
84 * (`core/mail_key.ts`). Admins only; the page, API, MCP tool and terminal say the same.
7085 */
86 export function mailKeyState(
87 app: App,
88 actor: User | undefined,
89 scope: string = "forge",
90 ref = "",
91 ): Result<MailKeyState, "not_found" | "invalid_scope"> {
92 const who = admin(actor);
93 if (!who.ok) return who;
94 const target = resolveTarget(app, scope, ref);
95 if (!target.ok) return target;
96 const won = resolveMailKey(app.db, mailAsker(app, target.value, ref), app.config.mail);
97 return ok({
98 inEffect: won ?? null,
99 line:
100 won === undefined
101 ? "No mail key is set: no mail goes out."
102 : `Mail goes out with the ${won}'s key (the key itself is never shown).`,
103 });
104 }
105
106 /** The line alone, for the page and the terminal; undefined for anyone but an admin. */
71107 export function mailKeyLine(
72108 app: App,
73109 actor: User | undefined,
74110 scope: string = "forge",
75111 ref = "",
76112 ): string | undefined {
77 if (!admin(actor).ok) return undefined;
113 const state = mailKeyState(app, actor, scope, ref);
114 return state.ok ? state.value.line : undefined;
115 }
116
117 export type MailKeyError = "not_found" | "invalid_scope" | "invalid_url" | "invalid_from" | "no_such_secret" | SecretError;
118
119 /** Thrown inside the transaction to undo the first write. */
120 class MailWriteRefused extends Error {
121 constructor(readonly reason: SecretError) {
122 super(reason);
123 }
124 }
125
126 const FROM = /^[^\s<>@,;:"\\]+@[^\s<>@,;:"\\]+$/;
127
128 /** An SMTP URL the sender will use: `smtps://` anywhere, `smtp://` on this machine only. */
129 function smtpUrlOk(text: string): boolean {
130 try {
131 const url = new URL(text);
132 return url.protocol === "smtps:" || (url.protocol === "smtp:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname));
133 } catch {
134 return false;
135 }
136 }
137
138 /**
139 * Set a place's mail key (its two sealed secrets together); the answer is the scope now in effect.
140 */
141 export function setMailKey(
142 app: App,
143 actor: User | undefined,
144 scope: string,
145 ref: string,
146 url: string,
147 from: string,
148 ): Result<MailKeyState, MailKeyError> {
149 const who = admin(actor);
150 if (!who.ok) return who;
78151 const target = resolveTarget(app, scope, ref);
79 if (!target.ok) return undefined;
80 const asker: { app?: string; domain?: string } = {};
81 if (target.value.scope === "repo") {
82 asker.app = target.value.scopeId;
83 const [owner = ""] = ref.split("/");
84 const org = getOrg(app.db, owner);
85 if (org) asker.domain = org.id;
86 } else if (target.value.scope === "org") asker.domain = target.value.scopeId;
87 const won = resolveMailKey(app.db, asker, app.config.mail);
88 return won === undefined
89 ? "No mail key is set: no mail goes out."
90 : `Mail goes out with the ${won}'s key (the key itself is never shown).`;
152 if (!target.ok) return target;
153 if (!smtpUrlOk(url)) return err("invalid_url");
154 if (!FROM.test(from)) return err("invalid_from");
155 // Both or neither: one transaction, so a refused second write leaves no half a key.
156 const t = target.value;
157 const pairs = [["MAIL_SMTP_URL", url], ["MAIL_FROM", from]] as const;
158 const failed = app.db.transaction((): void => {
159 for (const [name, value] of pairs) {
160 const set = setSecret(app.db, app.config.dataDir, t.scope, t.scopeId, name, value);
161 if (!set.ok) throw new MailWriteRefused(set.error);
162 }
163 });
164 try {
165 failed();
166 } catch (e) {
167 if (e instanceof MailWriteRefused) return err(e.reason);
168 throw e;
169 }
170 for (const [name] of pairs) {
171 app.bus.append({ kind: "secret.set", repoId: t.repoId, actorId: who.value.id, payload: { name, scope: t.scope } });
172 restartUsers(app, t.scope, t.scopeId, name);
173 }
174 return mailKeyState(app, actor, scope, ref);
175 }
176
177 /** Take a place's mail key away: the next resolution falls to the wider scope. */
178 export function removeMailKey(
179 app: App,
180 actor: User | undefined,
181 scope: string,
182 ref: string,
183 ): Result<MailKeyState, MailKeyError> {
184 const who = admin(actor);
185 if (!who.ok) return who;
186 const target = resolveTarget(app, scope, ref);
187 if (!target.ok) return target;
188 let any = false;
189 for (const name of MAIL_KEY_NAMES) if (removeSecret(app, actor, scope, ref, name).ok) any = true;
190 if (!any) return err("no_such_secret");
191 return mailKeyState(app, actor, scope, ref);
91192 }
92193
93194 export function listSecrets(
src/contract/openapi/routes/deleteApiV1MailKeyScope.ts added +13
@@ -0,0 +1,13 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "delete",
5 path: "/api/v1/mail-key/{scope}",
6 summary: "Remove a place's mail key; mail falls to the wider scope's key",
7 detail: "Remove a place's mail key (admin scope, a site admin's); answers { in_effect, line } for what is in effect now",
8 auth: true,
9 role: "admin",
10 query: { ref: "string" },
11 refusals: { no_such_secret: "the place holds no mail key", invalid_scope: "the scope is not one the forge keeps secrets for" },
12 refuses: [401, 403, 422],
13 };
src/contract/openapi/routes/getApiV1MailKeyScope.ts added +13
@@ -0,0 +1,13 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: "/api/v1/mail-key/{scope}",
6 summary: "Which scope's mail key is in effect for a place, never the key",
7 detail: "Which scope's mail key is in effect for a place (admin scope, a site admin's): app, domain, forge, platform or null; `ref` names an org or `owner/name`; answers { in_effect, line }",
8 auth: true,
9 role: "admin",
10 query: { ref: "string" },
11 refusals: { not_found: "the scope's owner is unknown", invalid_scope: "the scope is not one the forge keeps secrets for" },
12 refuses: [401, 422],
13 };
src/contract/openapi/routes/index.ts +3
@@ -11,6 +11,7 @@ export { route as deleteApiV1ConversationQueueId } from "./deleteApiV1Conversati
1111 export { route as deleteApiV1FeaturesSlug } from "./deleteApiV1FeaturesSlug.ts";
1212 export { route as deleteApiV1ForgeTemplatesId } from "./deleteApiV1ForgeTemplatesId.ts";
1313 export { route as deleteApiV1ForgesRecipesName } from "./deleteApiV1ForgesRecipesName.ts";
14 export { route as deleteApiV1MailKeyScope } from "./deleteApiV1MailKeyScope.ts";
1415 export { route as deleteApiV1OrgsOrgTeamsTeam } from "./deleteApiV1OrgsOrgTeamsTeam.ts";
1516 export { route as deleteApiV1OrgsOrgTeamsTeamMembersUsername } from "./deleteApiV1OrgsOrgTeamsTeamMembersUsername.ts";
1617 export { route as deleteApiV1ReposOwnerName } from "./deleteApiV1ReposOwnerName.ts";
@@ -129,6 +130,7 @@ export { route as getApiV1Health } from "./getApiV1Health.ts";
129130 export { route as getApiV1Here } from "./getApiV1Here.ts";
130131 export { route as getApiV1Keeper } from "./getApiV1Keeper.ts";
131132 export { route as getApiV1KeeperPulse } from "./getApiV1KeeperPulse.ts";
133 export { route as getApiV1MailKeyScope } from "./getApiV1MailKeyScope.ts";
132134 export { route as getApiV1MaintenanceDuties } from "./getApiV1MaintenanceDuties.ts";
133135 export { route as getApiV1MaintenanceRuns } from "./getApiV1MaintenanceRuns.ts";
134136 export { route as getApiV1Map } from "./getApiV1Map.ts";
@@ -518,6 +520,7 @@ export { route as putApiV1ForgesNameCredit } from "./putApiV1ForgesNameCredit.ts
518520 export { route as putApiV1ForgesNamePlan } from "./putApiV1ForgesNamePlan.ts";
519521 export { route as putApiV1ForgesRecipesName } from "./putApiV1ForgesRecipesName.ts";
520522 export { route as putApiV1Front } from "./putApiV1Front.ts";
523 export { route as putApiV1MailKeyScope } from "./putApiV1MailKeyScope.ts";
521524 export { route as putApiV1PacksName } from "./putApiV1PacksName.ts";
522525 export { route as putApiV1PlacesPin } from "./putApiV1PlacesPin.ts";
523526 export { route as putApiV1ReposOwnerNameAppDomainsHostOldRecords } from "./putApiV1ReposOwnerNameAppDomainsHostOldRecords.ts";
src/contract/openapi/routes/putApiV1MailKeyScope.ts added +17
@@ -0,0 +1,17 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "put",
5 path: "/api/v1/mail-key/{scope}",
6 summary: "Set a place's mail key; write-only, answers the scope in effect",
7 detail: "Set a place's mail key, an SMTP `url` and a `from` address sealed together (admin scope, a site admin's); `ref` names an org or `owner/name`; answers { in_effect, line }, never the key",
8 auth: true,
9 role: "admin",
10 body: { url: "string", from: "string", ref: "string" },
11 refusals: {
12 invalid_url: "`url` is not smtps:// (or smtp:// on this machine) (422)",
13 invalid_from: "`from` is not one address (422)",
14 invalid_scope: "the scope is not one the forge keeps secrets for (422)",
15 },
16 refuses: [401, 403, 422],
17 };
src/contract/tags.ts +1
@@ -52,6 +52,7 @@ const ALIAS: Readonly<Record<string, string>> = {
5252 waves: "plan",
5353 users: "user",
5454 secrets: "tokens",
55 "mail-key": "tokens",
5556 sessions: "tokens",
5657 "first-admin": "admin",
5758 runner: "meta",
src/generated/marks.ts +159 −157
@@ -46,163 +46,164 @@ import k41 from "../http/marks/api-v1-health.json";
4646 import k42 from "../http/marks/api-v1-heartbeat.json";
4747 import k43 from "../http/marks/api-v1-here.json";
4848 import k44 from "../http/marks/api-v1-keeper.json";
49 import k45 from "../http/marks/api-v1-maintenance.json";
50 import k46 from "../http/marks/api-v1-map.json";
51 import k47 from "../http/marks/api-v1-migrate.json";
52 import k48 from "../http/marks/api-v1-offers.json";
53 import k49 from "../http/marks/api-v1-openapi.json.json";
54 import k50 from "../http/marks/api-v1-orgs.json";
55 import k51 from "../http/marks/api-v1-packs.json";
56 import k52 from "../http/marks/api-v1-passport.json";
57 import k53 from "../http/marks/api-v1-places.json";
58 import k54 from "../http/marks/api-v1-plans.json";
59 import k55 from "../http/marks/api-v1-proof.json";
60 import k56 from "../http/marks/api-v1-reach.json";
61 import k57 from "../http/marks/api-v1-release.json";
62 import k58 from "../http/marks/api-v1-releases.json";
63 import k59 from "../http/marks/api-v1-repos.json";
64 import k60 from "../http/marks/api-v1-returns.json";
65 import k61 from "../http/marks/api-v1-runner.json";
66 import k62 from "../http/marks/api-v1-search.json";
67 import k63 from "../http/marks/api-v1-secrets.json";
68 import k64 from "../http/marks/api-v1-sessions.json";
69 import k65 from "../http/marks/api-v1-share.json";
70 import k66 from "../http/marks/api-v1-slash.json";
71 import k67 from "../http/marks/api-v1-start.json";
72 import k68 from "../http/marks/api-v1-status.json";
73 import k69 from "../http/marks/api-v1-telemetry.json";
74 import k70 from "../http/marks/api-v1-templates.json";
75 import k71 from "../http/marks/api-v1-thoughts.json";
76 import k72 from "../http/marks/api-v1-timers.json";
77 import k73 from "../http/marks/api-v1-tokens.json";
78 import k74 from "../http/marks/api-v1-usage.json";
79 import k75 from "../http/marks/api-v1-user.json";
80 import k76 from "../http/marks/api-v1-users.json";
81 import k77 from "../http/marks/api-v1-version.json";
82 import k78 from "../http/marks/api-v1.json";
83 import k79 from "../http/marks/api.json";
84 import k80 from "../http/marks/apple-touch-icon-precomposed.png.json";
85 import k81 from "../http/marks/apple-touch-icon.png.json";
86 import k82 from "../http/marks/apps.json";
87 import k83 from "../http/marks/asked.json";
88 import k84 from "../http/marks/asks.json";
89 import k85 from "../http/marks/assets.json";
90 import k86 from "../http/marks/audit.csv.json";
91 import k87 from "../http/marks/audit.json";
92 import k88 from "../http/marks/big.json";
93 import k89 from "../http/marks/board.json";
94 import k90 from "../http/marks/boards.json";
95 import k91 from "../http/marks/bring.json";
96 import k92 from "../http/marks/broker.json";
97 import k93 from "../http/marks/changelog.atom.json";
98 import k94 from "../http/marks/changelog.json";
99 import k95 from "../http/marks/claim.json";
100 import k96 from "../http/marks/cloud.json";
101 import k97 from "../http/marks/cockpit.json";
102 import k98 from "../http/marks/contract.json";
103 import k99 from "../http/marks/contribute.json";
104 import k100 from "../http/marks/csp-report.json";
105 import k101 from "../http/marks/dash.json";
106 import k102 from "../http/marks/data.json";
107 import k103 from "../http/marks/dataset.json";
108 import k104 from "../http/marks/deploy-to.json";
109 import k105 from "../http/marks/design.json";
110 import k106 from "../http/marks/desk.json";
111 import k107 from "../http/marks/displays.json";
112 import k108 from "../http/marks/docs.json";
113 import k109 from "../http/marks/edge.json";
114 import k110 from "../http/marks/edition.json";
115 import k111 from "../http/marks/events.json";
116 import k112 from "../http/marks/explore.atom.json";
117 import k113 from "../http/marks/explore.json";
118 import k114 from "../http/marks/explore.json.json";
119 import k115 from "../http/marks/family.json";
120 import k116 from "../http/marks/favicon.ico.json";
121 import k117 from "../http/marks/feed.json";
122 import k118 from "../http/marks/feed.json.json";
123 import k119 from "../http/marks/first-admin.json";
124 import k120 from "../http/marks/fleet.json";
125 import k121 from "../http/marks/flow.json";
126 import k122 from "../http/marks/forge.json";
127 import k123 from "../http/marks/forges.json";
128 import k124 from "../http/marks/forks.json";
129 import k125 from "../http/marks/front.json";
130 import k126 from "../http/marks/funnel.json";
131 import k127 from "../http/marks/games.json";
132 import k128 from "../http/marks/go.json";
133 import k129 from "../http/marks/health.json";
134 import k130 from "../http/marks/home.json";
135 import k131 from "../http/marks/hooks.json";
136 import k132 from "../http/marks/icons.json";
137 import k133 from "../http/marks/infra.json";
138 import k134 from "../http/marks/join.json";
139 import k135 from "../http/marks/live.json";
140 import k136 from "../http/marks/llms-full.txt.json";
141 import k137 from "../http/marks/llms.txt.json";
142 import k138 from "../http/marks/login.json";
143 import k139 from "../http/marks/logout.json";
144 import k140 from "../http/marks/maintenance-json.json";
145 import k141 from "../http/marks/maintenance.json";
146 import k142 from "../http/marks/manifest.webmanifest.json";
147 import k143 from "../http/marks/map.json";
148 import k144 from "../http/marks/mcp.json";
149 import k145 from "../http/marks/measure.json";
150 import k146 from "../http/marks/metrics.json";
151 import k147 from "../http/marks/migrate.json";
152 import k148 from "../http/marks/new.json";
153 import k149 from "../http/marks/next.json";
154 import k150 from "../http/marks/notes.json";
155 import k151 from "../http/marks/now.json";
156 import k152 from "../http/marks/oauth.json";
157 import k153 from "../http/marks/oembed.json";
158 import k154 from "../http/marks/offers.json";
159 import k155 from "../http/marks/offline.json";
160 import k156 from "../http/marks/og.json";
161 import k157 from "../http/marks/openapi.json.json";
162 import k158 from "../http/marks/opensearch.xml.json";
163 import k159 from "../http/marks/organizations.json";
164 import k160 from "../http/marks/origins.json";
165 import k161 from "../http/marks/owner.atom.json";
166 import k162 from "../http/marks/owner.json";
167 import k163 from "../http/marks/packs.json";
168 import k164 from "../http/marks/peek.json";
169 import k165 from "../http/marks/pinned.json";
170 import k166 from "../http/marks/pipeline.json";
171 import k167 from "../http/marks/plugins.json";
172 import k168 from "../http/marks/pricing.json";
173 import k169 from "../http/marks/privacy.json";
174 import k170 from "../http/marks/r.json";
175 import k171 from "../http/marks/recover.json";
176 import k172 from "../http/marks/releases.json";
177 import k173 from "../http/marks/releases.json.json";
178 import k174 from "../http/marks/repos.json";
179 import k175 from "../http/marks/resilience.json";
180 import k176 from "../http/marks/review.json";
181 import k177 from "../http/marks/robots.txt.json";
182 import k178 from "../http/marks/root.json";
183 import k179 from "../http/marks/runs.json";
184 import k180 from "../http/marks/script-error.json";
185 import k181 from "../http/marks/search.json";
186 import k182 from "../http/marks/security.json";
187 import k183 from "../http/marks/settings.json";
188 import k184 from "../http/marks/sign-in.json";
189 import k185 from "../http/marks/signin.json";
190 import k186 from "../http/marks/signup.json";
191 import k187 from "../http/marks/sitemap.xml.json";
192 import k188 from "../http/marks/status.json";
193 import k189 from "../http/marks/sw.js.json";
194 import k190 from "../http/marks/system.json";
195 import k191 from "../http/marks/talk.json";
196 import k192 from "../http/marks/tell.json";
197 import k193 from "../http/marks/templates.json";
198 import k194 from "../http/marks/templates.json.json";
199 import k195 from "../http/marks/terms.json";
200 import k196 from "../http/marks/theme.json";
201 import k197 from "../http/marks/toolbar-lab.js.json";
202 import k198 from "../http/marks/toolbar-lab.json";
203 import k199 from "../http/marks/verify.json";
204 import k200 from "../http/marks/welcome.json";
205 import k201 from "../http/marks/well-known.json";
49 import k45 from "../http/marks/api-v1-mail-key.json";
50 import k46 from "../http/marks/api-v1-maintenance.json";
51 import k47 from "../http/marks/api-v1-map.json";
52 import k48 from "../http/marks/api-v1-migrate.json";
53 import k49 from "../http/marks/api-v1-offers.json";
54 import k50 from "../http/marks/api-v1-openapi.json.json";
55 import k51 from "../http/marks/api-v1-orgs.json";
56 import k52 from "../http/marks/api-v1-packs.json";
57 import k53 from "../http/marks/api-v1-passport.json";
58 import k54 from "../http/marks/api-v1-places.json";
59 import k55 from "../http/marks/api-v1-plans.json";
60 import k56 from "../http/marks/api-v1-proof.json";
61 import k57 from "../http/marks/api-v1-reach.json";
62 import k58 from "../http/marks/api-v1-release.json";
63 import k59 from "../http/marks/api-v1-releases.json";
64 import k60 from "../http/marks/api-v1-repos.json";
65 import k61 from "../http/marks/api-v1-returns.json";
66 import k62 from "../http/marks/api-v1-runner.json";
67 import k63 from "../http/marks/api-v1-search.json";
68 import k64 from "../http/marks/api-v1-secrets.json";
69 import k65 from "../http/marks/api-v1-sessions.json";
70 import k66 from "../http/marks/api-v1-share.json";
71 import k67 from "../http/marks/api-v1-slash.json";
72 import k68 from "../http/marks/api-v1-start.json";
73 import k69 from "../http/marks/api-v1-status.json";
74 import k70 from "../http/marks/api-v1-telemetry.json";
75 import k71 from "../http/marks/api-v1-templates.json";
76 import k72 from "../http/marks/api-v1-thoughts.json";
77 import k73 from "../http/marks/api-v1-timers.json";
78 import k74 from "../http/marks/api-v1-tokens.json";
79 import k75 from "../http/marks/api-v1-usage.json";
80 import k76 from "../http/marks/api-v1-user.json";
81 import k77 from "../http/marks/api-v1-users.json";
82 import k78 from "../http/marks/api-v1-version.json";
83 import k79 from "../http/marks/api-v1.json";
84 import k80 from "../http/marks/api.json";
85 import k81 from "../http/marks/apple-touch-icon-precomposed.png.json";
86 import k82 from "../http/marks/apple-touch-icon.png.json";
87 import k83 from "../http/marks/apps.json";
88 import k84 from "../http/marks/asked.json";
89 import k85 from "../http/marks/asks.json";
90 import k86 from "../http/marks/assets.json";
91 import k87 from "../http/marks/audit.csv.json";
92 import k88 from "../http/marks/audit.json";
93 import k89 from "../http/marks/big.json";
94 import k90 from "../http/marks/board.json";
95 import k91 from "../http/marks/boards.json";
96 import k92 from "../http/marks/bring.json";
97 import k93 from "../http/marks/broker.json";
98 import k94 from "../http/marks/changelog.atom.json";
99 import k95 from "../http/marks/changelog.json";
100 import k96 from "../http/marks/claim.json";
101 import k97 from "../http/marks/cloud.json";
102 import k98 from "../http/marks/cockpit.json";
103 import k99 from "../http/marks/contract.json";
104 import k100 from "../http/marks/contribute.json";
105 import k101 from "../http/marks/csp-report.json";
106 import k102 from "../http/marks/dash.json";
107 import k103 from "../http/marks/data.json";
108 import k104 from "../http/marks/dataset.json";
109 import k105 from "../http/marks/deploy-to.json";
110 import k106 from "../http/marks/design.json";
111 import k107 from "../http/marks/desk.json";
112 import k108 from "../http/marks/displays.json";
113 import k109 from "../http/marks/docs.json";
114 import k110 from "../http/marks/edge.json";
115 import k111 from "../http/marks/edition.json";
116 import k112 from "../http/marks/events.json";
117 import k113 from "../http/marks/explore.atom.json";
118 import k114 from "../http/marks/explore.json";
119 import k115 from "../http/marks/explore.json.json";
120 import k116 from "../http/marks/family.json";
121 import k117 from "../http/marks/favicon.ico.json";
122 import k118 from "../http/marks/feed.json";
123 import k119 from "../http/marks/feed.json.json";
124 import k120 from "../http/marks/first-admin.json";
125 import k121 from "../http/marks/fleet.json";
126 import k122 from "../http/marks/flow.json";
127 import k123 from "../http/marks/forge.json";
128 import k124 from "../http/marks/forges.json";
129 import k125 from "../http/marks/forks.json";
130 import k126 from "../http/marks/front.json";
131 import k127 from "../http/marks/funnel.json";
132 import k128 from "../http/marks/games.json";
133 import k129 from "../http/marks/go.json";
134 import k130 from "../http/marks/health.json";
135 import k131 from "../http/marks/home.json";
136 import k132 from "../http/marks/hooks.json";
137 import k133 from "../http/marks/icons.json";
138 import k134 from "../http/marks/infra.json";
139 import k135 from "../http/marks/join.json";
140 import k136 from "../http/marks/live.json";
141 import k137 from "../http/marks/llms-full.txt.json";
142 import k138 from "../http/marks/llms.txt.json";
143 import k139 from "../http/marks/login.json";
144 import k140 from "../http/marks/logout.json";
145 import k141 from "../http/marks/maintenance-json.json";
146 import k142 from "../http/marks/maintenance.json";
147 import k143 from "../http/marks/manifest.webmanifest.json";
148 import k144 from "../http/marks/map.json";
149 import k145 from "../http/marks/mcp.json";
150 import k146 from "../http/marks/measure.json";
151 import k147 from "../http/marks/metrics.json";
152 import k148 from "../http/marks/migrate.json";
153 import k149 from "../http/marks/new.json";
154 import k150 from "../http/marks/next.json";
155 import k151 from "../http/marks/notes.json";
156 import k152 from "../http/marks/now.json";
157 import k153 from "../http/marks/oauth.json";
158 import k154 from "../http/marks/oembed.json";
159 import k155 from "../http/marks/offers.json";
160 import k156 from "../http/marks/offline.json";
161 import k157 from "../http/marks/og.json";
162 import k158 from "../http/marks/openapi.json.json";
163 import k159 from "../http/marks/opensearch.xml.json";
164 import k160 from "../http/marks/organizations.json";
165 import k161 from "../http/marks/origins.json";
166 import k162 from "../http/marks/owner.atom.json";
167 import k163 from "../http/marks/owner.json";
168 import k164 from "../http/marks/packs.json";
169 import k165 from "../http/marks/peek.json";
170 import k166 from "../http/marks/pinned.json";
171 import k167 from "../http/marks/pipeline.json";
172 import k168 from "../http/marks/plugins.json";
173 import k169 from "../http/marks/pricing.json";
174 import k170 from "../http/marks/privacy.json";
175 import k171 from "../http/marks/r.json";
176 import k172 from "../http/marks/recover.json";
177 import k173 from "../http/marks/releases.json";
178 import k174 from "../http/marks/releases.json.json";
179 import k175 from "../http/marks/repos.json";
180 import k176 from "../http/marks/resilience.json";
181 import k177 from "../http/marks/review.json";
182 import k178 from "../http/marks/robots.txt.json";
183 import k179 from "../http/marks/root.json";
184 import k180 from "../http/marks/runs.json";
185 import k181 from "../http/marks/script-error.json";
186 import k182 from "../http/marks/search.json";
187 import k183 from "../http/marks/security.json";
188 import k184 from "../http/marks/settings.json";
189 import k185 from "../http/marks/sign-in.json";
190 import k186 from "../http/marks/signin.json";
191 import k187 from "../http/marks/signup.json";
192 import k188 from "../http/marks/sitemap.xml.json";
193 import k189 from "../http/marks/status.json";
194 import k190 from "../http/marks/sw.js.json";
195 import k191 from "../http/marks/system.json";
196 import k192 from "../http/marks/talk.json";
197 import k193 from "../http/marks/tell.json";
198 import k194 from "../http/marks/templates.json";
199 import k195 from "../http/marks/templates.json.json";
200 import k196 from "../http/marks/terms.json";
201 import k197 from "../http/marks/theme.json";
202 import k198 from "../http/marks/toolbar-lab.js.json";
203 import k199 from "../http/marks/toolbar-lab.json";
204 import k200 from "../http/marks/verify.json";
205 import k201 from "../http/marks/welcome.json";
206 import k202 from "../http/marks/well-known.json";
206207
207208 /** Each file of `http/marks/`, parsed, in name order. */
208209 export const MARK_FILES: readonly unknown[] = [
@@ -408,4 +409,5 @@ export const MARK_FILES: readonly unknown[] = [
408409 k199,
409410 k200,
410411 k201,
412 k202,
411413 ];
src/http/api.ts +2
@@ -383,6 +383,7 @@ import { orgRoutes } from "./api/orgs.ts";
383383 import { promptRoutes } from "./api/prompts.ts";
384384 import { cloudRoutes } from "./api/cloud.ts";
385385 import { secretRoutes } from "./api/secrets.ts";
386 import { mailKeyRoutes } from "./api/mail_key.ts";
386387 import { drillRoutes } from "./api/drills.ts";
387388 import { featureRoutes } from "./api/features.ts";
388389 import { upstreamRoutes } from "./api/upstream.ts";
@@ -3282,6 +3283,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
32823283 });
32833284
32843285 secretRoutes(router);
3286 mailKeyRoutes(router);
32853287 drillRoutes(router);
32863288 featureRoutes(router);
32873289
src/http/api/mail_key.ts added +41
@@ -0,0 +1,41 @@
1 /**
2 * The mail key's doors over the API (#17336, part 3 of #15872): `GET
3 * /api/v1/mail-key/:scope` says which scope's key is in effect for a place,
4 * `PUT` sets that place's key (url and from together), `DELETE` removes it so
5 * the next resolution falls to the wider scope. The answer is a scope and a
6 * sentence, never a key; the rules are `actions/secrets.ts`'s.
7 */
8
9 import { mailKeyState, removeMailKey, setMailKey, type MailKeyState } from "../../actions/secrets.ts";
10 import type { Handler } from "../context.ts";
11 import { body, json, requireScope, respondAccess, str } from "../respond.ts";
12 import type { Router } from "../router.ts";
13
14 const shown = (s: MailKeyState): { in_effect: string | null; line: string } => ({
15 in_effect: s.inEffect,
16 line: s.line,
17 });
18
19 export function mailKeyRoutes(router: Router<Handler>): void {
20 router.add("GET", "/api/v1/mail-key/:scope", (ctx) => {
21 const denied = requireScope(ctx, "admin");
22 if (denied) return denied;
23 const state = mailKeyState(ctx.app, ctx.auth.user, ctx.params.scope ?? "", ctx.url.searchParams.get("ref") ?? "");
24 return state.ok ? json(shown(state.value)) : respondAccess(state.error, 422);
25 });
26
27 router.add("PUT", "/api/v1/mail-key/:scope", async (ctx) => {
28 const denied = requireScope(ctx, "admin");
29 if (denied) return denied;
30 const input = await body(ctx.request);
31 const set = setMailKey(ctx.app, ctx.auth.user, ctx.params.scope ?? "", str(input.ref), str(input.url), str(input.from));
32 return set.ok ? json(shown(set.value)) : respondAccess(set.error, 422);
33 });
34
35 router.add("DELETE", "/api/v1/mail-key/:scope", (ctx) => {
36 const denied = requireScope(ctx, "admin");
37 if (denied) return denied;
38 const gone = removeMailKey(ctx.app, ctx.auth.user, ctx.params.scope ?? "", ctx.url.searchParams.get("ref") ?? "");
39 return gone.ok ? json(shown(gone.value)) : respondAccess(gone.error, 422);
40 });
41 }
src/http/lazy_lists.ts +3
@@ -1600,6 +1600,9 @@ export const API_ROUTES = [
16001600 ["GET", "/api/v1/secrets/:scope"],
16011601 ["PUT", "/api/v1/secrets/:scope/:name"],
16021602 ["DELETE", "/api/v1/secrets/:scope/:name"],
1603 ["GET", "/api/v1/mail-key/:scope"],
1604 ["PUT", "/api/v1/mail-key/:scope"],
1605 ["DELETE", "/api/v1/mail-key/:scope"],
16031606 ["GET", "/api/v1/admin/drills"],
16041607 ["GET", "/api/v1/features"],
16051608 ["GET", "/api/v1/features/:slug"],
src/http/marks/api-v1-mail-key.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/api/v1/mail-key",
3 "mark": "open"
4 }
src/http/mcp/tools/secrets.ts +16 −5
@@ -1,11 +1,11 @@
1 import { listSecrets, putSecret, removeSecret } from "../../../actions/secrets.ts";
1 import { listSecrets, mailKeyState, putSecret, removeMailKey, removeSecret, setMailKey } from "../../../actions/secrets.ts";
22 import { scopeAllows } from "../../../core/tokens.ts";
33 import { good, bad, type Tool } from "../shared.ts";
44
55 export const tool: Tool = {
66 name: "secrets",
7 doc: "`{ scope, ref?, action, name?, value? }` (forge admin): `list` the names and timestamps of the forge's sealed secrets, `set` or `remove` one; `scope` is forge, org or repo, `ref` the org or `owner/name`; a value is never read back",
8 description: "Admin: list|set|remove sealed secrets.",
7 doc: "`{ scope, ref?, action, name?, value?, url?, from? }` (forge admin): `list` the names and timestamps of the forge's sealed secrets, `set` or `remove` one; `mail` says which scope's mail key is in effect for the place, `mail_set` (`url`, `from`) or `mail_remove` its own key, never shown; `scope` is forge, org or repo, `ref` the org or `owner/name`; a value is never read back",
8 description: "Admin: list|set|remove|mail|mail_set|mail_remove sealed secrets.",
99 inputSchema: {
1010 type: "object",
1111 properties: {
@@ -14,11 +14,13 @@ export const tool: Tool = {
1414 action: { type: "string" },
1515 name: { type: "string" },
1616 value: { type: "string" },
17 url: { type: "string" },
18 from: { type: "string" },
1719 },
1820 },
1921 writes: true,
2022 tier: "delete",
21 deletes: (args) => args["action"] === "remove",
23 deletes: (args) => args["action"] === "remove" || args["action"] === "mail_remove",
2224 where: "on Settings → Secrets (/settings/secrets)",
2325 adminOnly: true,
2426 run(ctx, user, args) {
@@ -42,6 +44,15 @@ export const tool: Tool = {
4244 const gone = removeSecret(ctx.app, user, scope, ref, name);
4345 return gone.ok ? good({ removed: name }) : bad(gone.error, gone.error);
4446 }
45 return bad("invalid", "action is list, set or remove");
47 if (action === "mail" || action === "mail_set" || action === "mail_remove") {
48 const state =
49 action === "mail"
50 ? mailKeyState(ctx.app, user, scope, ref)
51 : action === "mail_set"
52 ? setMailKey(ctx.app, user, scope, ref, str(args["url"]), str(args["from"]))
53 : removeMailKey(ctx.app, user, scope, ref);
54 return state.ok ? good({ in_effect: state.value.inEffect, line: state.value.line }) : bad(state.error, state.error);
55 }
56 return bad("invalid", "action is list, set, remove, mail, mail_set or mail_remove");
4657 },
4758 };
src/tui/screens/secrets.ts +45 −1
@@ -8,7 +8,7 @@
88 * the screen directly, sees and changes nothing.
99 */
1010
11 import { listSecrets, mailKeyLine, putSecret, removeSecret } from "../../actions/secrets.ts";
11 import { listSecrets, mailKeyLine, putSecret, removeMailKey, removeSecret, setMailKey } from "../../actions/secrets.ts";
1212 import { isSecretName, type SecretName } from "../../core/secret_store.ts";
1313 import type { Ctx, Screen } from "../app/app.ts";
1414 import { binding } from "../app/keys.ts";
@@ -26,6 +26,8 @@ const ERRORS: Record<string, string> = {
2626 invalid_scope: "Place is forge, org NAME or repo OWNER/NAME.",
2727 not_found: "No such organization or repository.",
2828 no_such_secret: "No secret by that name there.",
29 invalid_url: "The URL is smtps://user:pass@host:465 (smtp:// only for this machine).",
30 invalid_from: "From is one address, like [email protected].",
2931 };
3032
3133 const say = (code: string): string => ERRORS[code] ?? "That could not be done.";
@@ -64,6 +66,8 @@ export function secretsScreen(f: Session, ctx: Ctx): Screen {
6466 binding(["a"], "set a secret"),
6567 binding(["d"], "remove"),
6668 binding(["s"], "other place"),
69 binding(["m"], "set mail key here"),
70 binding(["u"], "remove mail key here"),
6771 binding(["esc"], "back"),
6872 ],
6973 render(area, s) {
@@ -148,6 +152,46 @@ export function secretsScreen(f: Session, ctx: Ctx): Screen {
148152 },
149153 }),
150154 );
155 else if (e.key === "m")
156 ctx.push(
157 promptScreen(ctx, screen, {
158 title: `Mail key at ${showPlace(place)}`,
159 label: "from address, like [email protected]",
160 onSubmit: (from) =>
161 later(ctx, () =>
162 promptScreen(ctx, screen, {
163 title: `Mail key at ${showPlace(place)}`,
164 label: "SMTP URL, smtps://user:pass@host:465 (never shown again)",
165 mask: true,
166 onSubmit: (url) => {
167 const set = setMailKey(f.app, f.user, place.scope, place.ref, url.trim(), from.trim());
168 if (!set.ok) return say(set.error);
169 note = `Mail key sealed at ${showPlace(place)}.`;
170 ctx.invalidate();
171 return undefined;
172 },
173 }),
174 ),
175 }),
176 );
177 else if (e.key === "u")
178 ctx.push(
179 confirmScreen(ctx, screen, {
180 title: "Remove the mail key?",
181 body: [`Both MAIL_SMTP_URL and MAIL_FROM are taken from ${showPlace(place)} and cannot be read back.`],
182 actions: [
183 { label: "Remove", variant: "danger" },
184 { label: "Cancel", variant: "ghost" },
185 ],
186 selected: 1,
187 onChoose: (choice) => {
188 if (choice !== 0) return;
189 const gone = removeMailKey(f.app, f.user, place.scope, place.ref);
190 note = gone.ok ? `Mail key removed from ${showPlace(place)}.` : say(gone.error);
191 ctx.invalidate();
192 },
193 }),
194 );
151195 else if (e.key === "d") {
152196 const row = names()[state.index];
153197 if (row === undefined) return true;
test/budgets/unfixtured/api-v1-mail-key-scope.json added +4
@@ -0,0 +1,4 @@
1 {
2 "pattern": "/api/v1/mail-key/:scope",
3 "why": "no fixture holds the id this route needs"
4 }
test/mail-key-doors.test.ts added +246
@@ -0,0 +1,246 @@
1 /**
2 * The mail key's doors (#17336, part 3 of #15872): API, MCP tool and terminal
3 * say which scope is in effect, set and remove an override, and a planted key
4 * is searched for on every surface — answers, page, screen, events, log rows.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { mailKeyState, removeMailKey, setMailKey } from "../src/actions/secrets.ts";
14 import { createOrg } from "../src/core/orgs.ts";
15 import { createSession } from "../src/core/sessions.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import { secretsScreen } from "../src/tui/screens/secrets.ts";
20 import { createForgeApp } from "../src/tui/forge.ts";
21 import { headlessTerminal } from "../src/tui/term/terminal.ts";
22 import { settleApp } from "./helpers/tui.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24
25 quietLogs();
26
27 const PLANT = "plantedpw-7f3a9c";
28 const URL_ = `smtp://user:${PLANT}@127.0.0.1:2525`;
29
30 describe("mail key doors", () => {
31 let dataDir = "";
32 let app: App;
33 let servers: Servers;
34 let admin: User;
35 let adminToken = "";
36 let rwToken = "";
37 const seen: string[] = [];
38
39 const api = async (method: string, path: string, token = adminToken, body?: unknown) => {
40 const r = await fetch(`${servers.url}${path}`, {
41 method,
42 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
43 body: body === undefined ? undefined : JSON.stringify(body),
44 });
45 const text = await r.text();
46 seen.push(text);
47 return { status: r.status, text, json: text ? (JSON.parse(text) as Record<string, unknown>) : {} };
48 };
49 let id = 1;
50 const mcp = async (args: Record<string, unknown>, token = adminToken) => {
51 const r = await fetch(`${servers.url}/mcp`, {
52 method: "POST",
53 headers: {
54 "content-type": "application/json",
55 accept: "application/json, text/event-stream",
56 authorization: `Bearer ${token}`,
57 },
58 body: JSON.stringify({ jsonrpc: "2.0", id: id++, method: "tools/call", params: { name: "secrets", arguments: args } }),
59 });
60 const body = (await r.json()) as { result?: { content: { text: string }[]; isError?: boolean }; error?: unknown };
61 // A protocol-level refusal (no `result`) is a refusal too.
62 const text = body.result?.content[0]?.text ?? JSON.stringify(body.error ?? body);
63 seen.push(text);
64 return { text, isError: body.result === undefined || body.result.isError === true };
65 };
66
67 beforeAll(async () => {
68 dataDir = await mkdtemp(join(tmpdir(), "forge-mail-doors-"));
69 app = createApp({ dataDir, port: 0 });
70 const u = await createUser(app.db, {
71 origin: "seed",
72 trusted: true,
73 username: "alice",
74 email: "[email protected]",
75 password: "a-good-passphrase",
76 adminIfFirst: true,
77 });
78 if (!u.ok) throw new Error(u.error);
79 admin = u.value;
80 const org = createOrg(app.db, "acme", admin.id);
81 if (!org.ok) throw new Error(org.error);
82 const repo = await createRepo(app, admin, { name: "site", visibility: "private" });
83 if (!repo.ok) throw new Error(String(repo.error));
84 adminToken = createToken(app.db, admin.id, "admin", "admin").token;
85 rwToken = createToken(app.db, admin.id, "rw", "rw").token;
86 servers = await serve(app);
87 }, 30_000);
88 afterAll(async () => {
89 servers.stop();
90 app.close();
91 await rm(dataDir, { recursive: true, force: true });
92 });
93
94 test("the API says which scope is in effect, sets an override and removes it", async () => {
95 expect((await api("GET", "/api/v1/mail-key/forge")).json).toEqual({
96 in_effect: null,
97 line: "No mail key is set: no mail goes out.",
98 });
99 const forge = await api("PUT", "/api/v1/mail-key/forge", adminToken, { url: URL_, from: "[email protected]" });
100 expect(forge.status).toBe(200);
101 expect(forge.json.in_effect).toBe("forge");
102 const org = await api("PUT", "/api/v1/mail-key/org", adminToken, { ref: "acme", url: URL_, from: "[email protected]" });
103 expect(org.json.in_effect).toBe("domain");
104 // The repository belongs to a user, not acme: it still sees the forge's key.
105 expect((await api("GET", "/api/v1/mail-key/repo?ref=alice/site")).json.in_effect).toBe("forge");
106 const app_ = await api("PUT", "/api/v1/mail-key/repo", adminToken, { ref: "alice/site", url: URL_, from: "[email protected]" });
107 expect(app_.json.in_effect).toBe("app");
108 const gone = await api("DELETE", "/api/v1/mail-key/repo?ref=alice/site");
109 expect(gone.json.in_effect).toBe("forge");
110 expect((await api("DELETE", "/api/v1/mail-key/org?ref=acme")).json.in_effect).toBe("forge");
111 expect((await api("DELETE", "/api/v1/mail-key/forge")).json.in_effect).toBeNull();
112 expect((await api("DELETE", "/api/v1/mail-key/forge")).status).toBe(422);
113 });
114
115 test("a bad url, address or scope is refused, and a token short of admin is too", async () => {
116 const put = (body: Record<string, unknown>, scope = "forge", token = adminToken) =>
117 api("PUT", `/api/v1/mail-key/${scope}`, token, body);
118 expect((await put({ url: "http://evil.test", from: "[email protected]" })).json.error).toBe("invalid_url");
119 expect((await put({ url: "smtp://u:[email protected]", from: "[email protected]" })).json.error).toBe("invalid_url");
120 expect((await put({ url: URL_, from: "not an address" })).json.error).toBe("invalid_from");
121 expect((await put({ url: URL_, from: "[email protected]" }, "moon")).json.error).toBe("invalid_scope");
122 expect((await put({ url: URL_, from: "[email protected]" }, "forge", rwToken)).status).toBe(403);
123 expect((await api("GET", "/api/v1/mail-key/forge", rwToken)).status).toBe(403);
124 expect((await api("GET", "/api/v1/mail-key/forge")).json.in_effect).toBeNull();
125 });
126
127 test("the MCP tool does the same through actions mail, mail_set and mail_remove", async () => {
128 expect(JSON.parse((await mcp({ scope: "forge", action: "mail" })).text).in_effect).toBeNull();
129 const set = await mcp({ scope: "org", ref: "acme", action: "mail_set", url: URL_, from: "[email protected]" });
130 expect(JSON.parse(set.text).in_effect).toBe("domain");
131 expect(JSON.parse((await mcp({ scope: "org", ref: "acme", action: "mail" })).text).in_effect).toBe("domain");
132 const bad = await mcp({ scope: "org", ref: "acme", action: "mail_set", url: "nope", from: "[email protected]" });
133 expect(bad.isError).toBe(true);
134 expect(JSON.parse((await mcp({ scope: "org", ref: "acme", action: "mail_remove" })).text).in_effect).toBeNull();
135 expect((await mcp({ scope: "forge", action: "mail" }, rwToken)).isError).toBe(true);
136 });
137
138 test("the terminal sets the key masked, shows the scope and removes it", async () => {
139 const terminal = headlessTerminal(120, 24);
140 const { app: tui } = createForgeApp(
141 app,
142 { sshUsername: "t", remoteAddress: "127.0.0.1", user: admin },
143 { terminal, exitHooks: false },
144 );
145 tui.start();
146 const key = (k: string, ctrl = false) => tui.dispatch({ type: "key", key: k, ctrl, alt: false, shift: false });
147 const press = async (...keys: string[]) => {
148 for (const k of keys) {
149 key(k);
150 await settleApp(tui);
151 seen.push(tui.screen.toText());
152 }
153 };
154 const type = async (text: string) => {
155 for (const ch of text) key(ch);
156 await settleApp(tui);
157 seen.push(tui.screen.toText());
158 };
159 key("k", true);
160 await type("Secrets");
161 await press("enter", "m");
162 await type("[email protected]");
163 await press("enter");
164 await type(URL_);
165 await press("enter");
166 expect(tui.screen.toText()).toContain("Mail key sealed at forge.");
167 expect(tui.screen.toText()).toContain("Mail goes out with the forge's key");
168 // `u` asks first; Cancel (the default) removes nothing.
169 await press("u");
170 expect(tui.screen.toText()).toContain("Remove the mail key?");
171 await press("enter");
172 expect(mailKeyState(app, admin, "forge", "").ok && (mailKeyState(app, admin, "forge", "") as { value: { inEffect: string } }).value.inEffect).toBe("forge");
173 expect(tui.screen.toText()).not.toContain("Mail key removed");
174 await press("u", "left", "enter");
175 expect(tui.screen.toText()).toContain("Mail key removed from forge.");
176 expect(tui.screen.toText()).toContain("No mail key is set");
177 await press("u", "left", "enter");
178 expect(tui.screen.toText()).toContain("No secret by that name there.");
179 tui.stop();
180 });
181
182 test("a user who is not an admin cannot set or remove, in the terminal or the MCP tool", async () => {
183 const made = await createUser(app.db, {
184 origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase",
185 });
186 if (!made.ok) throw new Error(made.error);
187 const bob = made.value;
188 expect(bob.isAdmin).toBe(false);
189 expect(setMailKey(app, bob, "forge", "", URL_, "[email protected]").ok).toBe(false);
190 expect(removeMailKey(app, bob, "forge", "").ok).toBe(false);
191 expect(mailKeyState(app, bob, "forge", "").ok).toBe(false);
192 const bobToken = createToken(app.db, bob.id, "bob", "admin").token;
193 expect((await mcp({ scope: "forge", action: "mail_set", url: URL_, from: "[email protected]" }, bobToken)).isError).toBe(true);
194 expect((await mcp({ scope: "forge", action: "mail_remove" }, bobToken)).isError).toBe(true);
195 expect((await api("PUT", "/api/v1/mail-key/forge", bobToken, { url: URL_, from: "[email protected]" })).status).toBeGreaterThanOrEqual(400);
196 // The terminal offers Secrets to admins only, and its keys call the same refused action.
197 const terminal = headlessTerminal(120, 24);
198 const { app: tui } = createForgeApp(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user: bob }, { terminal, exitHooks: false });
199 tui.start();
200 tui.dispatch({ type: "key", key: "k", ctrl: true, alt: false, shift: false });
201 for (const ch of "Secrets") tui.dispatch({ type: "key", key: ch, ctrl: false, alt: false, shift: false });
202 await settleApp(tui);
203 expect(tui.screen.toText()).not.toContain("Mail key");
204 tui.stop();
205 expect((await api("GET", "/api/v1/mail-key/forge")).json.in_effect).toBeNull();
206 });
207
208 test("a second write that fails leaves no half a key, and the error is the real one", () => {
209 const huge = `${"a".repeat(70_000)}@forge.test`; // a well-formed address the store refuses
210 const set = setMailKey(app, admin, "forge", "", URL_, huge);
211 expect(set.ok).toBe(false);
212 if (!set.ok) expect(set.error).toBe("invalid_value");
213 const names = app.db.query<{ name: string }, []>("SELECT name FROM secret WHERE name IN ('MAIL_SMTP_URL','MAIL_FROM')").all();
214 expect(names).toEqual([]);
215 });
216
217 test("a planted key appears on no surface", async () => {
218 setMailKey(app, admin, "forge", "", URL_, "[email protected]");
219 const state = mailKeyState(app, admin);
220 seen.push(JSON.stringify(state));
221 seen.push(String(removeMailKey(app, admin, "repo", "alice/site").ok));
222 await api("GET", "/api/v1/secrets/forge");
223 await mcp({ scope: "forge", action: "list" });
224 // The page, and the events and logs the store wrote.
225 const page = await fetch(`${servers.url}/settings/secrets`, {
226 headers: { cookie: `forge_session=${createSession(app.db, admin.id).token}` },
227 });
228 seen.push(await page.text());
229 const events = app.db.query<{ payload: string }, []>("SELECT payload FROM event").all();
230 seen.push(...events.map((e) => e.payload));
231 const terminal = headlessTerminal(100, 20);
232 const { app: tui, session } = createForgeApp(
233 app,
234 { sshUsername: "t", remoteAddress: "127.0.0.1", user: admin },
235 { terminal, exitHooks: false },
236 );
237 tui.start();
238 await settleApp(tui);
239 tui.push(secretsScreen(session, tui.ctx));
240 await settleApp(tui);
241 seen.push(tui.screen.toText());
242 tui.stop();
243 expect(seen.length).toBeGreaterThan(10);
244 for (const s of seen) expect(s).not.toContain(PLANT);
245 });
246 });
test/security-floor-routes.test.ts +1
@@ -130,6 +130,7 @@ const UNSEEDED: Record<string, string> = {
130130 "/api/v1/repos/:owner/:name/hooks/:id/deliveries": HOOK,
131131 "/api/v1/repos/:owner/:name/reports/:id/status": REPORT,
132132 "/api/v1/repos/:owner/:name/waves/:version": WAVE,
133 "/api/v1/mail-key/:scope": SECRET,
133134 "/api/v1/secrets/:scope": SECRET,
134135 "/api/v1/user/origins/:id/browse/:owner/:name": ORIGIN,
135136 "/api/v1/user/origins/:id/browse/:owner/:name/blob/:ref/*path": ORIGIN,

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs