Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions lexicons/k8s/src/serializer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -510,3 +510,105 @@ describe("k8sSerializer", () => {
expect(result).not.toMatch(/^spec:\s*\n\s+rules:/m);
});
});

// ── Cross-resource references (#1493) ────────────────────────────────
//
// Kubernetes YAML has no deploy-time reference mechanism, so a reference has
// to be resolved before serialization or it means nothing. These used to
// serialize to the *logical* name, so a Deployment referencing its PVC emitted
// `claimName: pgClaim` and named a resource that does not exist — it applied
// cleanly and failed on the cluster.

function mockAttrRef(attribute: string, logicalName: string): any {
// Shape isAttrRefLike() checks for: parent object, string attribute, and
// _setLogicalName. Without the last one the walker treats it as a plain
// object and the test silently asserts nothing.
return {
attribute,
parent: { deref: () => undefined },
_setLogicalName: () => {},
getLogicalName: () => logicalName,
};
}

describe("cross-resource references resolve at build time (#1493)", () => {
test(".name resolves to the referenced resource's metadata.name", () => {
const claim = mockResource("K8s::Core::PersistentVolumeClaim", {
metadata: { name: "fountain-postgres", namespace: "fountain" },
spec: { accessModes: ["ReadWriteOnce"] },
});
const dep = mockResource("K8s::Apps::Deployment", {
metadata: { name: "fountain-postgres", namespace: "fountain" },
spec: {
template: {
spec: {
volumes: [
{ name: "data", persistentVolumeClaim: { claimName: mockAttrRef("name", "pgClaim") } },
],
},
},
},
});
const yaml = k8sSerializer.serialize(new Map([["pgClaim", claim], ["pgDeployment", dep]]));
expect(yaml).toContain("claimName: fountain-postgres");
expect(yaml).not.toContain("claimName: pgClaim");
});

// A resource that declares no name gets one derived from its logical name.
// A reference to it has to derive the SAME one or the two silently disagree.
test(".name matches the derived name when the target declares none", () => {
const claim = mockResource("K8s::Core::PersistentVolumeClaim", {
spec: { accessModes: ["ReadWriteOnce"] },
});
const dep = mockResource("K8s::Apps::Deployment", {
spec: { template: { spec: { volumes: [{ claimName: mockAttrRef("name", "pgClaim") }] } } },
});
const yaml = k8sSerializer.serialize(new Map([["pgClaim", claim], ["dep", dep]]));
expect(yaml).toContain("name: pg-claim");
expect(yaml).toContain("claimName: pg-claim");
});

test(".namespace resolves to the declared namespace", () => {
const svc = mockResource("K8s::Core::Service", {
metadata: { name: "fountain", namespace: "fountain" },
});
const dep = mockResource("K8s::Apps::Deployment", {
metadata: { name: "app" },
spec: { host: mockAttrRef("namespace", "service") },
});
const yaml = k8sSerializer.serialize(new Map([["service", svc], ["dep", dep]]));
expect(yaml).toContain("host: fountain");
});

// A UID is assigned by the API server at admission, so emitting any
// build-time string for it would be a fabrication.
test(".uid is refused rather than fabricated", () => {
const svc = mockResource("K8s::Core::Service", { metadata: { name: "fountain" } });
const dep = mockResource("K8s::Apps::Deployment", {
spec: { ownerRef: mockAttrRef("uid", "service") },
});
expect(() => k8sSerializer.serialize(new Map([["service", svc], ["dep", dep]]))).toThrow(
/assigned by the API server/,
);
});

test("an unresolvable namespace says what to set rather than emitting a wrong one", () => {
const svc = mockResource("K8s::Core::Service", { metadata: { name: "fountain" } });
const dep = mockResource("K8s::Apps::Deployment", {
spec: { ns: mockAttrRef("namespace", "service") },
});
expect(() => k8sSerializer.serialize(new Map([["service", svc], ["dep", dep]]))).toThrow(
/declares no metadata.namespace/,
);
});

test("an attribute k8s cannot express is refused with the reason", () => {
const svc = mockResource("K8s::Core::Service", { metadata: { name: "fountain" } });
const dep = mockResource("K8s::Apps::Deployment", {
spec: { x: mockAttrRef("clusterIP", "service") },
});
expect(() => k8sSerializer.serialize(new Map([["service", svc], ["dep", dep]]))).toThrow(
/resolves .name and .namespace/,
);
});
});
79 changes: 72 additions & 7 deletions lexicons/k8s/src/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,16 +113,82 @@ function deriveGVKFromType(entityType: string): { apiVersion: string; kind: stri
return { apiVersion, kind };
}

/**
* The name a resource gets when it does not declare one: the logical name,
* kebab-cased. Shared with the manifest builder below so a reference and the
* thing it references cannot derive different names (#1493).
*/
function derivedName(logicalName: string): string {
return logicalName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
}

/**
* What a cross-resource reference resolves to on this substrate (#1493).
*
* Kubernetes YAML has no deploy-time reference mechanism — no `!Ref`, no
* `Fn::GetAtt`. Whatever a reference is going to mean has to be resolved here,
* before serialization, or it means nothing at all.
*
* This used to return the *logical* name for every attribute, so
* `claimName: pgClaim.name` emitted `claimName: pgClaim` and the manifest
* named a resource that does not exist. It applied cleanly and failed on the
* cluster, which is the failure this whole system exists to remove. The
* lexicon's own plugin comment already described the intended behaviour —
* "resolves to metadata.name" — so this brings the code to the documentation
* rather than the other way round.
*
* `uid` is refused rather than resolved: a UID is assigned by the API server
* at admission, so no build-time value exists and any string emitted here
* would be a fabrication.
*/
function resolveK8sAttr(entity: Declarable | undefined, logicalName: string, attr: string): unknown {
if (attr === "uid") {
throw new Error(
`Cannot reference "${logicalName}.uid": a Kubernetes UID is assigned by the API server at ` +
`admission, so it has no build-time value. Reference .name, or carry the UID at runtime ` +
`with fieldRef: { fieldPath: "metadata.uid" }.`,
);
}

const metadata =
entity && isResourceDeclarable(entity) && typeof entity.props === "object" && entity.props !== null
? ((entity.props as Record<string, unknown>).metadata as Record<string, unknown> | undefined)
: undefined;

if (attr === "name") {
// Same fallback the manifest builder applies, so a reference to a resource
// that declares no name still resolves to the name it will actually get.
const declared = metadata?.name;
return typeof declared === "string" && declared.length > 0 ? declared : derivedName(logicalName);
}

if (attr === "namespace") {
const ns = metadata?.namespace;
if (typeof ns === "string" && ns.length > 0) return ns;
throw new Error(
`Cannot reference "${logicalName}.namespace": it declares no metadata.namespace, and the ` +
`namespace a manifest lands in is decided at apply time (kubectl -n, or the context's ` +
`default). Set metadata.namespace on "${logicalName}" if the reference needs to be stable.`,
);
}

throw new Error(
`Cannot reference "${logicalName}.${attr}": the k8s lexicon resolves .name and .namespace at ` +
`build time, and Kubernetes YAML has no way to express any other attribute reference.`,
);
}

/**
* K8s visitor for the generic serializer walker.
*/
function k8sVisitor(entityNames: Map<Declarable, string>): SerializerVisitor {
// name → entity, so an AttrRef can reach the resource it points at. The
// walker hands the visitor a logical name, not the Declarable.
const byName = new Map<string, Declarable>();
for (const [entity, name] of entityNames) byName.set(name, entity);

return {
attrRef: (name, attr) => {
// For K8s, attribute references typically resolve to metadata.name
if (attr === "name") return name;
return name;
},
attrRef: (name, attr) => resolveK8sAttr(byName.get(name), name, attr),
resourceRef: (name) => name,
propertyDeclarable: (entity, walk) => {
if (!isResourceDeclarable(entity) || typeof entity.props !== "object" || entity.props === null) {
Expand Down Expand Up @@ -209,8 +275,7 @@ export const k8sSerializer: Serializer = {
// Build metadata
const metadata: Record<string, unknown> = props.metadata as Record<string, unknown> ?? {};
if (!metadata.name) {
// Use the logical name as the resource name (kebab-case)
metadata.name = name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
metadata.name = derivedName(name);
}

// Merge default labels
Expand Down