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

An app may reach a private address its owner approved: exact address:port in forge.json egress, granted by a site admin (the arm app to its tailnet server) #3372

Parked opened this in answer to
Closed without merging

scout/forge:scout/3369-an-app-may-reach-a-private-address-its-o → main 3 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
19 files changed +998 −6
docs/APPS.md +17
@@ -261,6 +261,23 @@ are capped by the machine (`FORGE_CELL_MEMORY_MAX_MIB`, default 4096; the
261261 number of cores; `FORGE_CELL_DISK_MAX_MIB`, default 16384). A cell's `/tmp`
262262 holds at most 256 MiB.
263263
264 A private destination (a machine on the owner's tailnet or LAN) is never
265 reachable by default. `forge.json` may name one by exact address or host and
266 port, `"egress": ["100.89.95.68:8101"]` (never a range or a wildcard), and
267 the entry stays inert until a site admin presses Grant under "Private
268 destinations asked for" on the app's settings page. The grant records who and
269 when, and the cell connects to the address granted, so DNS cannot widen it;
270 revoke it there too. Loopback, link-local (cloud metadata) and the forge's
271 own network can never be granted: the cluster service host is excluded
272 automatically, and `FORGE_EGRESS_NEVER` (comma-separated CIDRs) adds the pod
273 and service ranges. A grant takes effect when the app next starts. It is per repository, not per
274 branch: a pull's preview that keeps the entry in its `forge.json` reaches the
275 granted address too, so a grant is a statement about everyone who can push
276 a branch to that repository. The same screens: `GET/POST
277 /api/v1/repos/:owner/:name/app/egress` and `DELETE …/app/egress/:entry`
278 (admin-scope token), the MCP tool `app_egress`, and `G` in the terminal's
279 repository view. Only a site admin who is a person grants or revokes.
280
264281 Memory is held twice. The watch reads every cell's resident memory once a
265282 second and stops one over its limit. Where the forge holds a delegated
266283 cgroup v2 (`apps/cgroup.ts`), the kernel holds it as well: each cell runs
src/actions/egress_grants.ts added +140
@@ -0,0 +1,140 @@
1 /**
2 * A site admin's say over a repository's private destinations (#3369):
3 * which exact `host:port` entries of forge.json `egress` the repository may
4 * reach on a private network, and the record of who said so.
5 */
6
7 import { lookup } from "node:dns/promises";
8 import { isIP } from "node:net";
9 import type { App } from "../app.ts";
10 import { readFileAt } from "../apps/checkout.ts";
11 import { grantable, isPublicAddress } from "../apps/egress.ts";
12 import { parseManifest } from "../apps/manifest.ts";
13 import {
14 deleteEgressGrant,
15 listEgressGrants,
16 putEgressGrant,
17 type EgressGrant,
18 } from "../core/egress_grants.ts";
19 import { canAdmin, type Repo } from "../core/repos.ts";
20 import type { User } from "../core/users.ts";
21 import { resolveOid } from "../git/merge.ts";
22 import { repoDir } from "../git/repos.ts";
23 import { err, ok, type Result } from "../kernel/result.ts";
24
25 export type GrantError =
26 | "not_found"
27 | "not_asked"
28 | "public"
29 | "never"
30 | "unresolved";
31
32 export const GRANT_WORDS: Record<GrantError, string> = {
33 not_found: "Only a site admin grants a private destination.",
34 not_asked: "forge.json egress does not name that destination.",
35 public: "That is a public address; it needs no grant.",
36 never: "That address can never be granted: it is this machine, the metadata service, or the forge's own network.",
37 unresolved: "That name does not resolve.",
38 };
39
40 /** Who may grant: a site admin who is a person. The page offers Grant on this alone. */
41 export const siteAdmin = (actor: User | undefined): actor is User =>
42 actor?.isAdmin === true && actor.kind === "user";
43
44 export interface EgressAsk {
45 readonly entry: string;
46 readonly grant: EgressGrant | null;
47 }
48
49 /** What forge.json asks for and what has been granted: a repository admin's to read. */
50 export async function listEgress(
51 app: App,
52 actor: User | undefined,
53 repo: Repo,
54 ): Promise<Result<EgressAsk[], "not_found">> {
55 if (!canAdmin(app.db, repo, actor)) return err("not_found");
56 const granted = new Map(
57 listEgressGrants(app.db, repo.id).map((g) => [g.entry, g]),
58 );
59 const asks = await privateAsks(app, repo);
60 return ok(asks.map((entry) => ({ entry, grant: granted.get(entry) ?? null })));
61 }
62
63 /** The exact `host:port` entries of the default branch's forge.json egress. */
64 export async function privateAsks(app: App, repo: Repo): Promise<string[]> {
65 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
66 const tip = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
67 if (typeof tip !== "string") return [];
68 const [forgeJson, packageJson] = await Promise.all([
69 readFileAt(dir, tip, "forge.json"),
70 readFileAt(dir, tip, "package.json"),
71 ]);
72 const manifest = parseManifest(forgeJson, packageJson);
73 if (!manifest.ok) return [];
74 return (manifest.value.egress ?? []).filter(
75 (e) => !e.startsWith("*.") && e.includes(":"),
76 );
77 }
78
79 export async function grantEgress(
80 app: App,
81 actor: User | undefined,
82 repo: Repo,
83 entry: string,
84 ): Promise<Result<EgressGrant, GrantError>> {
85 if (!siteAdmin(actor)) return err("not_found");
86 const wanted = entry.trim().toLowerCase();
87 if (!(await privateAsks(app, repo)).includes(wanted)) return err("not_asked");
88 const at = wanted.lastIndexOf(":");
89 const host = wanted.slice(0, at);
90 const port = Number(wanted.slice(at + 1));
91 let address = host;
92 if (isIP(host) === 0) {
93 try {
94 address = (await lookup(host)).address;
95 } catch {
96 return err("unresolved");
97 }
98 }
99 if (isPublicAddress(address)) return err("public");
100 if (!grantable(address)) return err("never");
101 const grant = { entry: wanted, host, port, address, grantedBy: actor.id };
102 putEgressGrant(app.db, repo.id, grant);
103 app.bus.append({
104 kind: "app.egress.granted",
105 repoId: repo.id,
106 actorId: actor.id,
outdated

This logs the raw entry, but the row was deleted by entry.trim().toLowerCase(). Log the normalised value so the activity line names what was actually revoked.

107 payload: { entry: wanted, address },
108 });
109 const kept = listEgressGrants(app.db, repo.id).find((g) => g.entry === wanted);
110 return kept === undefined ? err("not_asked") : ok(kept);
111 }
112
113 export function revokeEgress(
114 app: App,
115 actor: User | undefined,
116 repo: Repo,
117 entry: string,
118 ): Result<void, "not_found"> {
119 if (!siteAdmin(actor)) return err("not_found");
120 const wanted = entry.trim().toLowerCase();
121 if (!deleteEgressGrant(app.db, repo.id, wanted)) return err("not_found");
122 app.bus.append({
123 kind: "app.egress.revoked",
124 repoId: repo.id,
125 actorId: actor.id,
126 payload: { entry: wanted },
127 });
128 return ok();
129 }
130
131 /** One ask as the JSON API and MCP say it. */
132 export function askJson(a: EgressAsk): Record<string, unknown> {
133 return {
134 entry: a.entry,
135 granted: a.grant !== null,
136 address: a.grant?.address ?? null,
137 granted_by: a.grant?.grantedBy ?? null,
138 granted_at: a.grant?.grantedAt ?? null,
139 };
140 }
src/apps/contain.ts +4 −1
@@ -36,7 +36,7 @@ import {
3636 import { availableParallelism, tmpdir } from "node:os";
3737 import { dirname, join } from "node:path";
3838 import { portInsteadOfSocket } from "../git/hook-address.ts";
39 import { relay, startEgress, type Egress } from "./egress.ts";
39 import { relay, startEgress, type Egress, type PrivateGrant } from "./egress.ts";
4040 import { cgroupHost, enterArgv, openCellCgroup } from "./cgroup.ts";
4141
4242 /** `ceiling`: a declaration was cut to the machine's maximum; `declared`: forge.json's own; `default`: neither. */
@@ -198,6 +198,8 @@ export interface CellSpec {
198198 * environment's (`egressMode`) when the caller has none.
199199 */
200200 readonly egressMode?: "enforce" | "report" | undefined;
201 /** Private destinations a site admin granted the repository, pinned to their addresses. */
202 readonly granted?: readonly PrivateGrant[] | undefined;
201203 /**
202204 * Whose cell this is, for the machine sampler (`boards/sampler.ts`):
203205 * `check:<run id>` or `app:<slug>/<env>`. An unlabelled cell is watched
@@ -360,6 +362,7 @@ export function openCell(
360362 {
361363 hosts: spec.egress,
362364 origins,
365 granted: spec.granted,
363366 report:
364367 (spec.egressMode ?? egressMode()) === "report"
365368 ? (host, port) => spec.onUndeclared?.(host, port)
src/apps/egress.ts +88 −3
@@ -11,6 +11,13 @@
1111 * the forge's own origin. The connection goes to the address that was
1212 * checked, so the answer cannot change between the check and the dial.
1313 *
14 * One exception, granted by a site admin per repository: a private
15 * destination named exactly, `address:port` or `host:port`, in `forge.json`.
16 * The grant records the address it was made for, and the connection goes to
17 * that address alone, so a name that later resolves elsewhere gains nothing.
18 * Loopback, link-local (the metadata service) and the forge's own pod and
19 * service ranges can never be granted (`grantable`).
20 *
1421 * `CONNECT host:port` (what HTTPS clients send) is tunnelled; an
1522 * absolute-form request (`GET http://host/path`) is forwarded once with
1623 * `Connection: close`, so a kept-alive socket can never be pointed at a
@@ -26,6 +33,8 @@ export interface EgressPolicy {
2633 readonly hosts: readonly string[];
2734 /** Origins always reachable, at exactly this host and port (the forge). */
2835 readonly origins: readonly { host: string; port: number }[];
36 /** Private destinations a site admin granted this repository, each pinned to its address. */
37 readonly granted?: readonly PrivateGrant[] | undefined;
2938 /**
3039 * Set while egress is only reported (`FORGE_CELLS_EGRESS=report`): an
3140 * undeclared public host is let through and handed here instead of
@@ -34,6 +43,12 @@ export interface EgressPolicy {
3443 readonly report?: ((host: string, port: number) => void) | undefined;
3544 }
3645
46 export interface PrivateGrant {
47 readonly host: string;
48 readonly port: number;
49 readonly address: string;
50 }
51
3752 export interface Egress {
3853 close(): void;
3954 }
@@ -92,11 +107,61 @@ export function isPublicAddress(address: string): boolean {
92107 return false;
93108 }
94109
110 const ipv4 = (ip: string): number =>
111 ip.split(".").reduce((n, part) => n * 256 + Number(part), 0);
112
113 /** Whether an IPv4 address is inside `cidr` (`a.b.c.d/n`, or one address). */
114 function inRange(ip: string, cidr: string): boolean {
115 const [base = "", bits] = cidr.split("/");
116 if (isIP(base) !== 4 || isIP(ip) !== 4) return false;
117 const n = bits === undefined ? 32 : Number(bits);
118 if (!Number.isInteger(n) || n < 0 || n > 32) return false;
119 const size = 2 ** (32 - n);
120 return Math.floor(ipv4(ip) / size) === Math.floor(ipv4(base) / size);
121 }
122
123 /**
124 * Whether a site admin may grant this address at all. Never: this machine,
125 * link-local (cloud metadata at 169.254.169.254), multicast and the
126 * unspecified address, nor the forge's own pod and service ranges
127 * (`FORGE_EGRESS_NEVER`, comma-separated CIDRs, and the cluster's service
128 * host when there is one). Not an address at all is not grantable either.
129 */
130 export function grantable(
131 address: string,
132 env: Record<string, string | undefined> = process.env,
133 ): boolean {
134 const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address);
135 const ip = mapped?.[1] ?? address;
136 if (isIP(ip) === 4) {
137 const [a = 0, b = 0] = ip.split(".").map(Number);
138 if (a === 0 || a === 127 || a >= 224) return false;
139 if (a === 169 && b === 254) return false;
140 const never = [
141 ...(env["FORGE_EGRESS_NEVER"] ?? "").split(","),
142 env["KUBERNETES_SERVICE_HOST"] ?? "",
143 ]
144 .map((c) => c.trim())
145 .filter((c) => c !== "");
146 return !never.some((c) => inRange(ip, c));
147 }
148 if (isIP(ip) === 6) {
149 const lower = ip.toLowerCase();
150 if (lower === "::" || lower === "::1") return false;
151 if (/^fe[89ab]/.test(lower) || lower.startsWith("ff")) return false;
152 return true;
153 }
154 return false;
155 }
156
157 const PRIVATE_WAY =
158 'add it to forge.json "egress" as host:port and ask a site admin to grant it';
159
95160 type Verdict =
96161 | { ok: true; address: string; undeclared: boolean }
97162 | { ok: false; why: string };
98163
99 async function decide(
164 export async function decide(
100165 policy: EgressPolicy,
101166 host: string,
102167 port: number,
@@ -106,13 +171,26 @@ async function decide(
106171 (o) => o.host.toLowerCase() === name && o.port === port,
107172 );
108173 const declared = origin || hostAllowed(policy.hosts, name, port);
174 // A grant counts only while forge.json still names that exact entry, and
175 // sends the connection to the address it was made for, not to a lookup.
176 const grant = policy.granted?.find(
177 (g) => g.host === name && g.port === port,
178 );
179 if (
180 grant !== undefined &&
181 policy.hosts.some((h) => h.toLowerCase() === `${name}:${port}`) &&
182 grantable(grant.address)
183 )
184 return { ok: true, address: grant.address, undeclared: false };
109185 // Reporting lets an undeclared host through (and says so) on the web
110186 // ports alone; any other port, and any private address (below), is
111187 // refused in both modes.
112188 if (!declared && (policy.report === undefined || !WEB_PORTS.includes(port)))
113189 return {
114190 ok: false,
115 why: `${name}:${port} is not in this repository's egress (forge.json "egress")`,
191 why: `${name}:${port} is not in this repository's egress (forge.json "egress")${
192 isIP(name) !== 0 && !isPublicAddress(name) ? `; to reach a private address, ${PRIVATE_WAY}` : ""
193 }`,
116194 };
117195 let addresses: string[];
118196 try {
@@ -124,7 +202,14 @@ async function decide(
124202 if (first === undefined)
125203 return { ok: false, why: `${name} does not resolve` };
126204 if (!origin && !addresses.every(isPublicAddress))
127 return { ok: false, why: `${name} resolves to a private address` };
205 return {
206 ok: false,
207 why: `${name} resolves to a private address; ${
208 policy.hosts.some((h) => h.toLowerCase() === `${name}:${port}`)
209 ? `it is in forge.json "egress", so ask a site admin to grant ${name}:${port}`
210 : PRIVATE_WAY
211 }`,
212 };
128213 return { ok: true, address: first, undeclared: !declared };
129214 }
130215
src/apps/process.ts +5
@@ -10,6 +10,7 @@
1010 * app, not to a shell that would swallow it.
1111 */
1212
13 import type { PrivateGrant } from "./egress.ts";
1314 import type { AppManifest } from "./manifest.ts";
1415 import type { EnvName } from "./data.ts";
1516 import { envPull } from "./data.ts";
@@ -80,6 +81,8 @@ export interface CellBase {
8081 readonly onUndeclared?: ((host: string, port: number) => void) | undefined;
8182 /** The egress mode, as the forge's setting says at this start. */
8283 readonly egressMode?: "enforce" | "report" | undefined;
84 /** Private destinations a site admin granted the repository (#3369). */
85 readonly granted?: readonly PrivateGrant[] | undefined;
8386 /** Whose cell, for the machine sampler: `app:<slug>/<env>`. */
8487 readonly label?: string | undefined;
8588 }
@@ -348,6 +351,7 @@ export function stepCell(input: StartInput): CellSpec | undefined {
348351 limits: resolveLimits("step", undefined),
349352 onUndeclared: base.onUndeclared,
350353 egressMode: base.egressMode,
354 granted: base.granted,
351355 label: base.label,
352356 };
353357 }
@@ -421,6 +425,7 @@ export async function startProcess(
421425 listen: port,
422426 onUndeclared: input.cell.onUndeclared,
423427 egressMode: input.cell.egressMode,
428 granted: input.cell.granted,
424429 label: input.cell.label,
425430 },
426431 log,
src/apps/runtime.ts +3
@@ -86,6 +86,7 @@ import {
8686 import { parseManifest, type AppManifest } from "./manifest.ts";
8787 import { identityKey } from "./proxy.ts";
8888 import { noteReached } from "./egress_report.ts";
89 import { listEgressGrants } from "../core/egress_grants.ts";
8990 import { egressSetting } from "../core/capacity.ts";
9091 import { noteProtection } from "../kernel/protection.ts";
9192 import { cellsAvailable, resolveLimits, type CellSpec } from "./contain.ts";
@@ -1404,6 +1405,7 @@ export class AppsRuntime {
14041405 noteReached(dataDir, record.repoId, host, port),
14051406 // Asked at every start: an admin's flip reaches the next cell.
14061407 egressMode: egressSetting(this.app.db),
1408 granted: listEgressGrants(this.app.db, record.repoId),
14071409 label: `app:${record.slug}/${env}`,
14081410 };
14091411 }
@@ -1454,6 +1456,7 @@ export class AppsRuntime {
14541456 terminal: true,
14551457 onUndeclared: base.onUndeclared,
14561458 egressMode: base.egressMode,
1459 granted: base.granted,
14571460 label: base.label,
14581461 },
14591462 };
src/core/egress_grants.ts added +74
@@ -0,0 +1,74 @@
1 /**
2 * Egress grants — the rows. A repository's forge.json may ask for a private
3 * destination by exact `host:port`; it is inert until a site admin grants
4 * it, and the grant keeps the address it was made for, who made it and when
5 * (`apps/egress.ts` connects to that address alone). Pure data: no authz.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import type { PrivateGrant } from "../apps/egress.ts";
10
11 export interface EgressGrant extends PrivateGrant {
12 readonly entry: string;
13 readonly grantedBy: string | null;
14 readonly grantedAt: string;
15 }
16
17 interface Row {
18 entry: string;
19 host: string;
20 port: number;
21 address: string;
22 granted_by: string | null;
23 granted_at: string;
24 }
25
26 export function listEgressGrants(db: Database, repoId: string): EgressGrant[] {
27 return db
28 .query<Row, [string]>(
29 `SELECT entry, host, port, address, granted_by, granted_at
30 FROM egress_grant WHERE repo_id = ?1 ORDER BY entry`,
31 )
32 .all(repoId)
33 .map((r) => ({
34 entry: r.entry,
35 host: r.host,
36 port: r.port,
37 address: r.address,
38 grantedBy: r.granted_by,
39 grantedAt: r.granted_at,
40 }));
41 }
42
43 export function putEgressGrant(
44 db: Database,
45 repoId: string,
46 grant: Omit<EgressGrant, "grantedAt">,
47 at: string = new Date().toISOString(),
48 ): void {
49 db.query(
50 `INSERT OR REPLACE INTO egress_grant
51 (repo_id, entry, host, port, address, granted_by, granted_at)
52 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)`,
53 ).run(
54 repoId,
55 grant.entry,
56 grant.host,
57 grant.port,
58 grant.address,
59 grant.grantedBy,
60 at,
61 );
62 }
63
64 export function deleteEgressGrant(
65 db: Database,
66 repoId: string,
67 entry: string,
68 ): boolean {
69 return (
70 db
71 .query("DELETE FROM egress_grant WHERE repo_id = ?1 AND entry = ?2")
72 .run(repoId, entry).changes > 0
73 );
74 }
src/core/event_audience.ts +1
@@ -36,6 +36,7 @@ export function eventAudience(kind: string): EventAudience {
3636 kind.startsWith("webhook.") ||
3737 kind.startsWith("app.env_") ||
3838 kind.startsWith("app.domain.") ||
39 kind.startsWith("app.egress.") ||
3940 kind.startsWith("prompt.") ||
4041 kind.startsWith("secret.") ||
4142 // The forge's mail ceiling is its owner's to hear (`actions/mail.ts`).
src/core/migrations/20261020130000-egress-grants.ts added +15
@@ -0,0 +1,15 @@
1 // A private destination an app asked for in forge.json `egress`, granted by
2 // a site admin (#3369): one exact host:port per repository, with the address
3 // it was granted for, who granted it and when. Additive.
4 export default `
5 CREATE TABLE egress_grant (
6 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
7 entry TEXT NOT NULL,
8 host TEXT NOT NULL,
9 port INTEGER NOT NULL,
10 address TEXT NOT NULL,
11 granted_by TEXT REFERENCES user(id) ON DELETE SET NULL,
12 granted_at TEXT NOT NULL,
13 PRIMARY KEY (repo_id, entry)
14 );
15 `;
src/design/activity.ts +7
@@ -58,6 +58,13 @@ export function eventVerb(event: ForgeEvent): string {
5858 ? `set ${which} in the app's environment`
5959 : `removed ${which} from the app's environment`;
6060 }
61 if (kind.startsWith("app.egress.")) {
62 const entry = payload["entry"];
63 const which = typeof entry === "string" ? entry : "a private destination";
64 return kind === "app.egress.granted"
65 ? `granted the app ${which}`
66 : `revoked the app's ${which}`;
67 }
6168 if (kind.startsWith("app.domain.")) {
6269 const host = payload["host"];
6370 const which = typeof host === "string" ? host : "a domain";
src/http/api.ts +58
@@ -272,6 +272,13 @@ import {
272272 listAppDomains,
273273 removeAppDomain,
274274 } from "../actions/domains.ts";
275 import {
276 GRANT_WORDS,
277 askJson,
278 grantEgress,
279 listEgress,
280 revokeEgress,
281 } from "../actions/egress_grants.ts";
275282 import {
276283 addPromptSource,
277284 listPromptSources,
@@ -5226,6 +5233,57 @@ export function apiRoutes(router: Router<Handler>): void {
52265233 },
52275234 );
52285235
5236 // Private destinations forge.json asks for, and a site admin's grant of
5237 // them (docs/APPS.md, "egress"). Reading is a repository admin's; granting
5238 // and revoking are a site admin's, and the action says so. `:entry` is one
5239 // path segment, `host:port`.
5240 router.add("GET", "/api/v1/repos/:owner/:name/app/egress", async (ctx) => {
5241 const denied = requireScope(ctx, "admin");
5242 if (denied) return denied;
5243 const repo = loadRepo(ctx);
5244 if (!repo) return notFound();
5245 const listed = await listEgress(ctx.app, ctx.auth.user, repo);
5246 if (!listed.ok) return respondAccess(listed.error, 422);
5247 return json({ items: listed.value.map(askJson), next_cursor: null });
5248 });
5249
5250 router.add("POST", "/api/v1/repos/:owner/:name/app/egress", async (ctx) => {
5251 const denied = requireScope(ctx, "admin");
5252 if (denied) return denied;
5253 const repo = loadRepo(ctx);
5254 if (!repo) return notFound();
5255 const input = await body(ctx.request);
5256 const granted = await grantEgress(
5257 ctx.app,
5258 ctx.auth.user,
5259 repo,
5260 str(input.entry),
5261 );
5262 if (!granted.ok)
5263 return granted.error === "not_found"
5264 ? notFound()
5265 : apiError(granted.error, 422, GRANT_WORDS[granted.error]);
5266 return json(
5267 askJson({ entry: granted.value.entry, grant: granted.value }),
5268 201,
5269 );
5270 });
5271
5272 router.add("DELETE", "/api/v1/repos/:owner/:name/app/egress/:entry", (ctx) => {
5273 const denied = requireScope(ctx, "admin");
5274 if (denied) return denied;
5275 const repo = loadRepo(ctx);
5276 if (!repo) return notFound();
5277 const revoked = revokeEgress(
5278 ctx.app,
5279 ctx.auth.user,
5280 repo,
5281 ctx.params.entry ?? "",
5282 );
5283 if (!revoked.ok) return respondAccess(revoked.error, 422);
5284 return json({}, 200);
5285 });
5286
52295287 // Where the crew's next tell comes from when nobody is typing
52305288 // (docs/APPS.md, "Prompts from Instagram"). Admin scope and admin over
52315289 // the repository; the token goes in once and never comes back out.
src/http/mcp.ts +58
@@ -169,6 +169,14 @@ import {
169169 readAppMembers,
170170 setAppMembersThrough,
171171 } from "../actions/app_members.ts";
172 import {
173 GRANT_WORDS,
174 askJson,
175 grantEgress,
176 listEgress,
177 revokeEgress,
178 siteAdmin,
179 } from "../actions/egress_grants.ts";
172180 import {
173181 explore,
174182 exploreLine,
@@ -1875,6 +1883,56 @@ const TOOLS: readonly Tool[] = [
18751883 return answer(setAppMembersThrough(ctx.app, user, repo, { members, dryRun }));
18761884 },
18771885 },
1886 {
1887 name: "app_egress",
1888 description:
1889 "The private destinations an app's forge.json `egress` asks for (exact `host:port` entries: a machine on a tailnet or LAN) and whether a site admin has granted each. Without `entry`, the list. With `entry` and no `revoke`, the grant it would make; with `revoke: true`, the revoking; with dryRun false, made — by a site admin who is a person, with an admin-scope token. A grant pins the app to the address it resolved to when granted; loopback, link-local (cloud metadata) and the forge's own network can never be granted. The same as the app's settings page and /api/v1/repos/:owner/:name/app/egress.",
1890 inputSchema: {
1891 type: "object",
1892 properties: {
1893 repo: REPO_ARG,
1894 entry: { type: "string", maxLength: 260 },
1895 revoke: { type: "boolean" },
1896 dryRun: { type: "boolean" },
1897 },
1898 required: ["repo"],
1899 },
1900 writes: true,
1901 dryByDefault: true,
1902 async run(ctx, user, args) {
1903 const repo = repoArg(ctx, user, args);
1904 if (isAnswer(repo)) return repo;
1905 const entry = str(args["entry"]).toLowerCase();
1906 if (entry === "") {
1907 const listed = await listEgress(ctx.app, user, repo);
1908 return listed.ok
1909 ? good({ asks: listed.value.map(askJson) })
1910 : bad("not_found", "no such app or repository (owner/name)");
1911 }
1912 const asks = await listEgress(ctx.app, user, repo);
1913 if (!asks.ok) return bad("not_found", "no such app or repository (owner/name)");
1914 const asked = asks.value.find((a) => a.entry === entry);
1915 if (asked === undefined) return bad("invalid", GRANT_WORDS.not_asked);
1916 if (!siteAdmin(user)) return bad("forbidden", GRANT_WORDS.not_found);
1917 const revoke = args["revoke"] === true;
1918 if (args["dryRun"] !== false)
1919 return good({
1920 would: revoke ? "revoke" : "grant",
1921 entry,
1922 granted: asked.grant !== null,
1923 });
1924 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
1925 return bad("forbidden", "changing a grant needs an admin-scope token");
1926 if (revoke) {
1927 const done = revokeEgress(ctx.app, user, repo, entry);
1928 return done.ok ? good({ revoked: entry }) : bad("not_found", "that entry is not granted");
1929 }
1930 const granted = await grantEgress(ctx.app, user, repo, entry);
1931 return granted.ok
1932 ? good(askJson({ entry, grant: granted.value }))
1933 : bad(granted.error, GRANT_WORDS[granted.error]);
1934 },
1935 },
18781936 {
18791937 name: "explore",
18801938 description:
src/http/server.ts +4
@@ -356,6 +356,8 @@ import {
356356 appDomainCheck,
357357 appDomainDelete,
358358 appEnvDelete,
359 appEgressGrant,
360 appEgressRevoke,
359361 appEnvSet,
360362 appSettingsPage,
361363 appSettingsUpdate,
@@ -1333,6 +1335,8 @@ export function buildRouter(): Router<Handler> {
13331335 router.add("POST", "/:owner/:name/settings/app", appSettingsUpdate);
13341336 router.add("POST", "/:owner/:name/settings/app/disable", appDisable);
13351337 router.add("POST", "/:owner/:name/settings/app/members", appMembersUpdate);
1338 router.add("POST", "/:owner/:name/settings/app/egress", appEgressGrant);

This is the only way in. Add the matching /api/v1/repos/:owner/:name/app/egress routes in http/api.ts (with an MCP tool) and a terminal screen next to tui/screens/domains.ts, all calling the same grantEgress and revokeEgress.

1339 router.add("POST", "/:owner/:name/settings/app/egress/revoke", appEgressRevoke);
13361340 router.add("POST", "/:owner/:name/settings/app/env", appEnvSet);
13371341 router.add(
13381342 "POST",
src/tui/screens/egress.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * An app's private destinations in the terminal (#3369): the exact
3 * `host:port` entries forge.json `egress` asks for, as the app's settings page
4 * lists them. `g` grants the selected one and `x` revokes it. Both go through
5 * the actions, so the gate is theirs: only a site admin who is a person
6 * grants; anyone else reads the list and is told so.
7 */
8
9 import { GRANT_WORDS, grantEgress, listEgress, revokeEgress, siteAdmin, type EgressAsk } from "../../actions/egress_grants.ts";
10 import type { Repo } from "../../core/repos.ts";
11 import type { Ctx, Screen } from "../app/app.ts";
12 import { binding } from "../app/keys.ts";
13 import { style } from "../term/style.ts";
14 import { truncate } from "../term/width.ts";
15 import type { Session } from "../session.ts";
16 import { fill, len, split } from "../ui/layout.ts";
17 import { ListState, drawList, type ListRow } from "./common.ts";
18
19 export function egressScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
20 const state = new ListState();
21 let asks: EgressAsk[] = [];
22 let loaded = false;
23 let note = "";
24
25 const read = async (): Promise<void> => {
26 const listed = await listEgress(f.app, f.user, repo);
27 asks = listed.ok ? listed.value : [];
28 loaded = true;
29 state.clamp(asks.length);
30 ctx.invalidate();
31 };
32
33 const rows = (): ListRow[] =>
34 asks.map((a) => ({
35 title: a.entry,
36 secondary: a.grant === null ? "asked for" : "granted",
37 meta:
38 a.grant === null
39 ? "refused until a site admin grants it"
40 : `at ${a.grant.address} · ${a.grant.grantedAt.slice(0, 16).replace("T", " ")} UTC`,
41 }));
42
43 const act = async (grant: boolean): Promise<void> => {
44 const ask = asks[state.index];
45 if (ask === undefined) return;
46 if (!siteAdmin(f.user)) note = GRANT_WORDS.not_found;
47 else if (grant) {
48 const done = await grantEgress(f.app, f.user, repo, ask.entry);
49 note = done.ok ? `Granted ${ask.entry} at ${done.value.address}.` : GRANT_WORDS[done.error];
50 } else {
51 note = revokeEgress(f.app, f.user, repo, ask.entry).ok ? `Revoked ${ask.entry}.` : "That entry is not granted.";
52 }
53 await read();
54 };
55
56 return {
57 title: "Private destinations",
58 keys: [binding(["j", "k"], "move cursor"), binding(["g"], "grant"), binding(["x"], "revoke")],
59 load: read,
60 render(area, s) {
61 const c = ctx.theme.c;
62 const [head, body] = split(area, "v", [len(1), fill(1)]);
63 const text =
64 note !== ""
65 ? note
66 : !loaded
67 ? "Loading…"
68 : asks.length === 0
69 ? "forge.json egress asks for no host:port."
70 : `${repo.ownerName}/${repo.name} · a site admin grants each entry (g), or revokes it (x)`;
71 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
72 drawList(s, body!, c, state, rows());
73 },
74 key(e) {
75 note = "";
76 if (state.key(e, asks.length)) return true;
77 if (e.ctrl || e.alt) return false;
78 if (e.key !== "g" && e.key !== "x") return false;
79 void act(e.key === "g");
80 return true;
81 },
82 };
83 }
src/tui/screens/workspace.ts +8
@@ -95,6 +95,7 @@ import { canSeeAnswers } from "../../web/studio/answers.ts";
9595 import { answersScreen } from "./answers.ts";
9696 import { commitsScreen } from "./commits.ts";
9797 import { deploysScreen } from "./deploys.ts";
98 import { egressScreen } from "./egress.ts";
9899 import {
99100 Filter,
100101 ListState,
@@ -1303,6 +1304,9 @@ export function workspaceScreen(
13031304 ...(repo !== undefined && canSeeAnswers(f.db, repo, f.user)
13041305 ? [binding(["a"], "your tells and the crew's answers")]
13051306 : []),
1307 ...(repo !== undefined && admin()
1308 ? [binding(["G"], "private destinations the app asks for")]
1309 : []),
13061310 ...(repo !== undefined && admin()
13071311 ? [binding(["R"], `decisions by ${(getRepoById(f.db, repo.id) ?? repo).decisionsBy} (cycle)`)]
13081312 : []),
@@ -1629,6 +1633,10 @@ export function workspaceScreen(
16291633 ctx.push(deploysScreen(f, ctx, repo));
16301634 return true;
16311635 }
1636 if (plain && e.key === "G" && repo !== undefined && admin()) {
1637 ctx.push(egressScreen(f, ctx, repo));
1638 return true;
1639 }
16321640 if (plain && e.key === "a" && repo !== undefined && canSeeAnswers(f.db, repo, f.user)) {
16331641 ctx.push(answersScreen(f, ctx, repo));
16341642 return true;
src/web/pages/settings.ts +113 −2
@@ -8,6 +8,15 @@
88 * same-origin POST and every one of them says what happened.
99 */
1010
11 import {
12 GRANT_WORDS,
13 grantEgress,
14 privateAsks,
15 revokeEgress,
16 siteAdmin,
17 } from "../../actions/egress_grants.ts";
18 import { listEgressGrants } from "../../core/egress_grants.ts";
19 import { getUserById } from "../../core/users.ts";
1120 import { appLimitWords } from "../../actions/app_limit.ts";
1221 import {
1322 deleteAppEnvVar,
@@ -490,6 +499,7 @@ function appSettingsView(
490499 repo: Repo,
491500 record: AppRecord | undefined,
492501 values: AppValues,
502 asks: readonly string[] = [],
493503 error?: string,
494504 ): Html {
495505 const base = repoBase(repo);
@@ -595,6 +605,10 @@ function appSettingsView(
595605 <div class="mt">
596606 ${appEnvView(base, listAppEnvNames(ctx.app.db, record.id))}
597607 </div>
608 ${when(
609 asks.length > 0,
610 () => html`<div class="mt">${appEgressView(ctx, repo, asks)}</div>`,
611 )}
598612 <div class="mt">
599613 ${appDomainsView(base, domains.ok ? domains.value : undefined)}
600614 </div>
@@ -660,6 +674,69 @@ export function appVisitorsView(v: AppVitals): Html {
660674 );
661675 }
662676
677 /** forge.json's exact host:port entries: inert until a site admin grants them. */
678 function appEgressView(ctx: Ctx, repo: Repo, asks: readonly string[]): Html {
679 const base = repoBase(repo);
outdated

siteAdmin in actions/egress_grants.ts also requires kind === "user". Export that predicate and use it here, so the page offers Grant only to someone the action will accept.

680 const admin = siteAdmin(ctx.auth.user);
681 const granted = new Map(
682 listEgressGrants(ctx.app.db, repo.id).map((g) => [g.entry, g]),
683 );
684 const rows = asks.map((entry) => {
685 const g = granted.get(entry);
686 const by =
687 g?.grantedBy == null ? undefined : getUserById(ctx.app.db, g.grantedBy);
688 return row({
689 lead: icon("key"),
690 title: html`<span class="mono">${entry}</span>`,
691 meta:
692 g === undefined
693 ? html`asked for, not granted: a private address stays refused`
694 : html`granted to <span class="mono">${g.address}</span> by
695 ${by?.username ?? "a site admin"} ${time(g.grantedAt)}`,
696 trail: !admin
697 ? html``
outdated

DESIGN.md §5: .row-actions is for secondary actions (delete, revoke). Grant is this row's primary control, so put it in .row-fields and wrap the list in setting-list. That way the long "granted to … by … time" meta wraps instead of being ellipsized.

698 : g === undefined
699 ? html`<form
700 class="row-fields"
701 method="post"
702 action="${base}/settings/app/egress"
703 >
704 <input type="hidden" name="entry" value="${entry}" />
705 ${btn("Grant", {
706 size: "sm",
707 variant: "primary",
708 label: `Grant ${entry}`,
709 })}
710 </form>`
711 : html`<form
712 class="row-actions"
713 method="post"
714 action="${base}/settings/app/egress/revoke"
715 >
716 <input type="hidden" name="entry" value="${entry}" />
717 ${btn("Revoke", { size: "sm", label: `Revoke ${entry}` })}
718 </form>`,
719 });
720 });
721 return card(
722 html`<div class="card-body">
723 <p class="muted small">
724 Private destinations asked for: exact <span class="mono">host:port</span>
725 entries in <span class="mono">forge.json</span> egress. A site admin
726 grants each one for this repository; the app then reaches that
727 address and port and nothing else on it.
728 </p>
729 </div>
730 <ul class="list setting-list">
731 ${rows}
732 </ul>`,
733 {
734 head: html`${icon("key")}<h2>Private destinations asked for</h2>`,
735 pad: false,
736 },
737 );
738 }
739
663740 function appEnvView(base: string, names: AppEnvName[]): Html {
664741 const rows = names.map((v) =>
665742 row({
@@ -893,12 +970,13 @@ const appValues = (repo: Repo, record: AppRecord | undefined): AppValues => ({
893970 });
894971
895972 // GET /:owner/:name/settings/app
896 export function appSettingsPage(ctx: Ctx): Response {
973 export async function appSettingsPage(ctx: Ctx): Promise<Response> {
897974 const repo = loadAdminRepo(ctx);
898975 if (!repo) return repoNotFound(ctx);
899976 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
900977 const record = getAppByRepo(ctx.app.db, repo.id);
901 const view = appSettingsView(ctx, repo, record, appValues(repo, record));
978 const asks = record === undefined ? [] : await privateAsks(ctx.app, repo);
979 const view = appSettingsView(ctx, repo, record, appValues(repo, record), asks);
902980 const rendering = performance.now();
903981 const response = settingsPageResponse(ctx, repo, "app", "App", view);
904982 notePhase(ctx.request, "render", performance.now() - rendering);
@@ -932,6 +1010,7 @@ export async function appSettingsUpdate(ctx: Ctx): Promise<Response> {
9321010 repo,
9331011 record,
9341012 values,
1013 record === undefined ? [] : await privateAsks(ctx.app, repo),
9351014 saved.error === "app_limit"
9361015 ? appLimitWords(ctx.app, repo.ownerId)
9371016 : (APP_ERRORS[saved.error] ?? "Those settings could not be saved."),
@@ -1090,6 +1169,38 @@ function recordsInWords(records: DnsRecord[]): string {
10901169 .join(" and ");
10911170 }
10921171
1172 // POST /:owner/:name/settings/app/egress — a site admin grants one entry.
1173 export async function appEgressGrant(ctx: Ctx): Promise<Response> {
1174 const gate = await adminForm(ctx);
1175 if (gate instanceof Response) return gate;
1176 const { repo, form } = gate;
1177 const entry = field(form, "entry");
1178 const granted = await grantEgress(ctx.app, ctx.auth.user, repo, entry);
1179 if (!granted.ok && granted.error === "not_found") return repoNotFound(ctx);
1180 return flashTo(
1181 ctx,
1182 `${repoBase(repo)}/settings/app`,
1183 granted.ok
1184 ? {
1185 message: `${granted.value.entry} is granted at ${granted.value.address}. The app reaches it from its next start.`,
1186 }
1187 : { tone: "danger", message: GRANT_WORDS[granted.error] },
1188 );
1189 }
1190
1191 // POST /:owner/:name/settings/app/egress/revoke
1192 export async function appEgressRevoke(ctx: Ctx): Promise<Response> {
1193 const gate = await adminForm(ctx);
1194 if (gate instanceof Response) return gate;
1195 const { repo, form } = gate;
1196 const entry = field(form, "entry");
1197 const revoked = revokeEgress(ctx.app, ctx.auth.user, repo, entry);
1198 if (!revoked.ok) return repoNotFound(ctx);
1199 return flashTo(ctx, `${repoBase(repo)}/settings/app`, {
1200 message: `${entry} is revoked. The app is refused it from its next start.`,
1201 });
1202 }
1203
10931204 // POST /:owner/:name/settings/app/domains — add one.
10941205 export async function appDomainAdd(ctx: Ctx): Promise<Response> {
10951206 const gate = await adminForm(ctx);
test/egress-grants.test.ts added +171
@@ -0,0 +1,171 @@
1 /**
2 * A private destination an app asked for in forge.json `egress` (#3369):
3 * inert until a site admin grants it, then reachable at exactly that
4 * address and port, never wider, and some addresses can never be granted.
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 {
13 grantEgress,
14 privateAsks,
15 revokeEgress,
16 } from "../src/actions/egress_grants.ts";
17 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
18 import { decide, grantable } from "../src/apps/egress.ts";
19 import { parseManifest } from "../src/apps/manifest.ts";
20 import { listEgressGrants } from "../src/core/egress_grants.ts";
21 import { listEvents } from "../src/core/events.ts";
22 import { eventAudience } from "../src/core/event_audience.ts";
23 import type { Repo } from "../src/core/repos.ts";
24 import { createUser, type User } from "../src/core/users.ts";
25
26 const ENTRY = "100.89.95.68:8101";
27 const asked = { hosts: [ENTRY], origins: [] };
28 const granted = [{ host: "100.89.95.68", port: 8101, address: "100.89.95.68" }];
29
30 describe("egress: a private destination, by exact address and port", () => {
31 test("declared but ungranted is refused, and the refusal says what to do", async () => {
32 const v = await decide(asked, "100.89.95.68", 8101);
33 expect(v.ok).toBe(false);
34 if (!v.ok) {
35 expect(v.why).toContain("resolves to a private address");
36 expect(v.why).toContain("ask a site admin to grant 100.89.95.68:8101");
37 }
38 const undeclared = await decide({ hosts: [], origins: [] }, "100.89.95.68", 8101);
39 expect(!undeclared.ok && undeclared.why).toContain(
40 'add it to forge.json "egress" as host:port and ask a site admin to grant it',
41 );
42 });
43
44 test("granted connects, to the granted address", async () => {
45 const v = await decide({ ...asked, granted }, "100.89.95.68", 8101);
46 expect(v).toEqual({ ok: true, address: "100.89.95.68", undeclared: false });
47 });
48
49 test("a grant to :8101 does not open :22, a neighbour, or a name the grant was not for", async () => {
50 const policy = { ...asked, granted };
51 expect((await decide(policy, "100.89.95.68", 22)).ok).toBe(false);
52 expect((await decide(policy, "100.89.95.69", 8101)).ok).toBe(false);
53 expect((await decide(policy, "localhost", 8101)).ok).toBe(false);
54 });
55
56 test("a grant is inert once forge.json no longer names the entry", async () => {
57 const v = await decide({ hosts: [], origins: [], granted }, "100.89.95.68", 8101);
58 expect(v.ok).toBe(false);
59 });
60
61 test("a granted name is pinned to its granted address, not to a lookup", async () => {
62 const policy = {
63 hosts: ["localhost:9000"],
64 origins: [],
65 granted: [{ host: "localhost", port: 9000, address: "100.64.0.7" }],
66 };
67 const v = await decide(policy, "localhost", 9000);
68 expect(v).toEqual({ ok: true, address: "100.64.0.7", undeclared: false });
69 });
70
71 test("metadata, loopback and the forge's own ranges can never be granted", async () => {
72 expect(grantable("169.254.169.254")).toBe(false);
73 expect(grantable("127.0.0.1")).toBe(false);
74 expect(grantable("::1")).toBe(false);
75 expect(grantable("0.0.0.0")).toBe(false);
76 expect(grantable("100.89.95.68")).toBe(true);
77 const env = { FORGE_EGRESS_NEVER: "10.42.0.0/16, 10.43.0.1", KUBERNETES_SERVICE_HOST: "10.96.0.1" };
78 expect(grantable("10.42.7.9", env)).toBe(false);
79 expect(grantable("10.43.0.1", env)).toBe(false);
80 expect(grantable("10.96.0.1", env)).toBe(false);
81 expect(grantable("10.44.0.1", env)).toBe(true);
82 // Even a forged grant row does not open the metadata service.
83 const v = await decide(
84 {
85 hosts: ["169.254.169.254:80"],
86 origins: [],
87 granted: [{ host: "169.254.169.254", port: 80, address: "169.254.169.254" }],
88 },
89 "169.254.169.254",
90 80,
91 );
92 expect(v.ok).toBe(false);
93 });
94
95 test("forge.json names an exact destination, never a range or a wildcard", () => {
96 const parse = (egress: unknown) =>
97 parseManifest(JSON.stringify({ egress, app: { run: "x" } }), undefined);
98 expect(parse([ENTRY]).ok).toBe(true);
99 for (const bad of ["100.64.0.0/10", "100.*", "*:8101", "*", "100.89.95.68:0", "100.89.95.68:99999"])
100 expect(parse([bad]).ok).toBe(false);
101 });
102 });
103
104 describe("egress grants: a site admin's say", () => {
105 let dataDir: string;
106 let app: App;
107 let admin: User;
108 let other: User;
109 let repo: Repo;
110
111 beforeAll(async () => {
112 dataDir = await mkdtemp(join(tmpdir(), "forge-grants-"));
113 app = createApp({ dataDir, port: 0 });
114 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
115 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
116 if (!a.ok || !b.ok) throw new Error("users");
117 admin = a.value;
118 other = b.value;
119 const made = await createRepo(app, admin, { name: "arm", visibility: "private" });
120 if (!made.ok) throw new Error(String(made.error));
121 repo = made.value;
122 await commitToBranch(app, admin, repo, {
123 message: "ask",
124 files: [
125 {
126 path: "forge.json",
127 content: JSON.stringify({
128 app: { run: "bun run x.ts" },
129 egress: ["api.example.com", "*.example.org", ENTRY, "169.254.169.254:80", "8.8.8.8:53"],
130 }),
131 },
132 ],
133 });
134 }, 30_000);
135
136 afterAll(async () => {
137 app.close();
138 await rm(dataDir, { recursive: true, force: true });
139 });
140
141 test("the asks are the exact host:port entries only", async () => {
142 expect(await privateAsks(app, repo)).toEqual([ENTRY, "169.254.169.254:80", "8.8.8.8:53"]);
143 });
144
145 test("a person who is not a site admin cannot grant; a site admin can, and it is recorded", async () => {
146 expect((await grantEgress(app, other, repo, ENTRY)).ok).toBe(false);
147 expect(listEgressGrants(app.db, repo.id)).toEqual([]);
148 const done = await grantEgress(app, admin, repo, ENTRY);
149 expect(done.ok && done.value.address).toBe("100.89.95.68");
150 const [row] = listEgressGrants(app.db, repo.id);
151 expect(row?.entry).toBe(ENTRY);
152 expect(row?.grantedBy).toBe(admin.id);
153 expect(row?.grantedAt).toMatch(/^\d{4}-/);
154 expect(eventAudience("app.egress.granted")).toBe("admins");
155 });
156
157 test("what was not asked, what is public and what can never be granted are refused", async () => {
158 expect(await grantEgress(app, admin, repo, "100.89.95.68:22")).toEqual({ ok: false, error: "not_asked" });
159 expect(await grantEgress(app, admin, repo, "8.8.8.8:53")).toEqual({ ok: false, error: "public" });
160 expect(await grantEgress(app, admin, repo, "169.254.169.254:80")).toEqual({ ok: false, error: "never" });
161 expect(listEgressGrants(app.db, repo.id).map((g) => g.entry)).toEqual([ENTRY]);
162 });
163
164 test("revoking removes it, for a site admin alone", async () => {
165 expect(revokeEgress(app, other, repo, ENTRY).ok).toBe(false);
166 expect(revokeEgress(app, admin, repo, ` ${ENTRY.toUpperCase()} `).ok).toBe(true);
167 const last = listEvents(app.db, { repoId: repo.id }).find((e) => e.kind === "app.egress.revoked");
168 expect(last?.payload).toEqual({ entry: ENTRY });
169 expect(listEgressGrants(app.db, repo.id)).toEqual([]);
170 });
171 });
test/mcp.test.ts +1
@@ -210,6 +210,7 @@ describe("the forge over MCP", () => {
210210 "thought",
211211 "asked",
212212 "app_members",
213 "app_egress",
213214 "explore",
214215 "feed",
215216 "feed_chips",
test/web-egress.test.ts added +148
@@ -0,0 +1,148 @@
1 /**
2 * The page, the JSON API and MCP for a repository's private destinations
3 * (#3369): only a site admin grants or revokes, a cross-origin form is
4 * refused, and the card offers Grant to a site admin alone.
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 { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { createApp as insertApp } from "../src/core/apps.ts";
14 import { listEgressGrants } from "../src/core/egress_grants.ts";
15 import type { Repo } from "../src/core/repos.ts";
16 import { setMember } from "../src/core/roles.ts";
17 import { createSession } from "../src/core/sessions.ts";
18 import { createToken } from "../src/core/tokens.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22 import { seedAdmin } from "./helpers/admin.ts";
23
24 quietLogs();
25
26 const ENTRY = "100.89.95.68:8101";
27
28 describe("private destinations: page, API and MCP", () => {
29 let dataDir: string;
30 let app: App;
31 let servers: Servers;
32 let base: string;
33 let alice: User;
34 let bob: User;
35 let aliceCookie: string;
36 let bobCookie: string;
37 let mine: Repo;
38 let his: Repo;
39
40 const post = (
41 cookie: string,
42 path: string,
43 form: Record<string, string>,
44 origin = base,
45 ): Promise<Response> =>
46 fetch(`${base}${path}`, {
47 method: "POST",
48 headers: { cookie, origin },
49 body: new URLSearchParams(form),
50 redirect: "manual",
51 });
52
53 const seed = async (owner: User, name: string): Promise<Repo> => {
54 const made = await createRepo(app, owner, { name, visibility: "private" });
55 if (!made.ok) throw new Error(String(made.error));
56 await commitToBranch(app, owner, made.value, {
57 message: "ask",
58 files: [
59 {
60 path: "forge.json",
61 content: JSON.stringify({ app: { run: "bun run x.ts" }, egress: [ENTRY] }),
62 },
63 ],
64 });
65 const record = insertApp(app.db, { repoId: made.value.id, slug: name, access: "private" });
66 if (!record.ok) throw new Error(record.error);
67 return made.value;
68 };
69
70 beforeAll(async () => {
71 dataDir = await mkdtemp(join(tmpdir(), "forge-web-egress-"));
72 app = createApp({ dataDir, port: 0 });
73 servers = await serve(app);
74 base = servers.url;
75 const a = await seedAdmin(app, { username: "alice", email: "[email protected]" });
76 if (!a.ok) throw new Error(a.error);
77 alice = a.value;
78 aliceCookie = `forge_session=${createSession(app.db, alice.id).token}`;
79 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-long-egress-passphrase" });
80 if (!b.ok) throw new Error(b.error);
81 bob = b.value;
82 setMember(app.db, bob.id, true, alice.id, new Date());
83 bobCookie = `forge_session=${createSession(app.db, bob.id).token}`;
84 mine = await seed(alice, "arm");
85 his = await seed(bob, "bobs");
86 }, 30_000);
87
88 afterAll(async () => {
89 servers.stop();
90 app.close();
91 await rm(dataDir, { recursive: true, force: true });
92 });
93
94 test("a repository admin who is not a site admin is told not found, and nothing is written", async () => {
95 const response = await post(bobCookie, "/bob/bobs/settings/app/egress", { entry: ENTRY });
96 expect(response.status).toBe(404);
97 expect(listEgressGrants(app.db, his.id)).toEqual([]);
98 });
99
100 test("a cross-origin form is refused", async () => {
101 const response = await post(aliceCookie, "/alice/arm/settings/app/egress", { entry: ENTRY }, "https://evil.example");
102 expect(response.status).toBe(403);
103 expect(listEgressGrants(app.db, mine.id)).toEqual([]);
104 });
105
106 test("the card offers Grant to a site admin alone", async () => {
107 const theirs = await (await fetch(`${base}/bob/bobs/settings/app`, { headers: { cookie: bobCookie } })).text();
108 expect(theirs).toContain("Private destinations asked for");
109 expect(theirs).toContain(ENTRY);
110 expect(theirs).not.toContain("Grant</");
111 expect(theirs).not.toContain("settings/app/egress");
112 const admins = await (await fetch(`${base}/alice/arm/settings/app`, { headers: { cookie: aliceCookie } })).text();
113 expect(admins).toContain("settings/app/egress");
114 expect(admins).toContain("row-fields");
115 });
116
117 test("a site admin grants: a flash and a row; then the card names who, and Revoke removes it", async () => {
118 const response = await post(aliceCookie, "/alice/arm/settings/app/egress", { entry: ENTRY });
119 expect(response.status).toBe(303);
120 expect(decodeURIComponent(response.headers.get("set-cookie") ?? "")).toContain(`${ENTRY} is granted at 100.89.95.68`);
121 const [row] = listEgressGrants(app.db, mine.id);
122 expect(row?.address).toBe("100.89.95.68");
123 expect(row?.grantedBy).toBe(alice.id);
124 const page = await (await fetch(`${base}/alice/arm/settings/app`, { headers: { cookie: aliceCookie } })).text();
125 expect(page).toContain("alice");
126 expect(page).toContain("settings/app/egress/revoke");
127 const revoked = await post(aliceCookie, "/alice/arm/settings/app/egress/revoke", { entry: ENTRY });
128 expect(revoked.status).toBe(303);
129 expect(listEgressGrants(app.db, mine.id)).toEqual([]);
130 });
131
132 test("the JSON API lists, grants and revokes for a site admin; anyone else is not found", async () => {
133 const as = (user: User) => ({ authorization: `Bearer ${createToken(app.db, user.id, "t", "admin").token}` });
134 const url = (repo: string) => `${base}/api/v1/repos/${repo}/app/egress`;
135 const denied = await fetch(url("bob/bobs"), { method: "POST", headers: { ...as(bob), "content-type": "application/json" }, body: JSON.stringify({ entry: ENTRY }) });
136 expect(denied.status).toBe(404);
137 const listed = await (await fetch(url("bob/bobs"), { headers: as(bob) })).json() as { items: { entry: string; granted: boolean }[] };
138 expect(listed.items).toEqual([expect.objectContaining({ entry: ENTRY, granted: false })]);
139 const granted = await fetch(url("alice/arm"), { method: "POST", headers: { ...as(alice), "content-type": "application/json" }, body: JSON.stringify({ entry: ENTRY }) });
140 expect(granted.status).toBe(201);
141 expect(await granted.json()).toMatchObject({ entry: ENTRY, granted: true, address: "100.89.95.68" });
142 const bad = await fetch(url("alice/arm"), { method: "POST", headers: { ...as(alice), "content-type": "application/json" }, body: JSON.stringify({ entry: "100.89.95.68:22" }) });
143 expect(bad.status).toBe(422);
144 const gone = await fetch(`${url("alice/arm")}/${ENTRY}`, { method: "DELETE", headers: as(alice) });
145 expect(gone.status).toBe(200);
146 expect(listEgressGrants(app.db, mine.id)).toEqual([]);
147 });
148 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs