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

Cloud pages: the missing permission, one thing's price, and where tax is #17651

opened this

Merged 21h 28m ago, live in production

sold/cloud-priya → main 0 commits 1 thread · 1 unresolved

  • Merged. sold/cloud-priya was merged into main as 00083d2.

Review

Sign in to review this change.
9 files changed +209 −20
docs/features/cloud.md +10
@@ -27,6 +27,16 @@ Answers: `401` with no signed-in user, `403` for a read-only token (every vendor
2727
2828 Not done: the route only lists. Attaching, rotating and removing stay on the page and in the terminal, where the token can be typed masked.
2929
30 ## What was not read (#17637)
31
32 When the last read of an account could not see something, its row at `/settings/cloud` has a **Not read** line for each reason: what, where, why, the permission when the answer names one, and what to change (`readFixes` in `src/cloud/tree.ts`).
33
34 1. Press **Check the account** on a "Not read" line at `/infra`, or open Settings → Cloud accounts.
35 2. Make the change named. On AWS that is a managed policy on the key's user or role, or the single permission. A key the cloud does not accept needs a new one, with **Rotate**.
36 3. Press **Read now** on Infrastructure. A bill is asked for once a day, so its line goes after the next day's read.
37
38 **In the terminal:** `enter` on an account of the Cloud accounts screen (`src/tui/screens/cloud.ts`) opens the same lines (`src/tui/screens/cloud_account.ts`), and so does `a` on Cloud resources. `r` on Cloud accounts rotates, and `P` on Cloud resources reads again.
39
3040 ## The project a forge is filed in (#16340)
3141
3242 - A DigitalOcean account can name the cloud **project** its forges go in: a text field on its row at `/settings/cloud`, `P` on the terminal screen, `set_project` on the MCP `cloud_account` tool. Empty is the provider's default project. An admin only; the name is checked, and the project must exist when a forge is deployed, or the deploy is refused before anything is made.
docs/features/infra.md +2 −2
@@ -96,12 +96,12 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro
9696
9797 /infra leads with what every cloud costs a month and draws one tree: cloud ▸ account ▸ project or region ▸ resource, the costliest first, the cost rolled up at each level (`src/cloud/tree.ts`, pure; `src/web/pages/cloud_tree.ts`). It is the code browser's column and script. A page reads the database alone, never a provider, and nothing in it changes a resource.
9898
99 - **Cost.** An AWS region, account and cloud show the last whole month billed; everything else is a list price. A bill stands in for its resources' prices and is never added to them. The total says it in words ("November's AWS bill, list prices for the rest, 2 things without a price"). In a row a bill is unmarked, `list` is a list price, `≥` means part has no price, and `–` means no price of its own: never $0. A screen reader hears each in full. Under a filter the headline is what was found ("10 unattached volumes") and only resources' own prices are added.
99 - **Cost.** An AWS region, account and cloud show the last whole month billed; everything else is a list price. A bill stands in for its resources' prices and is never added to them. The total says it in words ("November's AWS bill, list prices for the rest, 2 things without a price"). In a row a bill is unmarked, `list` is a list price, `≥` means part has no price, and `–` means no price of its own: never $0. One resource says "About $12.00 a month at list price", or "No list price is known for it" and which bill any cost is inside, with no region's total beside it. A bill's Tax line says it is included in the AWS total. A screen reader hears each in full. Under a filter the headline is what was found ("10 unattached volumes") and only resources' own prices are added.
100100 - **With nothing open** the pane is where the money goes, then what the forge runs; under a filter it is the matches. **Build** (`c`) is `/infra/build`: the compose form, a build's progress (`?plan=`), a DNS record, the code it is kept as and the pinned forges. `/pinned` redirects there, and so does `/infra?plan=`.
101101 - **Filter.** `/`, then `kind:volume cloud:aws attached:no cost:>10 text`. Properties: kind, cloud, account, project, region, size, name, state, attached, made, for, app, cost. `!` negates, a comma means any of, `cost:unknown` is a value, and `app:unknown` finds what has no app known, on any cloud, which does not mean nothing uses it. It is in the URL as `?q=`.
102102 - **A resource** is at `/infra/-/<cloud>/<account>/<project>/<id>`, beside the tree, or full width on a phone: cost, state, what it is attached to and what it holds, an AWS list price's day, what it leaves out and whose file it is (or why there is none), the app an AWS resource is part of and how that is known (nothing when it is not), what it was made from, who made it, when it was read, and Ask about this (a talk with those facts, fenced as data).
103103 - **Keys.** j and k move, Enter opens, h and l (or the arrows) close and open, `/` filters and Enter goes to the first match.
104 - **States.** No account (a link to /settings/cloud), not read yet, a failed read (one line: when, why, and how old what is shown is), a kind that could not be read with its reason (on its project and on the account, which says where; under the headline's sum, "Not everything is listed: 1 kind not read" links to that account, and text doors name it; a billed account's gaps count too, and change no sum), and a reading older than three of its duty's intervals. A project's note ("R2 is not switched on for this account") is a plain line and no trouble, on its account too when that has one project.
104 - **States.** No account (a link to /settings/cloud), not read yet, a failed read (one line: when, why, and how old what is shown is), a kind that could not be read with its reason (on its project and on the account, which says where; under the headline's sum, "Not everything is listed: 1 kind not read" links to that account, and text doors name it; a billed account's gaps count too, and change no sum), and a reading older than three of its duty's intervals. A project's note ("R2 is not switched on for this account") is a plain line and no trouble, on its account too when that has one project. **Check the account** (`a` in the terminal) opens the account: see [Cloud accounts](cloud.md#what-was-not-read-17637).
105105 - **Terminal.** `:` then Cloud resources, or `/` in Infra (`src/tui/screens/cloudtree.ts`): the same list, filter and facts, the List price, Old price, Price from and No price lines among them (both read `factsOf`); `tab` changes pane, `w` opens the web page, `P` reads every account.
106106 - **Tool.** `infra` `{action: "list", id: "<filter line>"}` and `{action: "cloud", id: "<cloud>/<account>/<project>/<id>"}`.
107107
src/cloud/tree.ts +51 −5
@@ -106,7 +106,7 @@ export function costSays(n: CloudNode): string {
106106 if (m.billed + m.list === 0) return "";
107107 return [
108108 ...(m.billed > 0 ? [billSays(n)] : []),
109 ...(m.list === 0 ? [] : [m.billed > 0 ? "list prices for the rest" : n.resource === undefined ? "list prices" : "list price"]),
109 ...(m.list === 0 ? [] : [m.billed > 0 ? "list prices for the rest" : "list prices"]),
110110 ...(m.unknown === 0 ? [] : [`${many(m.unknown, "thing")} without a price`]),
111111 ].join(", ");
112112 }
@@ -115,7 +115,17 @@ export function costSays(n: CloudNode): string {
115115 * A node's cost as a line of text: "$603.62 a month: November's AWS bill, list prices for the
116116 * rest".
117117 */
118 export const costLine = (n: CloudNode): string => (n.money.billed + n.money.list === 0 ? "" : `${dollars(n.money.cents)} a month: ${[costSays(n), unreadLine(n)].filter((x) => x !== "").join(". ")}`);
118 export const costLine = (n: CloudNode): string =>
119 n.money.billed + n.money.list === 0 ? "" : n.resource !== undefined ? `About ${dollars(n.money.cents)} a month at list price` : `${dollars(n.money.cents)} a month: ${[costSays(n), unreadLine(n)].filter((x) => x !== "").join(". ")}`;
120
121 /**
122 * Said where no price is known. A bill it is inside is named with no sum: a region's total beside
123 * one thing reads as that thing's cost.
124 */
125 export function unpricedSays(v: CloudView, n: CloudNode): string {
126 const inside = [3, 2].map((d) => (n.path.length >= d ? nodeAt(v.whole, n.path.slice(0, d)) : undefined)).find((x) => x?.month !== undefined);
127 return `${n.resource === undefined ? "No prices known here." : "No list price is known for it."}${inside === undefined ? "" : ` Any cost is inside ${billSays(inside)}.`}`;
128 }
119129
120130 export type Level = "cloud" | "account" | "project" | "resource";
121131
@@ -219,6 +229,36 @@ const groupBy = <T>(all: readonly T[], key: (x: T) => string): Map<string, T[]>
219229 const unreadTrouble = (unread: AccountRead["unread"], href: string, where: (own: AccountRead["unread"]) => string = () => ""): Trouble[] =>
220230 [...groupBy(unread, (u) => u.reason)].map(([reason, own]) => ({ says: `Not read: ${[...new Set(own.map((u) => u.kind))].join(", ")}${where(own)}${listGaps(own).length === 0 ? ", so the app some things are part of is not known" : ""}. ${reason}`, href, label: "Check the account", gap: "here" }));
221231
232 /** A key the cloud does not take at all, so no permission would help. */
233 const BAD_KEY = /answered 401\b|InvalidClientTokenId|UnrecognizedClient|SignatureDoesNotMatch|AuthFailure|ExpiredToken/;
234
235 const NO_FIX = "No missing permission is named.";
236 /** What to change for a reason, by the permission it names. */
237 function fixFor(provider: string, reason: string): string {
238 const needs = /the key needs ([^;]+)/.exec(reason)?.[1]?.replace(/\.$/, "");
239 if (needs !== undefined && provider === "aws")
240 return `In AWS IAM, attach the managed policy ${needs.startsWith("ce:") ? "AWSBillingReadOnlyAccess" : "ViewOnlyAccess"} to this key's user or role, or allow only ${needs}. If it has that already, an organization policy or a permissions boundary refuses it.`;
241 if (needs !== undefined) return `At ${cloudName(provider)}, give this key ${needs}. If a key cannot be changed there, make a new one and press Rotate here.`;
242 if (BAD_KEY.test(reason)) return `${cloudName(provider)} does not accept this key: make a new one and press Rotate here.`;
243 return NO_FIX;
244 }
245
246 /** What the last read of an account could not see, with why and what to change: one a reason. */
247 export function readFixes(read: AccountRead): { readonly says: string; readonly fix: string }[] {
248 const { provider } = read;
249 const where = (own: AccountRead["unread"]): string => {
250 const at = [...new Set(own.map((u) => u.project))];
251 return provider !== "aws" ? "" : ` in ${at.length > NAMED ? `${at.length} regions` : at.join(", ")}`;
252 };
253 const again = (fix: string): string => (fix === NO_FIX ? `${fix} Press Read now on Infrastructure to try again.` : `${fix} After that, press Read now on Infrastructure.`);
254 return [
255 ...(read.error === "" ? [] : [{ says: `The last read: ${read.error.replace(/\.$/, "")}.`, fix: again(fixFor(provider, read.error)) }]),
256 ...[...groupBy(read.unread, (u) => u.reason)].map(([reason, own]) => ({ says: `${[...new Set(own.map((u) => u.kind))].join(", ")}${where(own)}: ${reason.replace(/\.$/, "")}.`, fix: again(fixFor(provider, reason)) })),
257 // The bill is asked for once a day, so Read now does not read it.
258 ...((read.bill?.error ?? "") === "" ? [] : [{ says: `Its bill: ${read.bill!.error.replace(/\.$/, "")}.`, fix: fixFor(provider, read.bill!.error) }]),
259 ];
260 }
261
222262 /** Read only for the app a thing is part of: without them the list and its sum are as whole. */
223263 const PART_OF_ONLY: ReadonlySet<string> = new Set(["stack", "target-group", "interface"]);
224264 const listGaps = (unread: AccountRead["unread"]): AccountRead["unread"] => unread.filter((u) => !PART_OF_ONLY.has(u.kind));
@@ -520,8 +560,14 @@ export function linkedFacts(root: CloudNode, n: CloudNode): Fact[] {
520560 /** The same as plain text, for a door with no links. */
521561 export const factsOf = (root: CloudNode, n: CloudNode): { readonly label: string; readonly value: string }[] => linkedFacts(root, n).map(({ label, value }) => ({ label, value }));
522562
523 /** AWS's names that do not say what they are; Cost Explorer does not itemise them, so "usually". */
524 const USUALLY = new Map([["EC2 - Other", "usually disks, snapshots, NAT gateways and data transfer"]]);
563 /**
564 * What a billed line's name does not say. Cost Explorer does not itemise "EC2 - Other", so
565 * "usually"; a month's total is the sum of its lines, tax among them.
566 */
567 const HINTS = new Map([["EC2 - Other", "usually disks, snapshots, NAT gateways and data transfer"], ["Tax", "included in the AWS total"]]);
568
569 /** Whether a month's total holds a tax line, said beside it. */
570 export const taxSays = (m: { readonly from: string; readonly lines: readonly { readonly service: string }[] } | undefined): string => (m?.lines.some((l) => l.service === "Tax") === true ? `${monthName(m.from)}'s total includes tax` : "");
525571
526572 /** Where the money goes: the largest sums known, billed services and priced resources together. */
527573 export interface Cost {
@@ -549,7 +595,7 @@ export function largestCosts(n: CloudNode, most: number): Cost[] {
549595 const regions = new Map(x.children.map((c) => [c.path[2]!, c]));
550596 for (const l of month.lines.slice(0, most)) {
551597 const at = regions.get(l.region);
552 out.push({ says: l.service, where: `${cloudName(x.path[0]!)} ${l.region === "" ? "region not known" : at === undefined ? "no region" : l.region}`, hint: USUALLY.get(l.service) ?? "", path: at?.path ?? x.path, cents: Math.round(l.cents), from: "billed" });
598 out.push({ says: l.service, where: `${cloudName(x.path[0]!)} ${l.region === "" ? "region not known" : at === undefined ? "no region" : l.region}`, hint: HINTS.get(l.service) ?? "", path: at?.path ?? x.path, cents: Math.round(l.cents), from: "billed" });
553599 }
554600 return;
555601 }
src/tui/screens/cloud.ts +5 −2
@@ -1,7 +1,7 @@
11 /**
22 * Cloud accounts in the terminal, a forge admin's (#2199): each account with
33 * what it is used for, when it was verified and last used, and today's vendor
4 * calls, as Settings → Cloud accounts shows them. `a` attaches (verified, then
4 * calls, as Settings → Cloud accounts shows them. `enter` opens one: what was not read and what to change. `a` attaches (verified, then
55 * sealed), `C` connects a cloud the guided way (/cloud/connect: which cloud, where its key is
66 * made and what to tick, then the key; named for you), `v` re-verifies, `r` rotates, `n` renames, `x` removes — all through
77 * `actions/cloud.ts`, so the checks are the page's. A token is typed masked and
@@ -21,6 +21,7 @@ import { style } from "../term/style.ts";
2121 import { truncate } from "../term/width.ts";
2222 import type { Session } from "../session.ts";
2323 import { fill, len, split } from "../ui/layout.ts";
24 import { accountScreen } from "./cloud_account.ts";
2425 import { ListState, drawList, later, promptScreen, type ListRow } from "./common.ts";
2526 import type { PaletteEntry } from "./entries.ts";
2627 import { infraScreen } from "./infra.ts";
@@ -140,6 +141,7 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen {
140141 title: "Cloud accounts",
141142 keys: [
142143 binding(["j", "k"], "move cursor"),
144 binding(["enter"], "what was not read, and the fix"),
143145 binding(["a"], "attach"),
144146 binding(["C"], "connect a cloud, guided"),
145147 binding(["I"], "infrastructure: what runs on these accounts"),
@@ -191,7 +193,8 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen {
191193 const a = accounts()[state.index];
192194 if (a === undefined) return false;
193195 const { provider, name } = a;
194 if (e.key === "v") {
196 if (e.key === "enter") ctx.push(accountScreen(f, ctx, provider, name));
197 else if (e.key === "v") {
195198 say(`Verifying ${provider}/${name}…`);
196199 void settle(reverify(f.app, f.user, provider, name), () => `Verified ${provider}/${name}.`);
197200 } else if (e.key === "r")
src/tui/screens/cloud_account.ts added +51
@@ -0,0 +1,51 @@
1 /**
2 * One cloud account in the terminal (#17532, #17637): what its last read could not see, the
3 * permission each names and what to change, as its row at /settings/cloud says it (`readFixes`).
4 * `enter` on Cloud accounts opens it, and `a` on Cloud resources. A forge admin's, and read from the
5 * forge's database alone.
6 */
7
8 import { cloudOverview } from "../../cloud/overview.ts";
9 import { accountReads } from "../../cloud/projects.ts";
10 import { readFixes } from "../../cloud/tree.ts";
11 import type { Ctx, Screen } from "../app/app.ts";
12 import { binding } from "../app/keys.ts";
13 import type { Session } from "../session.ts";
14 import { style } from "../term/style.ts";
15 import { wrap } from "../term/width.ts";
16 import { Scroll, ago, drawLines } from "./common.ts";
17
18 /** The account's lines; anyone but a forge admin gets none of them. */
19 export function accountLines(f: Session, provider: string, name: string): string[] {
20 const all = cloudOverview(f.app, f.user);
21 if (!all.ok) return ["Cloud accounts are a forge admin's."];
22 const a = all.value.accounts.find((x) => x.provider === provider && x.name === name);
23 if (a === undefined) return [`No account ${provider}/${name} is attached.`];
24 const read = accountReads(f.app.db).find((r) => r.provider === provider && r.account === name);
25 const fixes = read === undefined ? [] : readFixes(read);
26 return [
27 a.summary,
28 `${a.writeAllowed ? "Writes allowed" : "Read-only"} · ${read === undefined ? "its resources are not read yet" : `asked for its resources ${ago(read.askedAt)}`}`,
29 ...fixes.flatMap((x) => ["", `Not read: ${x.says}`, x.fix]),
30 "",
31 fixes.length > 0 ? "Here, Rotate is r on Cloud accounts, and Read now is P on Cloud resources." : read === undefined ? "Press P on Cloud resources to read it." : "Its last read reports nothing missing.",
32 ];
33 }
34
35 export function accountScreen(f: Session, ctx: Ctx, provider: string, name: string): Screen {
36 const scroll = new Scroll();
37 let room = 80;
38 // Read once: a key only moves the page.
39 const text = accountLines(f, provider, name);
40 const lines = (): string[] => text.flatMap((l) => (l === "" ? [""] : wrap(l, room)));
41 return {
42 title: `${provider}/${name}`,
43 keys: [binding(["j", "k"], "scroll"), binding(["esc"], "back")],
44 render(area, s) {
45 const c = ctx.theme.c;
46 room = Math.max(10, area.w - 2);
47 drawLines(s, area, c, scroll, lines().map((l) => [{ text: l, style: l.startsWith("Not read:") ? style(c.fg, c.bg) : style(c.mutedFg, c.bg) }]));
48 },
49 key: (e) => scroll.key(e, lines().length),
50 };
51 }
src/tui/screens/cloudtree.ts +13 −4
@@ -6,7 +6,7 @@
66 */
77
88 import { cloudResources, readProjectsNow } from "../../actions/infra.ts";
9 import { billSays, cloudName, costLine, costliestOf, factsOf, findingOf, isStale, largestCosts, moneyMark, nodeAt, unreadAccounts, unreadLine, unused, type CloudNode, type CloudView } from "../../cloud/tree.ts";
9 import { cloudName, costLine, costliestOf, factsOf, findingOf, isStale, largestCosts, moneyMark, nodeAt, unreadAccounts, unreadLine, unpricedSays, unused, type CloudNode, type CloudView } from "../../cloud/tree.ts";
1010 import { dollars } from "../../cloud/prices.ts";
1111 import { keyOf } from "../../web/keymap.ts";
1212 import type { Ctx, Screen } from "../app/app.ts";
@@ -15,6 +15,7 @@ import type { Session } from "../session.ts";
1515 import { style } from "../term/style.ts";
1616 import { truncate, wrap } from "../term/width.ts";
1717 import { fill, len, split } from "../ui/layout.ts";
18 import { accountScreen } from "./cloud_account.ts";
1819 import { Filter, ListState, Scroll, ago, drawLines, hitList, openOnWeb } from "./common.ts";
1920 import type { PaletteEntry } from "./entries.ts";
2021 import { drawTree } from "./workspace_draw.ts";
@@ -35,13 +36,12 @@ const markOf = (n: CloudNode): string => {
3536
3637 /** What a node says when it is open: its cost first, then its facts or its costliest resources. */
3738 export function cloudLines(v: CloudView, n: CloudNode): string[] {
38 const inside = [3, 2].map((d) => (n.path.length >= d ? nodeAt(v.whole, n.path.slice(0, d)) : undefined)).find((x) => x?.month !== undefined);
39 const cost = costLine(n) || (n.count === 0 ? "No resources." : `No price of its own${inside === undefined ? "" : `: inside ${billSays(inside)}, ${dollars(inside.money.cents)} for ${inside.name}`}.`);
39 const cost = costLine(n) || (n.count === 0 ? "No resources." : unpricedSays(v, n));
4040 const head = [n.path.map((p, i) => (i === 0 ? cloudName(p) : (nodeAt(v.whole, n.path.slice(0, i + 1))?.name ?? p))).join(" ▸ "), cost];
4141 const read = n.readAt === "" ? "" : `Read ${ago(n.readAt)}${n.trouble.length === 0 && isStale(n.path[0]!, n.readAt, v.now) ? " (old)" : ""}`;
4242 // A cloud's own line names its accounts' gaps, since there is no link to follow.
4343 const under = n.path.length >= 2 ? [] : unreadAccounts(n).flatMap((a) => a.trouble.filter((t) => t.gap !== undefined).map((t) => ({ ...t, says: `${a.name}: ${t.says}` })));
44 const trouble = [...n.trouble, ...under].map((t) => `! ${t.says} ${t.label}: ${t.href}`);
44 const trouble = [...n.trouble, ...under].map((t) => `! ${t.says} ${t.label}: a, or ${t.href}`);
4545 if (n.resource !== undefined) return [...head, "", ...factsOf(v.whole, n).map((f) => `${f.label.padEnd(12)} ${f.value}`), `${"Created".padEnd(12)} ${n.resource.createdAt.slice(0, 10)}`, read];
4646 const goes = v.q.text === "" ? largestCosts(n, 6).filter((c) => c.from === "billed") : [];
4747 const line = (sum: string, words: string): string => `${sum.padStart(13)} ${words}`;
@@ -106,6 +106,7 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen {
106106 binding(["h"], "collapse"),
107107 binding([keyOf("search")], "filter: kind: cloud: region: cost:>10 text"),
108108 binding(["tab"], "tree / what is open"),
109 binding(["a"], "check the account: what was not read, and the fix"),
109110 binding(["w"], "open on the web"),
110111 binding(["P"], "read every account now"),
111112 ],
@@ -193,6 +194,14 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen {
193194 return true;
194195 }
195196 if (n === undefined) return false;
197 if (e.key === "a") {
198 const at = (focus === "pane" && opened !== undefined ? nodeAt(v.root, opened) : undefined) ?? n;
199 // On a cloud, its one account, else the first with something to check.
200 const account = at.path.length >= 2 ? at.path : (at.children.length === 1 ? at.children[0] : (at.children.find((x) => x.trouble.length > 0) ?? at.children[0]))?.path;
201 if (account === undefined) return false;
202 ctx.push(accountScreen(f, ctx, account[0]!, account[1]!));
203 return true;
204 }
196205 if (e.key === "w") {
197206 openOnWeb(f, ctx, `/infra/-/${n.path.map(encodeURIComponent).join("/")}`, n.name);
198207 return true;
src/web/pages/cloud.ts +10 −1
@@ -25,6 +25,8 @@ import { lastReading } from "../../cloud/watch_read.ts";
2525 import { spendOf } from "../../cloud/ceiling.ts";
2626 import { warmOf } from "../../cloud/warm_pool.ts";
2727 import { dollars } from "../../cloud/prices.ts";
28 import { accountReads, type AccountRead } from "../../cloud/projects.ts";
29 import { readFixes } from "../../cloud/tree.ts";
2830 import { auditToday } from "../../core/cloud_audit.ts";
2931 import {
3032 getCloudAccount,
@@ -84,7 +86,14 @@ function ceilingLine(db: Database, a: CloudAccount): string {
8486 return `ceiling $${s.ceilingDollars} a month · ${dollars(s.monthlyCents)} counted from this account's machines and databases · ${s.leftCents >= 0 ? `${dollars(s.leftCents)} left` : `${dollars(-s.leftCents)} over`}`;
8587 }
8688
89 /** What the last read could not see, each with the permission it names and what to change. */
90 function readFacts(reads: readonly AccountRead[], a: CloudAccount): { label: string; value: Html }[] {
91 const read = reads.find((r) => r.provider === a.provider && r.account === a.name);

Both doors: readFixes is shown only on the page. Show it in src/tui/screens/cloud.ts too, so a terminal user sees the missing permission and the fix, and add its how-to to the cloud accounts feature doc.

92 return read === undefined ? [] : readFixes(read).map((f) => ({ label: "Not\u00a0read", value: html`${f.says}<br />${f.fix}` }));
93 }
94
8795 function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[], uses: Map<string, VendorUse[]>): Html {
96 const inventory = accountReads(db);
8897 const rows = accounts.map((a) => {
8998 const last = reads.find((r) => r.provider === a.provider && r.name === a.name);
9099 return row({
@@ -94,7 +103,7 @@ function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[]
94103 meta: html`${a.summary}<br />${usedFor(uses.get(VENDOR_OF[a.provider]))}<br />${HOME[a.provider]}<br />verified ${a.verifiedAt ? time(a.verifiedAt) : "never"} ·
95104 ${last ? html`last used ${time(last.at)} by ${runWords(last.run)}` : "never used"} ·
96105 ${a.writeAllowed ? "writes allowed" : "read-only"}<br />${ceilingLine(db, a)}`,
97 facts: [...watchFacts(db, a), ...warmFacts(db, a)],
106 facts: [...readFacts(inventory, a), ...watchFacts(db, a), ...warmFacts(db, a)],
98107 trail: html`<div class="row-fields">
99108 <form method="post" action="/settings/cloud/verify">
100109 ${hidden(a.provider, a.name)}${btn("Verify", { size: "sm", label: `Verify ${a.name}` })}
src/web/pages/cloud_tree.ts +5 −4
@@ -18,7 +18,6 @@ import {
1818 isStale,
1919 largestCosts,
2020 lastMonth,
21 billSays,
2221 costSays,
2322 findingOf,
2423 moneyMark,
@@ -31,6 +30,8 @@ import {
3130 unreadAccounts,
3231 unreadSays,
3332 nodeAt,
33 taxSays,
34 unpricedSays,
3435 unused,
3536 type CloudNode,
3637 type CloudQuery,
@@ -174,10 +175,10 @@ function totalOf(v: CloudView): Html {
174175
175176 /** A node's cost under its name. */
176177 function sum(v: CloudView, n: CloudNode): Html {
178 if (n.resource !== undefined && n.money.list > 0) return html`<p class="cloud-sum">About <span class="num">${dollars(n.money.cents)}</span> a month <span class="muted">at list price</span></p>`;
177179 if (n.money.billed + n.money.list > 0) return html`<p class="cloud-sum"><span class="num">${dollars(n.money.cents)}</span> a month <span class="muted">${costSays(n)}${unreadLinks(v, n)}</span></p>`;
178180 if (n.money.unknown + n.money.unread === 0 && (n.path.length >= 2 || n.gaps === 0)) return html``;
179 const inside = [3, 2].map((d) => (n.path.length >= d ? nodeAt(v.whole, n.path.slice(0, d)) : undefined)).find((x) => x?.month !== undefined);
180 return html`<p class="muted" data-unpriced>${n.resource === undefined ? "No prices known here" : "No price of its own"}${inside === undefined ? null : html`: it is inside ${billSays(inside)}, ${dollars(inside.money.cents)} for ${inside.name}`}.${unreadLinks(v, n)}</p>`;
181 return html`<p class="muted" data-unpriced>${unpricedSays(v, n)}${unreadLinks(v, n)}</p>`;
181182 }
182183
183184 /** The largest sums under a node, each a link to where it is. */
@@ -234,7 +235,7 @@ function billLine(n: CloudNode): Html {
234235 const now = months.find((m) => !m.whole);
235236 const last = lastMonth(n);
236237 if (now === undefined && last === undefined) return n.read?.bill?.readAt === "" ? html`<p class="muted small">Its bill is not read yet, so what it costs is not known.</p>` : (n.read?.bill ?? null) === null ? html`` : html`<p class="muted small">AWS listed no cost for this account.</p>`;
237 return html`<p class="muted small" data-bill>${now === undefined ? null : html`${monthName(now.from)} so far ${dollars(now.cents)} · `}Before credits · Bill read ${time(n.read!.bill!.readAt)}</p>`;
238 return html`<p class="muted small" data-bill>${now === undefined ? null : html`${monthName(now.from)} so far ${dollars(now.cents)} · `}${taxSays(last ?? now) === "" ? null : html`${taxSays(last ?? now)} · `}Before credits · Bill read ${time(n.read!.bill!.readAt)}</p>`;
238239 }
239240
240241 /** What is open beside the tree: a branch's costliest resources, or one resource's facts. */
test/cloud-tree.test.ts +62 −2
@@ -11,7 +11,7 @@ import { tmpdir } from "node:os";
1111 import { join } from "node:path";
1212 import { createApp, type App } from "../src/app.ts";
1313 import { cloudResources } from "../src/actions/infra.ts";
14 import { costLine, costliestOf, factsOf, findingOf, largestCosts, moneyMark, moneyWords, nodeAt, type CloudNode, type CloudView } from "../src/cloud/tree.ts";
14 import { costLine, costliestOf, factsOf, findingOf, largestCosts, moneyMark, moneyWords, nodeAt, readFixes, type CloudNode, type CloudView } from "../src/cloud/tree.ts";
1515 import { aboutContext, aboutLine } from "../src/core/talk_about.ts";
1616 import { createSession } from "../src/core/sessions.ts";
1717 import { createToken } from "../src/core/tokens.ts";
@@ -22,6 +22,9 @@ import { cloudLines, cloudTreeScreen } from "../src/tui/screens/cloudtree.ts";
2222 import { headlessTerminal } from "../src/tui/term/terminal.ts";
2323 import { mcpTool } from "./helpers/mcp.ts";
2424 import { statements } from "./helpers/statements.ts";
25 import { cloudScreen } from "../src/tui/screens/cloud.ts";
26 import { accountLines } from "../src/tui/screens/cloud_account.ts";
27 import { Session } from "../src/tui/session.ts";
2528 import { settleApp } from "./helpers/tui.ts";
2629
2730 let dir = "";
@@ -186,7 +189,64 @@ describe("with accounts", () => {
186189 test("under a filter a resource still says its ties and the bill it is in", async () => {
187190 const pane = await (await get("/infra/-/aws/main/us-east-1/volume:vol-1?fragment=1&q=kind%3Avolume")).text();
188191 expect(pane).toContain('<a href="/infra/-/aws/main/us-east-1/machine:i-1?q=kind%3Avolume">api</a>');
189 expect(pane).toContain("it is inside November&#39;s AWS bill, $40.00 for us-east-1");
192 // A region's total beside one volume would read as the volume's cost.
193 expect(pane).toContain("No list price is known for it. Any cost is inside November&#39;s AWS bill.");
194 expect(pane).not.toContain("$40.00");
195 expect(cloudLines(view(), at(view(), "aws", "main", "us-east-1", "volume:vol-1"))[1]).toBe("No list price is known for it. Any cost is inside November's AWS bill.");
196 const priced = await (await get("/infra/-/digitalocean/main/site/machine:1?fragment=1")).text();
197 expect(priced).toContain('About <span class="num">$12.00</span> a month <span class="muted">at list price</span>');
198 expect(cloudLines(view(), at(view(), "digitalocean", "main", "site", "machine:1"))[1]).toBe("About $12.00 a month at list price");
199 });
200
201 test("tax is said to be inside the AWS total, in the list and beside the bill, and is in it", async () => {
202 const aws = at(view(), "aws", "main");
203 expect(aws.money.cents).toBe(4700);
204 expect(largestCosts(aws, 6).find((c) => c.says === "Tax")).toMatchObject({ cents: 500, hint: "included in the AWS total" });
205 expect(cloudLines(view(), aws).join("\n")).toContain("Tax · AWS no region · included in the AWS total");
206 expect(await (await get("/infra/-/aws/main?fragment=1")).text()).toContain("November&#39;s total includes tax · Before credits");
207 });
208
209 test("the terminal: a on Cloud resources and enter on Cloud accounts show the page's says and fix lines", async () => {
210 const says = "Not read: database in us-east-1: the key needs rds:DescribeDBInstances.";
211 const fix = "In AWS IAM, attach the managed policy ViewOnlyAccess to this key's user or role, or allow only rds:DescribeDBInstances.";
212 const flat = (x: string): string => x.replace(/\s+/g, " ");
213 const tree = flat(await drawn("/account:main cloud:aws\rja"));
214 expect(tree).toContain(says);
215 expect(tree).toContain(fix);
216 expect(cloudLines(view(), at(view(), "aws", "main")).join("\n")).toContain("Check the account: a, or /settings/cloud#account-aws-main");
217 const terminal = headlessTerminal(60, 40);
218 const session = { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice };
219 const { app: tui, session: s } = createForgeApp(app, session, { terminal, exitHooks: false });
220 onTestFinished(() => void tui.stop?.());
221 tui.start();
222 tui.ctx.push(cloudScreen(s, tui.ctx));
223 await settleApp(tui);
224 terminal.feed("\r");
225 await settleApp(tui);
226 expect(flat(tui.screen.toText())).toContain("aws/main");
227 expect(flat(tui.screen.toText())).toContain("ViewOnlyAccess to this key's user or role");
228 expect(accountLines(s, "hetzner", "eu").join("\n")).toContain("Hetzner Cloud does not accept this key");
229 expect(accountLines(s, "digitalocean", "main").at(-1)).toContain("Press P on Cloud resources");
230 expect(accountLines(new Session(app, { sshUsername: "nobody", remoteAddress: "127.0.0.1" }), "aws", "main")).toEqual(["Cloud accounts are a forge admin's."]);
231 });
232
233 test("Check the account opens the account, which names each missing permission and what to change", async () => {
234 const trouble = at(view(), "aws", "main").trouble.find((t) => t.says.startsWith("Not read: database"))!;
235 expect(trouble.href).toBe("/settings/cloud#account-aws-main");
236 const page = await (await get("/settings/cloud")).text();
237 const row = (id: string): string => page.slice(page.indexOf(`id="${id}"`)).split("</li>")[0]!;
238 expect(row("account-aws-main")).toContain("database in us-east-1: the key needs rds:DescribeDBInstances.");
239 expect(row("account-aws-main")).toContain("attach the managed policy ViewOnlyAccess to this key&#39;s user or role, or allow only rds:DescribeDBInstances.");
240 expect(row("account-hetzner-eu")).toContain("Hetzner Cloud does not accept this key: make a new one and press Rotate here.");
241 expect(row("account-digitalocean-main")).not.toContain("Not\u00a0read");
242 const read = { provider: "aws", account: "x", askedAt: AT, error: "", unread: [], bill: { readAt: "", error: "AccessDenied: the key needs ce:GetCostAndUsage; asked again tomorrow (UTC)", requestsToday: 1, months: [] } };
243 expect(readFixes(read)[0]!.fix).toContain("AWSBillingReadOnlyAccess to this key's user or role, or allow only ce:GetCostAndUsage.");
244 expect(readFixes(read)[0]!.fix).not.toContain("Read now");
245 const gap = { provider: "cloudflare", account: "x", project: "p", kind: "bucket", since: AT } as const;
246 expect(readFixes({ ...read, provider: "cloudflare", bill: null, unread: [{ ...gap, reason: "answered 403: the key needs Workers R2 Storage Read" }, { ...gap, reason: "no answer in 10 seconds" }] }).map((f) => f.fix)).toEqual([
247 "At Cloudflare, give this key Workers R2 Storage Read. If a key cannot be changed there, make a new one and press Rotate here. After that, press Read now on Infrastructure.",
248 "No missing permission is named. Press Read now on Infrastructure to try again.",
249 ]);
190250 });
191251
192252 test("a filter's headline is what it found; Back's fragment is the pane alone; building is its own page", async () => {

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs