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

A note filed from the app's own origin is a visitor's, never the signed-in person's, unless it carries the forge panel's proof #5096

Parked opened this
Closed without merging

scout/forge:scout/4940-a-note-filed-from-the-app-s-own-origin-i → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +146 −19
src/apps/feedback.ts +55 −11
@@ -22,6 +22,38 @@ import { sha256 } from "../kernel/hash.ts";
2222
2323 export const REQUEST_MAX = 16 * 1024;
2424 export const VISITOR_COOKIE = "forge_visitor";
25 export const PROOF_HEADER = "x-forge-proof";
26
27 /**
28 * The panel's proof (#4940). The door sits on the app's own origin, where the
29 * app's scripts send the grant cookie as surely as the panel does, so the
30 * cookie alone says only who is looking, not who chose to write. A note is a
31 * person's only when it carries a token the forge rendered into the panel's
32 * own script tag: bound to the grant it was rendered for, used once, and
33 * answered with the next one. Held in memory: a restart asks for a reload.
34 */
35 const PROOF_TTL_MS = 6 * 3600 * 1000;
36 const PROOF_MAX = 5000;
37 const proofs = new Map<string, { bind: string; until: number }>();
38
39 const bindOf = (grant: string, host: string): string => sha256(`${host}\n${grant}`);
40
41 /** A fresh token for the panel on `host`, bound to `grant`. */
42 export function issueProof(grant: string, host: string, now = Date.now()): string {
43 while (proofs.size >= PROOF_MAX) proofs.delete(proofs.keys().next().value as string);
44 const token = randomBytes(24).toString("hex");
45 proofs.set(token, { bind: bindOf(grant, host), until: now + PROOF_TTL_MS });
46 return token;
47 }
48
49 /** Spend `token`: true once, for the grant and host it was issued for. */
50 function spendProof(token: string | null, grant: string | undefined, host: string | null): boolean {
51 if (token === null || grant === undefined || host === null) return false;
52 const have = proofs.get(token);
53 if (have === undefined) return false;
54 proofs.delete(token);
55 return have.until > Date.now() && have.bind === bindOf(grant, host);
56 }
2557
2658 export interface FeedbackAsk {
2759 readonly app: App;
@@ -34,6 +66,8 @@ export interface FeedbackAsk {
3466 readonly sealed: boolean;
3567 /** The person the app's grant names, if any. */
3668 readonly viewerId: string | undefined;
69 /** The grant cookie's value the viewer came with, which a proof is bound to. */
70 readonly grant?: string | undefined;
3771 readonly secure: boolean;
3872 /** The client's limit key, from the socket (`clientBucket`). */
3973 readonly source: string;
@@ -85,8 +119,8 @@ function doorFor(ask: FeedbackAsk): Door | undefined {
85119 }
86120
87121 /** The sender: a person's key and name, or the anonymous cookie's. */
88 function senderOf(ask: FeedbackAsk, door: Door): { sender: Sender; fresh?: string } {
89 if (door.viewer !== undefined)
122 function senderOf(ask: FeedbackAsk, door: Door, proven: boolean): { sender: Sender; fresh?: string } {
123 if (proven && door.viewer !== undefined)
90124 return { sender: { key: `u:${door.viewer.id}`, name: `@${door.viewer.username}`, person: true } };
91125 const have = cookieOf(ask.request, VISITOR_COOKIE);
92126 const cookie = have !== undefined && /^[0-9a-f]{32}$/.test(have) ? have : undefined;
@@ -124,12 +158,12 @@ async function readJson(request: Request): Promise<Record<string, unknown> | und
124158 }
125159 }
126160
127 async function send(ask: FeedbackAsk, door: Door): Promise<Response> {
161 async function send(ask: FeedbackAsk, door: Door, proven: boolean, next: Record<string, string>): Promise<Response> {
128162 const { request } = ask;
129163 const body = await readJson(request);
130164 if (body === undefined) return json(400, { error: "bad_request", message: "That did not go through. Try again." });
131 const { sender, fresh } = senderOf(ask, door);
132 const cookies = fresh === undefined ? {} : { "set-cookie": visitorCookie(fresh, ask.secure) };
165 const { sender, fresh } = senderOf(ask, door, proven);
166 const cookies = fresh === undefined ? next : { ...next, "set-cookie": visitorCookie(fresh, ask.secure) };
133167 let page = "";
134168 if (typeof body.page === "string") {
135169 try {
@@ -154,16 +188,24 @@ async function send(ask: FeedbackAsk, door: Door): Promise<Response> {
154188 return json(201, { note: sent.value, name: sender.name }, cookies);
155189 }
156190
157 function list(ask: FeedbackAsk, door: Door): Response {
158 const { sender, fresh } = senderOf(ask, door);
191 function list(ask: FeedbackAsk, door: Door, proven: boolean, next: Record<string, string>): Response {
192 const { sender, fresh } = senderOf(ask, door, proven);
159193 const notes = notesFor(ask.app, ask.record, door.repo, ask.forgeUrl, sender);
160194 return json(
161195 200,
162 { name: sender.name, notes, admin: door.viewer !== undefined && canAdmin(ask.app.db, door.repo, door.viewer) },
163 fresh === undefined ? {} : { "set-cookie": visitorCookie(fresh, ask.secure) },
196 { name: sender.name, notes, admin: proven && door.viewer !== undefined && canAdmin(ask.app.db, door.repo, door.viewer) },
197 fresh === undefined ? next : { ...next, "set-cookie": visitorCookie(fresh, ask.secure) },
164198 );
165199 }
166200
201 /** Whether the request carries the panel's proof, and the header for the next one. */
202 function proof(ask: FeedbackAsk, door: Door): [boolean, Record<string, string>] {
203 const host = ask.request.headers.get("host");
204 const ok =
205 spendProof(ask.request.headers.get(PROOF_HEADER), ask.grant, host) && door.viewer !== undefined;
206 return [ok, ok && ask.grant !== undefined && host !== null ? { [PROOF_HEADER]: issueProof(ask.grant, host) } : {}];
207 }
208
167209 /** Answer a `/__forge/note*` request; `undefined` when the path is not one. */
168210 export async function feedback(ask: FeedbackAsk): Promise<Response | undefined> {
169211 const path = ask.url.pathname;
@@ -174,9 +216,11 @@ export async function feedback(ask: FeedbackAsk): Promise<Response | undefined>
174216 if (door === undefined) return json(404, { error: "not_found" });
175217 if (path === "/__forge/notes") {
176218 if (method !== "GET") return json(405, { error: "method" }, { allow: "GET" });
177 return list(ask, door);
219 const [proven, next] = proof(ask, door);
220 return list(ask, door, proven, next);
178221 }
179222 if (method !== "POST") return json(405, { error: "method" }, { allow: "POST" });
180223 if (!sameOrigin(ask.request)) return json(403, { error: "cross_origin" });
181 return send(ask, door);
224 const [proven, next] = proof(ask, door);
225 return send(ask, door, proven, next);
182226 }
src/apps/proxy.ts +21 −2
@@ -36,7 +36,7 @@ import { loadKey } from "../kernel/secret.ts";
3636 import { previewEnv, type EnvName } from "./data.ts";
3737 import type { AppsRuntime, EnvStatus } from "./runtime.ts";
3838 import { crewNow, tellLink } from "./crew.ts";
39 import { feedback } from "./feedback.ts";
39 import { feedback, issueProof } from "./feedback.ts";
4040 import { clientBucket } from "../http/peer.ts";
4141 import { doorPage } from "./door.ts";
4242 import { notFound } from "../http/respond.ts";
@@ -375,6 +375,24 @@ function sealedPull(runtime: AppsRuntime, target: AppTarget): Issue | undefined
375375 return pull?.sealed === true ? pull : undefined;
376376 }
377377
378 /**
379 * The pill with the note door's proof (#4940), for a signed-in person's page
380 * navigation only: a script's own fetch of the page says `empty`, and is given none.
381 */
382 function withProof(
383 where: PillWhere,
384 who: GrantWho | undefined,
385 request: Request,
386 target: AppTarget,
387 ): PillWhere {
388 const grant = cookieValue(request, grantCookieName(target));
389 const host = request.headers.get("host");
390 const dest = request.headers.get("sec-fetch-dest");
391 if (who === undefined || grant === undefined || host === null) return where;
392 if (dest !== null && dest !== "document" && dest !== "iframe") return where;
393 return { ...where, proof: issueProof(grant, host) };
394 }
395
378396 /**
379397 * What the pill says: the app, the environment and, for a preview, the pull
380398 * and its title. The title goes only to a viewer who may read the pull.
@@ -673,6 +691,7 @@ export async function proxyApp(
673691 env: target.env,
674692 sealed,
675693 viewerId,
694 grant: cookie,
676695 secure:
677696 url.protocol === "https:" ||
678697 request.headers.get("x-forwarded-proto") === "https",
@@ -814,7 +833,7 @@ export async function proxyApp(
814833 const page = withToolbar(
815834 bytes,
816835 runtime.options.forgeUrl,
817 pillWhere(runtime, target, vouched?.who),
836 withProof(pillWhere(runtime, target, vouched?.who), vouched?.who, request, target),
818837 );
819838 let sent = page;
820839 // Whether it is gzipped depends on the client, so every copy says so.
src/apps/toolbar.ts +25 −2
@@ -30,6 +30,26 @@ export const toolbarJs = `(function () {
3030 var pill = document.createElement("button");
3131 pill.type = "button";
3232 var d = me.dataset || {};
33 // The note door's proof is the panel's alone: taken off the tag at once,
34 // used once per request, and handed on by each answer.
35 var proof = d.proof || "";
36 try { me.removeAttribute("data-proof"); } catch (e) {}
37 var chain = Promise.resolve();
38 function call(url, init) {
39 var run = function () {
40 init.headers = init.headers || {};
41 if (proof) init.headers["x-forge-proof"] = proof;
42 proof = "";
43 return fetch(url, init).then(function (r) {
44 var next = r.headers.get("x-forge-proof");
45 if (next) proof = next;
46 return r;
47 });
48 };
49 var p = chain.then(run, run);
50 chain = p.catch(function () {});
51 return p;
52 }
3353 var where = d.env === "production" ? "production" : d.pull ? "preview of pull #" + d.pull : "";
3454 pill.setAttribute("aria-label", [d.app, where].filter(Boolean).join(", ") || "Forge");
3555 pill.setAttribute("aria-expanded", "false");
@@ -140,7 +160,7 @@ export const toolbarJs = `(function () {
140160 });
141161 }
142162 function refresh(sent) {
143 fetch("/__forge/notes", { credentials: "same-origin", cache: "no-store" })
163 call("/__forge/notes", { credentials: "same-origin", cache: "no-store" })
144164 .then(function (r) { return r.ok ? r.json() : null; })
145165 .then(function (j) {
146166 if (!j || !Array.isArray(j.notes)) return;
@@ -159,7 +179,7 @@ export const toolbarJs = `(function () {
159179 tellGo.setAttribute("aria-busy", "true");
160180 tellGo.style.opacity = ".6";
161181 function idle() { tellGo.disabled = false; tellGo.removeAttribute("aria-busy"); tellGo.style.opacity = "1"; }
162 fetch("/__forge/note", {
182 call("/__forge/note", {
163183 method: "POST",
164184 credentials: "same-origin",
165185 headers: { "content-type": "application/json" },
@@ -407,6 +427,8 @@ export type PillWhere = {
407427 env: string;
408428 pull?: number;
409429 title?: string;
430 /** The note door's one-use proof for a signed-in person's page (#4940). */
431 proof?: string;
410432 };
411433
412434 /** `text` safe inside a double-quoted HTML attribute. */
@@ -430,6 +452,7 @@ export function toolbarTag(forgeUrl: string, where?: PillWhere): string {
430452 ["env", where.env],
431453 ["pull", where.pull === undefined ? undefined : String(where.pull)],
432454 ["title", where.title],
455 ["proof", where.proof],
433456 ]
434457 .filter((pair): pair is [string, string] => pair[1] !== undefined)
435458 .map(([k, v]) => ` data-${k}="${escapeAttr(v)}"`)
test/apps-feedback.test.ts +45 −4
@@ -13,7 +13,7 @@ import { newApp } from "../src/actions/apps.ts";
1313 import { AppsRuntime } from "../src/apps/runtime.ts";
1414 import { toolbarJs } from "../src/apps/toolbar.ts";
1515 import { filtered, moderateNote, noteClock, PER_APP_DAY, PER_SENDER, PER_SOURCE, saysFromApp } from "../src/actions/app_notes.ts";
16 import { feedback, REQUEST_MAX } from "../src/apps/feedback.ts";
16 import { feedback, issueProof, PROOF_HEADER, REQUEST_MAX } from "../src/apps/feedback.ts";
1717 import { getAppBySlug } from "../src/core/apps.ts";
1818 import { getNote } from "../src/core/app_notes.ts";
1919 import { grantedCookie } from "./helpers/identity.ts";
@@ -85,6 +85,9 @@ describe("the forge button takes notes from anyone", () => {
8585 });
8686 const post = (text: string, cookie = "", source = "", slug = "notes") =>
8787 at(slug, "/__forge/note", { method: "POST", body: JSON.stringify({ text, page: `http://${host(slug)}/lists?x=1`, viewport: "390x844" }) }, cookie, source);
88 const proofFor = (cookie: string, slug: string) => issueProof(cookie.slice(cookie.indexOf("=") + 1), host(slug));
89 const posted = (text: string, cookie: string, source: string, slug: string, proof: string) =>
90 at(slug, "/__forge/note", { method: "POST", headers: { [PROOF_HEADER]: proof }, body: JSON.stringify({ text, viewport: "390x844" }) }, cookie, source);
8891 const cookieOf = (res: Response) => (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
8992
9093 test("a visitor's note files a from-app issue with page, viewport and time", async () => {
@@ -192,6 +195,42 @@ describe("the forge button takes notes from anyone", () => {
192195 expect((await post("still open", "", "", "notes")).status).toBe(201);
193196 });
194197
198 test("a signed-in person's note is theirs only with the panel's one-use proof (#4940)", async () => {
199 const owner = await grantedCookie(app, servers.url, alice, getAppBySlug(app.db, "diary")!);
200 // The app's own script: same origin, the grant cookie, no proof.
201 const bare = await post("filed by the page's script", owner, "10.6.0.1", "diary");
202 expect(bare.status).toBe(201);
203 expect(((await bare.json()) as { name: string }).name).toMatch(/^visitor-[0-9a-f]{6}$/);
204 // The panel's POST with the proof is the person's, and hands on the next.
205 const token = proofFor(owner, "diary");
206 const good = await posted("filed by the panel", owner, "10.6.0.2", "diary", token);
207 expect(good.status).toBe(201);
208 expect(((await good.json()) as { name: string }).name).toBe("@alice");
209 const next = good.headers.get(PROOF_HEADER)!;
210 expect(next).toMatch(/^[0-9a-f]{48}$/);
211 // A reused token is a visitor's note.
212 const reused = await posted("again", owner, "10.6.0.3", "diary", token);
213 expect(((await reused.json()) as { name: string }).name).toMatch(/^visitor-/);
214 // A token issued for someone else's grant, or another host, is refused.
215 const foreign = await posted("foreign", owner, "10.6.0.4", "diary", issueProof("another-grant", host("diary")));
216 expect(((await foreign.json()) as { name: string }).name).toMatch(/^visitor-/);
217 const elsewhere = await posted("elsewhere", owner, "10.6.0.5", "diary", issueProof(owner.slice(owner.indexOf("=") + 1), host("notes")));
218 expect(((await elsewhere.json()) as { name: string }).name).toMatch(/^visitor-/);
219 // The listing: the person's notes only with the proof, one use each.
220 const listed = async (proof?: string) =>
221 (await (await at("diary", "/__forge/notes", { headers: proof === undefined ? {} : { [PROOF_HEADER]: proof } }, owner)).json()) as { name: string; notes: { text: string }[] };
222 expect((await listed()).name).toMatch(/^visitor-/);
223 const mine = await listed(next);
224 expect(mine.name).toBe("@alice");
225 expect(mine.notes.map((n) => n.text)).toContain("filed by the panel");
226 expect((await listed(next)).name).toMatch(/^visitor-/);
227 });
228
229 test("the pill's tag carries a proof for a signed-in page navigation only", () => {
230 expect(toolbarJs).toContain("x-forge-proof");
231 expect(toolbarJs).toContain('removeAttribute("data-proof")');
232 });
233
195234 test("the word filter and the rate limit apply", async () => {
196235 const rude = await post("this is sh1t", "", "10.0.0.3");
197236 expect(rude.status).toBe(422);
@@ -299,15 +338,17 @@ describe("the forge button takes notes from anyone", () => {
299338
300339 test("a private app takes notes from a signed-in reader, as themselves, and from no one else", async () => {
301340 const reader = await grantedCookie(app, servers.url, alice, getAppBySlug(app.db, "diary")!);
302 const res = await post("A note on the diary", reader, "10.5.0.1", "diary");
341 const res = await posted("A note on the diary", reader, "10.5.0.1", "diary", proofFor(reader, "diary"));
303342 expect(res.status).toBe(201);
304343 expect(((await res.json()) as { name: string }).name).toBe("@alice");
305344 const repo = getRepo(app.db, "alice", "diary")!;
306345 const issue = app.db.query<{ body: string }, [string]>("SELECT body FROM issue WHERE repo_id = ?1 ORDER BY number DESC").get(repo.id)!;
307346 expect(issue.body).toContain("by @alice.");
308347 expect(issue.body).toContain("Untrusted data");
309 const mine = (await (await at("diary", "/__forge/notes", {}, reader)).json()) as { notes: unknown[]; admin: boolean };
310 expect(mine.notes.length).toBe(1);
348 const more = await posted("second", reader, "10.5.0.2", "diary", res.headers.get(PROOF_HEADER)!);
349 expect(more.status).toBe(201);
350 const mine = (await (await at("diary", "/__forge/notes", { headers: { [PROOF_HEADER]: more.headers.get(PROOF_HEADER)! } }, reader)).json()) as { notes: unknown[]; admin: boolean };
351 expect(mine.notes.length).toBeGreaterThanOrEqual(2);
311352 expect(mine.admin).toBe(true);
312353 expect((await at("diary", "/__forge/notes")).status).toBe(404);
313354 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs