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

Grant and revoke private destinations on the app's settings page (the half #3437 left out) #3568

Closed opened this in answer to
Closed without merging

scout/forge:scout/3564-grant-and-revoke-private-destinations-on → main 3 commits fork 6 threads · 6 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +782 −8
docs/APPS.md +10 −3
@@ -291,9 +291,16 @@ own pod and service ranges (`FORGE_NEVER_GRANT_CIDRS` adds more) are never
291291 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
294 `egress_grant` table and read at every app start. There is not yet a page or
295 terminal command to make one (#3469), so for now they are written through
296 `grantEgress`.
294 `egress_grant` table and read at every app start. A site admin grants or
295 revokes each from the app's settings page, under *Private destinations*
296 (`settings/app#private-destinations`; the refusal in the app's log names that
297 link): it lists the private `address:port` entries of the default branch's
298 `forge.json`, with who granted and when. Anyone else who administers the
299 repository sees "waiting for a site admin". The terminal has the same under the command palette's *Private destinations*
300 (`a` grants, `x` revokes; the same `grantDestination`/`revokeDestination`
301 actions). A change starts the app again so
302 the new cell carries it. Only an exact private IPv4 `address:port` is listed;
303 a name that happens to resolve privately is still granted with `grantEgress`.
297304
298305 A release that turns egress on must not break an app whose writers have
299306 not declared what it uses yet, so the operator can start it reported:
src/actions/egress.ts added +107
@@ -0,0 +1,107 @@
1 /**
2 * A site admin's yes or no to one private destination of an app, from its
3 * settings page. 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 { appsRuntime } from "../apps/runtime.ts";
12 import { getAppByRepo } from "../core/apps.ts";
13 import { grantEgress, revokeEgress } from "../core/egress_grants.ts";
14 import { canAdmin, type Repo } from "../core/repos.ts";
15 import type { User } from "../core/users.ts";
16 import { resolveOid } from "../git/merge.ts";
17 import { repoDir } from "../git/repos.ts";
18 import { err, ok, type Result } from "../kernel/result.ts";
19
20 /** The `egress` the default branch's `forge.json` declares. */
21 export async function declaredEgress(app: App, repo: Repo): Promise<string[]> {
22 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
23 const oid = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
24 if (oid === undefined) return [];
25 const [forgeJson, packageJson] = await Promise.all([
26 readFileAt(dir, oid, "forge.json"),
27 readFileAt(dir, oid, "package.json"),
28 ]);
29 const manifest = parseManifest(forgeJson, packageJson);
30 return manifest.ok ? [...(manifest.value.egress ?? [])] : [];
31 }
32
33 /** Whether the app was started again, so the page can say so. */
34 export interface Changed {
35 readonly restarted: boolean;
36 }
37
38 /**
39 * Start the app again so its new cell carries the change. Not awaited: a
40 * redeploy outlasts a request, so a failure is logged, not returned.
41 */
42 function restart(app: App, repo: Repo): boolean {
43 const record = getAppByRepo(app.db, repo.id);
44 const runtime = appsRuntime(app);
45 if (record === undefined || runtime === undefined) return false;
46 runtime.reconcileApp(record, repo, "redeploy").catch((e: unknown) => {
47 console.warn(`egress: restart of ${repo.ownerName}/${repo.name} failed: ${String(e)}`);
48 });
49 return true;
50 }
51
52 /**
53 * What the app's private-destinations card and screen show: for a repository
54 * administrator, each destination and whether this actor may change it (a
55 * site admin). Anyone else gets `not_found`, as the page does.
56 */
57 export async function listDestinations(
58 app: App,
59 actor: User | undefined,
60 repo: Repo,
61 ): Promise<Result<{ rows: PrivateDestination[]; siteAdmin: boolean }, "not_found">> {
62 if (actor === undefined || !canAdmin(app.db, repo, actor)) return err("not_found");
63 if (getAppByRepo(app.db, repo.id) === undefined) return ok({ rows: [], siteAdmin: actor.isAdmin });
64 const declared = await declaredEgress(app, repo);
65 return ok({
66 rows: privateDestinations(app.db, repo.id, declared),
67 siteAdmin: actor.isAdmin,
68 });
69 }
70
71 export async function grantDestination(
72 app: App,
73 actor: User | undefined,
74 repo: Repo,
75 destination: string,
76 ): Promise<Result<Changed, string>> {
77 if (actor?.isAdmin !== true) return err("only a site admin grants egress");
78 if (!privateEntries(await declaredEgress(app, repo)).includes(destination))
79 return err(`forge.json egress does not name ${destination}`);
80 const granted = grantEgress(app.db, repo.id, destination, actor);
81 if (!granted.ok) return granted;
82 app.bus.append({
83 kind: "app.egress_granted",

High: this event's kind is not classified in core/event_audience.ts, so it falls to app. → audience "app". Anyone who may enter the app, not only the repository's admins, then reads the private address:port and the granter. Classify app.egress_ as "admins", as app.env_* and app.domain.* already are, and add a test.

84 repoId: repo.id,
85 actorId: actor.id,
86 payload: { destination },
87 });
88 return ok({ restarted: restart(app, repo) });
89 }
90
91 export async function revokeDestination(
92 app: App,
93 actor: User | undefined,
94 repo: Repo,
95 destination: string,
96 ): Promise<Result<Changed, string>> {
97 if (actor?.isAdmin !== true) return err("only a site admin revokes egress");
98 if (!revokeEgress(app.db, repo.id, destination, actor))
99 return err("there was no such grant");
100 app.bus.append({
101 kind: "app.egress_revoked",
102 repoId: repo.id,
103 actorId: actor.id,
104 payload: { destination },
105 });
106 return ok({ restarted: restart(app, repo) });
107 }
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
@@ -1406,12 +1406,20 @@ export class AppsRuntime {
14061406 noteReached(dataDir, record.repoId, host, port),
14071407 // Asked at every start: an admin's grant reaches the next cell.
14081408 granted: grantedFor(this.app.db, record.repoId),
1409 settingsUrl: this.settingsUrl(record),
14091410 // Likewise an admin's flip of the egress mode.
14101411 egressMode: egressSetting(this.app.db),
14111412 label: `app:${record.slug}/${env}`,
14121413 };
14131414 }
14141415
1416 /** The app settings section where a refused private destination is granted. */
1417 private settingsUrl(record: AppRecord): string | undefined {

Untested: nothing checks that the cell spec carries this URL. A test on cellFor (or on the CellSpec that startProcess builds) would catch a broken link between here and decide.

1418 const repo = getRepoById(this.app.db, record.repoId);
1419 if (repo === undefined) return undefined;
1420 return `${this.options.forgeUrl.replace(/\/$/, "")}/${repo.ownerName}/${repo.name}/settings/app#private-destinations`;
1421 }
1422
14151423 /** Say on the run, once, whether its processes were held. */
14161424 private noteCell(runId: string, write: (line: string) => void): void {
14171425 noteRunProgress(this.app.db, runId, {
@@ -1449,6 +1457,7 @@ export class AppsRuntime {
14491457 hide: base.hide,
14501458 egress: live.manifest.egress ?? [],
14511459 granted: base.granted,
1460 settingsUrl: base.settingsUrl,
14521461 // A terminal is the app's own client: it reaches the app on
14531462 // its port, as it would beside it.
14541463 reach: [
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 === "app.egress_granted" || kind === "app.egress_revoked") {

These two verbs have no test. Add eventVerb cases for granted, revoked and a payload with no destination.

The wording is fine. Once the audience is fixed, this line only ever renders for the repository's admins, which is right for a private address.

62 const to = payload["destination"];
63 const which = typeof to === "string" ? to : "a private destination";
64 return kind === "app.egress_granted"
65 ? `let the app reach ${which}`
66 : `stopped the app reaching ${which}`;
67 }
6168 if (kind.startsWith("app.domain.")) {
6269 const host = payload["host"];
6370 const which = typeof host === "string" ? host : "a domain";
src/http/server.ts +5
@@ -354,6 +354,8 @@ import {
354354 appDomainDelete,
355355 appEnvDelete,
356356 appEnvSet,
357 appEgressGrant,
358 appEgressRevoke,
357359 appSettingsPage,
358360 appSettingsUpdate,
359361 autonomySettingsPage,
@@ -1342,6 +1344,9 @@ export function buildRouter(): Router<Handler> {
13421344 router.add("POST", "/:owner/:name/settings/app/disable", appDisable);
13431345 router.add("POST", "/:owner/:name/settings/app/members", appMembersUpdate);
13441346 router.add("POST", "/:owner/:name/settings/app/env", appEnvSet);
1347 // `:to` is one `host:port` segment, the colon percent-encoded or not.
1348 router.add("POST", "/:owner/:name/settings/app/egress/:to/grant", appEgressGrant);
1349 router.add("POST", "/:owner/:name/settings/app/egress/:to/revoke", appEgressRevoke);
13451350 router.add(
13461351 "POST",
13471352 "/: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 +140 −3
@@ -51,7 +51,16 @@ import {
5151 updateRepoSettings,
5252 } from "../../actions/repos.ts";
5353 import { appsRuntime } from "../../apps/runtime.ts";
54 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
54 import {
55 declaredEgress,
56 grantDestination,
57 revokeDestination,
58 } from "../../actions/egress.ts";
59 import {
60 privateDestinations,
61 type PrivateDestination,
62 } from "../../apps/private_destinations.ts";
63 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
5564 import { appVitals, shiftText, speedText as ms, type AppVitals } from "../../apps/vitals.ts";
5665 import type { PreviewData } from "../../apps/data.ts";
5766 import {
@@ -490,6 +499,7 @@ function appSettingsView(
490499 repo: Repo,
491500 record: AppRecord | undefined,
492501 values: AppValues,
502 destinations: readonly PrivateDestination[],
493503 error?: string,
494504 ): Html {
495505 const base = repoBase(repo);
@@ -590,6 +600,9 @@ function appSettingsView(
590600 appVitals(ctx.app.db, record.id),
591601 );
592602 return html`${form}
603 <div class="mt">
604 ${privateDestinationsView(base, destinations, ctx.auth.user?.isAdmin === true)}
605 </div>
593606 ${when(listed?.ok === true, () => html`<div class="mt">${appMembersView(base, values.access, named)}</div>`)}
594607 <div class="mt">${appVisitorsView(vitals)}</div>
595608 <div class="mt">
@@ -783,6 +796,74 @@ ${named.join("\n")}</textarea
783796 );
784797 }
785798
799 /**
800 * Private destinations the app's `forge.json` asks for. A site admin grants
801 * or revokes each; everyone else who administers the repository sees what
802 * is waiting. `#private-destinations` is where a refusal in the app's log
803 * points.
804 */
805 function privateDestinationsView(
806 base: string,
807 destinations: readonly PrivateDestination[],
808 siteAdmin: boolean,
809 ): Html {
810 const at = (to: string) =>
811 `${base}/settings/app/egress/${encodeURIComponent(to)}`;
812 const rows = destinations.map((d) =>
813 row({
814 lead: icon("lock"),
outdated

Use row({ lead, title, meta, trail }) from src/web/ui.ts instead of hand-built .row markup. Put the rows in <ul class="list setting-list"> and the Grant/Revoke form in .row-fields (DESIGN.md §5d), so the meta wraps instead of being cut off.

815 title: html`<span class="mono">${d.destination}</span>
816 ${d.grantedAt === undefined
817 ? badge("not granted", { tone: "attn" })
818 : badge("granted", { tone: "success" })}`,
819 meta:
820 d.grantedAt === undefined
821 ? html`The app is refused this address until a site admin grants it.${d.declared ? null : " · forge.json no longer names it"}`
822 : html`granted by ${d.grantedBy} ${time(d.grantedAt)}${d.declared ? null : " · forge.json no longer names it"}`,
823 trail: !siteAdmin
824 ? d.grantedAt === undefined
825 ? html`<span class="muted small">waiting for a site admin</span>`
826 : html``
827 : html`<form
828 class="row-fields"
829 method="post"
830 action="${at(d.destination)}/${d.grantedAt === undefined ? "grant" : "revoke"}"
831 >
832 ${btn(d.grantedAt === undefined ? "Grant" : "Revoke", {
833 variant: "outline",
834 size: "sm",
835 })}
836 </form>`,
837 }),
838 );
839 return card(
840 html`<div class="card-body">
841 <p class="muted small">
842 Private addresses the app's <span class="mono">forge.json</span>
outdated

One accent per page (DESIGN.md checklist 5). Each ungranted row adds another filled primary button next to the app's Save. Use outline (or secondary), as Revoke does.

843 <span class="mono">egress</span> names. Only a site admin lets the
844 app reach one, and only that address and port. Granting or revoking
845 starts the app again.
846 </p>
847 </div>
848 ${rows.length > 0
849 ? html`<ul class="list setting-list">
850 ${rows}
851 </ul>`
852 : html`<div class="card-body">
853 <p class="muted small">
854 <span class="mono">forge.json</span> names no private
855 destination.
856 </p>
857 </div>`}`,
858 {
859 id: "private-destinations",
860 head: html`${icon("lock")}
861 <h2>Private destinations</h2>`,
862 pad: false,
863 },
864 );
865 }
866
786867 function appDomainsView(
787868 base: string,
788869 domains: AppDomainView[] | undefined,
@@ -892,13 +973,33 @@ const appValues = (repo: Repo, record: AppRecord | undefined): AppValues => ({
892973 previewData: record?.previewData ?? "copy",
893974 });
894975
976 /** What the app's private-destinations card lists; none until it is an app. */
977 async function destinationsFor(
978 ctx: Ctx,
979 repo: Repo,
980 record: AppRecord | undefined,
981 ): Promise<PrivateDestination[]> {
982 if (record === undefined) return [];
983 const declared = await timePhaseAsync(ctx.request, "egress", () =>
984 declaredEgress(ctx.app, repo),
985 );
986 return privateDestinations(ctx.app.db, repo.id, declared);
987 }
988
895989 // GET /:owner/:name/settings/app
896 export function appSettingsPage(ctx: Ctx): Response {
990 export async function appSettingsPage(ctx: Ctx): Promise<Response> {
897991 const repo = loadAdminRepo(ctx);
898992 if (!repo) return repoNotFound(ctx);
899993 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
900994 const record = getAppByRepo(ctx.app.db, repo.id);
901 const view = appSettingsView(ctx, repo, record, appValues(repo, record));
995 const destinations = await destinationsFor(ctx, repo, record);
996 const view = appSettingsView(
997 ctx,
998 repo,
999 record,
1000 appValues(repo, record),
1001 destinations,
1002 );
9021003 const rendering = performance.now();
9031004 const response = settingsPageResponse(ctx, repo, "app", "App", view);
9041005 notePhase(ctx.request, "render", performance.now() - rendering);
@@ -932,6 +1033,7 @@ export async function appSettingsUpdate(ctx: Ctx): Promise<Response> {
9321033 repo,
9331034 record,
9341035 values,
1036 await destinationsFor(ctx, repo, record),
9351037 saved.error === "app_limit"
9361038 ? appLimitWords(ctx.app, repo.ownerId)
9371039 : (APP_ERRORS[saved.error] ?? "Those settings could not be saved."),
@@ -1007,6 +1109,41 @@ export async function appDisable(ctx: Ctx): Promise<Response> {
10071109 );
10081110 }
10091111
1112 // POST /:owner/:name/settings/app/egress/:to/grant — a site admin's yes.
1113 export async function appEgressGrant(ctx: Ctx): Promise<Response> {
1114 const gate = await adminForm(ctx);
1115 if (gate instanceof Response) return gate;
1116 const to = ctx.params.to ?? "";
1117 const done = await grantDestination(ctx.app, ctx.auth.user, gate.repo, to);
1118 return egressFlash(ctx, gate.repo, done, `${to} is granted.`);
1119 }
1120
1121 // POST /:owner/:name/settings/app/egress/:to/revoke
1122 export async function appEgressRevoke(ctx: Ctx): Promise<Response> {
outdated

Every route here needs a counterpart in src/tui (see screens/domains.ts for how app settings are done there), calling the same grantDestination/revokeDestination so the gate stays in one place.

1123 const gate = await adminForm(ctx);
1124 if (gate instanceof Response) return gate;
1125 const to = ctx.params.to ?? "";
1126 const done = await revokeDestination(ctx.app, ctx.auth.user, gate.repo, to);
1127 return egressFlash(ctx, gate.repo, done, `${to} is revoked.`);
1128 }
1129
1130 function egressFlash(
1131 ctx: Ctx,
1132 repo: Repo,
1133 done: { ok: true; value: { restarted: boolean } } | { ok: false; error: string },
1134 said: string,
1135 ): Response {
1136 return flashTo(
1137 ctx,
1138 `${repoBase(repo)}/settings/app#private-destinations`,
1139 done.ok
1140 ? {
1141 message: `${said} ${done.value.restarted ? "The app is starting again with it." : "The app is not running here; it takes effect when it next starts."}`,
1142 }
1143 : { tone: "danger", message: done.error },
1144 );
1145 }
1146
10101147 const APP_ENV_ERRORS: Record<string, string> = {
10111148 invalid_name: `A name is capital letters, digits and underscores, starting with a letter — ADMIN_PASSWORD, STRIPE_SECRET_KEY — and at most ${NAME_MAX} characters.`,
10121149 reserved_name:
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 egress");
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/100.89.95.68%3A8101/revoke");
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(`let the app reach ${DEST}`);
80 expect(eventVerb(event("app.egress_revoked", { destination: DEST }))).toBe(`stopped the app reaching ${DEST}`);
81 expect(eventVerb(event("app.egress_granted", {}))).toBe("let the app reach a private destination");
82 expect(eventVerb(event("app.egress_revoked", {}))).toBe("stopped the app reaching a private destination");
83 });
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 egress");
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