@intentius/chant-lexicon-k8s 0.124.54 → 0.124.56

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.
@@ -12,7 +12,14 @@ import type { TemplateIR } from "@intentius/chant/import/parser";
12
12
  export declare class K8sGenerator implements TypeScriptGenerator {
13
13
  /** The imports for embedded content the current `generate()` call references (#2962). */
14
14
  private scope;
15
+ /** Whether the current `generate()` call wrote a `maskedValue(...)` (chant import --index, #4538). */
16
+ private usesMaskedValue;
15
17
  generate(ir: TemplateIR): GeneratedFile[];
18
+ /**
19
+ * The helper a value masked in the index reads its environment variable
20
+ * through, with the parameters it stands for listed above it.
21
+ */
22
+ private maskedValueHelper;
16
23
  /**
17
24
  * Resolve a K8s type name to a constructor class name.
18
25
  * Falls back to extracting the last segment of the type.
@@ -1 +1 @@
1
- {"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../../src/import/generator.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAC5F,OAAO,KAAK,EAAE,UAAU,EAAc,MAAM,gCAAgC,CAAC;AAsH7E;;GAEG;AACH,qBAAa,YAAa,YAAW,mBAAmB;IACtD,yFAAyF;IACzF,OAAO,CAAC,KAAK,CAA+B;IAE5C,QAAQ,CAAC,EAAE,EAAE,UAAU,GAAG,aAAa,EAAE,CAsDxC;IAED;;;OAGG;IACH,OAAO,CAAC,YAAY;IAUpB,OAAO,CAAC,yBAAyB;IAmCjC,OAAO,CAAC,SAAS;IAejB,OAAO,CAAC,SAAS;IA0BjB,OAAO,CAAC,oBAAoB;IAuB5B,OAAO,CAAC,WAAW;CA6BpB"}
1
+ {"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../../src/import/generator.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAC5F,OAAO,KAAK,EAAE,UAAU,EAAc,MAAM,gCAAgC,CAAC;AAwH7E;;GAEG;AACH,qBAAa,YAAa,YAAW,mBAAmB;IACtD,yFAAyF;IACzF,OAAO,CAAC,KAAK,CAA+B;IAE5C,sGAAsG;IACtG,OAAO,CAAC,eAAe,CAAS;IAEhC,QAAQ,CAAC,EAAE,EAAE,UAAU,GAAG,aAAa,EAAE,CAqExC;IAED;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAYzB;;;OAGG;IACH,OAAO,CAAC,YAAY;IAUpB,OAAO,CAAC,yBAAyB;IAmCjC,OAAO,CAAC,SAAS;IAejB,OAAO,CAAC,SAAS;IA2BjB,OAAO,CAAC,oBAAoB;IAwB5B,OAAO,CAAC,WAAW;CAiCpB"}
@@ -5,6 +5,8 @@
5
5
  * source code using the @intentius/chant-lexicon-k8s constructors.
6
6
  */
7
7
  import { EmbeddedImportScope, isEmbeddedReference, renderEmbeddedReference, } from "@intentius/chant/import/embedded";
8
+ import { SECRET_DECLARATION_ENTITY_TYPE } from "@intentius/chant/secret-provenance";
9
+ import { isMaskedValueRef } from "../index-import.js";
8
10
  const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
9
11
  /** An object key as TypeScript: bare when it is an identifier, quoted otherwise (`"config.yaml"`, `"app.kubernetes.io/name"`). */
10
12
  function propertyKey(key) {
@@ -110,9 +112,13 @@ export class K8sGenerator {
110
112
  constructor() {
111
113
  /** The imports for embedded content the current `generate()` call references (#2962). */
112
114
  this.scope = new EmbeddedImportScope("");
115
+ /** Whether the current `generate()` call wrote a `maskedValue(...)` (chant import --index, #4538). */
116
+ this.usesMaskedValue = false;
113
117
  }
114
118
  generate(ir) {
115
119
  const lines = [];
120
+ this.usesMaskedValue = false;
121
+ let usesDeclareSecret = false;
116
122
  // Collect which constructors are needed
117
123
  const usedConstructors = new Set();
118
124
  for (const resource of ir.resources) {
@@ -137,6 +143,13 @@ export class K8sGenerator {
137
143
  }
138
144
  // Emit resources
139
145
  for (const resource of ir.resources) {
146
+ // A Secret `chant import --index` read masked: a referenced secret the user supplies (#4538).
147
+ if (resource.type === SECRET_DECLARATION_ENTITY_TYPE) {
148
+ usesDeclareSecret = true;
149
+ lines.push(`export const ${resource.logicalId} = declareSecret(${this.emitLiteral(resource.properties, 0, resource.type)});`);
150
+ lines.push("");
151
+ continue;
152
+ }
140
153
  const cls = this.resolveClass(resource.type);
141
154
  if (!cls) {
142
155
  lines.push(`// TODO: unsupported type ${resource.type} (${resource.logicalId})`);
@@ -156,9 +169,31 @@ export class K8sGenerator {
156
169
  for (const m of code.matchAll(/\bnew ([A-Z][A-Za-z0-9_]*)\(/g))
157
170
  usedConstructors.add(m[1]);
158
171
  const imports = [...usedConstructors].sort().join(", ");
159
- const head = [`import { ${imports} } from "@intentius/chant-lexicon-k8s";`, ...this.scope.lines(), ""];
172
+ const head = [
173
+ ...(usesDeclareSecret ? [`import { declareSecret } from "@intentius/chant";`] : []),
174
+ ...(imports ? [`import { ${imports} } from "@intentius/chant-lexicon-k8s";`] : []),
175
+ ...this.scope.lines(),
176
+ "",
177
+ ];
178
+ if (this.usesMaskedValue)
179
+ head.push(...this.maskedValueHelper(ir), "");
160
180
  return [{ path: "main.ts", content: [...head, ...lines].join("\n") }];
161
181
  }
182
+ /**
183
+ * The helper a value masked in the index reads its environment variable
184
+ * through, with the parameters it stands for listed above it.
185
+ */
186
+ maskedValueHelper(ir) {
187
+ return [
188
+ "// Values the index masked. Set each environment variable before building:",
189
+ ...ir.parameters.map((p) => `// ${p.name}: ${(p.description ?? "").replace(/\r?\n/g, " ")}`),
190
+ "function maskedValue(name: string): any {",
191
+ " const raw = process.env[name];",
192
+ " if (raw === undefined) throw new Error(`${name} is not set: the value was masked in the index`);",
193
+ " return /^\\s*[[{]/.test(raw) ? JSON.parse(raw) : raw;",
194
+ "}",
195
+ ];
196
+ }
162
197
  /**
163
198
  * Resolve a K8s type name to a constructor class name.
164
199
  * Falls back to extracting the last segment of the type.
@@ -174,7 +209,7 @@ export class K8sGenerator {
174
209
  }
175
210
  collectNestedConstructors(props, used, parentType) {
176
211
  for (const [key, value] of Object.entries(props)) {
177
- if (value === undefined || value === null)
212
+ if (value === undefined || value === null || isMaskedValueRef(value))
178
213
  continue;
179
214
  // Special case: "ports" on Service resources → ServicePort
180
215
  if (key === "ports" && SERVICE_PORT_TYPES.has(parentType)) {
@@ -220,6 +255,8 @@ export class K8sGenerator {
220
255
  return "undefined";
221
256
  if (isEmbeddedReference(value))
222
257
  return renderEmbeddedReference(value, this.scope, depth * 2);
258
+ if (isMaskedValueRef(value))
259
+ return this.emitLiteral(value, depth, parentType);
223
260
  // Special case: "ports" on Service → ServicePort constructor
224
261
  if (key === "ports" && SERVICE_PORT_TYPES.has(parentType) && Array.isArray(value)) {
225
262
  return this.emitConstructorArray("ServicePort", value, depth, parentType);
@@ -243,6 +280,8 @@ export class K8sGenerator {
243
280
  const indent = " ".repeat(depth);
244
281
  const innerIndent = " ".repeat(depth + 1);
245
282
  const emitted = items.map((item) => {
283
+ if (isMaskedValueRef(item))
284
+ return this.emitLiteral(item, depth + 1, parentType);
246
285
  if (typeof item === "object" && item !== null && !Array.isArray(item)) {
247
286
  const propsStr = this.emitProps(item, depth + 1, parentType);
248
287
  return `new ${constructor}(${propsStr})`;
@@ -259,6 +298,10 @@ export class K8sGenerator {
259
298
  return "undefined";
260
299
  if (isEmbeddedReference(value))
261
300
  return renderEmbeddedReference(value, this.scope, depth * 2);
301
+ if (isMaskedValueRef(value)) {
302
+ this.usesMaskedValue = true;
303
+ return `maskedValue(${JSON.stringify(value.__k8sMaskedValue)})`;
304
+ }
262
305
  if (typeof value === "string")
263
306
  return JSON.stringify(value);
264
307
  if (typeof value === "number" || typeof value === "boolean")
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The k8s lexicon's identity rule for indexed objects (#4538, on #4523's
3
+ * matcher, ../../../packages/core/src/lifecycle/identity-match.ts).
4
+ *
5
+ * core's Kubernetes lister (packages/core/src/cloud-lister/kubernetes.ts)
6
+ * writes each object as:
7
+ *
8
+ * - `listedType` `<apiVersion>/<kind>` (`apps/v1/Deployment`, `v1/Secret`);
9
+ * - `location` its namespace, or `cluster` for a cluster-scoped kind;
10
+ * - `nativeId` `<namespace>/<name>`, or `<name>` for a cluster-scoped kind;
11
+ * - one cloud id, `k8s-uid`, the object's `metadata.uid`.
12
+ *
13
+ * apiVersion, kind, namespace and name are all spelled by the user, so a
14
+ * declaration that was never applied still matches its object by value.
15
+ * The uid is assigned by the API server, so no declaration states it. It
16
+ * still names an indexed node to the identity edge pass, where another
17
+ * object's `ownerReferences[].uid` points at its owner.
18
+ *
19
+ * The match is by lexicon kind, not by listed type: discovery lists a
20
+ * group at its preferred version, which need not be the version the
21
+ * lexicon writes, and the kind is the same at any version. Coverage is
22
+ * still read for the declared listed type, so a version the index did not
23
+ * list reads not observed, never absent.
24
+ *
25
+ * What cannot match (`no-binding`):
26
+ * - a name the declaration leaves out, spells with a reference, or asks the
27
+ * API server to generate (`metadata.generateName`);
28
+ * - a namespaced kind with no `metadata.namespace`. The namespace kubectl
29
+ * or a GitOps controller would apply it to is not in the declaration.
30
+ *
31
+ * A type the lexicon has no API address for (`K8s::Sops::EncryptedSecretFile`,
32
+ * a kind outside the generated surface) is `unsupported-kind`.
33
+ */
34
+ import type { DeclaredIdentity, IndexIdentity } from "@intentius/chant/lifecycle/identity-match";
35
+ import type { NodeIdentityValue } from "@intentius/chant/graph-refs";
36
+ import type { IRNode } from "@intentius/chant/graph-ir";
37
+ import { type K8sOperationTable } from "./api/operation-surface.js";
38
+ /** The location core's Kubernetes lister gives a cluster-scoped object. */
39
+ export declare const K8S_CLUSTER_LOCATION = "cluster";
40
+ /** The cloud id kind holding an object's `metadata.uid`. */
41
+ export declare const K8S_UID_CLOUD_ID = "k8s-uid";
42
+ /**
43
+ * The identifier a k8s declaration spells for the index, or why it spells
44
+ * none. `table` is the generated operation surface; a test passes one.
45
+ */
46
+ export declare function k8sDeclaredIdentity(entityType: string, props: Record<string, unknown>, table?: K8sOperationTable): DeclaredIdentity;
47
+ /** The values that name an indexed k8s object: its `<namespace>/<name>` and its uid. */
48
+ export declare function k8sNodeIdentities(node: IRNode): NodeIdentityValue[];
49
+ export declare function createK8sIndexIdentity(table?: K8sOperationTable): IndexIdentity;
50
+ export declare const k8sIndexIdentity: IndexIdentity;
51
+ //# sourceMappingURL=index-identity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-identity.d.ts","sourceRoot":"","sources":["../src/index-identity.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,2CAA2C,CAAC;AACjG,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAA6D,KAAK,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAG5H,2EAA2E;AAC3E,eAAO,MAAM,oBAAoB,YAAY,CAAC;AAE9C,4DAA4D;AAC5D,eAAO,MAAM,gBAAgB,YAAY,CAAC;AAsB1C;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,CAAC,EAAE,iBAAiB,GAAG,gBAAgB,CA+BnI;AAED,wFAAwF;AACxF,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,iBAAiB,EAAE,CAKnE;AAED,wBAAgB,sBAAsB,CAAC,KAAK,CAAC,EAAE,iBAAiB,GAAG,aAAa,CAM/E;AAED,eAAO,MAAM,gBAAgB,EAAE,aAAwC,CAAC"}
@@ -0,0 +1,78 @@
1
+ import { operationFor, operationTable } from "./api/operation-surface.js";
2
+ import { k8sListedTypeFor } from "./listed-types.js";
3
+ /** The location core's Kubernetes lister gives a cluster-scoped object. */
4
+ export const K8S_CLUSTER_LOCATION = "cluster";
5
+ /** The cloud id kind holding an object's `metadata.uid`. */
6
+ export const K8S_UID_CLOUD_ID = "k8s-uid";
7
+ function isRecord(v) {
8
+ return typeof v === "object" && v !== null && !Array.isArray(v);
9
+ }
10
+ const nonEmptyString = (v) => typeof v === "string" && v !== "";
11
+ /**
12
+ * The descriptor for `entityType` and whether its scope is known: from the
13
+ * generated table when there is one, else derived (and the derived scope is
14
+ * a guess, so it is not trusted for a declaration without a namespace).
15
+ */
16
+ function addressOf(entityType, table) {
17
+ const t = table ?? operationTable();
18
+ if (t[entityType])
19
+ return { op: t[entityType], scopeKnown: true };
20
+ // Only the generated table knows CRDs and cluster-scoped kinds. A test table stands alone.
21
+ if (table)
22
+ return undefined;
23
+ const derived = operationFor(entityType);
24
+ return derived ? { op: derived, scopeKnown: false } : undefined;
25
+ }
26
+ /**
27
+ * The identifier a k8s declaration spells for the index, or why it spells
28
+ * none. `table` is the generated operation surface; a test passes one.
29
+ */
30
+ export function k8sDeclaredIdentity(entityType, props, table) {
31
+ const address = addressOf(entityType, table);
32
+ if (!address) {
33
+ return { kind: "unmatchable", reason: "unsupported-kind", detail: `${entityType} has no Kubernetes API address on record` };
34
+ }
35
+ const { op, scopeKnown } = address;
36
+ const metadata = isRecord(props.metadata) ? props.metadata : {};
37
+ if (!nonEmptyString(metadata.name)) {
38
+ const detail = nonEmptyString(metadata.generateName)
39
+ ? `the name of ${entityType} is generated by the API server (metadata.generateName), so no declaration states it`
40
+ : `identity is not in the declaration (${entityType} metadata.name)`;
41
+ return { kind: "unmatchable", reason: "no-binding", detail };
42
+ }
43
+ const name = metadata.name;
44
+ const apiVersion = nonEmptyString(props.apiVersion) ? props.apiVersion : op.apiVersion;
45
+ const listedType = k8sListedTypeFor(apiVersion, op.kind);
46
+ const namespace = nonEmptyString(metadata.namespace) ? metadata.namespace : undefined;
47
+ if (scopeKnown && op.scope === "Cluster") {
48
+ return { kind: "identifier", listedType, identifier: name, global: true, location: K8S_CLUSTER_LOCATION, entityKind: entityType };
49
+ }
50
+ if (!namespace) {
51
+ return {
52
+ kind: "unmatchable",
53
+ reason: "no-binding",
54
+ detail: scopeKnown
55
+ ? `identity is not in the declaration (${entityType} ${name} names no metadata.namespace)`
56
+ : `${entityType} ${name} names no metadata.namespace, and without a generated surface its scope is not known`,
57
+ };
58
+ }
59
+ return { kind: "identifier", listedType, identifier: `${namespace}/${name}`, global: false, location: namespace, entityKind: entityType };
60
+ }
61
+ /** The values that name an indexed k8s object: its `<namespace>/<name>` and its uid. */
62
+ export function k8sNodeIdentities(node) {
63
+ const out = [];
64
+ if (node.nativeId)
65
+ out.push({ kind: "native-id", value: node.nativeId });
66
+ for (const c of node.facts?.cloudIds ?? [])
67
+ if (c.kind === K8S_UID_CLOUD_ID)
68
+ out.push({ kind: c.kind, value: c.value });
69
+ return out;
70
+ }
71
+ export function createK8sIndexIdentity(table) {
72
+ return {
73
+ substrate: "kubernetes",
74
+ declaredIdentity: (entityType, props) => k8sDeclaredIdentity(entityType, props, table),
75
+ nodeIdentities: k8sNodeIdentities,
76
+ };
77
+ }
78
+ export const k8sIndexIdentity = createK8sIndexIdentity();
@@ -0,0 +1,20 @@
1
+ import type { IRNode } from "@intentius/chant/graph-ir";
2
+ import type { IndexImportCodegen } from "@intentius/chant/lifecycle/index-import";
3
+ /** A property value standing for a masked one: the generator writes `maskedValue("<ENV_VAR>")`. */
4
+ export interface K8sMaskedValueRef {
5
+ /** The environment variable the value is read from. */
6
+ __k8sMaskedValue: string;
7
+ }
8
+ export declare function isMaskedValueRef(v: unknown): v is K8sMaskedValueRef;
9
+ /** The properties a declaration of the node's kind can hold. */
10
+ export declare function k8sImportProperties(node: IRNode): Record<string, unknown>;
11
+ /** The referenced-secret declaration for a Secret whose data the index masked, and the note naming what it held. */
12
+ export declare function k8sReferencedSecret(node: IRNode): {
13
+ properties: Record<string, unknown>;
14
+ note: string;
15
+ };
16
+ /** The environment variable a masked value is read from: the parameter name in upper snake case. */
17
+ export declare function maskedValueEnvVar(name: string): string;
18
+ export declare function createK8sIndexImport(): IndexImportCodegen;
19
+ export declare const k8sIndexImport: IndexImportCodegen;
20
+ //# sourceMappingURL=index-import.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-import.d.ts","sourceRoot":"","sources":["../src/index-import.ts"],"names":[],"mappings":"AA+CA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAOlF,mGAAmG;AACnG,MAAM,WAAW,iBAAiB;IAChC,uDAAuD;IACvD,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,IAAI,iBAAiB,CAEnE;AAiCD,gEAAgE;AAChE,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAezE;AAED,oHAAoH;AACpH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAevG;AAED,oGAAoG;AACpG,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAKtD;AAED,wBAAgB,oBAAoB,IAAI,kBAAkB,CAsCzD;AAED,eAAO,MAAM,cAAc,EAAE,kBAA2C,CAAC"}
@@ -0,0 +1,170 @@
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 { SECRET_DECLARATION_ENTITY_TYPE } from "@intentius/chant/secret-provenance";
49
+ import { k8sDeepNormalizationHooks } from "./deep-observe-hooks.js";
50
+ import { operationFor } from "./api/operation-surface.js";
51
+ import { parseListedGvk } from "./listed-types.js";
52
+ export function isMaskedValueRef(v) {
53
+ return typeof v === "object" && v !== null && typeof v.__k8sMaskedValue === "string";
54
+ }
55
+ const SECRET_KIND = "K8s::Core::Secret";
56
+ const CLUSTER_WRITTEN_KINDS = new Set(["K8s::Core::Event", "K8s::Events::Event"]);
57
+ const CLUSTER_WRITTEN_SECRET_TYPES = new Set(["kubernetes.io/service-account-token"]);
58
+ const DROPPED_METADATA = new Set(["deletionTimestamp", "deletionGracePeriodSeconds"]);
59
+ function isRecord(v) {
60
+ return typeof v === "object" && v !== null && !Array.isArray(v);
61
+ }
62
+ function containsMasked(v) {
63
+ if (v === MASKED)
64
+ return true;
65
+ if (Array.isArray(v))
66
+ return v.some(containsMasked);
67
+ if (isRecord(v))
68
+ return Object.values(v).some(containsMasked);
69
+ return false;
70
+ }
71
+ /** `tree` without what the deep hooks prune from an undeclared live object. */
72
+ function pruneLive(entityType, tree, path, pattern) {
73
+ if (Array.isArray(tree))
74
+ return tree.map((v, i) => pruneLive(entityType, v, `${path}[${i}]`, `${pattern}[]`));
75
+ if (!isRecord(tree))
76
+ return tree;
77
+ const out = {};
78
+ for (const key of Object.keys(tree).sort()) {
79
+ const value = tree[key];
80
+ const p = path === "" ? key : `${path}.${key}`;
81
+ const pat = pattern === "" ? key : `${pattern}.${key}`;
82
+ if (k8sDeepNormalizationHooks.prune?.({ entityType, path: p, pattern: pat, key, value, side: "live", counterpart: "absent" }))
83
+ continue;
84
+ out[key] = pruneLive(entityType, value, p, pat);
85
+ }
86
+ return out;
87
+ }
88
+ /** The properties a declaration of the node's kind can hold. */
89
+ export function k8sImportProperties(node) {
90
+ const props = pruneLive(node.kind, node.attrs ?? {}, "", "");
91
+ if (isRecord(props.metadata)) {
92
+ const metadata = Object.fromEntries(Object.entries(props.metadata).filter(([k]) => !DROPPED_METADATA.has(k)));
93
+ for (const k of ["labels", "annotations"]) {
94
+ if (isRecord(metadata[k]) && Object.keys(metadata[k]).length === 0)
95
+ delete metadata[k];
96
+ }
97
+ props.metadata = metadata;
98
+ }
99
+ const gvk = node.listedType ? parseListedGvk(node.listedType) : undefined;
100
+ if (gvk) {
101
+ const listedApiVersion = gvk.group ? `${gvk.group}/${gvk.version}` : gvk.version;
102
+ if (operationFor(node.kind)?.apiVersion !== listedApiVersion)
103
+ return { apiVersion: listedApiVersion, ...props };
104
+ }
105
+ return props;
106
+ }
107
+ /** The referenced-secret declaration for a Secret whose data the index masked, and the note naming what it held. */
108
+ export function k8sReferencedSecret(node) {
109
+ const attrs = node.attrs ?? {};
110
+ const metadata = isRecord(attrs.metadata) ? attrs.metadata : {};
111
+ const name = typeof metadata.name === "string" ? metadata.name : (node.nativeId ?? node.id).split("/").pop();
112
+ const namespace = typeof metadata.namespace === "string" ? metadata.namespace : undefined;
113
+ const keys = [
114
+ ...new Set(["data", "stringData"].flatMap((f) => (isRecord(attrs[f]) ? Object.keys(attrs[f]) : []))),
115
+ ].sort();
116
+ const type = typeof attrs.type === "string" ? attrs.type : "Opaque";
117
+ return {
118
+ properties: { name, provenance: "referenced", ...(namespace ? { scope: namespace } : {}) },
119
+ note: `the Secret ${namespace ? `${namespace}/` : ""}${name} (type ${type}, keys ${keys.join(", ") || "none"}) was masked in the index, ` +
120
+ `so it is declared as a referenced secret: supply it out of band`,
121
+ };
122
+ }
123
+ /** The environment variable a masked value is read from: the parameter name in upper snake case. */
124
+ export function maskedValueEnvVar(name) {
125
+ return name
126
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
127
+ .replace(/[^A-Za-z0-9]+/g, "_")
128
+ .toUpperCase();
129
+ }
130
+ export function createK8sIndexImport() {
131
+ return {
132
+ resource(node) {
133
+ if (!node.kind.startsWith("K8s::") || node.kind.split("::").length !== 3) {
134
+ return { unsupported: `${node.kind} is not a Kubernetes kind of the k8s lexicon` };
135
+ }
136
+ if (CLUSTER_WRITTEN_KINDS.has(node.kind))
137
+ return { unsupported: `${node.kind} objects are written by the cluster` };
138
+ const attrs = node.attrs ?? {};
139
+ const metadata = isRecord(attrs.metadata) ? attrs.metadata : {};
140
+ const owners = Array.isArray(metadata.ownerReferences) ? metadata.ownerReferences.filter(isRecord) : [];
141
+ if (owners.length > 0) {
142
+ const named = owners.map((o) => `${String(o.kind ?? "?")}/${String(o.name ?? "?")}`).join(", ");
143
+ return { unsupported: `owned by ${named} (metadata.ownerReferences): its controller makes this object, so import the owner` };
144
+ }
145
+ if (node.kind === SECRET_KIND) {
146
+ if (typeof attrs.type === "string" && CLUSTER_WRITTEN_SECRET_TYPES.has(attrs.type)) {
147
+ return { unsupported: `a Secret of type ${attrs.type} is written by the cluster` };
148
+ }
149
+ if (containsMasked(attrs.data) || containsMasked(attrs.stringData)) {
150
+ const { properties, note } = k8sReferencedSecret(node);
151
+ return { type: SECRET_DECLARATION_ENTITY_TYPE, properties, notes: [note] };
152
+ }
153
+ }
154
+ return { type: node.kind, properties: k8sImportProperties(node) };
155
+ },
156
+ // A k8s object names another by name; the literal is the lexicon's spelling.
157
+ reference: () => undefined,
158
+ secretParameter(name, context) {
159
+ return {
160
+ name,
161
+ type: "String",
162
+ description: `${context.path} of ${context.node.id}, masked in the index; set ${maskedValueEnvVar(name)} before building`,
163
+ required: true,
164
+ };
165
+ },
166
+ parameterReference: (name) => ({ __k8sMaskedValue: maskedValueEnvVar(name) }),
167
+ typeLabel: (node) => node.kind.split("::").pop() ?? "Resource",
168
+ };
169
+ }
170
+ export const k8sIndexImport = createK8sIndexImport();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "algorithm": "sha256",
3
3
  "artifacts": {
4
- "manifest.json": "eae38679a1e122b4035fbfc82e0ddc3be5b43ee409bf91d2d3b698125386a727",
4
+ "manifest.json": "9a76f15766669fccf0d1be0cac8475effc4b0f6f20fe6e414893d9d636019148",
5
5
  "meta.json": "e187074ca194ceaf969a3e2f9a85a0be42e7935de316817f309f6c9bee4eb952",
6
6
  "types/index.d.ts": "35f6ca4fa77c28ecad363920b444f27ab72f0fe49e82eb20e42824c312ac689b",
7
7
  "rules/argo-appset-single-project.ts": "afa9f310753aa2d475f35012b13135b2dfaebed2a35d44edbe185ebc07673674",
@@ -78,5 +78,5 @@
78
78
  "skills/chant-k8s-argo.md": "24c9a85b78a2fc5c6657424baac9cc6d6caff6f47605b8146b2c0082133181cf",
79
79
  "skills/chant-k8s-flux.md": "9670efc2e9854bd14686b5adeb707396b9030a4dcaee6529b30abf56efe2c50c"
80
80
  },
81
- "composite": "edfc26a4ad39415e44c3eefa79a160540722b87e3d857db56d5c71737a2efa7c"
81
+ "composite": "bce950cad361ddbb3cf32c89a2d069e5492436bcf3df9d1b9f4cbcd79c70620f"
82
82
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "k8s",
3
- "version": "0.124.54",
3
+ "version": "0.124.56",
4
4
  "chantVersion": ">=0.1.0",
5
5
  "namespace": "K8s",
6
6
  "intrinsics": [],
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAqC,MAAM,0BAA0B,CAAC;AAmCjG,eAAO,MAAM,SAAS,EAAE,aAqwBvB,CAAC"}
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAqC,MAAM,0BAA0B,CAAC;AAqCjG,eAAO,MAAM,SAAS,EAAE,aA6wBvB,CAAC"}
package/dist/plugin.js CHANGED
@@ -24,6 +24,8 @@ import { K8sParser } from "./import/parser.js";
24
24
  import { K8sGenerator } from "./import/generator.js";
25
25
  import { k8sDeepNormalizationHooks } from "./deep-observe-hooks.js";
26
26
  import { k8sListedTypes } from "./listed-types.js";
27
+ import { k8sIndexIdentity } from "./index-identity.js";
28
+ import { k8sIndexImport } from "./index-import.js";
27
29
  import { k8sReferenceCatalog } from "./reference-catalog.js";
28
30
  import { LABEL_OWNERSHIP_KEYS } from "@intentius/chant/ownership";
29
31
  import { k8sConfigSchema } from "./config-schema.js";
@@ -761,4 +763,10 @@ const { deployment, service, serviceMonitor, prometheusRule } = MonitoredService
761
763
  // How its resources reference each other, for chant's catalog pass over an
762
764
  // index and a declared graph (#4535; behold#1005 retires behold's matcher on it).
763
765
  referenceCatalog: k8sReferenceCatalog,
766
+ // Declared objects matched to indexed ones by apiVersion/kind, namespace and
767
+ // name; the server-assigned uid names a node to the identity edge pass (#4538).
768
+ indexIdentity: k8sIndexIdentity,
769
+ // `chant import --index`: an indexed object as source; a masked Secret as a
770
+ // referenced secret, any other masked value read from the environment (#4538).
771
+ indexImport: k8sIndexImport,
764
772
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/chant-lexicon-k8s",
3
- "version": "0.124.54",
3
+ "version": "0.124.56",
4
4
  "description": "Kubernetes lexicon for chant — declarative IaC in TypeScript",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://intentius.io/chant",
@@ -74,13 +74,13 @@
74
74
  "build": "../../scripts/tsc7.sh -p tsconfig.build.json --sourceMap false && tsc-alias -p tsconfig.build.json && cp src/generated/index.d.ts dist/generated/index.d.d.ts"
75
75
  },
76
76
  "dependencies": {
77
- "@intentius/chant-lexicon-otel": "^0.124.54",
78
- "@intentius/chant-lexicon-prometheus": "^0.124.54",
77
+ "@intentius/chant-lexicon-otel": "^0.124.56",
78
+ "@intentius/chant-lexicon-prometheus": "^0.124.56",
79
79
  "js-yaml": "^4.3.1",
80
80
  "@types/js-yaml": "^4.0.9"
81
81
  },
82
82
  "optionalDependencies": {
83
- "@intentius/chant-k8s-client": "^0.124.54"
83
+ "@intentius/chant-k8s-client": "^0.124.56"
84
84
  },
85
85
  "devDependencies": {
86
86
  "@intentius/chant": "*",
@@ -88,6 +88,6 @@
88
88
  },
89
89
  "peerDependencies": {
90
90
  "zod": "^4.3.6",
91
- "@intentius/chant": "^0.124.54"
91
+ "@intentius/chant": "^0.124.56"
92
92
  }
93
93
  }
@@ -12,6 +12,8 @@ import {
12
12
  isEmbeddedReference,
13
13
  renderEmbeddedReference,
14
14
  } from "@intentius/chant/import/embedded";
15
+ import { SECRET_DECLARATION_ENTITY_TYPE } from "@intentius/chant/secret-provenance";
16
+ import { isMaskedValueRef } from "../index-import";
15
17
 
16
18
  const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
17
19
 
@@ -131,8 +133,13 @@ export class K8sGenerator implements TypeScriptGenerator {
131
133
  /** The imports for embedded content the current `generate()` call references (#2962). */
132
134
  private scope = new EmbeddedImportScope("");
133
135
 
136
+ /** Whether the current `generate()` call wrote a `maskedValue(...)` (chant import --index, #4538). */
137
+ private usesMaskedValue = false;
138
+
134
139
  generate(ir: TemplateIR): GeneratedFile[] {
135
140
  const lines: string[] = [];
141
+ this.usesMaskedValue = false;
142
+ let usesDeclareSecret = false;
136
143
 
137
144
  // Collect which constructors are needed
138
145
  const usedConstructors = new Set<string>();
@@ -161,6 +168,13 @@ export class K8sGenerator implements TypeScriptGenerator {
161
168
 
162
169
  // Emit resources
163
170
  for (const resource of ir.resources) {
171
+ // A Secret `chant import --index` read masked: a referenced secret the user supplies (#4538).
172
+ if (resource.type === SECRET_DECLARATION_ENTITY_TYPE) {
173
+ usesDeclareSecret = true;
174
+ lines.push(`export const ${resource.logicalId} = declareSecret(${this.emitLiteral(resource.properties, 0, resource.type)});`);
175
+ lines.push("");
176
+ continue;
177
+ }
164
178
  const cls = this.resolveClass(resource.type);
165
179
  if (!cls) {
166
180
  lines.push(`// TODO: unsupported type ${resource.type} (${resource.logicalId})`);
@@ -182,11 +196,33 @@ export class K8sGenerator implements TypeScriptGenerator {
182
196
  const code = lines.join("\n").replace(/"(?:[^"\\\n]|\\.)*"/g, '""');
183
197
  for (const m of code.matchAll(/\bnew ([A-Z][A-Za-z0-9_]*)\(/g)) usedConstructors.add(m[1]);
184
198
  const imports = [...usedConstructors].sort().join(", ");
185
- const head = [`import { ${imports} } from "@intentius/chant-lexicon-k8s";`, ...this.scope.lines(), ""];
199
+ const head = [
200
+ ...(usesDeclareSecret ? [`import { declareSecret } from "@intentius/chant";`] : []),
201
+ ...(imports ? [`import { ${imports} } from "@intentius/chant-lexicon-k8s";`] : []),
202
+ ...this.scope.lines(),
203
+ "",
204
+ ];
205
+ if (this.usesMaskedValue) head.push(...this.maskedValueHelper(ir), "");
186
206
 
187
207
  return [{ path: "main.ts", content: [...head, ...lines].join("\n") }];
188
208
  }
189
209
 
210
+ /**
211
+ * The helper a value masked in the index reads its environment variable
212
+ * through, with the parameters it stands for listed above it.
213
+ */
214
+ private maskedValueHelper(ir: TemplateIR): string[] {
215
+ return [
216
+ "// Values the index masked. Set each environment variable before building:",
217
+ ...ir.parameters.map((p) => `// ${p.name}: ${(p.description ?? "").replace(/\r?\n/g, " ")}`),
218
+ "function maskedValue(name: string): any {",
219
+ " const raw = process.env[name];",
220
+ " if (raw === undefined) throw new Error(`${name} is not set: the value was masked in the index`);",
221
+ " return /^\\s*[[{]/.test(raw) ? JSON.parse(raw) : raw;",
222
+ "}",
223
+ ];
224
+ }
225
+
190
226
  /**
191
227
  * Resolve a K8s type name to a constructor class name.
192
228
  * Falls back to extracting the last segment of the type.
@@ -207,7 +243,7 @@ export class K8sGenerator implements TypeScriptGenerator {
207
243
  parentType: string,
208
244
  ): void {
209
245
  for (const [key, value] of Object.entries(props)) {
210
- if (value === undefined || value === null) continue;
246
+ if (value === undefined || value === null || isMaskedValueRef(value)) continue;
211
247
 
212
248
  // Special case: "ports" on Service resources → ServicePort
213
249
  if (key === "ports" && SERVICE_PORT_TYPES.has(parentType)) {
@@ -254,6 +290,7 @@ export class K8sGenerator implements TypeScriptGenerator {
254
290
  private emitValue(key: string, value: unknown, depth: number, parentType: string): string {
255
291
  if (value === null || value === undefined) return "undefined";
256
292
  if (isEmbeddedReference(value)) return renderEmbeddedReference(value, this.scope, depth * 2);
293
+ if (isMaskedValueRef(value)) return this.emitLiteral(value, depth, parentType);
257
294
 
258
295
  // Special case: "ports" on Service → ServicePort constructor
259
296
  if (key === "ports" && SERVICE_PORT_TYPES.has(parentType) && Array.isArray(value)) {
@@ -287,6 +324,7 @@ export class K8sGenerator implements TypeScriptGenerator {
287
324
  const innerIndent = " ".repeat(depth + 1);
288
325
 
289
326
  const emitted = items.map((item) => {
327
+ if (isMaskedValueRef(item)) return this.emitLiteral(item, depth + 1, parentType);
290
328
  if (typeof item === "object" && item !== null && !Array.isArray(item)) {
291
329
  const propsStr = this.emitProps(item as Record<string, unknown>, depth + 1, parentType);
292
330
  return `new ${constructor}(${propsStr})`;
@@ -303,6 +341,10 @@ export class K8sGenerator implements TypeScriptGenerator {
303
341
  private emitLiteral(value: unknown, depth: number, parentType: string): string {
304
342
  if (value === null || value === undefined) return "undefined";
305
343
  if (isEmbeddedReference(value)) return renderEmbeddedReference(value, this.scope, depth * 2);
344
+ if (isMaskedValueRef(value)) {
345
+ this.usesMaskedValue = true;
346
+ return `maskedValue(${JSON.stringify(value.__k8sMaskedValue)})`;
347
+ }
306
348
  if (typeof value === "string") return JSON.stringify(value);
307
349
  if (typeof value === "number" || typeof value === "boolean") return String(value);
308
350
 
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The k8s lexicon's identity rule for indexed objects (#4538, on #4523's
3
+ * matcher, ../../../packages/core/src/lifecycle/identity-match.ts).
4
+ *
5
+ * core's Kubernetes lister (packages/core/src/cloud-lister/kubernetes.ts)
6
+ * writes each object as:
7
+ *
8
+ * - `listedType` `<apiVersion>/<kind>` (`apps/v1/Deployment`, `v1/Secret`);
9
+ * - `location` its namespace, or `cluster` for a cluster-scoped kind;
10
+ * - `nativeId` `<namespace>/<name>`, or `<name>` for a cluster-scoped kind;
11
+ * - one cloud id, `k8s-uid`, the object's `metadata.uid`.
12
+ *
13
+ * apiVersion, kind, namespace and name are all spelled by the user, so a
14
+ * declaration that was never applied still matches its object by value.
15
+ * The uid is assigned by the API server, so no declaration states it. It
16
+ * still names an indexed node to the identity edge pass, where another
17
+ * object's `ownerReferences[].uid` points at its owner.
18
+ *
19
+ * The match is by lexicon kind, not by listed type: discovery lists a
20
+ * group at its preferred version, which need not be the version the
21
+ * lexicon writes, and the kind is the same at any version. Coverage is
22
+ * still read for the declared listed type, so a version the index did not
23
+ * list reads not observed, never absent.
24
+ *
25
+ * What cannot match (`no-binding`):
26
+ * - a name the declaration leaves out, spells with a reference, or asks the
27
+ * API server to generate (`metadata.generateName`);
28
+ * - a namespaced kind with no `metadata.namespace`. The namespace kubectl
29
+ * or a GitOps controller would apply it to is not in the declaration.
30
+ *
31
+ * A type the lexicon has no API address for (`K8s::Sops::EncryptedSecretFile`,
32
+ * a kind outside the generated surface) is `unsupported-kind`.
33
+ */
34
+ import type { DeclaredIdentity, IndexIdentity } from "@intentius/chant/lifecycle/identity-match";
35
+ import type { NodeIdentityValue } from "@intentius/chant/graph-refs";
36
+ import type { IRNode } from "@intentius/chant/graph-ir";
37
+ import { operationFor, operationTable, type K8sOperationDescriptor, type K8sOperationTable } from "./api/operation-surface";
38
+ import { k8sListedTypeFor } from "./listed-types";
39
+
40
+ /** The location core's Kubernetes lister gives a cluster-scoped object. */
41
+ export const K8S_CLUSTER_LOCATION = "cluster";
42
+
43
+ /** The cloud id kind holding an object's `metadata.uid`. */
44
+ export const K8S_UID_CLOUD_ID = "k8s-uid";
45
+
46
+ function isRecord(v: unknown): v is Record<string, unknown> {
47
+ return typeof v === "object" && v !== null && !Array.isArray(v);
48
+ }
49
+
50
+ const nonEmptyString = (v: unknown): v is string => typeof v === "string" && v !== "";
51
+
52
+ /**
53
+ * The descriptor for `entityType` and whether its scope is known: from the
54
+ * generated table when there is one, else derived (and the derived scope is
55
+ * a guess, so it is not trusted for a declaration without a namespace).
56
+ */
57
+ function addressOf(entityType: string, table: K8sOperationTable | undefined): { op: K8sOperationDescriptor; scopeKnown: boolean } | undefined {
58
+ const t = table ?? operationTable();
59
+ if (t[entityType]) return { op: t[entityType], scopeKnown: true };
60
+ // Only the generated table knows CRDs and cluster-scoped kinds. A test table stands alone.
61
+ if (table) return undefined;
62
+ const derived = operationFor(entityType);
63
+ return derived ? { op: derived, scopeKnown: false } : undefined;
64
+ }
65
+
66
+ /**
67
+ * The identifier a k8s declaration spells for the index, or why it spells
68
+ * none. `table` is the generated operation surface; a test passes one.
69
+ */
70
+ export function k8sDeclaredIdentity(entityType: string, props: Record<string, unknown>, table?: K8sOperationTable): DeclaredIdentity {
71
+ const address = addressOf(entityType, table);
72
+ if (!address) {
73
+ return { kind: "unmatchable", reason: "unsupported-kind", detail: `${entityType} has no Kubernetes API address on record` };
74
+ }
75
+ const { op, scopeKnown } = address;
76
+ const metadata = isRecord(props.metadata) ? props.metadata : {};
77
+ if (!nonEmptyString(metadata.name)) {
78
+ const detail = nonEmptyString(metadata.generateName)
79
+ ? `the name of ${entityType} is generated by the API server (metadata.generateName), so no declaration states it`
80
+ : `identity is not in the declaration (${entityType} metadata.name)`;
81
+ return { kind: "unmatchable", reason: "no-binding", detail };
82
+ }
83
+ const name = metadata.name;
84
+ const apiVersion = nonEmptyString(props.apiVersion) ? props.apiVersion : op.apiVersion;
85
+ const listedType = k8sListedTypeFor(apiVersion, op.kind);
86
+ const namespace = nonEmptyString(metadata.namespace) ? metadata.namespace : undefined;
87
+
88
+ if (scopeKnown && op.scope === "Cluster") {
89
+ return { kind: "identifier", listedType, identifier: name, global: true, location: K8S_CLUSTER_LOCATION, entityKind: entityType };
90
+ }
91
+ if (!namespace) {
92
+ return {
93
+ kind: "unmatchable",
94
+ reason: "no-binding",
95
+ detail: scopeKnown
96
+ ? `identity is not in the declaration (${entityType} ${name} names no metadata.namespace)`
97
+ : `${entityType} ${name} names no metadata.namespace, and without a generated surface its scope is not known`,
98
+ };
99
+ }
100
+ return { kind: "identifier", listedType, identifier: `${namespace}/${name}`, global: false, location: namespace, entityKind: entityType };
101
+ }
102
+
103
+ /** The values that name an indexed k8s object: its `<namespace>/<name>` and its uid. */
104
+ export function k8sNodeIdentities(node: IRNode): NodeIdentityValue[] {
105
+ const out: NodeIdentityValue[] = [];
106
+ if (node.nativeId) out.push({ kind: "native-id", value: node.nativeId });
107
+ for (const c of node.facts?.cloudIds ?? []) if (c.kind === K8S_UID_CLOUD_ID) out.push({ kind: c.kind, value: c.value });
108
+ return out;
109
+ }
110
+
111
+ export function createK8sIndexIdentity(table?: K8sOperationTable): IndexIdentity {
112
+ return {
113
+ substrate: "kubernetes",
114
+ declaredIdentity: (entityType, props) => k8sDeclaredIdentity(entityType, props, table),
115
+ nodeIdentities: k8sNodeIdentities,
116
+ };
117
+ }
118
+
119
+ export const k8sIndexIdentity: IndexIdentity = createK8sIndexIdentity();
@@ -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();
package/src/plugin.ts CHANGED
@@ -30,6 +30,8 @@ import { K8sParser } from "./import/parser";
30
30
  import { K8sGenerator } from "./import/generator";
31
31
  import { k8sDeepNormalizationHooks } from "./deep-observe-hooks";
32
32
  import { k8sListedTypes } from "./listed-types";
33
+ import { k8sIndexIdentity } from "./index-identity";
34
+ import { k8sIndexImport } from "./index-import";
33
35
  import { k8sReferenceCatalog } from "./reference-catalog";
34
36
  import { LABEL_OWNERSHIP_KEYS } from "@intentius/chant/ownership";
35
37
  import { k8sConfigSchema } from "./config-schema";
@@ -814,4 +816,12 @@ const { deployment, service, serviceMonitor, prometheusRule } = MonitoredService
814
816
  // How its resources reference each other, for chant's catalog pass over an
815
817
  // index and a declared graph (#4535; behold#1005 retires behold's matcher on it).
816
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,
817
827
  };