From 6348d5bbb822acacb2c52a8fac74cedcfcb82405 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 26 Oct 2026 14:27:22 -0400 Subject: [PATCH] Self-host: switch the model provider at any time, and check a release's models before updating - Settings, System, Models: Claude on Amazon Bedrock or Anthropic API keys, stored at runtime (SYSTEM/MODELS); the deploy config is the first-boot default. Every model the release calls answers a test call first; the switch is audited, then saved, and reaches every service within 30 s. - Release model manifest (services/common/release_models.json), built into the services, held to the code by a test, published as models.json in the signed SHA256SUMS. - The updater reads models.json only through a read-only release check build after the signature check, then has the worker test each model through the install's provider. A refused model holds the update with its fix; checked daily; applies once it passes. No terms are ever accepted. - Every self-hosted install may call Claude on Bedrock (Anthropic models and inference profiles only); no Marketplace or agreement permissions. --- .github/workflows/release.yml | 8 +- docs/self-host/model-providers.md | 51 +- docs/self-host/updates.md | 8 +- infra/cfn/coderhelm-selfhost-launch.yaml | 2 +- infra/lib/service-env.ts | 27 +- infra/lib/updates-stack.ts | 94 ++- infra/test/synth.test.ts | 85 ++- installer/lib/wizard.mjs | 2 +- lambda/log-analyzer/handler.py | 9 + lambda/log-analyzer/usage.py | 81 ++- lambda/tests/test_log_analyzer.py | 29 + lambda/tests/test_updater.py | 252 +++++++ lambda/updater/handler.py | 280 +++++++- selfhost/launch/release-models.mjs | 43 ++ selfhost/launch/release-models.test.mjs | 40 ++ services/common/release_models.json | 21 + services/common/src/lib.rs | 1 + services/common/src/model_access.rs | 309 +++++++++ services/common/src/model_ids.rs | 153 ++++ services/common/src/model_provider.rs | 449 ++++++++++-- services/gateway/src/main.rs | 28 +- services/gateway/src/model_call.rs | 67 +- services/gateway/src/permissions.rs | 15 +- services/gateway/src/routes/api.rs | 19 +- services/gateway/src/routes/mod.rs | 1 + services/gateway/src/routes/setup_checks.rs | 192 +++++- services/gateway/src/routes/system.rs | 39 +- services/gateway/src/routes/system_models.rs | 690 +++++++++++++++++++ services/worker/src/agent/anthropic.rs | 28 + services/worker/src/agent/provider.rs | 60 +- services/worker/src/main.rs | 11 +- services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/model_check.rs | 220 ++++++ 33 files changed, 3175 insertions(+), 140 deletions(-) create mode 100644 selfhost/launch/release-models.mjs create mode 100644 selfhost/launch/release-models.test.mjs create mode 100644 services/common/release_models.json create mode 100644 services/common/src/model_access.rs create mode 100644 services/gateway/src/routes/system_models.rs create mode 100644 services/worker/src/passes/model_check.rs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f81358b39..9e4a581b8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -181,7 +181,12 @@ jobs: # The publish job uploads this same launch-stack.yaml to S3. node selfhost/launch/stamp-template.mjs infra/cfn/coderhelm-selfhost-launch.yaml "$TAG" > dist/launch-stack.yaml cp selfhost/launch/bootstrap.mjs dist/launch-bootstrap.mjs - (cd dist && sha256sum gateway.zip worker.zip mcp-proxy.zip dashboard.tar.gz source.tar.gz coderhelm-selfhost.tgz install.sh launch-stack.yaml launch-bootstrap.mjs > SHA256SUMS) + # The models this release calls, read from the code, with their + # Bedrock ids per inference profile prefix. In the signed + # SHA256SUMS: the updater reads it only through the update build, + # after the signature check (lambda/updater, model_check). + node selfhost/launch/release-models.mjs "$TAG" > dist/models.json + (cd dist && sha256sum gateway.zip worker.zip mcp-proxy.zip dashboard.tar.gz source.tar.gz coderhelm-selfhost.tgz install.sh launch-stack.yaml launch-bootstrap.mjs models.json > SHA256SUMS) cat dist/SHA256SUMS # The release's own CDK app synthesizes for a fresh self-host config. @@ -258,6 +263,7 @@ jobs: dist/install.sh dist/launch-bootstrap.mjs dist/launch-stack.yaml + dist/models.json # A published release's files are never replaced: a re-run only fills in # a release that has no SHA256SUMS yet (one made by hand, without diff --git a/docs/self-host/model-providers.md b/docs/self-host/model-providers.md index 3b218a351..81f9c8cee 100644 --- a/docs/self-host/model-providers.md +++ b/docs/self-host/model-providers.md @@ -4,7 +4,7 @@ description: Call Claude through the Anthropic API with each team's key, or thro order: 5 --- -CoderHelm uses Claude for every run, review, plan chat and log analysis. You pick how it is reached with `models.provider` in the config. +CoderHelm uses Claude for every run, review, plan chat and log analysis. You pick how it is reached when you install (`models.provider` in the config, or the install guide's **Models** step), and you can change it later in **Settings, System, Models** without a redeploy. See [Switch providers](#switch-providers). ## Anthropic API (default) @@ -25,10 +25,7 @@ Each team adds its own Anthropic API key in **Settings, AI models**, and picks i The gateway, streaming, worker and log analyzer functions call Bedrock with their own IAM roles. No API key exists anywhere; usage and cost land on your AWS bill, and data stays in AWS. -**Before you deploy:** - -1. In the Bedrock console of your region, open **Model access** and enable the Claude models you will use (by default Claude Opus 5.5 and Claude Sonnet 5.5). Some models ask you to accept terms first. -2. Pick the inference profile prefix for your region: `us.` for US regions, `eu.` for Europe, `apac.` for Asia Pacific, `global.` for the global profiles, or `""` to call a model in your region directly. +**Before you deploy (or switch):** see [Bedrock model access](#bedrock-model-access) below, then pick the inference profile prefix for your region: `us.` for US regions, `eu.` for Europe, `apac.` for Asia Pacific, `global.` for the global profiles, or `""` to call a model in your region directly. **How model names map to Bedrock ids.** Teams and the config use Anthropic's model names (`claude-opus-5-5`). CoderHelm turns them into Bedrock ids: @@ -41,10 +38,51 @@ The gateway, streaming, worker and log analyzer functions call Bedrock with thei - a name that already is a Bedrock id (contains `anthropic.`) is used as it is; - otherwise it becomes `anthropic.`, so `claude-sonnet-5-5` with `us.` is `us.anthropic.claude-sonnet-5-5`. Models whose Bedrock id carries a date (Claude Haiku 4.5) are mapped to the dated id for you. -**What the roles may call:** `bedrock:InvokeModel` and `bedrock:InvokeModelWithResponseStream` on Anthropic foundation models and your account's inference profiles, nothing else. +**What the roles may call:** `bedrock:InvokeModel` (which also covers the Converse API) and `bedrock:InvokeModelWithResponseStream` on Anthropic foundation models and your account's inference profiles, nothing else. Every self-hosted install gets this, even one that starts on Anthropic keys, so you can switch to Bedrock later without a redeploy. The roles never get `aws-marketplace:Subscribe` or the calls that accept a model agreement or submit the use case form. With Bedrock, the **Settings, AI models** page says the install uses Bedrock and no key is needed; teams can still choose which models they use. +## Bedrock model access + +Before CoderHelm can call a Claude model on Bedrock, someone in your company does three things in the AWS console, once per account. CoderHelm never does them for you: it only links to the page and checks the result. + +1. **Model access.** In the Bedrock console of your region, open **Model access** and turn on the Claude models CoderHelm calls (by default Claude Opus 5.5 and Claude Sonnet 5.5). +2. **Use case form.** The first time an account asks for an Anthropic model, Bedrock asks for a short description of how you will use it (**Submit use case details** on the same page). A person fills it in; it applies to every Anthropic model in the account. +3. **Anthropic's terms (AWS Marketplace).** Each Anthropic model is offered through AWS Marketplace. Accepting its terms subscribes your account; this needs a user allowed to subscribe in Marketplace and a valid payment method on the account. It can take a few minutes to finish. + +If a step is missing, every check (Setup, a switch, an update) names the model, says which step in one sentence, and links to the page. Then use **Check again**. + +## Switch providers + +Install admins can switch at any time in **Settings, System, Models**: + +- **Claude on Amazon Bedrock**, with the inference profile prefix (default `us.`) and, under **Advanced**, an exact Bedrock id for any model (an application inference profile ARN, for example). +- **Anthropic API keys**. Each team keeps using its own key from **Settings, AI models**, as before. There is no install-wide key: the key already lives with each team, every service reads it there, and each team's usage stays on its own Anthropic account. + +Before anything is saved, CoderHelm makes one test call (one token) to every model the running release calls, through the provider you picked: Bedrock with your settings, or the Anthropic API with your team's key. If any model is refused, nothing changes and you see which model, the fix in one sentence and a link, with **Check again**. A switch to Anthropic keys needs your own team to have a working key first. + +A saved switch: + +- is written to your team's audit log first (who, when, from what to what); if the log can't be written, nothing changes; +- reaches every part of CoderHelm within 30 seconds, with no redeploy; +- never stops a run. Model calls already under way finish where they started, and later calls use the new provider. A run that started on Bedrock without a team key keeps using Bedrock until it ends. + +The deploy config's `models` settings are only the first-boot default. Once you switch in Settings, that choice wins until you switch again; a redeploy doesn't undo it. + +## Updates and new models + +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: + +- **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). +- The check runs again every day. Once it passes, the update applies by itself in your maintenance window if auto-update is on; otherwise **Update now** works again. + +**Update now** has no override for a model the release calls. **Skip this check** appears only when the failing model isn't one the release calls. + +On the Anthropic API there are no terms to accept; the check uses the key of the team that last switched to keys, and is skipped when there is no such key. Models a team picks in **Settings, AI models** are checked by **Setup**, not before an update. + ## Which to choose | | Anthropic API | Bedrock | @@ -54,6 +92,7 @@ With Bedrock, the **Settings, AI models** page says the install uses Bedrock and | Data path | Your AWS, then Anthropic | Stays in AWS | | New models | Available on release day | When Bedrock adds them in your region | | Setup | Nothing at deploy | Enable model access first | +| Change later | Settings, System, Models | Settings, System, Models | ## Embeddings diff --git a/docs/self-host/updates.md b/docs/self-host/updates.md index 61d7afc57..c0c5b0f59 100644 --- a/docs/self-host/updates.md +++ b/docs/self-host/updates.md @@ -42,13 +42,17 @@ npx -y github:CoderHelm/coderhelm-platform auto-update on --window "Sun 03:00" - The settings take effect at once (no deploy). The same values in `coderhelm.config.json` under `updates` are the starting point of a new install. -An update starts only when all of these hold: auto-update is on, the hour is the window's hour in your time zone, the release is on your channel, it isn't a major release while majors are `ask`, no update is running, and that version hasn't already failed (an admin can still start it by hand). +An update starts only when all of these hold: auto-update is on, the hour is the window's hour in your time zone, the release is on your channel, it isn't a major release while majors are `ask`, no update is running, that version hasn't already failed (an admin can still start it by hand), and every model the release calls answers a test call through your provider. + +## The model check + +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 readiness Before you update, **Settings, then System** shows **Update readiness**: the same checks an update makes, run now, each with its fix. -- **Blocks the update:** a check that fails (the update's health check would stop it), or an update already running. **Update now** stays off until it is fixed. +- **Blocks the update:** a check that fails (the update's health check would stop it), a model the release calls that was refused, or an update already running. **Update now** stays off until it is fixed. - **Read first:** a major release whose notes ask you to do something, or a release whose last try failed or rolled back (with the reason). Each item says what is wrong and how to fix it: a command to copy, a link, or a page in CoderHelm. **Check again** reruns them. The same list is `GET /api/system/preflight`; see [Check your install](./check-your-install.md). diff --git a/infra/cfn/coderhelm-selfhost-launch.yaml b/infra/cfn/coderhelm-selfhost-launch.yaml index 0331cd77f..2a9d19df1 100644 --- a/infra/cfn/coderhelm-selfhost-launch.yaml +++ b/infra/cfn/coderhelm-selfhost-launch.yaml @@ -60,7 +60,7 @@ Parameters: Type: String Default: bedrock AllowedValues: [bedrock, anthropic] - Description: bedrock (Claude on Amazon Bedrock in this account, no API key) or anthropic (each team adds its own Anthropic API key). + Description: bedrock (Claude on Amazon Bedrock in this account, no API key) or anthropic (each team adds its own Anthropic API key). You can change this later in Settings, System. Version: Type: String # Stamped with the release's own tag when the release is published diff --git a/infra/lib/service-env.ts b/infra/lib/service-env.ts index 7c85a2038..74a6b2720 100644 --- a/infra/lib/service-env.ts +++ b/infra/lib/service-env.ts @@ -53,7 +53,12 @@ export function serviceEnvironment(cfg: ResolvedConfig, account: string): Record return env; } -/** MODEL_PROVIDER and the Bedrock model mapping (nothing for the default Anthropic API). */ +/** + * MODEL_PROVIDER and the Bedrock model mapping (nothing for the default + * Anthropic API). On a self-hosted install this is only the first-boot + * default: an admin can switch in Settings, System, Models at any time + * (services/common/src/model_provider.rs). + */ export function modelProviderEnvironment(cfg: ResolvedConfig): Record { if (cfg.models.provider !== "bedrock") return {}; return { @@ -63,11 +68,27 @@ export function modelProviderEnvironment(cfg: ResolvedConfig): Record /tmp/result.json; ' + + 'else echo \'{"status":"verified","manifest":null}\' > /tmp/result.json; fi', + ], + }, + post_build: { + commands: [ + // Anything short of a verified result reports a failure (nothing is trusted). + 'if [ "${CODEBUILD_BUILD_SUCCEEDING:-0}" != "1" ] || [ ! -s /tmp/result.json ]; then echo \'{"status":"failed","reason":"the release check failed: see its log"}\' > /tmp/result.json; fi', + 'node -e \'const r=require("/tmp/result.json");process.stdout.write(JSON.stringify({action:"models_verified",version:process.env.VERSION,status:r.status,reason:r.reason,manifest:r.manifest??null}))\' > /tmp/payload.json', + `aws lambda invoke --function-name ${cfg.prefix}-updater --cli-binary-format raw-in-base64-out --payload file:///tmp/payload.json /tmp/out.json`, + ], + }, + }, + }); +} + export function updateBuildSpec(cfg: ResolvedConfig): codebuild.BuildSpec { return codebuild.BuildSpec.fromObject({ version: "0.2", @@ -100,6 +143,7 @@ export function updateBuildSpec(cfg: ResolvedConfig): codebuild.BuildSpec { export class UpdatesStack extends cdk.Stack { public readonly updaterFunction: lambda.Function; public readonly project: codebuild.Project; + public readonly checkProject: codebuild.Project; constructor(scope: Construct, id: string, props: UpdatesStackProps) { super(scope, id, props); @@ -183,6 +227,37 @@ export class UpdatesStack extends cdk.Stack { buildSpec: updateBuildSpec(cfg), }); + // --- The release check (read-only; the model check reads its result) --- + const checkRole = new iam.Role(this, "ReleaseCheckRole", { + roleName: `${prefix}-release-check`, + description: "CoderHelm release check: verifies a release's signature and reads its model list; can only report to the updater", + assumedBy: new iam.ServicePrincipal("codebuild.amazonaws.com"), + }); + checkRole.addToPolicy(new iam.PolicyStatement({ + sid: "ReportResult", + actions: ["lambda:InvokeFunction"], + resources: [`arn:aws:lambda:${this.region}:${this.account}:function:${prefix}-updater`], + })); + const checkLogs = new logs.LogGroup(this, "ReleaseCheckLogs", { + logGroupName: `/aws/codebuild/${prefix}-release-check`, + retention: logs.RetentionDays.ONE_MONTH, + removalPolicy: cdk.RemovalPolicy.DESTROY, + }); + this.checkProject = new codebuild.Project(this, "ReleaseCheck", { + projectName: `${prefix}-release-check`, + description: "Checks a CoderHelm release's signature and reads the models it calls (no install, no deploy)", + role: checkRole, + timeout: cdk.Duration.minutes(15), + concurrentBuildLimit: 1, + environment: { + buildImage: codebuild.LinuxBuildImage.STANDARD_7_0, + computeType: codebuild.ComputeType.SMALL, + environmentVariables: { VERSION: { value: "" } }, + }, + logging: { cloudWatch: { logGroup: checkLogs } }, + buildSpec: releaseCheckBuildSpec(cfg), + }); + // --- The updater --- const updaterLogs = new logs.LogGroup(this, "UpdaterLogs", { logGroupName: `/aws/lambda/${prefix}-updater`, @@ -197,7 +272,8 @@ export class UpdatesStack extends cdk.Stack { handler: "handler.handler", code: lambda.Code.fromAsset(repoPath("lambda/updater"), { exclude: ["__pycache__"] }), memorySize: 256, - timeout: cdk.Duration.seconds(60), + // The model check waits on the worker's test calls (retried when Bedrock is busy). + timeout: cdk.Duration.minutes(3), logGroup: updaterLogs, environment: { SETTINGS_TABLE_NAME: props.settingsTable.tableName, @@ -212,6 +288,11 @@ export class UpdatesStack extends cdk.Stack { // Your own domain (docs/self-host/domains.md). DISTRIBUTION_DOMAIN_PARAMETER: cfg.distributionDomainParameter, RESOURCE_PREFIX: prefix, + // The model check before an update: the worker makes the test calls + // for every model the next release calls, plus the config's own. + WORKER_FUNCTION_NAME: `${prefix}-worker`, + RELEASE_CHECK_PROJECT_NAME: `${prefix}-release-check`, + CONFIGURED_MODELS: [...new Set([cfg.models.primary, cfg.models.light])].join(","), ...(cfg.updates.webhookUrl ? { UPDATE_WEBHOOK_URL: cfg.updates.webhookUrl } : {}), ...stampEnvironment(stamp), }, @@ -219,7 +300,7 @@ export class UpdatesStack extends cdk.Stack { props.settingsTable.grantReadWriteData(this.updaterFunction); this.updaterFunction.addToRolePolicy(new iam.PolicyStatement({ actions: ["codebuild:StartBuild"], - resources: [this.project.projectArn], + resources: [this.project.projectArn, this.checkProject.projectArn], })); this.updaterFunction.addToRolePolicy(new iam.PolicyStatement({ actions: ["ses:SendEmail"], @@ -227,6 +308,15 @@ export class UpdatesStack extends cdk.Stack { conditions: { StringEquals: { "ses:FromAddress": cfg.email.from } }, })); + // The model check: the worker makes the test calls with its own role (or + // a team's key). The updater itself never calls a model, and nothing in + // the install may subscribe in AWS Marketplace or accept model terms. + this.updaterFunction.addToRolePolicy(new iam.PolicyStatement({ + sid: "ModelCheckThroughWorker", + actions: ["lambda:InvokeFunction"], + resources: [`arn:aws:lambda:${this.region}:${this.account}:function:${prefix}-worker`], + })); + // refresh_secrets: stamp SECRETS_REVISION on the functions that read // the secret at start (nothing else about them can change this way). this.updaterFunction.addToRolePolicy(new iam.PolicyStatement({ diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index 63a0a020f..94cbfbc49 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -16,7 +16,7 @@ import { Template } from "aws-cdk-lib/assertions"; import { buildApp } from "../lib/app"; import { CoderhelmConfig, loadConfigFile, resolveConfig, ResolvedConfig } from "../lib/config"; import { API_PATHS, STREAM_PATH, runtimeConfigScript } from "../lib/web-stack"; -import { updateBuildSpec } from "../lib/updates-stack"; +import { releaseCheckBuildSpec, updateBuildSpec } from "../lib/updates-stack"; import { CHECK_VERSION, COSIGN_LINUX_AMD64_SHA256, VERIFY_SUMS } from "../lib/release-verify"; const INFRA = path.join(__dirname, "..", ".."); @@ -489,3 +489,86 @@ test("CORS: the gateway answers browsers, not API Gateway; the docs origin never } assert.ok(API_PATHS.includes("/api/*"), "the setup routes go through the API behavior"); }); + +// ── Switching the model provider (Settings, System, Models) ────────────── + +/** Every action any IAM policy or role in these templates allows. */ +function allowedActions(t: Record): string[] { + const out: string[] = []; + const walk = (v: unknown) => { + if (Array.isArray(v)) v.forEach(walk); + else if (v && typeof v === "object") { + for (const [k, x] of Object.entries(v)) { + if (k === "Action") out.push(...(Array.isArray(x) ? x : [x]).map(String)); + else walk(x); + } + } + }; + for (const tpl of Object.values(t)) walk(tpl.toJSON().Resources); + return out; +} + +test("a self-host that starts on Anthropic keys may still call Bedrock, and nothing may accept terms", () => { + const t = synth(selfHost({ models: { provider: "anthropic" } })); + // No MODEL_PROVIDER: the first-boot default is the Anthropic API. + assert.equal(envOf(t["coderhelm-prod-api"], "coderhelm-prod-gateway").MODEL_PROVIDER, undefined); + // Every function that calls Claude may call it on Bedrock, on Anthropic models and inference profiles only. + for (const stack of ["coderhelm-prod-api", "coderhelm-prod-worker", "coderhelm-prod-streaming", "coderhelm-prod-log-analyzer"]) { + const policies = Object.values(t[stack].findResources("AWS::IAM::Policy")); + const st = policies + .flatMap((p: any) => p.Properties.PolicyDocument.Statement) + .find((s: any) => s.Sid === "CallClaudeOnBedrock"); + assert.ok(st, `${stack} may call Claude on Bedrock`); + assert.deepEqual(st.Action, ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"]); + const res = JSON.stringify(st.Resource); + assert.ok(res.includes("foundation-model/anthropic.*"), stack); + assert.ok(res.includes("inference-profile/*"), stack); + assert.ok(!res.includes('"*"'), `${stack}: never every resource`); + } + // The install never subscribes in AWS Marketplace or accepts a model agreement or use case form. + const actions = allowedActions(t); + for (const a of actions) { + assert.ok(!/^aws-marketplace:/i.test(a), a); + assert.ok(!/bedrock:(CreateFoundationModelAgreement|PutUseCaseForModelAccess|\*)/i.test(a), a); + } + // The updater asks the worker for the model check, and knows the config's models. + const u = t["coderhelm-prod-updates"]; + const env = envOf(u, "coderhelm-prod-updater"); + assert.equal(env.WORKER_FUNCTION_NAME, "coderhelm-prod-worker"); + assert.equal(env.CONFIGURED_MODELS, "claude-opus-5-5,claude-sonnet-5-5"); + const up = JSON.stringify(u.findResources("AWS::IAM::Policy")); + assert.ok(up.includes("ModelCheckThroughWorker")); + assert.ok(!up.includes("bedrock:"), "the updater itself never calls a model"); +}); + +test("the hosted deployment on Anthropic keys gets no Bedrock model access", () => { + const hostedCfg = loadConfigFile(path.join(INFRA, "config", "hosted.prod.json"), { CDK_DEFAULT_ACCOUNT: "654654210434" }); + if (hostedCfg.models.provider === "bedrock") return; + const hosted = synth(hostedCfg, zoneContext("654654210434", "us-east-1", "coderhelm.com")); + const api = JSON.stringify(hosted["coderhelm-prod-api"].findResources("AWS::IAM::Policy")); + assert.ok(!api.includes("CallClaudeOnBedrock")); +}); + +test("the release check reads models.json only after the signature check, and can only report back", () => { + const cfg = selfHost(); + const commands: string[] = [...Object.values((releaseCheckBuildSpec(cfg) as any).spec.phases)].flatMap((p: any) => p.commands); + const verifyAt = commands.indexOf(VERIFY_SUMS); + assert.ok(verifyAt > 0, "the same exact signature check as the update build"); + assert.ok(commands.indexOf(CHECK_VERSION) < verifyAt); + const readAt = commands.findIndex((c) => c.includes("models.json")); + assert.ok(readAt > verifyAt, "models.json only after the signature check"); + assert.ok(commands[readAt].includes("grep ' models.json$' SHA256SUMS | sha256sum -c -"), "and only when its checksum matches"); + assert.ok(!commands.some((c) => /npm install|coderhelm-selfhost|cdk /.test(c)), "nothing installed or deployed"); + assert.ok(commands.some((c) => c.includes('action:"models_verified"'))); + const t = synth(cfg); + const u = t["coderhelm-prod-updates"]; + const roles = u.findResources("AWS::IAM::Role"); + const check = Object.entries(roles).find(([, r]: any) => r.Properties.RoleName === "coderhelm-prod-release-check"); + assert.ok(check, "its own role"); + const policies = Object.values(u.findResources("AWS::IAM::Policy")).filter((p: any) => JSON.stringify(p.Properties.Roles).includes(check![0])); + const actions = policies.flatMap((p: any) => p.Properties.PolicyDocument.Statement.flatMap((s: any) => [].concat(s.Action))); + // Only reporting back (plus CodeBuild's own logs and reports): no deploy, no secret, no assumed role. + assert.ok(actions.every((a) => a === "lambda:InvokeFunction" || a.startsWith("logs:") || /^codebuild:(Create|Update|BatchPut)/.test(a)), JSON.stringify(actions)); + assert.ok(!actions.some((a) => /sts:|secretsmanager:|ssm:|cloudformation:|bedrock:/.test(a))); + assert.equal(envOf(u, "coderhelm-prod-updater").RELEASE_CHECK_PROJECT_NAME, "coderhelm-prod-release-check"); +}); diff --git a/installer/lib/wizard.mjs b/installer/lib/wizard.mjs index 6ac190d15..ed760d6f7 100644 --- a/installer/lib/wizard.mjs +++ b/installer/lib/wizard.mjs @@ -195,7 +195,7 @@ export function bedrockPrefixFor(region) { async function stepModel(ctx, answers) { const { flags, runner, log } = ctx; - log("CoderHelm uses Claude. Either each team adds its own Anthropic API key, or the install calls Claude on Amazon Bedrock in this AWS account (no keys, billed by AWS)."); + log("CoderHelm uses Claude. Either each team adds its own Anthropic API key, or the install calls Claude on Amazon Bedrock in this AWS account (no keys, billed by AWS). You can change this later in Settings, System."); const provider = await answer(ctx, pick(flags, answers, "provider"), "Claude through anthropic or bedrock", "anthropic", (v) => (["anthropic", "bedrock"].includes(v) ? null : "anthropic or bedrock")); if (provider === BACK) return BACK; if (provider === "anthropic") { diff --git a/lambda/log-analyzer/handler.py b/lambda/log-analyzer/handler.py index 907bf58c7..98e63d720 100644 --- a/lambda/log-analyzer/handler.py +++ b/lambda/log-analyzer/handler.py @@ -47,6 +47,15 @@ dynamodb_client = boto3.client("dynamodb") aws_insights_table = dynamodb.Table(AWS_INSIGHTS_TABLE) settings_table = dynamodb.Table(SETTINGS_TABLE) + + +def _stored_model_provider(): + """The install's model provider from Settings, System, Models (or None).""" + item = settings_table.get_item(Key={"pk": "SYSTEM", "sk": "MODELS"}).get("Item") or {} + return json.loads(item["data"]) if item.get("data") else None + + +usage.RUNTIME_LOADER = _stored_model_provider sts_client = boto3.client("sts") kms_client = boto3.client("kms") diff --git a/lambda/log-analyzer/usage.py b/lambda/log-analyzer/usage.py index 84bebdb50..225415d1b 100644 --- a/lambda/log-analyzer/usage.py +++ b/lambda/log-analyzer/usage.py @@ -392,33 +392,86 @@ def call_messages(api_key, body, model_id, client, table, team_id, feature, raise StreamBroke("unreachable") -# ── Amazon Bedrock (MODEL_PROVIDER=bedrock) ────────────────────────────── +# ── Amazon Bedrock or Anthropic API keys ───────────────────────────────── +# +# The deploy config sets the first-boot default (MODEL_PROVIDER, +# BEDROCK_INFERENCE_PREFIX, BEDROCK_MODEL_IDS); an install admin can change +# it in Settings, System, Models, stored on the settings table (pk SYSTEM, +# sk MODELS). The handler sets RUNTIME_LOADER to read that record; it is read +# again at most every RUNTIME_SECONDS, like the Rust services +# (services/common/src/model_provider.rs). + +RUNTIME_SECONDS = 30 +RUNTIME_LOADER = None +_runtime = {"at": None, "value": None} +_PREFIX_RE = __import__("re").compile(r"^([a-z]{2,6}\.)?$") + + +def deploy_settings(env=None): + env = os.environ if env is None else env + try: + ids = json.loads(env.get("BEDROCK_MODEL_IDS") or "{}") + except ValueError: + ids = {} + return { + "provider": "bedrock" if (env.get("MODEL_PROVIDER") or "").strip().lower() == "bedrock" else "anthropic", + "inference_prefix": env.get("BEDROCK_INFERENCE_PREFIX", "us."), + "model_ids": ids if isinstance(ids, dict) else {}, + } + + +def resolve_settings(stored, default): + """A stored choice when it reads and is valid, else the deploy config's.""" + if not isinstance(stored, dict): + return default + provider = str(stored.get("provider") or "").strip().lower() + if provider not in ("anthropic", "bedrock"): + return default + prefix = str(stored.get("inference_prefix", default["inference_prefix"])).strip() + ids = stored.get("model_ids") or {} + if not _PREFIX_RE.match(prefix) or not isinstance(ids, dict): + return default + if any(not isinstance(v, str) or not ("anthropic." in v or v.startswith("arn:aws")) for v in ids.values()): + return default + return {"provider": provider, "inference_prefix": prefix, "model_ids": ids} + + +def provider_settings(env=None, clock=time.monotonic): + """The setting in force: the stored choice (read at most every 30 s), else the deploy config.""" + default = deploy_settings(env) + if RUNTIME_LOADER is None: + return default + now = clock() + if _runtime["at"] is None or now - _runtime["at"] >= RUNTIME_SECONDS: + try: + _runtime["value"] = RUNTIME_LOADER() + except Exception as e: # keep the last one; try again later + logger.warning(f"Model provider setting not read: {e}") + _runtime["at"] = now + return resolve_settings(_runtime["value"], default) + def is_bedrock(env=None): - """True when the deployment calls Claude through Amazon Bedrock.""" - env = os.environ if env is None else env - return (env.get("MODEL_PROVIDER") or "").strip().lower() == "bedrock" + """True when the install calls Claude through Amazon Bedrock now.""" + return provider_settings(env)["provider"] == "bedrock" def bedrock_model_id(model, env=None): """The Bedrock id for a model name (same rule as - services/common/src/model_provider.rs): an explicit BEDROCK_MODEL_IDS - entry, an id that already is a Bedrock id, else - anthropic..""" - env = os.environ if env is None else env - try: - mapping = json.loads(env.get("BEDROCK_MODEL_IDS") or "{}") - except ValueError: - mapping = {} + services/common/src/model_provider.rs): an explicit model id override, an + id that already is a Bedrock id, else anthropic..""" + s = provider_settings(env) + mapping = s["model_ids"] if model in mapping: return mapping[model] if "anthropic." in model or model.startswith("arn:"): return model name = BEDROCK_NAMES.get(model, model) - return f"{env.get('BEDROCK_INFERENCE_PREFIX', 'us.')}anthropic.{name}" + return f"{s['inference_prefix']}anthropic.{name}" -# Models whose Bedrock id isn't just their name (same table as the Rust side). +# Models whose Bedrock id isn't just their name (the release manifest's +# bedrock_names, services/common/release_models.json; a test holds them equal). BEDROCK_NAMES = { "claude-haiku-4-5": "claude-haiku-4-5-20251001-v1:0", "claude-haiku-4-5-20251001": "claude-haiku-4-5-20251001-v1:0", diff --git a/lambda/tests/test_log_analyzer.py b/lambda/tests/test_log_analyzer.py index 24e780b48..50c161d64 100644 --- a/lambda/tests/test_log_analyzer.py +++ b/lambda/tests/test_log_analyzer.py @@ -444,6 +444,35 @@ def test_switch_and_model_ids(self): env["BEDROCK_MODEL_IDS"] = '{"claude-sonnet-5-5": "arn:aws:bedrock:eu-west-1:1:application-inference-profile/p"}' self.assertTrue(self.u.bedrock_model_id("claude-sonnet-5-5", env).startswith("arn:")) + def test_the_stored_switch_wins_and_is_read_every_30_seconds(self): + u = self.u + reads = [] + stored = {"provider": "bedrock", "inference_prefix": "eu.", "model_ids": {}} + old = (u.RUNTIME_LOADER, dict(u._runtime)) + self.addCleanup(lambda: (setattr(u, "RUNTIME_LOADER", old[0]), u._runtime.update(old[1]))) + u.RUNTIME_LOADER = lambda: reads.append(1) or stored + u._runtime.update(at=None, value=None) + clock = [100.0] + tick = lambda: clock[0] + self.assertEqual(u.provider_settings({}, tick)["provider"], "bedrock") + self.assertEqual(u.provider_settings({}, tick)["inference_prefix"], "eu.") + self.assertEqual(len(reads), 1) + # Switched back to keys: seen after 30 seconds. + stored = {"provider": "anthropic"} + u.RUNTIME_LOADER = lambda: reads.append(1) or stored + clock[0] += 31 + self.assertEqual(u.provider_settings({"MODEL_PROVIDER": "bedrock"}, tick)["provider"], "anthropic") + # A broken record: the deploy config. + for bad in ({"provider": "openai"}, {"provider": "bedrock", "inference_prefix": "US"}, + {"provider": "bedrock", "model_ids": {"x": "gpt"}}, None, "x"): + self.assertEqual(u.resolve_settings(bad, u.deploy_settings({"MODEL_PROVIDER": "bedrock"}))["provider"], "bedrock") + + def test_bedrock_names_match_the_release_manifest(self): + import json as _j + import pathlib as _p + m = _j.loads((_p.Path(__file__).resolve().parents[2] / "services/common/release_models.json").read_text()) + self.assertEqual(self.u.BEDROCK_NAMES, m["bedrock_names"]) + def test_body(self): b = self.u.bedrock_body({"model": "m", "stream": True, "max_tokens": 5}) self.assertEqual(b, {"max_tokens": 5, "anthropic_version": "bedrock-2023-05-31"}) diff --git a/lambda/tests/test_updater.py b/lambda/tests/test_updater.py index 122840038..2a97eb46f 100644 --- a/lambda/tests/test_updater.py +++ b/lambda/tests/test_updater.py @@ -115,6 +115,10 @@ def setUp(self): self.builds, self.notices = [], [] u.start_build = lambda env, version, actor, mode, hid, extra=None: self.builds.append((version, actor, mode, hid)) or f"b-{len(self.builds)}" u.notify = lambda subject, text, env=None: self.notices.append(subject) or 1 + # Releases checked by the build and listing no models: nothing to check. + real = u.verified_manifest + u.verified_manifest = lambda store, version: (True, None) + self.addCleanup(setattr, u, "verified_manifest", real) self.env = {"CODERHELM_VERSION": "v1.0.0", "APP_URL": "https://helm.example.org", "UPDATE_PROJECT_NAME": "p"} def fetch(self, _repo): @@ -190,6 +194,10 @@ def setUp(self): u.notify = lambda subject, text, env=None: 1 self.env = {"CODERHELM_VERSION": "v1.2.0", "APP_URL": "https://helm.example.org", "UPDATE_PROJECT_NAME": "p"} self.fetch = lambda _r: [rel("v1.3.0")] + # Signed releases that list no models: the model check has nothing to hold. + real = u.verified_manifest + u.verified_manifest = lambda store, version: (True, None) + self.addCleanup(setattr, u, "verified_manifest", real) def test_update_now_never_goes_back_or_sideways(self): for v in ("v1.1.0", "v1.2.0", "v1.2.0-rc.1"): @@ -245,6 +253,250 @@ def test_releases_only_from_coderhelms_repository(self): u.fetch_releases("evil/coderhelm-platform") +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", "eu.": "eu.anthropic.claude-opus-5-5"}, + "claude-sonnet-5-5": {"us.": "us.anthropic.claude-sonnet-5-5", "eu.": "eu.anthropic.claude-sonnet-5-5"}, + }, +} + +REFUSED = { + "status": "fail", "code": "use_case_required", + "detail": "Bedrock refused us.anthropic.claude-sonnet-5-5: Anthropic's use case details haven't been submitted for this AWS account.", + "fix": "Submit the use case details on the Bedrock console's Model access page (a person fills in the form once per account), then check again.", + "url": "https://console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess", +} + + +class FakeWorker: + """Stands in for the worker's model check: no real model calls.""" + + def __init__(self, refuse=("claude-sonnet-5-5",)): + self.refuse = set(refuse) + self.payloads = [] + + def __call__(self, env, payload): + self.payloads.append(payload) + out = [] + for t in payload["targets"]: + m = t["model"] + if m in self.refuse: + out.append(dict(REFUSED, model=m, id=t["bedrock_ids"].get("us.", m))) + else: + out.append({"model": m, "id": t["bedrock_ids"].get("us.", m), "status": "pass", "code": "ok", "detail": "answered"}) + return {"provider": "bedrock", "region": "us-east-1", "inference_prefix": "us.", "results": out} + + +class ModelCheck(unittest.TestCase): + """The check before an update: a refused model holds it, a pass lets it go.""" + + def setUp(self): + self.db = FakeDynamo() + self.store = u.Store(self.db, "t") + self.builds, self.notices, self.texts = [], [], [] + real_build, real_notify = u.start_build, u.notify + u.start_build = lambda env, version, actor, mode, hid, extra=None: self.builds.append((version, actor, mode)) or "b-1" + u.notify = lambda subject, text, env=None: self.notices.append(subject) or self.texts.append(text) or 1 + self.addCleanup(setattr, u, "start_build", real_build) + self.addCleanup(setattr, u, "notify", real_notify) + real_check = u.start_check + u.start_check = lambda env, version: self.builds.append((version, "check", "release-check")) or "c-1" + self.addCleanup(setattr, u, "start_check", real_check) + self.env = {"CODERHELM_VERSION": "v1.0.0", "APP_URL": "https://helm.example.org", "UPDATE_PROJECT_NAME": "p", + "WORKER_FUNCTION_NAME": "coderhelm-prod-worker", "CONFIGURED_MODELS": "claude-opus-5-5,claude-sonnet-5-5"} + self.worker = FakeWorker() + # The update build checked v1.1.0's signature and models.json. + self.store.put("MANIFEST#v1.1.0", {"verified": True, "manifest": MANIFEST}) + u.handle({"action": "settings", "settings": {"auto": True, "day": "daily"}}, self.env, self.store, SUNDAY_3AM, self.releases) + + def releases(self, _repo): + return [rel("v1.1.0")] + + def tick(self, at): + return u.handle({"action": "tick"}, self.env, self.store, at, self.releases, self.worker) + + def test_a_refused_model_holds_the_update_and_tells_the_admins_once(self): + d = self.tick(SUNDAY_3AM) + self.assertEqual(d["action"], "notify") + self.assertIn("model this release calls was refused", d["reason"]) + self.assertEqual(self.builds, []) + self.assertIn("Update to v1.1.0 needs your action", self.notices) + text = self.texts[self.notices.index("Update to v1.1.0 needs your action")] + self.assertIn("claude-sonnet-5-5", text) + self.assertIn("#/modelaccess", text) + self.assertIn("done by a person in the AWS console", text) + # The worker was asked with the release's Bedrock ids per prefix. + t = self.worker.payloads[0]["targets"] + self.assertEqual([x["model"] for x in t], ["claude-opus-5-5", "claude-sonnet-5-5"]) + self.assertEqual(t[0]["bedrock_ids"]["eu."], "eu.anthropic.claude-opus-5-5") + # Status carries the check for Settings, System and Setup. + s = u.handle({"action": "status"}, self.env, self.store, SUNDAY_3AM, self.releases) + self.assertFalse(s["model_check"]["ok"]) + self.assertTrue(s["model_check"]["results"][1]["required"]) + # An hour later: not checked again, not notified again. + self.tick(SUNDAY_3AM + timedelta(hours=1)) + self.assertEqual(len(self.worker.payloads), 1) + self.assertEqual(self.notices.count("Update to v1.1.0 needs your action"), 1) + + def test_the_daily_retry_applies_the_update_once_it_passes(self): + self.tick(SUNDAY_3AM) + self.assertEqual(self.builds, []) + # A person submitted the form; the next day's check passes. + self.worker.refuse = set() + nextday = SUNDAY_3AM + timedelta(days=1) + d = self.tick(nextday) + self.assertEqual(d["action"], "update") + self.assertEqual(self.builds, [("v1.1.0", "auto", "update")]) + # Checked on first sight, the daily retry, and again right before applying. + self.assertEqual(len(self.worker.payloads), 3) + self.assertEqual(self.notices.count("Update to v1.1.0 needs your action"), 1) + + def test_a_pass_applies_in_the_window(self): + self.worker.refuse = set() + d = self.tick(SUNDAY_3AM) + self.assertEqual(d["action"], "update") + self.assertEqual(self.builds[0][0], "v1.1.0") + self.assertNotIn("Update to v1.1.0 needs your action", self.notices) + + def test_a_refusal_found_right_before_applying_stops_it(self): + # Checked an hour before the window: passes, nothing applied yet. + self.worker.refuse = set() + self.assertEqual(self.tick(SUNDAY_3AM - timedelta(hours=1))["action"], "notify") + # Model access was turned off since: the check right before applying stops it. + self.worker.refuse = {"claude-opus-5-5"} + d = self.tick(SUNDAY_3AM) + self.assertEqual(d["action"], "none") + self.assertEqual(self.builds, []) + self.assertIn("Update to v1.1.0 needs your action", self.notices) + + def test_update_now_is_refused_with_the_check_and_no_override(self): + with self.assertRaises(u.ModelsBlocked) as e: + u.handle({"action": "update_now", "actor": "a@example.org", "skip_check": True}, self.env, self.store, + SUNDAY_3AM, self.releases, self.worker) + self.assertTrue(str(e.exception).startswith("Update to v1.1.0 needs your action")) + self.assertEqual(e.exception.record["results"][1]["code"], "use_case_required") + self.assertNotIn("skippable", e.exception.record) + self.assertEqual(self.builds, []) + # Fixed: Update now goes ahead. + self.worker.refuse = set() + e2 = u.handle({"action": "update_now", "actor": "a@example.org"}, self.env, self.store, SUNDAY_3AM, + self.releases, self.worker) + self.assertEqual(e2["version"], "v1.1.0") + + def test_skip_is_offered_only_for_a_model_the_release_doesnt_call(self): + # The worker reports a model the release doesn't call (not required). + class Extra(FakeWorker): + def __call__(self, env, payload): + out = super().__call__(env, payload) + out["results"].append(dict(REFUSED, model="claude-haiku-4-5", id="us.anthropic.claude-haiku-4-5-20251001-v1:0")) + return out + self.worker = Extra(refuse=()) + with self.assertRaises(u.ModelsBlocked) as e: + u.handle({"action": "update_now", "actor": "a"}, self.env, self.store, SUNDAY_3AM, self.releases, self.worker) + self.assertTrue(e.exception.record["skippable"]) + self.assertIn("you can skip this check", str(e.exception)) + done = u.handle({"action": "update_now", "actor": "a", "skip_check": True}, self.env, self.store, SUNDAY_3AM, + self.releases, self.worker) + self.assertEqual(done["note"], "model check skipped for claude-haiku-4-5") + + def test_check_again_runs_now(self): + self.tick(SUNDAY_3AM) + self.worker.refuse = set() + r = u.handle({"action": "model_check"}, self.env, self.store, SUNDAY_3AM + timedelta(minutes=5), + self.releases, self.worker) + self.assertTrue(r["model_check"]["ok"]) + self.assertEqual(len(self.worker.payloads), 2) + + def test_a_signed_release_without_a_manifest_has_nothing_to_check(self): + self.store.put("MANIFEST#v1.1.0", {"verified": True, "manifest": None}) + r = u.handle({"action": "model_check"}, self.env, self.store, SUNDAY_3AM, self.releases, self.worker) + self.assertTrue(r["model_check"]["ok"]) + self.assertEqual(self.worker.payloads, []) + + def test_the_manifest_is_read_only_after_the_signature_check(self): + # Nothing verified yet: the build is started in its read-only mode, and the update waits. + self.db.items.pop(("SYSTEM", "MANIFEST#v1.1.0")) + self.worker.refuse = set() + d = self.tick(SUNDAY_3AM) + self.assertEqual(self.builds, [("v1.1.0", "check", "release-check")]) + self.assertEqual(d["action"], "notify") + self.assertEqual(self.worker.payloads, []) + self.assertTrue(self.store.get("MODEL_CHECK")["pending"]) + with self.assertRaises(u.ModelsBlocked) as e: + u.handle({"action": "update_now", "actor": "a"}, self.env, self.store, SUNDAY_3AM, self.releases, self.worker) + self.assertIn("signature", str(e.exception)) + # Not started again within 30 minutes. + self.assertEqual(self.builds, [("v1.1.0", "check", "release-check")]) + # A failed signature check trusts nothing. + u.handle({"action": "models_verified", "version": "v1.1.0", "status": "failed", "reason": "bad signature"}, + self.env, self.store, SUNDAY_3AM, self.releases, self.worker) + self.assertIsNone(self.store.get("MANIFEST#v1.1.0")) + # The build reports the verified file: the check runs at once. + r = u.handle({"action": "models_verified", "version": "v1.1.0", "status": "verified", "manifest": MANIFEST}, + self.env, self.store, SUNDAY_3AM, self.releases, self.worker) + self.assertTrue(r["model_check"]["ok"]) + self.assertEqual(len(self.worker.payloads), 1) + # A manifest for another release is refused. + with self.assertRaises(ValueError): + u.handle({"action": "models_verified", "version": "v1.2.0", "status": "verified", "manifest": MANIFEST}, + self.env, self.store, SUNDAY_3AM, self.releases, self.worker) + + def test_the_source_never_downloads_models_json_itself(self): + src = PATH.read_text() + self.assertNotIn("releases/download", src) + + def test_a_worker_that_doesnt_answer_holds_the_update(self): + def broken(env, payload): + raise RuntimeError("timeout") + d = u.handle({"action": "tick"}, self.env, self.store, SUNDAY_3AM, self.releases, broken) + self.assertEqual(d["action"], "notify") + self.assertEqual(self.builds, []) + self.assertEqual(self.store.get("MODEL_CHECK")["results"][0]["code"], "unreachable") + + def test_the_handler_returns_the_check_with_a_refusal(self): + real_handle = u.handle + u.handle = lambda event, env, store, now: real_handle(event, env, store, now, self.releases, self.worker) + self.addCleanup(setattr, u, "handle", real_handle) + real_client = u.client + u.client = lambda name, region=None: self.db + self.addCleanup(setattr, u, "client", real_client) + import os + old = dict(os.environ) + os.environ.update(self.env, SETTINGS_TABLE_NAME="t") + self.addCleanup(lambda: (os.environ.clear(), os.environ.update(old))) + out = u.handler({"action": "update_now", "actor": "a"}, None) + self.assertFalse(out["ok"]) + self.assertEqual(out["model_check"]["version"], "v1.1.0") + + +class NeverAcceptsTerms(unittest.TestCase): + """The updater only checks: no subscription, agreement or form is ever sent.""" + + def test_the_source_never_calls_an_accepting_api(self): + src = PATH.read_text() + for word in ("aws-marketplace", "marketplace", "create_foundation_model_agreement", + "put_use_case_for_model_access", "accept_agreement", "subscribe("): + code = "\n".join(l for l in src.splitlines() if not l.strip().startswith("#") and '"""' not in l) + self.assertNotIn(word, code.lower() if word.islower() else code, word) + + def test_the_worker_call_is_the_only_aws_call(self): + calls = [] + + class Recorder: + def __getattr__(self, name): + def f(**kw): + calls.append(name) + return {"Payload": type("P", (), {"read": lambda self: json.dumps({"results": []}).encode()})()} + return f + real = u.client + u.client = lambda name, region=None: calls.append(f"client:{name}") or Recorder() + self.addCleanup(setattr, u, "client", real) + u.invoke_worker({"WORKER_FUNCTION_NAME": "w"}, {"targets": []}) + self.assertEqual(calls, ["client:lambda", "invoke"]) + + class FakeLambda: def __init__(self, conflicts=0): self.env = {"f-gateway": {"A": "1"}, "f-worker": {}} diff --git a/lambda/updater/handler.py b/lambda/updater/handler.py index 7e625d26b..c8120143b 100644 --- a/lambda/updater/handler.py +++ b/lambda/updater/handler.py @@ -26,6 +26,15 @@ the build that puts the domain on CloudFront (mode "domain"). Also every 5 minutes (EventBridge). - domain_remove back to the AWS (CloudFront) address. +- model_check every model the next release calls gets one test call through + the install's provider (Settings, System, Models), made by the + worker with the install's own role or key. Also before every + update (automatic or Update now), on first sight of a release, + and once a day while a model is refused. A refused model holds + the update: admins are told which model, the fix and the console + page, and it applies by itself once the check passes (with + auto-update on). Nothing here accepts terms or subscribes to + anything; a person does that in the AWS console. The build itself (CodeBuild, infra/lib/updates-stack.ts) runs `coderhelm-selfhost update`: health check, checksum and signature check, @@ -62,6 +71,8 @@ RELEASE_REPO = "CoderHelm/coderhelm-platform" RELEASES_URL = f"https://api.github.com/repos/{RELEASE_REPO}/releases?per_page=30" RUNNING_STALE = timedelta(hours=3) +# A refused model is checked again this often (and a pass re-proven before applying). +MODEL_RETRY = timedelta(days=1) PK = "SYSTEM" DEFAULT_SETTINGS = { @@ -200,7 +211,7 @@ def pick_latest(releases, channel, current): return best -def decide(now_utc, settings, current, releases, state): +def decide(now_utc, settings, current, releases, state, model_check=None): """What the hourly check does: none, notify or update (with the reason).""" latest = pick_latest(releases, settings["channel"], current) if not latest: @@ -212,6 +223,8 @@ def decide(now_utc, settings, current, releases, state): quiet = {"action": "notify" if notify else "none", "version": v} if v in (state.get("failed_versions") or []): return {**quiet, "reason": "this version failed before; an admin can retry it"} + if blocking(model_check, v): + return {**quiet, "reason": "a model this release calls was refused; checking again daily"} if not settings["auto"]: return {**quiet, "reason": "auto-update is off"} if latest["breaking"] and settings["majors"] == "ask": @@ -664,6 +677,201 @@ def domain_finished(store, env, now, entry, status): return {"status": status, "domain": dom.get("state") or "none"} +# ── The model check before an update ────────────────────────────────────── +# +# One record on the settings table (pk SYSTEM, sk MODEL_CHECK): +# {version, checked_at, provider, region, inference_prefix, ok, results, +# notified} +# results: one per model, from the worker (common::model_access): model, id, +# status (pass, fail, skip), code, detail, fix, url, and `required` (the +# release calls it, or the deploy config names it). +# +# The release's models.json (written by its release workflow from the code, +# selfhost/release-models.mjs, and covered by the signed SHA256SUMS) lists +# the models it calls and their Bedrock ids for every inference profile +# prefix. The updater never downloads it: the release +# check build (its own read-only project) checks SHA256SUMS's signature and +# the file's checksum, and reports it back (models_verified). Until then the check is pending and +# holds the update. A signed release without one (older releases) has +# nothing to check. +# +# The check only calls models. It never subscribes, accepts an agreement or +# submits a form for anyone: those stay a person's action in the console. + + +class ModelsBlocked(ValueError): + """Update now refused by the model check (the record goes with it).""" + + def __init__(self, message, record): + super().__init__(message) + self.record = record + + +VERIFY_RETRY = timedelta(minutes=30) + + +def verified_manifest(store, version): + """(known, manifest): the release's models.json as the update build + reported it after checking SHA256SUMS's signature and the file's + checksum. Never read from anywhere else: an unverified file is never + trusted. `manifest` is None for a signed release that lists no models.""" + rec = store.get(f"MANIFEST#{version}") + if rec is None or not rec.get("verified"): + return False, None + return True, rec.get("manifest") + + +def start_check(env, version): + """Starts the release check build (infra/lib/updates-stack.ts, + releaseCheckBuildSpec): read-only, it only verifies and reports.""" + r = client("codebuild").start_build( + projectName=env["RELEASE_CHECK_PROJECT_NAME"], + environmentVariablesOverride=[{"name": "VERSION", "value": str(version), "type": "PLAINTEXT"}], + ) + return r["build"]["id"] + + +def start_verify(store, env, now, version): + """Starts the release check: it verifies the release's signature, reads + models.json only when the signed checksums list it and it matches, and + reports back (models_verified). At most once every 30 minutes per release.""" + state = store.get("UPDATE_STATE", {}) + v = state.get("verifying") or {} + if v.get("version") == version: + try: + if now - datetime.fromisoformat(v["at"]) < VERIFY_RETRY: + return False + except (KeyError, ValueError): + pass + try: + start_check(env, version) + except Exception as e: + logger.warning(f"Release check not started: {e}") + return False + state["verifying"] = {"version": version, "at": now.isoformat()} + store.put("UPDATE_STATE", state) + return True + + +def configured_models(env): + return [m for m in (env.get("CONFIGURED_MODELS") or "").split(",") if m] + + +def check_targets(manifest, env): + """Every model the release calls, plus the models the deploy config names, + with the release's Bedrock id for each prefix.""" + calls = list(manifest.get("calls") or []) + for m in configured_models(env): + if m not in calls: + calls.append(m) + ids = manifest.get("bedrock") or {} + return [{"model": m, "bedrock_ids": ids.get(m) or {}} for m in calls] + + +def invoke_worker(env, payload): + """The worker makes the test calls (its role, its meter) and explains them.""" + r = client("lambda").invoke( + FunctionName=env["WORKER_FUNCTION_NAME"], + InvocationType="RequestResponse", + Payload=json.dumps({"model_check": payload}).encode(), + ) + if r.get("FunctionError"): + raise RuntimeError(f"the worker's model check failed: {r['Payload'].read()[:300]!r}") + return json.loads(r["Payload"].read() or b"{}") + + +def blocking(record, version): + """True when the check for `version` found a model the release calls + refused, or hasn't run yet because the release's signature is being checked.""" + return bool(record and record.get("version") == version + and (record.get("pending") or failures(record, required=True))) + + +def failures(record, required=None): + out = [r for r in (record or {}).get("results") or [] if r.get("status") == "fail"] + if required is not None: + out = [r for r in out if bool(r.get("required", True)) == required] + return out + + +def model_check(store, env, now, version, repo, probe=invoke_worker): + """Runs the check for `version` and stores it. Until the release's + signature has been checked, the record is pending (and holds updates).""" + known, manifest = verified_manifest(store, version) + if not known: + start_verify(store, env, now, version) + record = {"version": version, "checked_at": now.isoformat(), "ok": False, "pending": True, "results": [], + "note": "checking the release's signature before reading the models it calls"} + store.put("MODEL_CHECK", dict(record, notified=False)) + return record + if manifest is None: + record = {"version": version, "checked_at": now.isoformat(), "ok": True, "results": [], + "note": "this release lists no models to check"} + else: + targets = check_targets(manifest, env) + required = set(manifest.get("calls") or []) | set(configured_models(env)) + models = store.get("MODELS") or {} + try: + answer = probe(env, {"targets": targets, "probe_team": models.get("probe_team")}) + except Exception as e: # the worker didn't answer: unknown, not refused + logger.warning(f"Model check not run: {e}") + answer = {"results": [{"model": t["model"], "id": t["model"], "status": "fail", "code": "unreachable", + "detail": "The model check couldn't run.", + "fix": "Check again in a few minutes; if it keeps failing, see the worker's log.", + } for t in targets]} + results = [dict(r, required=r.get("model") in required) for r in answer.get("results") or []] + record = { + "version": version, "checked_at": now.isoformat(), + "provider": answer.get("provider"), "region": answer.get("region"), + "inference_prefix": answer.get("inference_prefix"), + "ok": not any(r.get("status") == "fail" for r in results), + "results": results, + } + old = store.get("MODEL_CHECK") or {} + # Admins hear about a refused model once per release, not every day. + record["notified"] = bool(old.get("version") == version and old.get("notified")) + store.put("MODEL_CHECK", record) + return record + + +def needs_check(record, version, now): + if not record or record.get("version") != version or record.get("pending"): + return True + try: + at = datetime.fromisoformat(record["checked_at"]) + except (KeyError, ValueError): + return True + return now - at >= MODEL_RETRY + + +def blocked_text(record, env): + lines = [] + for f in failures(record, required=True): + lines.append(f"- {f.get('model')}: {f.get('detail')}\n Fix: {f.get('fix')}" + (f"\n {f['url']}" if f.get("url") else "")) + return ( + f"CoderHelm won't update to {record['version']} until every model it calls answers.\n\n" + + "\n".join(lines) + + "\n\nAgreeing to model terms and the Bedrock use case form are done by a person in the AWS console; " + "CoderHelm only checks. The check runs again daily, and the update applies by itself once it passes " + "if auto-update is on. Check again now: " + f"{app_url(env)}/settings/system/#readiness" + ) + + +def notify_blocked(store, env, record): + if record.get("notified") or not failures(record, required=True): + return + notify(f"Update to {record['version']} needs your action", blocked_text(record, env), env) + record["notified"] = True + store.put("MODEL_CHECK", record) + + +def blocked_message(record): + first = failures(record, required=True) or failures(record) + f = first[0] if first else {} + return f"Update to {record['version']} needs your action: {f.get('detail', 'a model was refused.')} {f.get('fix', '')}".strip() + + # ── Actions ─────────────────────────────────────────────────────────────── def app_url(env): @@ -692,7 +900,8 @@ def begin(store, env, now, version, actor, mode, extra=None, note=None): return dict(entry, id=hid) -def handle(event, env, store, now, fetch=fetch_releases): +def handle(event, env, store, now, fetch=fetch_releases, probe=None): + probe = probe or invoke_worker action = (event or {}).get("action", "tick") current = env.get("CODERHELM_VERSION", "") repo = env.get("RELEASE_REPO", "CoderHelm/coderhelm-platform") @@ -718,6 +927,9 @@ def handle(event, env, store, now, fetch=fetch_releases): # update preflight shows them with the reason from history. "failed_versions": sorted(state.get("failed_versions") or []), "history": store.history(), + # The model check for the latest release (Settings, System and Setup). + "model_check": (lambda mc: mc if latest and mc and mc.get("version") == latest["version"] else None)( + store.get("MODEL_CHECK")), } if action == "settings": @@ -737,7 +949,50 @@ def handle(event, env, store, now, fetch=fetch_releases): # Forward only: an older (or the same) release is a rollback. if parse_version(current) and compare(version, current) <= 0: raise ValueError(f"{version} is not newer than {current}; use Roll back to go to an earlier release") - return begin(store, env, now, version, event.get("actor") or "unknown", "update") + if running(state, now): + raise ValueError("an update is already running") + mc = model_check(store, env, now, version, repo, probe) + if mc.get("pending"): + raise ModelsBlocked(f"Checking {version}'s signature and the models it calls first; try Update now again in a few minutes.", mc) + if failures(mc, required=True): + # No override: the release would call a model this install can't. + raise ModelsBlocked(blocked_message(mc), mc) + note = None + if failures(mc): + if not event.get("skip_check"): + raise ModelsBlocked(blocked_message(mc) + " This release doesn't call it, so you can skip this check.", + dict(mc, skippable=True)) + note = "model check skipped for " + ", ".join(f.get("model", "?") for f in failures(mc)) + return begin(store, env, now, version, event.get("actor") or "unknown", "update", note=note) + + if action == "models_verified": + # From the release check build, after the signature check. + version = event.get("version") + if not parse_version(version): + raise ValueError("version must look like v1.2.3") + if event.get("status") != "verified": + logger.warning(f"Release check for {version} failed: {event.get('reason')}") + state.pop("verifying", None) + store.put("UPDATE_STATE", state) + return {"verified": False} + m = event.get("manifest") + if m is not None and (not isinstance(m, dict) or not isinstance(m.get("calls"), list) or m.get("version") not in (None, version)): + raise ValueError("models.json isn't a model manifest for this release") + store.put(f"MANIFEST#{version}", {"verified": True, "manifest": m, "at": now.isoformat()}) + state.pop("verifying", None) + store.put("UPDATE_STATE", state) + mc = model_check(store, env, now, version, repo, probe) + notify_blocked(store, env, mc) + return {"verified": True, "model_check": mc} + + if action == "model_check": + version = event.get("version") + if not version: + latest = pick_latest(releases_cached(store, repo, now.timestamp(), fetch), settings["channel"], current) + if not latest: + return {"model_check": None} + version = latest["version"] + return {"model_check": model_check(store, env, now, version, repo, probe)} if action == "rollback": target = event.get("version") @@ -801,7 +1056,13 @@ def handle(event, env, store, now, fetch=fetch_releases): if action == "tick": rel = releases_cached(store, repo, now.timestamp(), fetch) - d = decide(now, settings, current, rel, state) + latest = pick_latest(rel, settings["channel"], current) + mc = store.get("MODEL_CHECK") + # First sight of a release, and daily while a model is refused. + if latest and not running(state, now) and needs_check(mc, latest["version"], now): + mc = model_check(store, env, now, latest["version"], repo, probe) + notify_blocked(store, env, mc) + d = decide(now, settings, current, rel, state, mc) if d["action"] in ("notify", "update") and state.get("notified_version") != d.get("version"): latest = pick_latest(rel, settings["channel"], current) or {} notify( @@ -815,7 +1076,14 @@ def handle(event, env, store, now, fetch=fetch_releases): state["notified_version"] = d["version"] store.put("UPDATE_STATE", state) if d["action"] == "update": - begin(store, env, now, d["version"], "auto", "update") + # Proven again right before applying, whatever the last check said. + mc = model_check(store, env, now, d["version"], repo, probe) + if blocking(mc, d["version"]): + notify_blocked(store, env, mc) + d = {"action": "none", "version": d["version"], + "reason": "a model this release calls was refused; checking again daily"} + else: + begin(store, env, now, d["version"], "auto", "update") logger.info(json.dumps(d)) return d @@ -828,5 +1096,7 @@ def handler(event, context): now = datetime.now(timezone.utc) try: return {"ok": True, **handle(event, env, store, now)} + except ModelsBlocked as e: + return {"ok": False, "error": str(e), "model_check": e.record} except ValueError as e: return {"ok": False, "error": str(e)} diff --git a/selfhost/launch/release-models.mjs b/selfhost/launch/release-models.mjs new file mode 100644 index 000000000..c7b0eee90 --- /dev/null +++ b/selfhost/launch/release-models.mjs @@ -0,0 +1,43 @@ +// The release's model manifest, `models.json`: the models a release calls, +// read from the code (services/common/release_models.json, which the +// services build in), with the Bedrock id of each model for every inference +// profile prefix. The release workflow publishes it next to the other +// assets (and in SHA256SUMS); the updater reads it before it applies a +// release and checks each model through the install's provider. +// +// node selfhost/launch/release-models.mjs v1.2.3 > dist/models.json +import fs from "node:fs"; +import { fileURLToPath } from "node:url"; + +export const SOURCE = fileURLToPath(new URL("../../services/common/release_models.json", import.meta.url)); + +/** The inference profile prefixes a release lists ids for ("" is in-region). */ +export const PREFIXES = ["us.", "eu.", "apac.", "global.", ""]; + +/** The Bedrock id for a model name (services/common/src/model_provider.rs, map_model_id). */ +export function bedrockId(model, prefix, names) { + return `${prefix}anthropic.${names[model] ?? model}`; +} + +/** models.json for a release, from the code's manifest. */ +export function releaseModels(source, version) { + if (!/^v\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(version)) throw new Error(`${version} is not a release tag`); + if (source.schema !== 1 || !Array.isArray(source.calls) || source.calls.length === 0) { + throw new Error("release_models.json: schema 1 with a non-empty calls list"); + } + const names = source.bedrock_names ?? {}; + const models = [...new Set([...source.calls, ...(source.selectable ?? [])])]; + return { + schema: 1, + version, + calls: source.calls, + selectable: source.selectable ?? [], + anthropic: Object.fromEntries(models.map((m) => [m, m])), + bedrock: Object.fromEntries(models.map((m) => [m, Object.fromEntries(PREFIXES.map((p) => [p, bedrockId(m, p, names)]))])), + }; +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === fs.realpathSync(process.argv[1])) { + const doc = releaseModels(JSON.parse(fs.readFileSync(SOURCE, "utf8")), process.argv[2] ?? ""); + process.stdout.write(`${JSON.stringify(doc, null, 2)}\n`); +} diff --git a/selfhost/launch/release-models.test.mjs b/selfhost/launch/release-models.test.mjs new file mode 100644 index 000000000..8917cb187 --- /dev/null +++ b/selfhost/launch/release-models.test.mjs @@ -0,0 +1,40 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import { execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { PREFIXES, SOURCE, releaseModels } from "./release-models.mjs"; + +const source = JSON.parse(fs.readFileSync(SOURCE, "utf8")); +const RELEASE = fs.readFileSync(fileURLToPath(new URL("../../.github/workflows/release.yml", import.meta.url)), "utf8"); + +test("models.json lists the code's models with a Bedrock id for every prefix", () => { + const m = releaseModels(source, "v1.2.3"); + assert.equal(m.version, "v1.2.3"); + assert.deepEqual(m.calls, source.calls); + for (const model of m.calls) { + assert.equal(m.anthropic[model], model); + assert.deepEqual(Object.keys(m.bedrock[model]), PREFIXES); + assert.equal(m.bedrock[model]["eu."], `eu.anthropic.${model}`); + assert.equal(m.bedrock[model][""], `anthropic.${model}`); + } + // A model whose Bedrock id carries a date gets it. + assert.equal(m.bedrock["claude-haiku-4-5"]["us."], "us.anthropic.claude-haiku-4-5-20251001-v1:0"); +}); + +test("refuses a bad tag or an empty manifest", () => { + assert.throws(() => releaseModels(source, "latest"), /not a release tag/); + assert.throws(() => releaseModels({ schema: 1, calls: [] }, "v1.0.0"), /non-empty calls/); +}); + +test("the command prints the document", () => { + const out = JSON.parse(execFileSync(process.execPath, [fileURLToPath(new URL("./release-models.mjs", import.meta.url)), "v0.9.0"], { encoding: "utf8" })); + assert.equal(out.version, "v0.9.0"); + assert.deepEqual(out.calls, source.calls); +}); + +test("the release workflow publishes models.json, checksummed, from the code", () => { + assert.match(RELEASE, /node selfhost\/launch\/release-models\.mjs "\$TAG" > dist\/models\.json/); + const sums = RELEASE.split("\n").find((l) => l.includes("> SHA256SUMS")); + assert.ok(sums && sums.includes("models.json"), "models.json is in SHA256SUMS"); +}); diff --git a/services/common/release_models.json b/services/common/release_models.json new file mode 100644 index 000000000..cd551317d --- /dev/null +++ b/services/common/release_models.json @@ -0,0 +1,21 @@ +{ + "schema": 1, + "about": "The models this release calls. Read by the services (common::model_ids), the release workflow (selfhost/release-models.mjs writes models.json into each release) and the updater's model check. A test in common::model_ids fails when code names a model id that isn't listed here.", + "calls": ["claude-opus-5-5", "claude-sonnet-5-5"], + "selectable": [ + "claude-fable-5-1", + "claude-opus-5-5", + "claude-sonnet-5-5", + "claude-opus-4-8", + "claude-opus-4-7", + "claude-opus-4-6", + "claude-sonnet-4-6", + "claude-sonnet-4-5", + "claude-haiku-4-5", + "claude-haiku-4-5-20251001" + ], + "bedrock_names": { + "claude-haiku-4-5": "claude-haiku-4-5-20251001-v1:0", + "claude-haiku-4-5-20251001": "claude-haiku-4-5-20251001-v1:0" + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index e13d7d026..eeb85a3d6 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -5,6 +5,7 @@ /// the gateway's dashboard memory-delete (an unlocked delete raced a concurrent /// run's upload, silently resurrecting deleted memories). pub mod memlock; +pub mod model_access; pub mod model_ids; /// Expiring once-only claims (dedup markers, leases) on the settings table. diff --git a/services/common/src/model_access.rs b/services/common/src/model_access.rs new file mode 100644 index 000000000..07c126e16 --- /dev/null +++ b/services/common/src/model_access.rs @@ -0,0 +1,309 @@ +//! Can this install call a model, and if not, what exactly a person must do. +//! +//! One test call per model (one token out) answers it. The answer is mapped +//! here to a code, one sentence on what is wrong and one on the fix, with +//! the AWS or Anthropic console page to do it on. Setup, the provider switch +//! in Settings, System, Models, and the updater's check before an update all +//! show the same words. +//! +//! CoderHelm never accepts terms for anyone: agreeing to Anthropic's model +//! terms, submitting Bedrock's use case form and the AWS Marketplace +//! subscription stay a person's action in the AWS console. The install's +//! roles can't do them (no `aws-marketplace:Subscribe`); these fixes only +//! link to the page and the next check sees the result. + +use serde::Serialize; + +use crate::model_provider::Provider; + +/// What one test call found. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Access { + /// The model's name (`claude-opus-5-5`). + pub model: String, + /// What was called: the Bedrock id, or the name on the Anthropic API. + pub id: String, + /// `pass`, `fail`, or `skip` (nothing to check with). + pub status: &'static str, + /// `ok`, or why not (see [`refusal_code`]). + pub code: &'static str, + /// What is true now, in one sentence. + pub detail: String, + /// The fix in one sentence (empty when it passes). + #[serde(skip_serializing_if = "String::is_empty")] + pub fix: String, + /// Where to do it. + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, + /// A dashboard page that helps. + #[serde(skip_serializing_if = "Option::is_none")] + pub href: Option, +} + +/// A test call's raw answer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Answer { + Ok, + /// The provider refused: its status, and what it said. + Refused(u16, String), + /// No answer (network, timeout). + Unreachable(String), + /// Anthropic API: no key to check with. + NoKey, +} + +/// Bedrock's console page where model access, the use case form and the +/// model terms are handled. +pub fn bedrock_access_url(region: &str) -> String { + format!("https://console.aws.amazon.com/bedrock/home?region={region}#/modelaccess") +} + +/// Where Bedrock lists which models each region offers. +pub const BEDROCK_REGIONS_URL: &str = + "https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html"; +pub const IAM_ROLES_URL: &str = "https://console.aws.amazon.com/iam/home#/roles"; +pub const AWS_HEALTH_URL: &str = "https://health.aws.amazon.com/health/status"; +pub const ANTHROPIC_KEYS_URL: &str = "https://console.anthropic.com/settings/keys"; +pub const ANTHROPIC_STATUS_URL: &str = "https://status.anthropic.com"; + +/// Bedrock's refusal as a code, one for each fix. +pub fn refusal_code(status: u16, message: &str) -> &'static str { + let m = message.to_ascii_lowercase(); + if m.contains("use case") || m.contains("use-case") { + "use_case_required" + } else if m.contains("being processed") || m.contains("subscription") && m.contains("pending") { + "subscription_pending" + } else if m.contains("marketplace") + || m.contains("payment") + || m.contains("agreement") + || m.contains("subscri") + { + "marketplace_failed" + } else if m.contains("not authorized to perform") || m.contains("explicit deny") { + "iam_denied" + } else if m.contains("don't have access") + || m.contains("do not have access") + || m.contains("access to the model") + { + "access_denied" + } else if m.contains("not available") + || m.contains("not supported") + || m.contains("model identifier is invalid") + || status == 404 + { + "not_available" + } else if status == 403 { + "access_denied" + } else if status == 429 || status >= 500 { + "transient" + } else { + "unknown" + } +} + +/// One test call's answer, explained. +pub fn explain( + provider: Provider, + model: &str, + id: &str, + region: &str, + prefix: &str, + answer: &Answer, +) -> Access { + let base = |status, code, detail: String, fix: String, url: Option| Access { + model: model.to_string(), + id: id.to_string(), + status, + code, + detail, + fix, + url, + href: None, + }; + let via = match provider { + Provider::Bedrock => "Amazon Bedrock", + Provider::Anthropic => "the Anthropic API", + }; + match (provider, answer) { + (_, Answer::Ok) => base( + "pass", + "ok", + format!("{id} answered through {via}."), + String::new(), + None, + ), + (_, Answer::NoKey) => Access { + href: Some("/settings/models".into()), + ..base( + "skip", + "no_key", + format!("No Anthropic API key to check {model} with."), + "Add your team's key in Settings, AI models, then check again.".into(), + Some(ANTHROPIC_KEYS_URL.into()), + ) + }, + (_, Answer::Unreachable(_)) => base( + "fail", + "unreachable", + format!("The test call to {id} got no answer from {via}."), + "Check again in a minute; if it keeps failing, check the provider's status page." + .into(), + Some(match provider { + Provider::Bedrock => AWS_HEALTH_URL.into(), + Provider::Anthropic => ANTHROPIC_STATUS_URL.into(), + }), + ), + (Provider::Anthropic, Answer::Refused(status, _)) => match status { + 401 | 403 => Access { + href: Some("/settings/models".into()), + ..base( + "fail", + "key_refused", + format!("Anthropic refused the API key the test call to {model} used."), + "Create a new key in the Anthropic console and save it in Settings, AI models." + .into(), + Some(ANTHROPIC_KEYS_URL.into()), + ) + }, + 404 => base( + "fail", + "not_available", + format!("Anthropic doesn't offer {model} to this key."), + "Check that the key belongs to an organization that can use this model.".into(), + Some(ANTHROPIC_KEYS_URL.into()), + ), + s => base( + "fail", + if *s == 429 || *s >= 500 { + "transient" + } else { + "unknown" + }, + format!("The test call to {model} answered {s}."), + "Check again in a minute; if it keeps failing, check Anthropic's status page." + .into(), + Some(ANTHROPIC_STATUS_URL.into()), + ), + }, + (Provider::Bedrock, Answer::Refused(status, msg)) => { + let code = refusal_code(*status, msg); + let access = bedrock_access_url(region); + let (detail, fix, url) = match code { + "access_denied" => ( + format!("Bedrock refused {id} in {region}: model access isn't enabled."), + format!("Open Model access in the Bedrock console for {region}, enable {model}, then check again."), + access, + ), + "use_case_required" => ( + format!("Bedrock refused {id}: Anthropic's use case details haven't been submitted for this AWS account."), + "Submit the use case details on the Bedrock console's Model access page (a person fills in the form once per account), then check again.".into(), + access, + ), + "subscription_pending" => ( + format!("Bedrock is still setting up the subscription for {model}."), + "Wait a few minutes for AWS to finish, then check again.".into(), + access, + ), + "marketplace_failed" => ( + format!("Bedrock refused {id}: Anthropic's terms for this model haven't been accepted in AWS Marketplace."), + format!("Have someone allowed to subscribe in AWS Marketplace accept the terms for {model} on the Bedrock console's Model access page, then check again."), + access, + ), + "iam_denied" => ( + format!("The CoderHelm roles aren't allowed to call {id}."), + "Deploy the install again so its roles may call Bedrock models, or remove the policy that denies it, then check again.".into(), + IAM_ROLES_URL.into(), + ), + "not_available" => ( + format!("{id} isn't offered in {region}{}.", if prefix.is_empty() { String::new() } else { format!(" with the {prefix} inference profile") }), + format!("Pick the inference profile prefix for your region, or set the exact Bedrock id for {model} under Advanced."), + BEDROCK_REGIONS_URL.into(), + ), + _ => ( + format!("Bedrock answered {status} to the test call to {id}."), + "Check again in a minute; if it keeps failing, check the AWS Health Dashboard.".into(), + AWS_HEALTH_URL.into(), + ), + }; + base("fail", code, detail, fix, Some(url)) + } + } +} + +/// Whether every result lets the work go ahead (a skip is not a refusal). +pub fn all_pass(results: &[Access]) -> bool { + results.iter().all(|r| r.status != "fail") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn bedrock(msg: &str, status: u16) -> Access { + explain( + Provider::Bedrock, + "claude-opus-5-5", + "us.anthropic.claude-opus-5-5", + "us-east-1", + "us.", + &Answer::Refused(status, msg.into()), + ) + } + + #[test] + fn every_bedrock_refusal_has_its_own_fix_and_link() { + let cases = [ + ("You don't have access to the model with the specified model ID.", 403, "access_denied", "Model access", "#/modelaccess"), + ("Model use case details have not been submitted for this account.", 400, "use_case_required", "use case details", "#/modelaccess"), + ("Your request is being processed", 400, "subscription_pending", "Wait a few minutes", "#/modelaccess"), + ("aws-marketplace:Subscribe failed: no valid payment method", 403, "marketplace_failed", "accept the terms", "#/modelaccess"), + ("Model access agreement not accepted", 403, "marketplace_failed", "accept the terms", "#/modelaccess"), + ("User: arn:aws:sts::111122223333:assumed-role/x is not authorized to perform: bedrock:Converse", 403, "iam_denied", "call Bedrock models", "iam/home"), + ("The provided model identifier is invalid.", 400, "not_available", "inference profile prefix", "models-regions"), + ("Throttled", 429, "transient", "Check again", "health.aws"), + ("boom", 400, "unknown", "Check again", "health.aws"), + ]; + for (msg, status, code, fix, url) in cases { + let a = bedrock(msg, status); + assert_eq!(a.status, "fail", "{msg}"); + assert_eq!(a.code, code, "{msg}"); + assert!(a.fix.contains(fix), "{msg}: {}", a.fix); + assert!(a.url.as_deref().unwrap().contains(url), "{msg}"); + assert!(!a.detail.is_empty()); + } + } + + #[test] + fn the_fixes_never_claim_coderhelm_accepts_terms() { + for code_msg in ["use case", "marketplace", "agreement"] { + let a = bedrock(code_msg, 403); + assert!(!a.fix.to_lowercase().contains("coderhelm will")); + assert!(a.fix.contains("console") || a.fix.contains("Model access")); + } + } + + #[test] + fn anthropic_answers_are_explained() { + let a = |ans: Answer| { + explain( + Provider::Anthropic, + "claude-sonnet-5-5", + "claude-sonnet-5-5", + "us-east-1", + "", + &ans, + ) + }; + assert_eq!(a(Answer::Ok).status, "pass"); + assert!(a(Answer::Ok).detail.contains("the Anthropic API")); + assert_eq!(a(Answer::Refused(401, String::new())).code, "key_refused"); + assert_eq!(a(Answer::Refused(404, String::new())).code, "not_available"); + assert_eq!(a(Answer::Refused(529, String::new())).code, "transient"); + let nokey = a(Answer::NoKey); + assert_eq!((nokey.status, nokey.code), ("skip", "no_key")); + assert_eq!(nokey.href.as_deref(), Some("/settings/models")); + assert_eq!(a(Answer::Unreachable("x".into())).code, "unreachable"); + assert!(all_pass(&[a(Answer::Ok), nokey])); + assert!(!all_pass(&[a(Answer::Refused(401, String::new()))])); + } +} diff --git a/services/common/src/model_ids.rs b/services/common/src/model_ids.rs index 66b251a2d..a17eb6045 100644 --- a/services/common/src/model_ids.rs +++ b/services/common/src/model_ids.rs @@ -26,10 +26,163 @@ pub fn is_retired(id: &str) -> bool { RETIRED.iter().any(|(old, _)| *old == id) } +// ── The release's model manifest ────────────────────────────────────────── +// +// `release_models.json` (next to this crate's Cargo.toml) lists the models +// this release calls. The services read it from here, the release workflow +// turns it into each release's `models.json` (selfhost/release-models.mjs, +// with the Bedrock ids for every inference profile prefix), and the updater +// checks the next release's list before it applies it. The test at the +// bottom fails when code names a model id the manifest doesn't list. + +/// The manifest's text, built into the binary. +pub const MANIFEST_JSON: &str = include_str!("../release_models.json"); + +/// The parsed manifest. +#[derive(Debug, Clone, serde::Deserialize)] +pub struct Manifest { + pub schema: u32, + /// Called by every install of this release (the default models): an + /// update or a provider switch waits until each one answers. + pub calls: Vec, + /// What a team may pick in Settings, AI models. + pub selectable: Vec, + /// Models whose Bedrock id isn't just their name (Bedrock has no undated + /// Haiku 4.5 id). + #[serde(default)] + pub bedrock_names: std::collections::BTreeMap, +} + +/// This release's manifest. +pub fn manifest() -> &'static Manifest { + static M: std::sync::OnceLock = std::sync::OnceLock::new(); + M.get_or_init(|| serde_json::from_str(MANIFEST_JSON).expect("release_models.json is valid")) +} + +/// The models this release calls on every install (the update check and a +/// provider switch probe each one). +pub fn release_calls() -> Vec<&'static str> { + manifest().calls.iter().map(String::as_str).collect() +} + +/// Whether a team may pick this model. +pub fn is_selectable(id: &str) -> bool { + manifest().selectable.iter().any(|m| m == id) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn the_manifest_reads_and_its_calls_are_selectable() { + let m = manifest(); + assert_eq!(m.schema, 1); + assert!(!m.calls.is_empty()); + for c in &m.calls { + assert!(is_selectable(c), "{c} is called but a team can't pick it"); + } + for (_, new) in RETIRED { + assert!( + is_selectable(new), + "{new} replaces a retired id but isn't listed" + ); + } + } + + /// Every model id written in the services, the Lambdas and the infra + /// config is in the manifest: a release can't start calling a model the + /// update check doesn't know about. Test code is left out (it names + /// made-up and old ids on purpose); a family prefix (`claude-opus-5`, + /// matched with `starts_with`) counts when a listed id starts with it. + #[test] + fn code_names_only_models_in_the_manifest() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut files = Vec::new(); + for (dir, ext) in [("services", "rs"), ("lambda", "py"), ("infra/lib", "ts")] { + collect(&root.join(dir), ext, &mut files); + } + assert!(files.len() > 50, "found only {} source files", files.len()); + let m = manifest(); + let known = |id: &str| { + m.calls.iter().chain(&m.selectable).any(|k| k == id) + || RETIRED.iter().any(|(old, _)| *old == id) + || m.calls + .iter() + .chain(&m.selectable) + .any(|k| k.starts_with(&format!("{id}-"))) + }; + let mut missing = Vec::new(); + for f in files { + let src = std::fs::read_to_string(&f).unwrap_or_default(); + for id in model_literals(non_test_part(&src)) { + if !known(&id) { + missing.push(format!("{}: {id}", f.display())); + } + } + } + assert!( + missing.is_empty(), + "model ids missing from services/common/release_models.json:\n{}", + missing.join("\n") + ); + } + + #[test] + fn literals_and_test_code_are_told_apart() { + let src = "let m = \"claude-opus-5-5\"; let b = 'claude-haiku-4-5';\n#[cfg(test)]\nmod tests { \"claude-imaginary-9\" }"; + assert_eq!( + model_literals(non_test_part(src)), + vec![ + "claude-opus-5-5".to_string(), + "claude-haiku-4-5".to_string() + ] + ); + // Not a whole id inside its quotes: a Bedrock id, a sentence. + assert!( + model_literals("\"us.anthropic.claude-opus-5-5\" \"use claude-opus-5-5 here\"") + .is_empty() + ); + } + + /// The source before its test module. + fn non_test_part(src: &str) -> &str { + src.find("#[cfg(test)]\nmod ") + .or_else(|| src.find("\nclass Test")) + .map_or(src, |i| &src[..i]) + } + + /// Quoted strings that are exactly a model id (`claude--...`). + fn model_literals(src: &str) -> Vec { + let re = regex::Regex::new(r#"["']((claude-[a-z]+-[0-9][a-z0-9-]*))["']"#).unwrap(); + re.captures_iter(src).map(|c| c[1].to_string()).collect() + } + + fn collect(dir: &std::path::Path, ext: &str, out: &mut Vec) { + let Ok(rd) = std::fs::read_dir(dir) else { + return; + }; + for e in rd.flatten() { + let p = e.path(); + let name = p.file_name().and_then(|n| n.to_str()).unwrap_or(""); + if p.is_dir() { + if !matches!( + name, + "target" | "node_modules" | "tests" | "__pycache__" | "dist" + ) { + collect(&p, ext, out); + } + } else if p.extension().and_then(|x| x.to_str()) == Some(ext) + && !name.starts_with("test_") + && !name.ends_with("_test.rs") + && name != "tests.rs" + && !name.ends_with(".test.ts") + { + out.push(p); + } + } + } + #[test] fn a_retired_id_runs_as_its_replacement() { assert_eq!(current("claude-sonnet-4-20250514"), "claude-sonnet-5-5"); diff --git a/services/common/src/model_provider.rs b/services/common/src/model_provider.rs index 8b3ef1f5d..70ea54522 100644 --- a/services/common/src/model_provider.rs +++ b/services/common/src/model_provider.rs @@ -1,36 +1,311 @@ //! Which service the deployment calls Claude through. //! -//! The default is the Anthropic API with each team's own key (stored in -//! Settings → Model Provider). A self-hosted deployment can instead use -//! Amazon Bedrock in its own AWS account (`MODEL_PROVIDER=bedrock`, set by the -//! deploy config): no key is needed, the services' IAM roles call Bedrock, -//! and the model names a team picks (`claude-opus-5-5`) are mapped to Bedrock -//! ids here. +//! Two providers: the Anthropic API with each team's own key (stored in +//! Settings, AI models), or Amazon Bedrock in the install's own AWS account +//! (no key: the services' IAM roles call Bedrock, and the model names a team +//! picks, `claude-opus-5-5`, are mapped to Bedrock ids here). +//! +//! The deploy config sets the first-boot default (`MODEL_PROVIDER`, +//! `BEDROCK_INFERENCE_PREFIX`, `BEDROCK_MODEL_IDS`). On a self-hosted +//! install an admin can change it at any time in Settings, System, Models: +//! the choice is stored on the settings table (`pk = SYSTEM`, `sk = MODELS`, +//! a JSON `data` attribute, the updater's format) and wins over the deploy +//! config. The gateway and the worker read it through [`refresh`], at most +//! once every [`CACHE_FOR`] per instance, so a switch reaches every new +//! model call within that time. A model call already under way finishes on +//! the provider it started with. -use std::collections::HashMap; -use std::sync::OnceLock; +use std::collections::{BTreeMap, HashMap}; +use std::sync::{OnceLock, RwLock}; +use std::time::{Duration, Instant}; +use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -/// True when the deployment calls Claude through Amazon Bedrock. +/// Where the runtime setting is stored (settings table). +pub const SETTINGS_PK: &str = "SYSTEM"; +pub const SETTINGS_SK: &str = "MODELS"; +/// How long an instance keeps the setting it read. +pub const CACHE_FOR: Duration = Duration::from_secs(30); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "lowercase")] +pub enum Provider { + #[default] + Anthropic, + Bedrock, +} + +impl Provider { + pub fn as_str(self) -> &'static str { + match self { + Provider::Anthropic => "anthropic", + Provider::Bedrock => "bedrock", + } + } + pub fn parse(v: &str) -> Option { + match v.trim().to_ascii_lowercase().as_str() { + "anthropic" => Some(Provider::Anthropic), + "bedrock" => Some(Provider::Bedrock), + _ => None, + } + } +} + +/// How the install calls Claude. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Settings { + pub provider: Provider, + /// Bedrock: the inference profile prefix (`us.`, `eu.`, `apac.`, + /// `global.`), or `""` for in-region model ids. + #[serde(default = "default_prefix")] + pub inference_prefix: String, + /// Bedrock: exact ids for model names (an application inference profile + /// ARN, for example). Empty for the defaults. + #[serde(default)] + pub model_ids: BTreeMap, +} + +fn default_prefix() -> String { + "us.".into() +} + +impl Default for Settings { + fn default() -> Self { + Settings { + provider: Provider::Anthropic, + inference_prefix: default_prefix(), + model_ids: BTreeMap::new(), + } + } +} + +/// Where the setting in force came from. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Source { + /// The deploy config (nobody has changed it in Settings). + Deploy, + /// An admin's choice in Settings, System, Models. + Settings, +} + +impl Settings { + /// The Bedrock id for a model name under these settings. + pub fn bedrock_id(&self, model: &str) -> String { + let map: HashMap = self.model_ids.clone().into_iter().collect(); + map_model_id(model, &self.inference_prefix, &map) + } + + /// The settings, or what is wrong with them in plain words. + pub fn validate(&self) -> Result<(), String> { + let p = &self.inference_prefix; + let ok_prefix = p.is_empty() + || (p.ends_with('.') + && (3..=7).contains(&p.len()) + && p[..p.len() - 1].chars().all(|c| c.is_ascii_lowercase())); + if !ok_prefix { + return Err( + "The inference profile prefix is us., eu., apac., global. or empty.".into(), + ); + } + for (name, id) in &self.model_ids { + if name.trim().is_empty() || name.len() > 120 { + return Err("Each model id override needs the model's name.".into()); + } + let id = id.trim(); + if id.len() > 300 || !(id.contains("anthropic.") || id.starts_with("arn:aws")) { + return Err(format!( + "The Bedrock id for {name} must be an Anthropic model id, an inference profile id or an inference profile ARN." + )); + } + } + Ok(()) + } +} + +/// The deploy config's settings, from the environment variables it sets. +pub fn deploy_default_from( + provider: Option<&str>, + prefix: Option<&str>, + model_ids: Option<&str>, +) -> Settings { + Settings { + provider: if provider_is_bedrock(provider) { + Provider::Bedrock + } else { + Provider::Anthropic + }, + inference_prefix: prefix.map_or_else(default_prefix, str::to_string), + model_ids: model_ids + .and_then(|s| serde_json::from_str(s).ok()) + .unwrap_or_default(), + } +} + +/// The deploy config's settings (read once). +pub fn deploy_default() -> &'static Settings { + static D: OnceLock = OnceLock::new(); + D.get_or_init(|| { + let v = |k: &str| std::env::var(k).ok(); + deploy_default_from( + v("MODEL_PROVIDER").as_deref(), + v("BEDROCK_INFERENCE_PREFIX").as_deref(), + v("BEDROCK_MODEL_IDS").as_deref(), + ) + }) +} + +/// The setting in force: a stored choice when it reads and is valid, else +/// the deploy config's. +pub fn resolve(stored: Option<&str>, default: &Settings) -> (Settings, Source) { + let parsed = stored + .and_then(|s| serde_json::from_str::(s).ok()) + .and_then(|v| { + // The stored record also carries who changed it and when. + let provider = Provider::parse(v.get("provider")?.as_str()?)?; + let mut out = Settings { + provider, + inference_prefix: v + .get("inference_prefix") + .and_then(Value::as_str) + .map_or_else(|| default.inference_prefix.clone(), str::to_string), + model_ids: v + .get("model_ids") + .and_then(|m| serde_json::from_value(m.clone()).ok()) + .unwrap_or_default(), + }; + out.inference_prefix = out.inference_prefix.trim().to_string(); + out.validate().ok().map(|_| out) + }); + match parsed { + Some(s) => (s, Source::Settings), + None => (default.clone(), Source::Deploy), + } +} + +/// The record stored for a switch (the updater reads the same fields). +pub fn stored_record(s: &Settings, actor: &str, at: &str, probe_team: Option<&str>) -> Value { + json!({ + "provider": s.provider.as_str(), + "inference_prefix": s.inference_prefix, + "model_ids": s.model_ids, + "updated_at": at, + "updated_by": actor, + // The team whose key passed the switch's check (Anthropic API): the + // updater checks a new release's models with it. + "probe_team": probe_team, + }) +} + +struct Cached { + read_at: Option, + settings: Settings, + source: Source, +} + +fn cell() -> &'static RwLock> { + static C: OnceLock>> = OnceLock::new(); + C.get_or_init(|| RwLock::new(None)) +} + +/// The setting in force now, and where it came from. +pub fn current_with_source() -> (Settings, Source) { + match cell().read().unwrap_or_else(|e| e.into_inner()).as_ref() { + Some(c) => (c.settings.clone(), c.source), + None => (deploy_default().clone(), Source::Deploy), + } +} + +/// The setting in force now. +pub fn current() -> Settings { + current_with_source().0 +} + +/// Use these settings in this instance right away (the gateway, after a +/// switch it saved); other instances pick it up within [`CACHE_FOR`]. +pub fn set_current(settings: Settings, source: Source) { + *cell().write().unwrap_or_else(|e| e.into_inner()) = Some(Cached { + read_at: Some(Instant::now()), + settings, + source, + }); +} + +/// Whether the cached setting is older than [`CACHE_FOR`] (or was never read). +fn stale() -> bool { + cell() + .read() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .and_then(|c| c.read_at) + .is_none_or(|at| at.elapsed() >= CACHE_FOR) +} + +/// Reads the stored setting when the cached one is stale. A failed read +/// keeps what the instance had (or the deploy config), and tries again +/// after [`CACHE_FOR`]. +pub async fn refresh(dynamo: &aws_sdk_dynamodb::Client, table: &str) { + if table.is_empty() || !stale() { + return; + } + use aws_sdk_dynamodb::types::AttributeValue as A; + let read = dynamo + .get_item() + .table_name(table) + .key("pk", A::S(SETTINGS_PK.into())) + .key("sk", A::S(SETTINGS_SK.into())) + .send() + .await; + let mut guard = cell().write().unwrap_or_else(|e| e.into_inner()); + match read { + Ok(out) => { + let data = out + .item() + .and_then(|i| i.get("data")) + .and_then(|v| v.as_s().ok()) + .cloned(); + let (settings, source) = resolve(data.as_deref(), deploy_default()); + *guard = Some(Cached { + read_at: Some(Instant::now()), + settings, + source, + }); + } + Err(e) => { + tracing::warn!(error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "model provider setting not read; keeping the last one"); + let (settings, source) = match guard.as_ref() { + Some(c) => (c.settings.clone(), c.source), + None => (deploy_default().clone(), Source::Deploy), + }; + *guard = Some(Cached { + read_at: Some(Instant::now()), + settings, + source, + }); + } + } +} + +/// True when the install calls Claude through Amazon Bedrock now. pub fn is_bedrock() -> bool { - static B: OnceLock = OnceLock::new(); - *B.get_or_init(|| provider_is_bedrock(std::env::var("MODEL_PROVIDER").ok().as_deref())) + current().provider == Provider::Bedrock } -/// [`is_bedrock`]'s rule on a given value. +/// Whether a `MODEL_PROVIDER` value means Bedrock. pub fn provider_is_bedrock(v: Option<&str>) -> bool { v.is_some_and(|p| p.trim().eq_ignore_ascii_case("bedrock")) } static CLIENT: OnceLock = OnceLock::new(); -/// Keep the Bedrock client the services call Claude with (set at start). +/// Keep the Bedrock client the services call Claude with (set at start on +/// every install, so a switch to Bedrock needs no restart). pub fn set_bedrock_client(client: aws_sdk_bedrockruntime::Client) { let _ = CLIENT.set(client); } -/// The Bedrock client, when the deployment uses Bedrock and it was set. +/// The Bedrock client, when the install uses Bedrock now and it was set. pub fn bedrock_client() -> Option<&'static aws_sdk_bedrockruntime::Client> { if is_bedrock() { CLIENT.get() @@ -39,24 +314,21 @@ pub fn bedrock_client() -> Option<&'static aws_sdk_bedrockruntime::Client> { } } -/// The Bedrock id for a model name, from BEDROCK_MODEL_IDS (JSON object) -/// and BEDROCK_INFERENCE_PREFIX (`us.` by default). +/// The Bedrock client whatever the provider is now (a run that started on +/// Bedrock with no team key finishes there; a switch's check). +pub fn any_bedrock_client() -> Option<&'static aws_sdk_bedrockruntime::Client> { + CLIENT.get() +} + +/// The Bedrock id for a model name under the setting in force. pub fn bedrock_model_id(model: &str) -> String { - static MAP: OnceLock<(String, HashMap)> = OnceLock::new(); - let (prefix, map) = MAP.get_or_init(|| { - let prefix = std::env::var("BEDROCK_INFERENCE_PREFIX").unwrap_or_else(|_| "us.".into()); - let map = std::env::var("BEDROCK_MODEL_IDS") - .ok() - .and_then(|s| serde_json::from_str::>(&s).ok()) - .unwrap_or_default(); - (prefix, map) - }); - map_model_id(model, prefix, map) + current().bedrock_id(model) } /// [`bedrock_model_id`]'s rule: an explicit mapping wins; an id that is /// already a Bedrock id (`anthropic.` in it, or an ARN) is used as given; -/// anything else becomes `anthropic.`. +/// anything else becomes `anthropic.`, with the manifest's +/// Bedrock name for models whose id carries a date. pub fn map_model_id(model: &str, prefix: &str, map: &HashMap) -> String { if let Some(id) = map.get(model) { return id.clone(); @@ -64,23 +336,13 @@ pub fn map_model_id(model: &str, prefix: &str, map: &HashMap) -> if model.contains("anthropic.") || model.starts_with("arn:") { return model.to_string(); } - let name = BEDROCK_NAMES - .iter() - .find(|(n, _)| *n == model) - .map_or(model, |(_, id)| *id); + let name = crate::model_ids::manifest() + .bedrock_names + .get(model) + .map_or(model, String::as_str); format!("{prefix}anthropic.{name}") } -/// Models whose Bedrock id isn't just their name (Bedrock has no undated -/// Haiku 4.5 id). Others can be added per deployment in BEDROCK_MODEL_IDS. -const BEDROCK_NAMES: &[(&str, &str)] = &[ - ("claude-haiku-4-5", "claude-haiku-4-5-20251001-v1:0"), - ( - "claude-haiku-4-5-20251001", - "claude-haiku-4-5-20251001-v1:0", - ), -]; - /// A Messages API request body as Bedrock takes it: no model or stream /// fields (the model is in the call, streaming is the call), Bedrock's /// version marker added. Everything else, tools and cache_control @@ -112,6 +374,111 @@ pub fn sse_frame(event_json: &[u8]) -> Vec { mod tests { use super::*; + #[test] + fn the_stored_setting_wins_over_the_deploy_config() { + let deploy = deploy_default_from(Some("anthropic"), None, None); + assert_eq!(deploy.provider, Provider::Anthropic); + assert_eq!(deploy.inference_prefix, "us."); + // Nothing stored: the deploy config. + assert_eq!(resolve(None, &deploy), (deploy.clone(), Source::Deploy)); + // A switch to Bedrock in Europe. + let (s, src) = resolve( + Some( + r#"{"provider":"bedrock","inference_prefix":"eu.","model_ids":{},"updated_by":"a@example.com"}"#, + ), + &deploy, + ); + assert_eq!(src, Source::Settings); + assert_eq!(s.provider, Provider::Bedrock); + assert_eq!( + s.bedrock_id("claude-opus-5-5"), + "eu.anthropic.claude-opus-5-5" + ); + // No prefix stored: the deploy config's. + let (s, _) = resolve(Some(r#"{"provider":"bedrock"}"#), &deploy); + assert_eq!(s.inference_prefix, "us."); + } + + #[test] + fn a_broken_stored_setting_falls_back_to_the_deploy_config() { + let deploy = deploy_default_from( + Some("bedrock"), + Some("apac."), + Some(r#"{"claude-opus-5-5":"apac.anthropic.claude-opus-5-5"}"#), + ); + assert_eq!(deploy.provider, Provider::Bedrock); + assert_eq!(deploy.model_ids.len(), 1); + for bad in [ + "not json", + r#"{"provider":"openai"}"#, + r#"{"provider":"bedrock","inference_prefix":"US"}"#, + r#"{"provider":"bedrock","model_ids":{"claude-opus-5-5":"gpt-4"}}"#, + ] { + assert_eq!( + resolve(Some(bad), &deploy), + (deploy.clone(), Source::Deploy), + "{bad}" + ); + } + } + + #[test] + fn settings_are_checked_in_plain_words() { + let mut s = Settings { + provider: Provider::Bedrock, + ..Default::default() + }; + for ok in ["", "us.", "eu.", "apac.", "global."] { + s.inference_prefix = ok.into(); + assert!(s.validate().is_ok(), "{ok}"); + } + for bad in ["us", "US.", "a.", "toolongprefix.", "u s."] { + s.inference_prefix = bad.into(); + assert!(s.validate().unwrap_err().contains("prefix"), "{bad}"); + } + s.inference_prefix = "us.".into(); + s.model_ids.insert( + "claude-opus-5-5".into(), + "arn:aws:bedrock:us-east-1:111122223333:application-inference-profile/abc".into(), + ); + assert!(s.validate().is_ok()); + s.model_ids.insert("claude-sonnet-5-5".into(), "gpt".into()); + assert!(s.validate().unwrap_err().contains("claude-sonnet-5-5")); + } + + #[test] + fn a_switch_takes_effect_in_this_instance_at_once() { + let s = Settings { + provider: Provider::Bedrock, + inference_prefix: "eu.".into(), + model_ids: BTreeMap::new(), + }; + set_current(s.clone(), Source::Settings); + assert!(is_bedrock()); + assert_eq!( + bedrock_model_id("claude-sonnet-5-5"), + "eu.anthropic.claude-sonnet-5-5" + ); + assert_eq!(current_with_source(), (s, Source::Settings)); + // Fresh: refresh would not read again yet. + assert!(!stale()); + set_current(Settings::default(), Source::Deploy); + assert!(!is_bedrock()); + } + + #[test] + fn the_stored_record_has_what_the_updater_reads() { + let s = Settings { + provider: Provider::Bedrock, + inference_prefix: "eu.".into(), + model_ids: BTreeMap::new(), + }; + let r = stored_record(&s, "a@example.com", "2026-10-26T00:00:00Z", None); + assert_eq!(r["provider"], "bedrock"); + assert_eq!(r["inference_prefix"], "eu."); + assert_eq!(resolve(Some(&r.to_string()), &Settings::default()).0, s); + } + #[test] fn provider_switch() { assert!(provider_is_bedrock(Some("bedrock"))); diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index e35622df4..145f478a7 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -1,4 +1,5 @@ use axum::{ + extract::State, http::header, middleware as axum_middleware, routing::{delete, get, post, put}, @@ -56,7 +57,8 @@ async fn main() -> Result<(), Error> { let kms = aws_sdk_kms::Client::new(&aws_config); let sts = aws_sdk_sts::Client::new(&aws_config); let bedrock = aws_sdk_bedrockruntime::Client::new(&aws_config); - // Claude through Bedrock when the deployment says so (MODEL_PROVIDER). + // Claude through Bedrock: set on every install, so a switch to Bedrock + // in Settings needs no restart. common::model_provider::set_bedrock_client(bedrock.clone()); let scheduler = common::plugins::schedule::aws_sdk_scheduler::Client::new(&aws_config); let sm = aws_sdk_secretsmanager::Client::new(&aws_config); @@ -145,6 +147,18 @@ async fn main() -> Result<(), Error> { .route("/system/update", post(routes::system::update_now)) .route("/system/rollback", post(routes::system::rollback)) .route("/system/test-email", post(routes::system::test_email)) + // The model check before an update, run again now ("Check again"). + .route("/system/update-check", post(routes::system::check_update)) + // How the install calls Claude: Bedrock or Anthropic API keys, + // switched at any time once every model answers. + .route( + "/system/models", + get(routes::system_models::get_models).put(routes::system_models::set_models), + ) + .route( + "/system/models/check", + post(routes::system_models::check_models), + ) // Your own domain: status and records, set, back to the AWS address. .route( "/system/domain", @@ -1296,10 +1310,16 @@ async fn main() -> Result<(), Error> { header::CACHE_CONTROL, header::HeaderValue::from_static("no-store"), )) - // The public URL, if it couldn't be read at start (first deploy). - .layer(axum::middleware::from_fn( - |req: axum::extract::Request, next: axum::middleware::Next| async move { + // The public URL, if it couldn't be read at start (first deploy), + // and the install's model provider (Settings, System, Models), read + // again at most every 30 seconds. + .layer(axum::middleware::from_fn_with_state( + state.clone(), + |State(st): State>, + req: axum::extract::Request, + next: axum::middleware::Next| async move { common::public_urls::ensure().await; + common::model_provider::refresh(&st.dynamo, &st.config.settings_table_name).await; next.run(req).await }, )) diff --git a/services/gateway/src/model_call.rs b/services/gateway/src/model_call.rs index 3f158224c..509c3310c 100644 --- a/services/gateway/src/model_call.rs +++ b/services/gateway/src/model_call.rs @@ -59,6 +59,24 @@ pub async fn log_repo_turn( whole_turn(http, api_key, body, meter, model_id, feature::LOG_ANALYSIS).await } +/// Where one call goes: Bedrock (with the id to call) or the Anthropic API. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Via { + Bedrock(String), + Anthropic, +} + +impl Via { + /// The install's provider as it is now (Settings, System, Models). + pub fn now(model_id: &str) -> Self { + if common::model_provider::is_bedrock() { + Via::Bedrock(common::model_provider::bedrock_model_id(model_id)) + } else { + Via::Anthropic + } + } +} + async fn whole_turn( http: &reqwest::Client, api_key: &str, @@ -67,9 +85,30 @@ async fn whole_turn( model_id: &str, feature_tag: &'static str, ) -> Result { - if common::model_provider::is_bedrock() { + whole_turn_via( + Via::now(model_id), + http, + api_key, + body, + meter, + model_id, + feature_tag, + ) + .await +} + +async fn whole_turn_via( + via: Via, + http: &reqwest::Client, + api_key: &str, + body: &Value, + meter: &UsageMeter, + model_id: &str, + feature_tag: &'static str, +) -> Result { + if let Via::Bedrock(bedrock_id) = via { let (mut stream, mut flight) = - open_bedrock_stream(body, meter, model_id, feature_tag).await?; + open_bedrock_stream(&bedrock_id, body, meter, model_id, feature_tag).await?; let mut parser = SseParser::default(); while let Some(chunk) = stream.next().await { match chunk { @@ -126,6 +165,18 @@ pub async fn probe( api_key: &str, meter: &UsageMeter, model: &str, +) -> crate::routes::setup_checks::ModelProbe { + probe_via(Via::now(model), http, api_key, meter, model).await +} + +/// [`probe`] on a given provider, whatever the install uses now: a +/// provider switch checks the provider it would switch to. +pub async fn probe_via( + via: Via, + http: &reqwest::Client, + api_key: &str, + meter: &UsageMeter, + model: &str, ) -> crate::routes::setup_checks::ModelProbe { use crate::routes::setup_checks::ModelProbe; let body = json!({ @@ -133,7 +184,7 @@ pub async fn probe( "max_tokens": 1, "messages": [{ "role": "user", "content": "Reply with OK." }], }); - match chat_turn(http, api_key, &body, meter, model).await { + match whole_turn_via(via, http, api_key, &body, meter, model, feature::CHAT).await { Ok(_) => ModelProbe::Ok, // The token limit is the point of a one-token call. Err(e) if e.kind == ModelErrorKind::Truncated => ModelProbe::Ok, @@ -178,8 +229,8 @@ async fn open_stream( model_id: &str, feature_tag: &'static str, ) -> Result<(ChatBytes, InFlight), ModelCallError> { - if common::model_provider::is_bedrock() { - return open_bedrock_stream(body, meter, model_id, feature_tag).await; + if let Via::Bedrock(bedrock_id) = Via::now(model_id) { + return open_bedrock_stream(&bedrock_id, body, meter, model_id, feature_tag).await; } let bytes = serde_json::to_vec(body).unwrap_or_default(); let resp = common::model_retry::send_streaming( @@ -217,6 +268,7 @@ pub type ChatBytes = std::pin::Pin /// until a stream starts. Bedrock's events are framed as SSE, so callers /// read them exactly like the Anthropic API's. async fn open_bedrock_stream( + bedrock_id: &str, body: &Value, meter: &UsageMeter, model_id: &str, @@ -224,19 +276,18 @@ async fn open_bedrock_stream( ) -> Result<(ChatBytes, InFlight), ModelCallError> { use aws_sdk_bedrockruntime::types::ResponseStream; use common::model_retry::{backoff, is_transient_status, INTERACTIVE_BACKOFF_SECS}; - let Some(client) = common::model_provider::bedrock_client() else { + let Some(client) = common::model_provider::any_bedrock_client() else { return Err(ModelCallError::new( ModelErrorKind::Network, "Bedrock is the model provider but no client was set up", )); }; let bytes = serde_json::to_vec(&common::model_provider::bedrock_body(body)).unwrap_or_default(); - let bedrock_id = common::model_provider::bedrock_model_id(model_id); let mut attempt = 0; let out = loop { let result = client .invoke_model_with_response_stream() - .model_id(&bedrock_id) + .model_id(bedrock_id) .content_type("application/json") .accept("application/json") .body(aws_smithy_types::Blob::new(bytes.clone())) diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 418bd40f9..82e8ec32c 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -603,6 +603,7 @@ pub const CAPABILITIES: &[Capability] = &[ "system::version", "system::set_auto_update", "system::update_now", + "system::check_update", "system::rollback", "system::test_email", "system::domain", @@ -622,6 +623,18 @@ pub const CAPABILITIES: &[Capability] = &[ "hybrid_install::put_settings", ], }, + Capability { + key: "system.models", + label: "Change how this install calls Claude (Amazon Bedrock or Anthropic API keys), after every model it uses answers a test call (self-hosted installs; install admins only)", + min_role: "admin", + // Also checked inside each handler: the person must be an install + // admin (PLATFORM_ADMIN_EMAILS). + handlers: &[ + "system_models::get_models", + "system_models::check_models", + "system_models::set_models", + ], + }, Capability { key: "plugins.install", label: "Add plugin sources, install, update, pin or roll back plugins, and set their settings, approvers and limits", @@ -719,7 +732,7 @@ pub const CUSTOM_PREFIX: &str = "custom:"; /// Capabilities a custom role can never hold, whatever the table says about /// them: managing roles, and support (checked by built-in role inside the /// support handlers), stay with built-in admins and owners. -pub const NEVER_IN_CUSTOM_ROLES: &[&str] = &["roles", "support", "system"]; +pub const NEVER_IN_CUSTOM_ROLES: &[&str] = &["roles", "support", "system", "system.models"]; /// The id in a `custom:` role, or `None` for a built-in role. pub fn custom_role_id(role: &str) -> Option<&str> { diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 434d6d825..8847d2f9f 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -4752,20 +4752,6 @@ pub async fn update_git_conventions( Ok(Json(git_conventions_json(&c))) } -/// Allowed model IDs for the Anthropic provider. -const ALLOWED_MODELS: &[&str] = &[ - "claude-fable-5-1", - "claude-opus-5-5", - "claude-sonnet-5-5", - "claude-opus-4-8", - "claude-opus-4-7", - "claude-opus-4-6", - "claude-sonnet-4-6", - "claude-sonnet-4-5", - "claude-haiku-4-5", - "claude-haiku-4-5-20251001", -]; - /// GET /api/settings/model-provider — get model provider configuration. pub async fn get_model_provider( State(state): State>, @@ -4860,7 +4846,10 @@ pub async fn update_model_provider( .as_str() .ok_or(StatusCode::BAD_REQUEST)?; - if !ALLOWED_MODELS.contains(&primary_model) || !ALLOWED_MODELS.contains(&heavy_model) { + // What a team may pick is the release's manifest (common::model_ids). + if !common::model_ids::is_selectable(primary_model) + || !common::model_ids::is_selectable(heavy_model) + { return Err(StatusCode::BAD_REQUEST); } diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 68bf8cbd8..eb7bed098 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -54,6 +54,7 @@ pub mod sns; pub mod support; pub mod support_access; pub mod system; +pub mod system_models; pub mod telemetry; pub mod tests; pub mod tests_setup; diff --git a/services/gateway/src/routes/setup_checks.rs b/services/gateway/src/routes/setup_checks.rs index e5585fd0e..53673daf7 100644 --- a/services/gateway/src/routes/setup_checks.rs +++ b/services/gateway/src/routes/setup_checks.rs @@ -572,7 +572,7 @@ pub enum ModelProbe { /// Bedrock's console page where model access is turned on. pub fn bedrock_access_url(region: &str) -> String { - format!("https://console.aws.amazon.com/bedrock/home?region={region}#/modelaccess") + common::model_access::bedrock_access_url(region) } pub fn model(bedrock: bool, region: &str, model_id: &str, probe: &ModelProbe) -> Check { @@ -1292,6 +1292,67 @@ pub fn public_updates(status: Option<&Value>) -> PublicCheck { } } +/// The updater's model check for the next release: every model it calls, +/// tried through the install's provider. `None` until it has run. +pub fn update_models(status: Option<&Value>) -> Option { + let mc = status?.get("model_check").filter(|m| m.is_object())?; + let version = mc["version"].as_str().unwrap_or("the next release"); + let failing: Vec<&Value> = mc["results"] + .as_array() + .map(|r| r.iter().filter(|x| x["status"] == "fail").collect()) + .unwrap_or_default(); + let label = "The next release's models answer"; + if mc["pending"].as_bool() == Some(true) { + return Some(Check::not_ok( + Status::Warn, + "update_models", + M, + label, + format!("Checking {version}'s signature before reading the models it calls."), + "The update waits until every model it calls answers.", + Fix::text("Wait a few minutes, then check again.").href("/settings/system#readiness"), + )); + } + if mc["ok"].as_bool() == Some(true) || failing.is_empty() { + return Some(Check::pass( + "update_models", + M, + label, + format!("Every model {version} calls answered a test call."), + )); + } + let first = failing[0]; + let models: Vec<&str> = failing.iter().filter_map(|f| f["model"].as_str()).collect(); + let mut fix = Fix::text( + first["fix"] + .as_str() + .unwrap_or("Fix the model access, then check again."), + ); + if let Some(u) = first["url"].as_str() { + fix = fix.url(u); + } + if let Some(h) = first["href"].as_str() { + fix = fix.href(h); + } + Some(Check::not_ok( + Status::Fail, + "update_models", + M, + label, + format!( + "Update to {version} needs your action: {}", + first["detail"].as_str().unwrap_or("a model was refused.") + ), + format!( + "{version} calls {}; it won't be applied until {} answer{}. The check runs again daily.", + models.join(" and "), + if models.len() == 1 { "it" } else { "they" }, + if models.len() == 1 { "s" } else { "" }, + ), + fix, + )) +} + // ── Update preflight ────────────────────────────────────────────────────── /// One thing that would stop (or should pause) an update. @@ -1308,7 +1369,11 @@ pub struct Blocker { pub fn preflight(checks: &[Check], status: Option<&Value>) -> Vec { let mut out: Vec = checks .iter() - .filter(|c| c.status == Status::Fail && !matches!(c.group, "Integrations")) + .filter(|c| { + c.status == Status::Fail + && !matches!(c.group, "Integrations") + && c.key != "update_models" + }) .map(|c| Blocker { key: c.key.to_string(), severity: "block", @@ -1328,6 +1393,54 @@ pub fn preflight(checks: &[Check], status: Option<&Value>) -> Vec { }); return out; }; + // The next release calls a model this install can't call yet: one + // blocker per model, each with its own fix. + if let Some(mc) = v.get("model_check").filter(|m| m["pending"] == true) { + let ver = mc["version"].as_str().unwrap_or("the next release"); + out.push(Blocker { + key: "model_check_pending".into(), + severity: "block", + detail: format!("Checking {ver}'s signature before reading the models it calls."), + fix: Fix::text("Wait a few minutes, then check again.") + .href("/settings/system#readiness"), + }); + } + if let Some(mc) = v + .get("model_check") + .filter(|m| m["ok"] == false && m["pending"] != true) + { + let ver = mc["version"].as_str().unwrap_or("the next release"); + for f in mc["results"].as_array().into_iter().flatten() { + if f["status"] != "fail" { + continue; + } + let mut fix = Fix::text( + f["fix"] + .as_str() + .unwrap_or("Fix the model access, then check again."), + ); + if let Some(u) = f["url"].as_str() { + fix = fix.url(u); + } + if let Some(h) = f["href"].as_str() { + fix = fix.href(h); + } + out.push(Blocker { + key: format!("model:{}", f["model"].as_str().unwrap_or("?")), + // Only a model the release calls blocks; another can be skipped. + severity: if f["required"] == false { + "warn" + } else { + "block" + }, + detail: format!( + "Update to {ver} needs your action: {}", + f["detail"].as_str().unwrap_or("a model was refused.") + ), + fix, + }); + } + } if v["running"].as_bool() == Some(true) { out.push(Blocker { key: "running".into(), @@ -1838,6 +1951,7 @@ pub async fn run_all(state: &AppState, team_id: &str) -> (Vec, Option &'static str { - let m = message.to_ascii_lowercase(); - if m.contains("use case") || m.contains("use-case") { - "use_case_required" - } else if m.contains("being processed") || m.contains("subscription") && m.contains("pending") { - "subscription_pending" - } else if m.contains("marketplace") || m.contains("payment") { - "marketplace_failed" - } else if m.contains("not authorized to perform") || m.contains("explicit deny") { - "iam_denied" - } else if m.contains("don't have access") - || m.contains("do not have access") - || m.contains("access to the model") - { - "access_denied" - } else if m.contains("not available") - || m.contains("not supported") - || m.contains("model identifier is invalid") - || status == 404 - { - "not_available" - } else if status == 403 { - "access_denied" - } else { - "unknown" + match common::model_access::refusal_code(status, message) { + "transient" => "unknown", + c => c, } } @@ -2686,6 +2781,51 @@ mod tests { assert_eq!(s["skip"], 1); } + #[test] + fn a_refused_model_in_the_next_release_blocks_the_update() { + let status = json!({ + "running": false, + "latest": {"version": "v1.3.0"}, + "model_check": { + "version": "v1.3.0", "ok": false, + "results": [ + {"model": "claude-opus-5-5", "status": "pass", "code": "ok"}, + {"model": "claude-sonnet-5-5", "status": "fail", "code": "marketplace_failed", "required": true, + "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-east-1#/modelaccess"}, + ], + }, + }); + let b = preflight(&[], Some(&status)); + assert_eq!(b.len(), 1); + assert_eq!(b[0].key, "model:claude-sonnet-5-5"); + assert_eq!(b[0].severity, "block"); + assert!(b[0] + .detail + .starts_with("Update to v1.3.0 needs your action")); + assert!(b[0].fix.url.as_deref().unwrap().contains("#/modelaccess")); + // Setup shows it as a failing check, which the preflight doesn't count twice. + let c = update_models(Some(&status)).unwrap(); + assert_eq!(c.status, Status::Fail); + assert!(c.detail.contains("Update to v1.3.0 needs your action")); + assert!(c.why.contains("claude-sonnet-5-5")); + assert_eq!(preflight(&[c], Some(&status)).len(), 1); + // Passed, or never run. + let ok = json!({"model_check": {"version": "v1.3.0", "ok": true, "results": []}}); + assert_eq!(update_models(Some(&ok)).unwrap().status, Status::Pass); + assert!(update_models(Some(&json!({}))).is_none()); + // Before the release's signature is checked: held, not refused. + let pending = json!({"model_check": {"version": "v1.3.0", "ok": false, "pending": true, "results": []}}); + assert_eq!(update_models(Some(&pending)).unwrap().status, Status::Warn); + let b = preflight(&[], Some(&pending)); + assert_eq!( + (b[0].key.as_str(), b[0].severity), + ("model_check_pending", "block") + ); + assert!(preflight(&[], Some(&ok)).is_empty()); + } + #[test] fn preflight_blocks_on_failures_and_a_running_update() { let checks = vec![github_app(Some(401)), jira(false), dlq(Some(0))]; diff --git a/services/gateway/src/routes/system.rs b/services/gateway/src/routes/system.rs index 3c29e7459..86797b30f 100644 --- a/services/gateway/src/routes/system.rs +++ b/services/gateway/src/routes/system.rs @@ -77,11 +77,16 @@ pub(crate) async fn call(state: &AppState, payload: Value) -> Result Result, (StatusCode, Json)> { if body.get("ok").and_then(Value::as_bool) == Some(false) { let msg = body.get("error").cloned().unwrap_or(json!("refused")); - return Err((StatusCode::BAD_REQUEST, Json(json!({ "error": msg })))); + let mut out = json!({ "error": msg }); + if let Some(m) = body.get("model_check").filter(|m| !m.is_null()) { + out["model_check"] = m.clone(); + } + return Err((StatusCode::BAD_REQUEST, Json(out))); } Ok(Json(body)) } @@ -148,6 +153,9 @@ pub async fn set_auto_update( } /// POST /api/system/update: update to `version` (default: the latest). +/// The updater checks every model the release calls first and refuses +/// while one is refused; `skip_check` passes only a failure on a model the +/// release doesn't call. pub async fn update_now( State(state): State>, Extension(claims): Extension, @@ -159,9 +167,27 @@ pub async fn update_now( .get("version") .and_then(Value::as_str) .map(str::to_string); + let skip = body.get("skip_check").and_then(Value::as_bool) == Some(true); let body = call( &state, - json!({ "action": "update_now", "version": version, "actor": claims.email }), + json!({ "action": "update_now", "version": version, "actor": claims.email, "skip_check": skip }), + ) + .await + .map_err(status_only)?; + answer(body) +} + +/// POST /api/system/update-check: check the next release's models again +/// now (the update banner's "Check again"). +pub async fn check_update( + State(state): State>, + Extension(claims): Extension, +) -> Reply { + claims.require_role(3).map_err(status_only)?; + allowed(&claims).map_err(status_only)?; + let body = call( + &state, + json!({ "action": "model_check", "actor": claims.email }), ) .await .map_err(status_only)?; @@ -363,6 +389,13 @@ mod tests { let (code, body) = r.unwrap_err(); assert_eq!(code, StatusCode::BAD_REQUEST); assert_eq!(body.0["error"], "an update is already running"); + assert!(body.0.get("model_check").is_none()); + // A model the release calls was refused: the check comes along. + let r = answer( + json!({"ok": false, "error": "Update to v1.3.0 needs your action", "model_check": {"version": "v1.3.0", "ok": false}}), + ); + let (_, body) = r.unwrap_err(); + assert_eq!(body.0["model_check"]["version"], "v1.3.0"); assert!(answer(json!({"ok": true, "version": "v1.2.0"})).is_ok()); } diff --git a/services/gateway/src/routes/system_models.rs b/services/gateway/src/routes/system_models.rs new file mode 100644 index 000000000..827718113 --- /dev/null +++ b/services/gateway/src/routes/system_models.rs @@ -0,0 +1,690 @@ +//! Settings, System, Models: how this self-hosted install calls Claude. +//! +//! An install admin switches between Claude on Amazon Bedrock (this AWS +//! account, no key) and Anthropic API keys (each team adds its own in +//! Settings, AI models, as before) at any time. The deploy config's choice +//! is only the first-boot default (common::model_provider). +//! +//! A switch is checked before it is saved: every model the release calls +//! (common::model_ids, the release's manifest) gets one test call through +//! the provider being switched to, the same call Setup makes. When any is +//! refused, nothing changes and the answer says which model, the fix in one +//! sentence and the console page. A saved switch is written to the team's +//! audit log first (no record, no switch), then stored; this instance uses +//! it at once, every other within 30 seconds. A model call already under +//! way finishes on the provider it started with. +//! +//! Why Anthropic keys stay per team: the key already lives on each team's +//! settings item, the worker, gateway and log analyzer all read it there, +//! and each team's usage lands on its own Anthropic account. An install-wide +//! key would need a second place every reader checks and would pool every +//! team's usage on one bill. The check uses the switching admin's team key. + +use std::sync::Arc; + +use async_trait::async_trait; +use axum::{extract::State, http::StatusCode, Extension, Json}; +use common::model_access::{self, Access, Answer}; +use common::model_provider::{self as mp, Provider, Settings, Source}; +use serde_json::{json, Value}; +use tracing::{info, warn}; + +use super::api::is_platform_admin; +use crate::models::Claims; +use crate::AppState; + +type Reply = Result, (StatusCode, Json)>; + +fn not_admin(s: StatusCode) -> (StatusCode, Json) { + refuse( + s, + "Only team admins can see or change how the install calls Claude.", + ) +} + +fn refuse(code: StatusCode, msg: &str) -> (StatusCode, Json) { + (code, Json(json!({ "error": msg }))) +} + +/// A self-hosted install's admin, or the refusal. +fn allowed(claims: &Claims) -> Result<(), (StatusCode, Json)> { + if !super::setup_checks::self_hosted() { + return Err(refuse( + StatusCode::NOT_FOUND, + "Only a self-hosted install changes its model provider here.", + )); + } + if !is_platform_admin(claims) { + warn!(email = %claims.email, "Models route refused: not an install admin"); + return Err(refuse( + StatusCode::FORBIDDEN, + "Only the install's admins can change how it calls Claude.", + )); + } + Ok(()) +} + +fn region() -> String { + std::env::var("AWS_REGION").unwrap_or_else(|_| "us-east-1".into()) +} + +/// The settings a request asks for, checked. +pub fn requested(body: &Value) -> Result { + let provider = body + .get("provider") + .and_then(Value::as_str) + .and_then(Provider::parse) + .ok_or("Pick Claude on Amazon Bedrock or Anthropic API keys.")?; + let mut s = Settings { + provider, + ..Default::default() + }; + if provider == Provider::Bedrock { + if let Some(p) = body.get("inference_prefix") { + s.inference_prefix = p + .as_str() + .ok_or("The inference profile prefix is text.")? + .trim() + .to_string(); + } + if let Some(m) = body.get("model_ids").filter(|v| !v.is_null()) { + let map = m + .as_object() + .ok_or("Model id overrides are a list of model name and Bedrock id.")?; + for (k, v) in map { + let id = v.as_str().unwrap_or("").trim(); + if !id.is_empty() { + s.model_ids.insert(k.trim().to_string(), id.to_string()); + } + } + } + s.validate()?; + } + Ok(s) +} + +/// The test calls a switch makes: every model the release calls, each with +/// the id it is called by under `settings`. +pub fn targets(settings: &Settings) -> Vec<(String, String)> { + common::model_ids::release_calls() + .into_iter() + .map(|m| { + let id = match settings.provider { + Provider::Bedrock => settings.bedrock_id(m), + Provider::Anthropic => m.to_string(), + }; + (m.to_string(), id) + }) + .collect() +} + +/// Makes the test calls (swapped for a fake in tests: no real model calls). +#[async_trait] +pub trait Prober: Send + Sync { + async fn bedrock(&self, model: &str, bedrock_id: &str) -> Answer; + async fn anthropic(&self, api_key: &str, model: &str) -> Answer; +} + +/// Stores the switch and its audit entry. +#[async_trait] +pub trait Store: Send + Sync { + /// The team's Anthropic key, when it has one. + async fn team_key(&self, team_id: &str) -> Option; + async fn audit(&self, detail: &str) -> Result<(), String>; + async fn save(&self, record: &Value) -> Result<(), String>; +} + +/// Every test call for a switch, explained. +pub async fn check( + prober: &dyn Prober, + store: &dyn Store, + team_id: &str, + settings: &Settings, +) -> Vec { + let region = region(); + let key = if settings.provider == Provider::Anthropic { + store.team_key(team_id).await + } else { + None + }; + let mut out = Vec::new(); + for (model, id) in targets(settings) { + let answer = match settings.provider { + Provider::Bedrock => prober.bedrock(&model, &id).await, + Provider::Anthropic => match key.as_deref() { + Some(k) => prober.anthropic(k, &model).await, + None => Answer::NoKey, + }, + }; + let mut a = model_access::explain( + settings.provider, + &model, + &id, + ®ion, + &settings.inference_prefix, + &answer, + ); + // A switch to keys needs one key that works: without one nothing + // could run, so it is refused rather than skipped. + if a.code == "no_key" { + a.status = "fail"; + a.detail = + "Your team hasn't added an Anthropic API key, so the switch can't be checked." + .into(); + } + out.push(a); + } + out +} + +/// One line for the audit log. +pub fn audit_detail(from: &Settings, to: &Settings) -> String { + let say = |s: &Settings| match s.provider { + Provider::Anthropic => "Anthropic API keys".to_string(), + Provider::Bedrock => format!( + "Claude on Amazon Bedrock ({}{})", + if s.inference_prefix.is_empty() { + "in-region ids".to_string() + } else { + format!("{} inference profiles", s.inference_prefix) + }, + if s.model_ids.is_empty() { + String::new() + } else { + format!(", {} model id override(s)", s.model_ids.len()) + } + ), + }; + format!( + "Changed how the install calls Claude from {} to {}.", + say(from), + say(to) + ) +} + +/// Check, then save: refused when any model fails (nothing written), or +/// when the audit entry can't be written first. +pub async fn switch( + prober: &dyn Prober, + store: &dyn Store, + team_id: &str, + actor: &str, + to: Settings, +) -> Result<(Value, Vec), (StatusCode, Value)> { + let results = check(prober, store, team_id, &to).await; + if !model_access::all_pass(&results) { + let failing: Vec<&str> = results + .iter() + .filter(|r| r.status == "fail") + .map(|r| r.model.as_str()) + .collect(); + return Err(( + StatusCode::CONFLICT, + json!({ + "error": format!("Not switched: {} didn't answer. Fix it and check again.", failing.join(" and ")), + "results": results, + }), + )); + } + let from = mp::current(); + store.audit(&audit_detail(&from, &to)).await.map_err(|e| { + ( + StatusCode::INTERNAL_SERVER_ERROR, + json!({ "error": format!("Not switched: the audit log couldn't be written ({e}).") }), + ) + })?; + let at = chrono::Utc::now().to_rfc3339(); + let probe_team = (to.provider == Provider::Anthropic).then_some(team_id); + let record = mp::stored_record(&to, actor, &at, probe_team); + store.save(&record).await.map_err(|e| { + ( + StatusCode::INTERNAL_SERVER_ERROR, + json!({ "error": format!("Not switched: the setting couldn't be saved ({e}).") }), + ) + })?; + Ok((record, results)) +} + +// ── The real calls ──────────────────────────────────────────────────────── + +struct Live<'a> { + state: &'a AppState, + claims: &'a Claims, +} + +fn answer_of(p: super::setup_checks::ModelProbe) -> Answer { + use super::setup_checks::ModelProbe as P; + match p { + P::Ok => Answer::Ok, + P::NoKey => Answer::NoKey, + P::Refused(s, m) => Answer::Refused(s, m), + P::Unreachable(m) => Answer::Unreachable(m), + } +} + +#[async_trait] +impl Prober for Live<'_> { + async fn bedrock(&self, model: &str, bedrock_id: &str) -> Answer { + // Metered on the install's setup meter, like Setup's own test call. + let meter = crate::model_call::chat_meter(self.state, "SETUP"); + answer_of( + crate::model_call::probe_via( + crate::model_call::Via::Bedrock(bedrock_id.to_string()), + &self.state.http, + "", + &meter, + model, + ) + .await, + ) + } + async fn anthropic(&self, api_key: &str, model: &str) -> Answer { + let meter = crate::model_call::chat_meter(self.state, &self.claims.team_id); + answer_of( + crate::model_call::probe_via( + crate::model_call::Via::Anthropic, + &self.state.http, + api_key, + &meter, + model, + ) + .await, + ) + } +} + +#[async_trait] +impl Store for Live<'_> { + async fn team_key(&self, team_id: &str) -> Option { + use aws_sdk_dynamodb::types::AttributeValue as A; + self.state + .dynamo + .get_item() + .table_name(&self.state.config.settings_table_name) + .key("pk", A::S(team_id.to_string())) + .key("sk", A::S("SETTINGS#MODEL_PROVIDER".into())) + .send() + .await + .ok()? + .item()? + .get("api_key")? + .as_s() + .ok() + .filter(|k| !k.is_empty()) + .cloned() + } + async fn audit(&self, detail: &str) -> Result<(), String> { + super::roles::record( + self.state, + self.claims, + super::roles::AuditEntry { + action: "model_provider_switched", + role_id: "", + role_name: "", + detail: detail.to_string(), + }, + ) + .await + .map_err(|_| "write failed".to_string()) + } + async fn save(&self, record: &Value) -> Result<(), String> { + use aws_sdk_dynamodb::types::AttributeValue as A; + self.state + .dynamo + .put_item() + .table_name(&self.state.config.settings_table_name) + .item("pk", A::S(mp::SETTINGS_PK.into())) + .item("sk", A::S(mp::SETTINGS_SK.into())) + .item("data", A::S(record.to_string())) + .send() + .await + .map(|_| ()) + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(&e).to_string()) + } +} + +/// What the Models section shows. +pub fn view(settings: &Settings, source: Source, stored: Option<&Value>) -> Value { + let deploy = mp::deploy_default(); + let ids: serde_json::Map = targets(&Settings { + provider: Provider::Bedrock, + ..settings.clone() + }) + .into_iter() + .map(|(m, id)| (m, json!(id))) + .collect(); + json!({ + "provider": settings.provider.as_str(), + "inference_prefix": settings.inference_prefix, + "model_ids": settings.model_ids, + "source": source, + "updated_at": stored.and_then(|s| s.get("updated_at")).cloned().unwrap_or(Value::Null), + "updated_by": stored.and_then(|s| s.get("updated_by")).cloned().unwrap_or(Value::Null), + "deploy_default": { + "provider": deploy.provider.as_str(), + "inference_prefix": deploy.inference_prefix, + }, + "region": region(), + "models": common::model_ids::release_calls(), + // The Bedrock id each model is called by under these settings. + "bedrock_ids": ids, + "prefixes": ["us.", "eu.", "apac.", "global.", ""], + }) +} + +async fn stored(state: &AppState) -> Option { + use aws_sdk_dynamodb::types::AttributeValue as A; + let out = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", A::S(mp::SETTINGS_PK.into())) + .key("sk", A::S(mp::SETTINGS_SK.into())) + .send() + .await + .ok()?; + serde_json::from_str(out.item()?.get("data")?.as_s().ok()?).ok() +} + +/// GET /api/system/models: the provider in force, where it came from, and +/// the ids each model is called by. +pub async fn get_models( + State(state): State>, + Extension(claims): Extension, +) -> Reply { + claims.require_role(3).map_err(not_admin)?; + allowed(&claims)?; + let rec = stored(&state).await; + let (settings, source) = mp::resolve( + rec.as_ref().map(|r| r.to_string()).as_deref(), + mp::deploy_default(), + ); + Ok(Json(view(&settings, source, rec.as_ref()))) +} + +/// POST /api/system/models/check: the test calls a switch would make, with +/// nothing saved ("Check again"). +pub async fn check_models( + State(state): State>, + Extension(claims): Extension, + Json(body): Json, +) -> Reply { + claims.require_role(3).map_err(not_admin)?; + allowed(&claims)?; + let to = requested(&body).map_err(|m| refuse(StatusCode::BAD_REQUEST, &m))?; + let live = Live { + state: &state, + claims: &claims, + }; + let results = check(&live, &live, &claims.team_id, &to).await; + Ok(Json(json!({ + "ok": model_access::all_pass(&results), + "results": results, + }))) +} + +/// PUT /api/system/models: switch, once every model answers. +pub async fn set_models( + State(state): State>, + Extension(claims): Extension, + Json(body): Json, +) -> Reply { + claims.require_role(3).map_err(not_admin)?; + allowed(&claims)?; + let to = requested(&body).map_err(|m| refuse(StatusCode::BAD_REQUEST, &m))?; + let live = Live { + state: &state, + claims: &claims, + }; + let (record, results) = switch(&live, &live, &claims.team_id, &claims.email, to.clone()) + .await + .map_err(|(c, v)| (c, Json(v)))?; + // This instance at once; the others within 30 seconds. + mp::set_current(to.clone(), Source::Settings); + info!(provider = to.provider.as_str(), actor = %claims.email, "model provider switched"); + let mut out = view(&to, Source::Settings, Some(&record)); + out["results"] = json!(results); + Ok(Json(out)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + + struct Fake { + bedrock: fn(&str) -> Answer, + anthropic: fn(&str) -> Answer, + key: Option<&'static str>, + audit_ok: bool, + calls: Mutex>, + audited: Mutex>, + saved: Mutex>, + } + + impl Fake { + fn new(bedrock: fn(&str) -> Answer) -> Self { + Fake { + bedrock, + anthropic: |_| Answer::Ok, + key: Some("sk-ant-test"), + audit_ok: true, + calls: Mutex::new(vec![]), + audited: Mutex::new(vec![]), + saved: Mutex::new(vec![]), + } + } + } + + #[async_trait] + impl Prober for Fake { + async fn bedrock(&self, _model: &str, id: &str) -> Answer { + self.calls.lock().unwrap().push(format!("bedrock {id}")); + (self.bedrock)(id) + } + async fn anthropic(&self, key: &str, model: &str) -> Answer { + self.calls + .lock() + .unwrap() + .push(format!("anthropic {model} {key}")); + (self.anthropic)(model) + } + } + + #[async_trait] + impl Store for Fake { + async fn team_key(&self, _team: &str) -> Option { + self.key.map(str::to_string) + } + async fn audit(&self, detail: &str) -> Result<(), String> { + if !self.audit_ok { + return Err("throttled".into()); + } + self.audited.lock().unwrap().push(detail.to_string()); + Ok(()) + } + async fn save(&self, record: &Value) -> Result<(), String> { + self.saved.lock().unwrap().push(record.clone()); + Ok(()) + } + } + + fn bedrock_eu() -> Settings { + requested(&json!({"provider": "bedrock", "inference_prefix": "eu."})).unwrap() + } + + #[test] + fn a_request_is_read_and_checked() { + let s = requested(&json!({"provider": "bedrock", "inference_prefix": " apac. ", "model_ids": {"claude-opus-5-5": "arn:aws:bedrock:ap-southeast-2:111122223333:application-inference-profile/x", "claude-sonnet-5-5": ""}})).unwrap(); + assert_eq!(s.inference_prefix, "apac."); + assert_eq!(s.model_ids.len(), 1); + assert!(requested(&json!({"provider": "openai"})).is_err()); + assert!( + requested(&json!({"provider": "bedrock", "inference_prefix": "US"})) + .unwrap_err() + .contains("prefix") + ); + assert!(requested( + &json!({"provider": "bedrock", "model_ids": {"claude-opus-5-5": "gpt"}}) + ) + .is_err()); + // Keys: no Bedrock fields kept. + let k = requested(&json!({"provider": "anthropic", "inference_prefix": "eu."})).unwrap(); + assert_eq!(k.provider, Provider::Anthropic); + assert_eq!(k.inference_prefix, "us."); + } + + #[test] + fn every_model_the_release_calls_is_checked_by_its_bedrock_id() { + let t = targets(&bedrock_eu()); + let models: Vec<&str> = t.iter().map(|(m, _)| m.as_str()).collect(); + assert_eq!(models, common::model_ids::release_calls()); + assert!(t.iter().all(|(m, id)| id == &format!("eu.anthropic.{m}"))); + } + + #[tokio::test] + async fn a_switch_that_passes_is_audited_then_saved() { + let f = Fake::new(|_| Answer::Ok); + let (record, results) = switch(&f, &f, "TEAM#1", "admin@example.com", bedrock_eu()) + .await + .unwrap(); + assert!(results.iter().all(|r| r.status == "pass")); + assert_eq!(record["provider"], "bedrock"); + assert_eq!(record["inference_prefix"], "eu."); + assert_eq!(record["updated_by"], "admin@example.com"); + assert_eq!(f.saved.lock().unwrap().len(), 1); + let audited = f.audited.lock().unwrap(); + assert_eq!(audited.len(), 1); + assert!(audited[0].contains("to Claude on Amazon Bedrock (eu. inference profiles)")); + assert_eq!( + f.calls.lock().unwrap().len(), + common::model_ids::release_calls().len() + ); + } + + #[tokio::test] + async fn a_refused_model_stops_the_switch_and_says_why() { + let f = Fake::new(|id| { + if id.contains("opus") { + Answer::Refused( + 400, + "Model use case details have not been submitted for this account.".into(), + ) + } else { + Answer::Ok + } + }); + let (code, body) = switch(&f, &f, "TEAM#1", "a@example.com", bedrock_eu()) + .await + .unwrap_err(); + assert_eq!(code, StatusCode::CONFLICT); + assert!(body["error"].as_str().unwrap().contains("claude-opus-5-5")); + let bad = body["results"] + .as_array() + .unwrap() + .iter() + .find(|r| r["status"] == "fail") + .unwrap(); + assert_eq!(bad["code"], "use_case_required"); + assert!(bad["url"].as_str().unwrap().contains("#/modelaccess")); + assert!(!bad["fix"].as_str().unwrap().is_empty()); + // Nothing written. + assert!(f.saved.lock().unwrap().is_empty()); + assert!(f.audited.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn every_refusal_kind_refuses_the_switch() { + let kinds: [fn(&str) -> Answer; 6] = [ + |_| Answer::Refused(403, "You don't have access to the model".into()), + |_| Answer::Refused(400, "use case details have not been submitted".into()), + |_| Answer::Refused(403, "aws-marketplace:Subscribe failed".into()), + |_| Answer::Refused(403, "is not authorized to perform: bedrock:Converse".into()), + |_| Answer::Refused(400, "The provided model identifier is invalid.".into()), + |_| Answer::Unreachable("timeout".into()), + ]; + let codes = [ + "access_denied", + "use_case_required", + "marketplace_failed", + "iam_denied", + "not_available", + "unreachable", + ]; + for (k, code) in kinds.into_iter().zip(codes) { + let f = Fake::new(k); + let (_, body) = switch(&f, &f, "TEAM#1", "a@example.com", bedrock_eu()) + .await + .unwrap_err(); + assert_eq!(body["results"][0]["code"], code); + assert!(f.saved.lock().unwrap().is_empty(), "{code}"); + } + } + + #[tokio::test] + async fn a_switch_to_keys_needs_a_working_team_key() { + let mut f = Fake::new(|_| Answer::Ok); + f.key = None; + let to = requested(&json!({"provider": "anthropic"})).unwrap(); + let (_, body) = switch(&f, &f, "TEAM#1", "a@example.com", to.clone()) + .await + .unwrap_err(); + assert_eq!(body["results"][0]["code"], "no_key"); + assert!(f.calls.lock().unwrap().is_empty()); + // With a key: checked with it, and the team is kept for the updater. + let f = Fake::new(|_| Answer::Ok); + let (record, _) = switch(&f, &f, "TEAM#1", "a@example.com", to).await.unwrap(); + assert_eq!(record["probe_team"], "TEAM#1"); + assert!(f.calls.lock().unwrap()[0].ends_with("sk-ant-test")); + let mut f = Fake::new(|_| Answer::Ok); + f.anthropic = |_| Answer::Refused(401, "invalid x-api-key".into()); + let to = requested(&json!({"provider": "anthropic"})).unwrap(); + let (_, body) = switch(&f, &f, "TEAM#1", "a@example.com", to) + .await + .unwrap_err(); + assert_eq!(body["results"][0]["code"], "key_refused"); + } + + #[tokio::test] + async fn no_audit_entry_no_switch() { + let mut f = Fake::new(|_| Answer::Ok); + f.audit_ok = false; + let (code, body) = switch(&f, &f, "TEAM#1", "a@example.com", bedrock_eu()) + .await + .unwrap_err(); + assert_eq!(code, StatusCode::INTERNAL_SERVER_ERROR); + assert!(body["error"].as_str().unwrap().contains("audit log")); + assert!(f.saved.lock().unwrap().is_empty()); + } + + #[test] + fn the_audit_line_says_from_and_to() { + let keys = Settings::default(); + let mut b = bedrock_eu(); + assert_eq!( + audit_detail(&keys, &b), + "Changed how the install calls Claude from Anthropic API keys to Claude on Amazon Bedrock (eu. inference profiles)." + ); + b.inference_prefix = String::new(); + b.model_ids + .insert("claude-opus-5-5".into(), "anthropic.claude-opus-5-5".into()); + assert!(audit_detail(&b, &keys).contains("in-region ids, 1 model id override(s)")); + } + + #[test] + fn the_view_shows_the_ids_and_where_the_setting_came_from() { + let v = view( + &bedrock_eu(), + Source::Settings, + Some(&json!({"updated_by": "a@example.com", "updated_at": "2026-10-26T00:00:00Z"})), + ); + assert_eq!(v["provider"], "bedrock"); + assert_eq!(v["source"], "settings"); + assert_eq!(v["updated_by"], "a@example.com"); + assert_eq!( + v["bedrock_ids"]["claude-opus-5-5"], + "eu.anthropic.claude-opus-5-5" + ); + assert!(v["prefixes"].as_array().unwrap().contains(&json!(""))); + } +} diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index f1ef11296..cff3160e6 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -386,6 +386,34 @@ pub async fn converse_simple( extract_text(&resp.blocks()) } +/// The model check's test call: one token out, recorded on the client's +/// meter like any call. `Ok` when the model answered (a reply cut at the +/// one-token limit is an answer). +pub async fn probe( + client: &AnthropicClient, + model_id: &str, + usage: &mut crate::models::TokenUsage, +) -> Result<(), Box> { + let request = MessagesRequest { + model: model_id.to_string(), + max_tokens: 1, + system: vec![], + messages: vec![ApiMessage { + role: "user".to_string(), + content: vec![json!({ "type": "text", "text": "Reply with OK." })], + }], + tools: None, + cache_control: None, + thinking: None, + output_config: None, + context_management: None, + fallbacks: None, + tool_choice: None, + temperature: None, + }; + send_request(client, &request, usage).await.map(|_| ()) +} + /// One call whose answer is a JSON object matching `schema`, parsed. With /// `constrained`, the API holds the answer to the schema (structured /// outputs); without, the schema is in the instructions and the answer's diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index dd738db2c..3d5b94ab1 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -33,6 +33,8 @@ impl ModelProvider { settings_table: &str, team_id: &str, ) -> Result> { + // The install's provider as it is now (Settings, System, Models). + common::model_provider::refresh(dynamo, settings_table).await; let result = dynamo .get_item() .table_name(settings_table) @@ -142,19 +144,46 @@ impl ModelProvider { &self.api_key } - /// A client whose every response is counted for this team. + /// A client whose every response is counted for this team, on the + /// install's provider as it is now. A run that started on Bedrock with + /// no team key loaded keeps Bedrock after a switch to Anthropic keys, so + /// a switch never breaks a run under way. pub fn client(&self) -> AnthropicClient { let meter = self.meter.clone().unwrap_or_else(|| { tracing::warn!("Model provider without a usage meter; usage stays uncounted"); common::usage::UsageMeter::memory("").0 }); - match common::model_provider::bedrock_client() { - Some(bedrock) => AnthropicClient::bedrock(bedrock.clone(), meter), - None => AnthropicClient::new(self.api_key.clone(), meter), + let bedrock = common::model_provider::any_bedrock_client(); + match pick_client( + common::model_provider::is_bedrock(), + bedrock.is_some(), + !self.api_key.is_empty(), + ) { + ClientKind::Bedrock => match bedrock { + Some(b) => AnthropicClient::bedrock(b.clone(), meter), + None => AnthropicClient::new(self.api_key.clone(), meter), + }, + ClientKind::Anthropic => AnthropicClient::new(self.api_key.clone(), meter), } } } +#[derive(Debug, PartialEq, Eq)] +enum ClientKind { + Bedrock, + Anthropic, +} + +/// Which client a call gets: the provider in force, except that a run with +/// no team key stays on Bedrock (it started there before a switch). +fn pick_client(bedrock_now: bool, have_bedrock: bool, have_key: bool) -> ClientKind { + if have_bedrock && (bedrock_now || !have_key) { + ClientKind::Bedrock + } else { + ClientKind::Anthropic + } +} + /// Converse with tool use loop via Anthropic Messages API. #[allow(clippy::too_many_arguments)] pub async fn converse( @@ -171,6 +200,8 @@ pub async fn converse( on_tool_call: Option<&super::llm::OnToolCall>, conversation_log: Option<&mut Vec>, ) -> Result> { + // A switch in Settings, System, Models reaches the next loop. + common::model_provider::refresh(&state.dynamo, &state.config.settings_table_name).await; let client = provider.client(); // Every call this loop makes is asked of the policy gate first. let gate = super::policy::gate(state, provider.scope.ctx(agent), opts.deadline) @@ -196,13 +227,32 @@ pub async fn converse( /// Simple one-shot converse (no tools) via Anthropic Messages API. pub async fn converse_simple( - _state: &crate::WorkerState, + state: &crate::WorkerState, provider: &ModelProvider, model_id: &str, system_prompt: &str, user_message: &str, usage: &mut TokenUsage, ) -> Result> { + common::model_provider::refresh(&state.dynamo, &state.config.settings_table_name).await; let client = provider.client(); anthropic::converse_simple(&client, model_id, system_prompt, user_message, usage).await } + +#[cfg(test)] +mod client_tests { + use super::*; + + #[test] + fn a_switch_never_strands_a_run() { + // Bedrock now: Bedrock. + assert_eq!(pick_client(true, true, false), ClientKind::Bedrock); + assert_eq!(pick_client(true, true, true), ClientKind::Bedrock); + // Switched to Anthropic keys: the team's key when it has one... + assert_eq!(pick_client(false, true, true), ClientKind::Anthropic); + // ...and a run that started on Bedrock without a key finishes there. + assert_eq!(pick_client(false, true, false), ClientKind::Bedrock); + // No Bedrock client at all: the Anthropic API. + assert_eq!(pick_client(false, false, true), ClientKind::Anthropic); + } +} diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 83ed90a3c..f67e1bd41 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -42,7 +42,8 @@ async fn main() -> Result<(), Error> { let s3 = aws_sdk_s3::Client::new(&aws_config); let ses = aws_sdk_sesv2::Client::new(&aws_config); let bedrock = aws_sdk_bedrockruntime::Client::new(&aws_config); - // Claude through Bedrock when the deployment says so (MODEL_PROVIDER). + // Claude through Bedrock: set on every install, so a switch to Bedrock + // in Settings needs no restart. common::model_provider::set_bedrock_client(bedrock.clone()); let lambda_client = aws_sdk_lambda::Client::new(&aws_config); let sqs = aws_sdk_sqs::Client::new(&aws_config); @@ -104,6 +105,9 @@ async fn handle_event( ) -> Result { let (payload, context) = event.into_parts(); common::public_urls::ensure().await; + // The install's model provider (Settings, System, Models), read again + // at most every 30 seconds. + common::model_provider::refresh(&state.dynamo, &state.config.settings_table_name).await; // In-flight model calls are cancelled (and their usage recorded) this // long before the Lambda's own deadline, leaving time for the writes. common::model_stream::set_deadline_epoch_ms(Some( @@ -119,6 +123,11 @@ async fn handle_event( }; let call = passes::plan_chat::handle(&state, req); Ok(common::usage::with_feature(feature, call).await) + } else if let Some(req) = payload.get("model_check") { + // The updater's check before it applies a release: one test call + // per model, through the install's provider. + let req: passes::model_check::Request = serde_json::from_value(req.clone())?; + Ok(passes::model_check::run(&state, req).await) } else if let Some(req) = payload.get("knowledge_ingest") { // A knowledge base file the browser finished uploading (called // asynchronously by the gateway). diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 433b8f1b0..9d366bfea 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -714,6 +714,7 @@ pub mod log_evidence; mod log_fix_checks; #[cfg(test)] mod log_fix_eval; +pub mod model_check; pub mod onboard; pub mod ops_tools; mod plan; diff --git a/services/worker/src/passes/model_check.rs b/services/worker/src/passes/model_check.rs new file mode 100644 index 000000000..5f5b9aedc --- /dev/null +++ b/services/worker/src/passes/model_check.rs @@ -0,0 +1,220 @@ +//! The updater's model check (lambda/updater): before a release is applied, +//! every model it calls gets one test call through the install's provider +//! as it is now (Settings, System, Models), and each answer comes back +//! explained (common::model_access) for Settings, System and Setup. +//! +//! The updater sends the release's models with their Bedrock ids for each +//! inference profile prefix (the release's `models.json`), so a new model +//! is checked by the id the new release will call. An id an admin set under +//! Advanced still wins. Nothing here accepts terms or subscribes to +//! anything: a refusal is reported, and a person fixes it in the console. + +use std::collections::BTreeMap; + +use common::model_access::{self, Access, Answer}; +use common::model_provider::{self as mp, Provider, Settings}; +use serde::Deserialize; +use serde_json::{json, Value}; + +#[derive(Debug, Deserialize)] +pub struct Request { + pub targets: Vec, + /// The team whose key passed the last switch to Anthropic API keys. + #[serde(default)] + pub probe_team: Option, +} + +#[derive(Debug, Deserialize)] +pub struct Target { + pub model: String, + /// The new release's Bedrock id for each inference profile prefix. + #[serde(default)] + pub bedrock_ids: BTreeMap, +} + +/// The id a target is called by under `s`. +pub fn target_id(s: &Settings, t: &Target) -> String { + match s.provider { + Provider::Anthropic => t.model.clone(), + Provider::Bedrock => s + .model_ids + .get(&t.model) + .cloned() + .or_else(|| t.bedrock_ids.get(&s.inference_prefix).cloned()) + .unwrap_or_else(|| s.bedrock_id(&t.model)), + } +} + +fn answer_of(r: Result<(), Box>) -> Answer { + use common::model_retry::{ModelCallError, ModelErrorKind}; + match r { + Ok(()) => Answer::Ok, + Err(e) => match e.downcast_ref::() { + Some(m) => match m.kind { + ModelErrorKind::Status(code) => Answer::Refused(code, m.message.clone()), + ModelErrorKind::Network => Answer::Unreachable(m.message.clone()), + // It answered (cut at one token, or declined "Reply with OK"). + _ => Answer::Ok, + }, + None => Answer::Unreachable(e.to_string()), + }, + } +} + +/// The settings, ids and results as the updater stores them. +pub fn report(s: &Settings, region: &str, results: &[Access]) -> Value { + json!({ + "provider": s.provider.as_str(), + "inference_prefix": s.inference_prefix, + "region": region, + "ok": model_access::all_pass(results), + "results": results, + }) +} + +pub async fn run(state: &crate::WorkerState, req: Request) -> Value { + mp::refresh(&state.dynamo, &state.config.settings_table_name).await; + let s = mp::current(); + let region = std::env::var("AWS_REGION").unwrap_or_else(|_| "us-east-1".into()); + let analytics = std::env::var("ANALYTICS_TABLE_NAME").unwrap_or_default(); + let key = match (s.provider, req.probe_team.as_deref()) { + (Provider::Anthropic, Some(team)) => team_key(state, team).await, + _ => None, + }; + // Bedrock calls are the install's own (the setup meter); a key's are its team's. + let meter_team = match s.provider { + Provider::Bedrock => "SETUP".to_string(), + Provider::Anthropic => req.probe_team.clone().unwrap_or_else(|| "SETUP".into()), + }; + let meter = common::usage::UsageMeter::dynamo(state.dynamo.clone(), &analytics, &meter_team); + let mut results = Vec::new(); + for t in &req.targets { + let id = target_id(&s, t); + let answer = match s.provider { + Provider::Bedrock => match mp::any_bedrock_client() { + Some(b) => { + let client = + crate::agent::anthropic::AnthropicClient::bedrock(b.clone(), meter.clone()); + let mut usage = crate::models::TokenUsage::default(); + answer_of(crate::agent::anthropic::probe(&client, &id, &mut usage).await) + } + None => Answer::Unreachable("no Bedrock client".into()), + }, + Provider::Anthropic => match key.as_deref() { + Some(k) => { + let client = + crate::agent::anthropic::AnthropicClient::new(k.to_string(), meter.clone()); + let mut usage = crate::models::TokenUsage::default(); + answer_of(crate::agent::anthropic::probe(&client, &id, &mut usage).await) + } + None => Answer::NoKey, + }, + }; + results.push(model_access::explain( + s.provider, + &t.model, + &id, + ®ion, + &s.inference_prefix, + &answer, + )); + } + report(&s, ®ion, &results) +} + +async fn team_key(state: &crate::WorkerState, team: &str) -> Option { + use aws_sdk_dynamodb::types::AttributeValue as A; + state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", A::S(team.to_string())) + .key("sk", A::S("SETTINGS#MODEL_PROVIDER".into())) + .send() + .await + .ok()? + .item()? + .get("api_key")? + .as_s() + .ok() + .filter(|k| !k.is_empty()) + .cloned() +} + +#[cfg(test)] +mod tests { + use super::*; + use common::model_retry::{ModelCallError, ModelErrorKind}; + + fn target() -> Target { + serde_json::from_value(json!({ + "model": "claude-opus-5-5", + "bedrock_ids": {"us.": "us.anthropic.claude-opus-5-5-v2:0", "eu.": "eu.anthropic.claude-opus-5-5-v2:0"} + })) + .unwrap() + } + + #[test] + fn the_new_release_id_for_the_install_prefix_is_checked() { + let mut s = Settings { + provider: Provider::Bedrock, + inference_prefix: "eu.".into(), + ..Default::default() + }; + assert_eq!( + target_id(&s, &target()), + "eu.anthropic.claude-opus-5-5-v2:0" + ); + // A prefix the release didn't list: the usual rule. + s.inference_prefix = "apac.".into(); + assert_eq!(target_id(&s, &target()), "apac.anthropic.claude-opus-5-5"); + // An admin's override wins. + s.model_ids.insert( + "claude-opus-5-5".into(), + "arn:aws:bedrock:x:1:application-inference-profile/p".into(), + ); + assert!(target_id(&s, &target()).starts_with("arn:")); + // Keys: the model's name. + assert_eq!( + target_id(&Settings::default(), &target()), + "claude-opus-5-5" + ); + } + + #[test] + fn call_errors_become_answers() { + let e = |k| { + Err(Box::new(ModelCallError::new(k, "m")) as Box) + }; + assert_eq!(answer_of(Ok(())), Answer::Ok); + assert_eq!( + answer_of(e(ModelErrorKind::Status(403))), + Answer::Refused(403, "m".into()) + ); + assert_eq!( + answer_of(e(ModelErrorKind::Network)), + Answer::Unreachable("m".into()) + ); + assert_eq!(answer_of(e(ModelErrorKind::Truncated)), Answer::Ok); + } + + #[test] + fn the_report_says_whether_every_model_answered() { + let s = Settings { + provider: Provider::Bedrock, + ..Default::default() + }; + let refused = model_access::explain( + Provider::Bedrock, + "claude-opus-5-5", + "us.anthropic.claude-opus-5-5", + "us-east-1", + "us.", + &Answer::Refused(400, "use case details have not been submitted".into()), + ); + let r = report(&s, "us-east-1", &[refused]); + assert_eq!(r["ok"], false); + assert_eq!(r["provider"], "bedrock"); + assert_eq!(r["results"][0]["code"], "use_case_required"); + } +}