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

An app secret's value is never in a page's HTML: the secrets page shows its name, last change and a Replace action #13154

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/13142-an-app-secret-s-value-is-never-in-a-page → main 6 commits fork 1 thread · 1 unresolved

  • Merged. scout/13142-an-app-secret-s-value-is-never-in-a-page was merged into main as 613eb35.

Review

Sign in to review this change.
4 files changed +176 −5
docs/design/areas/settings.md +2 −1
@@ -14,7 +14,8 @@ the text wrap and gives the control a place that is always visible. Use `.row-ac
1414 `src/web/pages/repo.ts`, `src/web/pages/pull.ts`, `src/web/pages/map.ts` and `src/web/studio/make_it_yours.ts`.
1515 Styled in `src/web/style/components.ts`.
1616 - `.row-fields` — the form in a settings row's trail (input, Save, Default): always visible, never hover-gated,
17 wrapping under the text before it would clip. Written in the trail of `row()` by `src/web/pages/flags.ts`,
17 wrapping under the text before it would clip. Written in the trail of `row()` by `appEnvView()` in `src/web/pages/settings.ts` (Replace, a write-only
18 password field), `src/web/pages/flags.ts`,
1819 `src/web/pages/telemetry.ts`, `src/web/pages/cloud.ts`, `src/web/pages/people.ts`, `src/web/pages/admin-limits.ts`,
1920 `src/web/pages/capacity.ts`, `src/web/pages/subscriptions.ts` and `src/web/studio/crew.ts`. Styled in
2021 `src/web/style/components.ts`.
docs/features/app-secrets.md +13 −2
@@ -16,9 +16,20 @@ current value. A secret typed on the new-app page is the app's own at once
1616 and the first issue names it, never its value. Every open is a `secret.read`
1717 event (the app and environment, the name, never the value).
1818
19 ## Replacing a secret
20
21 A secret's value is never shown back: not on the page, not in the API's
22 `app/env` answer, not in the MCP `app_env` list. Its row under **Settings →
23 App → Environment** shows the name, its scope and when it last changed, with
24 a password field and **Replace** beside it; type the new value and press
25 Replace (a same-origin POST to `settings/app/env`). The change is an
26 `app.env_set` event holding who and when, never the value. Replace is offered
27 on secrets only: a plain variable's value is printed in its row, so it is set
28 again with the form under the list.
29
1930
2031 ## In the terminal
2132
22 From a repository that is an app, the palette offers **Variables** (`src/tui/screens/appenv.ts`: `a` sets one, choosing its scope and whether it is a secret or a variable; the list shows each kind and a variable's value) and **Secrets this app uses** (`src/tui/screens/appsecrets.ts`: needs, has, missing; `a` grants, `x` revokes, a forge admin only).
33 From a repository that is an app, the palette offers **Variables** (`src/tui/screens/appenv.ts`: `a` sets one, choosing its scope and whether it is a secret or a variable, and setting an existing name again replaces its value; the list shows each kind and a variable's value, never a secret's) and **Secrets this app uses** (`src/tui/screens/appsecrets.ts`: needs, has, missing; `a` grants, `x` revokes, a forge admin only).
2334
24 Code: `src/core/app_secrets.ts`, `src/actions/secrets.ts` (`grantToRepo`, `revokeFromRepo`), `src/web/pages/app_secrets.ts`. Tests: `test/app-secrets.test.ts`, `test/app-secrets-web.test.ts`, `test/guest-pull.test.ts`.
35 Code: `src/core/app_secrets.ts`, `src/actions/secrets.ts` (`grantToRepo`, `revokeFromRepo`), `src/web/pages/app_secrets.ts`. Tests: `test/app-secrets.test.ts`, `test/app-secrets-value.test.ts`, `test/app-secrets-web.test.ts`, `test/guest-pull.test.ts`.
src/web/pages/settings.ts +19 −2
@@ -894,7 +894,23 @@ export function appEnvView(base: string, names: AppEnvName[]): Html {
894894 meta: html`${v.kind === "secret" ? "secret" : "variable"} · ${SCOPE_WORDS[v.scope]} · set ${time(v.updatedAt)}${
895895 v.kind === "variable" ? html` · <span class="mono">${v.value ?? ""}</span>` : html``
896896 }`,
897 trail: html`<form
897 // Replace is a secret's only way to change: its value is never shown back. A variable's
outdated

Replace shows on variables too, though the issue is about secrets and a variable's value is printed in the meta. Show the password field only for kind === 'secret', or document the choice in docs/features/app-secrets.md.

898 // value is printed in the meta, so setting it again goes through the form below.
899 trail: html`${v.kind === "secret" ? html`<form class="row-fields" method="post" action="${base}/settings/app/env">
900 <input type="hidden" name="name" value="${v.name}" />
901 <input type="hidden" name="scope" value="${v.scope}" />
902 <input type="hidden" name="kind" value="${v.kind}" />
903 <input
904 class="input"
905 type="password"
906 name="value"
907 placeholder="New value"
908 aria-label="New value for ${v.name} (${SCOPE_WORDS[v.scope]})"
909 autocomplete="off"
910 required
911 />
912 ${btn("Replace", { size: "sm", label: `Replace ${v.name} (${SCOPE_WORDS[v.scope]})` })}
913 </form>` : html``}<form
898914 class="row-actions"
899915 method="post"
900916 action="${base}/settings/app/env/${encodeURIComponent(v.name)}/delete"
@@ -1534,7 +1550,8 @@ export async function autonomySettingsUpdate(ctx: Ctx): Promise<Response> {
15341550 if (gate instanceof Response) return gate;
15351551 const { repo, form } = gate;
15361552 const base = repoBase(repo);
1537 // The builders' slots are the Builder pillar's number on the team card; this form only keeps them.
1553 // The builders' slots are the Builder pillar's number on the team card; this form only keeps
1554 // them.
15381555 const slotsField = field(form, "slots");
15391556 const slots = slotsField === "" ? repo.autonomySlots : Number(slotsField);
15401557 const checked = checkAutonomy(field(form, "autonomy"), slots);
test/app-secrets-value.test.ts added +142
@@ -0,0 +1,142 @@
1 /**
2 * An app secret's value is never read back (#13142): the app's settings
3 * page lists each secret by name and when it last changed, with a Replace
4 * action; the page, the API and the MCP answer all carry no trace of the
5 * value. Replace is a same-origin POST, and records who changed it and
6 * when, without the value.
7 */
8
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { newApp } from "../src/actions/apps.ts";
15 import { createSession } from "../src/core/sessions.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19 import { seedAdmin } from "./helpers/admin.ts";
20
21 quietLogs();
22
23 describe("an app secret's value is never in an answer", () => {
24 let dataDir = "";
25 let app: App;
26 let servers: Servers;
27 let base = "";
28 let cookie = "";
29 let token = "";
30 let adminId = "";
31 const FIRST = "first-value-7f3a9c-must-not-leak";
32 const SECOND = "second-value-b81d2e-must-not-leak";
33
34 const page = async (): Promise<string> =>
35 (await fetch(`${base}/alice/budgeting/settings/app`, { headers: { cookie } })).text();
36 const api = async (): Promise<string> =>
37 (await fetch(`${base}/api/v1/repos/alice/budgeting/app/env`, { headers: { authorization: `Bearer ${token}` } })).text();
38 const mcp = async (): Promise<string> =>
39 (
40 await fetch(`${base}/mcp`, {
41 method: "POST",
42 headers: {
43 "content-type": "application/json",
44 accept: "application/json, text/event-stream",
45 authorization: `Bearer ${token}`,
46 },
47 body: JSON.stringify({
48 jsonrpc: "2.0",
49 id: 1,
50 method: "tools/call",
51 params: { name: "app_env", arguments: { repo: "alice/budgeting", action: "list" } },
52 }),
53 })
54 ).text();
55 const replace = (value: string, origin: string): Promise<Response> =>
56 fetch(`${base}/alice/budgeting/settings/app/env`, {
57 method: "POST",
58 headers: { cookie, origin },
59 redirect: "manual",
60 body: new URLSearchParams({ name: "OWN_KEY", scope: "all", kind: "secret", value }),
61 });
62
63 beforeAll(async () => {
64 dataDir = await mkdtemp(join(tmpdir(), "forge-app-secret-value-"));
65 app = createApp({ dataDir, port: 0 });
66 servers = await serve(app);
67 base = servers.url;
68 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-good-passphrase" });
69 if (!a.ok) throw new Error(a.error);
70 adminId = a.value.id;
71 cookie = `forge_session=${createSession(app.db, a.value.id).token}`;
72 token = createToken(app.db, a.value.id, "admin", "admin").token;
73 const made = await newApp(app, a.value, { name: "budgeting", secrets: [{ name: "OWN_KEY", value: FIRST }] });
74 if (!made.ok) throw new Error(made.error);
75 });
76 afterAll(async () => {
77 servers.stop();
78 app.close();
79 await rm(dataDir, { recursive: true, force: true });
80 });
81
82 test("the page lists the secret's name, when it changed, and a Replace action", async () => {
83 const html = await page();
84 expect(html).toContain(">OWN_KEY<");
85 expect(html).toMatch(/secret · [^<]* · set <time/);
86 const replaceForm = html.match(/<form class="row-fields" method="post" action="\/alice\/budgeting\/settings\/app\/env">[\s\S]*?<\/form>/);
87 expect(replaceForm).not.toBeNull();
88 expect(replaceForm![0]).toContain('name="name" value="OWN_KEY"');
89 expect(replaceForm![0]).toContain('type="password"');
90 expect(replaceForm![0]).toContain("Replace");
91 });
92
93 test("a plain variable, whose value the row prints, offers no Replace form", async () => {
94 const set = await fetch(`${base}/alice/budgeting/settings/app/env`, {
95 method: "POST",
96 headers: { cookie, origin: base },
97 redirect: "manual",
98 body: new URLSearchParams({ name: "PLAIN_MODE", scope: "all", kind: "variable", value: "loud" }),
99 });
100 expect(set.status).toBe(303);
101 const html = await page();
102 expect(html).toContain(">PLAIN_MODE<");
103 const forms = html.match(/<form class="row-fields"[\s\S]*?<\/form>/g) ?? [];
104 expect(forms.some((f) => f.includes('value="OWN_KEY"'))).toBe(true);
105 expect(forms.some((f) => f.includes('value="PLAIN_MODE"'))).toBe(false);
106 });
107
108 test("the value is in no HTML, no API answer and no MCP answer", async () => {
109 const [h, j, m] = await Promise.all([page(), api(), mcp()]);
110 expect(j).toContain("OWN_KEY");
111 expect(m).toContain("OWN_KEY");
112 for (const answer of [h, j, m]) expect(answer).not.toContain(FIRST);
113 });
114
115 test("Replace without the page's origin is refused, and nothing changes", async () => {
116 const before = app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM event WHERE kind = 'app.env_set'").get()!.n;
117 const refused = await replace(SECOND, "https://elsewhere.example");
118 expect(refused.status).toBe(403);
119 const after = app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM event WHERE kind = 'app.env_set'").get()!.n;
120 expect(after).toBe(before);
121 });
122
123 test("Replace takes a new value, records who and when, and never shows it", async () => {
124 const res = await replace(SECOND, base);
125 expect(res.status).toBe(303);
126 const ev = app.db
127 .query<{ actor_id: string; payload: string; created_at: string }, []>(
128 "SELECT actor_id, payload, created_at FROM event WHERE kind = 'app.env_set' ORDER BY rowid DESC LIMIT 1",
129 )
130 .get()!;
131 expect(ev.actor_id).toBe(adminId);
132 expect(ev.created_at).toMatch(/^\d{4}-\d\d-\d\dT/);
133 expect(JSON.parse(ev.payload)).toMatchObject({ name: "OWN_KEY", kind: "secret" });
134 const everything = app.db.query<{ payload: string }, []>("SELECT payload FROM event").all().map((e) => e.payload).join("\n");
135 expect(everything).not.toContain(SECOND);
136 const [h, j, m] = await Promise.all([page(), api(), mcp()]);
137 for (const answer of [h, j, m]) {
138 expect(answer).not.toContain(SECOND);
139 expect(answer).not.toContain(FIRST);
140 }
141 });
142 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs