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

src/apps/proxy.ts hands the signed grants to their own module, with the same answers #15628

Merged opened this

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

Merged

mason/forge:mason/15623-src-apps-proxy-ts-hands-the-signed-grant → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/15623-src-apps-proxy-ts-hands-the-signed-grant was merged into main as 9699b42.

Review

Sign in to review this change.
11 files changed +179 −163
src/actions/apps.ts +2 −1
@@ -23,7 +23,8 @@ import { openPulls } from "../apps/door_pulls.ts";
2323 import { goldenPath, goldenPathLine } from "../apps/golden_path.ts";
2424 import { appVitals, type AppVitals } from "../apps/vitals.ts";
2525 import { appsRuntime, envsFor, type EnvStatus } from "../apps/runtime.ts";
26 import { grantUrl, originFor, sideForViewer, sideReader } from "../apps/proxy.ts";
26 import { grantUrl } from "../apps/grants.ts";
27 import { originFor, sideForViewer, sideReader } from "../apps/proxy.ts";
2728 import { plainLine } from "../apps/side.ts";
2829 import { scaffoldFiles } from "../apps/template.ts";
2930 import type { FileWrite } from "../git/write.ts";
src/actions/feature_tools.ts +1 −1
@@ -8,7 +8,7 @@
88
99 import type { App } from "../app.ts";
1010 import { runRecorded } from "../apps/feature_schedule.ts";
11 import { identityKey } from "../apps/proxy.ts";
11 import { identityKey } from "../apps/grants.ts";
1212 import { callTool } from "../apps/feature_tools.ts";
1313 import { appsRuntime } from "../apps/runtime.ts";
1414 import { getAbsorbed } from "../core/features.ts";
src/apps/grants.ts added +165
@@ -0,0 +1,165 @@
1 /**
2 * Signed grants: how the forge proves to an app who is asking. A grant
3 * token is what `/__forge/grant` turns into the grant cookie; the identity
4 * headers are what the app hears about the visitor. Every signature here is
5 * under a key derived from the forge's own (`loadKey`), which never leaves
6 * the forge's data directory.
7 */
8
9 import { createHmac, timingSafeEqual } from "node:crypto";
10 import { loadKey } from "../kernel/secret.ts";
11 import { originFor, type AppTarget } from "./proxy.ts";

Runtime cycle with proxy.ts (originFor). Safe today because nothing is called at load; move originFor into its own module to remove it.

12 import type { AppsRuntime } from "./runtime.ts";
13
14 const GRANT_URL_TTL_MS = 2 * 60_000;
15
16 /**
17 * Who a grant vouches for. `user` can see the app's repository; `admin`
18 * can write it. A grant with nobody named is a door opened for a visitor
19 * the forge could not name (a public app's guest who never signed in).
20 */
21 export interface GrantWho {
22 readonly id: string;
23 readonly name: string;
24 readonly role: "user" | "admin";
25 }
26
27 /**
28 * A signed grant: `<app id>.<env>.<expiry ms>.<user id>.<username>.<role>.<signature>`,
29 * with `-` in the three person fields when nobody is named. Usernames and
30 * ids never contain a dot, so the token splits cleanly.
31 */
32 export function signGrant(
33 dataDir: string,
34 target: AppTarget,
35 ttlMs: number,
36 now = Date.now(),
37 who?: GrantWho,
38 ): string {
39 const payload = `${target.app.id}.${target.env}.${now + ttlMs}.${who?.id ?? "-"}.${who?.name ?? "-"}.${who?.role ?? "-"}`;
40 return `${payload}.${mac(dataDir, payload)}`;
41 }
42
43 /**
44 * The forge's own proof that a grant link is for the browser it opens a look
45 * with, on the forge's plain-http listener (`looks/service.ts`). Such a
46 * browser drops a `Secure` cookie set over http, so the grant it follows
47 * sets a plain one; only a link carrying this proof (which only this forge
48 * can mint, and only for that token) gets it. Everyone else keeps `Secure`.
49 */
50 export function plainProof(dataDir: string, token: string): string {
51 return mac(dataDir, `plain.${token}`);
52 }
53
54 function mac(dataDir: string, payload: string): string {
55 return createHmac("sha256", loadKey(dataDir))
56 .update(payload)
57 .digest("base64url");
58 }
59
60 /** A grant taken apart and checked: who it names, and until when. */
61 export interface Grant {
62 readonly who: GrantWho | undefined;
63 readonly expiresMs: number;
64 }
65
66 /** The grant behind a token, when it vouches for this target right now. */
67 export function readGrant(
68 dataDir: string,
69 grant: string,
70 target: AppTarget,
71 now = Date.now(),
72 ): Grant | undefined {
73 const parts = grant.split(".");
74 if (parts.length !== 7) return undefined;
75 const [appId, env, expires, id, name, role, signature] = parts as [
76 string,
77 string,
78 string,
79 string,
80 string,
81 string,
82 string,
83 ];
84 if (appId !== target.app.id || env !== target.env) return undefined;
85 if (!/^\d+$/.test(expires) || Number(expires) <= now) return undefined;
86 const expected = mac(
87 dataDir,
88 `${appId}.${env}.${expires}.${id}.${name}.${role}`,
89 );
90 const a = Buffer.from(signature);
91 const b = Buffer.from(expected);
92 if (a.length !== b.length || !timingSafeEqual(a, b)) return undefined;
93 const named: GrantWho | undefined =
94 id !== "-" && name !== "-" && (role === "user" || role === "admin")
95 ? { id, name, role }
96 : undefined;
97 return { who: named, expiresMs: Number(expires) };
98 }
99
100 /** Whether `grant` vouches for this target right now. */
101 export function verifyGrant(
102 dataDir: string,
103 grant: string,
104 target: AppTarget,
105 now = Date.now(),
106 ): boolean {
107 return readGrant(dataDir, grant, target, now) !== undefined;
108 }
109
110 /**
111 * The key an app verifies identity with, derived from the forge's own so
112 * nothing new is stored: the same for production and every preview of the
113 * app, different for every app.
114 */
115 export function identityKey(dataDir: string, appId: string): string {
116 return createHmac("sha256", loadKey(dataDir))
117 .update(`identity:${appId}`)
118 .digest("hex");
119 }
120
121 /**
122 * What the app hears about the visitor: `x-forge-identity` is
123 * `<user id>|<username>|<role>|<expiry ms>` and `x-forge-signature` is its
124 * HMAC-SHA256 (base64url) under the app's identity key. No headers means
125 * nobody the forge could name. A client's own copies of these headers are
126 * dropped before the forge speaks, so a verified signature is the only
127 * thing an app has to trust.
128 */
129 export const IDENTITY_HEADERS = ["x-forge-identity", "x-forge-signature"];
130
131 export function identityHeaders(
132 dataDir: string,
133 appId: string,
134 grant: Grant | undefined,
135 ): Record<string, string> {
136 if (grant?.who === undefined) return {};
137 const identity = `${grant.who.id}|${grant.who.name}|${grant.who.role}|${grant.expiresMs}`;
138 const signature = createHmac("sha256", identityKey(dataDir, appId))
139 .update(identity)
140 .digest("base64url");
141 return { "x-forge-identity": identity, "x-forge-signature": signature };
142 }
143
144 /** The URL the forge redirects a vouched-for visitor to. */
145 export function grantUrl(
146 runtime: AppsRuntime,
147 target: AppTarget,
148 path = "/",
149 host?: string,
150 who?: GrantWho,
151 ): string {
152 const token = signGrant(
153 runtime.app.config.dataDir,
154 target,
155 GRANT_URL_TTL_MS,
156 Date.now(),
157 who,
158 );
159 // The cookie a grant sets belongs to one hostname. A visitor who asked
160 // for a hostname inside the app's own world — an app of a forge hosted
161 // here, or the app's canonical host when it has a domain of its own —
162 // must be granted on that hostname, not the one production's URL names,
163 // or the cookie lands where the request never goes.
164 return `${originFor(runtime, target, host)}/__forge/grant?t=${encodeURIComponent(token)}&to=${encodeURIComponent(path)}`;
165 }
src/apps/proxy.ts +4 −154
@@ -28,7 +28,7 @@ import { holdOpen } from "../http/caller.ts";
2828 import { appHostSuffix } from "./host.ts";
2929 import { REPORT_LINK_TITLE } from "../actions/report_words.ts";
3030 import { takesOffers } from "../actions/offer.ts";
31 import { createHmac, timingSafeEqual } from "node:crypto";
31 import { timingSafeEqual } from "node:crypto";
3232 import type { App } from "../app.ts";
3333 import { getAppById, getAppBySlug, type AppRecord } from "../core/apps.ts";
3434 import { getVerifiedDomain } from "../core/domains.ts";
@@ -44,7 +44,6 @@ import { RateLimiter } from "../core/ratelimit.ts";
4444 import { verifyToken } from "../core/tokens.ts";
4545 import { getUserById, isActive, type User } from "../core/users.ts";
4646 import { err, ok, type Result } from "../kernel/result.ts";
47 import { loadKey } from "../kernel/secret.ts";
4847 import {
4948 buildEnvFromLabel,
5049 variantEnvFromLabel,
@@ -80,6 +79,9 @@ import { behindDefault } from "./pill_behind.ts";
8079 import { repoDir } from "../git/repos.ts";
8180 import { cspNonce, HIDE_COOKIE, HIDE_PATH, HIDE_SECONDS, htmlAnswer, readPage, rewritable, TOOLBAR_ASSET_PATH, TOOLBAR_ASSET_PREFIX, toolbarResponse, withToolbar, type PillWhere } from "./toolbar.ts";
8281 import { COMMENT_ASSET_PATH, commentResponse } from "./toolbar_comment.ts";
82 import { IDENTITY_HEADERS, identityHeaders, plainProof, readGrant, signGrant, verifyGrant, type Grant, type GrantWho } from "./grants.ts";
83 // The grants moved to grants.ts (#15623); the tests still reach them here.
84 export { grantUrl, identityKey, IDENTITY_HEADERS, plainProof, readGrant, signGrant, verifyGrant, type Grant, type GrantWho } from "./grants.ts";

Transitional re-export shim kept so tests stay unedited. Follow-up: repoint the tests at grants.ts and drop this line.

8385
8486 const proxySecure = (request: Request, url: URL, forgeUrl: string): boolean =>
8587 secureFor(url, forgeUrl) ||
@@ -259,160 +261,8 @@ export function originFor(
259261 */
260262 const grantCookieName = (target: AppTarget): string =>
261263 `forge_grant_${target.app.id.slice(-8)}`;
262 const GRANT_URL_TTL_MS = 2 * 60_000;
263264 const GRANT_COOKIE_TTL_MS = 12 * 60 * 60_000;
264265
265 /**
266 * Who a grant vouches for. `user` can see the app's repository; `admin`
267 * can write it. A grant with nobody named is a door opened for a visitor
268 * the forge could not name (a public app's guest who never signed in).
269 */
270 export interface GrantWho {
271 readonly id: string;
272 readonly name: string;
273 readonly role: "user" | "admin";
274 }
275
276 /**
277 * A signed grant: `<app id>.<env>.<expiry ms>.<user id>.<username>.<role>.<signature>`,
278 * with `-` in the three person fields when nobody is named. Usernames and
279 * ids never contain a dot, so the token splits cleanly.
280 */
281 export function signGrant(
282 dataDir: string,
283 target: AppTarget,
284 ttlMs: number,
285 now = Date.now(),
286 who?: GrantWho,
287 ): string {
288 const payload = `${target.app.id}.${target.env}.${now + ttlMs}.${who?.id ?? "-"}.${who?.name ?? "-"}.${who?.role ?? "-"}`;
289 return `${payload}.${mac(dataDir, payload)}`;
290 }
291
292 /**
293 * The forge's own proof that a grant link is for the browser it opens a look
294 * with, on the forge's plain-http listener (`looks/service.ts`). Such a
295 * browser drops a `Secure` cookie set over http, so the grant it follows
296 * sets a plain one; only a link carrying this proof (which only this forge
297 * can mint, and only for that token) gets it. Everyone else keeps `Secure`.
298 */
299 export function plainProof(dataDir: string, token: string): string {
300 return mac(dataDir, `plain.${token}`);
301 }
302
303 function mac(dataDir: string, payload: string): string {
304 return createHmac("sha256", loadKey(dataDir))
305 .update(payload)
306 .digest("base64url");
307 }
308
309 /** A grant taken apart and checked: who it names, and until when. */
310 export interface Grant {
311 readonly who: GrantWho | undefined;
312 readonly expiresMs: number;
313 }
314
315 /** The grant behind a token, when it vouches for this target right now. */
316 export function readGrant(
317 dataDir: string,
318 grant: string,
319 target: AppTarget,
320 now = Date.now(),
321 ): Grant | undefined {
322 const parts = grant.split(".");
323 if (parts.length !== 7) return undefined;
324 const [appId, env, expires, id, name, role, signature] = parts as [
325 string,
326 string,
327 string,
328 string,
329 string,
330 string,
331 string,
332 ];
333 if (appId !== target.app.id || env !== target.env) return undefined;
334 if (!/^\d+$/.test(expires) || Number(expires) <= now) return undefined;
335 const expected = mac(
336 dataDir,
337 `${appId}.${env}.${expires}.${id}.${name}.${role}`,
338 );
339 const a = Buffer.from(signature);
340 const b = Buffer.from(expected);
341 if (a.length !== b.length || !timingSafeEqual(a, b)) return undefined;
342 const named: GrantWho | undefined =
343 id !== "-" && name !== "-" && (role === "user" || role === "admin")
344 ? { id, name, role }
345 : undefined;
346 return { who: named, expiresMs: Number(expires) };
347 }
348
349 /** Whether `grant` vouches for this target right now. */
350 export function verifyGrant(
351 dataDir: string,
352 grant: string,
353 target: AppTarget,
354 now = Date.now(),
355 ): boolean {
356 return readGrant(dataDir, grant, target, now) !== undefined;
357 }
358
359 /**
360 * The key an app verifies identity with, derived from the forge's own so
361 * nothing new is stored: the same for production and every preview of the
362 * app, different for every app.
363 */
364 export function identityKey(dataDir: string, appId: string): string {
365 return createHmac("sha256", loadKey(dataDir))
366 .update(`identity:${appId}`)
367 .digest("hex");
368 }
369
370 /**
371 * What the app hears about the visitor: `x-forge-identity` is
372 * `<user id>|<username>|<role>|<expiry ms>` and `x-forge-signature` is its
373 * HMAC-SHA256 (base64url) under the app's identity key. No headers means
374 * nobody the forge could name. A client's own copies of these headers are
375 * dropped before the forge speaks, so a verified signature is the only
376 * thing an app has to trust.
377 */
378 export const IDENTITY_HEADERS = ["x-forge-identity", "x-forge-signature"];
379
380 export function identityHeaders(
381 dataDir: string,
382 appId: string,
383 grant: Grant | undefined,
384 ): Record<string, string> {
385 if (grant?.who === undefined) return {};
386 const identity = `${grant.who.id}|${grant.who.name}|${grant.who.role}|${grant.expiresMs}`;
387 const signature = createHmac("sha256", identityKey(dataDir, appId))
388 .update(identity)
389 .digest("base64url");
390 return { "x-forge-identity": identity, "x-forge-signature": signature };
391 }
392
393 /** The URL the forge redirects a vouched-for visitor to. */
394 export function grantUrl(
395 runtime: AppsRuntime,
396 target: AppTarget,
397 path = "/",
398 host?: string,
399 who?: GrantWho,
400 ): string {
401 const token = signGrant(
402 runtime.app.config.dataDir,
403 target,
404 GRANT_URL_TTL_MS,
405 Date.now(),
406 who,
407 );
408 // The cookie a grant sets belongs to one hostname. A visitor who asked
409 // for a hostname inside the app's own world — an app of a forge hosted
410 // here, or the app's canonical host when it has a domain of its own —
411 // must be granted on that hostname, not the one production's URL names,
412 // or the cookie lands where the request never goes.
413 return `${originFor(runtime, target, host)}/__forge/grant?t=${encodeURIComponent(token)}&to=${encodeURIComponent(path)}`;
414 }
415
416266 /**
417267 * The forge's and the edge's credentials never reach tenant code: every
418268 * `x-plat-*` header, `authorization`, and this forge's grant cookie for
src/apps/pull_schedule.ts +1 −1
@@ -25,7 +25,7 @@ import { resolveOid } from "../git/merge.ts";
2525 import { repoDir } from "../git/repos.ts";
2626 import { parseAdapter, type AdapterSpec } from "./adapter.ts";
2727 import { readFileAt } from "./checkout.ts";
28 import { identityHeaders, type GrantWho } from "./proxy.ts";
28 import { identityHeaders, type GrantWho } from "./grants.ts";
2929 import { parsePullAnswer, PULL_BODY_MAX, recordPull, type PullAnswer } from "./pull.ts";
3030 import { appsRuntime } from "./runtime.ts";
3131 import { during } from "../perf/jobs.ts";
src/apps/runtime_bringup.ts +1 −1
@@ -20,7 +20,7 @@ import { Stopwatch } from "./timing.ts";
2020 import { ensureEnvData, envDataDir, envDir, envPull, reseedEmpty, waitedEmptyNote } from "./data.ts";
2121 import { parseManifest } from "./manifest.ts";
2222 import { releaseAt } from "./release_at.ts";
23 import { identityKey } from "./proxy.ts";
23 import { identityKey } from "./grants.ts";
2424 import { startProcess, type StartInput } from "./process.ts";
2525 import type { AppsRuntime } from "./runtime.ts";
2626 import { type Live, diedBeforeAnswering, rootFault, type Environment } from "./runtime_env.ts";
src/apps/runtime_sleep.ts +1 −1
@@ -26,7 +26,7 @@ import { BUSY_WORDS, busyReason } from "./busy.ts";
2626 import { envBuild, envVariant, envDataDir, envDir, envPull, type EnvName } from "./data.ts";
2727 import { parseManifest } from "./manifest.ts";
2828 import { heldManifest } from "../core/starts.ts";
29 import { identityKey } from "./proxy.ts";
29 import { identityKey } from "./grants.ts";
3030 import { policyAt } from "../core/slider.ts";
3131 import { getEconomics } from "../settings/economics.ts";
3232 import { asleepWords, sleepWindow, type WindowSource } from "./sleep_window.ts";
src/apps/timer_service.ts +1 −1
@@ -14,7 +14,7 @@ import { getAbsorbed } from "../core/features.ts";
1414 import { getRepoById } from "../core/repos.ts";
1515 import { dropGoneEnvs, syncSchedules, syncedCommit, type Timer } from "../core/timers.ts";
1616 import { readFileAt } from "./checkout.ts";
17 import { identityKey } from "./proxy.ts";
17 import { identityKey } from "./grants.ts";
1818 import { parseFeature, toolPath } from "./feature.ts";
1919 import { probeSchedules } from "./schedule_probe.ts";
2020 import { parseManifest } from "./manifest.ts";
src/apps/tty.ts +1 −1
@@ -22,7 +22,7 @@ import { shellCommand } from "./run_command.ts";
2222 import { killTree, openCell, type Cell } from "./contain.ts";
2323 import type { App as Forge } from "../app.ts";
2424 import { getAppBySlug, type AppRecord } from "../core/apps.ts";
25 import { identityKey } from "./proxy.ts";
25 import { identityKey } from "./grants.ts";
2626 import { canEnterApp, canRead, canWrite, getRepoById } from "../core/repos.ts";
2727 import type { User } from "../core/users.ts";
2828 import { mayView, sealedPreviewPull } from "../core/sealed.ts";
src/contract/probe.ts +1 −1
@@ -18,7 +18,7 @@
1818 * `contract.test.ts`, which has rows.
1919 */
2020
21 import { identityHeaders } from "../apps/proxy.ts";
21 import { identityHeaders } from "../apps/grants.ts";
2222 import type { AppsRuntime } from "../apps/runtime.ts";
2323 import type { AppRecord } from "../core/apps.ts";
2424 import type { Repo } from "../core/repos.ts";
src/looks/service.ts +1 −1
@@ -38,7 +38,7 @@ import {
3838 import { dirname, join } from "node:path";
3939 import type { App } from "../app.ts";
4040 import { envBuild, envPull, isEnvName, previewEnv, type EnvName } from "../apps/data.ts";
41 import { plainProof, signGrant, type GrantWho } from "../apps/proxy.ts";
41 import { plainProof, signGrant, type GrantWho } from "../apps/grants.ts";
4242 import { appsRuntime } from "../apps/runtime.ts";
4343 import {
4444 getAppById,

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs