diff --git a/docs/self-host/model-providers.md b/docs/self-host/model-providers.md index 81f9c8cee..52c291c36 100644 --- a/docs/self-host/model-providers.md +++ b/docs/self-host/model-providers.md @@ -73,7 +73,7 @@ The deploy config's `models` settings are only the first-boot default. Once you A new release can call a model your install hasn't used before. Each release publishes `models.json` with the models it calls and their Bedrock ids for every prefix. It is made from the code, so it can't miss one. It is listed in the release's signed `SHA256SUMS`, and your install only reads it through a small read-only build (`-release-check`) that checks the signature first, exactly like an update does; a file that doesn't match is never used. -Before the updater applies a release, automatically or with **Update now**, it makes one test call to each of those models (plus the ones your config names) through your current provider: +Before a release is applied (automatically, with **Update now**, or with `update` from your machine), CoderHelm makes one test call to each of those models (plus the ones your config names) through your current provider: - **All answer:** the update goes ahead as usual. - **One is refused** (model access off, use case form missing, Marketplace terms not accepted or still processing, IAM, or the model isn't offered in your region): the update doesn't start. **Settings, System** and **Setup** show **Update to vX needs your action** with the model, the fix and the console link. Install admins get one email (and a post to `updates.webhookUrl` if set). diff --git a/docs/self-host/updates.md b/docs/self-host/updates.md index efe5fde8a..d4f9339bd 100644 --- a/docs/self-host/updates.md +++ b/docs/self-host/updates.md @@ -51,6 +51,8 @@ An update starts only when all of these hold: auto-update is on, the hour is the Each release lists the models it calls (`models.json`, made from the code and covered by the signed `SHA256SUMS`). The updater reads it only after a read-only build has checked the release's signature and the file's checksum; until then the update waits. Before an update, automatic or **Update now**, the updater asks the worker to make one test call to each, through your current provider (Bedrock or Anthropic keys). If one is refused, the update waits: **Settings, System** and **Setup** say **Update to vX needs your action** with the model, the fix and the AWS console link, and admins get one email. The check runs again daily and the update applies by itself once it passes (with auto-update on). **Check again** reruns it now. CoderHelm never accepts model terms or submits forms for you; see [Model providers](./model-providers.md#bedrock-model-access). +`update` from your machine runs the same check after the release's signature passes, through your install's worker, before anything is deployed. A refused model stops it with the fix and the console link. `--skip-model-check` goes on only when the refused model is one the release doesn't call; a model it calls can't be skipped. A rollback skips the check (you go back to models you already used). + ## Update readiness Before you update, **Settings, then System** shows **Update readiness**: the same checks an update makes, run now, each with its fix. diff --git a/infra/lib/updates-stack.ts b/infra/lib/updates-stack.ts index f857f3f9d..6cbe14f8b 100644 --- a/infra/lib/updates-stack.ts +++ b/infra/lib/updates-stack.ts @@ -191,6 +191,20 @@ export class UpdatesStack extends cdk.Stack { `arn:aws:secretsmanager:${this.region}:${this.account}:secret:${cfg.secretName}-??????`, ], })); + // The installer's model check before it deploys (installer/lib/commands.mjs, + // updateModelCheck): the worker makes the test calls; the build only asks, + // and reads which team's key passed the last switch to Anthropic keys. + buildRole.addToPolicy(new iam.PolicyStatement({ + sid: "InstallerModelCheck", + actions: ["lambda:InvokeFunction"], + resources: [`arn:aws:lambda:${this.region}:${this.account}:function:${prefix}-worker`], + })); + buildRole.addToPolicy(new iam.PolicyStatement({ + sid: "ModelCheckSetting", + actions: ["dynamodb:GetItem"], + resources: [props.settingsTable.tableArn], + conditions: { "ForAllValues:StringEquals": { "dynamodb:LeadingKeys": ["SYSTEM"] } }, + })); buildRole.addToPolicy(new iam.PolicyStatement({ sid: "ReportResult", actions: ["lambda:InvokeFunction"], diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index 2f5b70c8c..de8dfa99c 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -667,3 +667,13 @@ test("outbound webhooks: one queue, wired to the worker, sendable by every emitt // The template for the admins' email when an endpoint is turned off. assert.ok(json(t["coderhelm-prod-email"]).includes("coderhelm-prod-webhook-disabled")); }); + +test("the update build may run the installer's model check: ask the worker, read the SYSTEM setting only", () => { + const u = synth(selfHost())["coderhelm-prod-updates"]; + const statements = Object.values(u.findResources("AWS::IAM::Policy")).flatMap((p: any) => p.Properties.PolicyDocument.Statement); + const invoke = statements.find((s: any) => s.Sid === "InstallerModelCheck" && JSON.stringify(s.Resource).includes("coderhelm-prod-worker")); + assert.ok(invoke); + const read = statements.find((s: any) => s.Sid === "ModelCheckSetting"); + assert.deepEqual(read.Action, "dynamodb:GetItem"); + assert.deepEqual(read.Condition, { "ForAllValues:StringEquals": { "dynamodb:LeadingKeys": ["SYSTEM"] } }); +}); diff --git a/installer/lib/cli.mjs b/installer/lib/cli.mjs index ea0ed59bd..7669a62da 100644 --- a/installer/lib/cli.mjs +++ b/installer/lib/cli.mjs @@ -59,6 +59,8 @@ Options --require-signature (always on: a release whose signature can't be checked is refused) --auto-rollback update: deploy the previous release again if health fails --result-file update: write {status, from, to, reason} to this file + --skip-model-check update: go on when only a model the release doesn't call + was refused (a model it calls can never be skipped) --skip-checks init: go on past these failed checks (comma-separated ids, or "all"); without a terminal a failed check stops --verbose Show full error details (they are always saved to a diff --git a/installer/lib/commands.mjs b/installer/lib/commands.mjs index df5d46146..be1f807f7 100644 --- a/installer/lib/commands.mjs +++ b/installer/lib/commands.mjs @@ -3,6 +3,7 @@ import fs from "node:fs"; import path from "node:path"; import crypto from "node:crypto"; +import os from "node:os"; import { checkPrereqs } from "./prereqs.mjs"; import { checkTag, fetchRelease, latestVersion, releasePaths, releasesDir, TAG_RE } from "./release.mjs"; import { openBrowser } from "./github-app.mjs"; @@ -88,6 +89,8 @@ export async function resolveSource(ctx, version) { const paths = await fetchRelease(tag, { runner, fetchImpl: ctx.fetchImpl, log }); return { version: tag, + // The release's model list, read after its signature check (or null). + models: paths.models ?? null, infra: paths.infra, dashboard: paths.dashboard, env: { GATEWAY_ZIP: paths.gatewayZip, WORKER_ZIP: paths.workerZip, MCP_PROXY_DIR: paths.mcpProxyZip }, @@ -373,6 +376,12 @@ export async function update(ctx) { } const src = await resolveSource(ctx, target); + // Every model the release calls must answer through the install's + // provider before anything is deployed (the same check as the updater's). + if (!flags.rollback) { + const note = await updateModelCheck(ctx, loadConfig(flags), src, target); + if (note) result.note = note; + } const migrationsFile = path.join(path.dirname(src.infra), "selfhost", "MIGRATIONS.json"); const notes = migrationNotes(runner.dryRun ? [] : readJson(migrationsFile, { releases: [] }).releases, state.version, target); if (notes.length) log("Release notes this update crosses:"); @@ -417,6 +426,99 @@ export async function update(ctx) { const CHECK_CMD = "npx -y github:CoderHelm/coderhelm-platform doctor"; +/** + * What a release's model check found: blocking failures are models the + * release calls (or the config names), which nothing can skip; the rest + * may be skipped with --skip-model-check, as on the dashboard. + */ +export function modelCheckVerdict(results, required, skip = false) { + const failing = (results ?? []).filter((r) => r.status === "fail"); + const blocking = failing.filter((r) => required.has(r.model)); + const other = failing.filter((r) => !required.has(r.model)); + if (blocking.length) return { ok: false, blocking, other, skippable: false }; + if (other.length && !skip) return { ok: false, blocking, other, skippable: true }; + return { ok: true, blocking, other, skipped: skip ? other.map((r) => r.model) : [] }; +} + +/** The models to test: the release's, plus the config's own (each with its Bedrock ids). */ +export function modelTargets(manifest, cfg) { + const names = [...(manifest.calls ?? [])]; + for (const m of [cfg.models?.primary ?? "claude-opus-5-5", cfg.models?.light ?? "claude-sonnet-5-5"]) { + if (!names.includes(m)) names.push(m); + } + return names.map((model) => ({ model, bedrock_ids: manifest.bedrock?.[model] ?? {} })); +} + +/** + * The model check before an update from this machine: the worker of the + * running install makes one test call per model through the install's + * provider (Settings, System, Models), with its own role or a team's key. + * A refused model stops the update with its fix and the console link. + * Nothing here accepts terms or subscribes: a person does that in the + * AWS console. Returns a note when a check was skipped. + */ +export async function updateModelCheck(ctx, cfg, src, target) { + const { flags, runner, log } = ctx; + log("\nThe models this release calls"); + if (src.models === undefined || src.version === "source") { + log(" skipped: deploying from a checkout, not a signed release"); + return null; + } + if (runner.dryRun) { + log(" [dry run] test each model the release calls through the install's provider"); + return null; + } + if (!src.models) { + log(` ${target} lists no models to check`); + return null; + } + const d = derived(cfg); + const stored = await runner.json("aws", [ + "dynamodb", "get-item", "--table-name", `${d.prefix}-settings`, "--region", cfg.region, + "--key", JSON.stringify({ pk: { S: "SYSTEM" }, sk: { S: "MODELS" } }), "--output", "json", + ], { capture: true, allowFail: true }); + let probeTeam = null; + try { + probeTeam = JSON.parse(stored?.Item?.data?.S ?? "{}").probe_team ?? null; + } catch { + probeTeam = null; + } + const targets = modelTargets(src.models, cfg); + const required = new Set(targets.map((t) => t.model)); + const out = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "ch-models-")), "out.json"); + const r = await runner.run("aws", [ + "lambda", "invoke", "--function-name", `${d.prefix}-worker`, "--region", cfg.region, + "--cli-binary-format", "raw-in-base64-out", + "--payload", JSON.stringify({ model_check: { targets, probe_team: probeTeam } }), out, + ], { capture: true, allowFail: true }); + let answer = null; + try { + answer = r.code === 0 ? JSON.parse(fs.readFileSync(out, "utf8")) : null; + } catch { + answer = null; + } + if (!answer || !Array.isArray(answer.results)) { + throw plainError(`The model check couldn't run (the install's worker, ${d.prefix}-worker, didn't answer), so nothing was changed. Check your AWS credentials for ${cfg.region} and that the install is running, then run the update again.`); + } + for (const a of answer.results) { + if (a.status === "pass") log(` PASS ${a.model}`); + else if (a.status === "skip") log(` SKIP ${a.model}: ${a.detail}`); + else log(` FAIL ${a.model}: ${a.detail}\n How to fix: ${a.fix ?? "see Settings, System, Models"}${a.url ? `\n ${a.url}` : ""}`); + } + const v = modelCheckVerdict(answer.results, required, !!flags.skipModelCheck); + if (v.blocking.length) { + throw plainError(`Update to ${target} needs your action: ${v.blocking.map((b) => b.model).join(" and ")} ${v.blocking.length === 1 ? "was" : "were"} refused (fix above). The release calls ${v.blocking.length === 1 ? "it" : "them"}, so this can't be skipped; nothing was changed. Agreeing to model terms and the Bedrock use case form are done by a person in the AWS console. Then run the update again.`); + } + if (v.skippable) { + throw plainError(`Update to ${target} needs your action: ${v.other.map((b) => b.model).join(" and ")} ${v.other.length === 1 ? "was" : "were"} refused (fix above). This release doesn't call ${v.other.length === 1 ? "it" : "them"}, so --skip-model-check lets the update go ahead; nothing was changed.`); + } + if (v.skipped?.length) { + log(` skipped for ${v.skipped.join(", ")} (--skip-model-check; the release doesn't call ${v.skipped.length === 1 ? "it" : "them"})`); + return `model check skipped for ${v.skipped.join(", ")}`; + } + return null; +} + function plainError(message) { return Object.assign(new Error(message), { plain: true }); } diff --git a/installer/lib/release.mjs b/installer/lib/release.mjs index ce26daecf..23089be74 100644 --- a/installer/lib/release.mjs +++ b/installer/lib/release.mjs @@ -5,6 +5,7 @@ // mcp-proxy.zip the MCP proxy Lambda // dashboard.tar.gz the dashboard (static export, no API URL baked in) // source.tar.gz this repository at the tag (the CDK app) +// models.json the models the release calls (newer releases) // SHA256SUMS checksums of all of the above // SHA256SUMS.sigstore.json cosign's keyless signature of SHA256SUMS, // made by this repository's release workflow @@ -119,8 +120,10 @@ export async function fetchRelease(tag, { runner, fetchImpl = fetch, log = conso } // A release downloaded before is checked again: its files may have changed since. if (fs.existsSync(done)) { - verifySums(dir, parseSums(fs.readFileSync(path.join(dir, "SHA256SUMS"), "utf8"))); - await verifySignature(paths, runner, { tag, log }); + const sums = parseSums(fs.readFileSync(path.join(dir, "SHA256SUMS"), "utf8")); + verifySums(dir, sums); + const method = await verifySignature(paths, runner, { tag, log }); + paths.models = await releaseModels(dir, sums, { runner, fetchImpl, tag, method, log }); return paths; } fs.rmSync(dir, { recursive: true, force: true }); @@ -130,8 +133,10 @@ export async function fetchRelease(tag, { runner, fetchImpl = fetch, log = conso fs.writeFileSync(path.join(dir, n), await download(fetchImpl, tag, n)); } // Checked before anything is unpacked or run. - verifySums(dir, parseSums(fs.readFileSync(path.join(dir, "SHA256SUMS"), "utf8"))); - await verifySignature(paths, runner, { tag, log }); + const sums = parseSums(fs.readFileSync(path.join(dir, "SHA256SUMS"), "utf8")); + verifySums(dir, sums); + const method = await verifySignature(paths, runner, { tag, log }); + paths.models = await releaseModels(dir, sums, { runner, fetchImpl, tag, method, log }); fs.mkdirSync(paths.source, { recursive: true }); fs.mkdirSync(paths.dashboard, { recursive: true }); await runner.run("tar", ["-xzf", path.join(dir, "source.tar.gz"), "-C", paths.source, "--strip-components=1"]); @@ -140,6 +145,41 @@ export async function fetchRelease(tag, { runner, fetchImpl = fetch, log = conso return paths; } +export const MODELS = "models.json"; + +/** + * The release's model manifest (models.json: the models it calls, with their + * Bedrock ids per inference profile prefix), read only after the signature + * check passed, only when the signed SHA256SUMS lists it, and only when it + * matches its checksum (verified with gh, it must carry its own build + * attestation too). null for a signed release that lists none (releases + * from before model manifests). Throws on any mismatch. + */ +export async function releaseModels(dir, sums, { runner, fetchImpl = fetch, tag, method, log = console.log }) { + if (!method) throw new Error("The release's signature wasn't checked: not reading its model list."); + if (!sums[MODELS]) return null; + const file = path.join(dir, MODELS); + if (!fs.existsSync(file)) { + log(` downloading ${MODELS}`); + fs.writeFileSync(file, await download(fetchImpl, tag, MODELS)); + } + verifySums(dir, sums, [MODELS]); + if (method === "attestation") { + const r = await runner.run("gh", attestationArgs(tag, file), { capture: true, allowFail: true }); + if (r.code !== 0) throw new Error(`${MODELS} has no valid build attestation from ${SIGNER_WORKFLOW} on ${tag}: not using it.`); + } + let m; + try { + m = JSON.parse(fs.readFileSync(file, "utf8")); + } catch { + throw new Error(`${MODELS} of ${tag} isn't valid JSON.`); + } + if (!m || !Array.isArray(m.calls) || (m.version !== undefined && m.version !== tag)) { + throw new Error(`${MODELS} of ${tag} isn't a model list for this release.`); + } + return m; +} + export function releasePaths(dir) { return { dir, diff --git a/installer/test/installer.test.mjs b/installer/test/installer.test.mjs index fbc5f2c7d..5f9d2737a 100644 --- a/installer/test/installer.test.mjs +++ b/installer/test/installer.test.mjs @@ -622,3 +622,130 @@ test("domain apply: bad values fail before deploying, and the result file says w assert.equal(JSON.parse(fs.readFileSync(file, "utf8")).domain, null, "config unchanged"); assert.equal(JSON.parse(fs.readFileSync(result, "utf8")).status, "failed"); }); + +// ── The model check before an update from this machine ─────────────────── + +const MANIFEST = { + schema: 1, version: "v1.1.0", + calls: ["claude-opus-5-5", "claude-sonnet-5-5"], + bedrock: { "claude-opus-5-5": { "us.": "us.anthropic.claude-opus-5-5" }, "claude-sonnet-5-5": { "us.": "us.anthropic.claude-sonnet-5-5" } }, +}; +const TERMS = { + status: "fail", code: "marketplace_failed", + detail: "Bedrock refused us.anthropic.claude-sonnet-5-5: Anthropic's terms for this model haven't been accepted in AWS Marketplace.", + fix: "Have someone allowed to subscribe in AWS Marketplace accept the terms for claude-sonnet-5-5 on the Bedrock console's Model access page, then check again.", + url: "https://console.aws.amazon.com/bedrock/home?region=us-west-2#/modelaccess", +}; + +/** A signed release with a model list, as resolveSource returns it after the signature check. */ +const signedSource = (manifest = MANIFEST) => async (_ctx, version) => ({ version, models: manifest, infra: path.join(tmpdir(), "infra"), dashboard: null, env: {} }); + +/** The install's worker answering the model check (the outfile is its reply); no real model calls. */ +function workerAnswers(results, { fail = false, payloads = [] } = {}) { + return { + "dynamodb get-item": { Item: { data: { S: JSON.stringify({ provider: "bedrock", probe_team: "TEAM#1" }) } } }, + "lambda invoke --function-name coderhelm-prod-worker": (args) => { + payloads.push(JSON.parse(args[args.indexOf("--payload") + 1])); + if (fail) return { code: 255, stderr: "AccessDenied" }; + const out = args[args.length - 1]; + const targets = payloads.at(-1).model_check.targets; + fs.writeFileSync(out, JSON.stringify({ provider: "bedrock", region: "us-west-2", ok: false, results: results(targets) })); + return "{}"; + }, + }; +} + +function modelRunner(results, opts) { + const base = healthyThen(99); + Object.assign(base.answers, workerAnswers(results, opts)); + return base; +} + +/** Runs the CLI; a refusal (thrown, like every update refusal) comes back as code 1 with its message. */ +async function attempt(argv, deps) { + const logs = []; + try { + const code = await main(argv, { log: (m) => logs.push(String(m)), interactive: false, ask: quietAsk(), ...deps }); + return { code, out: logs.join("\n") }; + } catch (e) { + return { code: 1, out: `${logs.join("\n")}\n${e.message}` }; + } +} + +const pass = (t) => ({ model: t.model, id: t.bedrock_ids["us."] ?? t.model, status: "pass", code: "ok", detail: "answered" }); + +test("update: a refused model the release calls stops it before anything deploys, with the fix and the link", async () => { + const { dir, file } = stateDir("v1.0.0"); + const payloads = []; + const runner = modelRunner((ts) => ts.map((t) => (t.model === "claude-sonnet-5-5" ? { ...TERMS, model: t.model } : pass(t))), { payloads }); + const result = path.join(dir, "r.json"); + const r = await attempt(["update", "--config", file, "--to", "v1.1.0", "--yes", "--skip-model-check", "--result-file", result], { runner, resolveSource: signedSource() }); + assert.equal(r.code, 1); + assert.match(r.out, /FAIL {2}claude-sonnet-5-5: Bedrock refused/); + assert.match(r.out, /How to fix: Have someone allowed to subscribe/); + assert.match(r.out, /#\/modelaccess/); + assert.match(r.out, /Update to v1\.1\.0 needs your action: claude-sonnet-5-5 was refused.*can't be skipped/s); + assert.ok(!runner.commands.some((c) => c.args.includes("deploy")), "nothing deployed, --skip-model-check or not"); + assert.equal(JSON.parse(fs.readFileSync(result, "utf8")).status, "failed"); + // The worker was asked about every model the release calls, with the release's Bedrock ids and the probe team. + assert.deepEqual(payloads[0].model_check.targets.map((t) => t.model), ["claude-opus-5-5", "claude-sonnet-5-5"]); + assert.equal(payloads[0].model_check.targets[0].bedrock_ids["us."], "us.anthropic.claude-opus-5-5"); + assert.equal(payloads[0].model_check.probe_team, "TEAM#1"); + // Nothing accepts terms or subscribes. + assert.ok(!runner.lines().some((l) => /marketplace|agreement|use-case|subscribe/i.test(l))); +}); + +test("update: every model answers, so the update deploys", async () => { + const { dir, file } = stateDir("v1.0.0"); + const runner = modelRunner((ts) => ts.map(pass)); + const result = path.join(dir, "r.json"); + const r = await attempt(["update", "--config", file, "--to", "v1.1.0", "--yes", "--result-file", result], { runner, resolveSource: signedSource() }); + assert.equal(r.code, 0, r.out); + assert.match(r.out, /PASS {2}claude-opus-5-5/); + assert.ok(runner.commands.some((c) => c.args.includes("deploy"))); + assert.equal(JSON.parse(fs.readFileSync(result, "utf8")).status, "succeeded"); +}); + +test("update: --skip-model-check passes only a model the release doesn't call", async () => { + const extra = (ts) => [...ts.map(pass), { ...TERMS, model: "claude-haiku-4-5", id: "us.anthropic.claude-haiku-4-5-20251001-v1:0" }]; + const a = stateDir("v1.0.0"); + const refused = await attempt(["update", "--config", a.file, "--to", "v1.1.0", "--yes"], { runner: modelRunner(extra), resolveSource: signedSource() }); + assert.equal(refused.code, 1); + assert.match(refused.out, /doesn't call it, so --skip-model-check lets the update go ahead/); + + const b = stateDir("v1.0.0"); + const runner = modelRunner(extra); + const result = path.join(b.dir, "r.json"); + const ok = await attempt(["update", "--config", b.file, "--to", "v1.1.0", "--yes", "--skip-model-check", "--result-file", result], { runner, resolveSource: signedSource() }); + assert.equal(ok.code, 0, ok.out); + assert.match(ok.out, /skipped for claude-haiku-4-5/); + assert.equal(JSON.parse(fs.readFileSync(result, "utf8")).note, "model check skipped for claude-haiku-4-5"); +}); + +test("update: a model the config names is required too, and a worker that doesn't answer stops the update", async () => { + const { file } = stateDir("v1.0.0"); + fs.writeFileSync(file, JSON.stringify({ ...JSON.parse(fs.readFileSync(file, "utf8")), models: { provider: "bedrock", primary: "claude-opus-4-8" } })); + const payloads = []; + const runner = modelRunner((ts) => ts.map((t) => (t.model === "claude-opus-4-8" ? { ...TERMS, model: t.model } : pass(t))), { payloads }); + const r = await attempt(["update", "--config", file, "--to", "v1.1.0", "--yes", "--skip-model-check"], { runner, resolveSource: signedSource() }); + assert.equal(r.code, 1); + assert.ok(payloads[0].model_check.targets.some((t) => t.model === "claude-opus-4-8")); + assert.ok(!runner.commands.some((c) => c.args.includes("deploy"))); + + const down = stateDir("v1.0.0"); + const runner2 = modelRunner(() => [], { fail: true }); + const r2 = await attempt(["update", "--config", down.file, "--to", "v1.1.0", "--yes"], { runner: runner2, resolveSource: signedSource() }); + assert.equal(r2.code, 1); + assert.match(r2.out, /model check couldn't run/); + assert.ok(!runner2.commands.some((c) => c.args.includes("deploy"))); +}); + +test("update: a signed release without a model list, a rollback and a checkout skip the model check", async () => { + const unit = { flags: {}, runner: new FakeRunner(), log: () => {} }; + assert.equal(await cmd.updateModelCheck(unit, { region: "us-west-2", stage: "prod" }, { version: "v1.1.0", models: null }, "v1.1.0"), null); + assert.equal(await cmd.updateModelCheck(unit, { region: "us-west-2", stage: "prod" }, { version: "source" }, "source"), null); + assert.equal(unit.runner.commands.length, 0, "no AWS calls"); + const v = cmd.modelCheckVerdict([{ model: "a", status: "fail" }, { model: "b", status: "fail" }], new Set(["a"]), true); + assert.equal(v.ok, false); + assert.deepEqual(v.blocking.map((x) => x.model), ["a"]); +}); diff --git a/installer/test/release-security.test.mjs b/installer/test/release-security.test.mjs index 66d01f616..2532d8b62 100644 --- a/installer/test/release-security.test.mjs +++ b/installer/test/release-security.test.mjs @@ -261,3 +261,57 @@ test("rollback: only to a release this install ran before", () => { assert.throws(() => checkRollbackTarget(state, "v1.4.0"), /not a release this install ran before/); assert.throws(() => checkRollbackTarget({ version: "v1.4.0" }, "v1.0.0"), /none recorded/); }); + +// ── models.json: read only after the signature check ───────────────────── + +import { MODELS, releaseModels } from "../lib/release.mjs"; + +const MANIFEST_BODY = Buffer.from(JSON.stringify({ schema: 1, version: TAG, calls: ["claude-opus-5-5"], bedrock: {} })); + +/** A release whose signed SHA256SUMS lists models.json. */ +function filesWithModels(body = MANIFEST_BODY) { + const files = releaseFiles(); + files[MODELS] = body; + files.SHA256SUMS = Buffer.from(String(files.SHA256SUMS) + `${sha(MANIFEST_BODY)} ${MODELS}\n`); + return files; +} + +test("models.json is downloaded only after the signature verifies, and must match the signed checksum", async () => { + process.env.CODERHELM_HOME = tmpdir(); + const runner = cosignOk(); + const gh = fakeGithub(filesWithModels()); + const paths = await fetchRelease(TAG, { runner, fetchImpl: gh.fetchImpl, log: () => {} }); + assert.deepEqual(paths.models.calls, ["claude-opus-5-5"]); + const verifiedAt = runner.commands.findIndex((c) => c.args[0] === "verify-blob"); + assert.ok(verifiedAt >= 0); + assert.equal(gh.asked.filter((u) => u.endsWith(`/${MODELS}`)).length, 1); + + // Changed after signing: refused. + process.env.CODERHELM_HOME = tmpdir(); + const swapped = fakeGithub(filesWithModels(Buffer.from(JSON.stringify({ schema: 1, version: TAG, calls: [] })))); + await assert.rejects(() => fetchRelease(TAG, { runner: cosignOk(), fetchImpl: swapped.fetchImpl, log: () => {} }), /models\.json does not match its checksum/); + + // A signature that doesn't verify: models.json is never fetched. + process.env.CODERHELM_HOME = tmpdir(); + const bad = new FakeRunner({ "cosign version": "v2.4.1", "cosign verify-blob": { code: 1, stderr: "no" } }); + const gh2 = fakeGithub(filesWithModels()); + await assert.rejects(() => fetchRelease(TAG, { runner: bad, fetchImpl: gh2.fetchImpl, log: () => {} }), /does not verify/); + assert.ok(!gh2.asked.some((u) => u.endsWith(`/${MODELS}`))); +}); + +test("models.json: a release that doesn't list it has none; with gh it needs its own attestation; never without a check", async () => { + process.env.CODERHELM_HOME = tmpdir(); + const plain = await fetchRelease(TAG, { runner: cosignOk(), fetchImpl: fakeGithub(releaseFiles()).fetchImpl, log: () => {} }); + assert.equal(plain.models, null); + + const dir = tmpdir(); + fs.writeFileSync(path.join(dir, MODELS), MANIFEST_BODY); + const sums = { [MODELS]: sha(MANIFEST_BODY) }; + const noAttestation = new FakeRunner({ "gh attestation verify": { code: 1 } }); + await assert.rejects(() => releaseModels(dir, sums, { runner: noAttestation, tag: TAG, method: "attestation", log: () => {} }), /no valid build attestation/); + const attested = new FakeRunner({ "gh attestation verify": "ok" }); + assert.equal((await releaseModels(dir, sums, { runner: attested, tag: TAG, method: "attestation", log: () => {} })).version, TAG); + await assert.rejects(() => releaseModels(dir, sums, { runner: attested, tag: TAG, method: undefined, log: () => {} }), /signature wasn't checked/); + // Another release's list is refused. + await assert.rejects(() => releaseModels(dir, sums, { runner: attested, tag: "v9.9.9", method: "cosign", log: () => {} }), /isn't a model list for this release/); +});