@intentius/chant-lexicon-k8s 0.124.52 → 0.124.55

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.
@@ -0,0 +1,244 @@
1
+ /**
2
+ * #4538 on the k8s lexicon: `chant import --index` through the k8s seam,
3
+ * and the identity rule `chant search --index` and the identity edge pass
4
+ * join k8s rows with.
5
+ *
6
+ * The listing is the #4521 fixture (testdata/indexed/listing.json: a
7
+ * Deployment, a Secret, a Flux Kustomization, an unmapped custom resource)
8
+ * plus a ConfigMap whose `db.password` key the listing masks by name, a
9
+ * ReplicaSet the Deployment owns, and a ClusterRole. It is typed through the
10
+ * k8s hooks as `behold index` writes it, then imported through the seam and
11
+ * `K8sGenerator`, the codegen `chant import <manifest>` uses.
12
+ *
13
+ * The cluster round trip (index a kind cluster, import, build, apply with
14
+ * markers, then search binds every row) is a maintainer run.
15
+ */
16
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import { describe, expect, test } from "vitest";
19
+ import { loadAll } from "js-yaml";
20
+ import { build } from "@intentius/chant/build";
21
+ import { MASKED } from "@intentius/chant/deep-observation";
22
+ import type { LexiconPlugin } from "@intentius/chant/lexicon";
23
+ import type { SerializerResult } from "@intentius/chant/serializer";
24
+ import { matchDeclaredToIndex } from "@intentius/chant/lifecycle/identity-match";
25
+ import { planIndexImport } from "@intentius/chant/lifecycle/index-import";
26
+ import { typeListing, type ListedResource, type ListingLexicon, type ListingResult } from "@intentius/chant/lifecycle/type-listing";
27
+ import { renderIndexImport } from "@intentius/chant/cli/commands/import-index";
28
+ import type { K8sOperationTable } from "./api/operation-surface";
29
+ import { createK8sIndexIdentity, k8sDeclaredIdentity, k8sNodeIdentities } from "./index-identity";
30
+ import { k8sImportProperties, maskedValueEnvVar } from "./index-import";
31
+ import { k8sKindForListedType } from "./listed-types";
32
+ import { k8sPlugin } from "./plugin";
33
+ import { k8sSerializer } from "./serializer";
34
+
35
+ const here = import.meta.dirname;
36
+ const surface = JSON.parse(readFileSync(join(here, "..", "surface.snapshot.json"), "utf-8")) as {
37
+ entries: Record<string, { kind: string; resourceType: string }>;
38
+ };
39
+ const KINDS: ReadonlySet<string> = new Set(Object.values(surface.entries).filter((e) => e.kind === "resource").map((e) => e.resourceType));
40
+
41
+ const TABLE: K8sOperationTable = {
42
+ "K8s::Apps::Deployment": { entityType: "K8s::Apps::Deployment", apiVersion: "apps/v1", kind: "Deployment", plural: "deployments", scope: "Namespaced", verbs: [] },
43
+ "K8s::Core::Secret": { entityType: "K8s::Core::Secret", apiVersion: "v1", kind: "Secret", plural: "secrets", scope: "Namespaced", verbs: [] },
44
+ "K8s::Core::ConfigMap": { entityType: "K8s::Core::ConfigMap", apiVersion: "v1", kind: "ConfigMap", plural: "configmaps", scope: "Namespaced", verbs: [] },
45
+ "K8s::Rbac::ClusterRole": { entityType: "K8s::Rbac::ClusterRole", apiVersion: "rbac.authorization.k8s.io/v1", kind: "ClusterRole", plural: "clusterroles", scope: "Cluster", verbs: [] },
46
+ };
47
+
48
+ const k8sListing: ListingLexicon = {
49
+ name: k8sPlugin.name,
50
+ deepNormalizationHooks: k8sPlugin.deepNormalizationHooks,
51
+ listedTypes: { ...k8sPlugin.listedTypes!, kindFor: (t) => k8sKindForListedType(t, KINDS) },
52
+ };
53
+
54
+ function obj(listedType: string, location: string, name: string, uid: string, properties: Record<string, unknown>): ListedResource {
55
+ return {
56
+ listedType,
57
+ location,
58
+ nativeId: location === "cluster" ? name : `${location}/${name}`,
59
+ cloudIds: [{ kind: "k8s-uid", value: uid }],
60
+ tags: {},
61
+ properties,
62
+ observedAt: "2026-10-26T09:00:01.000Z",
63
+ };
64
+ }
65
+
66
+ const base = JSON.parse(readFileSync(join(here, "testdata", "indexed", "listing.json"), "utf-8")) as ListingResult;
67
+ const listing: ListingResult = {
68
+ ...base,
69
+ resources: [
70
+ ...base.resources,
71
+ obj("v1/ConfigMap", "shop", "app", "uid-cm", {
72
+ apiVersion: "v1",
73
+ kind: "ConfigMap",
74
+ metadata: { name: "app", namespace: "shop", uid: "uid-cm", resourceVersion: "9", annotations: { "kubectl.kubernetes.io/last-applied-configuration": "{}" } },
75
+ data: { "db.host": "db.shop.svc", "db.password": "hunter2" },
76
+ }),
77
+ obj("apps/v1/ReplicaSet", "shop", "web-5d8f", "uid-rs", {
78
+ apiVersion: "apps/v1",
79
+ kind: "ReplicaSet",
80
+ metadata: { name: "web-5d8f", namespace: "shop", ownerReferences: [{ apiVersion: "apps/v1", kind: "Deployment", name: "web", uid: "5f1c2a8e-0000-4000-8000-000000000001" }] },
81
+ spec: { replicas: 2 },
82
+ }),
83
+ obj("rbac.authorization.k8s.io/v1/ClusterRole", "cluster", "reader", "uid-cr", {
84
+ apiVersion: "rbac.authorization.k8s.io/v1",
85
+ kind: "ClusterRole",
86
+ metadata: { name: "reader" },
87
+ rules: [{ apiGroups: [""], resources: ["pods"], verbs: ["get", "list"] }],
88
+ }),
89
+ ],
90
+ };
91
+ const doc = typeListing(listing, [k8sListing]);
92
+ const node = (nativeId: string) => doc.graph.nodes.find((n) => n.nativeId === nativeId)!;
93
+
94
+ const identity = createK8sIndexIdentity(TABLE);
95
+ const plugin = k8sPlugin as LexiconPlugin;
96
+
97
+ function primary(out: string | SerializerResult | undefined): string {
98
+ if (out === undefined) return "";
99
+ return typeof out === "string" ? out : out.primary;
100
+ }
101
+
102
+ describe("the k8s identity rule", () => {
103
+ test("a namespaced object is <namespace>/<name> at its namespace, matched by kind", () => {
104
+ expect(k8sDeclaredIdentity("K8s::Apps::Deployment", { metadata: { name: "web", namespace: "shop" } }, TABLE)).toEqual({
105
+ kind: "identifier",
106
+ listedType: "apps/v1/Deployment",
107
+ identifier: "shop/web",
108
+ global: false,
109
+ location: "shop",
110
+ entityKind: "K8s::Apps::Deployment",
111
+ });
112
+ });
113
+
114
+ test("a cluster-scoped object is its name at location cluster", () => {
115
+ expect(k8sDeclaredIdentity("K8s::Rbac::ClusterRole", { metadata: { name: "reader" } }, TABLE)).toMatchObject({
116
+ kind: "identifier",
117
+ identifier: "reader",
118
+ location: "cluster",
119
+ listedType: "rbac.authorization.k8s.io/v1/ClusterRole",
120
+ });
121
+ });
122
+
123
+ test("a declared apiVersion is the listed type's version", () => {
124
+ expect(k8sDeclaredIdentity("K8s::Apps::Deployment", { apiVersion: "apps/v1beta2", metadata: { name: "web", namespace: "shop" } }, TABLE)).toMatchObject({
125
+ listedType: "apps/v1beta2/Deployment",
126
+ });
127
+ });
128
+
129
+ test("no name, a generated name, or no namespace cannot match; an unknown kind is unsupported", () => {
130
+ expect(k8sDeclaredIdentity("K8s::Apps::Deployment", { metadata: { namespace: "shop" } }, TABLE)).toMatchObject({ kind: "unmatchable", reason: "no-binding" });
131
+ expect(k8sDeclaredIdentity("K8s::Apps::Deployment", { metadata: { generateName: "web-", namespace: "shop" } }, TABLE)).toMatchObject({
132
+ kind: "unmatchable",
133
+ reason: "no-binding",
134
+ detail: expect.stringMatching(/generateName/),
135
+ });
136
+ expect(k8sDeclaredIdentity("K8s::Apps::Deployment", { metadata: { name: "web" } }, TABLE)).toMatchObject({
137
+ kind: "unmatchable",
138
+ reason: "no-binding",
139
+ detail: expect.stringMatching(/namespace/),
140
+ });
141
+ expect(k8sDeclaredIdentity("K8s::Sops::EncryptedSecretFile", { metadata: { name: "x" } }, TABLE)).toMatchObject({ kind: "unmatchable", reason: "unsupported-kind" });
142
+ });
143
+
144
+ test("an indexed object is named by its native id and its uid", () => {
145
+ expect(k8sNodeIdentities(node("shop/web"))).toEqual([
146
+ { kind: "native-id", value: "shop/web" },
147
+ { kind: "k8s-uid", value: "5f1c2a8e-0000-4000-8000-000000000001" },
148
+ ]);
149
+ });
150
+
151
+ test("declared rows bind, read absent, or read not observed against the index", () => {
152
+ const { matches } = matchDeclaredToIndex(
153
+ [
154
+ { name: "web", entityType: "K8s::Apps::Deployment", props: { metadata: { name: "web", namespace: "shop" } } },
155
+ // Another version of the same kind binds: the match is by kind.
156
+ { name: "webOld", entityType: "K8s::Apps::Deployment", props: { apiVersion: "apps/v1beta2", metadata: { name: "web", namespace: "shop" } } },
157
+ { name: "reader", entityType: "K8s::Rbac::ClusterRole", props: { metadata: { name: "reader" } } },
158
+ { name: "api", entityType: "K8s::Apps::Deployment", props: { metadata: { name: "api", namespace: "shop" } } },
159
+ { name: "loose", entityType: "K8s::Apps::Deployment", props: { metadata: { name: "loose" } } },
160
+ ],
161
+ [doc],
162
+ identity,
163
+ );
164
+ expect(matches.web).toMatchObject({ verdict: "bound", node: node("shop/web").id, location: "shop" });
165
+ expect(matches.webOld).toMatchObject({ verdict: "bound", node: node("shop/web").id });
166
+ expect(matches.reader).toMatchObject({ verdict: "bound", node: node("reader").id, location: "cluster" });
167
+ expect(matches.api).toMatchObject({ verdict: "absent", identifier: "shop/api", location: "shop" });
168
+ expect(matches.loose).toMatchObject({ verdict: "not-observed", reason: "no-binding" });
169
+ });
170
+
171
+ test("the plugin declares the identity rule", () => {
172
+ expect(k8sPlugin.indexIdentity?.substrate).toBe("kubernetes");
173
+ });
174
+ });
175
+
176
+ describe("chant import --index on the k8s fixture", () => {
177
+ const plan = planIndexImport([doc], { all: true }, [k8sPlugin]);
178
+ const report = new Map(plan.report.resources.map((r) => [r.identity.nativeId, r]));
179
+
180
+ test("server-written fields and chant's own labels are left out; apiVersion only when the version differs", () => {
181
+ const props = k8sImportProperties(node("shop/web"));
182
+ expect(props).toEqual({ metadata: { labels: { app: "web" }, name: "web", namespace: "shop" }, spec: { replicas: 2, selector: { matchLabels: { app: "web" } } } });
183
+ expect(k8sImportProperties({ ...node("shop/web"), listedType: "apps/v1beta2/Deployment" }).apiVersion).toBe("apps/v1beta2");
184
+ });
185
+
186
+ test("an owned object, and a kind with no lexicon mapping, are refused by name", () => {
187
+ expect(report.get("shop/web-5d8f")).toMatchObject({ status: "unsupported", reason: expect.stringMatching(/owned by Deployment\/web/) });
188
+ expect(report.get("shop/w1")).toMatchObject({ status: "unsupported", reason: expect.stringMatching(/no lexicon kind maps/) });
189
+ });
190
+
191
+ test("a masked Secret is a referenced secret; another masked value is a parameter read from the environment", () => {
192
+ expect(report.get("shop/db-credentials")).toMatchObject({ status: "imported" });
193
+ expect(report.get("shop/db-credentials")!.parameters).toBeUndefined();
194
+ const cm = report.get("shop/app")!;
195
+ expect(cm.status).toBe("imported");
196
+ expect(cm.parameters).toHaveLength(1);
197
+ expect(plan.report.parameters).toEqual([{ name: cm.parameters![0], node: cm.node, path: "data.db.password", group: expect.any(String) }]);
198
+ expect(node("shop/app").attrs.data).toEqual({ "db.host": "db.shop.svc", "db.password": MASKED });
199
+ });
200
+
201
+ test("round trip: import, build, and every imported object comes back with its indexed fields", async () => {
202
+ const { files, warnings } = renderIndexImport(plan, [plugin]);
203
+ expect(warnings).toEqual([]);
204
+ const all = files.map((f) => f.content).join("\n");
205
+ expect(all).toContain('import { declareSecret } from "@intentius/chant";');
206
+ expect(all).toMatch(/declareSecret\(\{\s+name: "db-credentials",\s+provenance: "referenced",\s+scope: "shop",\s+\}\)/);
207
+ expect(all).toContain("keys app.conf");
208
+ expect(all).not.toContain(MASKED);
209
+ expect(all).not.toContain("hunter2");
210
+ expect(all).not.toContain("5f1c2a8e");
211
+
212
+ const cm = report.get("shop/app")!;
213
+ const envVar = maskedValueEnvVar(cm.parameters![0]);
214
+ expect(all).toContain(`maskedValue("${envVar}")`);
215
+
216
+ const dir = mkdtempSync(join(here, "../.index-import-tmp-"));
217
+ const saved = process.env[envVar];
218
+ process.env[envVar] = "from-env";
219
+ try {
220
+ const src = join(dir, "src");
221
+ for (const f of files) {
222
+ mkdirSync(join(src, f.path, ".."), { recursive: true });
223
+ writeFileSync(join(src, f.path), f.content);
224
+ }
225
+ const result = await build(src, [k8sSerializer]);
226
+ expect(result.errors.map((e) => e.message)).toEqual([]);
227
+ const docs = (loadAll(primary(result.outputs.get("k8s"))) as Array<Record<string, any>>).filter((d) => d);
228
+ const byKind = new Map(docs.map((d) => [`${d.kind}/${d.metadata?.name}`, d]));
229
+ expect(byKind.get("Deployment/web")).toMatchObject({ apiVersion: "apps/v1", metadata: { name: "web", namespace: "shop" }, spec: { replicas: 2 } });
230
+ expect(byKind.get("ConfigMap/app")).toMatchObject({ data: { "db.host": "db.shop.svc", "db.password": "from-env" } });
231
+ expect(byKind.get("ClusterRole/reader")).toMatchObject({ rules: [{ verbs: ["get", "list"] }] });
232
+ // The Secret is supplied out of band; nothing writes it.
233
+ expect(byKind.has("Secret/db-credentials")).toBe(false);
234
+ } finally {
235
+ if (saved === undefined) delete process.env[envVar];
236
+ else process.env[envVar] = saved;
237
+ rmSync(dir, { recursive: true, force: true });
238
+ }
239
+ });
240
+
241
+ test("the plugin declares the seam", () => {
242
+ expect(k8sPlugin.indexImport).toBeDefined();
243
+ });
244
+ });
@@ -0,0 +1,181 @@
1
+ /**
2
+ * The k8s lexicon's index import seam (#4538, on #4524's
3
+ * `chant import --index`).
4
+ *
5
+ * An indexed k8s object's `attrs` are its manifest without `apiVersion` and
6
+ * `kind` (./listed-types.ts), normalized by this lexicon's deep hooks, so
7
+ * the import IR is what the YAML parser (./import/parser.ts) writes for the
8
+ * same object and `K8sGenerator` turns it into source.
9
+ *
10
+ * What is left out of the properties:
11
+ * - what the deep hooks prune from a live object nobody declared: the
12
+ * envelope (`status`, `metadata.uid`, `resourceVersion`, ...), the
13
+ * controllers' bookkeeping labels and annotations, chant's own ownership
14
+ * labels (the serializer writes them again), server-assigned fields
15
+ * (`spec.clusterIP`) and values equal to the API server's defaults;
16
+ * - `metadata.deletionTimestamp` and `metadata.deletionGracePeriodSeconds`.
17
+ *
18
+ * `apiVersion` is kept only when the listed version is not the one the
19
+ * lexicon writes for the kind, as the YAML parser keeps an aliased one.
20
+ *
21
+ * Refused, by name:
22
+ * - an object with `metadata.ownerReferences`: its controller makes it
23
+ * (a Deployment's ReplicaSets and Pods), so the owner is what to import;
24
+ * - an `Event`, and a Secret of type `kubernetes.io/service-account-token`,
25
+ * which the cluster writes.
26
+ *
27
+ * References stay literals. A k8s object names another by its name, and
28
+ * that literal is how the lexicon spells it.
29
+ *
30
+ * Masked values. k8s has no template parameters, so a masked value takes
31
+ * one of two k8s forms:
32
+ * - a Secret whose `data` or `stringData` the index masked (all of it is:
33
+ * the k8s mask hook masks every value of a Secret) is written as a
34
+ * referenced secret, `declareSecret({ name, provenance: "referenced",
35
+ * scope: <namespace> })`. The Secret object stays in the cluster and the
36
+ * user supplies it out of band (kubectl, sops through a
37
+ * `committed-encrypted` declaration, an external secrets operator). Its
38
+ * key names and type go into the header comment. Nothing value-shaped is
39
+ * written;
40
+ * - any other masked value (a key-name match such as a ConfigMap's
41
+ * `db.password`, or a container's `secretKeyRef`) reads an environment
42
+ * variable at build time: `maskedValue("<ENV_VAR>")` in the generated
43
+ * file, which throws when the variable is unset. The variable is the
44
+ * parameter's name in upper snake case (`CONFIG_MAP_APP_DATA_DB_PASSWORD`). A value that starts with `{` or
45
+ * `[` is parsed as JSON, for an object the index masked whole.
46
+ */
47
+ import { MASKED } from "@intentius/chant/deep-observation";
48
+ import type { IRNode } from "@intentius/chant/graph-ir";
49
+ import type { IndexImportCodegen } from "@intentius/chant/lifecycle/index-import";
50
+ import type { ParameterIR } from "@intentius/chant/import/parser";
51
+ import { SECRET_DECLARATION_ENTITY_TYPE } from "@intentius/chant/secret-provenance";
52
+ import { k8sDeepNormalizationHooks } from "./deep-observe-hooks";
53
+ import { operationFor } from "./api/operation-surface";
54
+ import { parseListedGvk } from "./listed-types";
55
+
56
+ /** A property value standing for a masked one: the generator writes `maskedValue("<ENV_VAR>")`. */
57
+ export interface K8sMaskedValueRef {
58
+ /** The environment variable the value is read from. */
59
+ __k8sMaskedValue: string;
60
+ }
61
+
62
+ export function isMaskedValueRef(v: unknown): v is K8sMaskedValueRef {
63
+ return typeof v === "object" && v !== null && typeof (v as Record<string, unknown>).__k8sMaskedValue === "string";
64
+ }
65
+
66
+ const SECRET_KIND = "K8s::Core::Secret";
67
+ const CLUSTER_WRITTEN_KINDS: ReadonlySet<string> = new Set(["K8s::Core::Event", "K8s::Events::Event"]);
68
+ const CLUSTER_WRITTEN_SECRET_TYPES: ReadonlySet<string> = new Set(["kubernetes.io/service-account-token"]);
69
+ const DROPPED_METADATA = new Set(["deletionTimestamp", "deletionGracePeriodSeconds"]);
70
+
71
+ function isRecord(v: unknown): v is Record<string, unknown> {
72
+ return typeof v === "object" && v !== null && !Array.isArray(v);
73
+ }
74
+
75
+ function containsMasked(v: unknown): boolean {
76
+ if (v === MASKED) return true;
77
+ if (Array.isArray(v)) return v.some(containsMasked);
78
+ if (isRecord(v)) return Object.values(v).some(containsMasked);
79
+ return false;
80
+ }
81
+
82
+ /** `tree` without what the deep hooks prune from an undeclared live object. */
83
+ function pruneLive(entityType: string, tree: unknown, path: string, pattern: string): unknown {
84
+ if (Array.isArray(tree)) return tree.map((v, i) => pruneLive(entityType, v, `${path}[${i}]`, `${pattern}[]`));
85
+ if (!isRecord(tree)) return tree;
86
+ const out: Record<string, unknown> = {};
87
+ for (const key of Object.keys(tree).sort()) {
88
+ const value = tree[key];
89
+ const p = path === "" ? key : `${path}.${key}`;
90
+ const pat = pattern === "" ? key : `${pattern}.${key}`;
91
+ if (k8sDeepNormalizationHooks.prune?.({ entityType, path: p, pattern: pat, key, value, side: "live", counterpart: "absent" })) continue;
92
+ out[key] = pruneLive(entityType, value, p, pat);
93
+ }
94
+ return out;
95
+ }
96
+
97
+ /** The properties a declaration of the node's kind can hold. */
98
+ export function k8sImportProperties(node: IRNode): Record<string, unknown> {
99
+ const props = pruneLive(node.kind, node.attrs ?? {}, "", "") as Record<string, unknown>;
100
+ if (isRecord(props.metadata)) {
101
+ const metadata = Object.fromEntries(Object.entries(props.metadata).filter(([k]) => !DROPPED_METADATA.has(k)));
102
+ for (const k of ["labels", "annotations"]) {
103
+ if (isRecord(metadata[k]) && Object.keys(metadata[k] as object).length === 0) delete metadata[k];
104
+ }
105
+ props.metadata = metadata;
106
+ }
107
+ const gvk = node.listedType ? parseListedGvk(node.listedType) : undefined;
108
+ if (gvk) {
109
+ const listedApiVersion = gvk.group ? `${gvk.group}/${gvk.version}` : gvk.version;
110
+ if (operationFor(node.kind)?.apiVersion !== listedApiVersion) return { apiVersion: listedApiVersion, ...props };
111
+ }
112
+ return props;
113
+ }
114
+
115
+ /** The referenced-secret declaration for a Secret whose data the index masked, and the note naming what it held. */
116
+ export function k8sReferencedSecret(node: IRNode): { properties: Record<string, unknown>; note: string } {
117
+ const attrs = node.attrs ?? {};
118
+ const metadata = isRecord(attrs.metadata) ? attrs.metadata : {};
119
+ const name = typeof metadata.name === "string" ? metadata.name : (node.nativeId ?? node.id).split("/").pop()!;
120
+ const namespace = typeof metadata.namespace === "string" ? metadata.namespace : undefined;
121
+ const keys = [
122
+ ...new Set(["data", "stringData"].flatMap((f) => (isRecord(attrs[f]) ? Object.keys(attrs[f] as object) : []))),
123
+ ].sort();
124
+ const type = typeof attrs.type === "string" ? attrs.type : "Opaque";
125
+ return {
126
+ properties: { name, provenance: "referenced", ...(namespace ? { scope: namespace } : {}) },
127
+ note:
128
+ `the Secret ${namespace ? `${namespace}/` : ""}${name} (type ${type}, keys ${keys.join(", ") || "none"}) was masked in the index, ` +
129
+ `so it is declared as a referenced secret: supply it out of band`,
130
+ };
131
+ }
132
+
133
+ /** The environment variable a masked value is read from: the parameter name in upper snake case. */
134
+ export function maskedValueEnvVar(name: string): string {
135
+ return name
136
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
137
+ .replace(/[^A-Za-z0-9]+/g, "_")
138
+ .toUpperCase();
139
+ }
140
+
141
+ export function createK8sIndexImport(): IndexImportCodegen {
142
+ return {
143
+ resource(node: IRNode) {
144
+ if (!node.kind.startsWith("K8s::") || node.kind.split("::").length !== 3) {
145
+ return { unsupported: `${node.kind} is not a Kubernetes kind of the k8s lexicon` };
146
+ }
147
+ if (CLUSTER_WRITTEN_KINDS.has(node.kind)) return { unsupported: `${node.kind} objects are written by the cluster` };
148
+ const attrs = node.attrs ?? {};
149
+ const metadata = isRecord(attrs.metadata) ? attrs.metadata : {};
150
+ const owners = Array.isArray(metadata.ownerReferences) ? metadata.ownerReferences.filter(isRecord) : [];
151
+ if (owners.length > 0) {
152
+ const named = owners.map((o) => `${String(o.kind ?? "?")}/${String(o.name ?? "?")}`).join(", ");
153
+ return { unsupported: `owned by ${named} (metadata.ownerReferences): its controller makes this object, so import the owner` };
154
+ }
155
+ if (node.kind === SECRET_KIND) {
156
+ if (typeof attrs.type === "string" && CLUSTER_WRITTEN_SECRET_TYPES.has(attrs.type)) {
157
+ return { unsupported: `a Secret of type ${attrs.type} is written by the cluster` };
158
+ }
159
+ if (containsMasked(attrs.data) || containsMasked(attrs.stringData)) {
160
+ const { properties, note } = k8sReferencedSecret(node);
161
+ return { type: SECRET_DECLARATION_ENTITY_TYPE, properties, notes: [note] };
162
+ }
163
+ }
164
+ return { type: node.kind, properties: k8sImportProperties(node) };
165
+ },
166
+ // A k8s object names another by name; the literal is the lexicon's spelling.
167
+ reference: () => undefined,
168
+ secretParameter(name, context): ParameterIR {
169
+ return {
170
+ name,
171
+ type: "String",
172
+ description: `${context.path} of ${context.node.id}, masked in the index; set ${maskedValueEnvVar(name)} before building`,
173
+ required: true,
174
+ };
175
+ },
176
+ parameterReference: (name): K8sMaskedValueRef => ({ __k8sMaskedValue: maskedValueEnvVar(name) }),
177
+ typeLabel: (node) => node.kind.split("::").pop() ?? "Resource",
178
+ };
179
+ }
180
+
181
+ export const k8sIndexImport: IndexImportCodegen = createK8sIndexImport();
@@ -0,0 +1,76 @@
1
+ /**
2
+ * #4521 on the k8s lexicon: discovery's group/version/kind mapped to kinds,
3
+ * and a fixture listing typed into nodes through the k8s hooks.
4
+ */
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { describe, expect, it } from "vitest";
8
+ import { typeListing, type ListingLexicon, type ListingResult } from "@intentius/chant/lifecycle/type-listing";
9
+ import { MASKED } from "@intentius/chant/deep-observation";
10
+ import { operationTable } from "./api/operation-surface";
11
+ import { k8sKindForListedType, k8sListedTypeFor } from "./listed-types";
12
+ import { k8sPlugin } from "./plugin";
13
+
14
+ const here = import.meta.dirname;
15
+ const surface = JSON.parse(readFileSync(join(here, "..", "surface.snapshot.json"), "utf-8")) as {
16
+ entries: Record<string, { kind: string; resourceType: string }>;
17
+ };
18
+ const KINDS: ReadonlySet<string> = new Set(
19
+ Object.values(surface.entries).filter((e) => e.kind === "resource").map((e) => e.resourceType),
20
+ );
21
+ const listing = JSON.parse(readFileSync(join(here, "testdata", "indexed", "listing.json"), "utf-8")) as ListingResult;
22
+ const hasGenerated = existsSync(join(here, "generated", "operations.json"));
23
+
24
+ const k8s: ListingLexicon = {
25
+ name: k8sPlugin.name,
26
+ deepNormalizationHooks: k8sPlugin.deepNormalizationHooks,
27
+ listedTypes: { ...k8sPlugin.listedTypes!, kindFor: (t) => k8sKindForListedType(t, KINDS) },
28
+ };
29
+
30
+ describe("discovery types to k8s kinds", () => {
31
+ it("maps group/version/kind through the shared group rule; the version is not part of the kind", () => {
32
+ expect(k8sKindForListedType("v1/Pod", KINDS)).toBe("K8s::Core::Pod");
33
+ expect(k8sKindForListedType("apps/v1/Deployment", KINDS)).toBe("K8s::Apps::Deployment");
34
+ expect(k8sKindForListedType("apps/v1beta2/Deployment", KINDS)).toBe("K8s::Apps::Deployment");
35
+ expect(k8sKindForListedType("networking.k8s.io/v1/Ingress", KINDS)).toBe("K8s::Networking::Ingress");
36
+ expect(k8sKindForListedType("rbac.authorization.k8s.io/v1/ClusterRole", KINDS)).toBe("K8s::Rbac::ClusterRole");
37
+ expect(k8sKindForListedType("kustomize.toolkit.fluxcd.io/v1/Kustomization", KINDS)).toBe("K8s::Flux::Kustomization");
38
+ expect(k8sKindForListedType("argoproj.io/v1alpha1/Application", KINDS)).toBe("K8s::Argo::Application");
39
+ expect(k8sKindForListedType("widgets.example.com/v1alpha1/Widget", KINDS)).toBeUndefined();
40
+ expect(k8sKindForListedType("Deployment", KINDS)).toBeUndefined();
41
+ });
42
+
43
+ it.skipIf(!hasGenerated)("every kind of the generated operation surface maps back from its apiVersion and kind", () => {
44
+ const table = operationTable();
45
+ const kinds = new Set(Object.keys(table));
46
+ const missing = Object.values(table).filter((d) => k8sKindForListedType(k8sListedTypeFor(d.apiVersion, d.kind), kinds) !== d.entityType);
47
+ expect(missing.map((d) => d.entityType)).toEqual([]);
48
+ });
49
+ });
50
+
51
+ describe("the k8s fixture listing as typed nodes", () => {
52
+ const doc = typeListing(listing, [k8s]);
53
+
54
+ it("produces typed nodes, and keeps the unmapped custom resource as an unknown-kind node", () => {
55
+ expect(doc.graph.nodes.map((n) => [n.nativeId, n.kind, n.lexicon, n.unmappedKind ?? false])).toEqual([
56
+ ["flux-system/apps", "K8s::Flux::Kustomization", "k8s", false],
57
+ ["shop/web", "K8s::Apps::Deployment", "k8s", false],
58
+ ["shop/db-credentials", "K8s::Core::Secret", "k8s", false],
59
+ ["shop/w1", "widgets.example.com/v1alpha1/Widget", "kubernetes", true],
60
+ ]);
61
+ });
62
+
63
+ it("drops apiVersion and kind, and prunes what the k8s hooks prune", () => {
64
+ const web = doc.graph.nodes.find((n) => n.nativeId === "shop/web")!;
65
+ expect(web.attrs.apiVersion).toBeUndefined();
66
+ expect(web.attrs.kind).toBeUndefined();
67
+ expect(web.attrs.status).toBeUndefined();
68
+ expect((web.attrs.metadata as Record<string, unknown>).uid).toBeUndefined();
69
+ expect(web.attrs.spec).toEqual({ replicas: 2, selector: { matchLabels: { app: "web" } } });
70
+ });
71
+
72
+ it("masks a Secret's data whatever its keys are called", () => {
73
+ const secret = doc.graph.nodes.find((n) => n.kind === "K8s::Core::Secret")!;
74
+ expect(secret.attrs.data).toEqual({ "app.conf": MASKED });
75
+ });
76
+ });
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Kubernetes discovery's type names as k8s lexicon kinds (#4521).
3
+ *
4
+ * behold#1029 lists a cluster through API discovery and LIST, and names each
5
+ * object's type by group, version and kind: `apps/v1/Deployment`, or
6
+ * `v1/Pod` for the core group. The lexicon's kinds are
7
+ * `K8s::<Group>::<Kind>`, the group's segment from the one rule every other
8
+ * path uses (./group-namespace.ts, as `gvkToTypeName` applies it). The
9
+ * version is not part of the kind.
10
+ *
11
+ * A listed object is the whole manifest. The deep reader compares it without
12
+ * `apiVersion` and `kind`, so those two are dropped before the hooks run.
13
+ */
14
+ import type { ListedTypeMapping } from "@intentius/chant/lifecycle/type-listing";
15
+ import { operationTable } from "./api/operation-surface";
16
+ import { namespaceSegmentForGroup } from "./group-namespace";
17
+
18
+ /** `apps/v1/Deployment` or `v1/Pod` as its group, version and kind. */
19
+ export function parseListedGvk(listedType: string): { group: string; version: string; kind: string } | undefined {
20
+ const parts = listedType.split("/");
21
+ if (parts.length === 2 && parts[0] && parts[1]) return { group: "", version: parts[0], kind: parts[1] };
22
+ if (parts.length === 3 && parts[0] && parts[1] && parts[2]) return { group: parts[0], version: parts[1], kind: parts[2] };
23
+ return undefined;
24
+ }
25
+
26
+ /** `apiVersion` (`apps/v1`, `v1`) and kind as the listed type behold's lister writes. */
27
+ export function k8sListedTypeFor(apiVersion: string, kind: string): string {
28
+ return `${apiVersion}/${kind}`;
29
+ }
30
+
31
+ /** The kind the group rule gives, before any check that the lexicon has it. */
32
+ export function k8sKindByRule(listedType: string): string | undefined {
33
+ const gvk = parseListedGvk(listedType);
34
+ if (!gvk) return undefined;
35
+ return `K8s::${namespaceSegmentForGroup(gvk.group)}::${gvk.kind}`;
36
+ }
37
+
38
+ let cachedKinds: ReadonlySet<string> | null | undefined;
39
+
40
+ /** The entity types of the generated operation surface, or null in a checkout that has not generated. */
41
+ function generatedKinds(): ReadonlySet<string> | null {
42
+ if (cachedKinds !== undefined) return cachedKinds;
43
+ const table = operationTable();
44
+ cachedKinds = Object.keys(table).length > 0 ? new Set(Object.keys(table)) : null;
45
+ return cachedKinds;
46
+ }
47
+
48
+ /**
49
+ * The k8s kind for a discovery type, or undefined. The rule's answer must be
50
+ * a kind the lexicon generated; with nothing generated the rule's answer
51
+ * stands, as the lexicon's own discovery sweep does.
52
+ */
53
+ export function k8sKindForListedType(listedType: string, kinds: ReadonlySet<string> | null = generatedKinds()): string | undefined {
54
+ const kind = k8sKindByRule(listedType);
55
+ if (kind === undefined) return undefined;
56
+ if (kinds && !kinds.has(kind)) return undefined;
57
+ return kind;
58
+ }
59
+
60
+ /** A listed object in the tree the deep reader compares. */
61
+ export function k8sObservedTree(properties: Record<string, unknown>): Record<string, unknown> {
62
+ const { apiVersion: _apiVersion, kind: _kind, ...rest } = properties;
63
+ return rest;
64
+ }
65
+
66
+ export const k8sListedTypes: ListedTypeMapping = {
67
+ substrate: "kubernetes",
68
+ kindFor: (listedType) => k8sKindForListedType(listedType),
69
+ observedTree: (properties) => k8sObservedTree(properties),
70
+ };
package/src/plugin.ts CHANGED
@@ -29,6 +29,10 @@ import { k8sHover } from "./lsp/hover";
29
29
  import { K8sParser } from "./import/parser";
30
30
  import { K8sGenerator } from "./import/generator";
31
31
  import { k8sDeepNormalizationHooks } from "./deep-observe-hooks";
32
+ import { k8sListedTypes } from "./listed-types";
33
+ import { k8sIndexIdentity } from "./index-identity";
34
+ import { k8sIndexImport } from "./index-import";
35
+ import { k8sReferenceCatalog } from "./reference-catalog";
32
36
  import { LABEL_OWNERSHIP_KEYS } from "@intentius/chant/ownership";
33
37
  import { k8sConfigSchema } from "./config-schema";
34
38
  import type { K8sChantConfig } from "./config";
@@ -805,4 +809,19 @@ const { deployment, service, serviceMonitor, prometheusRule } = MonitoredService
805
809
  },
806
810
 
807
811
  deepNormalizationHooks: k8sDeepNormalizationHooks,
812
+
813
+ // Cloud inventory type names to kinds, for an indexed resource (#4521).
814
+ listedTypes: k8sListedTypes,
815
+
816
+ // How its resources reference each other, for chant's catalog pass over an
817
+ // index and a declared graph (#4535; behold#1005 retires behold's matcher on it).
818
+ referenceCatalog: k8sReferenceCatalog,
819
+
820
+ // Declared objects matched to indexed ones by apiVersion/kind, namespace and
821
+ // name; the server-assigned uid names a node to the identity edge pass (#4538).
822
+ indexIdentity: k8sIndexIdentity,
823
+
824
+ // `chant import --index`: an indexed object as source; a masked Secret as a
825
+ // referenced secret, any other masked value read from the environment (#4538).
826
+ indexImport: k8sIndexImport,
808
827
  };