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

A site admin grants an app's private destinations on its settings page, and only the repository's admins hear about it #3625

Parked opened this
Closed without merging

scout/forge:scout/3621-a-site-admin-grants-an-app-s-private-des → main 6 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
17 files changed +688 −58
docs/APPS.md +10 −7
@@ -292,14 +292,17 @@ grantable. Until granted, the refusal says to add it and ask a site admin.
292292 A grant needs the exact `host:port` in `egress`: a wildcard entry such as
293293 `*.example.com:80` never opens a granted name. Grants are stored in the
294294 `egress_grant` table and read at every app start. A site admin grants
295 and revokes on the app's settings page ("Private destinations asked for",
296 which lists the exact `host:port` entries forge.json names and who granted
297 each) or with `POST`/`DELETE /api/v1/repos/:owner/:name/egress-grants`
295 and revokes on the app's settings page, under *Private destinations*
296 (`settings/app#private-destinations`; the refusal in the app's log names that
297 link), which lists the exact `host:port` entries forge.json names and who
298 granted each, or with `POST`/`DELETE /api/v1/repos/:owner/:name/egress-grants`
298299 and a `{ "destination": "100.89.95.68:8101" }` body; `GET` lists them. Anyone
299 else who administers the repository sees the list with no buttons. A
300 destination forge.json does not name is refused, and each change is an
301 `app.egress.granted` or `app.egress.revoked` event with who and when. There is
302 not yet a terminal command (#3469).
300 else who administers the repository sees "waiting for a site admin". A
301 destination forge.json does not name is refused. A change starts the app
302 again so the new cell carries it, and is an `app.egress.granted` or
303 `app.egress.revoked` event with who and when, for the repository's admins
304 only. The terminal has the same under the command palette's *Private
305 destinations* (`a` grants, `x` revokes).
303306
304307 A release that turns egress on must not break an app whose writers have
305308 not declared what it uses yet, so the operator can start it reported:
src/actions/egress.ts added +74
@@ -0,0 +1,74 @@
1 /**
2 * A site admin's yes or no to one private destination of an app, from its
3 * settings page (`actions/egress_grants.ts` holds the rules; this is the terminal's view of them). A grant takes effect at once: the app is started again, so
4 * its new cell is built with the grant (`apps/runtime.ts` `cellFor`).
5 */
6
7 import type { App } from "../app.ts";
8 import { parseManifest } from "../apps/manifest.ts";
9 import { readFileAt } from "../apps/checkout.ts";
10 import { privateDestinations, privateEntries, type PrivateDestination } from "../apps/private_destinations.ts";
11 import { getAppByRepo } from "../core/apps.ts";
12 import { EGRESS_MESSAGES, grantAppEgress, restartsApp, revokeAppEgress } from "./egress_grants.ts";
13 import { canAdmin, type Repo } from "../core/repos.ts";
14 import type { User } from "../core/users.ts";
15 import { resolveOid } from "../git/merge.ts";
16 import { repoDir } from "../git/repos.ts";
17 import { err, ok, type Result } from "../kernel/result.ts";
18
19 /** The `egress` the default branch's `forge.json` declares. */
20 export async function declaredEgress(app: App, repo: Repo): Promise<string[]> {
21 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
22 const oid = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
23 if (oid === undefined) return [];
24 const [forgeJson, packageJson] = await Promise.all([
25 readFileAt(dir, oid, "forge.json"),
26 readFileAt(dir, oid, "package.json"),
27 ]);
28 const manifest = parseManifest(forgeJson, packageJson);
29 return manifest.ok ? [...(manifest.value.egress ?? [])] : [];
30 }
31
32 /** Whether the app was started again, so the page can say so. */
33 export interface Changed {
34 readonly restarted: boolean;
35 }
36
37 /**
38 * What the app's private-destinations card and screen show: for a repository
39 * administrator, each destination and whether this actor may change it (a
40 * site admin). Anyone else gets `not_found`, as the page does.
41 */
42 export async function listDestinations(
43 app: App,
44 actor: User | undefined,
45 repo: Repo,
46 ): Promise<Result<{ rows: PrivateDestination[]; siteAdmin: boolean }, "not_found">> {
47 if (actor === undefined || !canAdmin(app.db, repo, actor)) return err("not_found");
48 if (getAppByRepo(app.db, repo.id) === undefined) return ok({ rows: [], siteAdmin: actor.isAdmin });
49 const declared = await declaredEgress(app, repo);
50 return ok({
51 rows: privateDestinations(app.db, repo.id, declared),
52 siteAdmin: actor.isAdmin,
53 });
54 }
55
56 export async function grantDestination(
57 app: App,
58 actor: User | undefined,
59 repo: Repo,
60 destination: string,
61 ): Promise<Result<Changed, string>> {
62 const done = await grantAppEgress(app, actor, repo, destination);
63 return done.ok ? ok({ restarted: restartsApp(app, repo) }) : err(EGRESS_MESSAGES[done.error]);
64 }
65
66 export async function revokeDestination(
67 app: App,
68 actor: User | undefined,
69 repo: Repo,
70 destination: string,
71 ): Promise<Result<Changed, string>> {
72 const done = revokeAppEgress(app, actor, repo, destination);
73 return done.ok ? ok({ restarted: restartsApp(app, repo) }) : err(EGRESS_MESSAGES[done.error]);
74 }
src/actions/egress_grants.ts +33
@@ -21,6 +21,8 @@ import { getUserById, type User } from "../core/users.ts";
2121 import { resolveOid } from "../git/merge.ts";
2222 import { repoDir } from "../git/repos.ts";
2323 import { err, ok, type Result } from "../kernel/result.ts";
24 import { getAppByRepo } from "../core/apps.ts";
25 import { appsRuntime } from "../apps/runtime.ts";
2426 import { requireRepoAdmin } from "./access.ts";
2527
2628 /** One destination as a page or the API shows it. */
@@ -56,6 +58,16 @@ export type EgressError =
5658 | "never_grantable"
5759 | "no_such_grant";
5860
61 export const EGRESS_MESSAGES: Record<EgressError, string> = {
62 not_found: "There is no such repository.",
63 forbidden: "Only a site admin grants or revokes a private destination.",
64 invalid_destination: "That is not an address and port.",
65 not_asked: "forge.json does not ask for that destination.",
66 never_grantable:
67 "That address can never be granted: it is this machine, link-local or the forge's own cluster.",
68 no_such_grant: "There was no grant for that destination.",
69 };
70
5971 const CHANGES_SHOWN = 8;
6072
6173 const siteAdmin = (actor: User): boolean =>
@@ -149,6 +161,25 @@ function changer(
149161 return siteAdmin(admin.value) ? ok(admin.value) : err("forbidden");
150162 }
151163
164 /**
165 * Start the app again so its new cell carries the change. Not awaited: a
166 * redeploy outlasts a request, so a failure is logged, not returned.
167 */
168 function restart(app: App, repo: Repo): boolean {
169 const record = getAppByRepo(app.db, repo.id);
170 const runtime = appsRuntime(app);
171 if (record === undefined || runtime === undefined) return false;
172 runtime.reconcileApp(record, repo, "redeploy").catch((e: unknown) => {
173 console.warn(`egress: restart of ${repo.ownerName}/${repo.name} failed: ${String(e)}`);
174 });
175 return true;
176 }
177
178 /** Whether a change to `repo`'s grants starts its app again. */
179 export function restartsApp(app: App, repo: Repo): boolean {
180 return getAppByRepo(app.db, repo.id) !== undefined && appsRuntime(app) !== undefined;
181 }
182
152183 /** Grant one destination forge.json names exactly. */
153184 export async function grantAppEgress(
154185 app: App,
@@ -171,6 +202,7 @@ export async function grantAppEgress(
171202 actorId: admin.value.id,
172203 payload: { destination: text },
173204 });
205 restart(app, repo);
174206 return ok({
175207 destination: text,
176208 asked: true,
@@ -199,5 +231,6 @@ export function revokeAppEgress(
199231 actorId: admin.value.id,
200232 payload: { destination: parsed.value.text },
201233 });
234 restart(app, repo);
202235 return ok(parsed.value.text);
203236 }
src/apps/contain.ts +3
@@ -185,6 +185,8 @@ export interface CellSpec {
185185 readonly egress: readonly string[];
186186 /** Private `host:port` destinations a site admin granted (`core/egress_grants.ts`). */
187187 readonly granted?: readonly string[] | undefined;
188 /** The settings section where a refused private destination is granted. */
189 readonly settingsUrl?: string | undefined;
188190 /** Origins always reachable: the forge's own URL. */
189191 readonly reach: readonly string[];
190192 readonly limits: Limits;
@@ -362,6 +364,7 @@ export function openCell(
362364 {
363365 hosts: spec.egress,
364366 granted: spec.granted,
367 settingsUrl: spec.settingsUrl,
365368 origins,
366369 report:
367370 (spec.egressMode ?? egressMode()) === "report"
src/apps/egress.ts +6 −2
@@ -32,6 +32,8 @@ export interface EgressPolicy {
3232 * (`core/egress_grants.ts`). One only opens when `hosts` also declares it.
3333 */
3434 readonly granted?: readonly string[] | undefined;
35 /** Where a site admin grants one (the app's settings page); named in a refusal. */
36 readonly settingsUrl?: string | undefined;
3537 /**
3638 * Set while egress is only reported (`FORGE_CELLS_EGRESS=report`): an
3739 * undeclared public host is let through and handed here instead of
@@ -113,9 +115,11 @@ export async function decide(
113115 );
114116 const declared = origin || hostAllowed(policy.hosts, name, port);
115117 const literalPrivate = isIP(name) !== 0 && !isPublicAddress(name);
118 const where =
119 policy.settingsUrl === undefined ? "" : ` at ${policy.settingsUrl}`;
116120 const askAdmin =
117121 `${name}:${port} is a private destination: ` +
118 "add it to forge.json egress and ask a site admin to grant it";
122 `add it to forge.json egress and ask a site admin to grant it${where}`;
119123 // A grant opens only a destination forge.json names exactly: a wildcard
120124 // entry declares names, it never makes one of them grantable.
121125 const granted =
@@ -146,7 +150,7 @@ export async function decide(
146150 why: literalPrivate
147151 ? askAdmin
148152 : `${name} resolves to a private address; add ${name}:${port} ` +
149 "to forge.json egress and ask a site admin to grant it",
153 `to forge.json egress and ask a site admin to grant it${where}`,
150154 };
151155 // A grant opens one destination, never the metadata service or the
152156 // forge's own cluster, whatever a name resolves to.
src/apps/private_destinations.ts added +55
@@ -0,0 +1,55 @@
1 /**
2 * The private destinations an app's settings page shows: every `forge.json`
3 * `egress` entry that is one exact private `address:port`, and whether a site
4 * admin granted it (`core/egress_grants.ts`). A grant whose entry has left
5 * `forge.json` stays listed, so it can still be revoked.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { isIP } from "node:net";
10 import { listEgressGrants } from "../core/egress_grants.ts";
11 import { getUserById } from "../core/users.ts";
12 import { isPublicAddress } from "./egress.ts";
13
14 export interface PrivateDestination {
15 readonly destination: string;
16 /** `forge.json` still names it. */
17 readonly declared: boolean;
18 readonly grantedBy: string | undefined;
19 readonly grantedAt: string | undefined;
20 }
21
22 /** The entries that are a private IPv4 address with its port. */
23 export function privateEntries(egress: readonly string[]): string[] {
24 const out: string[] = [];
25 for (const entry of egress) {
26 const at = entry.lastIndexOf(":");
27 const host = entry.slice(0, at);
28 if (at > 0 && isIP(host) === 4 && !isPublicAddress(host)) out.push(entry);
29 }
30 return [...new Set(out)];
31 }
32
33 export function privateDestinations(
34 db: Database,
35 repoId: string,
36 egress: readonly string[],
37 ): PrivateDestination[] {
38 const grants = new Map(
39 listEgressGrants(db, repoId).map((g) => [g.destination, g]),
40 );
41 const declared = privateEntries(egress);
42 const names = [...new Set([...declared, ...grants.keys()])].sort();
43 return names.map((destination) => {
44 const g = grants.get(destination);
45 return {
46 destination,
47 declared: declared.includes(destination),
48 grantedBy:
49 g === undefined
50 ? undefined
51 : (getUserById(db, g.grantedBy)?.username ?? "a site admin"),
52 grantedAt: g?.grantedAt,
53 };
54 });
55 }
src/apps/process.ts +3
@@ -80,6 +80,8 @@ export interface CellBase {
8080 readonly onUndeclared?: ((host: string, port: number) => void) | undefined;
8181 /** Private `host:port` destinations a site admin granted this repository. */
8282 readonly granted?: readonly string[] | undefined;
83 /** Where a site admin grants a refused private destination. */
84 readonly settingsUrl?: string | undefined;
8385 /** The egress mode, as the forge's setting says at this start. */
8486 readonly egressMode?: "enforce" | "report" | undefined;
8587 /** Whose cell, for the machine sampler: `app:<slug>/<env>`. */
@@ -419,6 +421,7 @@ export async function startProcess(
419421 hide: input.cell.hide,
420422 egress: manifest.egress ?? [],
421423 granted: input.cell.granted,
424 settingsUrl: input.cell.settingsUrl,
422425 reach: [input.forgeUrl],
423426 limits: resolveLimits("app", manifest.limits),
424427 listen: port,
src/apps/runtime.ts +9
@@ -1411,12 +1411,20 @@ export class AppsRuntime {
14111411 noteReached(dataDir, record.repoId, host, port),
14121412 // Asked at every start: an admin's grant reaches the next cell.
14131413 granted: grantedFor(this.app.db, record.repoId),
1414 settingsUrl: this.settingsUrl(record),
14141415 // Likewise an admin's flip of the egress mode.
14151416 egressMode: egressSetting(this.app.db),
14161417 label: `app:${record.slug}/${env}`,
14171418 };
14181419 }
14191420
1421 /** The app settings section where a refused private destination is granted. */
1422 private settingsUrl(record: AppRecord): string | undefined {
1423 const repo = getRepoById(this.app.db, record.repoId);
1424 if (repo === undefined) return undefined;
1425 return `${this.options.forgeUrl.replace(/\/$/, "")}/${repo.ownerName}/${repo.name}/settings/app#private-destinations`;
1426 }
1427
14201428 /** Say on the run, once, whether its processes were held. */
14211429 private noteCell(runId: string, write: (line: string) => void): void {
14221430 noteRunProgress(this.app.db, runId, {
@@ -1454,6 +1462,7 @@ export class AppsRuntime {
14541462 hide: base.hide,
14551463 egress: live.manifest.egress ?? [],
14561464 granted: base.granted,
1465 settingsUrl: base.settingsUrl,
14571466 // A terminal is the app's own client: it reaches the app on
14581467 // its port, as it would beside it.
14591468 reach: [
src/core/event_audience.ts +3
@@ -36,6 +36,9 @@ export function eventAudience(kind: string): EventAudience {
3636 kind.startsWith("webhook.") ||
3737 kind.startsWith("app.env_") ||
3838 kind.startsWith("app.domain.") ||
39 // A private destination is an address:port on the operator's network,
40 // and the site admin who granted it is theirs to name.
41 kind.startsWith("app.egress.") ||
3942 kind.startsWith("prompt.") ||
4043 kind.startsWith("secret.") ||
4144 // The forge's mail ceiling is its owner's to hear (`actions/mail.ts`).
src/http/server.ts +1
@@ -1344,6 +1344,7 @@ export function buildRouter(): Router<Handler> {
13441344 router.add("POST", "/:owner/:name/settings/app/disable", appDisable);
13451345 router.add("POST", "/:owner/:name/settings/app/members", appMembersUpdate);
13461346 router.add("POST", "/:owner/:name/settings/app/env", appEnvSet);
1347 // `:to` is one `host:port` segment, the colon percent-encoded or not.
13471348 router.add(
13481349 "POST",
13491350 "/:owner/:name/settings/app/env/:var/delete",
src/tui/forge.ts +9
@@ -57,6 +57,7 @@ import { canScreen } from "./screens/can.ts";
5757 import { peopleScreen } from "./screens/people.ts";
5858 import { modelCeilingPrompt, modelGrantPrompt, modelScreen } from "./screens/model.ts";
5959 import { proposalTokensPrompt } from "./screens/proposal_tokens.ts";
60 import { privateDestinationsPrompt } from "./screens/private_destinations.ts";
6061 import { invitesScreen } from "./screens/invites.ts";
6162 import { quotasScreen } from "./screens/quotas.ts";
6263 import { teamsScreen } from "./screens/teams.ts";
@@ -405,6 +406,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
405406 hint: "mint, list and revoke what a child proposes with",
406407 run: () => ctx.push(proposalTokensPrompt(session, ctx, blank("Proposal tokens"))),
407408 });
409 // An app's settings → Private destinations: a site admin grants, an administrator reads.
410 if (session.user !== undefined)
411 commands.push({
412 id: "private-destinations",
413 title: "Private destinations",
414 hint: "which private addresses an app may reach: grant and revoke",
415 run: () => ctx.push(privateDestinationsPrompt(session, ctx, blank("Private destinations"))),
416 });
408417 // Settings → Model: a person's own budget and subscription, as the page has them (#1145).
409418 if (session.user?.kind === "user")
410419 commands.push({
src/tui/screens/private_destinations.ts added +103
@@ -0,0 +1,103 @@
1 /**
2 * An app's private destinations in the terminal, as its settings page has
3 * them: each exact private `address:port` its `forge.json` asks for, with
4 * `a` to grant and `x` to revoke the one under the cursor. Every rule is the
5 * action's (`actions/egress.ts`): only a site admin changes one, any other
6 * administrator of the repository sees "waiting for a site admin", and a
7 * repository you do not administer is "not visible to you".
8 */
9
10 import {
11 grantDestination,
12 listDestinations,
13 revokeDestination,
14 } from "../../actions/egress.ts";
15 import { repoByName } from "../../actions/proposal_tokens.ts";
16 import type { PrivateDestination } from "../../apps/private_destinations.ts";
17 import { canAdmin, type Repo } from "../../core/repos.ts";
18 import type { Ctx, Screen } from "../app/app.ts";
19 import { binding } from "../app/keys.ts";
20 import { style } from "../term/style.ts";
21 import { truncate } from "../term/width.ts";
22 import type { Session } from "../session.ts";
23 import { fill, len, split } from "../ui/layout.ts";
24 import { ListState, drawList, later, promptScreen, type ListRow } from "./common.ts";
25
26 /** Ask for `owner/name`, then show its private destinations. */
27 export function privateDestinationsPrompt(f: Session, ctx: Ctx, parent: Screen): Screen {
28 return promptScreen(ctx, parent, {
29 title: "Private destinations",
30 label: "repository, as owner/name",
31 onSubmit: (raw) => {
32 const repo = repoByName(f.app, raw.trim());
33 if (repo === undefined || f.user === undefined || !canAdmin(f.app.db, repo, f.user))
34 return "not visible to you";
35 return later(ctx, () => privateDestinationsScreen(f, ctx, repo));
36 },
37 });
38 }
39
40 export function privateDestinationsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
41 const state = new ListState();
42 let items: PrivateDestination[] = [];
43 let siteAdmin = false;
44 let note = "";
45 let loaded = false;
46
47 const reload = async (): Promise<void> => {
48 const listed = await listDestinations(f.app, f.user, repo);
49 items = listed.ok ? listed.value.rows : [];
50 siteAdmin = listed.ok && listed.value.siteAdmin;
51 if (!listed.ok) note = "not visible to you";
52 loaded = true;
53 state.clamp(items.length);
54 ctx.invalidate();
55 };
56
57 const rows = (): ListRow[] =>
58 items.map((d) => ({
59 title: d.destination,
60 secondary: d.grantedAt === undefined ? "not granted" : "granted",
61 meta:
62 d.grantedAt === undefined
63 ? siteAdmin ? "a grants it" : "waiting for a site admin"
64 : `by ${d.grantedBy} ${d.grantedAt.slice(0, 16).replace("T", " ")} UTC${d.declared ? "" : " · forge.json no longer names it"}${siteAdmin ? " · x revokes" : ""}`,
65 }));
66
67 const change = async (grant: boolean): Promise<void> => {
68 const d = items[state.index];
69 if (d === undefined) return;
70 const done = await (grant ? grantDestination : revokeDestination)(f.app, f.user, repo, d.destination);
71 note = done.ok
72 ? `${d.destination}: ${grant ? "granted" : "revoked"}.${done.value.restarted ? " The app is starting again." : ""}`
73 : done.error;
74 await reload();
75 };
76
77 const screen: Screen = {
78 title: `Private destinations: ${repo.ownerName}/${repo.name}`,
79 keys: [binding(["j", "k"], "move cursor"), binding(["a"], "grant"), binding(["x"], "revoke")],
80 load: reload,
81 render(area, s) {
82 const c = ctx.theme.c;
83 const [head, body] = split(area, "v", [len(1), fill(1)]);
84 const text =
85 note !== "" ? note
86 : !loaded ? "Loading…"
87 : items.length === 0 ? "forge.json names no private destination."
88 : "Private addresses forge.json asks for; only a site admin lets the app reach one.";
89 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
90 drawList(s, body!, c, state, rows());
91 },
92 key(e) {
93 if (state.key(e, items.length)) return true;
94 if (e.ctrl || e.alt) return false;
95 if (e.key === "a" || e.key === "x") {
96 ctx.track(change(e.key === "a"));
97 return true;
98 }
99 return false;
100 },
101 };
102 return screen;
103 }
src/web/pages/settings.ts +34 −49
@@ -24,6 +24,7 @@ import {
2424 type AppDomainView,
2525 } from "../../actions/domains.ts";
2626 import {
27 EGRESS_MESSAGES,
2728 egressView,
2829 grantAppEgress,
2930 revokeAppEgress,
@@ -606,7 +607,7 @@ function appSettingsView(
606607 <div class="mt">
607608 ${appDomainsView(base, domains.ok ? domains.value : undefined)}
608609 </div>
609 ${when(egress !== undefined && egress.rows.length > 0, () => html`<div class="mt">${appEgressView(base, egress!)}</div>`)}
610 ${when(egress !== undefined && egress.rows.length > 0, () => html`<div class="mt" id="private-destinations">${appEgressView(base, egress!)}</div>`)}
610611 <div class="mt">
611612 ${card(
612613 html`<p>
@@ -1185,42 +1186,33 @@ export async function appDomainDelete(ctx: Ctx): Promise<Response> {
11851186 function appEgressView(base: string, egress: EgressView): Html {
11861187 const at = (destination: string) =>
11871188 `${base}/settings/app/egress/${encodeURIComponent(destination)}`;
1188 const rows = egress.rows.map(
1189 (r) =>
1190 html`<li>
1191 <div class="row">
1192 <span class="row-lead">${icon("globe")}</span>
1193 <span class="row-main">
1194 <span class="row-title"
1195 ><span class="mono">${r.destination}</span> ${r.granted
1196 ? badge("granted", { tone: "success" })
1197 : badge("not granted", { tone: "attn" })}
1198 ${r.asked ? null : badge("no longer asked")}</span
1199 >
1200 <span class="row-meta"
1201 >${r.granted && r.grantedAt !== null
1202 ? html`Granted by ${r.grantedBy ?? "someone"}
1203 ${time(r.grantedAt)}`
1204 : "Nothing reaches it until a site admin grants it."}</span
1205 >
1206 </span>
1207 ${when(
1208 egress.canChange,
1209 () =>
1210 html`<span class="row-trail">
1211 ${r.granted
1212 ? confirmAction({
1213 action: `${at(r.destination)}/revoke`,
1214 verb: "Revoke",
1215 size: "sm",
1216 })
1217 : html`<form method="post" action="${at(r.destination)}/grant">
1218 ${btn("Grant", { size: "sm" })}
1219 </form>`}
1220 </span>`,
1221 )}
1222 </div>
1223 </li>`,
1189 const rows = egress.rows.map((r) =>
1190 row({
1191 lead: icon("globe"),
1192 title: html`<span class="mono">${r.destination}</span> ${r.granted
1193 ? badge("granted", { tone: "success" })
1194 : badge("not granted", { tone: "attn" })}
1195 ${r.asked ? null : badge("no longer asked")}`,
1196 meta:
1197 r.granted && r.grantedAt !== null
1198 ? html`Granted by ${r.grantedBy ?? "someone"} ${time(r.grantedAt)}`
1199 : egress.canChange
1200 ? "Nothing reaches it until you grant it."
1201 : "Nothing reaches it: waiting for a site admin.",
1202 trail: egress.canChange
1203 ? html`<span class="row-fields"
1204 >${r.granted
1205 ? confirmAction({
1206 action: `${at(r.destination)}/revoke`,
1207 verb: "Revoke",
1208 size: "sm",
1209 })
1210 : html`<form method="post" action="${at(r.destination)}/grant">
1211 ${btn("Grant", { size: "sm", variant: "outline" })}
1212 </form>`}</span
1213 >`
1214 : undefined,
1215 }),
12241216 );
12251217 const changes = egress.changes.map(
12261218 (c) =>
@@ -1236,12 +1228,13 @@ function appEgressView(base: string, egress: EgressView): Html {
12361228 html`<div class="card-body">
12371229 <p class="muted small">
12381230 Each is an exact address and port forge.json asks for. A grant opens
1239 that one destination for the app's cells and nothing else.${egress.canChange
1231 that one destination for the app's cells and nothing else; the app is
1232 started again so a grant takes effect at once.${egress.canChange
12401233 ? null
12411234 : " Only a site admin grants or revokes."}
12421235 </p>
12431236 </div>
1244 <ul class="list">
1237 <ul class="list setting-list">
12451238 ${rows}
12461239 </ul>
12471240 ${when(
@@ -1258,14 +1251,6 @@ function appEgressView(base: string, egress: EgressView): Html {
12581251 );
12591252 }
12601253
1261 const EGRESS_ERRORS: Record<string, string> = {
1262 forbidden: "Only a site admin grants or revokes a private destination.",
1263 invalid_destination: "That is not an address and port.",
1264 not_asked: "forge.json does not ask for that destination.",
1265 never_grantable:
1266 "That address can never be granted: it is this machine, link-local or the forge's own cluster.",
1267 no_such_grant: "There was no grant for that destination.",
1268 };
12691254
12701255 // POST /:owner/:name/settings/app/egress/:destination/grant
12711256 export async function appEgressGrant(ctx: Ctx): Promise<Response> {
@@ -1282,7 +1267,7 @@ export async function appEgressGrant(ctx: Ctx): Promise<Response> {
12821267 ? { message: `${granted.value.destination} is granted.` }
12831268 : {
12841269 tone: "danger",
1285 message: EGRESS_ERRORS[granted.error] ?? "That could not be granted.",
1270 message: EGRESS_MESSAGES[granted.error],
12861271 },
12871272 );
12881273 }
@@ -1302,7 +1287,7 @@ export async function appEgressRevoke(ctx: Ctx): Promise<Response> {
13021287 ? { message: `${revoked.value} is revoked.` }
13031288 : {
13041289 tone: "danger",
1305 message: EGRESS_ERRORS[revoked.error] ?? "That could not be revoked.",
1290 message: EGRESS_MESSAGES[revoked.error],
13061291 },
13071292 );
13081293 }
test/app-private-destinations.test.ts added +133
@@ -0,0 +1,133 @@
1 /** An app's settings page grants and revokes its private destinations (#3564). */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
8 import { createApp as insertApp } from "../src/core/apps.ts";
9 import { listEgressGrants } from "../src/core/egress_grants.ts";
10 import { createSession } from "../src/core/sessions.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { decide } from "../src/apps/egress.ts";
13 import { privateEntries } from "../src/apps/private_destinations.ts";
14 import { grantedFor } from "../src/apps/runtime.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { seedAdmin } from "./helpers/admin.ts";
17 import { promote } from "./helpers/members.ts";
18
19 const DEST = "100.89.95.68:8101";
20 let dataDir = "";
21 let app: App, servers: Servers;
22 let adminCookie = "", ownerCookie = "";
23 let repoId = "";
24 const page = "/bob/arm/settings/app";
25
26 const get = (cookie: string) =>
27 fetch(`${servers.url}${page}`, { headers: { cookie } }).then((r) => r.text());
28 const post = (cookie: string, to: string, origin = servers.url) =>
29 fetch(`${servers.url}${page}/egress/${encodeURIComponent(DEST)}/${to}`, {
30 method: "POST",
31 headers: { cookie, origin },
32 redirect: "manual",
33 });
34
35 beforeAll(async () => {
36 dataDir = await mkdtemp(join(tmpdir(), "forge-pdest-"));
37 app = createApp({ dataDir, port: 0 });
38 servers = await serve(app);
39 const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
40 if (!admin.ok) throw new Error(admin.error);
41 adminCookie = `forge_session=${createSession(app.db, admin.value.id).token}`;
42 const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "correct-horse-battery" });
43 if (!bob.ok) throw new Error(bob.error);
44 promote(app.db, bob.value);
45 ownerCookie = `forge_session=${createSession(app.db, bob.value.id).token}`;
46 const made = await createRepo(app, bob.value, { name: "arm", visibility: "public", description: "" });
47 if (!made.ok) throw new Error(String(made.error));
48 repoId = made.value.id;
49 const files = [{ path: "forge.json", content: JSON.stringify({ app: { run: "bun x" }, egress: [DEST, "api.example.com"] }) }];
50 const c = await commitToBranch(app, bob.value, made.value, { files });
51 if (!c.ok) throw new Error(String(c.error));
52 const row = insertApp(app.db, { repoId, slug: "arm", access: "public" });
53 if (!row.ok) throw new Error(row.error);
54 });
55
56 afterAll(async () => {
57 servers.stop();
58 app.close();
59 await rm(dataDir, { recursive: true, force: true });
60 });
61
62 const policy = () => ({ hosts: [DEST], origins: [], granted: grantedFor(app.db, repoId) });
63
64 describe("private destinations on the app settings page", () => {
65 test("only private exact address:port entries are listed", () => {
66 expect(privateEntries([DEST, "api.example.com", "8.8.8.8:53", "*.example.com"])).toEqual([DEST]);
67 });
68
69 test("ungranted: a site admin sees a Grant button; the app is refused", async () => {
70 const html = await get(adminCookie);
71 expect(html).toContain('id="private-destinations"');
72 expect(html).toContain(DEST);
73 expect(html).toContain("/egress/100.89.95.68%3A8101/grant");
74 expect(html).not.toContain("api.example.com");
75 const v = await decide(policy(), "100.89.95.68", 8101);
76 expect(v.ok).toBe(false);
77 });
78
79 test("the repository's owner, not a site admin, sees it read-only", async () => {
80 const html = await get(ownerCookie);
81 expect(html).toContain("waiting for a site admin");
82 expect(html).not.toContain("/grant");
83 const res = await post(ownerCookie, "grant");
84 expect(res.status).toBe(303);
85 expect(res.headers.get("location")).toContain("/bob/arm/settings/app");
86 expect(listEgressGrants(app.db, repoId)).toEqual([]);
87 const flash = decodeURIComponent(res.headers.get("set-cookie") ?? "");
88 expect(flash).toContain("Only a site admin grants or revokes");
89 expect(flash).toContain("danger");
90 });
91
92 test("a cross-origin grant is refused", async () => {
93 const res = await post(adminCookie, "grant", "http://evil.example");
94 expect(res.status).toBeGreaterThanOrEqual(400);
95 expect(listEgressGrants(app.db, repoId)).toEqual([]);
96 });
97
98 test("grant: listed with who, and the app reaches it", async () => {
99 const res = await post(adminCookie, "grant");
100 expect(res.status).toBe(303);
101 expect(listEgressGrants(app.db, repoId).map((g) => g.destination)).toEqual([DEST]);
102 const html = await get(adminCookie);
103 expect(html).toContain("Granted by alice");
104 expect(html).toContain("egress%2F100.89.95.68%253A8101%2Frevoke");
105 expect(grantedFor(app.db, repoId)).toEqual([DEST]);
106 // Past the declared-and-granted check; the dial itself is not made here.
107 const v = await decide(policy(), "100.89.95.68", 8101);
108 expect(v.ok).toBe(true);
109 });
110
111 test("a destination forge.json does not name cannot be granted", async () => {
112 const res = await fetch(`${servers.url}${page}/egress/${encodeURIComponent("100.89.95.99:80")}/grant`, {
113 method: "POST", headers: { cookie: adminCookie, origin: servers.url }, redirect: "manual",
114 });
115 expect(res.status).toBe(303);
116 expect(listEgressGrants(app.db, repoId).map((g) => g.destination)).toEqual([DEST]);
117 });
118
119 test("revoke: refused again", async () => {
120 const res = await post(adminCookie, "revoke");
121 expect(res.status).toBe(303);
122 expect(listEgressGrants(app.db, repoId)).toEqual([]);
123 const v = await decide(policy(), "100.89.95.68", 8101);
124 expect(v.ok).toBe(false);
125 expect(await get(adminCookie)).toContain("/grant");
126 });
127
128 test("a refusal names the settings section", async () => {
129 const v = await decide({ ...policy(), settingsUrl: "https://f.test/bob/arm/settings/app#private-destinations" }, "100.89.95.68", 8101);
130 expect(v.ok).toBe(false);
131 if (!v.ok) expect(v.why).toContain("/bob/arm/settings/app#private-destinations");
132 });
133 });
test/egress-actions.test.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * The seams of #3564 the page tests do not reach: a grant starts the app
3 * again, the cell carries the link a refusal names, and the activity feed
4 * words the two events.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { grantDestination, revokeDestination } from "../src/actions/egress.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { AppsRuntime } from "../src/apps/runtime.ts";
14 import { createApp as insertApp, type AppRecord } from "../src/core/apps.ts";
15 import type { ForgeEvent } from "../src/core/events.ts";
16 import type { Repo } from "../src/core/repos.ts";
17 import type { User } from "../src/core/users.ts";
18 import { eventVerb } from "../src/design/activity.ts";
19 import { seedAdmin } from "./helpers/admin.ts";
20
21 const DEST = "100.89.95.68:8101";
22 let dataDir = "";
23 let app: App, runtime: AppsRuntime, alice: User, repo: Repo, record: AppRecord;
24 const restarts: string[] = [];
25
26 beforeAll(async () => {
27 dataDir = await mkdtemp(join(tmpdir(), "forge-egress-actions-"));
28 app = createApp({ dataDir, port: 0 });
29 runtime = new AppsRuntime(app, { domain: "e.test", scheme: "http", publicPort: 80, forgeUrl: "https://forge.test/", concurrency: 1 });
30 // No deploy here: only whether and why the app is asked to start again.
31 runtime.reconcileApp = (_record, _repo, reason) => {
32 restarts.push(reason);
33 return Promise.resolve();
34 };
35 (runtime as unknown as { cells: { ok: true } }).cells = { ok: true };
36 const made = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
37 if (!made.ok) throw new Error(made.error);
38 alice = made.value;
39 const r = await createRepo(app, alice, { name: "arm", visibility: "public", description: "" });
40 if (!r.ok) throw new Error(String(r.error));
41 repo = r.value;
42 const files = [{ path: "forge.json", content: JSON.stringify({ app: { run: "bun x" }, egress: [DEST] }) }];
43 const c = await commitToBranch(app, alice, repo, { files });
44 if (!c.ok) throw new Error(String(c.error));
45 const row = insertApp(app.db, { repoId: repo.id, slug: "arm", access: "public" });
46 if (!row.ok) throw new Error(row.error);
47 record = row.value;
48 });
49 afterAll(async () => {
50 app.close();
51 await rm(dataDir, { recursive: true, force: true });
52 });
53
54 test("granting and revoking start the app again, and say so", async () => {
55 const granted = await grantDestination(app, alice, repo, DEST);
56 expect(granted).toEqual({ ok: true, value: { restarted: true } });
57 expect(restarts).toEqual(["redeploy"]);
58 const revoked = await revokeDestination(app, alice, repo, DEST);
59 expect(revoked).toEqual({ ok: true, value: { restarted: true } });
60 expect(restarts).toEqual(["redeploy", "redeploy"]);
61 });
62
63 test("a refused change starts nothing", async () => {
64 const before = restarts.length;
65 expect((await revokeDestination(app, alice, repo, DEST)).ok).toBe(false);
66 expect((await grantDestination(app, alice, repo, "100.89.95.99:80")).ok).toBe(false);
67 expect(restarts.length).toBe(before);
68 });
69
70 test("the cell carries the settings link a refusal names", () => {
71 expect(runtime.cellFor(record, "production")?.settingsUrl).toBe(
72 "https://forge.test/alice/arm/settings/app#private-destinations",
73 );
74 });
75
76 const event = (kind: string, payload: Record<string, unknown>): ForgeEvent => ({ kind, payload }) as unknown as ForgeEvent;
77
78 test("the activity feed words a grant and a revoke", () => {
79 expect(eventVerb(event("app.egress.granted", { destination: DEST }))).toBe(`granted the app ${DEST}`);
80 expect(eventVerb(event("app.egress.revoked", { destination: DEST }))).toBe(`revoked the app's grant on ${DEST}`);
81 expect(eventVerb(event("app.egress.granted", {}))).toBe("granted the app a destination");
82 expect(eventVerb(event("app.egress.revoked", {}))).toBe("revoked the app's grant on a destination");
83 });
test/event-audience.test.ts +20
@@ -116,6 +116,26 @@ describe("who an event is for", () => {
116116 expect(eventAudience("a.kind.nobody.classified")).toBe("readers");
117117 });
118118
119 test("a private destination and its granter are for the repository's admins", () => {
120 expect(eventAudience("app.egress.granted")).toBe("admins");
121 expect(eventAudience("app.egress.revoked")).toBe("admins");
122 app.bus.append({
123 kind: "app.egress.granted",
124 repoId: repo.id,
125 actorId: alice.id,
126 payload: { destination: "10.1.2.3:5432" },
127 });
128 const all = listEvents(app.db, { repoId: repo.id });
129 const seenBy = (viewer: User | undefined) =>
130 JSON.stringify(all.filter(audienceFilter(app.db, viewer)));
131 for (const guest of [undefined, bob]) {
132 const seen = seenBy(guest);
133 expect(seen).not.toContain("10.1.2.3:5432");
134 expect(seen).not.toContain("app.egress.granted");
135 }
136 expect(seenBy(alice)).toContain("10.1.2.3:5432");
137 });
138
119139 test("the filter: admins see configuration, an actor their own choice, a stranger neither", () => {
120140 const all = listEvents(app.db, { repoId: repo.id });
121141 const seenBy = (viewer: User | undefined) =>
test/tui-private-destinations.test.ts added +109
@@ -0,0 +1,109 @@
1 /**
2 * Private destinations in the terminal (#3564): a site admin lists, grants
3 * and revokes; a repository's owner who is not one reads "waiting for a site
4 * admin"; a stranger is told it is not visible.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App as Forge } from "../src/app.ts";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { createApp as insertApp } from "../src/core/apps.ts";
13 import { listEgressGrants } from "../src/core/egress_grants.ts";
14 import { createUser, getUserByName } from "../src/core/users.ts";
15 import { createForgeApp } from "../src/tui/forge.ts";
16 import type { TuiIdentity } from "../src/tui/session.ts";
17 import { headlessTerminal } from "../src/tui/term/terminal.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19 import { promote } from "./helpers/members.ts";
20 import { settleApp } from "./helpers/tui.ts";
21
22 quietLogs();
23
24 const DEST = "100.89.95.68:8101";
25
26 describe("private destinations in the terminal", () => {
27 let dataDir: string;
28 let forge: Forge;
29 let repoId = "";
30
31 function boot(username: string) {
32 const terminal = headlessTerminal(140, 32);
33 const user = getUserByName(forge.db, username)!;
34 const identity: TuiIdentity = { sshUsername: "t", remoteAddress: "127.0.0.1", user };
35 const { app } = createForgeApp(forge, identity, { terminal, exitHooks: false });
36 app.start();
37 const key = (k: string) => app.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false });
38 return {
39 text: () => app.screen.toText(),
40 press: async (...keys: string[]) => { keys.forEach(key); await settleApp(app); },
41 ctrl: async (k: string) => { app.dispatch({ type: "key", key: k, ctrl: true, alt: false, shift: false }); await settleApp(app); },
42 type: async (t: string) => { for (const ch of t) key(ch); await settleApp(app); },
43 stop: () => app.stop(),
44 };
45 }
46 const open = async (h: ReturnType<typeof boot>) => {
47 await h.ctrl("k");
48 await h.type("Private destinations");
49 await h.press("enter");
50 await h.type("bob/arm");
51 await h.press("enter");
52 };
53
54 beforeAll(async () => {
55 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-pdest-"));
56 forge = createApp({ dataDir, port: 0 });
57 for (const [username, adminIfFirst] of [["alice", true], ["bob", false], ["carol", false]] as const) {
58 const made = await createUser(forge.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst });
59 if (!made.ok) throw new Error(made.error);
60 }
61 const bob = getUserByName(forge.db, "bob")!;
62 promote(forge.db, bob);
63 const made = await createRepo(forge, bob, { name: "arm", visibility: "public", description: "" });
64 if (!made.ok) throw new Error(String(made.error));
65 repoId = made.value.id;
66 const files = [{ path: "forge.json", content: JSON.stringify({ app: { run: "bun x" }, egress: [DEST] }) }];
67 const c = await commitToBranch(forge, bob, made.value, { files });
68 if (!c.ok) throw new Error(String(c.error));
69 const row = insertApp(forge.db, { repoId, slug: "arm", access: "public" });
70 if (!row.ok) throw new Error(row.error);
71 });
72 afterAll(async () => {
73 forge.close();
74 await rm(dataDir, { recursive: true, force: true });
75 });
76
77 test("a site admin grants, sees who, and revokes", async () => {
78 const h = boot("alice");
79 await open(h);
80 expect(h.text()).toContain(DEST);
81 expect(h.text()).toContain("not granted");
82 await h.press("a");
83 expect(listEgressGrants(forge.db, repoId).map((g) => g.destination)).toEqual([DEST]);
84 expect(h.text()).toContain(`${DEST}: granted.`);
85 expect(h.text()).toContain("by alice");
86 await h.press("x");
87 expect(listEgressGrants(forge.db, repoId)).toEqual([]);
88 expect(h.text()).toContain(`${DEST}: revoked.`);
89 h.stop();
90 });
91
92 test("the owner who is not a site admin reads, and a does nothing", async () => {
93 const h = boot("bob");
94 await open(h);
95 expect(h.text()).toContain("waiting for a site admin");
96 await h.press("a");
97 expect(h.text()).toContain("Only a site admin grants or revokes a private destination");
98 expect(listEgressGrants(forge.db, repoId)).toEqual([]);
99 h.stop();
100 });
101
102 test("a stranger is told it is not visible", async () => {
103 const h = boot("carol");
104 await open(h);
105 expect(h.text()).toContain("not visible to you");
106 expect(h.text()).not.toContain(DEST);
107 h.stop();
108 });
109 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs