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

Terraform state is read as a resource table with secrets masked #16037

Merged opened this

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

Merged

scout/forge:scout/16025-terraform-state-is-read-as-a-resource-ta → main 0 commits fork

  • Merged. scout/16025-terraform-state-is-read-as-a-resource-ta was merged into main as 1f70a59.

Review

Sign in to review this change.
15 files changed +392 −2
docs/design/areas/code.md +1
@@ -20,3 +20,4 @@ An HTML file's preview (`render/html_preview.ts`): `.html-frame` is a bare sandb
2020 - `.hexdump` — the last-resort view of a binary file (`render/hexdump.ts`): a `pre.card` of offset, sixteen hex bytes and their ASCII in `--mono` 12.5px, scrolling sideways inside its own box so the page never does at 390px.
2121
2222 - `.waveform` — a PCM WAV's peaks above its player (`render/audio.ts`): a `figure` with its browser margins zeroed and 12px under it, an SVG 96px tall on `--muted` with `--muted-fg` strokes, and a caption line whose height (1.5em) is reserved so nothing shifts; the caption wraps anywhere, so it never scrolls the page at 360px.
23 - Terraform state (`render/tfstate.ts`): no new class. The version, serial and Terraform version are a `dl.status-rows`; the resources are the existing `.table` with `data-dense`, each row's attributes a `dl.status-rows` inside its last cell.
docs/features/file-kinds.md +1
@@ -75,6 +75,7 @@ The forge draws a file on its page when its kind is below and it is within the s
7575 - **Mailbox**, drawn up to 5 MB: `.mbox`
7676 - **Bibliography**, drawn up to 1 MB: `.bib`
7777 - **Protocol Buffers**, drawn up to 1 MB: `.proto`
78 - **Terraform state**, drawn up to 5 MB: `.tfstate`
7879 - **INI or properties**, drawn up to 1 MB: `.ini`, `.properties`
7980 - **Rich text**, drawn up to 5 MB: `.rtf`
8081 - **XML**, drawn up to 5 MB: `.xml`
docs/features/file-tfstate.md added +14
@@ -0,0 +1,14 @@
1 ---
2 topic: Files in the browser
3 row: A Terraform state file opens as its resources, secrets masked
4 ---
5 # A Terraform state file opens as its resources, secrets masked
6
7 A `.tfstate` file (JSON) opens as its version, serial and Terraform version, then a table of resources: mode, type, name, provider, instance count and a few attributes. Source is one tap away.
8
9 - **Masking:** state holds secrets. An attribute value is shown only when its key is on a short exact allowlist of identifiers (`id`, `name`, `arn`, `region`, `instance_type` …); every other value is `••••••`. Nested values are never shown. Outputs show their names, never their values; control characters are stripped from every cell.
10 - **Cap:** 500 resources; the page says how many were left out. Over 5 MB, or a file that does not parse or has no `resources` array, keeps the source with one line why.
11 - **MCP:** `read_file` on a `.tfstate` carries `about: {kind, version, serial, total, resources}` (first 50, same masking).
12 - Every string is escaped; no script, no dependency.
13
14 Code: `src/web/render/tfstate.ts`, `src/web/render/kinds.ts`. Test: `test/render-tfstate.test.ts`.
scripts/kinds-guide.ts +1 −1
@@ -18,7 +18,7 @@ export const NAMES: Readonly<Record<FileKind, string>> = {
1818 excalidraw: "Excalidraw", step: "STEP model", iges: "IGES drawing", prproj: "Premiere project", sarif: "SARIF report", lcov: "Coverage (lcov)", junit: "JUnit report",
1919 opml: "OPML", feed: "RSS or Atom feed", env: "Env example", openapi: "OpenAPI", package: "package.json", manifest: "Dependency manifest", makefile: "Makefile",
2020 dockerfile: "Dockerfile", workflow: "GitHub workflow", compose: "Compose file", sql: "SQL", graphql: "GraphQL",
21 epub: "EPUB book", mbox: "Mailbox", bib: "Bibliography", proto: "Protocol Buffers", ini: "INI or properties", rtf: "Rich text", xml: "XML", text: "Other text", binary: "Other binary",
21 epub: "EPUB book", mbox: "Mailbox", bib: "Bibliography", proto: "Protocol Buffers", tfstate: "Terraform state", ini: "INI or properties", rtf: "Rich text", xml: "XML", text: "Other text", binary: "Other binary",
2222 };
2323
2424 /** 1_000_000 as `1 MB`; 4_000_000_000 as `4 GB`; no cap as `none: download only`. */
src/http/mcp/tools/read_file.ts +2
@@ -5,6 +5,7 @@ import { blobForRender, listTree } from "../../../git/read.ts";
55 import { readStl, sayStl, stlSize, TOO_LARGE } from "../../../text/stl.ts";
66 import { checkConfig, configKind, type ConfigKind } from "../../../text/config_check.ts";
77 import { describeMedia } from "../../../text/mp4.ts";
8 import { aboutTfstate } from "../../../web/render/tfstate.ts";
89 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
910
1011 export const tool: Tool = {
@@ -71,6 +72,7 @@ function aboutFile(path: string, body: Uint8Array, text: string | undefined): Re
7172 const { format, triangles } = stl.value;
7273 return { kind: "stl", format, triangles, size: stlSize(stl.value), says: sayStl(stl.value) };
7374 }
75 if (text !== undefined && /\.tfstate$/i.test(path)) return aboutTfstate(text);
7476 const media = describeMedia(path, body);
7577 if (media) return media;
7678 if (text === undefined) return undefined;
src/tui/screens/workspace.ts +2 −1
@@ -100,6 +100,7 @@ import { sqliteStep, sqliteView, type SqliteAt } from "./workspace_sqlite.ts";
100100 import { officeView } from "./workspace_office.ts";
101101 import { parquetView } from "./workspace_parquet.ts";
102102 import { bibView } from "./workspace_bib.ts";
103 import { tfstateView } from "./workspace_tfstate.ts";
103104 import { factsView } from "./workspace_facts.ts";
104105 import { depsView } from "./workspace_deps.ts";
105106 import { cadView } from "./workspace_cad.ts";
@@ -1577,7 +1578,7 @@ export function workspaceScreen(
15771578 // bytes as text is how a terminal ends up beeping at you.
15781579 const base = looksLikeImage(t.path) ? null : sqliteView(t.path, read.value.body, { table: 0, page: 1 });
15791580 if (base !== null && typeof base !== "string") db = read.value.body;
1580 const book = looksLikeImage(t.path) ? null : (base ?? sheetView(t.path, read.value.body) ?? officeView(t.path, read.value.body) ?? parquetView(t.path, read.value.body) ?? bibView(t.path, read.value.body) ?? factsView(t.path, read.value.body) ?? cadView(t.path, read.value.body, read.value.size, formatSize));
1581 const book = looksLikeImage(t.path) ? null : (base ?? sheetView(t.path, read.value.body) ?? officeView(t.path, read.value.body) ?? parquetView(t.path, read.value.body) ?? bibView(t.path, read.value.body) ?? tfstateView(t.path, read.value.body) ?? factsView(t.path, read.value.body) ?? cadView(t.path, read.value.body, read.value.size, formatSize));
15811582 if (looksLikeImage(t.path)) picture = read.value.body;
15821583 else if (book !== null && typeof book !== "string") sheet = book;
15831584 else if (typeof book === "string") note = book;
src/tui/screens/workspace_tfstate.ts added +34
@@ -0,0 +1,34 @@
1 /**
2 * A Terraform state file in the terminal workspace, read the way the page reads it: the same
3 * `parseTfstate`, drawn as a table of resources with every value masked unless its key is a
4 * plain identifier; outputs are listed by name. Without this the terminal would show the raw JSON,
5 * secrets and all.
6 *
7 * `tfstateView(path, body)` answers a table, a sentence (the workspace shows it as its note),
8 * or `null` for a file that is not a state.
9 */
10
11 import { fileKind, HEAD_BYTES, RENDER_CAP } from "../../web/render/kinds.ts";
12 import { MASK, parseTfstate } from "../../web/render/tfstate.ts";
13 import type { Table } from "../../text/csv.ts";
14
15 export function tfstateView(path: string, body: Uint8Array): Table | string | null {
16 if (fileKind(path, body.subarray(0, HEAD_BYTES)) !== "tfstate") return null;
17 if (body.length > RENDER_CAP.tfstate)
18 return `This file is over ${RENDER_CAP.tfstate / 1_000_000} MB, too large to open here. Download it instead.`;
19 const doc = parseTfstate(new TextDecoder().decode(body));
20 if ("error" in doc) return `This file is not drawn as Terraform state: ${doc.error}.`;
21 if (doc.resources.length === 0 && doc.outputs.length === 0) return "This state holds no resources.";
22 const header = ["Mode", "Type", "Name", "Provider", "Instances", "Attributes"];
23 const rows = doc.resources.map((r) => [
24 r.mode,
25 r.type,
26 r.name,
27 r.provider,
28 String(r.instances),
29 r.attributes.map((a) => `${a.key} ${a.value === undefined ? MASK : a.value}`).join(", "),
30 ]);
31 // Outputs are names only, as on the page: one row each, mode `output`.
32 for (const o of doc.outputs) rows.push(["output", "", o, "", "", MASK]);
33 return { header, rows, more: Math.max(0, doc.total - doc.resources.length), delimiter: ",", columns: header.length };
34 }
src/web/render/kinds.ts +7
@@ -15,6 +15,7 @@
1515
1616 import { binaryFacts, FACTS_EXTENSIONS } from "./binary-facts.ts";
1717 import { isSbomHead } from "./sbom.ts";
18 import { isTfstateHead } from "./tfstate.ts";
1819 import { isWasm } from "./wasm.ts";
1920
2021 export type FileKind =
@@ -85,6 +86,7 @@ export type FileKind =
8586 | "mbox"
8687 | "bib"
8788 | "proto"
89 | "tfstate"
8890 | "ini"
8991 | "rtf"
9092 | "xml"
@@ -185,6 +187,8 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
185187 mbox: 5 * MB,
186188 bib: 1 * MB,
187189 proto: 1 * MB,
190 // Parsed whole as JSON; a file over it keeps its source view.
191 tfstate: 5 * MB,
188192 ini: 1 * MB,
189193 rtf: 5 * MB,
190194 xml: 5 * MB,
@@ -347,6 +351,7 @@ const TEXTUAL: Readonly<Record<string, FileKind>> = {
347351 mbox: "mbox",
348352 bib: "bib",
349353 proto: "proto",
354 tfstate: "tfstate",
350355 pem: "cert",
351356 crt: "cert",
352357 cer: "cert",
@@ -578,6 +583,8 @@ export function fileKind(path: string, head: Uint8Array): FileKind {
578583 if (ext === "pem" || ext === "crt" || ext === "cer") return /-----BEGIN /.test(new TextDecoder().decode(head)) ? "cert" : "text";
579584 // CycloneDX and SPDX name themselves in a top-level key; any other JSON keeps its view.
580585 if (ext === "json" && isSbomHead(new TextDecoder().decode(head))) return "sbom";
586 // Terraform state is JSON: a `.tfstate` that does not open on `{` is only text.
587 if (ext === "tfstate") return isTfstateHead(head) ? "tfstate" : "text";
581588 // Collada opens on a `<COLLADA` root: a `.dae` that does not is only text.
582589 if (ext === "dae") return /<COLLADA[\s>]/.test(new TextDecoder().decode(head)) ? "model3d" : "text";
583590 // A Kdenlive project is MLT XML: a `.kdenlive` whose root is not `<mlt>` is only text.
src/web/render/renderers.ts +2
@@ -20,6 +20,7 @@ import { graphql } from "./graphql.ts";
2020 import { mbox } from "./mbox.ts";
2121 import { bib } from "./bib.ts";
2222 import { proto } from "./proto.ts";
23 import { tfstate } from "./tfstate.ts";
2324 import { ini } from "./ini.ts";
2425 import { rtf } from "./rtf.ts";
2526 import { xml } from "./xml.ts";
@@ -182,6 +183,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
182183 mbox,
183184 bib,
184185 proto,
186 tfstate,
185187 ini,
186188 rtf,
187189 xml,
src/web/render/tfstate.ts added +164
@@ -0,0 +1,164 @@
1 /**
2 * A Terraform state file (`.tfstate`, JSON) as its version, serial and a table of resources: mode,
3 * type, name, provider, how many instances, and the few attributes that are safe to show. State
4 * holds secrets (passwords, keys, tokens), so a value is drawn only when its key is on
5 * `SHOWN_KEYS`, an exact allowlist of identifiers; every other value is masked, and only a
6 * top-level scalar is ever considered, so a nested secret never reaches the page. Outputs show
7 * their names and never their values. At most `RESOURCE_CAP` resources are drawn, and the page
8 * says how many were left out; the array is cut before any loop walks it. Invalid JSON, or a file
9 * with no `resources` array, falls back to the source with the reason. Every string is escaped.
10 */
11
12 import { emptyList } from "../empty_words.ts";
13 import { escapeHtml, html, raw } from "../html.ts";
14 import { fileSize } from "../ui.ts";
15 import type { Rendered, RenderInput } from "./renderers.ts";
16
17 export const RESOURCE_CAP = 500;
18 export const ATTRIBUTE_CAP = 8;
19 export const OUTPUT_CAP = 100;
20 const VALUE_CAP = 120;
21 export const MASK = "••••••";
22
23 /** The only attribute keys whose value is shown. Exact names; nothing is matched by pattern. */
24 export const SHOWN_KEYS: ReadonlySet<string> = new Set([
25 "id", "name", "arn", "region", "location", "zone", "availability_zone", "instance_type", "ami",
26 "engine", "engine_version", "family", "size", "status", "state", "type", "cidr_block", "runtime",
27 "image", "namespace", "project", "account_id",
28 ]);
29
30 export interface Attribute {
31 readonly key: string;
32 /** The value as text when its key is allowlisted, otherwise undefined (masked). */
33 readonly value: string | undefined;
34 }
35 export interface TfResource {
36 readonly mode: string;
37 readonly type: string;
38 readonly name: string;
39 readonly provider: string;
40 readonly instances: number;
41 readonly attributes: readonly Attribute[];
42 }
43 export type Tfstate =
44 | {
45 readonly version: number;
46 readonly serial: number;
47 readonly terraform: string;
48 readonly total: number;
49 readonly resources: readonly TfResource[];
50 readonly outputs: readonly string[];
51 }
52 | { readonly error: string };
53
54 const isObj = (v: unknown): v is Record<string, unknown> =>
55 typeof v === "object" && v !== null && !Array.isArray(v);
56 /**
57 * Control characters (C0, DEL, C1) never survive the parse, so no door can pass one to a terminal.
58 */
59 const clean = (v: string): string => v.replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
60 const str = (v: unknown): string => (typeof v === "string" ? clean(v) : "");
61 const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0);
62
63 /** Is this the head of a Terraform state: a JSON object. The kind is decided by name and this. */
64 export const isTfstateHead = (head: Uint8Array): boolean =>
65 /^?\s*\{/.test(new TextDecoder().decode(head.subarray(0, 64)));
66
67 function attributes(instances: unknown): Attribute[] {
68 const first = Array.isArray(instances) && isObj(instances[0]) ? instances[0] : {};
69 const attrs = isObj(first.attributes) ? first.attributes : {};
70 const out: Attribute[] = [];
71 for (const key in attrs) {
72 if (out.length >= ATTRIBUTE_CAP) break;
73 if (!Object.hasOwn(attrs, key)) continue;
74 const v = attrs[key];
75 if (typeof v === "object" && v !== null) continue; // nested values are never shown
76 const shown = SHOWN_KEYS.has(key) && v !== null && v !== undefined ? clean(String(v)).slice(0, VALUE_CAP) : undefined;
77 out.push({ key: clean(key).slice(0, 80), value: shown });
78 }
79 return out;
80 }
81
82 /** Parse a state file's text. Pure; never throws. */
83 export function parseTfstate(source: string): Tfstate {
84 let doc: unknown;
85 try {
86 doc = JSON.parse(source.replace(/^/, ""));
87 } catch (e) {
88 return { error: `it is not valid JSON (${e instanceof Error ? e.message : "parse error"})` };
89 }
90 if (!isObj(doc) || !Array.isArray(doc.resources)) return { error: "it has no `resources` array" };
91 const resources = doc.resources.slice(0, RESOURCE_CAP).map((r): TfResource => {
92 const o = isObj(r) ? r : {};
93 return {
94 mode: str(o.mode).slice(0, 20),
95 type: str(o.type).slice(0, 200),
96 name: str(o.name).slice(0, 200),
97 provider: str(o.provider).slice(0, 300),
98 instances: Array.isArray(o.instances) ? o.instances.length : 0,
99 attributes: attributes(o.instances),
100 };
101 });
102 const outputs = isObj(doc.outputs) ? Object.keys(doc.outputs).slice(0, OUTPUT_CAP).map((k) => clean(k).slice(0, 200)) : [];
103 return {
104 version: num(doc.version),
105 serial: num(doc.serial),
106 terraform: str(doc.terraform_version).slice(0, 40),
107 total: doc.resources.length,
108 resources,
109 outputs,
110 };
111 }
112
113 export function tfstate(input: RenderInput): Rendered {
114 const doc = parseTfstate(new TextDecoder().decode(input.body));
115 if ("error" in doc) return { content: html``, lines: 0, fallback: `This file is not drawn as Terraform state: ${doc.error}.` };
116 const attrs = (r: TfResource): string =>
117 r.attributes.length === 0
118 ? ""
119 : `<dl class="status-rows">${r.attributes
120 .map((a) => `<div class="status-row"><dt>${escapeHtml(a.key)}</dt><dd>${a.value === undefined ? MASK : escapeHtml(a.value)}</dd></div>`)
121 .join("")}</dl>`;
122 let rows = "";
123 for (const r of doc.resources)
124 rows += `<tr><td>${escapeHtml(r.mode)}</td><td>${escapeHtml(r.type)}</td><td>${escapeHtml(r.name)}</td><td>${escapeHtml(r.provider)}</td><td>${r.instances.toLocaleString()}</td><td>${attrs(r)}</td></tr>`;
125 const table =
126 doc.resources.length === 0
127 ? String(emptyList("rows", { noAction: true }))
128 : `<table class="table" data-dense aria-label="Resources"><thead><tr><th scope="col">Mode</th><th scope="col">Type</th><th scope="col">Name</th><th scope="col">Provider</th><th scope="col">Instances</th><th scope="col">Attributes</th></tr></thead><tbody>${rows}</tbody></table>`;
129 const left = doc.total - doc.resources.length;
130 const more =
131 left > 0
132 ? `<p class="muted small">Showing ${doc.resources.length.toLocaleString()} of ${doc.total.toLocaleString()} resources, ${left.toLocaleString()} left out. The rest is in the raw file.</p>`
133 : "";
134 const outs =
135 doc.outputs.length > 0
136 ? `<h3>Outputs</h3><p>${doc.outputs.map((o) => `<code>${escapeHtml(o)}</code>`).join(", ")}</p>`
137 : "";
138 const fact = (k: string, v: string): string => `<div class="status-row"><dt>${k}</dt><dd>${escapeHtml(v)}</dd></div>`;
139 const facts = `<dl class="status-rows" aria-label="State">${fact("Version", String(doc.version))}${fact("Serial", String(doc.serial))}${doc.terraform === "" ? "" : fact("Terraform", doc.terraform)}</dl>`;
140 const note = `<p class="muted small">Values are masked unless the attribute is a plain identifier; outputs show names only.</p>`;
141 const content = html`${raw(facts)}${raw(table)}${raw(more)}${raw(outs)}${raw(note)}`;
142 return { content, lines: 0, summary: `${doc.total.toLocaleString()} ${doc.total === 1 ? "resource" : "resources"} · ${fileSize(input.size)}` };
143 }
144
145 /** The same facts for the MCP file tool: the page's parse, values masked, resources cut to 50. */
146 export function aboutTfstate(source: string): Record<string, unknown> {
147 const doc = parseTfstate(source);
148 if ("error" in doc) return { kind: "tfstate", parses: false, message: doc.error };
149 return {
150 kind: "tfstate",
151 parses: true,
152 version: doc.version,
153 serial: doc.serial,
154 total: doc.total,
155 resources: doc.resources.slice(0, 50).map((r) => ({
156 mode: r.mode,
157 type: r.type,
158 name: r.name,
159 provider: r.provider,
160 instances: r.instances,
161 attributes: Object.fromEntries(r.attributes.map((a) => [a.key, a.value ?? MASK])),
162 })),
163 };
164 }
test/fuzz-renderers.test.ts +6
@@ -207,6 +207,12 @@ export const SAMPLES: Readonly<Record<string, { path: string; files: readonly st
207207 '@string{j = "J. <b>X</b>"}\n@comment{x}\n@article{k1, author = {Erd{\\H{o}}s, P. and M{\\"u}ller}, title = {A {B} <i>c</i>}, journal = j # {!}, year = 2001}\n@inproceedings{k2, booktitle = "Proc", year = {2}}\n@article{bad, title = {open\n',
208208 ],
209209 },
210 tfstate: {
211 path: "terraform.tfstate",
212 files: [
213 '{"version":4,"terraform_version":"1.6.0","serial":7,"lineage":"x","outputs":{"<b>pw</b>":{"value":"s3cret","sensitive":true}},"resources":[{"mode":"managed","type":"aws_db_instance","name":"<script>a</script>","provider":"provider[\\"registry.terraform.io/hashicorp/aws\\"]","instances":[{"attributes":{"id":"db-1","password":"hunter2","tags":{"k":"v"},"engine":"javascript:alert(1)"}}]}]}',
214 ],
215 },
210216 proto: {
211217 path: "user.proto",
212218 files: [
test/mcp-read-file.test.ts +13
@@ -80,6 +80,12 @@ beforeAll(async () => {
8080 ],
8181 }),
8282 );
83 ok(
84 await commitToBranch(app, owner, pub, {
85 message: "state",
86 files: [{ path: "infra/terraform.tfstate", content: JSON.stringify({ version: 4, serial: 2, resources: [{ mode: "managed", type: "aws_db_instance", name: "db", provider: "aws", instances: [{ attributes: { id: "db-1", password: "hunter2" } }] }] }) }],
87 }),
88 );
8389 tok["owner"] = createToken(app.db, owner.id, "o", "ro").token;
8490 tok["stranger"] = createToken(app.db, stranger.id, "s", "ro").token;
8591 }, 30_000);
@@ -147,3 +153,10 @@ test("a config file says whether it parses; other files carry no about", async (
147153 expect((await read(t, { repo: "ada/pub", path: "good.json" })).value.about).toEqual({ kind: "json", parses: true });
148154 expect((await read(t, { repo: "ada/pub", path: "src/a.txt" })).value.about).toBeUndefined();
149155 });
156
157 test("a .tfstate file carries about with its secrets masked", async () => {
158 const file = (await read(tok["stranger"]!, { repo: "ada/pub", path: "infra/terraform.tfstate" })).value;
159 expect(file.about.kind).toBe("tfstate");
160 expect(file.about.total).toBe(1);
161 expect(file.about.resources[0].attributes).toEqual({ id: "db-1", password: "••••••" });
162 });
test/render-kinds.test.ts +1
@@ -123,6 +123,7 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = {
123123 rtf: [enc("{\\rtf1 hi}"), "rtf", "application/octet-stream"],
124124 xml: [enc("<a/>"), "xml", "application/octet-stream"],
125125 proto: [enc('syntax = "proto3";\nmessage A {}\n'), "proto", "application/octet-stream"],
126 tfstate: [enc('{"version":4,"resources":[]}'), "tfstate", "application/octet-stream"],
126127 sarif: [enc('{"runs":[]}'), "sarif", "application/octet-stream"],
127128 opml: [enc("<opml/>"), "opml", "application/octet-stream"],
128129 rss: [enc("<rss/>"), "feed", "application/octet-stream"],
test/render-tfstate.test.ts added +94
@@ -0,0 +1,94 @@
1 /**
2 * Terraform state as a resource table: parse, masking, escaping, the cap, the fallback, the MCP
3 * facts.
4 */
5 import { describe, expect, test } from "bun:test";
6 import { MASK, RESOURCE_CAP, aboutTfstate, parseTfstate, tfstate } from "../src/web/render/tfstate.ts";
7 import { RENDER_CAP, fileKind } from "../src/web/render/kinds.ts";
8 import { RENDERERS, plainReason, rendererFor } from "../src/web/render/renderers.ts";
9
10 import type { Blob } from "../src/view/source.ts";
11 const enc = (s: string): Uint8Array => new TextEncoder().encode(s);
12 const draw = (text: string) => tfstate({ path: "terraform.tfstate", size: text.length, body: enc(text), media: "/m", download: "/d" });
13 const res = (o: object = {}) => ({
14 mode: "managed", type: "aws_db_instance", name: "main", provider: 'provider["registry.terraform.io/hashicorp/aws"]',
15 instances: [{ attributes: { id: "db-1", engine: "postgres", password: "hunter2", secret_key: "AKIA-SECRET", tags: { k: "nested-secret" } } }], ...o,
16 });
17 const state = (resources: object[], extra: object = {}) =>
18 JSON.stringify({ version: 4, terraform_version: "1.6.0", serial: 7, outputs: { token: { value: "out-secret", sensitive: true } }, resources, ...extra });
19
20 describe("tfstate", () => {
21 test("the registry names .tfstate by its first byte and a renderer draws it", () => {
22 expect(fileKind("a/terraform.tfstate", enc("{}"))).toBe("tfstate");
23 expect(fileKind("a/terraform.tfstate", enc("not json"))).toBe("text");
24 expect(RENDERERS.tfstate).toBe(tfstate);
25 });
26
27 test("parse: version, serial, and a row per resource", () => {
28 const r = draw(state([res()]));
29 const h = String(r.content);
30 expect(r.fallback).toBeUndefined();
31 expect(h).toContain("<dt>Version</dt><dd>4</dd>");
32 expect(h).toContain("<dt>Serial</dt><dd>7</dd>");
33 expect(h).toContain("<dt>Terraform</dt><dd>1.6.0</dd>");
34 expect(h).toContain("<td>aws_db_instance</td><td>main</td>");
35 expect(h).toContain("db-1");
36 expect(h).toContain("postgres");
37 expect(r.summary).toContain("1 resource");
38 });
39
40 test("masking: a secret value never reaches the HTML, allowlisted ids do", () => {
41 const h = String(draw(state([res()])).content);
42 for (const secret of ["hunter2", "AKIA-SECRET", "nested-secret", "out-secret"]) expect(h).not.toContain(secret);
43 expect(h).toContain(`<dt>password</dt><dd>${MASK}</dd>`);
44 expect(h).toContain(MASK);
45 expect(h).toContain("<code>token</code>"); // an output's name, never its value
46 expect(JSON.stringify(aboutTfstate(state([res()])))).not.toContain("hunter2");
47 });
48
49 test("escape: every value drawn from the file", () => {
50 const evil = res({ type: "<script>t</script>", name: "<img onerror=x>", provider: "<b>p</b>", instances: [{ attributes: { id: "<script>i</script>" } }] });
51 const h = String(draw(state([evil], { terraform_version: "<i>v</i>", outputs: { "<u>o</u>": {} } })).content);
52 expect(h).not.toMatch(/<script|<img|<b>p|<i>v|<u>o/);
53 expect(h).toContain("&lt;script&gt;");
54 });
55
56 test("cap: resources past the cap are counted, not drawn", () => {
57 const many = Array.from({ length: RESOURCE_CAP + 5 }, (_, i) => res({ name: `r${i}` }));
58 const doc = parseTfstate(state(many));
59 expect("error" in doc ? 0 : doc.resources.length).toBe(RESOURCE_CAP);
60 expect(String(draw(state(many)).content)).toContain(`Showing ${RESOURCE_CAP} of ${RESOURCE_CAP + 5} resources, 5 left out`);
61 });
62
63 test("malformed: invalid JSON or no resources keeps the source with one line why", () => {
64 expect(draw("{nope").fallback).toContain("not valid JSON");
65 expect(draw('{"version":4}').fallback).toContain("no `resources` array");
66 expect(draw("[1]").fallback).toContain("Terraform state");
67 });
68
69 test("hostile shapes: non-objects and lying fields do not throw", () => {
70 const h = String(draw('{"resources":[1,null,{"instances":"x"},{"instances":[{"attributes":{"id":null,"a":[1]}}]}],"serial":"9"}').content);
71 expect(h).toContain("<dt>Serial</dt><dd>0</dd>");
72 });
73
74 test("MCP facts: the read_file about carries the masked table", () => {
75 const about = aboutTfstate(state([res()])) as { parses: boolean; resources: { type: string; attributes: Record<string, string> }[] };
76 expect(about.parses).toBe(true);
77 expect(about.resources[0]!.type).toBe("aws_db_instance");
78 expect(about.resources[0]!.attributes.password).toBe(MASK);
79 expect(about.resources[0]!.attributes.id).toBe("db-1");
80 expect(aboutTfstate("{").parses).toBe(false);
81 });
82
83 test("one masking line, said once", () => {
84 const h = String(draw(state([res()])).content);
85 expect(h.match(/masked/g)?.length).toBe(1);
86 });
87
88 test("a body over the cap keeps the source view and says why", () => {
89 const body = enc("{" + " ".repeat(RENDER_CAP.tfstate) + "}");
90 const blob: Blob = { kind: "text", body, size: body.length, partial: false };
91 expect(rendererFor("terraform.tfstate", blob)).toBeUndefined();
92 expect(plainReason("terraform.tfstate", blob)).toContain("too large");
93 });
94 });
test/tfstate-tui.test.ts added +50
@@ -0,0 +1,50 @@
1 import { expect, test } from "bun:test";
2 import { tfstateView } from "../src/tui/screens/workspace_tfstate.ts";
3
4 const state = JSON.stringify({
5 version: 4, serial: 1, terraform_version: "1.6.0",
6 resources: [{ mode: "managed", type: "aws_db_instance", name: "db", provider: "aws",
7 instances: [{ attributes: { id: "db-1", password: "hunter2-secret" } }] }],
8 });
9 const enc = (s: string) => new TextEncoder().encode(s);
10
11 test("terminal draws a state as a table with secrets masked", () => {
12 const v = tfstateView("infra/terraform.tfstate", enc(state));
13 expect(typeof v).toBe("object");
14 const cells = JSON.stringify(v);
15 expect(cells).toContain("aws_db_instance");
16 expect(cells).toContain("db-1");
17 expect(cells).not.toContain("hunter2-secret");
18 });
19
20 test("terminal leaves other files and bad states alone", () => {
21 expect(tfstateView("a.txt", enc(state))).toBeNull();
22 expect(typeof tfstateView("x.tfstate", enc("{ nope"))).toBe("string");
23 });
24
25 test("control and escape characters in a value never reach the terminal", () => {
26 const evil = JSON.stringify({
27 resources: [{ mode: "managed", type: "t\u001b[2J", name: "n\u0007", provider: "p",
28 instances: [{ attributes: { id: "x\u001b]0;pwn\u0007y\u009b31m", "k\u001b": "v" } }] }],
29 outputs: { "o\u001b[31m": { value: "s3cret" } },
30 });
31 const v = tfstateView("a.tfstate", enc(evil));
32 expect(typeof v).toBe("object");
33 const all = JSON.stringify((v as { rows: string[][] }).rows);
34 expect(/[\u0000-\u001f\u007f-\u009f]/.test(JSON.parse(all).flat().join(""))).toBe(false);
35 expect(all).toContain("x]0;pwny31m");
36 });
37
38 test("outputs are listed by name, never by value", () => {
39 const v = tfstateView("a.tfstate", enc(JSON.stringify({ resources: [], outputs: { db_url: { value: "s3cret" } } })));
40 expect(typeof v).toBe("object");
41 expect(JSON.stringify(v)).toContain("db_url");
42 expect(JSON.stringify(v)).not.toContain("s3cret");
43 });
44
45 test("a body over the cap keeps the source and says why", async () => {
46 const { RENDER_CAP } = await import("../src/web/render/kinds.ts");
47 const big = enc("{" + " ".repeat(RENDER_CAP.tfstate) + "}");
48 const v = tfstateView("big.tfstate", big);
49 expect(v).toBe(`This file is over ${RENDER_CAP.tfstate / 1_000_000} MB, too large to open here. Download it instead.`);
50 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs