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
54 changes: 27 additions & 27 deletions plugins/stewards/evidence.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { describe, expect, it } from "vitest";
import { createEvidenceReader, EVIDENCE_RECENT_JOBS, type EvidenceKubectl } from "./evidence.js";
import { EvidenceUnavailableError } from "./triage.js";
import type { KubectlResult } from "./kubectl.js";
import { evidenceKubectlRefusal, type KubectlResult } from "./kubectl.js";

const NAMESPACE = "bithub";
const JOB = "bithub-deel-sync-28934567";
const KUBECONFIG = "apiVersion: v1\n# EVIDENCE_MARKER_9f3a\nkind: Config\n";
const NAMESPACES = [NAMESPACE] as const;

const rawJob = (over: Record<string, unknown> = {}) => ({
metadata: { name: JOB, namespace: NAMESPACE },
Expand Down Expand Up @@ -42,16 +42,14 @@ const rawSuccess = {

const ok = (stdout: string): KubectlResult => ({ exitCode: 0, stdout, stderr: "" });

/** A fake kubectl that records every call and its kubeconfig. */
/** A fake kubectl that records every call. */
function fake(answer: (args: string[]) => KubectlResult) {
const calls: string[][] = [];
const kubeconfigs: string[] = [];
const run: EvidenceKubectl = async (args, kubeconfig) => {
const run: EvidenceKubectl = async (args) => {
calls.push(args);
kubeconfigs.push(kubeconfig);
return answer(args);
};
return { calls, kubeconfigs, run };
return { calls, run };
}

const happyAnswer = (args: string[]): KubectlResult => {
Expand All @@ -64,46 +62,49 @@ const happyAnswer = (args: string[]): KubectlResult => {

const reader = (over: Partial<Parameters<typeof createEvidenceReader>[0]> = {}) => {
const k = fake(happyAnswer);
const r = createEvidenceReader({ namespace: NAMESPACE, kubeconfig: KUBECONFIG, kubectl: k.run, ...over });
const r = createEvidenceReader({ namespaces: NAMESPACES, kubectl: k.run, ...over });
return { reader: r, ...k };
};

describe("the evidence reader", () => {
it("reads the Job, its pods, Warning events, one container's logs and recent successful Jobs", async () => {
const { reader: r, kubeconfigs } = reader();
const { reader: r, calls } = reader();
expect((await r.job(NAMESPACE, JOB))?.value).toMatchObject({ name: JOB, outcome: "failed", reason: "BackoffLimitExceeded", failed: 3 });
expect((await r.pods(NAMESPACE, JOB)).map((p) => p.value.name)).toEqual([`${JOB}-abc`]);
expect((await r.events(NAMESPACE, JOB)).map((e) => e.reason)).toEqual(["BackoffLimitExceeded", "FailedScheduling"]);
const logs = await r.logs(NAMESPACE, `${JOB}-abc`, "sync");
expect(logs?.lines).toEqual(["first line", "last line token=[redacted]"]);
expect((await r.recentSuccessfulJobs(NAMESPACE, "2026-11-27T22:00:00Z")).map((j) => j.value.name)).toEqual([rawSuccess.metadata.name]);
expect(kubeconfigs).toEqual(Array(6).fill(KUBECONFIG.trim()));
// Every call is one the strict evidence gate admits, and none names a kubeconfig.
expect(calls.every((a) => evidenceKubectlRefusal(a, NAMESPACES) === null)).toBe(true);
expect(calls.every((a) => !a.some((x) => x.startsWith("--kubeconfig")))).toBe(true);
});

it("treats a missing Job and missing logs as a missing read, not a refusal", async () => {
const k = fake((args) => (args[0] === "logs" ? { exitCode: 1, stdout: "", stderr: `Error from server (NotFound): pods "${JOB}-abc" not found` } : ok(JSON.stringify({ items: [] }))));
const r = createEvidenceReader({ namespace: NAMESPACE, kubeconfig: KUBECONFIG, kubectl: k.run });
const r = createEvidenceReader({ namespaces: NAMESPACES, kubectl: k.run });
expect(await r.job(NAMESPACE, JOB)).toBeNull();
expect(await r.logs(NAMESPACE, `${JOB}-abc`, "sync")).toBeNull();
});

it("throws EvidenceUnavailableError with no kubeconfig set, and never calls kubectl", async () => {
for (const kubeconfig of [null, "", " "]) {
const { reader: r, calls } = reader({ kubeconfig });
await expect(r.job(NAMESPACE, JOB)).rejects.toBeInstanceOf(EvidenceUnavailableError);
await expect(r.pods(NAMESPACE, JOB)).rejects.toBeInstanceOf(EvidenceUnavailableError);
expect(calls).toEqual([]);
}
it("is off with no pilot namespace, so every read is unavailable and kubectl never runs", async () => {
const { reader: r, calls } = reader({ namespaces: [] });
await expect(r.job(NAMESPACE, JOB)).rejects.toMatchObject({ name: "EvidenceUnavailableError", what: "evidence" });
await expect(r.pods(NAMESPACE, JOB)).rejects.toBeInstanceOf(EvidenceUnavailableError);
await expect(r.events(NAMESPACE, JOB)).rejects.toBeInstanceOf(EvidenceUnavailableError);
await expect(r.logs(NAMESPACE, `${JOB}-abc`, "sync")).rejects.toBeInstanceOf(EvidenceUnavailableError);
await expect(r.recentSuccessfulJobs(NAMESPACE, "2026-11-27T22:00:00Z")).rejects.toBeInstanceOf(EvidenceUnavailableError);
expect(calls).toEqual([]);
});

it("throws EvidenceUnavailableError on a forbidden read and never falls back", async () => {
const k = fake(() => ({ exitCode: 1, stdout: "", stderr: `Error from server (Forbidden): jobs "${JOB}" is forbidden: User "system:anonymous" cannot get resource "jobs"` }));
const r = createEvidenceReader({ namespace: NAMESPACE, kubeconfig: KUBECONFIG, kubectl: k.run });
const r = createEvidenceReader({ namespaces: NAMESPACES, kubectl: k.run });
await expect(r.job(NAMESPACE, JOB)).rejects.toMatchObject({ name: "EvidenceUnavailableError", what: "permission" });
await expect(r.recentSuccessfulJobs(NAMESPACE, "2026-11-27T22:00:00Z")).rejects.toBeInstanceOf(EvidenceUnavailableError);
});

it("refuses a namespace other than the one the identity is scoped to", async () => {
it("refuses a namespace outside the configured pilot list, and never calls kubectl", async () => {
const { reader: r, calls } = reader();
await expect(r.job("some-other-namespace", JOB)).rejects.toMatchObject({ name: "EvidenceUnavailableError", what: "namespace" });
expect(calls).toEqual([]);
Expand All @@ -115,20 +116,19 @@ describe("the evidence reader", () => {
expect(calls).toEqual([]);
});

it("never puts the kubeconfig value in an error or the output, and redacts a token from kubectl", async () => {
it("never puts a token from kubectl in an error, and redacts one in the output", async () => {
const k = fake(() => ({ exitCode: 1, stdout: "", stderr: "Error from server (Forbidden): token=sk_live_secret\n" }));
const r = createEvidenceReader({ namespace: NAMESPACE, kubeconfig: KUBECONFIG, kubectl: k.run });
const r = createEvidenceReader({ namespaces: NAMESPACES, kubectl: k.run });
let caught: unknown;
try {
await r.job(NAMESPACE, JOB);
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(EvidenceUnavailableError);
const message = (caught as Error).message;
expect(message).not.toContain("EVIDENCE_MARKER_9f3a");
expect(message).not.toContain(KUBECONFIG);
expect(message).toContain("[redacted]");
expect((caught as Error).message).toContain("[redacted]");
const logs = createEvidenceReader({ namespaces: NAMESPACES, kubectl: async () => ok("token=sk_live_secret\n") });
expect((await logs.logs(NAMESPACE, `${JOB}-abc`, "sync"))?.lines).toEqual(["token=[redacted]"]);
});

it("caps the recent successful Jobs it returns", async () => {
Expand All @@ -137,7 +137,7 @@ describe("the evidence reader", () => {
status: { conditions: [{ type: "Complete", status: "True", reason: "Completed", lastTransitionTime: `2026-11-27T23:${String(i).padStart(2, "0")}:00Z` }], completionTime: `2026-11-27T23:${String(i).padStart(2, "0")}:00Z`, succeeded: 1, failed: 0, active: 0 },
}));
const k = fake(() => ok(JSON.stringify({ items: many })));
const r = createEvidenceReader({ namespace: NAMESPACE, kubeconfig: KUBECONFIG, kubectl: k.run });
const r = createEvidenceReader({ namespaces: NAMESPACES, kubectl: k.run });
const jobs = await r.recentSuccessfulJobs(NAMESPACE, "2026-11-27T00:00:00Z");
expect(jobs).toHaveLength(EVIDENCE_RECENT_JOBS);
expect(jobs[0]!.value.finishedAt).toBe("2026-11-27T23:24:00Z");
Expand Down
54 changes: 25 additions & 29 deletions plugins/stewards/evidence.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
// The real `EvidenceReader` behind the Job-failure triage reply (BB-419).
//
// The reply's composer (triage.ts, BB-419) is pure; this is the part that
// reads the cluster. It reads one namespace through a separately scoped,
// read-only kubeconfig that reaches the plugin as the `opsEvidenceKubeconfig`
// secret setting, never the developer's ambient one. Every call passes the
// same gate as the ops kind (`kubectlRefusal`: get, describe, logs); the host
// entry (host.ts) writes the kubeconfig to a private temp file and passes only
// its path, so the value is never an argv element, a log line, a wake or an
// error. A missing setting, a namespace other than the scoped one, or a
// refused/forbidden read throws `EvidenceUnavailableError`, which the composer
// labels "evidence unavailable"; it never falls back to the ambient identity.
// reads the cluster. The owner decided the reader needs no separate credential:
// it reads one of the configured pilot namespaces with the kubectl access the
// server's threads already have, never a value from the plugin. Because that
// ambient identity is not read-only, every call passes `evidenceKubectlRefusal`,
// a strict allowlist on top of the ops kind's `kubectlRefusal`: get on jobs,
// pods and events, and logs (pods/log), in one configured namespace, `-o json`
// only. A namespace outside the pilot list, an empty list (the reader is off
// until one is configured), or a refused/forbidden read throws
// `EvidenceUnavailableError`, which the composer labels "evidence unavailable".
//
// Alert, Job, event and log text is untrusted data. Log lines and error text
// pass through `redactLine`/`scrubCredentials` before they leave here.
import { EvidenceUnavailableError, type EvidenceItem, type EvidenceReader, type LogEvidence } from "./triage.js";
import { eventsOf, jobsOf, podsOf, redactLine, scrubCredentials, type OpsEvent, type OpsJob, type OpsPod } from "./ops.js";
import { kubectlError, type KubectlResult } from "./kubectl.js";
import { evidenceKubectlRefusal, kubectlError, type KubectlResult } from "./kubectl.js";

/** The lines one log read returns, and how long one line may be. */
export const EVIDENCE_LOG_TAIL = 50;
Expand All @@ -25,34 +25,30 @@ export const EVIDENCE_RECENT_JOBS = 20;
/** A Kubernetes resource name (Job, pod or container): the API's own shape. */
const K8S_NAME = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/u;

/** Runs kubectl on the project's machine, with the evidence kubeconfig. */
export type EvidenceKubectl = (args: string[], evidenceKubeconfig: string) => Promise<KubectlResult>;
/** Runs kubectl on the project's machine, with the machine's own ambient config. */
export type EvidenceKubectl = (args: string[]) => Promise<KubectlResult>;

/**
* A read-only `EvidenceReader` for one namespace. `kubeconfig` is the
* `opsEvidenceKubeconfig` secret setting; when it is unset every read throws
* `EvidenceUnavailableError`, so the reply labels evidence unavailable rather
* than reading with the developer's ambient kubeconfig. `kubectl` is the host
* entry, which writes the kubeconfig to a private temp file and passes its
* path.
* A read-only `EvidenceReader` for the configured pilot namespaces. `namespaces`
* is the pilot list the owner opted into; an empty list is the off state, so
* every read throws `EvidenceUnavailableError` and no kubectl runs until a
* namespace is configured. `kubectl` is the host entry, which applies the ops
* gate; this reader applies `evidenceKubectlRefusal` first.
*/
export function createEvidenceReader(input: { namespace: string; kubeconfig: string | null | undefined; kubectl: EvidenceKubectl }): EvidenceReader {
const scoped = input.namespace.trim();
export function createEvidenceReader(input: { namespaces: readonly string[]; kubectl: EvidenceKubectl }): EvidenceReader {
const namespaces = input.namespaces.map((n) => n.trim()).filter((n) => n !== "");
const refuse: (what: string, message: string) => never = (what, message) => {
throw new EvidenceUnavailableError(what, scrubCredentials(message));
};
const kubeconfig = (): string => {
const value = input.kubeconfig?.trim();
if (value === undefined || value === "") refuse("evidence kubeconfig", "no read-only evidence kubeconfig is set, so evidence is unavailable; the developer's own kubeconfig is never used for evidence");
return value;
};
const run = async (namespace: string, args: string[]): Promise<KubectlResult> => {
const value = kubeconfig();
if (namespace !== scoped) refuse("namespace", `the evidence identity is scoped to ${scoped === "" ? "(no namespace)" : scoped}, not ${namespace}`);
return input.kubectl(args, value);
if (namespaces.length === 0) refuse("evidence", "no pilot namespace is configured, so the Job-failure triage reply is off and evidence is unavailable");
if (!namespaces.includes(namespace)) refuse("namespace", `the evidence reader is configured for ${namespaces.join(", ")}, not ${namespace}`);
const refused = evidenceKubectlRefusal(args, namespaces);
if (refused !== null) refuse("command", refused);
return input.kubectl(args);
};
const failed = (what: string, r: KubectlResult): never => {
if (/\bforbidden\b/iu.test(r.stderr)) refuse("permission", `the read-only evidence identity is not granted ${what} (${kubectlError(r)})`);
if (/\bforbidden\b/iu.test(r.stderr)) refuse("permission", `the ambient kubectl identity is not granted ${what} (${kubectlError(r)})`);
refuse(what, kubectlError(r));
};
const json = async (namespace: string, args: string[]): Promise<unknown> => {
Expand Down
11 changes: 1 addition & 10 deletions plugins/stewards/host-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,7 @@ const projectFilePath = z.string().min(1).max(300).regex(/^[A-Za-z0-9._-]+(?:\/[

export const hostContract = defineRpcContract({
opsKubectl: {
input: z
.object({
args: z.array(z.string().min(1).max(300)).min(1).max(30),
timeoutMs: z.number().int().min(1000).max(120_000),
// BB-419: the evidence reader's read-only kubeconfig. The host writes
// it to a private temp file and passes only its path; it is never an
// argv element. Callers do not set it except the evidence reader.
evidenceKubeconfig: z.string().min(1).max(65_536).optional(),
})
.strict(),
input: z.object({ args: z.array(z.string().min(1).max(300)).min(1).max(30), timeoutMs: z.number().int().min(1000).max(120_000) }).strict(),
output: z.object({ exitCode: z.number().int(), stdout: z.string(), stderr: z.string(), missing: z.boolean() }).strict(),
},
gitProjectFiles: {
Expand Down
48 changes: 6 additions & 42 deletions plugins/stewards/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,59 +4,23 @@
// reads a project checkout's `.bb` from `origin/<default>` for the native
// project source (project-git.ts).
import { execFile } from "node:child_process";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { experimental_defineHostEntry, experimental_sanitizeInheritedChildProcessEnv } from "@get-bb/plugin-sdk/host";
import { hostContract } from "./host-contract.js";
import { kubectlRefusal, type KubectlGate } from "./kubectl.js";
import { kubectlRefusal } from "./kubectl.js";
import { readProjectGit } from "./project-git.js";

/** A namespace's pods as JSON can be large; past this, kubectl's output is cut and fails to parse rather than flooding the call. */
const MAX_OUTPUT_BYTES = 16 * 1024 * 1024;

/**
* The evidence reader's read-only kubeconfig, written to a private temp file
* for one kubectl call and removed when it returns (BB-419). Only the temp
* file's path reaches argv, never the value; `kubectlRefusal` allows that one
* path and refuses every caller-supplied `--kubeconfig`. Null when the file
* could not be written, which the caller reports as a refusal, not a fallback.
*/
export function prepareEvidenceKubeconfig(kubeconfig: string): { path: string; dir: string } | null {
try {
const dir = mkdtempSync(join(tmpdir(), "bb-evidence-"));
const path = join(dir, "kubeconfig");
writeFileSync(path, kubeconfig, { mode: 0o600 });
return { path, dir };
} catch {
return null;
}
}

export function runKubectlHere(args: string[], timeoutMs: number, command = "kubectl", evidenceKubeconfig?: string): Promise<{ exitCode: number; stdout: string; stderr: string; missing: boolean }> {
let runArgs = args;
let evidence: { path: string; dir: string } | null = null;
if (evidenceKubeconfig !== undefined) {
// A present but blank value is a refusal, never a fall-through to the
// machine's ambient kubeconfig.
if (evidenceKubeconfig.trim() === "") return Promise.resolve({ exitCode: 126, stdout: "", stderr: "the read-only evidence kubeconfig is empty", missing: false });
evidence = prepareEvidenceKubeconfig(evidenceKubeconfig);
if (evidence === null) return Promise.resolve({ exitCode: 126, stdout: "", stderr: "the read-only evidence kubeconfig could not be prepared", missing: false });
runArgs = [...args, `--kubeconfig=${evidence.path}`];
}
const gate: KubectlGate = evidence === null ? {} : { evidenceKubeconfigPath: evidence.path };
const refused = kubectlRefusal(runArgs, gate);
if (refused !== null) {
if (evidence !== null) rmSync(evidence.dir, { recursive: true, force: true });
return Promise.resolve({ exitCode: 126, stdout: "", stderr: refused, missing: false });
}
export function runKubectlHere(args: string[], timeoutMs: number, command = "kubectl"): Promise<{ exitCode: number; stdout: string; stderr: string; missing: boolean }> {
const refused = kubectlRefusal(args);
if (refused !== null) return Promise.resolve({ exitCode: 126, stdout: "", stderr: refused, missing: false });
return new Promise((resolve) => {
execFile(
command,
runArgs,
args,
{ timeout: timeoutMs, maxBuffer: MAX_OUTPUT_BYTES, env: { ...experimental_sanitizeInheritedChildProcessEnv({ env: process.env }), NO_COLOR: "1" }, windowsHide: true },
(error, stdout, stderr) => {
if (evidence !== null) rmSync(evidence.dir, { recursive: true, force: true });
const e = error as (Omit<NodeJS.ErrnoException, "code"> & { code?: string | number; killed?: boolean }) | null;
if (e?.code === "ENOENT") return resolve({ exitCode: 127, stdout: "", stderr: `${command}: not found`, missing: true });
const exitCode = e === null ? 0 : typeof e.code === "number" ? e.code : 1;
Expand All @@ -69,7 +33,7 @@ export function runKubectlHere(args: string[], timeoutMs: number, command = "kub
export default experimental_defineHostEntry({
contract: hostContract,
handlers: {
opsKubectl: ({ args, timeoutMs, evidenceKubeconfig }) => runKubectlHere(args, timeoutMs, "kubectl", evidenceKubeconfig),
opsKubectl: ({ args, timeoutMs }) => runKubectlHere(args, timeoutMs),
gitProjectFiles: ({ path, files, fetch }) => readProjectGit({ path, files, fetch }),
},
});
Loading