@skillstech/thunderlang 0.5.11 → 0.5.12

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.
Files changed (66) hide show
  1. package/CHANGELOG.md +437 -0
  2. package/dist/core.cjs +30431 -7604
  3. package/dist/index.cjs +28577 -5331
  4. package/dist/learn.cjs +22676 -3870
  5. package/package.json +12 -3
  6. package/src/bicep.mjs +167 -0
  7. package/src/cli.mjs +169 -3
  8. package/src/commands.mjs +464 -0
  9. package/src/core.d.ts +12 -4
  10. package/src/core.mjs +12 -4
  11. package/src/emit.mjs +1 -1
  12. package/src/executed.d.mts +53 -0
  13. package/src/executed.mjs +465 -0
  14. package/src/faithful.mjs +137 -0
  15. package/src/file-formats.mjs +35 -0
  16. package/src/hcl.mjs +94 -0
  17. package/src/index.d.ts +7 -1
  18. package/src/index.mjs +6 -1
  19. package/src/infra-bicep.mjs +312 -0
  20. package/src/infra-cloud.mjs +348 -0
  21. package/src/infra-compose.mjs +315 -0
  22. package/src/infra-containers.mjs +100 -0
  23. package/src/infra-docker.mjs +267 -0
  24. package/src/infra-expr.mjs +509 -0
  25. package/src/infra-gha.mjs +350 -0
  26. package/src/infra-k8s.mjs +657 -0
  27. package/src/infra-terraform.mjs +499 -0
  28. package/src/infra-words.mjs +811 -0
  29. package/src/libraries.mjs +202 -0
  30. package/src/lift.mjs +48 -6
  31. package/src/meaning.d.mts +89 -0
  32. package/src/meaning.mjs +2544 -0
  33. package/src/model.d.mts +59 -12
  34. package/src/model.mjs +462 -80
  35. package/src/powershell.mjs +1361 -0
  36. package/src/read-repo-fs.mjs +29 -7
  37. package/src/read-repo.d.mts +5 -1
  38. package/src/read-repo.mjs +33 -7
  39. package/src/read.d.mts +21 -1
  40. package/src/read.mjs +1015 -42
  41. package/src/review.d.mts +35 -0
  42. package/src/review.mjs +671 -0
  43. package/src/rlang.mjs +1084 -0
  44. package/src/round-trip.d.mts +12 -0
  45. package/src/round-trip.mjs +174 -0
  46. package/src/runners/thunder-generate.mjs +56 -0
  47. package/src/runners/thunder-trace.cjs +284 -0
  48. package/src/runners/thunder_trace.py +599 -0
  49. package/src/running.d.mts +104 -0
  50. package/src/running.mjs +787 -0
  51. package/src/same.d.mts +1 -0
  52. package/src/same.mjs +24 -3
  53. package/src/shell.mjs +1212 -0
  54. package/src/sql.mjs +3 -2
  55. package/src/steps.d.mts +6 -1
  56. package/src/steps.mjs +1448 -86
  57. package/src/system.d.mts +12 -0
  58. package/src/system.mjs +845 -0
  59. package/src/things-langs.mjs +275 -0
  60. package/src/thunderize.mjs +3 -3
  61. package/src/visual.d.mts +5 -5
  62. package/src/visual.mjs +24 -3
  63. package/src/write-steps.d.mts +64 -0
  64. package/src/write-steps.mjs +1608 -0
  65. package/src/write.mjs +2 -1
  66. package/src/yaml.mjs +403 -0
@@ -0,0 +1,657 @@
1
+ // Kubernetes in Thunder (spec section 12): what a cluster is told to run, who can reach it, and who can do what in
2
+ // it. Each resource in a YAML file (several documents per file are fine) is a Resource with its kind as written and
3
+ // an address (`Deployment/api`, `Service/shop/web` in a namespace). A workload knows what it runs in words: the image,
4
+ // how many copies, ports, settings (a Secret's value is only named), CPU and memory, its health checks, and the user
5
+ // it runs as. A Service sends to the workloads its selector picks; an Ingress sends web addresses to Services; RBAC
6
+ // roles and bindings are Permissions (wide when they allow everything or give cluster-admin). The order things are
7
+ // made is one Steps card per file. Helm templates are not read (they are not Kubernetes until Helm fills them in).
8
+ // Deterministic, browser-safe; reads the file, not the cluster.
9
+ import { parseYamlDocs, get, entry, list, scalar } from './yaml.mjs';
10
+ import { cronWords, listWords, cap } from './infra-words.mjs';
11
+ import { topoOrder } from './infra-cloud.mjs';
12
+ import { parseImage, imageShort, imageWords, imageNotPinned, cpuWords, memWords, isSecretName, secretLiteral, servicesNamed, commandText, hasVar } from './infra-containers.mjs';
13
+
14
+ const STARTS = 'worked out when it starts';
15
+
16
+ /** Kinds in words, for labels and steps. Kinds Thunder does not know keep their name. */
17
+ const KIND_WORDS = {
18
+ Deployment: 'deployment', StatefulSet: 'stateful set', DaemonSet: 'daemon set', ReplicaSet: 'replica set', ReplicationController: 'replication controller',
19
+ Job: 'job', CronJob: 'scheduled job', Pod: 'pod', Service: 'service', Ingress: 'ingress', ConfigMap: 'ConfigMap', Secret: 'Secret',
20
+ PersistentVolumeClaim: 'storage claim', PersistentVolume: 'storage volume', StorageClass: 'storage class', ServiceAccount: 'service account',
21
+ Role: 'role', ClusterRole: 'cluster role', RoleBinding: 'role binding', ClusterRoleBinding: 'cluster role binding', NetworkPolicy: 'network policy',
22
+ HorizontalPodAutoscaler: 'autoscaler', Namespace: 'namespace', PodDisruptionBudget: 'disruption budget', IngressClass: 'ingress class',
23
+ LimitRange: 'limit range', ResourceQuota: 'resource quota', CustomResourceDefinition: 'custom resource definition',
24
+ };
25
+ const CLUSTER_SCOPED = new Set(['Namespace', 'ClusterRole', 'ClusterRoleBinding', 'PersistentVolume', 'StorageClass', 'IngressClass', 'CustomResourceDefinition', 'Node', 'PriorityClass', 'MutatingWebhookConfiguration', 'ValidatingWebhookConfiguration', 'APIService']);
26
+ const WORKLOADS = new Set(['Deployment', 'StatefulSet', 'DaemonSet', 'ReplicaSet', 'ReplicationController', 'Job', 'CronJob', 'Pod']);
27
+ export const kindWords = (k) => KIND_WORDS[k] ?? k;
28
+
29
+ /** A stable address: `Kind/name`, or `Kind/namespace/name` outside the default namespace. */
30
+ export function k8sAddress(kind, name, ns) {
31
+ return CLUSTER_SCOPED.has(kind) || !ns || ns === 'default' ? `${kind}/${name}` : `${kind}/${ns}/${name}`;
32
+ }
33
+
34
+ /** True when the file is a Helm template (or another template), not Kubernetes YAML yet. */
35
+ export function isHelmTemplate(src) {
36
+ const s = String(src ?? '');
37
+ if (!s.includes('{{')) return false;
38
+ return /\{\{-?\s*(?:\.Values|\.Release|\.Chart|\.Capabilities|\.Files|include\s|template\s|toYaml\b|tpl\s)/.test(s) || /^\s*\{\{-?\s*(?:if|end|range|with|define|else)\b/m.test(s);
39
+ }
40
+
41
+ const str = (n) => { const v = scalar(n); return v == null ? undefined : String(v); };
42
+ const num = (n) => { const v = scalar(n); return typeof v === 'number' ? v : v != null && /^\d+$/.test(String(v)) ? Number(v) : undefined; };
43
+ const bool = (n) => { const v = scalar(n); return typeof v === 'boolean' ? v : undefined; };
44
+ const at = (n, ...keys) => { let cur = n; for (const k of keys) cur = get(cur, k); return cur; };
45
+ const lineOf = (n, key, fallback) => entry(n, key)?.line ?? fallback;
46
+ const labelsOf = (n) => (n?.t === 'map' ? Object.fromEntries(n.entries.map((e) => [e.key, str(e.value) ?? ''])) : {});
47
+ const selectorWords = (labels) => listWords(Object.entries(labels).map(([k, v]) => `${k}=${v}`));
48
+ /** A label selector (matchLabels, or a plain map), with matchExpressions in words. */
49
+ function selectorOf(n) {
50
+ if (!n || n.t !== 'map') return { labels: {}, says: 'every pod' };
51
+ const ml = get(n, 'matchLabels'), me = get(n, 'matchExpressions');
52
+ const labels = ml || me ? labelsOf(ml) : labelsOf(n);
53
+ const parts = Object.entries(labels).map(([k, v]) => `${k}=${v}`);
54
+ for (const x of list(me)) {
55
+ const vals = list(get(x, 'values')).map(str);
56
+ const op = str(get(x, 'operator'));
57
+ parts.push(op === 'In' ? `${str(get(x, 'key'))} is ${vals.join(' or ')}` : op === 'NotIn' ? `${str(get(x, 'key'))} is not ${vals.join(' or ')}` : op === 'Exists' ? `${str(get(x, 'key'))} is set` : `${str(get(x, 'key'))} is not set`);
58
+ }
59
+ return { labels, exprs: !!me, says: parts.length ? `pods with ${listWords(parts)}` : 'every pod' };
60
+ }
61
+ const matches = (sel, labels) => Object.keys(sel).length > 0 && Object.entries(sel).every(([k, v]) => labels?.[k] === v);
62
+
63
+ const short = (s, n = 80) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
64
+ const seconds = (n) => (n === 1 ? '1 second' : `${n} seconds`);
65
+
66
+ /** A health check in words: "a web request to /_healthz on port 8080, every 10 seconds". */
67
+ function probeWords(p, verb = 'succeeds') {
68
+ let how;
69
+ const h = get(p, 'httpGet'), t = get(p, 'tcpSocket'), e = get(p, 'exec'), g = get(p, 'grpc');
70
+ if (h) how = `a web request to ${str(get(h, 'path')) ?? '/'} on port ${str(get(h, 'port')) ?? '?'}${/^https$/i.test(str(get(h, 'scheme')) ?? '') ? ' (HTTPS)' : ''}`;
71
+ else if (t) how = `a connection to port ${str(get(t, 'port')) ?? '?'}`;
72
+ else if (e) how = `running ${short(commandText(list(get(e, 'command')).map(str)))}`;
73
+ else if (g) how = `a gRPC health check on port ${str(get(g, 'port')) ?? '?'}`;
74
+ else how = 'a check the file does not spell out';
75
+ const extra = [];
76
+ const d = num(get(p, 'initialDelaySeconds')), every = num(get(p, 'periodSeconds')), fails = num(get(p, 'failureThreshold'));
77
+ if (d) extra.push(`starting after ${seconds(d)}`);
78
+ if (every) extra.push(`every ${seconds(every)}`);
79
+ if (fails) extra.push(`giving up after ${fails} failure${fails === 1 ? '' : 's'}`);
80
+ return `${how} ${verb}${extra.length ? ` (${extra.join(', ')})` : ''}`;
81
+ }
82
+
83
+ const ACCESS = { ReadWriteOnce: 'read and written by one node at a time', ReadOnlyMany: 'read by many nodes', ReadWriteMany: 'read and written by many nodes', ReadWriteOncePod: 'read and written by one pod at a time' };
84
+ const VERB_WORDS = { get: 'read', list: 'list', watch: 'watch', create: 'create', update: 'change', patch: 'change', delete: 'delete', deletecollection: 'delete', impersonate: 'act as', bind: 'give out', escalate: 'raise', use: 'use', approve: 'approve', sign: 'sign' };
85
+ /** RBAC verbs in words: get/list/watch -> "read (get, list, watch)"; "*" -> "do anything to". */
86
+ function verbsWords(verbs) {
87
+ if (verbs.includes('*')) return 'do anything to';
88
+ const read = ['get', 'list', 'watch'];
89
+ if (verbs.every((v) => read.includes(v))) return `read (${listWords(verbs)})`;
90
+ return listWords([...new Set(verbs.map((v) => VERB_WORDS[v] ?? v))]);
91
+ }
92
+ const BUILTIN_ROLES = {
93
+ 'cluster-admin': 'do anything (cluster-admin)', admin: 'do almost anything, including give others access (admin)',
94
+ edit: 'read and change most things, but not roles or access (edit)', view: 'read most things, but not Secrets (view)',
95
+ };
96
+
97
+ // ── One resource ──────────────────────────────────────────────────────────────────────────────────────────
98
+
99
+ /**
100
+ * Read a Kubernetes YAML file: every resource as a Resource, its settings, facts, links, and permissions, plus one
101
+ * Steps card with the order they are made. `file` is the path shown in links and facts.
102
+ */
103
+ export function readKubernetes(src, file = 'k8s.yaml') {
104
+ const source = String(src ?? '');
105
+ if (isHelmTemplate(source)) throw new Error('This is a Helm template: {{ … }} is filled in by Helm before Kubernetes sees it. Thunder reads plain Kubernetes YAML, not templates yet.');
106
+ const docs = parseYamlDocs(source);
107
+ // Other templates ({{cell}}, {{ config_data }}) are not YAML until they are filled in either.
108
+ if (source.includes('{{') && docs.some((d) => d.error)) throw new Error('This is a template: {{ … }} is filled in before Kubernetes sees it. Thunder reads plain Kubernetes YAML, not templates yet.');
109
+ const srcLines = source.split('\n');
110
+ const things = [], settings = [], facts = [], links = [], permissions = [], unknowns = [], declared = [];
111
+ const factIds = new Set();
112
+ const fact = (kind, says, line) => {
113
+ let id = `${file}#${kind}#${line}`;
114
+ for (let i = 2; factIds.has(id); i++) id = `${file}#${kind}#${line}#${i}`;
115
+ factIds.add(id);
116
+ facts.push({ id, kind, says, file, line });
117
+ };
118
+ const setting = (x) => { if (!settings.some((s) => s.name === x.name && s.source === x.source && s.line === x.line)) settings.push({ file, ...x }); };
119
+ const link = (from, to, kind, line, extra = {}) => {
120
+ if (from === to) return;
121
+ if (links.some((l) => l.from === from && l.to === to && l.kind === kind && !extra.selector)) return;
122
+ links.push({ from, to, kind, file, line, ...extra });
123
+ };
124
+
125
+ // Resources, with `kind: List` opened up.
126
+ const resources = [];
127
+ for (const d of docs) {
128
+ if (d.error) { unknowns.push({ file, line: d.error.line ?? d.line, why: `This document could not be read as YAML: ${d.error.message}` }); continue; }
129
+ const n = d.node;
130
+ if (!n || n.t !== 'map') continue;
131
+ if (str(get(n, 'kind')) === 'List' || (str(get(n, 'kind')) ?? '').endsWith('List') && get(n, 'items')) {
132
+ for (const it of list(get(n, 'items'))) if (it.t === 'map') resources.push({ n: it, line: it.line, endLine: lastLine(it) });
133
+ } else resources.push({ n, line: d.line, endLine: d.endLine });
134
+ }
135
+
136
+ for (const r of resources) {
137
+ const kind = str(get(r.n, 'kind'));
138
+ const apiVersion = str(get(r.n, 'apiVersion'));
139
+ const meta = get(r.n, 'metadata');
140
+ const name = str(get(meta, 'name')) ?? str(get(meta, 'generateName')) ?? (kind === 'Kustomization' || kind === 'Component' ? 'kustomization' : '(no name)');
141
+ if (!kind) { unknowns.push({ file, line: r.line, why: 'This document has no kind:, so Thunder cannot tell what it makes.' }); continue; }
142
+ const ns = CLUSTER_SCOPED.has(kind) ? undefined : str(get(meta, 'namespace'));
143
+ const address = k8sAddress(kind, name, ns);
144
+ const addr = (k, nm) => k8sAddress(k, nm, CLUSTER_SCOPED.has(k) ? undefined : ns);
145
+ declared.push({ address, kind, name, line: r.line, n: r.n });
146
+ const knows = [];
147
+ const know = (label, kindText, line, extra = {}) => knows.push({ name: extra.name ?? label, label, kind: kindText, start: null, line: line ?? r.line, ...extra });
148
+ const where = `The ${kindWords(kind)} ${name}`;
149
+ const thing = { kind: 'resource', name: address, label: `${cap(kindWords(kind))} ${name}`, resourceType: kind, address, file, lines: [r.line, r.endLine], knows, choices: [] };
150
+ const doc = commentAbove(srcLines, r.line);
151
+ if (doc) thing.doc = doc;
152
+ if (ns) { know('Namespace', ns, lineOf(meta, 'namespace')); link(address, `Namespace/${ns}`, 'runs-in', lineOf(meta, 'namespace')); }
153
+ const spec = get(r.n, 'spec');
154
+
155
+ if (WORKLOADS.has(kind)) {
156
+ readWorkload({ kind, name, spec, n: r.n, address, ns, where, know, fact, setting, link, addr, thing, line: r.line });
157
+ } else if (kind === 'Service') {
158
+ const type = str(get(spec, 'type')) ?? 'ClusterIP';
159
+ const typeLine = lineOf(spec, 'type', r.line);
160
+ const ann = labelsOf(get(meta, 'annotations'));
161
+ const internal = Object.entries(ann).some(([k, v]) => (/load-balancer-internal$/.test(k) && /^(true|0\.0\.0\.0\/0)$/i.test(v)) || (/load-balancer-(type|scheme)$/.test(k) && /^internal$/i.test(v)));
162
+ const ranges = list(get(spec, 'loadBalancerSourceRanges')).map(str);
163
+ const ports = list(get(spec, 'ports'));
164
+ const portList = ports.map((p) => {
165
+ const port = str(get(p, 'port')), target = str(get(p, 'targetPort')), node = str(get(p, 'nodePort'));
166
+ return `${port}${target && target !== port ? ` (to ${target} on the pods)` : ''}${node ? ` (and ${node} on every node)` : ''}${/^udp$/i.test(str(get(p, 'protocol')) ?? '') ? ' (UDP)' : ''}`;
167
+ });
168
+ if (type === 'ExternalName') {
169
+ know('Sends to', `the outside address ${str(get(spec, 'externalName')) ?? '?'}`, lineOf(spec, 'externalName'));
170
+ } else {
171
+ const reach = type === 'LoadBalancer' ? (internal ? 'inside the private network only (an internal load balancer)' : ranges.length && !ranges.includes('0.0.0.0/0') ? `outside the cluster, only from ${listWords(ranges)}` : 'the internet, through a load balancer')
172
+ : type === 'NodePort' ? 'outside the cluster, on a port of every node' : str(get(spec, 'clusterIP')) === 'None' ? 'inside the cluster, each pod by its own name (no shared address)' : 'inside the cluster only';
173
+ know('Reachable from', reach, typeLine);
174
+ if ((type === 'LoadBalancer' && !internal && (!ranges.length || ranges.includes('0.0.0.0/0'))) || type === 'NodePort') {
175
+ fact('public-ingress', type === 'NodePort'
176
+ ? `${where} is a NodePort: anyone who can reach a node can reach ${portList.length ? `port${ports.length === 1 ? '' : 's'} ${listWords(ports.map((p) => str(get(p, 'nodePort')) ?? '(picked by Kubernetes)'))}` : 'it'}.`
177
+ : `${where} is a LoadBalancer: anyone on the internet can reach ${portList.length ? `port${ports.length === 1 ? '' : 's'} ${listWords(ports.map((p) => str(get(p, 'port'))))}` : 'it'}.`, typeLine);
178
+ }
179
+ }
180
+ if (portList.length) know(ports.length === 1 ? 'Port' : 'Ports', listWords(portList), lineOf(spec, 'ports'));
181
+ const sel = get(spec, 'selector');
182
+ if (sel) {
183
+ const s = selectorOf(sel);
184
+ know('Sends to', s.says, lineOf(spec, 'selector'));
185
+ thing.selects = { labels: s.labels, ns, line: lineOf(spec, 'selector') };
186
+ } else if (type !== 'ExternalName') know('Sends to', 'addresses listed elsewhere (no selector)', typeLine);
187
+ } else if (kind === 'Ingress') {
188
+ readIngress({ spec, meta, where, know, fact, link, address, addr, line: r.line });
189
+ } else if (kind === 'ConfigMap') {
190
+ for (const key of ['data', 'binaryData']) for (const e of get(r.n, key)?.entries ?? []) {
191
+ const v = str(e.value) ?? '';
192
+ const secret = isSecretName(e.key);
193
+ const multi = v.includes('\n');
194
+ if (secretLiteral(e.key, v)) fact('secret-in-plain-config', `The ConfigMap ${name} has ${e.key} written in the file, and ConfigMaps are not kept secret.`, e.line);
195
+ const shown = key === 'binaryData' ? 'binary data' : secret ? 'a secret-looking value (not shown)' : multi ? `a file (${v.replace(/\n$/, '').split('\n').length} lines)` : v === '' ? '(empty)' : short(v);
196
+ know(e.key, shown, e.line, { setting: true, ...(secret ? { secret: true } : {}) });
197
+ setting({ name: e.key, source: 'literal', secret, line: e.line, ...(!secret && !multi && key === 'data' ? { default: short(v) } : {}) });
198
+ }
199
+ } else if (kind === 'Secret') {
200
+ const type = str(get(r.n, 'type')) ?? 'Opaque';
201
+ know('Holds', { 'kubernetes.io/tls': 'a TLS certificate and its key', 'kubernetes.io/dockerconfigjson': 'a sign-in for a container registry', 'kubernetes.io/dockercfg': 'a sign-in for a container registry', 'kubernetes.io/service-account-token': 'a service account token', 'kubernetes.io/basic-auth': 'a user name and password', 'kubernetes.io/ssh-auth': 'an SSH key' }[type] ?? `secret values (${type})`, lineOf(r.n, 'type'));
202
+ let written = null;
203
+ for (const key of ['data', 'stringData']) for (const e of get(r.n, key)?.entries ?? []) {
204
+ know(e.key, 'a secret value (only its name is shown)', e.line, { setting: true, secret: true });
205
+ setting({ name: e.key, source: 'secret', secret: true, line: e.line });
206
+ if (!written && (str(e.value) ?? '') !== '' && !hasVar(str(e.value))) written = e.line;
207
+ }
208
+ if (written) fact('secret-in-plain-config', `The Secret ${name} has its values written in this file: ${get(r.n, 'data') ? 'values under data: are only base64-encoded, not encrypted, so ' : ''}anyone who can read the file can read them.`, written);
209
+ } else if (kind === 'PersistentVolumeClaim') {
210
+ const size = str(at(spec, 'resources', 'requests', 'storage'));
211
+ if (size) know('Asks for', `${memWords(size)} of storage`, lineOf(spec, 'resources'));
212
+ const modes = list(get(spec, 'accessModes')).map(str);
213
+ if (modes.length) know('Can be', listWords(modes.map((m) => ACCESS[m] ?? m)), lineOf(spec, 'accessModes'));
214
+ const sc = str(get(spec, 'storageClassName'));
215
+ if (sc != null) know('Storage class', sc === '' ? 'none (only a volume made by hand)' : sc, lineOf(spec, 'storageClassName'));
216
+ const vol = str(get(spec, 'volumeName'));
217
+ if (vol) { know('Uses the volume', vol, lineOf(spec, 'volumeName')); link(address, `PersistentVolume/${vol}`, 'uses', lineOf(spec, 'volumeName')); }
218
+ } else if (kind === 'PersistentVolume') {
219
+ const size = str(at(spec, 'capacity', 'storage'));
220
+ if (size) know('Holds', `${memWords(size)} of storage`, lineOf(spec, 'capacity'));
221
+ const hp = str(at(spec, 'hostPath', 'path'));
222
+ if (hp) know('Kept in', `the node's own folder ${hp}`, lineOf(spec, 'hostPath'));
223
+ const policy = str(get(spec, 'persistentVolumeReclaimPolicy'));
224
+ if (policy) know('When released', { Retain: 'kept until someone removes it', Delete: 'deleted', Recycle: 'emptied and reused' }[policy] ?? policy, lineOf(spec, 'persistentVolumeReclaimPolicy'));
225
+ } else if (kind === 'ServiceAccount') {
226
+ const auto = bool(get(r.n, 'automountServiceAccountToken'));
227
+ know('Its token', auto === false ? 'not handed to its pods unless they ask' : 'handed to every pod that runs as it (the default)', lineOf(r.n, 'automountServiceAccountToken'));
228
+ for (const s of list(get(r.n, 'imagePullSecrets'))) { const sn = str(get(s, 'name')); if (sn) { know('Signs in to pull images with', `the Secret ${sn}`, s.line); link(address, addr('Secret', sn), 'reads-from', s.line); } }
229
+ } else if (kind === 'Role' || kind === 'ClusterRole') {
230
+ readRole({ kind, name, n: r.n, ns, know, permissions, file });
231
+ } else if (kind === 'RoleBinding' || kind === 'ClusterRoleBinding') {
232
+ readBinding({ kind, name, n: r.n, ns, know, permissions, file, address, link, addr });
233
+ } else if (kind === 'NetworkPolicy') {
234
+ readNetworkPolicy({ spec, know });
235
+ } else if (kind === 'HorizontalPodAutoscaler') {
236
+ const target = get(spec, 'scaleTargetRef');
237
+ const tk = str(get(target, 'kind')), tn = str(get(target, 'name'));
238
+ if (tk && tn) { know('Scales', `the ${kindWords(tk)} ${tn}`, lineOf(spec, 'scaleTargetRef')); link(address, addr(tk, tn), 'uses', lineOf(spec, 'scaleTargetRef')); }
239
+ const min = num(get(spec, 'minReplicas')) ?? 1, max = num(get(spec, 'maxReplicas'));
240
+ know('Copies', `between ${min} and ${max ?? '?'}`, lineOf(spec, 'maxReplicas'));
241
+ const aims = [];
242
+ const v1 = num(get(spec, 'targetCPUUtilizationPercentage'));
243
+ if (v1) aims.push(`${v1}% of the CPU it asks for`);
244
+ for (const m of list(get(spec, 'metrics'))) {
245
+ const res = get(m, 'resource');
246
+ if (res) {
247
+ const util = num(at(res, 'target', 'averageUtilization')) ?? num(get(res, 'targetAverageUtilization'));
248
+ aims.push(util != null ? `${util}% of the ${str(get(res, 'name')) === 'memory' ? 'memory' : 'CPU'} it asks for` : `a ${str(get(res, 'name')) ?? 'resource'} target`);
249
+ } else aims.push(`a ${str(get(m, 'type'))?.toLowerCase() ?? 'custom'} measure`);
250
+ }
251
+ if (aims.length) know('Aims for', listWords(aims), lineOf(spec, v1 ? 'targetCPUUtilizationPercentage' : 'metrics'));
252
+ } else if (kind === 'Namespace') {
253
+ know('Is', 'a named space that keeps the resources in it apart from others', r.line);
254
+ } else if ((kind === 'Kustomization' || kind === 'Component') && /kustomize/.test(apiVersion ?? '')) {
255
+ // A kustomization is not a resource in the cluster: it says which files to combine and how to change them.
256
+ const files = [...list(get(r.n, 'resources')), ...list(get(r.n, 'components')), ...list(get(r.n, 'bases'))].map(str).filter(Boolean);
257
+ know('Combines', files.length ? short(listWords(files), 160) : 'nothing listed', lineOf(r.n, 'resources', lineOf(r.n, 'components')));
258
+ const patches = list(get(r.n, 'patches')).length + list(get(r.n, 'patchesStrategicMerge')).length + list(get(r.n, 'patchesJson6902')).length;
259
+ if (patches) know('Changes them with', `${patches} patch${patches === 1 ? '' : 'es'}`, lineOf(r.n, 'patches', lineOf(r.n, 'patchesStrategicMerge')));
260
+ const nsSet = str(get(r.n, 'namespace'));
261
+ if (nsSet) know('Puts everything in the namespace', nsSet, lineOf(r.n, 'namespace'));
262
+ for (const im of list(get(r.n, 'images'))) know(`Image ${str(get(im, 'name'))}`, `becomes ${[str(get(im, 'newName')) ?? str(get(im, 'name')), str(get(im, 'newTag')) ?? str(get(im, 'digest'))].filter(Boolean).join(':')}`, im.line);
263
+ thing.label = `Kustomization ${kind === 'Component' ? 'component ' : ''}(${file.slice(file.lastIndexOf('/') + 1)})`;
264
+ } else if (kind === 'PodDisruptionBudget') {
265
+ const min = str(get(spec, 'minAvailable')), max = str(get(spec, 'maxUnavailable'));
266
+ know('Keeps running', min != null ? `at least ${min} of ${selectorOf(get(spec, 'selector')).says}` : `all but ${max ?? '?'} of ${selectorOf(get(spec, 'selector')).says}`, lineOf(spec, min != null ? 'minAvailable' : 'maxUnavailable'));
267
+ } else {
268
+ // A kind Thunder does not read in detail is still drawn, with its type as written.
269
+ const keys = (spec?.t === 'map' ? spec.entries : r.n.entries.filter((e) => !['apiVersion', 'kind', 'metadata'].includes(e.key))).map((e) => e.key);
270
+ know('Kind', `${kind}${apiVersion ? ` (${apiVersion})` : ''}: Thunder draws it but does not read its settings yet`, r.line);
271
+ if (keys.length) know('Says', `${listWords(keys.slice(0, 6))}${keys.length > 6 ? `, and ${keys.length - 6} more` : ''}`, r.line);
272
+ }
273
+ things.push(thing);
274
+ }
275
+
276
+ // Services send to the workloads their selector picks, in this file; the rest are matched across files.
277
+ const workloads = things.filter((t) => t.podLabels);
278
+ for (const t of things) {
279
+ if (!t.selects) continue;
280
+ const hits = workloads.filter((w) => (w.podLabels.ns ?? '') === (t.selects.ns ?? '') && matches(t.selects.labels, w.podLabels.labels));
281
+ for (const w of hits) link(t.address, w.address, 'sends-to', t.selects.line);
282
+ if (!hits.length && Object.keys(t.selects.labels).length) links.push({ from: t.address, to: null, kind: 'sends-to', file, line: t.selects.line, selector: t.selects.labels, namespace: t.selects.ns ?? null });
283
+ }
284
+ // A setting whose value names a Service (`redis:6379`, `http://api:8080`, `db.shop.svc.cluster.local`) sends to it.
285
+ // Only exact names: the link is drawn when a Service with that address is read, in this file or another.
286
+ for (const t of things) for (const k of t.knows) if (k.setting && k.value != null) {
287
+ const ns = t.address.split('/').length === 3 ? t.address.split('/')[1] : undefined;
288
+ for (const host of servicesNamed(k.name, k.value, null)) {
289
+ const m = /^([a-z0-9-]+)\.([a-z0-9-]+)\.svc(\.cluster\.local)?$/.exec(host);
290
+ if (m) link(t.address, k8sAddress('Service', m[1], m[2]), 'sends-to', k.line);
291
+ else if (/^[a-z0-9-]+$/.test(host)) link(t.address, k8sAddress('Service', host, ns), 'sends-to', k.line);
292
+ }
293
+ delete k.value;
294
+ }
295
+
296
+ for (const p of permissions) if (p.wide) fact('wide-permission', `${cap(p.who)} can ${p.can} ${p.on}: ${p.why}.`, p.line);
297
+
298
+ // ── The order things are made: one Steps card ──
299
+ const byAddress = new Map(declared.map((d) => [d.address, d]));
300
+ const edges = links.filter((l) => l.to && byAddress.has(l.to) && l.kind !== 'sends-to').map((l) => [l.from, l.to]);
301
+ const order = topoOrder(declared.map((d) => d.address), edges);
302
+ const steps = [];
303
+ const seen = new Set();
304
+ for (const a of order) {
305
+ if (seen.has(a)) continue;
306
+ seen.add(a);
307
+ const d = byAddress.get(a);
308
+ const t = things.find((x) => x.address === a);
309
+ steps.push({ kind: 'call', says: stepWords(d, t, links, byAddress), code: `kind: ${d.kind}\nname: ${d.name}`, line: d.line });
310
+ }
311
+ const base = file.slice(file.lastIndexOf('/') + 1);
312
+ const items = [];
313
+ if (steps.length) {
314
+ const first = Math.min(...steps.map((s) => s.line)), last = Math.max(...resources.map((r) => r.endLine));
315
+ const n = declared.length;
316
+ items.push({
317
+ id: `apply:${first}`, name: 'apply', label: `Applying ${base}`, title: `What applying ${base} makes, in order`, line: first, endLine: last,
318
+ inputs: [], returns: null, provenance: 'inferred-from-code', kind: 'function', status: 'signature-only', steps, stepsMore: 0, stepsReadable: 1,
319
+ says: `Applying ${base} makes ${n} Kubernetes resource${n === 1 ? '' : 's'}, in the order they rely on each other.`,
320
+ headline: `Applying ${base}: ${n} resource${n === 1 ? '' : 's'}.`, guards: [], unread: [],
321
+ });
322
+ }
323
+ return { items, things, settings, facts, links, permissions, unknowns };
324
+ }
325
+
326
+ /** The last line a node covers. */
327
+ function lastLine(n) {
328
+ if (!n) return 0;
329
+ if (n.t === 'map') return Math.max(n.line, ...n.entries.map((e) => Math.max(e.line, lastLine(e.value))));
330
+ if (n.t === 'seq') return Math.max(n.line, ...n.items.map(lastLine));
331
+ if (n.block) return (n.valueLine ?? n.line) + Math.max(0, String(n.v).replace(/\n+$/, '').split('\n').length - 1);
332
+ return n.line;
333
+ }
334
+
335
+ /** The comment written right above a resource, unless it is a license header. */
336
+ function commentAbove(lines, line) {
337
+ const out = [];
338
+ for (let i = line - 2; i >= 0; i--) {
339
+ const t = lines[i].trim();
340
+ if (!t.startsWith('#')) break;
341
+ out.unshift(t.replace(/^#+\s?/, ''));
342
+ }
343
+ const text = out.filter(Boolean).join(' ').trim();
344
+ if (!text || /copyright|licen[sc]e|SPDX|^Source: /i.test(text) || text.length > 300) return null;
345
+ return text;
346
+ }
347
+
348
+ /** What one step of "applying" says: "Creates the deployment api (2 copies of api:1.4)". */
349
+ function stepWords(d, t, links, byAddress) {
350
+ const w = `the ${kindWords(d.kind)} ${d.name}`;
351
+ const k = (label) => t?.knows.find((x) => x.label === label)?.kind;
352
+ const sends = links.filter((l) => l.from === d.address && l.kind === 'sends-to' && l.to && byAddress.has(l.to)).map((l) => `the ${kindWords(byAddress.get(l.to).kind)} ${byAddress.get(l.to).name}`);
353
+ if (WORKLOADS.has(d.kind)) {
354
+ const image = t?.knows.find((x) => x.name === 'image')?.kind;
355
+ const copies = k('How many')?.replace(/ \(.*$/, '');
356
+ const img = image ? imageShort(image.replace(/ \(.*$/, '')) : null;
357
+ if (d.kind === 'CronJob') return `Creates ${w}, which runs ${k('When') ?? 'on a schedule'}${img ? ` (${img})` : ''}`;
358
+ if (d.kind === 'Job') return `Creates ${w}, which runs once until it succeeds${img ? ` (${img})` : ''}`;
359
+ if (d.kind === 'DaemonSet') return `Creates ${w}${img ? `, which runs ${img}` : ''} on every node`;
360
+ if (d.kind === 'Pod') return `Creates ${w}${img ? `, which runs ${img}` : ''}`;
361
+ return `Creates ${w}${copies || img ? ` (${[copies, img].filter(Boolean).join(' of ')})` : ''}`;
362
+ }
363
+ if (d.kind === 'Service' || d.kind === 'Ingress') return `Creates ${w}${sends.length ? `, which sends to ${listWords([...new Set(sends)])}` : ''}`;
364
+ if (d.kind === 'RoleBinding' || d.kind === 'ClusterRoleBinding') return `Creates ${w}, which ${t?.knows.find((x) => x.label === 'Gives')?.kind ? `gives ${t.knows.find((x) => x.label === 'Gives').kind}` : 'gives a role'}`;
365
+ return `Creates ${w}`;
366
+ }
367
+
368
+ // ── Workloads ─────────────────────────────────────────────────────────────────────────────────────────────
369
+
370
+ function readWorkload(c) {
371
+ const { kind, name, spec, n, address, ns, where, know, fact, setting, link, addr, thing } = c;
372
+ let tmpl, podSpec, podMeta;
373
+ if (kind === 'Pod') { podSpec = spec; podMeta = get(n, 'metadata'); }
374
+ else if (kind === 'CronJob') { tmpl = at(spec, 'jobTemplate', 'spec', 'template'); podSpec = get(tmpl, 'spec'); podMeta = get(tmpl, 'metadata'); }
375
+ else { tmpl = get(spec, 'template'); podSpec = get(tmpl, 'spec'); podMeta = get(tmpl, 'metadata'); }
376
+ thing.podLabels = { labels: labelsOf(get(podMeta, 'labels')), ns: ns ?? null };
377
+
378
+ if (kind === 'CronJob') {
379
+ const sched = str(get(spec, 'schedule'));
380
+ const tz = str(get(spec, 'timeZone'));
381
+ const w = sched ? cronWords(sched) : null;
382
+ know('When', w ? (tz ? w.replace(/ UTC$/, ` (${tz} time)`) : w.replace(/ UTC$/, " (the cluster's time zone)")) : `on the schedule ${sched ?? '?'} (cron)`, lineOf(spec, 'schedule'));
383
+ if (bool(get(spec, 'suspend'))) know('Paused', 'yes: it does not run until someone turns it back on', lineOf(spec, 'suspend'));
384
+ const cp = str(get(spec, 'concurrencyPolicy'));
385
+ if (cp) know('If the last run is still going', { Allow: 'runs again anyway', Forbid: 'skips this run', Replace: 'stops the last run and starts again' }[cp] ?? cp, lineOf(spec, 'concurrencyPolicy'));
386
+ } else if (kind === 'Job') {
387
+ const back = num(get(spec, 'backoffLimit'));
388
+ const comp = num(get(spec, 'completions'));
389
+ know('How many', `runs ${comp && comp > 1 ? `until it succeeds ${comp} times` : 'once until it succeeds'}, trying up to ${back ?? 6} more times`, lineOf(spec, 'backoffLimit'));
390
+ } else if (kind === 'DaemonSet') {
391
+ know('How many', 'one copy on every node', c.line);
392
+ } else if (kind !== 'Pod') {
393
+ const repl = get(spec, 'replicas');
394
+ const rn = num(repl);
395
+ know('How many', repl ? (rn != null ? `${rn} cop${rn === 1 ? 'y' : 'ies'}` : `${str(repl)} copies`) : '1 copy (the default; an autoscaler may change it)', lineOf(spec, 'replicas'));
396
+ }
397
+ if (kind === 'StatefulSet') {
398
+ const svc = str(get(spec, 'serviceName'));
399
+ if (svc) { know('Named through', `the service ${svc}`, lineOf(spec, 'serviceName')); link(address, addr('Service', svc), 'uses', lineOf(spec, 'serviceName')); }
400
+ for (const vct of list(get(spec, 'volumeClaimTemplates'))) {
401
+ const size = str(at(vct, 'spec', 'resources', 'requests', 'storage'));
402
+ know(`Each copy keeps ${str(at(vct, 'metadata', 'name')) ?? 'storage'}`, size ? `its own ${memWords(size)} of storage` : 'its own storage', vct.line);
403
+ }
404
+ }
405
+ if (!podSpec) return;
406
+
407
+ const sa = str(get(podSpec, 'serviceAccountName')) ?? str(get(podSpec, 'serviceAccount'));
408
+ if (sa) { know('Runs as the identity', `the service account ${sa}`, lineOf(podSpec, sa === str(get(podSpec, 'serviceAccountName')) ? 'serviceAccountName' : 'serviceAccount')); link(address, addr('ServiceAccount', sa), 'uses', lineOf(podSpec, 'serviceAccountName', lineOf(podSpec, 'serviceAccount'))); }
409
+ for (const h of ['hostNetwork', 'hostPID', 'hostIPC']) if (bool(get(podSpec, h))) {
410
+ const what = { hostNetwork: "the node's own network", hostPID: "every process on the node", hostIPC: "the node's shared memory" }[h];
411
+ know('Shares', what, lineOf(podSpec, h));
412
+ fact('privileged-container', `${where} shares ${what} (${h}: true), so it can see or reach far more than its own containers.`, lineOf(podSpec, h));
413
+ }
414
+ const nodeSel = labelsOf(get(podSpec, 'nodeSelector'));
415
+ if (Object.keys(nodeSel).length) know('Runs only on nodes with', selectorWords(nodeSel), lineOf(podSpec, 'nodeSelector'));
416
+ for (const s of list(get(podSpec, 'imagePullSecrets'))) { const sn = str(get(s, 'name')); if (sn) link(address, addr('Secret', sn), 'reads-from', s.line); }
417
+
418
+ // Volumes: what each name is, so a mount can say where its files come from.
419
+ const volumes = new Map();
420
+ for (const v of list(get(podSpec, 'volumes'))) {
421
+ const vn = str(get(v, 'name'));
422
+ let says = 'a volume', target = null, linkKind = 'uses';
423
+ const cm = get(v, 'configMap'), sec = get(v, 'secret'), pvc = get(v, 'persistentVolumeClaim'), hp = get(v, 'hostPath'), ed = get(v, 'emptyDir');
424
+ if (cm) { const x = str(get(cm, 'name')); says = `the files in the ConfigMap ${x}`; target = addr('ConfigMap', x); linkKind = 'reads-from'; }
425
+ else if (sec) { const x = str(get(sec, 'secretName')); says = `the Secret ${x}`; target = addr('Secret', x); linkKind = 'reads-from'; }
426
+ else if (pvc) { const x = str(get(pvc, 'claimName')); says = `the storage claim ${x}`; target = addr('PersistentVolumeClaim', x); }
427
+ else if (hp) {
428
+ const p = str(get(hp, 'path'));
429
+ says = `the node's own folder ${p}`;
430
+ if (/^\/(var\/run\/docker\.sock|run\/containerd|var\/run\/crio|proc|sys)?$|docker\.sock$/.test(p ?? '')) fact('privileged-container', `${where} mounts the node's ${p === '/' ? 'whole disk' : p}, which gives it control over the node.`, v.line);
431
+ } else if (ed) says = `a scratch folder${str(get(ed, 'medium')) === 'Memory' ? ' in memory' : ''} (emptied when the pod goes away)`;
432
+ else if (get(v, 'projected')) says = 'files gathered from several places';
433
+ if (vn) volumes.set(vn, { says, target, linkKind, line: v.line });
434
+ }
435
+
436
+ const pod = get(podSpec, 'securityContext');
437
+ const containers = [...list(get(podSpec, 'initContainers')).map((x) => ({ n: x, init: true })), ...list(get(podSpec, 'containers')).map((x) => ({ n: x, init: false }))];
438
+ const many = containers.length > 1;
439
+ for (const { n: ct, init } of containers) {
440
+ const cn = str(get(ct, 'name')) ?? 'container';
441
+ const pre = many ? `${init ? 'Before it starts, ' : ''}${cn}: ` : '';
442
+ const cwhere = many ? `The container ${cn} in ${where.replace(/^The /, 'the ')}` : where;
443
+ const image = str(get(ct, 'image'));
444
+ if (image) {
445
+ know(`${pre}Runs`, imageWords(image, STARTS), lineOf(ct, 'image'), { name: 'image', ...(hasVar(image) ? { computed: true } : {}) });
446
+ const says = imageNotPinned(image, cwhere);
447
+ if (says) fact('image-not-pinned', says, lineOf(ct, 'image'));
448
+ thing.images = [...(thing.images ?? []), { name: parseImage(image).name, ref: image, line: lineOf(ct, 'image') }];
449
+ }
450
+ const cmd = list(get(ct, 'command')).map(str), args = list(get(ct, 'args')).map(str);
451
+ if (cmd.length || args.length) know(`${pre}Starts with`, short(commandText([...cmd, ...args]), 120), lineOf(ct, cmd.length ? 'command' : 'args'));
452
+ const ports = list(get(ct, 'ports'));
453
+ if (ports.length) know(`${pre}${ports.length === 1 ? 'Opens port' : 'Opens ports'}`, listWords(ports.map((p) => `${str(get(p, 'containerPort'))}${str(get(p, 'name')) ? ` (${str(get(p, 'name'))})` : ''}${/^udp$/i.test(str(get(p, 'protocol')) ?? '') ? ' (UDP)' : ''}`)), lineOf(ct, 'ports'));
454
+ // Settings: a literal value is shown unless the name looks secret; a Secret's value is only named.
455
+ for (const e of list(get(ct, 'env'))) {
456
+ const en = str(get(e, 'name'));
457
+ if (!en) continue;
458
+ const vf = get(e, 'valueFrom');
459
+ const line = e.line;
460
+ if (vf) {
461
+ const sk = get(vf, 'secretKeyRef'), ck = get(vf, 'configMapKeyRef'), fr = get(vf, 'fieldRef'), rr = get(vf, 'resourceFieldRef');
462
+ if (sk) {
463
+ const sn = str(get(sk, 'name')), key = str(get(sk, 'key'));
464
+ know(`${pre}${en}`, `the secret value ${key} in the Secret ${sn} (only its name is shown)`, line, { name: en, setting: true, secret: true });
465
+ setting({ name: en, source: 'secret', secret: true, line });
466
+ link(address, addr('Secret', sn), 'reads-from', line);
467
+ } else if (ck) {
468
+ const cmn = str(get(ck, 'name')), key = str(get(ck, 'key'));
469
+ know(`${pre}${en}`, `the value ${key} in the ConfigMap ${cmn}`, line, { name: en, setting: true });
470
+ setting({ name: en, source: 'variable', secret: false, line });
471
+ link(address, addr('ConfigMap', cmn), 'reads-from', line);
472
+ } else if (fr || rr) {
473
+ const what = fr ? `its own ${str(get(fr, 'fieldPath')) ?? 'details'}` : `its own ${str(get(rr, 'resource')) ?? 'resource'} amount`;
474
+ know(`${pre}${en}`, `${what} (${STARTS})`, line, { name: en, setting: true, computed: true });
475
+ setting({ name: en, source: 'computed', secret: false, computed: true, line });
476
+ }
477
+ continue;
478
+ }
479
+ const v = str(get(e, 'value')) ?? '';
480
+ const secret = isSecretName(en);
481
+ const computed = /\$\([A-Za-z_]/.test(v);
482
+ if (secretLiteral(en, v)) fact('secret-in-plain-env', `${cwhere} has ${en} written in the file, where anyone who can read it sees the value.`, line);
483
+ know(`${pre}${en}`, secret ? 'a secret-looking setting, written in the file (not shown)' : computed ? `${short(v)} (${STARTS})` : `a setting: ${v === '' ? '(empty)' : short(v)}`, line, { name: en, setting: true, ...(secret ? { secret: true } : {}), ...(computed ? { computed: true } : {}), ...(!secret ? { value: v } : {}) });
484
+ setting({ name: en, source: computed ? 'computed' : 'literal', secret, line, ...(computed ? { computed: true } : {}), ...(!secret && !computed ? { default: v === '' ? '(empty)' : short(v) } : {}) });
485
+ }
486
+ for (const ef of list(get(ct, 'envFrom'))) {
487
+ const cmr = get(ef, 'configMapRef'), sr = get(ef, 'secretRef');
488
+ const pfx = str(get(ef, 'prefix'));
489
+ if (cmr) { const x = str(get(cmr, 'name')); know(`${pre}Takes every setting in`, `the ConfigMap ${x}${pfx ? ` (named with ${pfx} in front)` : ''}`, ef.line); link(address, addr('ConfigMap', x), 'reads-from', ef.line); }
490
+ if (sr) { const x = str(get(sr, 'name')); know(`${pre}Takes every secret in`, `the Secret ${x} (only its name is shown)`, ef.line, { secret: true }); link(address, addr('Secret', x), 'reads-from', ef.line); }
491
+ }
492
+ // CPU and memory.
493
+ const res = get(ct, 'resources');
494
+ const req = get(res, 'requests'), lim = get(res, 'limits');
495
+ const amount = (m) => listWords([str(get(m, 'cpu')) && cpuWords(str(get(m, 'cpu'))), str(get(m, 'memory')) && `${memWords(str(get(m, 'memory')))} of memory`].filter(Boolean));
496
+ if (req && amount(req)) know(`${pre}Asks for`, amount(req), lineOf(res, 'requests'));
497
+ if (lim && amount(lim)) know(`${pre}Can use at most`, amount(lim), lineOf(res, 'limits'));
498
+ if (!init && (!lim || !lim.entries?.length)) fact('no-resource-limits', `${cwhere} has no resource limits, so it can use as much CPU and memory as the node has.`, lineOf(ct, 'resources', lineOf(ct, 'name', ct.line)));
499
+ // Health checks.
500
+ for (const [key, label] of [['startupProbe', 'Has started when'], ['readinessProbe', 'Ready for traffic when'], ['livenessProbe', 'Restarted when']]) {
501
+ const p = get(ct, key);
502
+ if (p) know(`${pre}${label}`, probeWords(p, key === 'livenessProbe' ? 'fails' : 'succeeds'), lineOf(ct, key));
503
+ }
504
+ // Who it runs as.
505
+ const sc = get(ct, 'securityContext');
506
+ const pick = (k) => { const a = get(sc, k); return a ? { v: scalar(a), line: lineOf(sc, k) } : get(pod, k) ? { v: scalar(get(pod, k)), line: lineOf(pod, k) } : null; };
507
+ const user = pick('runAsUser'), nonRoot = pick('runAsNonRoot');
508
+ const privileged = bool(get(sc, 'privileged'));
509
+ const adds = list(at(sc, 'capabilities', 'add')).map(str);
510
+ const scLine = lineOf(ct, 'securityContext', lineOf(ct, 'name', ct.line));
511
+ if (privileged) { know(`${pre}Privileged`, 'yes: it can do almost anything on the node', lineOf(sc, 'privileged')); fact('privileged-container', `${cwhere} is privileged (privileged: true), so it can do almost anything on the node.`, lineOf(sc, 'privileged')); }
512
+ if (adds.some((a) => /^(ALL|SYS_ADMIN|CAP_SYS_ADMIN)$/i.test(a))) fact('privileged-container', `${cwhere} adds the ${adds.filter((a) => /ALL|SYS_ADMIN/i.test(a)).join(' and ')} capabilit${adds.length === 1 ? 'y' : 'ies'}, which gives it nearly the power of the node itself.`, lineOf(sc, 'capabilities'));
513
+ if (user && Number(user.v) === 0) {
514
+ know(`${pre}Runs as`, 'root (user 0), the user that can do anything', user.line);
515
+ fact('runs-as-root', `${cwhere} runs as root (runAsUser: 0).`, user.line);
516
+ } else if (user && user.v != null) {
517
+ know(`${pre}Runs as`, `the user ${user.v}${nonRoot?.v === true ? ' (never root)' : ''}`, user.line);
518
+ } else if (nonRoot?.v === true) {
519
+ know(`${pre}Runs as`, 'a user that is not root (Kubernetes refuses to start it as root)', nonRoot.line);
520
+ } else {
521
+ know(`${pre}Runs as`, "the image's own user (the file does not say; it may be root)", scLine);
522
+ fact('runs-as-root', `${cwhere} may run as root: nothing in the file stops it (no runAsNonRoot: true and no runAsUser).`, scLine);
523
+ }
524
+ if (bool(get(sc, 'readOnlyRootFilesystem'))) know(`${pre}Its own files`, 'read-only (it cannot change its image)', lineOf(sc, 'readOnlyRootFilesystem'));
525
+ // Where its volumes are mounted.
526
+ for (const m of list(get(ct, 'volumeMounts'))) {
527
+ const v = volumes.get(str(get(m, 'name')));
528
+ const ro = bool(get(m, 'readOnly'));
529
+ know(`${pre}${str(get(m, 'mountPath'))}`, `${v?.says ?? `the volume ${str(get(m, 'name'))}`}${ro ? ' (read-only)' : ''}`, m.line);
530
+ if (v?.target) link(address, v.target, v.linkKind, m.line);
531
+ }
532
+ }
533
+ // Volumes no container mounts still point at what they name.
534
+ for (const v of volumes.values()) if (v.target) link(address, v.target, v.linkKind, v.line);
535
+ }
536
+
537
+ // ── Ingress ───────────────────────────────────────────────────────────────────────────────────────────────
538
+
539
+ function readIngress({ spec, meta, where, know, fact, link, address, addr, line }) {
540
+ const cls = str(get(spec, 'ingressClassName')) ?? labelsOf(get(meta, 'annotations'))['kubernetes.io/ingress.class'];
541
+ if (cls) know('Handled by', `the ${cls} ingress controller`, lineOf(spec, 'ingressClassName', line));
542
+ const backend = (b) => {
543
+ if (!b) return null;
544
+ const svc = get(b, 'service');
545
+ const sn = str(get(svc, 'name')) ?? str(get(b, 'serviceName'));
546
+ const port = str(at(svc, 'port', 'number')) ?? str(at(svc, 'port', 'name')) ?? str(get(b, 'servicePort'));
547
+ if (!sn) { const r = get(b, 'resource'); return r ? { says: `the ${kindWords(str(get(r, 'kind')))} ${str(get(r, 'name'))}` } : null; }
548
+ return { sn, says: `the service ${sn}${port ? `, port ${port}` : ''}` };
549
+ };
550
+ const hosts = [];
551
+ const def = backend(get(spec, 'defaultBackend') ?? get(spec, 'backend'));
552
+ if (def) { know('Everything else goes to', def.says, lineOf(spec, 'defaultBackend', lineOf(spec, 'backend'))); if (def.sn) link(address, addr('Service', def.sn), 'sends-to', lineOf(spec, 'defaultBackend', lineOf(spec, 'backend'))); }
553
+ for (const rule of list(get(spec, 'rules'))) {
554
+ const host = str(get(rule, 'host'));
555
+ if (host) hosts.push(host);
556
+ for (const p of list(at(rule, 'http', 'paths'))) {
557
+ const b = backend(get(p, 'backend'));
558
+ const path = str(get(p, 'path')) ?? '/';
559
+ const type = str(get(p, 'pathType'));
560
+ know(`${host ?? '(any address)'}${path}`, `${b?.says ?? 'nowhere the file names'}${type === 'Exact' ? ' (this exact path only)' : type === 'Prefix' ? ' (and everything under it)' : ''}`, p.line);
561
+ if (b?.sn) link(address, addr('Service', b.sn), 'sends-to', p.line);
562
+ }
563
+ }
564
+ for (const t of list(get(spec, 'tls'))) {
565
+ const sn = str(get(t, 'secretName'));
566
+ const th = list(get(t, 'hosts')).map(str);
567
+ know('Uses HTTPS for', `${th.length ? listWords(th) : 'its addresses'}${sn ? `, with the certificate in the Secret ${sn}` : ''}`, t.line);
568
+ if (sn) link(address, addr('Secret', sn), 'reads-from', t.line);
569
+ }
570
+ fact('public-ingress', `${where} lets requests from outside the cluster reach ${hosts.length ? listWords([...new Set(hosts)]) : 'its paths'} (wherever its ingress controller listens).`, lineOf(spec, 'rules', line));
571
+ }
572
+
573
+ // ── RBAC ──────────────────────────────────────────────────────────────────────────────────────────────────
574
+
575
+ function readRole({ kind, name, n, ns, know, permissions, file }) {
576
+ const scope = kind === 'ClusterRole' ? 'wherever it is given (one namespace, or the whole cluster)' : `in the namespace ${ns ?? 'it is made in'}`;
577
+ const who = `whoever is given the ${kindWords(kind)} ${name}`;
578
+ for (const rule of list(get(n, 'rules'))) {
579
+ const verbs = list(get(rule, 'verbs')).map(str);
580
+ const res = list(get(rule, 'resources')).map(str);
581
+ const groups = list(get(rule, 'apiGroups')).map(str);
582
+ const names = list(get(rule, 'resourceNames')).map(str);
583
+ const urls = list(get(rule, 'nonResourceURLs')).map(str);
584
+ const on = urls.length ? `the addresses ${listWords(urls)}` : res.includes('*') ? `every kind of resource${groups.includes('*') ? '' : groups.length && groups.some((g) => g) ? ` in ${listWords(groups.filter(Boolean))}` : ''}` : `${names.length ? `the ${listWords(res)} named ${listWords(names)}` : listWords(res)}`;
585
+ const can = verbsWords(verbs);
586
+ const wide = verbs.includes('*') || res.includes('*');
587
+ const touchesSecrets = res.includes('secrets') && verbs.some((v) => ['get', 'list', 'watch', '*'].includes(v));
588
+ know(cap(can), `${on}${urls.length ? '' : ` ${scope}`}`, rule.line);
589
+ permissions.push({
590
+ id: `${file}#permission#${rule.line}#${permissions.length}`, who, can, on: `${on}${urls.length ? '' : ` ${scope}`}`, wide, ...(wide ? { why: verbs.includes('*') && res.includes('*') && (groups.includes('*') || !groups.length) ? 'it can do anything to anything' : verbs.includes('*') ? `it can do anything to ${on}` : `it can ${can} every kind of resource` } : {}),
591
+ role: name, file, line: rule.line, says: `${cap(who)} can ${can} ${on}${urls.length ? '' : ` ${scope}`}${wide ? ' (wide)' : touchesSecrets ? ' (including Secret values)' : ''}`,
592
+ });
593
+ }
594
+ const agg = get(n, 'aggregationRule');
595
+ if (agg) know('Gathers', `the rules of every cluster role with ${listWords(list(get(agg, 'clusterRoleSelectors')).map((s) => selectorOf(s).says.replace(/^pods with /, '')))}`, lineOf(n, 'aggregationRule'));
596
+ }
597
+
598
+ function subjectWords(s) {
599
+ const k = str(get(s, 'kind')), n = str(get(s, 'name')), ns = str(get(s, 'namespace'));
600
+ if (k === 'Group' && n === 'system:unauthenticated') return 'anyone, even without signing in';
601
+ if (k === 'Group' && n === 'system:authenticated') return 'everyone who is signed in to the cluster';
602
+ if (k === 'User' && n === 'system:anonymous') return 'anyone, even without signing in';
603
+ if (k === 'Group' && n === 'system:serviceaccounts') return 'every service account in the cluster';
604
+ if (k === 'ServiceAccount') return `the service account ${ns ? `${ns}/` : ''}${n}`;
605
+ return `the ${String(k ?? 'subject').toLowerCase()} ${n}`;
606
+ }
607
+
608
+ function readBinding({ kind, name, n, ns, know, permissions, file, address, link, addr }) {
609
+ const ref = get(n, 'roleRef');
610
+ const rk = str(get(ref, 'kind')) ?? 'Role', rn = str(get(ref, 'name')) ?? '?';
611
+ const subs = list(get(n, 'subjects'));
612
+ const who = subs.length ? listWords(subs.map(subjectWords)) : 'no one (it has no subjects)';
613
+ const scope = kind === 'ClusterRoleBinding' ? 'in the whole cluster' : `in the namespace ${ns ?? 'it is made in'}`;
614
+ const builtin = rk === 'ClusterRole' ? BUILTIN_ROLES[rn] : null;
615
+ const can = builtin ?? `do what the ${kindWords(rk)} ${rn} allows`;
616
+ const anyone = subs.some((s) => /^system:(unauthenticated|anonymous|authenticated)$/.test(str(get(s, 'name')) ?? ''));
617
+ const wide = rn === 'cluster-admin' || (kind === 'ClusterRoleBinding' && (rn === 'admin' || rn === 'edit')) || (anyone && rn !== 'system:public-info-viewer' && rn !== 'system:discovery' && rn !== 'system:basic-user');
618
+ know('Gives', `${who} the ${kindWords(rk)} ${rn}`, lineOf(n, 'roleRef'));
619
+ know('Where', scope, lineOf(n, 'roleRef'));
620
+ permissions.push({
621
+ id: `${file}#permission#${lineOf(n, 'roleRef', n.line)}#${permissions.length}`, who, can, on: scope, wide, role: rn,
622
+ ...(wide ? { why: rn === 'cluster-admin' ? `cluster-admin lets ${anyone ? 'them' : 'it'} do anything in the whole cluster` : anyone ? `it gives ${rn} to ${who}` : `${rn} ${scope} lets it change almost everything` } : {}),
623
+ file, line: lineOf(n, 'roleRef', n.line), says: `${cap(who)} can ${can} ${scope}${wide ? ' (wide)' : ''}`,
624
+ });
625
+ link(address, addr(rk, rn), 'uses', lineOf(n, 'roleRef'));
626
+ for (const s of subs) if (str(get(s, 'kind')) === 'ServiceAccount') link(address, k8sAddress('ServiceAccount', str(get(s, 'name')), str(get(s, 'namespace')) ?? ns), 'uses', s.line);
627
+ }
628
+
629
+ // ── Network policies, in words ────────────────────────────────────────────────────────────────────────────
630
+
631
+ function peerWords(p) {
632
+ const parts = [];
633
+ const pod = get(p, 'podSelector'), nsSel = get(p, 'namespaceSelector'), ip = get(p, 'ipBlock');
634
+ if (ip) { const ex = list(get(ip, 'except')).map(str); parts.push(`${str(get(ip, 'cidr')) === '0.0.0.0/0' ? 'any address' : `addresses in ${str(get(ip, 'cidr'))}`}${ex.length ? ` except ${listWords(ex)}` : ''}`); }
635
+ if (pod || nsSel) {
636
+ const pw = pod ? selectorOf(pod).says : 'every pod';
637
+ const nw = nsSel ? (Object.keys(selectorOf(nsSel).labels).length ? `namespaces with ${selectorWords(selectorOf(nsSel).labels)}` : 'every namespace') : 'its own namespace';
638
+ parts.push(`${pw} in ${nw}`);
639
+ }
640
+ return parts.join(' and ') || 'anywhere';
641
+ }
642
+
643
+ function readNetworkPolicy({ spec, know }) {
644
+ know('Applies to', `${selectorOf(get(spec, 'podSelector')).says} in its namespace`, lineOf(spec, 'podSelector'));
645
+ const types = list(get(spec, 'policyTypes')).map(str);
646
+ const has = (k) => types.includes(k) || (!types.length && (k === 'Ingress' || get(spec, 'egress')));
647
+ for (const [key, type, label, dir] of [['ingress', 'Ingress', 'Lets in', 'from'], ['egress', 'Egress', 'Lets out', 'to']]) {
648
+ if (!has(type)) continue;
649
+ const rules = list(get(spec, key));
650
+ if (!rules.length) { know(label, `nothing: every ${key === 'ingress' ? 'incoming' : 'outgoing'} connection is blocked`, lineOf(spec, key, lineOf(spec, 'policyTypes'))); continue; }
651
+ for (const r of rules) {
652
+ const peers = list(get(r, dir));
653
+ const ports = list(get(r, 'ports')).map((p) => `${str(get(p, 'port')) ?? 'any port'}${/^udp$/i.test(str(get(p, 'protocol')) ?? '') ? ' (UDP)' : ''}`);
654
+ know(label, `${peers.length ? `${dir} ${listWords(peers.map(peerWords))}` : `${dir} anywhere`}${ports.length ? `, on port${ports.length === 1 ? '' : 's'} ${listWords(ports)}` : ''}`, r.line);
655
+ }
656
+ }
657
+ }