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
2 changes: 1 addition & 1 deletion docs/self-host/model-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`<prefix>-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).
Expand Down
2 changes: 2 additions & 0 deletions docs/self-host/updates.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
14 changes: 14 additions & 0 deletions infra/lib/updates-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
10 changes: 10 additions & 0 deletions infra/test/synth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"] } });
});
2 changes: 2 additions & 0 deletions installer/lib/cli.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 <f> 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 <ids> 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
Expand Down
102 changes: 102 additions & 0 deletions installer/lib/commands.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 },
Expand Down Expand Up @@ -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:");
Expand Down Expand Up @@ -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 });
}
Expand Down
48 changes: 44 additions & 4 deletions installer/lib/release.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 });
Expand All @@ -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"]);
Expand All @@ -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,
Expand Down
Loading
Loading