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
171 changes: 171 additions & 0 deletions lexicons/k8s/src/api/owner-chain.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import { describe, test, expect, vi } from "vitest";
import { resolveK8sOwnerChain } from "./owner-chain";
import type { K8sObject } from "@intentius/chant-k8s-client";

function pod(uid: string, ownerRefs?: Array<Record<string, unknown>>): K8sObject {
return {
apiVersion: "v1",
kind: "Pod",
metadata: { name: "p", namespace: "prod", uid, ...(ownerRefs ? { ownerReferences: ownerRefs } : {}) },
};
}

function ownerRef(kind: string, name: string, uid: string, controller = true): Record<string, unknown> {
return { apiVersion: "apps/v1", kind, name, uid, controller };
}

describe("resolveK8sOwnerChain (#1077)", () => {
test("no ownerReferences at all → unowned", async () => {
const reader = { readIfPresent: vi.fn() };
const result = await resolveK8sOwnerChain(pod("pod-uid"), {
declaredByUid: new Map(),
reader,
namespace: "prod",
});
expect(result).toEqual({ root: "unowned" });
expect(reader.readIfPresent).not.toHaveBeenCalled();
});

test("owner uid matches a declared entity directly → declared, no extra reads", async () => {
const reader = { readIfPresent: vi.fn() };
const result = await resolveK8sOwnerChain(pod("pod-uid", [ownerRef("Deployment", "web", "deploy-uid")]), {
declaredByUid: new Map([["deploy-uid", "web"]]),
reader,
namespace: "prod",
});
expect(result).toEqual({ root: "declared", entity: "web" });
expect(reader.readIfPresent).not.toHaveBeenCalled();
});

test("Pod → ReplicaSet (undeclared, read live) → Deployment (declared) resolves through the intermediate hop", async () => {
const replicaSet: K8sObject = {
apiVersion: "apps/v1",
kind: "ReplicaSet",
metadata: {
name: "web-7d9f8c9c8",
namespace: "prod",
uid: "rs-uid",
ownerReferences: [ownerRef("Deployment", "web", "deploy-uid")],
},
};
const reader = { readIfPresent: vi.fn().mockResolvedValue(replicaSet) };
const result = await resolveK8sOwnerChain(pod("pod-uid", [ownerRef("ReplicaSet", "web-7d9f8c9c8", "rs-uid")]), {
declaredByUid: new Map([["deploy-uid", "web"]]),
reader,
namespace: "prod",
});
expect(result).toEqual({ root: "declared", entity: "web" });
expect(reader.readIfPresent).toHaveBeenCalledTimes(1);
expect(reader.readIfPresent).toHaveBeenCalledWith({
apiVersion: "apps/v1",
kind: "ReplicaSet",
name: "web-7d9f8c9c8",
namespace: "prod",
});
});

test("chain resolves fully to a live, undeclared root → foreign", async () => {
const replicaSet: K8sObject = {
apiVersion: "apps/v1",
kind: "ReplicaSet",
metadata: { name: "other-rs", namespace: "prod", uid: "rs-uid" }, // no further owner
};
const reader = { readIfPresent: vi.fn().mockResolvedValue(replicaSet) };
const result = await resolveK8sOwnerChain(pod("pod-uid", [ownerRef("ReplicaSet", "other-rs", "rs-uid")]), {
declaredByUid: new Map(), // nothing declared at all
reader,
namespace: "prod",
});
expect(result).toEqual({ root: "foreign" });
});

test("an owner read that 404s (readIfPresent → undefined) is conservative unknown, not foreign", async () => {
const reader = { readIfPresent: vi.fn().mockResolvedValue(undefined) };
const result = await resolveK8sOwnerChain(pod("pod-uid", [ownerRef("ReplicaSet", "gone-rs", "rs-uid")]), {
declaredByUid: new Map(),
reader,
namespace: "prod",
});
expect(result).toEqual({ root: "unknown" });
});

test("an owner read that throws (RBAC denial, transport error) is conservative unknown", async () => {
const reader = { readIfPresent: vi.fn().mockRejectedValue(new Error("Forbidden")) };
const result = await resolveK8sOwnerChain(pod("pod-uid", [ownerRef("ReplicaSet", "denied-rs", "rs-uid")]), {
declaredByUid: new Map(),
reader,
namespace: "prod",
});
expect(result).toEqual({ root: "unknown" });
});

test("a cycle (A owns B, B owns A) terminates and classifies unknown rather than looping forever", async () => {
const objA: K8sObject = {
apiVersion: "v1",
kind: "Widget",
metadata: { name: "a", namespace: "prod", uid: "a-uid", ownerReferences: [ownerRef("Widget", "b", "b-uid")] },
};
const objB: K8sObject = {
apiVersion: "v1",
kind: "Widget",
metadata: { name: "b", namespace: "prod", uid: "b-uid", ownerReferences: [ownerRef("Widget", "a", "a-uid")] },
};
const reader = {
readIfPresent: vi.fn(async ({ name }: { name: string }) => (name === "a" ? objA : objB)),
};
const start: K8sObject = {
apiVersion: "v1",
kind: "Widget",
metadata: { name: "start", namespace: "prod", uid: "start-uid", ownerReferences: [ownerRef("Widget", "a", "a-uid")] },
};
const result = await resolveK8sOwnerChain(start, { declaredByUid: new Map(), reader, namespace: "prod" });
expect(result).toEqual({ root: "unknown" });
});

test("respects a custom maxDepth, fetching no more than maxDepth + 1 objects", async () => {
// A chain 5 hops deep, but bounded to 2 — never reaches the declared root.
const objects: Record<string, K8sObject> = {};
for (let i = 0; i < 5; i++) {
objects[`n${i}`] = {
apiVersion: "v1",
kind: "Widget",
metadata: { name: `n${i}`, namespace: "prod", uid: `uid-${i}`, ownerReferences: [ownerRef("Widget", `n${i + 1}`, `uid-${i + 1}`)] },
};
}
const reader = {
readIfPresent: vi.fn(async ({ name }: { name: string }) => objects[name]),
};
const start: K8sObject = {
apiVersion: "v1",
kind: "Widget",
metadata: { name: "start", namespace: "prod", uid: "start-uid", ownerReferences: [ownerRef("Widget", "n0", "uid-0")] },
};
const result = await resolveK8sOwnerChain(start, {
declaredByUid: new Map([["uid-4", "deep-entity"]]), // reachable, but past the bound
reader,
namespace: "prod",
maxDepth: 2,
});
expect(result).toEqual({ root: "unknown" });
expect(reader.readIfPresent.mock.calls.length).toBeLessThanOrEqual(3); // maxDepth + 1
});

test("a starting object without a uid cannot be classified — unknown", async () => {
const reader = { readIfPresent: vi.fn() };
const noUid: K8sObject = { apiVersion: "v1", kind: "Pod", metadata: { name: "p", namespace: "prod" } };
const result = await resolveK8sOwnerChain(noUid, { declaredByUid: new Map(), reader, namespace: "prod" });
expect(result).toEqual({ root: "unknown" });
expect(reader.readIfPresent).not.toHaveBeenCalled();
});

test("picks the controller:true owner reference when several are present", async () => {
const reader = { readIfPresent: vi.fn() };
const refs = [ownerRef("OtherOwner", "shared", "shared-uid", false), ownerRef("Deployment", "web", "deploy-uid", true)];
const result = await resolveK8sOwnerChain(pod("pod-uid", refs), {
declaredByUid: new Map([["deploy-uid", "web"]]),
reader,
namespace: "prod",
});
expect(result).toEqual({ root: "declared", entity: "web" });
});
});
144 changes: 144 additions & 0 deletions lexicons/k8s/src/api/owner-chain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/**
* Resolving a live Kubernetes object's `ownerReferences` chain up to a
* declared, chant-observed entity (chant #1077).
*
* There is no server-side "who ultimately owns this object" query — Kubernetes'
* own garbage collector does not have one either; it walks the same chain one
* hop at a time, reading each intermediate owner. A Pod's `ownerReferences`
* names its ReplicaSet, which chant never declared; the ReplicaSet's own
* `ownerReferences` names the Deployment, which is declared. Reaching that
* declared entity takes reading the ReplicaSet in between.
*
* This module's only job is assembling that chain — fetching each hop through
* the typed client, bounded and cycle-guarded so a corrupt or adversarial
* chain cannot hang an observation. The bounded/cycle-safe *interpretation* of
* the assembled chain (declared / unowned / foreign / unknown) is core's
* `classifyOwnerChain` (`@intentius/chant/owner-chain`) — the issue's own
* division of labor: core owns the category, the lexicon supplies the chain.
*/

import type { K8sClient, K8sObject } from "@intentius/chant-k8s-client";
import {
classifyOwnerChain,
DEFAULT_MAX_OWNER_CHAIN_DEPTH,
type OwnerChainNode,
type OwnerChainVerdict,
} from "@intentius/chant/owner-chain";

interface RawOwnerRef {
apiVersion?: string;
kind?: string;
name?: string;
uid?: string;
controller?: boolean;
}

function ownerRefs(obj: K8sObject): RawOwnerRef[] {
const refs = obj.metadata?.ownerReferences;
return Array.isArray(refs) ? (refs as RawOwnerRef[]) : [];
}

/**
* The reference Kubernetes' own garbage collector treats as the controlling
* parent: the entry with `controller: true`, else the first. An object with
* several owner references (rare — usually a shared, non-controller owner
* alongside the controlling one) is walked through its controller, matching
* what actually recreates the object were it deleted.
*/
function controllingRef(obj: K8sObject): RawOwnerRef | undefined {
const refs = ownerRefs(obj);
return refs.find((r) => r.controller === true) ?? refs[0];
}

/** The client surface this module needs — a single object read, addressed by
* an owner reference's own coordinates. */
export type OwnerChainReader = Pick<K8sClient, "readIfPresent">;

export interface ResolveOwnerChainOptions {
/** uid → declared chant entity name, from this observation's own resolved entities. */
declaredByUid: ReadonlyMap<string, string>;
/** Reads each intermediate owner. */
reader: OwnerChainReader;
/**
* Namespace the starting object lives in. Owner references are same-namespace
* only — a namespaced object cannot be owned by an object in another
* namespace, the same rule Kubernetes' own garbage collector enforces —so
* every hop is read in this namespace.
*/
namespace: string | undefined;
maxDepth?: number;
}

/**
* Walk `obj`'s owner-reference chain up to a declared entity, a foreign root,
* or a bound (#1077). Fetches at most `maxDepth + 1` objects (the starting
* object plus up to `maxDepth` ancestors) — the same bound `classifyOwnerChain`
* enforces when interpreting the result, so nothing is fetched that the
* interpretation would not have used anyway.
*/
export async function resolveK8sOwnerChain(
obj: K8sObject,
options: ResolveOwnerChainOptions,
): Promise<OwnerChainVerdict> {
const startUid = obj.metadata?.uid;
if (!startUid) return { root: "unknown" };

const maxDepth = options.maxDepth ?? DEFAULT_MAX_OWNER_CHAIN_DEPTH;
const nodes = new Map<string, OwnerChainNode>();
const visited = new Set<string>();

let uid: string | undefined = startUid;
let object: K8sObject | undefined = obj;

for (let depth = 0; uid !== undefined && depth <= maxDepth; depth++) {
if (visited.has(uid)) break; // cycle — classifyOwnerChain reads it off `nodes`
visited.add(uid);

const declaredEntity = options.declaredByUid.get(uid);
if (declaredEntity) {
nodes.set(uid, { declaredEntity });
break;
}
if (!object) {
nodes.set(uid, { ownerUnreadable: true });
break;
}

const ref = controllingRef(object);
if (!ref?.uid || !ref.kind || !ref.apiVersion || !ref.name) {
nodes.set(uid, {}); // no further owner — a real, live root
break;
}
nodes.set(uid, { ownerId: ref.uid });

if (visited.has(ref.uid)) {
// About to cycle back to an already-visited node — let the loop's own
// check classify it next iteration rather than issuing a wasted read.
uid = ref.uid;
continue;
}
if (options.declaredByUid.has(ref.uid)) {
// Already known to be a declared entity from this observation's own
// resolved set — no need to read it, the next iteration resolves it
// from `declaredByUid` directly.
uid = ref.uid;
object = undefined;
continue;
}

try {
object = await options.reader.readIfPresent({
apiVersion: ref.apiVersion,
kind: ref.kind,
name: ref.name,
namespace: options.namespace,
});
} catch {
object = undefined;
}
if (!object) nodes.set(ref.uid, { ownerUnreadable: true });
uid = ref.uid;
}

return classifyOwnerChain(startUid, nodes, maxDepth);
}
Loading