@skillstech/thunderlang 0.5.11 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +441 -0
- package/dist/core.cjs +30431 -7604
- package/dist/index.cjs +28577 -5331
- package/dist/learn.cjs +22676 -3870
- package/package.json +12 -3
- package/src/bicep.mjs +167 -0
- package/src/cli.mjs +169 -3
- package/src/commands.mjs +464 -0
- package/src/core.d.ts +12 -4
- package/src/core.mjs +12 -4
- package/src/emit.mjs +1 -1
- package/src/executed.d.mts +53 -0
- package/src/executed.mjs +465 -0
- package/src/faithful.mjs +137 -0
- package/src/file-formats.mjs +35 -0
- package/src/hcl.mjs +94 -0
- package/src/index.d.ts +7 -1
- package/src/index.mjs +6 -1
- package/src/infra-bicep.mjs +312 -0
- package/src/infra-cloud.mjs +348 -0
- package/src/infra-compose.mjs +315 -0
- package/src/infra-containers.mjs +100 -0
- package/src/infra-docker.mjs +267 -0
- package/src/infra-expr.mjs +509 -0
- package/src/infra-gha.mjs +350 -0
- package/src/infra-k8s.mjs +657 -0
- package/src/infra-terraform.mjs +499 -0
- package/src/infra-words.mjs +811 -0
- package/src/libraries.mjs +202 -0
- package/src/lift.mjs +48 -6
- package/src/meaning.d.mts +89 -0
- package/src/meaning.mjs +2544 -0
- package/src/model.d.mts +59 -12
- package/src/model.mjs +462 -80
- package/src/powershell.mjs +1361 -0
- package/src/read-repo-fs.mjs +29 -7
- package/src/read-repo.d.mts +5 -1
- package/src/read-repo.mjs +33 -7
- package/src/read.d.mts +21 -1
- package/src/read.mjs +1015 -42
- package/src/review.d.mts +35 -0
- package/src/review.mjs +671 -0
- package/src/rlang.mjs +1084 -0
- package/src/round-trip.d.mts +12 -0
- package/src/round-trip.mjs +174 -0
- package/src/runners/thunder-generate.mjs +56 -0
- package/src/runners/thunder-trace.cjs +284 -0
- package/src/runners/thunder_trace.py +599 -0
- package/src/running.d.mts +104 -0
- package/src/running.mjs +787 -0
- package/src/same.d.mts +1 -0
- package/src/same.mjs +24 -3
- package/src/shell.mjs +1212 -0
- package/src/sql.mjs +3 -2
- package/src/steps.d.mts +6 -1
- package/src/steps.mjs +1448 -86
- package/src/system.d.mts +12 -0
- package/src/system.mjs +845 -0
- package/src/things-langs.mjs +275 -0
- package/src/thunderize.mjs +3 -3
- package/src/visual.d.mts +5 -5
- package/src/visual.mjs +24 -3
- package/src/write-steps.d.mts +64 -0
- package/src/write-steps.mjs +1608 -0
- package/src/write.mjs +2 -1
- package/src/yaml.mjs +403 -0
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
// Terraform in Thunder (spec section 12): what a configuration makes, where, and who can do what. Each `resource`
|
|
2
|
+
// is a Resource that knows its arguments in words (a value only when the file writes it; references and functions are
|
|
3
|
+
// "worked out when it is applied"); `data` sources look up something that already exists; a `module` is a group of
|
|
4
|
+
// its own; `variable`, `locals`, and `output` are Settings (a sensitive one is only named). References and
|
|
5
|
+
// `depends_on` are links with their lines, and the order things are created is one Steps card. Role assignments and
|
|
6
|
+
// IAM policies are Permissions (wide when they can change everything); open ports, public storage, secrets written
|
|
7
|
+
// in the file, and encryption turned off are Facts. Deterministic, browser-safe; reads the file, not the cloud.
|
|
8
|
+
import { parseHcl, attrOf, blocksOf } from './hcl.mjs';
|
|
9
|
+
import { refsIn, isLiteral, toValue } from './infra-expr.mjs';
|
|
10
|
+
import {
|
|
11
|
+
APPLIED, words, typeWords, resourceLabel, providerWords, roleCan, roleIn, WIDE_ROLES, linkKind, valueText, conditionWords,
|
|
12
|
+
keyFacts, isSecretKey, literalEntries, fromAnywhere, portsOpen, topoOrder, addLink, question, leaves,
|
|
13
|
+
} from './infra-cloud.mjs';
|
|
14
|
+
import { listWords, cap } from './infra-words.mjs';
|
|
15
|
+
|
|
16
|
+
/** "the storage account main"; a resource named `this` (a common module convention) is just "the storage account". */
|
|
17
|
+
export const named = (typeW, name) => (name === 'this' || name === 'default' ? `the ${typeW}` : `the ${typeW} ${name}`);
|
|
18
|
+
|
|
19
|
+
const RESERVED = new Set(['var', 'local', 'each', 'count', 'path', 'terraform', 'self', 'data', 'module']);
|
|
20
|
+
const META = new Set(['count', 'for_each', 'depends_on', 'provider', 'providers', 'lifecycle', 'source', 'version']);
|
|
21
|
+
const BACKENDS = { s3: 'an S3 bucket', azurerm: 'an Azure storage account', gcs: 'a Google Cloud Storage bucket', remote: 'HCP Terraform', cloud: 'HCP Terraform', local: 'a file on the computer that runs it', consul: 'Consul', http: 'a web service', kubernetes: 'a Kubernetes secret', pg: 'a PostgreSQL database' };
|
|
22
|
+
|
|
23
|
+
/** The address a reference points to ('azurerm_storage_account.main', 'data.x.y', 'module.net'), or null. */
|
|
24
|
+
export function tfTarget(ref) {
|
|
25
|
+
const p = ref.path;
|
|
26
|
+
if (p[0] === 'data') return p.length >= 3 && !p[1].startsWith('[') ? `data.${p[1]}.${p[2]}` : null;
|
|
27
|
+
if (p[0] === 'module') return p.length >= 2 ? `module.${p[1]}` : null;
|
|
28
|
+
if (RESERVED.has(p[0]) || p.length < 2 || p[1].startsWith('[') || p[1] === '*') return null;
|
|
29
|
+
return /^[a-z][a-z0-9]*_[a-z0-9_]+$/.test(p[0]) ? `${p[0]}.${p[1]}` : null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const attrPath = (parts) => parts.filter((x) => x !== '*' && !x.startsWith('[')).map((x) => words(x)).join(' ');
|
|
33
|
+
|
|
34
|
+
/** A reference in words: var.location -> "the setting location"; azurerm_resource_group.rg.location -> "the location of the resource group rg". */
|
|
35
|
+
export function tfRefWords(ref) {
|
|
36
|
+
if (ref.t !== 'ref') return null;
|
|
37
|
+
const p = ref.path;
|
|
38
|
+
const rest = (k) => attrPath(p.slice(k));
|
|
39
|
+
switch (p[0]) {
|
|
40
|
+
case 'var': return p[1] ? `the setting ${p[1]}${p.length > 2 ? `'s ${rest(2)}` : ''}` : null;
|
|
41
|
+
case 'local': return p[1] ? `the value ${p[1]}${p.length > 2 ? `'s ${rest(2)}` : ''}` : null;
|
|
42
|
+
case 'each': return p[1] === 'key' ? "each item's key" : p.length > 2 ? `each item's ${rest(2)}` : "each item's value";
|
|
43
|
+
case 'count': return 'its number in the count (from 0)';
|
|
44
|
+
case 'path': return p[1] === 'root' ? 'the root folder' : p[1] === 'cwd' ? 'the working folder' : "this module's folder";
|
|
45
|
+
case 'terraform': return p[1] === 'workspace' ? 'the workspace name' : 'Terraform';
|
|
46
|
+
case 'self': return `its own ${rest(1)}`;
|
|
47
|
+
case 'data': return p.length >= 3 ? `${p.length > 3 ? `the ${rest(3)} of ` : ''}the looked-up ${typeWords(p[1])} ${p[2]}` : null;
|
|
48
|
+
case 'module': return p.length >= 2 ? `${p.length > 2 ? `the ${rest(2)} from ` : ''}the module ${p[1]}` : null;
|
|
49
|
+
default: {
|
|
50
|
+
const t = tfTarget(ref);
|
|
51
|
+
if (!t) return p.length === 1 ? `the value ${p[0]}` : null;
|
|
52
|
+
const attr = rest(2);
|
|
53
|
+
return `${attr ? `the ${attr} of ` : ''}the ${typeWords(p[0])} ${p[1]}`;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Every attribute under a body, nested blocks included, with the block path it sits under. */
|
|
59
|
+
function walkAttrs(items, fn, path = []) {
|
|
60
|
+
for (const it of items ?? []) {
|
|
61
|
+
if (it.kind === 'attr') fn(it, path);
|
|
62
|
+
else if (it.type === 'dynamic') { const content = blocksOf(it.body, 'content')[0]; walkAttrs(it.body.filter((x) => x !== content), fn, [...path, it.labels[0]]); if (content) walkAttrs(content.body, fn, [...path, it.labels[0]]); }
|
|
63
|
+
else walkAttrs(it.body, fn, [...path, it.type]);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A nested block in a few words: "always on: yes; application stack: …; and 3 more". */
|
|
68
|
+
function blockSummary(b, refWords, depth = 0) {
|
|
69
|
+
const parts = [];
|
|
70
|
+
for (const it of b.body) {
|
|
71
|
+
if (it.kind === 'attr') parts.push(`${words(it.name)}: ${valueText(it.value, refWords).text}`);
|
|
72
|
+
else parts.push(depth < 1 ? `${words(it.type === 'dynamic' ? it.labels[0] : it.type)} (${blockSummary(it, refWords, depth + 1) || 'empty'})` : `${words(it.type)} (…)`);
|
|
73
|
+
}
|
|
74
|
+
if (!parts.length) return 'set, with nothing inside';
|
|
75
|
+
const shown = parts.slice(0, 4).join('; ');
|
|
76
|
+
return `${shown}${parts.length > 4 ? `; and ${parts.length - 4} more` : ''}`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Statements of an IAM policy: [{ effect, actions, notActions, resources, principals, line }]. */
|
|
80
|
+
function policyStatements(node, ctx) {
|
|
81
|
+
if (!node) return [];
|
|
82
|
+
if (node.t === 'ref' && node.path[0] === 'data' && node.path[1] === 'aws_iam_policy_document') return ctx.policyDocs.get(node.path[2]) ?? [];
|
|
83
|
+
let doc = null;
|
|
84
|
+
if (node.t === 'call' && node.name === 'jsonencode') doc = toValue(node.args[0], ctx.src);
|
|
85
|
+
else if (node.t === 'str') {
|
|
86
|
+
const text = node.template ? node.parts.map((p) => (typeof p === 'string' ? p : 'REF')).join('') : node.v;
|
|
87
|
+
try { doc = JSON.parse(text); } catch { doc = null; }
|
|
88
|
+
}
|
|
89
|
+
const sts = doc && typeof doc === 'object' ? doc.Statement ?? doc.statement : null;
|
|
90
|
+
const arr = (x) => (x == null ? [] : Array.isArray(x) ? x : [x]).map((v) => (v && typeof v === 'object' && 'ref' in v ? `(${APPLIED})` : String(v)));
|
|
91
|
+
return (Array.isArray(sts) ? sts : sts ? [sts] : []).filter((s) => s && typeof s === 'object').map((s) => ({
|
|
92
|
+
effect: String(s.Effect ?? 'Allow'), actions: arr(s.Action), notActions: arr(s.NotAction), resources: arr(s.Resource ?? s.NotResource),
|
|
93
|
+
principals: s.Principal == null ? [] : typeof s.Principal === 'string' ? [{ type: '*', ids: [s.Principal] }] : Object.entries(s.Principal).map(([type, ids]) => ({ type, ids: arr(ids) })),
|
|
94
|
+
line: node.line,
|
|
95
|
+
}));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** IAM actions in words: '*' -> "do anything"; 's3:*' -> "do anything in S3". */
|
|
99
|
+
function actionsWords(actions, notActions = []) {
|
|
100
|
+
if (notActions.length) return `do anything except ${listWords(notActions.slice(0, 4))}${notActions.length > 4 ? ` and ${notActions.length - 4} more` : ''}`;
|
|
101
|
+
if (!actions.length) return 'do nothing';
|
|
102
|
+
if (actions.includes('*')) return 'do anything';
|
|
103
|
+
const all = actions.filter((a) => /:\*$/.test(a)).map((a) => a.split(':')[0].toUpperCase());
|
|
104
|
+
const rest = actions.filter((a) => !/:\*$/.test(a));
|
|
105
|
+
const parts = [...(all.length ? [`do anything in ${listWords(all)}`] : []), ...(rest.length ? [rest.length > 4 ? `${rest.slice(0, 4).join(', ')}, and ${rest.length - 4} more` : listWords(rest)] : [])];
|
|
106
|
+
return parts.join(', and ');
|
|
107
|
+
}
|
|
108
|
+
const READ_ONLY = (a) => /:(Describe|Get|List|Head|BatchGet|Query|Scan|Lookup|Search|View|Read)[A-Za-z]*\*?$/.test(a);
|
|
109
|
+
function statementWide(st) {
|
|
110
|
+
if (st.notActions.length) return 'every action except a few';
|
|
111
|
+
if (st.actions.includes('*')) return 'every action on every resource it names';
|
|
112
|
+
const svc = st.actions.find((a) => /:\*$/.test(a));
|
|
113
|
+
if (svc) return `every ${svc.split(':')[0].toUpperCase()} action`;
|
|
114
|
+
if (st.resources.includes('*') && st.actions.some((a) => !READ_ONLY(a))) return 'changes to every resource of those kinds (Resource "*")';
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
const resourcesWords = (rs) => (!rs.length ? 'what it is attached to' : rs.includes('*') ? 'every resource' : rs.length === 1 ? rs[0] : `${listWords(rs.slice(0, 3))}${rs.length > 3 ? ` and ${rs.length - 3} more` : ''}`);
|
|
118
|
+
const principalWords = (ps) => listWords(ps.flatMap((p) => p.ids.map((id) => (id === '*' ? 'anyone' : p.type === 'Service' ? `the service ${id}` : p.type === 'Federated' ? `sign-ins from ${id}` : `the AWS account or role ${id}`))));
|
|
119
|
+
|
|
120
|
+
/** Read a Terraform file. Returns { items, things, settings, facts, links, permissions, unknowns, purpose }. */
|
|
121
|
+
export function readTerraform(src, file = 'main.tf') {
|
|
122
|
+
const parsed = parseHcl(src);
|
|
123
|
+
const { body, comments } = parsed;
|
|
124
|
+
const blocks = body.filter((b) => b.kind === 'block');
|
|
125
|
+
const things = [], settings = [], facts = [], links = [], permissions = [];
|
|
126
|
+
const unknowns = parsed.errors.map((e) => ({ file, line: e.line, why: `Not read yet: ${e.why}.` }));
|
|
127
|
+
const factIds = new Set();
|
|
128
|
+
const fact = (kind, says, line) => { const id = `${file}#${kind}#${line}`; if (!factIds.has(id)) { factIds.add(id); facts.push({ id, kind, says, file, line }); } };
|
|
129
|
+
const refWords = tfRefWords;
|
|
130
|
+
|
|
131
|
+
// Locals: what each one refers to, so a resource that uses a local is linked to what the local names.
|
|
132
|
+
const localRefs = new Map();
|
|
133
|
+
for (const b of blocksOf(body, 'locals')) for (const a of b.body) if (a.kind === 'attr') localRefs.set(a.name, refsIn(a.value));
|
|
134
|
+
const targetsOf = (node) => {
|
|
135
|
+
const out = [];
|
|
136
|
+
const visit = (refs, depth) => {
|
|
137
|
+
for (const r of refs) {
|
|
138
|
+
if (r.path[0] === 'local' && depth < 3 && localRefs.has(r.path[1])) { visit(localRefs.get(r.path[1]), depth + 1); continue; }
|
|
139
|
+
const t = tfTarget(r);
|
|
140
|
+
if (t) out.push({ to: t, ref: r });
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
visit(refsIn(node), 0);
|
|
144
|
+
return out;
|
|
145
|
+
};
|
|
146
|
+
// IAM policy documents written in this file, for policies that use them.
|
|
147
|
+
const ctx = { src: parsed.src, policyDocs: new Map() };
|
|
148
|
+
for (const b of blocks) if (b.type === 'data' && b.labels[0] === 'aws_iam_policy_document') {
|
|
149
|
+
ctx.policyDocs.set(b.labels[1], blocksOf(b.body, 'statement').map((s) => {
|
|
150
|
+
const list = (n) => { const a = attrOf(s.body, n)?.value; return !a ? [] : a.t === 'list' ? a.items.map((x) => (x.t === 'str' && !x.template ? x.v : `(${APPLIED})`)) : [`(${APPLIED})`]; };
|
|
151
|
+
return {
|
|
152
|
+
effect: attrOf(s.body, 'effect')?.value?.v ?? 'Allow', actions: list('actions'), notActions: list('not_actions'), resources: [...list('resources'), ...list('not_resources')],
|
|
153
|
+
principals: blocksOf(s.body, 'principals').map((p) => ({ type: attrOf(p.body, 'type')?.value?.v ?? '*', ids: (() => { const a = attrOf(p.body, 'identifiers')?.value; return a?.t === 'list' ? a.items.map((x) => (x.t === 'str' && !x.template ? x.v : `(${APPLIED})`)) : []; })() })),
|
|
154
|
+
line: s.line,
|
|
155
|
+
};
|
|
156
|
+
}));
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ── Resources, data sources, and modules ──
|
|
160
|
+
const declared = [];
|
|
161
|
+
for (const b of blocks) {
|
|
162
|
+
if (b.type === 'resource' && b.labels.length >= 2) declared.push({ b, kind: 'resource', type: b.labels[0], name: b.labels[1], address: `${b.labels[0]}.${b.labels[1]}` });
|
|
163
|
+
else if (b.type === 'data' && b.labels.length >= 2) declared.push({ b, kind: 'data', type: b.labels[0], name: b.labels[1], address: `data.${b.labels[0]}.${b.labels[1]}` });
|
|
164
|
+
else if (b.type === 'module' && b.labels.length >= 1) declared.push({ b, kind: 'module', type: 'module', name: b.labels[0], address: `module.${b.labels[0]}` });
|
|
165
|
+
}
|
|
166
|
+
const byAddress = new Map(declared.map((d) => [d.address, d]));
|
|
167
|
+
const link = (from, to, kind, line) => addLink(links, file, from, to, kind, line);
|
|
168
|
+
|
|
169
|
+
for (const d of declared) {
|
|
170
|
+
const { b, type, name, address } = d;
|
|
171
|
+
const where = d.kind === 'module' ? `The module ${name}` : cap(named(typeWords(type), name));
|
|
172
|
+
const knows = [];
|
|
173
|
+
const know = (k) => knows.push({ start: null, ...k });
|
|
174
|
+
if (d.kind === 'data') know({ name: 'looks-up', label: 'Looks up', kind: `an existing ${typeWords(type)}, made elsewhere (Terraform only reads it)`, line: b.line });
|
|
175
|
+
if (d.kind === 'module') {
|
|
176
|
+
const source = attrOf(b.body, 'source'), version = attrOf(b.body, 'version');
|
|
177
|
+
if (source) know({ name: 'source', label: 'Uses the module', kind: valueText(source.value, refWords).text, line: source.line });
|
|
178
|
+
if (version) know({ name: 'version', label: 'Version', kind: valueText(version.value, refWords).text, line: version.line });
|
|
179
|
+
}
|
|
180
|
+
for (const it of b.body) {
|
|
181
|
+
if (it.kind === 'attr') {
|
|
182
|
+
if (it.name === 'count') { know({ name: 'count', label: 'How many', kind: countWords(it.value, refWords), line: it.line, ...(isLiteral(it.value) ? {} : { computed: true }) }); continue; }
|
|
183
|
+
if (it.name === 'for_each') { know({ name: 'for_each', label: 'One for each', kind: forEachWords(it.value, refWords).replace(/^one for each (of )?/, ''), line: it.line, ...(isLiteral(it.value) ? {} : { computed: true }) }); continue; }
|
|
184
|
+
if (it.name === 'depends_on') {
|
|
185
|
+
const ts = it.value.t === 'list' ? it.value.items.flatMap((x) => targetsOf(x)) : targetsOf(it.value);
|
|
186
|
+
for (const t of ts) link(address, t.to, 'uses', it.line);
|
|
187
|
+
know({ name: 'depends_on', label: 'Waits for', kind: listWords(ts.map((t) => tfRefWords({ t: 'ref', path: t.to.split('.') }) ?? t.to)), line: it.line });
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
if (it.name === 'provider') { know({ name: 'provider', label: 'Uses the provider', kind: it.value.t === 'ref' ? it.value.path.join('.') : valueText(it.value, refWords).text, line: it.line }); continue; }
|
|
191
|
+
if (d.kind === 'module' && (it.name === 'source' || it.name === 'version' || it.name === 'providers')) continue;
|
|
192
|
+
const v = valueText(it.value, refWords);
|
|
193
|
+
const secret = isSecretKey(it.name) && (it.value.t === 'str' || v.computed);
|
|
194
|
+
const isLit = it.value.t === 'str' && !it.value.template;
|
|
195
|
+
know({ name: it.name, label: cap(words(it.name)), kind: secret ? (isLit ? 'a secret written in the file (its value is not shown)' : `a secret${v.from?.length ? ` from ${listWords(v.from)}` : ''} (its value is not shown)`) : v.text, line: it.line, ...(v.computed ? { computed: true } : {}), ...(secret ? { secret: true } : {}) });
|
|
196
|
+
} else if (it.type === 'lifecycle') {
|
|
197
|
+
for (const a of it.body) {
|
|
198
|
+
if (a.kind !== 'attr') { if (a.type === 'precondition' || a.type === 'postcondition') know({ name: a.type, label: a.type === 'precondition' ? 'Checks first' : 'Checks after', kind: `${conditionWords(attrOf(a.body, 'condition')?.value, refWords)}${attrOf(a.body, 'error_message') ? `, or stops: "${valueText(attrOf(a.body, 'error_message').value, refWords).text}"` : ''}`, line: a.line }); continue; }
|
|
199
|
+
if (a.name === 'prevent_destroy' && a.value.t === 'bool' && a.value.v) know({ name: 'prevent_destroy', label: 'Protected', kind: 'Terraform refuses to destroy it (prevent_destroy)', line: a.line });
|
|
200
|
+
else if (a.name === 'create_before_destroy' && a.value.t === 'bool' && a.value.v) know({ name: 'create_before_destroy', label: 'When replaced', kind: 'makes the new one before removing the old one', line: a.line });
|
|
201
|
+
else if (a.name === 'ignore_changes') know({ name: 'ignore_changes', label: 'Ignores changes to', kind: a.value.t === 'list' ? listWords(a.value.items.map((x) => (x.t === 'ref' ? words(x.path.join('.')) : valueText(x, refWords).text))) || 'nothing' : a.value.t === 'ref' && a.value.path[0] === 'all' ? 'everything (it is only made, never updated)' : valueText(a.value, refWords).text, line: a.line });
|
|
202
|
+
else if (a.name === 'replace_triggered_by') know({ name: 'replace_triggered_by', label: 'Replaced when these change', kind: listWords((a.value.items ?? []).map((x) => tfRefWords(x) ?? 'a value')), line: a.line });
|
|
203
|
+
}
|
|
204
|
+
} else if (it.type === 'dynamic') {
|
|
205
|
+
const fe = attrOf(it.body, 'for_each');
|
|
206
|
+
know({ name: it.labels[0], label: cap(words(it.labels[0])), kind: `one block for each ${fe ? forEachWords(fe.value, refWords).replace(/^one for each /, '') : 'item'}`, line: it.line, computed: true });
|
|
207
|
+
} else if (it.type !== 'connection' && it.type !== 'provisioner') {
|
|
208
|
+
const nm = attrOf(it.body, 'name')?.value;
|
|
209
|
+
know({ name: it.type, label: cap(words([it.type, ...it.labels].join(' '))) + (nm?.t === 'str' && !nm.template ? ` ${nm.v}` : ''), kind: blockSummary(it, refWords), line: it.line });
|
|
210
|
+
} else know({ name: it.type, label: it.type === 'provisioner' ? `Runs (${it.labels[0] ?? 'provisioner'})` : 'Connects with', kind: blockSummary(it, refWords), line: it.line });
|
|
211
|
+
}
|
|
212
|
+
// Links: every reference to another resource, under the key it sits in.
|
|
213
|
+
walkAttrs(b.body, (a) => {
|
|
214
|
+
if (a.name === 'depends_on') return;
|
|
215
|
+
for (const lf of leaves(a.value, a.name, a.line)) for (const t of targetsOf(lf.value)) link(address, t.to, linkKind(lf.key, { toLookup: t.to.startsWith('data.'), fromType: type, secretValue: /secret$/.test(t.to.split('.').at(-2) ?? '') && t.ref.path.at(-1) === 'value' }), lf.line);
|
|
216
|
+
});
|
|
217
|
+
// Facts from what the resource says about itself.
|
|
218
|
+
walkAttrs(b.body, (a) => {
|
|
219
|
+
keyFacts(a.name, a.value, (kind, says) => fact(kind, says, a.line), where);
|
|
220
|
+
if (a.value.t === 'obj') for (const e of literalEntries(a.value)) keyFacts(e.key, e.value, (kind, says) => fact(kind, says, e.line), where);
|
|
221
|
+
});
|
|
222
|
+
ingressFacts(d, fact);
|
|
223
|
+
const perms = permissionsOf(d, ctx, file, refWords);
|
|
224
|
+
for (const p of perms) { const k = p.role && knows.find((kn) => kn.name === 'role_definition_id'); if (k) { k.kind = `${p.role} (a built-in role)`; delete k.computed; } }
|
|
225
|
+
permissions.push(...perms);
|
|
226
|
+
things.push({
|
|
227
|
+
kind: 'resource', name: address, label: d.kind === 'module' ? `Module ${name}` : resourceLabel(type, name), resourceType: type, address, file,
|
|
228
|
+
lines: [b.line, b.endLine], knows, choices: [], ...(b.doc ? { doc: b.doc } : {}), ...(d.kind === 'data' ? { existing: true } : {}),
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
for (const p of permissions) if (p.wide) fact('wide-permission', `${cap(p.who)} can ${p.can} on ${p.on}: ${p.why}.`, p.line);
|
|
232
|
+
|
|
233
|
+
// ── Settings: variables, locals, outputs ──
|
|
234
|
+
for (const b of blocks) {
|
|
235
|
+
if (b.type === 'variable' && b.labels[0]) {
|
|
236
|
+
const n = b.labels[0];
|
|
237
|
+
const sens = attrOf(b.body, 'sensitive')?.value;
|
|
238
|
+
const secret = (sens?.t === 'bool' && sens.v) || isSecretKey(n);
|
|
239
|
+
const def = attrOf(b.body, 'default'), desc = attrOf(b.body, 'description'), ty = attrOf(b.body, 'type');
|
|
240
|
+
if (secret && def && def.value.t === 'str' && !def.value.template && def.value.v) fact('secret-in-plain-config', `The setting ${n} is a secret, but its default value is written in the file.`, def.line);
|
|
241
|
+
settings.push({ name: n, source: 'parameter', secret: !!secret, file, line: b.line,
|
|
242
|
+
...(def && !secret ? { default: valueText(def.value, refWords).text.replace(` (${APPLIED})`, '') } : {}), ...(ty ? { type: typeExprWords(ty.value, parsed.src) } : {}),
|
|
243
|
+
...(desc?.value.t === 'str' && desc.value.v ? { doc: desc.value.v.trim() } : {}) });
|
|
244
|
+
} else if (b.type === 'locals') {
|
|
245
|
+
for (const a of b.body) if (a.kind === 'attr') {
|
|
246
|
+
const lit = isLiteral(a.value);
|
|
247
|
+
const secret = isSecretKey(a.name) && a.value.t === 'str';
|
|
248
|
+
if (secret && lit && a.value.v) fact('secret-in-plain-config', `The value ${a.name} looks like a secret and is written in the file.`, a.line);
|
|
249
|
+
settings.push({ name: a.name, source: lit ? 'literal' : 'computed', secret, file, line: a.line, ...(lit ? {} : { computed: true }), ...(lit && !secret ? { default: valueText(a.value, refWords).text } : {}) });
|
|
250
|
+
}
|
|
251
|
+
} else if (b.type === 'output' && b.labels[0]) {
|
|
252
|
+
const sens = attrOf(b.body, 'sensitive')?.value;
|
|
253
|
+
const desc = attrOf(b.body, 'description');
|
|
254
|
+
const val = attrOf(b.body, 'value');
|
|
255
|
+
const from = val ? valueText(val.value, refWords) : null;
|
|
256
|
+
settings.push({ name: b.labels[0], source: 'computed', secret: !!(sens?.t === 'bool' && sens.v), computed: true, output: true, file, line: b.line,
|
|
257
|
+
...(from?.from?.length ? { from: from.from.slice(0, 3) } : {}), ...(desc?.value.t === 'str' && desc.value.v ? { doc: desc.value.v.trim() } : {}) });
|
|
258
|
+
} else if (b.type === 'provider') {
|
|
259
|
+
walkAttrs(b.body, (a) => { keyFacts(a.name, a.value, (kind, says) => fact(kind, says, a.line), `The ${providerWords(b.labels[0])} provider`); });
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ── The order things are created: one Steps card ──
|
|
264
|
+
const steps = [];
|
|
265
|
+
for (const b of blocksOf(body, 'terraform')) {
|
|
266
|
+
for (const be of blocksOf(b.body, 'backend')) steps.push({ kind: 'call', says: `Keeps what it made (its state) in ${BACKENDS[be.labels[0]] ?? `the ${be.labels[0]} backend`}`, code: `backend "${be.labels[0]}"`, line: be.line });
|
|
267
|
+
const cl = blocksOf(b.body, 'cloud')[0];
|
|
268
|
+
if (cl) steps.push({ kind: 'call', says: 'Keeps what it made (its state) in HCP Terraform', code: 'cloud { … }', line: cl.line });
|
|
269
|
+
}
|
|
270
|
+
for (const b of blocksOf(body, 'provider')) {
|
|
271
|
+
const p = b.labels[0] ?? '';
|
|
272
|
+
const bits = [];
|
|
273
|
+
for (const k of ['region', 'location', 'project', 'subscription_id', 'zone']) {
|
|
274
|
+
const a = attrOf(b.body, k);
|
|
275
|
+
if (a) bits.push(`${k === 'subscription_id' ? 'the subscription' : `the ${words(k)}`} ${valueText(a.value, refWords).text}`);
|
|
276
|
+
}
|
|
277
|
+
const alias = attrOf(b.body, 'alias');
|
|
278
|
+
steps.push({ kind: 'call', says: `Works in ${providerWords(p)}${bits.length ? `, in ${listWords(bits)}` : ''}${alias ? ` (as ${p}.${valueText(alias.value, refWords).text})` : ''}`, code: `provider "${p}"`, line: b.line });
|
|
279
|
+
}
|
|
280
|
+
const edges = links.filter((l) => byAddress.has(l.to)).map((l) => [l.from, l.to]);
|
|
281
|
+
const order = topoOrder(declared.map((d) => d.address), edges);
|
|
282
|
+
for (const addr of order) {
|
|
283
|
+
const d = byAddress.get(addr);
|
|
284
|
+
const { b, type, name } = d;
|
|
285
|
+
const inLink = links.find((l) => l.from === addr && l.kind === 'runs-in' && byAddress.has(l.to));
|
|
286
|
+
const inWords = inLink ? ` in the ${typeWords(byAddress.get(inLink.to).type)} ${byAddress.get(inLink.to).name}` : '';
|
|
287
|
+
const head = d.kind === 'resource' ? `resource "${type}" "${name}"` : d.kind === 'data' ? `data "${type}" "${name}"` : `module "${name}"`;
|
|
288
|
+
const src = attrOf(b.body, 'source');
|
|
289
|
+
const what = d.kind === 'module' ? `the module ${name}${src ? ` (${valueText(src.value, refWords).text})` : ''}` : named(typeWords(type), name);
|
|
290
|
+
const verb = d.kind === 'data' ? 'Looks up' : d.kind === 'module' ? 'Uses' : 'Creates';
|
|
291
|
+
let step = { kind: 'call', says: `${verb} ${what}${inWords}`, code: head, line: b.line };
|
|
292
|
+
const count = attrOf(b.body, 'count'), fe = attrOf(b.body, 'for_each');
|
|
293
|
+
if (count) {
|
|
294
|
+
const c = count.value;
|
|
295
|
+
const cond = c.t === 'cond' ? c : null;
|
|
296
|
+
if (cond && isZero(cond.no)) step = { kind: 'branch', says: question(conditionWords(cond.test, refWords)), code: `count = ${parsed.src.slice(c.s, c.e)}`, line: count.line, children: [step] };
|
|
297
|
+
else if (cond && isZero(cond.yes)) step = { kind: 'branch', says: question(conditionWords({ t: 'unary', op: '!', x: cond.test }, refWords)), code: `count = ${parsed.src.slice(c.s, c.e)}`, line: count.line, children: [step] };
|
|
298
|
+
else if (c.t === 'num') { if (c.v === 0) step.says += ' (none: count is 0)'; else if (c.v !== 1) step.says = `${verb} ${c.v} of ${what}${inWords}`; }
|
|
299
|
+
else step = { kind: 'loop', says: `As many times as ${valueText(c, refWords).text.replace(` (${APPLIED})`, '')}`, code: `count = ${parsed.src.slice(c.s, c.e)}`, line: count.line, children: [step] };
|
|
300
|
+
} else if (fe) step = { kind: 'loop', says: `For each ${forEachWords(fe.value, refWords).replace(/^one for each /, '')}`, code: `for_each = ${parsed.src.slice(fe.value.s, fe.value.e)}`, line: fe.line, children: [step] };
|
|
301
|
+
steps.push(step);
|
|
302
|
+
}
|
|
303
|
+
const base = file.slice(file.lastIndexOf('/') + 1);
|
|
304
|
+
const items = [];
|
|
305
|
+
if (declared.length) {
|
|
306
|
+
const first = Math.min(...steps.map((s) => s.line)), last = Math.max(...declared.map((d) => d.b.endLine));
|
|
307
|
+
items.push({
|
|
308
|
+
id: `apply:${first}`, name: 'apply', label: `Applying ${base}`, title: `What applying ${base} makes, in order`, line: first, endLine: last,
|
|
309
|
+
inputs: [], returns: null, provenance: 'inferred-from-code', kind: 'function', status: 'signature-only', steps, stepsMore: 0, stepsReadable: 1,
|
|
310
|
+
says: `Applying ${base} makes ${declared.filter((d) => d.kind === 'resource').length} resource${declared.filter((d) => d.kind === 'resource').length === 1 ? '' : 's'}${declared.some((d) => d.kind === 'module') ? ` and uses ${declared.filter((d) => d.kind === 'module').length} module${declared.filter((d) => d.kind === 'module').length === 1 ? '' : 's'}` : ''}, in the order they rely on each other.`,
|
|
311
|
+
headline: `Applying ${base}: ${steps.length} step${steps.length === 1 ? '' : 's'}.`, guards: [], unread: [],
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
const top = comments.find((c) => c.line === 1);
|
|
315
|
+
return { items, things, settings, facts, links, permissions, unknowns, purpose: top && top.text && !/^(disable|tflint)/.test(top.text) ? top.text : null };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const isZero = (n) => n?.t === 'num' && n.v === 0;
|
|
319
|
+
function countWords(n, refWords) {
|
|
320
|
+
if (n.t === 'num') return n.v === 0 ? 'none (count is 0)' : String(n.v);
|
|
321
|
+
if (n.t === 'cond' && isZero(n.no)) return `${n.yes.t === 'num' ? n.yes.v === 1 ? 'one' : n.yes.v : valueText(n.yes, refWords).text}, only when ${conditionWords(n.test, refWords)}`;
|
|
322
|
+
if (n.t === 'cond' && isZero(n.yes)) return `${n.no.t === 'num' ? n.no.v === 1 ? 'one' : n.no.v : valueText(n.no, refWords).text}, only when ${conditionWords({ t: 'unary', op: '!', x: n.test }, refWords)}`;
|
|
323
|
+
return valueText(n, refWords).text;
|
|
324
|
+
}
|
|
325
|
+
function forEachWords(n, refWords) {
|
|
326
|
+
if (isLiteral(n)) { const v = valueText(n, refWords).text; return `one for each of ${v}`; }
|
|
327
|
+
const inner = n.t === 'call' && /^(toset|tomap|tolist)$/.test(n.name) && n.args.length === 1 ? n.args[0] : n;
|
|
328
|
+
if (inner.t === 'cond') return `one for each item in ${valueText(inner.yes, refWords).from?.[0] ?? 'a list'}, only when ${conditionWords(inner.test, refWords)}`;
|
|
329
|
+
const v = valueText(inner, refWords);
|
|
330
|
+
return `one for each item in ${v.from?.length === 1 ? v.from[0] : `a list ${APPLIED}`}`;
|
|
331
|
+
}
|
|
332
|
+
function typeExprWords(n, src) {
|
|
333
|
+
const raw = src.slice(n.s, n.e).replace(/\s+/g, ' ');
|
|
334
|
+
if (n.t === 'ref') return { string: 'words', number: 'a number', bool: 'yes or no', any: 'anything' }[n.path[0]] ?? raw;
|
|
335
|
+
if (n.t === 'call' && n.args.length === 1) { const inner = typeExprWords(n.args[0], src); return { list: `a list of ${inner}`, set: `a set of ${inner}`, map: `a map of ${inner}` }[n.name] ?? raw; }
|
|
336
|
+
return raw.length > 60 ? `${raw.slice(0, 59)}…` : raw;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// ── Permissions ─────────────────────────────────────────────────────────────────────────────────────────────
|
|
340
|
+
|
|
341
|
+
function scopeWords(n, refWords) {
|
|
342
|
+
if (!n) return { on: 'what it is attached to', wide: false };
|
|
343
|
+
if (n.t === 'ref') {
|
|
344
|
+
const p = n.path;
|
|
345
|
+
if ((p[0] === 'data' && p[1] === 'azurerm_subscription') || (p[0] === 'data' && p[1] === 'azurerm_subscriptions')) return { on: 'the whole subscription', wide: true };
|
|
346
|
+
if (/management_group/.test(p[0] === 'data' ? p[1] : p[0])) return { on: `the management group ${p[0] === 'data' ? p[2] : p[1]} (every subscription in it)`, wide: true };
|
|
347
|
+
const t = tfTarget(n);
|
|
348
|
+
if (t) { const parts = t.split('.'); return { on: parts[0] === 'data' ? `the ${typeWords(parts[1])} ${parts[2]}` : parts[0] === 'module' ? `what the module ${parts[1]} makes` : `the ${typeWords(parts[0])} ${parts[1]}` }; }
|
|
349
|
+
return { on: `the scope ${refWords(n) ?? APPLIED}`, wide: false };
|
|
350
|
+
}
|
|
351
|
+
const text = n.t === 'str' ? (n.template ? n.parts.map((x) => (typeof x === 'string' ? x : '{…}')).join('') : n.v) : null;
|
|
352
|
+
if (text != null) {
|
|
353
|
+
if (/^\/subscriptions\/[^/]+\/?$/i.test(text)) return { on: 'the whole subscription', wide: true };
|
|
354
|
+
if (/managementGroups\//i.test(text)) return { on: 'a management group (every subscription in it)', wide: true };
|
|
355
|
+
const rg = /\/resourceGroups\/([^/]+)\/?$/i.exec(text);
|
|
356
|
+
if (rg) return { on: `the resource group ${rg[1]}` };
|
|
357
|
+
if (/^projects\/|^organizations\/|^folders\//.test(text)) return { on: text };
|
|
358
|
+
return { on: text.includes('/') ? `the resource ${text.split('/').filter(Boolean).pop()}` : text };
|
|
359
|
+
}
|
|
360
|
+
return { on: valueText(n, refWords).text };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function azurePrincipal(n, refWords) {
|
|
364
|
+
if (!n) return 'someone';
|
|
365
|
+
if (n.t === 'ref') {
|
|
366
|
+
const p = n.path;
|
|
367
|
+
if (p[0] === 'data' && p[1] === 'azurerm_client_config') return 'whoever runs Terraform';
|
|
368
|
+
if (p[0] === 'var') return `the identity given in the setting ${p[1]}`;
|
|
369
|
+
const t = tfTarget(n);
|
|
370
|
+
if (t && !t.startsWith('module.') && !t.startsWith('data.')) {
|
|
371
|
+
if (p.includes('identity')) return `the ${typeWords(p[0])} ${p[1]} (its own identity)`;
|
|
372
|
+
if (p[0] === 'azurerm_user_assigned_identity') return `the managed identity ${p[1]}`;
|
|
373
|
+
return `the ${typeWords(p[0])} ${p[1]}`;
|
|
374
|
+
}
|
|
375
|
+
return refWords(n) ?? 'an identity worked out when it is applied';
|
|
376
|
+
}
|
|
377
|
+
if (n.t === 'str' && !n.template) return `the identity ${n.v}`;
|
|
378
|
+
return `an identity ${APPLIED}`;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function roleOf(body) {
|
|
382
|
+
const name = attrOf(body, 'role_definition_name')?.value;
|
|
383
|
+
if (name?.t === 'str' && !name.template) return { role: name.v };
|
|
384
|
+
const id = attrOf(body, 'role_definition_id')?.value;
|
|
385
|
+
if (id) { const r = roleIn(id.t === 'str' ? (id.v ?? id.parts.filter((x) => typeof x === 'string').join('')) : ''); if (r) return { role: r }; }
|
|
386
|
+
return { role: null, node: name ?? id };
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function permissionsOf(d, ctx, file, refWords) {
|
|
390
|
+
const { b, type, name } = d;
|
|
391
|
+
if (d.kind !== 'resource') return [];
|
|
392
|
+
const out = [];
|
|
393
|
+
const add = (who, can, on, line, wide = false, why, role) => out.push({ id: `${file}#permission#${line}#${out.length}`, who, can, on, wide: !!wide, ...(wide && why ? { why } : {}), ...(role ? { role } : {}), file, line, says: `${cap(who)} can ${can} on ${on}` });
|
|
394
|
+
const val = (k) => attrOf(b.body, k)?.value;
|
|
395
|
+
if (type === 'azurerm_role_assignment') {
|
|
396
|
+
const { role, node } = roleOf(b.body);
|
|
397
|
+
const scope = scopeWords(val('scope'), refWords);
|
|
398
|
+
const wide = role && WIDE_ROLES.has(role) && scope.wide;
|
|
399
|
+
add(azurePrincipal(val('principal_id'), refWords), role ? roleCan(role) : `act in the role ${node ? valueText(node, refWords).text : 'it is given'}`, scope.on, b.line, wide, wide ? `${role} of ${scope.on}` : undefined, role);
|
|
400
|
+
} else if (type === 'azurerm_key_vault_access_policy' || type === 'azurerm_key_vault') {
|
|
401
|
+
const pols = type === 'azurerm_key_vault' ? blocksOf(b.body, 'access_policy') : [b];
|
|
402
|
+
for (const p of pols) {
|
|
403
|
+
const perms = ['secret', 'key', 'certificate', 'storage'].map((k) => { const a = attrOf(p.body, `${k}_permissions`)?.value; return a?.t === 'list' && a.items.length ? `${listWords(a.items.map((x) => (x.v ?? '…').toLowerCase()))} ${k}s` : null; }).filter(Boolean);
|
|
404
|
+
if (!perms.length) continue;
|
|
405
|
+
const kv = type === 'azurerm_key_vault' ? `the key vault ${name}` : scopeWords(attrOf(p.body, 'key_vault_id')?.value, refWords).on;
|
|
406
|
+
const all = perms.some((x) => /\bpurge\b|\ball\b/.test(x));
|
|
407
|
+
add(azurePrincipal(attrOf(p.body, 'object_id')?.value, refWords), listWords(perms), kv, p.line, all, all ? 'it can purge or do everything to them' : undefined);
|
|
408
|
+
}
|
|
409
|
+
} else if (/^aws_iam_(role_policy|user_policy|group_policy|policy)$/.test(type)) {
|
|
410
|
+
const who = type === 'aws_iam_policy' ? `whoever is given ${named('policy', name)}` : type === 'aws_iam_role_policy' ? iamWho('IAM role', val('role'), refWords) : type === 'aws_iam_user_policy' ? iamWho('IAM user', val('user'), refWords) : iamWho('IAM group', val('group'), refWords);
|
|
411
|
+
for (const st of policyStatements(val('policy'), ctx)) if (/^allow$/i.test(st.effect)) { const w = statementWide(st); add(who, actionsWords(st.actions, st.notActions), resourcesWords(st.resources), attrOf(b.body, 'policy').line, w, w); }
|
|
412
|
+
} else if (type === 'aws_iam_role') {
|
|
413
|
+
for (const st of policyStatements(val('assume_role_policy'), ctx)) if (/^allow$/i.test(st.effect) && st.principals.length) {
|
|
414
|
+
const anyone = st.principals.some((p) => p.ids.includes('*'));
|
|
415
|
+
add(principalWords(st.principals), 'act as this role', `the IAM role ${name}`, attrOf(b.body, 'assume_role_policy').line, anyone, anyone ? 'anyone can take on this role' : undefined);
|
|
416
|
+
}
|
|
417
|
+
for (const ip of blocksOf(b.body, 'inline_policy')) for (const st of policyStatements(attrOf(ip.body, 'policy')?.value, ctx)) if (/^allow$/i.test(st.effect)) { const w = statementWide(st); add(`the IAM role ${name}`, actionsWords(st.actions, st.notActions), resourcesWords(st.resources), ip.line, w, w); }
|
|
418
|
+
} else if (/^aws_iam_(role|user|group)_policy_attachment$/.test(type) || type === 'aws_iam_policy_attachment') {
|
|
419
|
+
const arn = val('policy_arn');
|
|
420
|
+
const kind = type.includes('_user_') ? 'IAM user' : type.includes('_group_') ? 'IAM group' : 'IAM role';
|
|
421
|
+
const who = type === 'aws_iam_policy_attachment' ? `the roles, users, and groups it lists` : iamWho(kind, val(kind === 'IAM user' ? 'user' : kind === 'IAM group' ? 'group' : 'role'), refWords);
|
|
422
|
+
const pname = arn?.t === 'str' && !arn.template ? arn.v.split('/').pop() : null;
|
|
423
|
+
const can = pname ? `do what the AWS policy ${pname} allows` : arn?.t === 'ref' && arn.path[0] === 'aws_iam_policy' ? `do what ${named('policy', arn.path[1])} allows` : `do what the policy in ${(arn && (refWords(arn) ?? valueText(arn, refWords).from?.[0])) ?? `a value ${APPLIED}`} allows`;
|
|
424
|
+
const wide = pname && /^(AdministratorAccess|PowerUserAccess|IAMFullAccess)$/.test(pname);
|
|
425
|
+
add(who, can, 'what that policy names', b.line, wide, wide ? `${pname} can do almost anything in the account` : undefined);
|
|
426
|
+
} else if (/^google_.*_iam_(member|binding)$/.test(type)) {
|
|
427
|
+
const role = val('role');
|
|
428
|
+
const roleName = role?.t === 'str' && !role.template ? role.v : null;
|
|
429
|
+
const members = type.endsWith('_binding') ? (val('members')?.items ?? []) : [val('member')].filter(Boolean);
|
|
430
|
+
const level = type.replace(/^google_/, '').replace(/_iam_(member|binding)$/, '');
|
|
431
|
+
const target = ['project', 'folder', 'organization'].includes(level) ? `the ${level} ${valueText(val(level === 'organization' ? 'org_id' : level === 'folder' ? 'folder' : 'project') ?? { t: 'str', v: '(its default)', template: false, parts: [] }, refWords).text}` : `the ${words(level)} ${valueText(val(level.split('_').pop()) ?? val('name') ?? { t: 'null' }, refWords).text}`;
|
|
432
|
+
const wide = roleName && WIDE_ROLES.has(roleName) && ['project', 'folder', 'organization'].includes(level);
|
|
433
|
+
for (const m of members) {
|
|
434
|
+
const who = gcpMember(m, refWords);
|
|
435
|
+
add(who, roleName ? `act as ${roleName}` : `act in the role ${valueText(role, refWords).text}`, target, m.line ?? b.line, wide, wide ? `${roleName} on ${target}` : undefined, roleName);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
return out;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function iamWho(kind, n, refWords) {
|
|
442
|
+
if (!n) return `the ${kind}`;
|
|
443
|
+
if (n.t === 'ref' && /^aws_iam_(role|user|group)$/.test(n.path[0])) return named(kind, n.path[1]);
|
|
444
|
+
if (n.t === 'str' && !n.template) return `the ${kind} ${n.v}`;
|
|
445
|
+
return `the ${kind} ${refWords(n) ?? APPLIED}`;
|
|
446
|
+
}
|
|
447
|
+
function gcpMember(n, refWords) {
|
|
448
|
+
if (n.t !== 'str' || n.template) return `the member ${valueText(n, refWords).text}`;
|
|
449
|
+
const v = n.v;
|
|
450
|
+
if (v === 'allUsers') return 'anyone on the internet';
|
|
451
|
+
if (v === 'allAuthenticatedUsers') return 'anyone with a Google account';
|
|
452
|
+
const [kind, id] = v.split(':');
|
|
453
|
+
return { serviceAccount: `the service account ${id}`, user: `the user ${id}`, group: `the group ${id}`, domain: `everyone in ${id}` }[kind] ?? v;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// ── Open ports ──────────────────────────────────────────────────────────────────────────────────────────────
|
|
457
|
+
|
|
458
|
+
function strList(n) {
|
|
459
|
+
if (!n) return [];
|
|
460
|
+
if (n.t === 'list') return n.items.filter((x) => x.t === 'str' && !x.template).map((x) => x.v);
|
|
461
|
+
if (n.t === 'str' && !n.template) return [n.v];
|
|
462
|
+
return [];
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function ingressFacts(d, fact) {
|
|
466
|
+
const { b, type, name } = d;
|
|
467
|
+
const where = cap(named(typeWords(type), name));
|
|
468
|
+
const v = (body, k) => attrOf(body, k)?.value;
|
|
469
|
+
const num = (n) => (n?.t === 'num' ? n.v : n?.t === 'str' && !n.template ? n.v : null);
|
|
470
|
+
const report = (ports, line) => { if (ports.beyondWeb) fact('public-ingress', `${where} lets anyone on the internet reach ${ports.says}.`, line); };
|
|
471
|
+
if (type === 'aws_security_group') {
|
|
472
|
+
for (const r of blocksOf(b.body, 'ingress')) {
|
|
473
|
+
if (fromAnywhere([...strList(v(r.body, 'cidr_blocks')), ...strList(v(r.body, 'ipv6_cidr_blocks'))])) report(portsOpen(num(v(r.body, 'from_port')), num(v(r.body, 'to_port')), num(v(r.body, 'protocol'))), r.line);
|
|
474
|
+
}
|
|
475
|
+
} else if (type === 'aws_security_group_rule') {
|
|
476
|
+
if (num(v(b.body, 'type')) === 'ingress' && fromAnywhere([...strList(v(b.body, 'cidr_blocks')), ...strList(v(b.body, 'ipv6_cidr_blocks'))])) report(portsOpen(num(v(b.body, 'from_port')), num(v(b.body, 'to_port')), num(v(b.body, 'protocol'))), b.line);
|
|
477
|
+
} else if (type === 'aws_vpc_security_group_ingress_rule') {
|
|
478
|
+
if (fromAnywhere([...strList(v(b.body, 'cidr_ipv4')), ...strList(v(b.body, 'cidr_ipv6'))])) report(portsOpen(num(v(b.body, 'from_port')), num(v(b.body, 'to_port')), num(v(b.body, 'ip_protocol'))), b.line);
|
|
479
|
+
} else if (type === 'azurerm_network_security_rule' || type === 'azurerm_network_security_group') {
|
|
480
|
+
const rules = type === 'azurerm_network_security_rule' ? [b] : blocksOf(b.body, 'security_rule');
|
|
481
|
+
for (const r of rules) {
|
|
482
|
+
if (String(num(v(r.body, 'direction')) ?? '').toLowerCase() !== 'inbound' || String(num(v(r.body, 'access')) ?? '').toLowerCase() !== 'allow') continue;
|
|
483
|
+
if (!fromAnywhere([...strList(v(r.body, 'source_address_prefix')), ...strList(v(r.body, 'source_address_prefixes'))])) continue;
|
|
484
|
+
const ports = [...strList(v(r.body, 'destination_port_range')), ...strList(v(r.body, 'destination_port_ranges'))];
|
|
485
|
+
for (const p of ports.length ? ports : ['*']) report(p === '*' ? { says: 'every port', beyondWeb: true } : portsOpen(p, null, num(v(r.body, 'protocol'))), r.line);
|
|
486
|
+
}
|
|
487
|
+
} else if (type === 'google_compute_firewall') {
|
|
488
|
+
const dir = String(num(v(b.body, 'direction')) ?? 'INGRESS').toUpperCase();
|
|
489
|
+
if (dir === 'INGRESS' && fromAnywhere(strList(v(b.body, 'source_ranges')))) {
|
|
490
|
+
for (const a of blocksOf(b.body, 'allow')) {
|
|
491
|
+
const ports = strList(v(a.body, 'ports'));
|
|
492
|
+
for (const p of ports.length ? ports : ['*']) report(portsOpen(p === '*' ? null : p, null, num(v(a.body, 'protocol'))), a.line);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
} else if (type === 'google_storage_bucket_iam_member' || type === 'google_storage_bucket_iam_binding') {
|
|
496
|
+
const ms = type.endsWith('_binding') ? strList(v(b.body, 'members')) : strList(v(b.body, 'member'));
|
|
497
|
+
if (ms.some((m) => m === 'allUsers' || m === 'allAuthenticatedUsers')) fact('storage-public', `${where} lets ${ms.includes('allUsers') ? 'anyone on the internet' : 'anyone with a Google account'} into the bucket.`, b.line);
|
|
498
|
+
}
|
|
499
|
+
}
|