diff --git a/lexicons/k8s/src/api/connect.ts b/lexicons/k8s/src/api/connect.ts index c23a94b0e2..ce8d566cd5 100644 --- a/lexicons/k8s/src/api/connect.ts +++ b/lexicons/k8s/src/api/connect.ts @@ -1,23 +1,20 @@ /** * Getting from a chant environment to a live API client — chant #1074. * - * The cluster binding (chant #1100, landed in #1155) is unchanged by the move - * off `kubectl`, and deliberately so: `resolveClusterTarget` in core stays the - * single resolver, shared with the GCP lexicon's Config Connector observation, - * and the refusal it throws on a bound-but-mismatched context still aborts - * before any resource is touched. What changes is only *how the ambient - * context is read*: the typed client parses the kubeconfig it is about to use - * rather than shelling `kubectl config current-context`, so a worker image with - * no `kubectl` in it can still check the binding. Same question, same three + * The cluster binding (chant #1100/#1155, revised by #1488): + * `resolveClusterTarget` in core stays the single resolver, and a declared + * binding is now *used*, never policed against the ambient context. Two * outcomes: * - * - **Bound and ambient agrees** — the bound context is passed explicitly to - * the client, never left to the ambient default. - * - **Bound and ambient disagrees** — `ClusterBindingMismatchError`, thrown - * before the first request. Core turns the throw into NOT-OBSERVED for every - * declared entity (chant #1089), which is what stops a wrong-cluster read - * becoming a confident list of creates. - * - **Unbound** — the kubeconfig's own current-context, with the same visible + * - **Bound** — the bound context is passed explicitly to the client, + * regardless of what `kubectl` is ambiently pointed at. A binding that + * names a context the kubeconfig does not have fails in the client with an + * error naming both the context and the `k8s.profiles..context` + * binding — never by falling back to ambient. (#1488: the old + * ambient-mismatch refusal meant any other project's k3d cluster stealing + * the current-context turned a healthy estate grey with `read-failed` as + * the only explanation.) + * - **Unbound** — the kubeconfig's own current-context, with a visible * warning naming the environment and the missing binding. */ @@ -62,7 +59,7 @@ export interface ConnectedClient { * build a client honoring it. */ export const defaultK8sConnector: K8sConnector = async (options) => { - const { createK8sClient, readAmbientContext } = await import("@intentius/chant-k8s-client"); + const { createK8sClient } = await import("@intentius/chant-k8s-client"); if (options.context !== undefined) { const client = await createK8sClient({ @@ -82,17 +79,10 @@ export const defaultK8sConnector: K8sConnector = async (options) => { const k8sConfig = (config as { k8s?: K8sChantConfig }).k8s; const execAllowlist = k8sConfig?.execCredentialPlugins; - // The binding check reads the kubeconfig's current-context directly. Only a - // context name is needed, and requiring a *usable* ambient cluster to check a - // binding would defeat the binding: pointing an environment at a specific - // context is how you recover from an ambient one that is wrong or broken. - const target = await resolveClusterTarget(config as Record, options.environment, "k8s", { - ambientContext: () => - readAmbientContext({ - kubeconfig: options.client?.kubeconfig, - kubeconfigPath: options.client?.kubeconfigPath, - }), - }); + // #1488 — the resolver returns the declared binding (or ambient-with-warning + // when unbound); it no longer reads the ambient context at all, so no reader + // is supplied. + const target = await resolveClusterTarget(config as Record, options.environment, "k8s"); const client = await createK8sClient({ ...options.client, diff --git a/lexicons/k8s/src/describe-resources.test.ts b/lexicons/k8s/src/describe-resources.test.ts index 7ba28d9795..530a0da323 100644 --- a/lexicons/k8s/src/describe-resources.test.ts +++ b/lexicons/k8s/src/describe-resources.test.ts @@ -420,8 +420,11 @@ describe("k8s describeResources", () => { expect(result.resources.web).toMatchObject({ type: "K8s::Apps::Deployment", physicalId: "uid-1", status: "READY" }); }); - test("bound and ambient context mismatches: refuses loudly instead of reading the wrong cluster", async () => { + test("bound while a different context is ambient: the binding wins and the estate observes (#1488)", async () => { loadChantConfigMock.mockResolvedValue({ config: { k8s: { profiles: { prod: { context: "prod-eks" } } } } }); + // Ambient points at staging — the state any other project's k3d cluster + // leaves behind. Before #1488 this refused and the whole estate read + // grey; the declared binding must simply be used instead. const ambientIsStaging = fakeKubeconfig({ contexts: [ { name: "prod-eks", cluster: "prod", user: "prod-user" }, @@ -429,16 +432,17 @@ describe("k8s describeResources", () => { ], currentContext: "staging-eks", }); - const cluster = fakeCluster({ kubeconfig: ambientIsStaging }); + const cluster = fakeCluster({ + kubeconfig: ambientIsStaging, + objects: { [objectKey("apps/v1", "Deployment", "web", "prod")]: web }, + }); - await expect( - describeResources({ environment: "prod", buildOutput: "", entityNames: ["web"], entities: entities() }, (o) => - defaultK8sConnector({ ...o, client: { kubeconfig: ambientIsStaging, requestLayer: cluster.layer } }), - ), - ).rejects.toThrow(/environment "prod".*"prod-eks".*"staging-eks"/s); + const result = await describeResources( + { environment: "prod", buildOutput: "", entityNames: ["web"], entities: entities() }, + (o) => defaultK8sConnector({ ...o, client: { kubeconfig: ambientIsStaging, requestLayer: cluster.layer } }), + ); - // Refused before a single request left the process. - expect(cluster.layer.requests).toHaveLength(0); + expect(result.resources.web).toMatchObject({ type: "K8s::Apps::Deployment", physicalId: "uid-1", status: "READY" }); }); test("unbound: the kubeconfig's own context is used, and the fallback is visible", async () => { diff --git a/packages/core/src/kubectl-context.test.ts b/packages/core/src/kubectl-context.test.ts index 8f20c64eef..ea75c3a89f 100644 --- a/packages/core/src/kubectl-context.test.ts +++ b/packages/core/src/kubectl-context.test.ts @@ -16,7 +16,7 @@ vi.mock("node:child_process", async () => { const { resolveClusterTarget, ClusterBindingMismatchError } = await import("./kubectl-context"); -describe("resolveClusterTarget (chant #1100)", () => { +describe("resolveClusterTarget (chant #1100, #1488)", () => { beforeEach(() => { execMock.mockReset(); }); @@ -34,9 +34,7 @@ describe("resolveClusterTarget (chant #1100)", () => { warnSpy.mockRestore(); }); - test("bound and ambient context matches: returns the bound context", async () => { - execMock.mockResolvedValue({ stdout: "prod-eks\n", stderr: "" }); - + test("bound: returns the bound context without ever probing the ambient one (#1488)", async () => { const target = await resolveClusterTarget( { k8s: { profiles: { prod: { context: "prod-eks" } } } }, "prod", @@ -44,11 +42,14 @@ describe("resolveClusterTarget (chant #1100)", () => { ); expect(target).toEqual({ context: "prod-eks", source: "bound" }); - expect(execMock).toHaveBeenCalledWith(expect.stringContaining("current-context")); + expect(execMock).not.toHaveBeenCalled(); }); - test("bound and ambient context cannot be determined: proceeds with the bound context anyway", async () => { - execMock.mockRejectedValue(new Error("no kubeconfig")); + test("bound while a different context is ambient: the binding wins, no refusal (#1488)", async () => { + // Ambient says staging-eks; the declared binding must be used regardless. + // Before #1488 this threw ClusterBindingMismatchError, which turned a + // healthy estate grey the moment any other project switched the context. + execMock.mockResolvedValue({ stdout: "staging-eks\n", stderr: "" }); const target = await resolveClusterTarget( { k8s: { profiles: { prod: { context: "prod-eks" } } } }, @@ -59,23 +60,14 @@ describe("resolveClusterTarget (chant #1100)", () => { expect(target).toEqual({ context: "prod-eks", source: "bound" }); }); - test("bound and ambient context mismatches: refuses loudly, naming env/expected/ambient", async () => { - execMock.mockResolvedValue({ stdout: "staging-eks\n", stderr: "" }); - - const err: unknown = await resolveClusterTarget( - { k8s: { profiles: { prod: { context: "prod-eks" } } } }, - "prod", - "k8s", - ).catch((e: unknown) => e); - - expect(err).toBeInstanceOf(ClusterBindingMismatchError); - const mismatch = err as InstanceType; - expect(mismatch.environment).toBe("prod"); - expect(mismatch.expectedContext).toBe("prod-eks"); - expect(mismatch.ambientContext).toBe("staging-eks"); - expect(mismatch.message).toContain('environment "prod"'); - expect(mismatch.message).toContain('"prod-eks"'); - expect(mismatch.message).toContain('"staging-eks"'); + test("ClusterBindingMismatchError still constructs and names all three parts (catchers rely on it)", () => { + const err = new ClusterBindingMismatchError("prod", "prod-eks", "staging-eks"); + expect(err.environment).toBe("prod"); + expect(err.expectedContext).toBe("prod-eks"); + expect(err.ambientContext).toBe("staging-eks"); + expect(err.message).toContain('environment "prod"'); + expect(err.message).toContain('"prod-eks"'); + expect(err.message).toContain('"staging-eks"'); }); test("bound for a different environment than the one requested: treated as unbound for this environment", async () => { diff --git a/packages/core/src/kubectl-context.ts b/packages/core/src/kubectl-context.ts index c4a2b05561..77946a4fae 100644 --- a/packages/core/src/kubectl-context.ts +++ b/packages/core/src/kubectl-context.ts @@ -38,11 +38,13 @@ export interface K8sConfigShape { } /** - * Thrown when an environment declares a cluster binding but the ambient - * kubectl context disagrees with it. Refusing here — instead of silently - * observing whichever cluster is ambient — is the fix for #1100: a - * wrong-cluster read reports every declared resource as missing, which #1089 - * then classifies as a confident (and wrong) list of `create` actions. + * Historically thrown when an environment declared a cluster binding but the + * ambient kubectl context disagreed with it (#1100/#1155). As of #1488 the + * resolver no longer polices ambient at all — a declared binding is USED, not + * checked — so {@link resolveClusterTarget} never throws this anymore. The + * class stays exported because the k8s lexicon's read/write paths still catch + * it (converting a refusal into NOT-OBSERVED), and a custom connector may + * still throw it to get that classification. */ export class ClusterBindingMismatchError extends Error { constructor( @@ -77,8 +79,11 @@ export interface ResolvedClusterTarget { * `kubectl config current-context`; the k8s lexicon's typed API client * (chant #1074) supplies one that reads the parsed kubeconfig instead, so a * client that never needs the `kubectl` binary does not acquire a dependency - * on it just to check the binding. Both answer the same question, so the - * refusal semantics below are identical either way. + * on it just to check the binding. + * + * As of #1488 the resolver itself no longer reads ambient (a declared binding + * is used directly), so this hook only matters to callers that surface the + * ambient context in their own messages. */ export type AmbientContextReader = () => Promise; @@ -112,13 +117,16 @@ export interface ResolveClusterTargetOptions { * - No binding declared: returns `{ source: "ambient" }` — unchanged * behavior — but logs a visible warning identifying the caller and * environment, so the fallback is never silent (#1100 acceptance). - * - Binding declared and the ambient context agrees (or ambient can't be - * determined): returns `{ context: bound, source: "bound" }`. Callers - * should pass this context explicitly on every kubectl invocation rather - * than relying on it also being ambient. - * - Binding declared and the ambient context disagrees: throws - * {@link ClusterBindingMismatchError} — a loud refusal instead of quietly - * reading the wrong cluster. + * - Binding declared: returns `{ context: bound, source: "bound" }`, + * regardless of what is ambient (#1488). The declared binding is the + * selection, not a check: callers pass this context explicitly on every + * read and write, so whichever cluster `kubectl` happens to be pointed at + * is irrelevant. Any k3d cluster another project creates mid-session used + * to steal the ambient context and turn a healthy estate grey with + * `read-failed` as the only explanation; now it cannot. A bound context + * that is absent from the kubeconfig fails downstream in the typed client + * with an error naming the context and the `k8s.profiles..context` + * binding — never by falling back to ambient. */ export async function resolveClusterTarget( config: Record, @@ -141,11 +149,6 @@ export async function resolveClusterTarget( return { source: "ambient" }; } - const ambient = await (options.ambientContext ?? currentAmbientContext)(); - if (ambient && ambient !== bound) { - throw new ClusterBindingMismatchError(environment, bound, ambient); - } - return { context: bound, source: "bound" }; }