From 88f8829c9afea303a5d5d7934d2a26adbf5dbaa6 Mon Sep 17 00:00:00 2001 From: Harlan Wilton Date: Wed, 18 Nov 2026 23:22:05 +1100 Subject: [PATCH 1/4] feat(artifacts): serve trusted roots by root key id The private key for the root skilld-root-2026 is lost, so that root can never list a new signing key, and skilld-production-2026-08 closes on 2026-11-20. skilld CLI 3.7.0 pins new roots and fetches each one by id from /api/v1/trusted-roots/{rootKeyId}, while older CLIs keep reading /api/v1/trusted-root. The site verifies with the first served root and falls back to the legacy root until ARTIFACT_TRUSTED_ROOTS_JSON is set. The ceremony tool gains create-root, and the runbook records where each root key lives. --- .dev.vars.example | 3 ++ GLOSSARY.md | 6 +++ checks/_helpers/signing-key.ts | 2 +- docs/runbooks/signing-key-rotation.md | 33 +++++++++++++ .../v1/artifacts/[id]/grants/index.post.ts | 4 +- .../api/v1/trusted-roots/[rootKeyId].get.ts | 20 ++++++++ .../artifact-delivery/server/utils/queue.ts | 4 +- .../server/utils/trusted-root.ts | 35 ++++++++++++++ scripts/lib/trusted-root-ceremony.ts | 8 ++++ scripts/trusted-root.ts | 44 ++++++++++++----- test/unit/trusted-root-ceremony.test.ts | 37 +++++++++++++++ test/unit/trusted-root.test.ts | 47 ++++++++++++++++++- worker-configuration.d.ts | 5 +- 13 files changed, 227 insertions(+), 21 deletions(-) create mode 100644 layers/artifact-delivery/server/api/v1/trusted-roots/[rootKeyId].get.ts diff --git a/.dev.vars.example b/.dev.vars.example index 1e8990c6..c71851f3 100644 --- a/.dev.vars.example +++ b/.dev.vars.example @@ -36,6 +36,9 @@ ARTIFACT_KEY_WRAP_KEY_SECONDARY= ARTIFACT_GRANT_IDEMPOTENCY_KEY= # Public verification material. The signer keeps private keys in its Worker. ARTIFACT_TRUSTED_ROOT_JSON= +# A JSON array of trusted roots, served by root key id. The first one lists +# every signing key the site accepts. skilld CLI 3.7.0 and later read these. +ARTIFACT_TRUSTED_ROOTS_JSON= ANTHROPIC_API_KEY= VOYAGE_API_KEY= X_BEARER_KEY= diff --git a/GLOSSARY.md b/GLOSSARY.md index 3a4051cb..6e33692a 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -303,6 +303,12 @@ Existing route paths, table names, and protocol fields keep their identifiers. **Never:** signature (bare), certificate, receipt. +### trusted root + +**Is:** the list of signing keys an Artifact attestation may use, each signed by an offline root key. Each skilld CLI release pins one root key and fetches that root by its id. + +**Never:** keyring, trust store, certificate chain. + ### linked file **Is:** a Skill file the Artifact attestation lists by path, size, and Git blob SHA, without packing its bytes. The skilld CLI reads it from GitHub at the attested commit and checks it against that SHA. Only a CLI that sends `Skilld-Capabilities: linked-files` gets one. See ADR-0013. diff --git a/checks/_helpers/signing-key.ts b/checks/_helpers/signing-key.ts index f170186f..9453dd9b 100644 --- a/checks/_helpers/signing-key.ts +++ b/checks/_helpers/signing-key.ts @@ -6,7 +6,7 @@ import { fail, pass, readBoundedResponseText, warn } from '@harlan-zw/nuxt-check import { z } from 'zod' import { ARTIFACT_SIGNING_KEY_SLOTS, selectSigningKey } from '../../workers/artifact-signer/src/slots' -export const TRUSTED_ROOT_URL = 'https://skilld.dev/api/v1/trusted-root' +export const TRUSTED_ROOT_URL = 'https://skilld.dev/api/v1/trusted-roots/skilld-root-2026-11' export const SIGNING_KEY_WARN_DAYS = 30 export const SIGNING_KEY_FAIL_DAYS = 7 const DAY_SECONDS = 86_400 diff --git a/docs/runbooks/signing-key-rotation.md b/docs/runbooks/signing-key-rotation.md index 9c2fa054..b3352bad 100644 --- a/docs/runbooks/signing-key-rotation.md +++ b/docs/runbooks/signing-key-rotation.md @@ -9,6 +9,39 @@ The key `skilld-production-2026-08` closes at `2026-11-20T00:00:00.000Z`. This runbook replaces it with `skilld-production-2026-11` and keeps both keys trusted during an overlap. The daily check-in result `skilld.signing-key` warns 30 days before the last window closes. +## Root keys + +The private key for the first root, `skilld-root-2026`, was lost in November 2026. +CLI releases 3.0.0 to 3.6.9 pin that root and read it from `/api/v1/trusted-root`, so no new signing key can reach them. + +From 3.7.0, each CLI pins a primary and a backup root and fetches each one from `/api/v1/trusted-roots/{rootKeyId}`. +The site serves those roots from the `ARTIFACT_TRUSTED_ROOTS_JSON` secret, a JSON array. +The first root in the array lists every signing key the site accepts. + +| Root key | Pinned by | Where the private key lives | +| --- | --- | --- | +| `skilld-root-2026-11` | 3.7.0 and later, first | Harlan's password manager, and an offline USB stick | +| `skilld-root-backup-2026-11` | 3.7.0 and later, if the primary root is not served | Harlan's password manager, and a second offline USB stick | + +Before every ceremony, restore each root key you need from its copy and check it with `verify --signing-key`. +If both copies of a root key are gone, serve the other root. If both roots are gone, a new root needs a CLI release. + +### Start a new root + +`create-root` signs the first signing key under a new root key. `add-key` signs the rest. + +```sh +pnpm exec tsx scripts/trusted-root.ts signing-key --key-id skilld-root-2026-11 --out "$KEYS" +pnpm exec tsx scripts/trusted-root.ts create-root \ + --root-key-id skilld-root-2026-11 \ + --root-key "$KEYS/skilld-root-2026-11.pkcs8" \ + --key-id skilld-production-2026-08 \ + --public-key-file "$KEYS/skilld-production-2026-08.pub" \ + --not-before 2026-08-20T00:00:00Z \ + --not-after 2026-11-20T00:00:00Z \ + --out "$KEYS/skilld-root-2026-11.json" +``` + ## How signing works The site stages an attestation statement for a Resolution. diff --git a/layers/artifact-delivery/server/api/v1/artifacts/[id]/grants/index.post.ts b/layers/artifact-delivery/server/api/v1/artifacts/[id]/grants/index.post.ts index 01439a65..dd091002 100644 --- a/layers/artifact-delivery/server/api/v1/artifacts/[id]/grants/index.post.ts +++ b/layers/artifact-delivery/server/api/v1/artifacts/[id]/grants/index.post.ts @@ -10,7 +10,7 @@ import { import { createPublicArtifactGrant } from '../../../../../utils/grant' import { privateArtifactAccessEnabled } from '../../../../../utils/private-feature' import { createPrivateArtifactGrant } from '../../../../../utils/private-grant' -import { parseTrustedRoot } from '../../../../../utils/trusted-root' +import { siteTrustedRoot } from '../../../../../utils/trusted-root' export default withArtifactProblems(defineApiHandler({ response: artifactGrantSchema, @@ -30,7 +30,7 @@ export default withArtifactProblems(defineApiHandler({ }) } const now = Math.floor(Date.now() / 1000) - const trustedRoot = parseTrustedRoot(platform.env.ARTIFACT_TRUSTED_ROOT_JSON, now) + const trustedRoot = siteTrustedRoot(platform.env, now) const publicResult = await createPublicArtifactGrant({ db: platform.db, trustedRoot, diff --git a/layers/artifact-delivery/server/api/v1/trusted-roots/[rootKeyId].get.ts b/layers/artifact-delivery/server/api/v1/trusted-roots/[rootKeyId].get.ts new file mode 100644 index 00000000..ff60e464 --- /dev/null +++ b/layers/artifact-delivery/server/api/v1/trusted-roots/[rootKeyId].get.ts @@ -0,0 +1,20 @@ +import { getRouterParam, setHeader } from 'h3' +import { defineApiHandler } from '#shared/server/handler' +import { trustedRootSchema } from '../../../schemas/contracts' +import { withArtifactProblems } from '../../../utils/artifact-problem' +import { parseTrustedRoots } from '../../../utils/trusted-root' + +// skilld CLI 3.7.0 and later fetch the root they pin by its id, so a new root +// never replaces the one an older CLI pins. +export default withArtifactProblems(defineApiHandler({ + response: trustedRootSchema, + handler({ event, platform }) { + const rootKeyId = getRouterParam(event, 'rootKeyId') + const root = parseTrustedRoots(platform.env.ARTIFACT_TRUSTED_ROOTS_JSON, Math.floor(Date.now() / 1000)) + .find(served => served.rootKeyId === rootKeyId) + if (!root) + throw createError({ statusCode: 404, message: 'Trusted root not found' }) + setHeader(event, 'cache-control', 'public, max-age=300, s-maxage=300') + return root + }, +})) diff --git a/layers/artifact-delivery/server/utils/queue.ts b/layers/artifact-delivery/server/utils/queue.ts index 797157ac..392e804a 100644 --- a/layers/artifact-delivery/server/utils/queue.ts +++ b/layers/artifact-delivery/server/utils/queue.ts @@ -23,7 +23,7 @@ import { privateArtifactAccessEnabled } from './private-feature' import { putPrivateArtifact } from './private-storage' import { createRequesterGithubSource, forgetResolutionRequester } from './requester-github' import { getResolution } from './state' -import { parseTrustedRoot } from './trusted-root' +import { siteTrustedRoot } from './trusted-root' export const ARTIFACT_BUILD_QUEUE_NAME = 'skilld-artifact-build' @@ -228,7 +228,7 @@ export function createArtifactBuildDependencies(env: Cloudflare.Env): ArtifactBu }), bucket: env.PUBLIC_ARTIFACTS, signer: createArtifactSigner(env.ARTIFACT_SIGNER), - trustedRoot: parseTrustedRoot(env.ARTIFACT_TRUSTED_ROOT_JSON, Math.floor(Date.now() / 1000)), + trustedRoot: siteTrustedRoot(env, Math.floor(Date.now() / 1000)), now: () => Math.floor(Date.now() / 1000), reviewBehaviors: createBehaviorReviewer({ db: env.DB, diff --git a/layers/artifact-delivery/server/utils/trusted-root.ts b/layers/artifact-delivery/server/utils/trusted-root.ts index 37330429..5f9f2378 100644 --- a/layers/artifact-delivery/server/utils/trusted-root.ts +++ b/layers/artifact-delivery/server/utils/trusted-root.ts @@ -21,6 +21,41 @@ export function parseTrustedRoot(value: string, now: number) { }) } +/** + * The roots served at `/api/v1/trusted-roots/{rootKeyId}`, from a JSON array. + * skilld CLI 3.7.0 and later fetch the root they pin by its id. Older CLIs pin + * `skilld-root-2026`, whose key was lost, and read `/api/v1/trusted-root`. + */ +export function parseTrustedRoots(value: string | undefined, now: number): TrustedRoot[] { + if (!value?.trim()) + return [] + const configs: unknown = JSON.parse(value) + if (!Array.isArray(configs) || configs.length === 0) + throw new Error('Served trusted roots must be a non-empty JSON array') + const roots = configs.map(config => parseTrustedRoot(JSON.stringify(config), now)) + const seen = new Set() + for (const root of roots) { + if (seen.has(root.rootKeyId)) + throw new Error(`Trusted root ${root.rootKeyId} is served twice`) + seen.add(root.rootKeyId) + } + return roots +} + +interface TrustedRootEnv { + ARTIFACT_TRUSTED_ROOTS_JSON?: string + ARTIFACT_TRUSTED_ROOT_JSON: string +} + +/** + * The root whose signing keys the site verifies attestations with: the first + * served root, which lists every key the site accepts. Until roots are served, + * the legacy root. + */ +export function siteTrustedRoot(env: TrustedRootEnv, now: number): TrustedRoot { + return parseTrustedRoots(env.ARTIFACT_TRUSTED_ROOTS_JSON, now)[0] ?? parseTrustedRoot(env.ARTIFACT_TRUSTED_ROOT_JSON, now) +} + function decodeCanonicalBase64Url(value: string): Uint8Array | null { if (value.length % 4 === 1) return null diff --git a/scripts/lib/trusted-root-ceremony.ts b/scripts/lib/trusted-root-ceremony.ts index 4d5c0f37..feec876d 100644 --- a/scripts/lib/trusted-root-ceremony.ts +++ b/scripts/lib/trusted-root-ceremony.ts @@ -114,6 +114,14 @@ export function addTrustedKey(root: TrustedRootConfig, rootPrivateKey: KeyObject }) } +/** + * Starts a trusted root under a new root key with its first signing key. A + * root lists at least one key, so the root and its first key are made together. + */ +export function createTrustedRoot(rootKeyId: string, rootPrivateKey: KeyObject, firstKey: NewTrustedKey): TrustedRootConfig { + return addTrustedKey({ version: 1, rootKeyId, rootPublicKey: publicKeyOf(rootPrivateKey), keys: [] }, rootPrivateKey, firstKey) +} + /** Removes one signing key. Removal needs no root signature. */ export function removeTrustedKey(root: TrustedRootConfig, keyId: string): TrustedRootConfig { if (!root.keys.some(key => key.keyId === keyId)) diff --git a/scripts/trusted-root.ts b/scripts/trusted-root.ts index ae3e54a7..1caef06e 100644 --- a/scripts/trusted-root.ts +++ b/scripts/trusted-root.ts @@ -1,12 +1,13 @@ // The Artifact signing key ceremony. docs/runbooks/signing-key-rotation.md // gives the order. No command prints a private key: each one reads or writes // key files with mode 600. -import type { RootPin, TrustedRootConfig } from './lib/trusted-root-ceremony' +import type { NewTrustedKey, RootPin, TrustedRootConfig } from './lib/trusted-root-ceremony' import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { parseArgs } from 'node:util' import { addTrustedKey, + createTrustedRoot, generateSigningKey, parseRootConfig, readPrivateKey, @@ -15,12 +16,17 @@ import { verifyTrustedRoot, } from './lib/trusted-root-ceremony' -const LIVE_ROOT = 'https://skilld.dev/api/v1/trusted-root' +// The root that skilld CLI 3.7.0 and later pin first. Each root is served at +// its own path, so CLIs pinned to an older root keep reading theirs. +const LIVE_ROOT = 'https://skilld.dev/api/v1/trusted-roots/skilld-root-2026-11' const USAGE = `Usage: pnpm exec tsx scripts/trusted-root.ts [options] signing-key --key-id --out - Write /.pkcs8 (the signer secret) and /.pub. + Write /.pkcs8 and /.pub. Also makes a root key pair. + create-root --root-key-id --root-key --key-id --public-key-file + --not-before --not-after [--status active|overlapping] --out + Start a trusted root under a new root key, with its first signing key. add-key --root --root-key --key-id --public-key-file --not-before --not-after [--status active|overlapping] --out Sign the key statement with the offline root key and write the new root. @@ -41,6 +47,7 @@ const { positionals, values } = parseArgs({ 'public-key-file': { type: 'string' }, 'root': { type: 'string' }, 'root-key': { type: 'string' }, + 'root-key-id': { type: 'string' }, 'signing-key': { type: 'string' }, 'status': { type: 'string' }, }, @@ -70,6 +77,19 @@ function writeNew(path: string, value: string, mode: number): void { writeFileSync(path, value, { mode, flag: 'wx' }) } +function newKeyFromArgs(): NewTrustedKey { + const status = values.status ?? 'active' + if (status !== 'active' && status !== 'overlapping') + throw new Error('--status must be active or overlapping.') + return { + keyId: required('key-id'), + publicKey: readFileSync(required('public-key-file'), 'utf8').trim(), + notBefore: required('not-before'), + notAfter: required('not-after'), + status, + } +} + function printKeys(root: TrustedRootConfig): void { const now = Date.now() for (const key of root.keys) { @@ -89,18 +109,16 @@ async function main(command: string | undefined): Promise { console.log(`Wrote ${join(out, `${keyId}.pkcs8`)} (private, mode 600) and ${join(out, `${keyId}.pub`)}.`) return } + case 'create-root': { + const next = createTrustedRoot(required('root-key-id'), readPrivateKey(readFileSync(required('root-key'), 'utf8')), newKeyFromArgs()) + writeNew(required('out'), JSON.stringify(next), 0o600) + console.log(`Wrote ${required('out')} for root ${next.rootKeyId}:`) + printKeys(next) + return + } case 'add-key': { const root = await readRoot(required('root')) - const status = values.status ?? 'active' - if (status !== 'active' && status !== 'overlapping') - throw new Error('--status must be active or overlapping.') - const next = addTrustedKey(root, readPrivateKey(readFileSync(required('root-key'), 'utf8')), { - keyId: required('key-id'), - publicKey: readFileSync(required('public-key-file'), 'utf8').trim(), - notBefore: required('not-before'), - notAfter: required('not-after'), - status, - }) + const next = addTrustedKey(root, readPrivateKey(readFileSync(required('root-key'), 'utf8')), newKeyFromArgs()) writeNew(required('out'), JSON.stringify(next), 0o600) console.log(`Wrote ${required('out')}:`) printKeys(next) diff --git a/test/unit/trusted-root-ceremony.test.ts b/test/unit/trusted-root-ceremony.test.ts index 1739f914..2b31ac09 100644 --- a/test/unit/trusted-root-ceremony.test.ts +++ b/test/unit/trusted-root-ceremony.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest' import { parseTrustedRoot } from '../../layers/artifact-delivery/server/utils/trusted-root' import { addTrustedKey, + createTrustedRoot, generateSigningKey, parseRootConfig, publicKeyOf, @@ -131,3 +132,39 @@ describe('trusted root ceremony', () => { expect(signingKeyMatches(current, 'skilld-production-2026-08', readPrivateKey(newKey.privateKeyPkcs8))).toBe(false) }) }) + +// The root key for `skilld-root-2026` was lost, so the next root starts from a +// new root key and re-signs every signing key it still trusts. +describe('new trusted root', () => { + it('creates a root that the CLI rules accept under its own root key', () => { + const { privateKey: rootPrivateKey } = generateKeyPairSync('ed25519') + const signingKey = generateSigningKey() + + const root = createTrustedRoot('skilld-root-2026-11', rootPrivateKey, { + keyId: 'skilld-production-2026-08', + publicKey: signingKey.publicKey, + notBefore: '2026-08-20T00:00:00.000Z', + notAfter: '2026-11-20T00:00:00.000Z', + status: 'active', + }) + + const pin = { rootKeyId: 'skilld-root-2026-11', rootPublicKey: publicKeyOf(rootPrivateKey) } + expect(verifyTrustedRoot(root, pin, NOW)).toEqual({ _tag: 'valid' }) + expect(parseTrustedRoot(JSON.stringify(root), NOW).keys.map(key => key.keyId)).toEqual(['skilld-production-2026-08']) + }) + + it('fails a CLI that pins the previous root', () => { + const { pin: previousPin } = ceremony() + const { privateKey: rootPrivateKey } = generateKeyPairSync('ed25519') + + const root = createTrustedRoot('skilld-root-2026-11', rootPrivateKey, { + keyId: 'skilld-production-2026-11', + publicKey: generateSigningKey().publicKey, + notBefore: '2026-11-18T00:00:00Z', + notAfter: '2027-05-20T00:00:00Z', + status: 'active', + }) + + expect(verifyTrustedRoot(root, previousPin, NOW)._tag).toBe('invalid') + }) +}) diff --git a/test/unit/trusted-root.test.ts b/test/unit/trusted-root.test.ts index d9a463e1..4e41cf72 100644 --- a/test/unit/trusted-root.test.ts +++ b/test/unit/trusted-root.test.ts @@ -1,6 +1,9 @@ +import type { TrustedRootConfig } from '../../scripts/lib/trusted-root-ceremony' +import { generateKeyPairSync } from 'node:crypto' import { describe, expect, it } from 'vitest' import { bytesToBase64Url } from '../../layers/artifact-delivery/server/utils/encoding' -import { parseTrustedRoot } from '../../layers/artifact-delivery/server/utils/trusted-root' +import { parseTrustedRoot, parseTrustedRoots, siteTrustedRoot } from '../../layers/artifact-delivery/server/utils/trusted-root' +import { createTrustedRoot, generateSigningKey } from '../../scripts/lib/trusted-root-ceremony' const statement = { version: 1, @@ -49,3 +52,45 @@ describe('trusted root parsing', () => { expect(() => parseTrustedRoot(trustedRoot({ statement: `${encoded}=` }), 1_776_297_600)).toThrow() }) }) + +// skilld CLI 3.7.0 and later fetch their pinned root by id, because the key for +// `skilld-root-2026` was lost and older CLIs can only ever read that root. +describe('trusted roots by id', () => { + const now = Date.parse('2026-11-18T12:00:00.000Z') / 1000 + + function root(rootKeyId: string): TrustedRootConfig { + const { privateKey } = generateKeyPairSync('ed25519') + return createTrustedRoot(rootKeyId, privateKey, { + keyId: 'skilld-production-2026-11', + publicKey: generateSigningKey().publicKey, + notBefore: '2026-11-18T00:00:00.000Z', + notAfter: '2027-05-20T00:00:00.000Z', + status: 'active', + }) + } + + it('reads every served root with its root key id', () => { + const roots = parseTrustedRoots(JSON.stringify([root('skilld-root-2026-11'), root('skilld-root-backup-2026-11')]), now) + + expect(roots.map(served => served.rootKeyId)).toEqual(['skilld-root-2026-11', 'skilld-root-backup-2026-11']) + }) + + it('rejects two roots with the same root key id', () => { + expect(() => parseTrustedRoots(JSON.stringify([root('skilld-root-2026-11'), root('skilld-root-2026-11')]), now)) + .toThrow('skilld-root-2026-11') + }) + + it('verifies attestations with the first served root', () => { + const env = { + ARTIFACT_TRUSTED_ROOTS_JSON: JSON.stringify([root('skilld-root-2026-11'), root('skilld-root-backup-2026-11')]), + ARTIFACT_TRUSTED_ROOT_JSON: trustedRoot(), + } + + expect(siteTrustedRoot(env, now).rootKeyId).toBe('skilld-root-2026-11') + }) + + it('verifies with the legacy root while no roots are served', () => { + expect(siteTrustedRoot({ ARTIFACT_TRUSTED_ROOTS_JSON: '', ARTIFACT_TRUSTED_ROOT_JSON: trustedRoot() }, now).rootKeyId) + .toBe('skilld-root-2026') + }) +}) diff --git a/worker-configuration.d.ts b/worker-configuration.d.ts index 9f6ac6eb..4c2c4d5b 100644 --- a/worker-configuration.d.ts +++ b/worker-configuration.d.ts @@ -1,5 +1,5 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types --config=wrangler.jsonc --env-file=.dev.vars.example` (hash: c76e9e543390620faf57b5dc6f955317) +// Generated by Wrangler by running `wrangler types --config=wrangler.jsonc --env-file=.dev.vars.example` (hash: 06d06a392caa46bad36439b22a45b2d9) // Runtime types generated with workerd@1.20260828.1 2026-08-20 nodejs_compat interface __BaseEnv_Env { KV_CACHE: KVNamespace; @@ -52,6 +52,7 @@ interface __BaseEnv_Env { ARTIFACT_KEY_WRAP_KEY_SECONDARY: string; ARTIFACT_GRANT_IDEMPOTENCY_KEY: string; ARTIFACT_TRUSTED_ROOT_JSON: string; + ARTIFACT_TRUSTED_ROOTS_JSON: string; ANTHROPIC_API_KEY: string; VOYAGE_API_KEY: string; X_BEARER_KEY: string; @@ -69,7 +70,7 @@ type StringifyValues> = { [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; }; declare namespace NodeJS { - interface ProcessEnv extends StringifyValues> {} + interface ProcessEnv extends StringifyValues> {} } // Begin runtime types From 7d8da61d0bbd078a78afacf23bbfe8e3e5aaecc0 Mon Sep 17 00:00:00 2001 From: Harlan GitHub Agent Date: Wed, 18 Nov 2026 23:36:42 +1100 Subject: [PATCH 2/4] fix(artifacts): isolate roots and validate rollout coverage --- docs/runbooks/signing-key-rotation.md | 363 +++++++----------- .../server/utils/trusted-root.ts | 38 +- scripts/lib/trusted-root-ceremony.ts | 20 +- scripts/trusted-root.ts | 14 +- test/unit/trusted-root-ceremony.test.ts | 56 ++- test/unit/trusted-root.test.ts | 62 ++- 6 files changed, 312 insertions(+), 241 deletions(-) diff --git a/docs/runbooks/signing-key-rotation.md b/docs/runbooks/signing-key-rotation.md index b3352bad..50acf072 100644 --- a/docs/runbooks/signing-key-rotation.md +++ b/docs/runbooks/signing-key-rotation.md @@ -1,314 +1,231 @@ # Signing key rotation -Every Artifact attestation carries an Ed25519 signature from the Artifact signer. -Each signing key has a validity window. -When the last usable window closes, the signer refuses to sign and the site stops trusting stored attestations. -After that, every `skilld run` fails. - +Rotate the Artifact signing key before its validity window closes. The key `skilld-production-2026-08` closes at `2026-11-20T00:00:00.000Z`. -This runbook replaces it with `skilld-production-2026-11` and keeps both keys trusted during an overlap. -The daily check-in result `skilld.signing-key` warns 30 days before the last window closes. +This rotation adds `skilld-production-2026-11`, with both keys trusted during the overlap. +The `skilld.signing-key` check-in warns 30 days before the last window closes. ## Root keys -The private key for the first root, `skilld-root-2026`, was lost in November 2026. -CLI releases 3.0.0 to 3.6.9 pin that root and read it from `/api/v1/trusted-root`, so no new signing key can reach them. +The private key for `skilld-root-2026` was lost in November 2026. +Do not use it for this ceremony. +Preserve `ARTIFACT_TRUSTED_ROOT_JSON` unchanged for `/api/v1/trusted-root`. +CLI releases 3.0.0 through 3.6.9 pin that root and cannot trust the new signing key. +Those users must upgrade to a release carrying the new pins before the signer switches keys. +Even without a switch, their old key expires on November 20. -From 3.7.0, each CLI pins a primary and a backup root and fetches each one from `/api/v1/trusted-roots/{rootKeyId}`. -The site serves those roots from the `ARTIFACT_TRUSTED_ROOTS_JSON` secret, a JSON array. -The first root in the array lists every signing key the site accepts. +The CLI 3.7.0 rollout pins these two roots independently: -| Root key | Pinned by | Where the private key lives | +| Root key | Selection | Private key escrow | | --- | --- | --- | -| `skilld-root-2026-11` | 3.7.0 and later, first | Harlan's password manager, and an offline USB stick | -| `skilld-root-backup-2026-11` | 3.7.0 and later, if the primary root is not served | Harlan's password manager, and a second offline USB stick | - -Before every ceremony, restore each root key you need from its copy and check it with `verify --signing-key`. -If both copies of a root key are gone, serve the other root. If both roots are gone, a new root needs a CLI release. +| `skilld-root-2026-11` | Primary | Harlan's password manager and an offline USB stick | +| `skilld-root-backup-2026-11` | Backup when the primary is absent | Harlan's password manager and a second offline USB stick | -### Start a new root +Confirm that the released CLI contains both exact public keys before activation. +A matching root ID alone does not establish a pin. +Never generate replacement root keys for IDs already pinned by a released CLI. +If one root key is lost, serve the other root. If both are lost, release new CLI pins. -`create-root` signs the first signing key under a new root key. `add-key` signs the rest. - -```sh -pnpm exec tsx scripts/trusted-root.ts signing-key --key-id skilld-root-2026-11 --out "$KEYS" -pnpm exec tsx scripts/trusted-root.ts create-root \ - --root-key-id skilld-root-2026-11 \ - --root-key "$KEYS/skilld-root-2026-11.pkcs8" \ - --key-id skilld-production-2026-08 \ - --public-key-file "$KEYS/skilld-production-2026-08.pub" \ - --not-before 2026-08-20T00:00:00Z \ - --not-after 2026-11-20T00:00:00Z \ - --out "$KEYS/skilld-root-2026-11.json" -``` +`ARTIFACT_TRUSTED_ROOTS_JSON` holds a JSON array, primary first, backup second. +The site verifies attestations with the first entry, without automatic failover from an invalid entry. +Each `/api/v1/trusted-roots/{rootKeyId}` endpoint serves its own valid entry independently. +An invalid entry logs its array index without logging its contents. +Both roots must contain identical signing key IDs, public keys, statuses, algorithms, and validity windows. +Their root public keys, statements, and root signatures differ by design. ## How signing works The site stages an attestation statement for a Resolution. -The signer Worker `workers/artifact-signer` loads that statement from D1, checks the R2 bytes, and signs a digest of the statement. +The signer Worker checks its D1 state and R2 bytes, then signs a digest of the statement. +It signs only a Resolution in `signing` state with fresh check results. -The signer has two key slots. Each slot is three vars in `workers/artifact-signer/wrangler.jsonc` and one secret. +The signer has two slots in `workers/artifact-signer/wrangler.jsonc`: | Slot | Vars | Secret | | --- | --- | --- | | primary | `ARTIFACT_SIGNING_KEY_ID`, `ARTIFACT_SIGNING_KEY_NOT_BEFORE`, `ARTIFACT_SIGNING_KEY_NOT_AFTER` | `ARTIFACT_SIGNING_PRIVATE_KEY_PKCS8` | | secondary | `ARTIFACT_SIGNING_SECONDARY_KEY_ID`, `ARTIFACT_SIGNING_SECONDARY_KEY_NOT_BEFORE`, `ARTIFACT_SIGNING_SECONDARY_KEY_NOT_AFTER` | `ARTIFACT_SIGNING_SECONDARY_PRIVATE_KEY_PKCS8` | -A slot counts only when its vars name a key ID. -A secret with no vars signs nothing, so you can put a secret before the deploy that names it. -If a named slot has no valid secret, the signer refuses every request with `SIGNING_KEY_INVALID`. - -For each statement, the signer uses the newest key whose window holds both the statement's `createdAt` and the current time. -A Resolution created before a new window opens still gets the old key. - -The trusted root is the `ARTIFACT_TRUSTED_ROOT_JSON` secret on the public Worker. -It holds the root key ID, the root public key, and one entry per signing key. -Each entry carries a statement that the offline root key signed. -The site serves it at `/api/v1/trusted-root` with a five-minute cache. - -Each verifier applies these rules to a signing key: - -| Rule | Signer | Site | skilld CLI | -| --- | --- | --- | --- | -| The trusted root names the key with status `active` or `overlapping` | no | yes | yes | -| The root key signed the key entry | no | no | yes | -| The window holds the statement's `createdAt` | yes | yes | yes | -| The window holds the current time | yes | yes | no | - -The CLI fetches the trusted root on every run and keeps no copy. -It checks the root against a root key compiled into each release. -Every release from 3.0.0 through 3.6.4 carries the root key `skilld-root-2026` and no signing key. -A signing key rotation needs no CLI release. Only a root key change needs one. - -## What happens to stored Artifacts - -Once a key window closes, the site stops trusting every attestation that key signed. -The next request for that Skill commit misses the reuse check with `attestation-untrusted` and builds again. -The new build signs under the current key. -The bytes match, so the Artifact ID and the R2 object stay the same. Only a new attestation row is added. - -The signer cannot sign a stored statement again. It signs only a Resolution in `signing` state with fresh check results. -A rebuild is the only way to sign an Artifact again. - -The CLI keeps no attestation on disk. A lockfile names a commit, so `skilld install` resolves again and gets the new attestation. +A secret with no slot vars signs nothing. +If a named slot lacks a valid secret, every signing request fails with `SIGNING_KEY_INVALID`. +The signer selects the newest key covering both the statement's `createdAt` and the current time. +The site requires the same coverage and an `active` or `overlapping` status. +The CLI checks the statement's time and the root signature against its compiled pin. +The site parser checks statement consistency but does not verify root signatures. +The ceremony verification below therefore gates publication. -Private Artifacts follow the same path through `verifyArtifactAttestation`. +When a key expires or leaves the roots, stored attestations lose site trust. +The next request builds again and signs with the current key. +Matching bytes keep the Artifact ID and R2 object. A new attestation row records the signature. +Private Artifacts use the same attestation verification. ## Before you start -You need the offline root private key for `skilld-root-2026`, in PKCS8 PEM or base64url DER form. -Never copy it into the repository, [Cloudflare](https://cloudflare.com), or GitHub Actions. +Restore both new root private keys from escrow. +Keep them outside the repository, Cloudflare, and GitHub Actions. +Prepare a complete root configuration file for each new root as a local pin file. +Compare each file's `rootKeyId` and `rootPublicKey` with the reviewed CLI release's compiled pins. +Stop if either differs. The tool parses each pin file as a complete root configuration. +Do not obtain pins from the endpoint being tested. +Save them as `$KEYS/primary-pin.json` and `$KEYS/backup-pin.json`. -Work in a private directory outside the repository, for example on an encrypted volume. -Set `KEYS` to that directory. Run every command from the repository root. +Use a private directory on an encrypted volume. Run commands from the repository root: ```sh export KEYS=/path/to/private/dir ``` -`scripts/trusted-root.ts` runs the ceremony. It never prints a private key. -It writes new files with mode 600 and refuses to overwrite a file. - -## Timeline - -All times are UTC. Each date is the latest safe date. Earlier is better. - -| Step | Action | Latest safe date | -| --- | --- | --- | -| 1 | Deploy slot support | 2026-11-02 | -| 2 | Run the ceremony | 2026-11-06 | -| 3 | Put the new trusted root on the site | 2026-11-09 | -| 4 | Put the new private key in the free slot | 2026-11-09 | -| 5 | Name the new key in the signer vars | 2026-11-13 | -| 6 | Remove the old key from the trusted root | 2026-11-19 | -| 7 | Empty the old slot | after 2026-11-20 | - -Step 3 must reach production at least 10 minutes before step 5, so that cached roots expire. -If step 5 slips past 2026-11-13, a failed deploy has less than a week to recover. -If step 5 does not deploy before `2026-11-20T00:00:00.000Z`, every `skilld run` fails until it does. - -## 1. Deploy slot support - -Confirm that `workers/artifact-signer/src/slots.ts` exists on `main`. -Confirm that the last `Deploy to Cloudflare` run on `main` passed after that file arrived. +The ceremony tool writes new files without overwriting existing files. +Private key and root files use mode 600. +The commands below assume escrowed roots already contain the old signing key. +For initial activation, create those roots first with each escrowed private key: ```sh -git fetch origin main -git log -1 --format='%H %cs' origin/main -- workers/artifact-signer/src/slots.ts -gh run list --repo skilld-dev/skilld.dev --workflow deploy-cloudflare.yml --branch main --limit 3 +for ROOT in skilld-root-2026-11 skilld-root-backup-2026-11; do + pnpm exec tsx scripts/trusted-root.ts create-root \ + --root-key-id "$ROOT" --root-key "$KEYS/$ROOT.pkcs8" \ + --key-id skilld-production-2026-08 \ + --public-key-file "$KEYS/skilld-production-2026-08.pub" \ + --not-before 2026-08-20T00:00:00Z --not-after 2026-11-20T00:00:00Z \ + --out "$KEYS/$ROOT-before.json" +done ``` -## 2. Run the ceremony +Use the old public key and window from the preserved legacy root. +For later rotations, save both current endpoints as the `*-before.json` files instead. +Retain the exact previous array and its order as `$KEYS/roots-before.json` for rollback. +For initial activation, record that the array was absent instead. -Save the live root. It is the rollback value and the pin for the checks below. +## 1. Prepare and verify both roots -```sh -curl -fsS https://skilld.dev/api/v1/trusted-root | jq -c 'del(.fetchedAt)' > "$KEYS/root-before.json" -``` - -Generate the new signing key. +Generate one signing key, then sign the same entry under both root keys: ```sh pnpm exec tsx scripts/trusted-root.ts signing-key --key-id skilld-production-2026-11 --out "$KEYS" -``` - -Sign its statement with the root key. -Set `--not-before` to the ceremony day at 00:00. Set `--not-after` six months later. -A longer window means fewer ceremonies. A shorter one limits the damage of a leaked key. - -```sh -pnpm exec tsx scripts/trusted-root.ts add-key \ - --root "$KEYS/root-before.json" \ - --root-key /path/to/root-private-key \ - --key-id skilld-production-2026-11 \ - --public-key-file "$KEYS/skilld-production-2026-11.pub" \ - --not-before 2026-10-14T00:00:00Z \ - --not-after 2027-05-20T00:00:00Z \ - --status active \ - --out "$KEYS/root-next.json" -``` - -Use `active`. The verifiers treat `overlapping` the same way, and the status is part of the signed statement. - -Check the new root by the rules every released CLI applies, and check that the private key matches the entry: - -```sh +for ROOT in skilld-root-2026-11 skilld-root-backup-2026-11; do + pnpm exec tsx scripts/trusted-root.ts add-key \ + --root "$KEYS/$ROOT-before.json" --root-key "$KEYS/$ROOT.pkcs8" \ + --key-id skilld-production-2026-11 \ + --public-key-file "$KEYS/skilld-production-2026-11.pub" \ + --not-before 2026-11-18T00:00:00Z --not-after 2027-05-20T00:00:00Z \ + --status active --out "$KEYS/$ROOT-next.json" +done pnpm exec tsx scripts/trusted-root.ts verify \ - --root "$KEYS/root-next.json" \ - --pin "$KEYS/root-before.json" \ - --key-id skilld-production-2026-11 \ - --signing-key "$KEYS/skilld-production-2026-11.pkcs8" + --root "$KEYS/skilld-root-2026-11-next.json" --pin "$KEYS/primary-pin.json" \ + --peer-root "$KEYS/skilld-root-backup-2026-11-next.json" --peer-pin "$KEYS/backup-pin.json" \ + --key-id skilld-production-2026-11 --signing-key "$KEYS/skilld-production-2026-11.pkcs8" +jq -s '.' "$KEYS/skilld-root-2026-11-next.json" "$KEYS/skilld-root-backup-2026-11-next.json" > "$KEYS/roots-next.json" ``` -Stop unless it prints `OK`. - -## 3. Put the new trusted root on the site - -```sh -pnpm exec wrangler secret put ARTIFACT_TRUSTED_ROOT_JSON --config wrangler.jsonc < "$KEYS/root-next.json" -``` +Stop unless verification prints `OK`. +It checks both pins, both sets of root signatures, matching signer coverage, and the new signing private key. +If the ceremony date changes, use its UTC midnight for `notBefore` in both roots and signer vars. -The put deploys a new public Worker version at once. +## 2. Publish and verify both endpoints -Verify the live root: +Production deployment uses `.github/workflows/deploy-cloudflare.yml` only. +Execute secret uploads as approved configuration steps in that workflow, never as a local deployment. +The upload step consumes the verified array, which contains public data only: ```sh -pnpm exec tsx scripts/trusted-root.ts verify --root https://skilld.dev/api/v1/trusted-root --pin "$KEYS/root-before.json" +pnpm exec wrangler secret put ARTIFACT_TRUSTED_ROOTS_JSON --config wrangler.jsonc < "$KEYS/roots-next.json" ``` -It must list both keys and print `OK`. - -Run the oldest and newest released CLIs. Each run checks every root signature as shipped: +Do not upload either new root to `ARTIFACT_TRUSTED_ROOT_JSON`. +After the route deployment, verify both live endpoints against their own independent pins: ```sh -npx -y skilld@3.0.0 run skilld-dev/skills/find-skill > /dev/null && echo ok -npx -y skilld@latest run skilld-dev/skills/find-skill > /dev/null && echo ok +pnpm exec tsx scripts/trusted-root.ts verify \ + --root https://skilld.dev/api/v1/trusted-roots/skilld-root-2026-11 --pin "$KEYS/primary-pin.json" \ + --peer-root https://skilld.dev/api/v1/trusted-roots/skilld-root-backup-2026-11 --peer-pin "$KEYS/backup-pin.json" ``` -If either run fails with a `TRUSTED_ROOT_` code, roll back this step at once. +Stop unless it prints `OK` and lists both signing keys. +Wait at least 10 minutes after publication before switching the signer, so five-minute endpoint caches expire. +Confirm a released CLI with both new pins can run a Skill before proceeding. +Do not use an old CLI's success under the old key as proof of new root support. -## 4. Put the new private key in the free slot +## 3. Activate the signer -The free slot is the one whose vars name no key. For this rotation it is the secondary slot. +Confirm slot support passed the production deploy workflow. +The free slot has no key ID vars. This rotation uses the secondary slot. +Upload its signing secret through the approved deploy workflow before adding its vars: ```sh pnpm --filter @skilld/artifact-signer-worker exec wrangler secret put ARTIFACT_SIGNING_SECONDARY_PRIVATE_KEY_PKCS8 --config wrangler.jsonc < "$KEYS/skilld-production-2026-11.pkcs8" -pnpm --filter @skilld/artifact-signer-worker exec wrangler secret list --config wrangler.jsonc ``` -The list must name `ARTIFACT_SIGNING_SECONDARY_PRIVATE_KEY_PKCS8`. -The signer still signs with the old key, because no vars name the secondary slot. - -## 5. Name the new key in the signer vars - -Open a pull request that adds these vars to `workers/artifact-signer/wrangler.jsonc`. -Use the same window as the trusted root entry, or a window inside it. +Open a pull request adding these vars to `workers/artifact-signer/wrangler.jsonc`: ```jsonc { "vars": { "ARTIFACT_SIGNING_SECONDARY_KEY_ID": "skilld-production-2026-11", - "ARTIFACT_SIGNING_SECONDARY_KEY_NOT_BEFORE": "2026-10-14T00:00:00.000Z", + "ARTIFACT_SIGNING_SECONDARY_KEY_NOT_BEFORE": "2026-11-18T00:00:00.000Z", "ARTIFACT_SIGNING_SECONDARY_KEY_NOT_AFTER": "2027-05-20T00:00:00.000Z" } } ``` -Regenerate the signer types in the same pull request: - -```sh -pnpm --filter @skilld/artifact-signer-worker types -``` - -Before you merge, confirm step 3 is live and step 4 lists the secret. -The merge runs `Deploy to Cloudflare`. It deploys the signer first. -From that deploy, each new build signs with `skilld-production-2026-11`. - -Count attestations per key. New builds must show the new key ID: +Run `pnpm --filter @skilld/artifact-signer-worker types` in that pull request. +Before merging, confirm both live root checks passed and the secondary secret exists. +The deploy workflow deploys the signer first. New statements then use the new key. +Inspect new attestation key IDs with a read-only D1 query: ```sh pnpm exec wrangler d1 execute DB --remote --config wrangler.jsonc --command \ "SELECT json_extract(attestation_json, '$.signature.keyId') AS key_id, COUNT(*) AS attestations, datetime(MAX(created_at), 'unixepoch') AS newest FROM artifact_attestations GROUP BY key_id" ``` -Check [Sentry](https://sentry.io) for `Artifact signer returned an invalid signature` and the signer logs for `SIGNING_KEY_INVALID`. -Either one means the signer and the trusted root disagree. Roll back this step. +Check signer logs for `SIGNING_KEY_INVALID` and Sentry for `Artifact signer returned an invalid signature`. +Either error requires signer rollback while the old window remains open. -## 6. Remove the old key from the trusted root +## 4. Remove the old signing key -Do this at a time you can watch, at least one day before the old window closes. -Every stored Artifact that the old key signed then builds again on its next request. -The same rebuilds happen at `2026-11-20T00:00:00.000Z` anyway. Before that time, you can still roll back. - -Removal needs no root key. +After confirming new signatures work, remove the old entry from both new roots: ```sh -pnpm exec tsx scripts/trusted-root.ts remove-key --root "$KEYS/root-next.json" --key-id skilld-production-2026-08 --out "$KEYS/root-after.json" -pnpm exec tsx scripts/trusted-root.ts verify --root "$KEYS/root-after.json" --pin "$KEYS/root-before.json" -pnpm exec wrangler secret put ARTIFACT_TRUSTED_ROOT_JSON --config wrangler.jsonc < "$KEYS/root-after.json" -pnpm exec tsx scripts/trusted-root.ts verify --root https://skilld.dev/api/v1/trusted-root --pin "$KEYS/root-before.json" +for ROOT in skilld-root-2026-11 skilld-root-backup-2026-11; do + pnpm exec tsx scripts/trusted-root.ts remove-key \ + --root "$KEYS/$ROOT-next.json" --key-id skilld-production-2026-08 --out "$KEYS/$ROOT-after.json" +done +pnpm exec tsx scripts/trusted-root.ts verify \ + --root "$KEYS/skilld-root-2026-11-after.json" --pin "$KEYS/primary-pin.json" \ + --peer-root "$KEYS/skilld-root-backup-2026-11-after.json" --peer-pin "$KEYS/backup-pin.json" +jq -s '.' "$KEYS/skilld-root-2026-11-after.json" "$KEYS/skilld-root-backup-2026-11-after.json" > "$KEYS/roots-after.json" ``` -Watch the build queue, failed jobs, and [GitHub](https://github.com) read quota in the daily check-in for one hour. -A CLI that held a Resolution across the change fails once with `SIGNING_KEY_UNKNOWN`. Its next run passes. +Publish `roots-after.json` to `ARTIFACT_TRUSTED_ROOTS_JSON` through the same workflow configuration step. +Repeat the live endpoint verification from step 2. +Preserve the legacy secret. Removing its old key cannot make old CLIs trust the new key. +Watch the build queue and failed jobs for one hour as stored Artifacts rebuild. +A Resolution held across removal can fail once with `SIGNING_KEY_UNKNOWN`; its next run resolves again. -## 7. Empty the old slot +After November 20, remove the three primary slot vars through a pull request and regenerate signer types. +After that deployment, delete `ARTIFACT_SIGNING_PRIVATE_KEY_PKCS8` through the approved configuration workflow. +Never delete a secret while vars name its slot. +Store the new signing private key offline, or delete the local copy. -After `2026-11-20T00:00:00.000Z`, open a pull request that removes the three primary slot vars from `workers/artifact-signer/wrangler.jsonc`. -Regenerate the signer types in it. -After its deploy, delete the old secret: +## Roll back -```sh -pnpm --filter @skilld/artifact-signer-worker exec wrangler secret delete ARTIFACT_SIGNING_PRIVATE_KEY_PKCS8 --config wrangler.jsonc -``` +| Change | Recovery | Limit | +| --- | --- | --- | +| New array, before signer activation | Restore the previous array and order. For initial activation, remove the array to restore legacy site verification. | Before any new-key attestations exist | +| Secondary secret, before slot vars | Delete the unused secondary secret through the configuration workflow. | Before signer activation | +| Signer activation | Revert the vars pull request. Keep the new signing key in both roots because it signed live attestations. | Old key window closes November 20 | +| Old key removal | Republish `roots-next.json` to `ARTIFACT_TRUSTED_ROOTS_JSON`, then verify both endpoints against their pins. | Old signatures remain usable only before November 20 | -Never delete a secret while vars still name its slot. The signer then refuses every request. +Do not restore legacy-only verification after the new key signs live attestations. +After the old window closes, recover forward with a valid new signing key in both roots and the signer. +All recovery deployments use the production workflow. Never overwrite the legacy secret with a new root. -Store the new private key file offline, or delete it. Cloudflare holds the only copy the signer needs. +For root failover, validate matching coverage first, then serve only the backup root in the array. +Verify its endpoint against the backup pin. Removing the primary lets clients select the backup. +The backup becomes the site's first entry. Do not leave an invalid primary in that position. ## Next rotation -The next rotation uses the slot this one emptied, so the slots alternate. -Repeat steps 2 to 7 with the slot names swapped. -`skilld.signing-key` warns 30 days before `skilld-production-2026-11` closes. - -## Roll back - -| Step | Roll back | Valid until | -| --- | --- | --- | -| 3 | Put `$KEYS/root-before.json` back as `ARTIFACT_TRUSTED_ROOT_JSON`. | step 5 deploys | -| 4 | Delete `ARTIFACT_SIGNING_SECONDARY_PRIVATE_KEY_PKCS8`. | step 5 deploys | -| 5 | Revert the vars pull request. The signer signs with the old key again. Keep the new key in the trusted root, because it signed live attestations. | `2026-11-20T00:00:00.000Z` | -| 6 | Put `$KEYS/root-next.json` back as `ARTIFACT_TRUSTED_ROOT_JSON`. | `2026-11-20T00:00:00.000Z` | - -Never remove a key from the trusted root while the signer still names it. -The site then rejects every new signature, and every build fails. - -## Rules for every released CLI - -- Never change the root key without a CLI release. Each release compiles in the root key and refuses any other root. -- Never add a field to a trusted root key entry or statement. The CLI rejects unknown fields there. -- Use only the statuses `active`, `overlapping`, `retired`, and `revoked`. -- A status change needs a new root signature. Remove a key instead of retiring it. -- Run `scripts/trusted-root.ts verify` before every `wrangler secret put ARTIFACT_TRUSTED_ROOT_JSON`. - The site never checks a root signature. A bad one stops every CLI with an upgrade message that no upgrade fixes. +Alternate signer slots. Repeat the ceremony for both roots and compare coverage before every publication. +Never add fields to key entries or statements, because released CLIs reject unknown fields. +Use only `active`, `overlapping`, `retired`, and `revoked` statuses. +A status change requires a new root signature. Removal needs no root private key. diff --git a/layers/artifact-delivery/server/utils/trusted-root.ts b/layers/artifact-delivery/server/utils/trusted-root.ts index 5f9f2378..c9c0ac9b 100644 --- a/layers/artifact-delivery/server/utils/trusted-root.ts +++ b/layers/artifact-delivery/server/utils/trusted-root.ts @@ -27,19 +27,34 @@ export function parseTrustedRoot(value: string, now: number) { * `skilld-root-2026`, whose key was lost, and read `/api/v1/trusted-root`. */ export function parseTrustedRoots(value: string | undefined, now: number): TrustedRoot[] { + return readTrustedRoots(value, now).flatMap(result => result._tag === 'valid' ? [result.root] : []) +} + +type RootResult = { _tag: 'valid', root: TrustedRoot } | { _tag: 'invalid' } + +function readTrustedRoots(value: string | undefined, now: number): RootResult[] { if (!value?.trim()) return [] const configs: unknown = JSON.parse(value) if (!Array.isArray(configs) || configs.length === 0) throw new Error('Served trusted roots must be a non-empty JSON array') - const roots = configs.map(config => parseTrustedRoot(JSON.stringify(config), now)) - const seen = new Set() - for (const root of roots) { - if (seen.has(root.rootKeyId)) - throw new Error(`Trusted root ${root.rootKeyId} is served twice`) - seen.add(root.rootKeyId) - } - return roots + const ids = configs.map((config: unknown) => { + if (typeof config === 'object' && config !== null && 'rootKeyId' in config) + return config.rootKeyId + return undefined + }) + return configs.map((config: unknown, index): RootResult => { + try { + if (ids[index] !== undefined && ids.indexOf(ids[index]) !== ids.lastIndexOf(ids[index])) + throw new Error('Duplicate root ID') + return { _tag: 'valid', root: parseTrustedRoot(JSON.stringify(config), now) } + } + catch { + // Config can contain secrets or untrusted text. Report only its array position. + console.error(`Rejected trusted root at array index ${index}: invalid or duplicate entry`) + return { _tag: 'invalid' } + } + }) } interface TrustedRootEnv { @@ -53,7 +68,12 @@ interface TrustedRootEnv { * the legacy root. */ export function siteTrustedRoot(env: TrustedRootEnv, now: number): TrustedRoot { - return parseTrustedRoots(env.ARTIFACT_TRUSTED_ROOTS_JSON, now)[0] ?? parseTrustedRoot(env.ARTIFACT_TRUSTED_ROOT_JSON, now) + const selected = readTrustedRoots(env.ARTIFACT_TRUSTED_ROOTS_JSON, now)[0] + if (!selected) + return parseTrustedRoot(env.ARTIFACT_TRUSTED_ROOT_JSON, now) + if (selected._tag === 'invalid') + throw new Error('The selected site trusted root is invalid') + return selected.root } function decodeCanonicalBase64Url(value: string): Uint8Array | null { diff --git a/scripts/lib/trusted-root-ceremony.ts b/scripts/lib/trusted-root-ceremony.ts index feec876d..da6b8eeb 100644 --- a/scripts/lib/trusted-root-ceremony.ts +++ b/scripts/lib/trusted-root-ceremony.ts @@ -136,8 +136,26 @@ export function removeTrustedKey(root: TrustedRootConfig, keyId: string): Truste * Checks a root by the rules every released skilld CLI applies, then by the * site's own parser. Each failed rule is one problem. */ -export function verifyTrustedRoot(root: TrustedRootConfig, pin: RootPin, now: number): VerifyResult { +export function verifyTrustedRoot( + root: TrustedRootConfig, + pin: RootPin, + now: number, + peers: { root: TrustedRootConfig, pin: RootPin }[] = [], +): VerifyResult { const problems: string[] = [] + const coverage = (config: TrustedRootConfig) => canonicalJson(config.keys.map(({ statement: _statement, rootSignature: _signature, ...key }) => key) + .sort((a, b) => a.keyId.localeCompare(b.keyId))) + const seenRoots = new Set([root.rootKeyId]) + for (const peer of peers) { + if (seenRoots.has(peer.root.rootKeyId)) + problems.push('A rollout root ID appears twice.') + seenRoots.add(peer.root.rootKeyId) + const result = verifyTrustedRoot(peer.root, peer.pin, now) + if (result._tag === 'invalid') + problems.push(...result.problems) + if (coverage(root) !== coverage(peer.root)) + problems.push('Rollout roots have different signing key coverage.') + } if (root.rootKeyId !== pin.rootKeyId || root.rootPublicKey !== pin.rootPublicKey) problems.push('The root key differs from the pin the released CLIs carry.') const rootKey = attempt(() => decodePublicKey(root.rootPublicKey)) diff --git a/scripts/trusted-root.ts b/scripts/trusted-root.ts index 1caef06e..8afc0d87 100644 --- a/scripts/trusted-root.ts +++ b/scripts/trusted-root.ts @@ -33,8 +33,10 @@ const USAGE = `Usage: pnpm exec tsx scripts/trusted-root.ts [options] remove-key --root --key-id --out Write the root without that key. Removal needs no root key. verify --root [--pin ] [--key-id --signing-key ] + [--peer-root --peer-pin ] Check the root as every released skilld CLI does. --pin defaults to ${LIVE_ROOT}. - With --signing-key, also check the private key matches that key ID.` + With --signing-key, also check the private key matches that key ID. + With --peer-root and --peer-pin, verify both roots and require matching signing key coverage.` const { positionals, values } = parseArgs({ allowPositionals: true, @@ -44,6 +46,8 @@ const { positionals, values } = parseArgs({ 'not-before': { type: 'string' }, 'out': { type: 'string' }, 'pin': { type: 'string' }, + 'peer-root': { type: 'string' }, + 'peer-pin': { type: 'string' }, 'public-key-file': { type: 'string' }, 'root': { type: 'string' }, 'root-key': { type: 'string' }, @@ -135,7 +139,13 @@ async function main(command: string | undefined): Promise { const root = await readRoot(required('root')) const pinRoot = await readRoot(values.pin ?? LIVE_ROOT) const pin: RootPin = { rootKeyId: pinRoot.rootKeyId, rootPublicKey: pinRoot.rootPublicKey } - const result = verifyTrustedRoot(root, pin, Math.floor(Date.now() / 1000)) + const peers = [] + if (values['peer-root'] || values['peer-pin']) { + const peerRoot = await readRoot(required('peer-root')) + const peerPin = await readRoot(required('peer-pin')) + peers.push({ root: peerRoot, pin: peerPin }) + } + const result = verifyTrustedRoot(root, pin, Math.floor(Date.now() / 1000), peers) const problems = result._tag === 'invalid' ? [...result.problems] : [] if (values['signing-key']) { const keyId = required('key-id') diff --git a/test/unit/trusted-root-ceremony.test.ts b/test/unit/trusted-root-ceremony.test.ts index 2b31ac09..b9f8d887 100644 --- a/test/unit/trusted-root-ceremony.test.ts +++ b/test/unit/trusted-root-ceremony.test.ts @@ -1,7 +1,8 @@ import type { TrustedRootConfig } from '../../scripts/lib/trusted-root-ceremony' -import { generateKeyPairSync } from 'node:crypto' +import { generateKeyPairSync, sign } from 'node:crypto' import { describe, expect, it } from 'vitest' -import { parseTrustedRoot } from '../../layers/artifact-delivery/server/utils/trusted-root' +import { completeAttestation, createAttestationSignaturePayload, createAttestationStatement, encodeAttestationStatement, verifyArtifactAttestation } from '../../layers/artifact-delivery/server/utils/attestation' +import { parseTrustedRoot, siteTrustedRoot } from '../../layers/artifact-delivery/server/utils/trusted-root' import { addTrustedKey, createTrustedRoot, @@ -131,6 +132,57 @@ describe('trusted root ceremony', () => { expect(signingKeyMatches(current, 'skilld-production-2026-08', readPrivateKey(oldKey.privateKeyPkcs8))).toBe(true) expect(signingKeyMatches(current, 'skilld-production-2026-08', readPrivateKey(newKey.privateKeyPkcs8))).toBe(false) }) + + it.each(['publicKey', 'status', 'notBefore', 'notAfter', 'keyId'] as const)('rejects rollout roots with different %s coverage', (field) => { + const { current } = ceremony() + const { privateKey } = generateKeyPairSync('ed25519') + const original = current.keys[0]! + const changes = { + publicKey: generateSigningKey().publicKey, + status: 'overlapping' as const, + notBefore: '2026-08-21T00:00:00.000Z', + notAfter: '2026-11-19T00:00:00.000Z', + keyId: 'other-key', + } + const backup = createTrustedRoot('backup', privateKey, { ...original, status: 'active', [field]: changes[field] }) + expect(verifyTrustedRoot(backup, backup, NOW)).toEqual({ _tag: 'valid' }) + expect(verifyTrustedRoot(current, current, NOW, [{ root: backup, pin: backup }])._tag).toBe('invalid') + }) + + it('verifies the same attestation after publishing matching roots and removing the primary', async () => { + const { current, oldKey } = ceremony() + const { privateKey } = generateKeyPairSync('ed25519') + const backup = createTrustedRoot('backup', privateKey, { ...current.keys[0]!, status: 'active' }) + expect(verifyTrustedRoot(current, current, NOW, [{ root: backup, pin: backup }])).toEqual({ _tag: 'valid' }) + const statement = encodeAttestationStatement(createAttestationStatement({ + artifactId: `sha256:${'a'.repeat(64)}`, + createdAt: new Date(NOW * 1000).toISOString(), + source: { + provider: 'github', + repositoryId: 1, + owner: 'skilld-dev', + repository: 'skills', + visibility: 'public', + commitSha: 'a'.repeat(40), + treeSha: 'b'.repeat(40), + skillPath: 'skills/demo', + }, + contentSha256: 'a'.repeat(64), + contentBytes: 1, + files: [{ path: 'SKILL.md', mode: 420, size: 1, sha256: 'b'.repeat(64) }], + checkResults: [{ name: 'path-policy', version: '1', outcome: 'pass', required: true }], + })) + const payload = await createAttestationSignaturePayload(new TextEncoder().encode(statement)) + const attestation = completeAttestation(statement, { + algorithm: 'Ed25519', + keyId: current.keys[0]!.keyId, + value: Buffer.from(sign(null, payload, readPrivateKey(oldKey.privateKeyPkcs8))).toString('base64url'), + }) + for (const roots of [[current, backup], [backup]]) { + const selected = siteTrustedRoot({ ARTIFACT_TRUSTED_ROOTS_JSON: JSON.stringify(roots), ARTIFACT_TRUSTED_ROOT_JSON: '' }, NOW) + expect(await verifyArtifactAttestation(attestation, selected, NOW)).toBe(true) + } + }) }) // The root key for `skilld-root-2026` was lost, so the next root starts from a diff --git a/test/unit/trusted-root.test.ts b/test/unit/trusted-root.test.ts index 4e41cf72..254e6ff6 100644 --- a/test/unit/trusted-root.test.ts +++ b/test/unit/trusted-root.test.ts @@ -1,10 +1,19 @@ import type { TrustedRootConfig } from '../../scripts/lib/trusted-root-ceremony' import { generateKeyPairSync } from 'node:crypto' -import { describe, expect, it } from 'vitest' +import { createApp, createError, createRouter, defineEventHandler, toWebHandler } from 'h3' +import { afterEach, describe, expect, it, vi } from 'vitest' import { bytesToBase64Url } from '../../layers/artifact-delivery/server/utils/encoding' import { parseTrustedRoot, parseTrustedRoots, siteTrustedRoot } from '../../layers/artifact-delivery/server/utils/trusted-root' import { createTrustedRoot, generateSigningKey } from '../../scripts/lib/trusted-root-ceremony' +vi.mock('../../shared/server/session-access', () => ({ readUserSession: async () => null })) +vi.mock('../../layers/identity/server/utils/bearer', () => ({ resolveBearerSession: async () => null })) + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + const statement = { version: 1, rootKeyId: 'skilld-root-2026', @@ -69,15 +78,60 @@ describe('trusted roots by id', () => { }) } + it.each([0, 1])('serves a healthy endpoint when root at index %i is malformed', async (invalidIndex) => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.stubGlobal('defineEventHandler', defineEventHandler) + vi.stubGlobal('createError', createError) + const { default: handler } = await import('../../layers/artifact-delivery/server/api/v1/trusted-roots/[rootKeyId].get') + const configs = [root('primary'), root('backup')] + configs[invalidIndex] = { ...configs[invalidIndex]!, keys: [] } + const healthy = configs[1 - invalidIndex]! + const app = createApp().use(defineEventHandler((event) => { + event.context.platform = { env: { ARTIFACT_TRUSTED_ROOTS_JSON: JSON.stringify(configs) } } as never + })) + app.use(createRouter().get('/api/v1/trusted-roots/:rootKeyId', handler)) + const response = await toWebHandler(app)(new Request(`http://localhost/api/v1/trusted-roots/${healthy.rootKeyId}`)) + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject(healthy) + }) + it('reads every served root with its root key id', () => { const roots = parseTrustedRoots(JSON.stringify([root('skilld-root-2026-11'), root('skilld-root-backup-2026-11')]), now) expect(roots.map(served => served.rootKeyId)).toEqual(['skilld-root-2026-11', 'skilld-root-backup-2026-11']) }) - it('rejects two roots with the same root key id', () => { - expect(() => parseTrustedRoots(JSON.stringify([root('skilld-root-2026-11'), root('skilld-root-2026-11')]), now)) - .toThrow('skilld-root-2026-11') + it('rejects ambiguous ids without disabling unrelated roots', () => { + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + const backup = root('backup') + expect(parseTrustedRoots(JSON.stringify([root('primary'), root('primary'), backup]), now)) + .toEqual([parseTrustedRoot(JSON.stringify(backup), now)]) + report.mockRestore() + }) + + it('keeps site verification and the primary root available with a malformed backup', () => { + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + const primary = root('primary') + const env = { + ARTIFACT_TRUSTED_ROOTS_JSON: JSON.stringify([primary, { ...root('backup'), keys: [] }]), + ARTIFACT_TRUSTED_ROOT_JSON: trustedRoot(), + } + expect(siteTrustedRoot(env, now)).toEqual(parseTrustedRoot(JSON.stringify(primary), now)) + expect(parseTrustedRoots(env.ARTIFACT_TRUSTED_ROOTS_JSON, now)).toEqual([siteTrustedRoot(env, now)]) + expect(report).toHaveBeenCalled() + report.mockRestore() + }) + + it('serves the backup with a malformed primary but keeps site verification fail-closed', () => { + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + const backup = root('backup') + const env = { + ARTIFACT_TRUSTED_ROOTS_JSON: JSON.stringify([{ ...root('primary'), keys: [] }, backup]), + ARTIFACT_TRUSTED_ROOT_JSON: trustedRoot(), + } + expect(parseTrustedRoots(env.ARTIFACT_TRUSTED_ROOTS_JSON, now)).toEqual([parseTrustedRoot(JSON.stringify(backup), now)]) + expect(() => siteTrustedRoot(env, now)).toThrow() + report.mockRestore() }) it('verifies attestations with the first served root', () => { From c291127d6e4cc0228938bc7a1036eaee08ba4bc8 Mon Sep 17 00:00:00 2001 From: Harlan GitHub Agent Date: Wed, 18 Nov 2026 23:51:22 +1100 Subject: [PATCH 3/4] fix(artifacts): isolate root collisions and stage rotation secrets --- .github/workflows/deploy-cloudflare.yml | 61 ++++++++ docs/runbooks/signing-key-rotation.md | 60 ++++++-- .../server/utils/trusted-root.ts | 22 +-- test/unit/signing-configuration.test.ts | 135 ++++++++++++++++++ test/unit/trusted-root.test.ts | 41 ++++++ 5 files changed, 297 insertions(+), 22 deletions(-) create mode 100644 test/unit/signing-configuration.test.ts diff --git a/.github/workflows/deploy-cloudflare.yml b/.github/workflows/deploy-cloudflare.yml index 55bcc9cc..d32bba16 100644 --- a/.github/workflows/deploy-cloudflare.yml +++ b/.github/workflows/deploy-cloudflare.yml @@ -15,6 +15,14 @@ on: description: Rotate the registry GitHub fallback token type: boolean default: false + publish_artifact_roots: + description: Publish the verified Artifact trusted roots + type: boolean + default: false + stage_artifact_secondary: + description: Stage the Artifact signing secret in the unused secondary slot + type: boolean + default: false permissions: contents: read @@ -128,6 +136,59 @@ jobs: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + - name: Stage Artifact signing configuration + if: github.event_name == 'workflow_dispatch' && (inputs.publish_artifact_roots || inputs.stage_artifact_secondary) + shell: bash + run: | + set -euo pipefail + umask 077 + staging=$(mktemp -d "$RUNNER_TEMP/artifact-rotation.XXXXXX") + trap 'rm -rf "$staging"' EXIT + if [ "$STAGE_ARTIFACT_SECONDARY" = true ]; then + jq -e '(.vars.ARTIFACT_SIGNING_SECONDARY_KEY_ID // "") == ""' "$ARTIFACT_SIGNER_CONFIG" > /dev/null + test -n "$ARTIFACT_ROTATION_SECONDARY_PKCS8" + test -n "$ARTIFACT_ROTATION_KEY_ID" + fi + printf '%s' "$ARTIFACT_ROTATION_ROOTS_JSON" > "$staging/roots.json" + jq -e 'type == "array" and length == 2' "$staging/roots.json" > /dev/null + jq '.[0]' "$staging/roots.json" > "$staging/primary.json" + jq '.[1]' "$staging/roots.json" > "$staging/backup.json" + printf '%s' "$ARTIFACT_ROTATION_PRIMARY_PIN_JSON" > "$staging/primary-pin.json" + printf '%s' "$ARTIFACT_ROTATION_BACKUP_PIN_JSON" > "$staging/backup-pin.json" + verify_args=( + --root "$staging/primary.json" --pin "$staging/primary-pin.json" + --peer-root "$staging/backup.json" --peer-pin "$staging/backup-pin.json" + ) + if [ "$STAGE_ARTIFACT_SECONDARY" = true ]; then + printf '%s' "$ARTIFACT_ROTATION_SECONDARY_PKCS8" > "$staging/secondary.pkcs8" + verify_args+=(--key-id "$ARTIFACT_ROTATION_KEY_ID" --signing-key "$staging/secondary.pkcs8") + fi + # Verification can include untrusted configuration in diagnostics. + # Keep it private and print only the result. + if ! pnpm exec tsx scripts/trusted-root.ts verify "${verify_args[@]}" > "$staging/verify.log" 2>&1; then + echo 'Artifact signing configuration verification failed.' >&2 + exit 1 + fi + if [ "$PUBLISH_ARTIFACT_ROOTS" = true ]; then + pnpm exec wrangler secret put ARTIFACT_TRUSTED_ROOTS_JSON --config wrangler.jsonc < "$staging/roots.json" + echo 'Published the verified Artifact trusted roots.' >> "$GITHUB_STEP_SUMMARY" + fi + if [ "$STAGE_ARTIFACT_SECONDARY" = true ]; then + pnpm --filter @skilld/artifact-signer-worker exec wrangler secret put ARTIFACT_SIGNING_SECONDARY_PRIVATE_KEY_PKCS8 --config wrangler.jsonc < "$staging/secondary.pkcs8" + echo 'Staged the secondary Artifact signing secret.' >> "$GITHUB_STEP_SUMMARY" + fi + env: + PUBLISH_ARTIFACT_ROOTS: ${{ inputs.publish_artifact_roots }} + STAGE_ARTIFACT_SECONDARY: ${{ inputs.stage_artifact_secondary }} + ARTIFACT_SIGNER_CONFIG: workers/artifact-signer/wrangler.jsonc + ARTIFACT_ROTATION_ROOTS_JSON: ${{ secrets.ARTIFACT_ROTATION_ROOTS_JSON }} + ARTIFACT_ROTATION_PRIMARY_PIN_JSON: ${{ secrets.ARTIFACT_ROTATION_PRIMARY_PIN_JSON }} + ARTIFACT_ROTATION_BACKUP_PIN_JSON: ${{ secrets.ARTIFACT_ROTATION_BACKUP_PIN_JSON }} + ARTIFACT_ROTATION_KEY_ID: ${{ vars.ARTIFACT_ROTATION_KEY_ID }} + ARTIFACT_ROTATION_SECONDARY_PKCS8: ${{ secrets.ARTIFACT_ROTATION_SECONDARY_PKCS8 }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + # Retries a transient Cloudflare API fault, such as code 10013. Any other # failure stops the job at once. - name: Deploy Artifact signer diff --git a/docs/runbooks/signing-key-rotation.md b/docs/runbooks/signing-key-rotation.md index 50acf072..5e95762e 100644 --- a/docs/runbooks/signing-key-rotation.md +++ b/docs/runbooks/signing-key-rotation.md @@ -62,7 +62,7 @@ Private Artifacts use the same attestation verification. ## Before you start Restore both new root private keys from escrow. -Keep them outside the repository, Cloudflare, and GitHub Actions. +Keep them outside the repository, [Cloudflare](https://cloudflare.com), and GitHub Actions. Prepare a complete root configuration file for each new root as a local pin file. Compare each file's `rootKeyId` and `rootPublicKey` with the reviewed CLI release's compiled pins. Stop if either differs. The tool parses each pin file as a complete root configuration. @@ -124,13 +124,39 @@ If the ceremony date changes, use its UTC midnight for `notBefore` in both roots ## 2. Publish and verify both endpoints Production deployment uses `.github/workflows/deploy-cloudflare.yml` only. -Execute secret uploads as approved configuration steps in that workflow, never as a local deployment. -The upload step consumes the verified array, which contains public data only: +The `Stage Artifact signing configuration` step accepts files through GitHub Actions secrets. +An operator with production write approval must perform this step. +This does not grant an Agent production write access. + +Confirm the deployed secondary slot has no key ID vars before staging its secret. +The workflow also rejects a named secondary slot in the checked-out signer configuration. +Upload the verified files to these repository secrets: ```sh -pnpm exec wrangler secret put ARTIFACT_TRUSTED_ROOTS_JSON --config wrangler.jsonc < "$KEYS/roots-next.json" +gh secret set ARTIFACT_ROTATION_ROOTS_JSON --repo skilld-dev/skilld.dev < "$KEYS/roots-next.json" +gh secret set ARTIFACT_ROTATION_PRIMARY_PIN_JSON --repo skilld-dev/skilld.dev < "$KEYS/primary-pin.json" +gh secret set ARTIFACT_ROTATION_BACKUP_PIN_JSON --repo skilld-dev/skilld.dev < "$KEYS/backup-pin.json" +gh secret set ARTIFACT_ROTATION_SECONDARY_PKCS8 --repo skilld-dev/skilld.dev < "$KEYS/skilld-production-2026-11.pkcs8" +gh variable set ARTIFACT_ROTATION_KEY_ID --repo skilld-dev/skilld.dev --body skilld-production-2026-11 +gh workflow run deploy-cloudflare.yml --repo skilld-dev/skilld.dev --ref main \ + -f target=site -f publish_artifact_roots=true -f stage_artifact_secondary=true ``` +Use pin files checked against the released CLI, never files fetched from the live endpoints. +The workflow checks both root signatures, matching signer coverage, and the private key before either upload. +It publishes `ARTIFACT_TRUSTED_ROOTS_JSON`, then stages `ARTIFACT_SIGNING_SECONDARY_PRIVATE_KEY_PKCS8`. +It never receives either offline root private key. +Both dispatch inputs default to false for normal deployments. +Secret uploads update live Worker configuration before the signer and site deployment steps. +If a later step fails, uploaded secrets remain. Inspect the completed steps before retrying. + +Open the dispatched run under Actions, then wait for it: + +```sh +gh run watch --repo skilld-dev/skilld.dev --exit-status +``` + +Confirm both publication messages appear in the run summary and both upload commands succeeded. Do not upload either new root to `ARTIFACT_TRUSTED_ROOT_JSON`. After the route deployment, verify both live endpoints against their own independent pins: @@ -149,11 +175,8 @@ Do not use an old CLI's success under the old key as proof of new root support. Confirm slot support passed the production deploy workflow. The free slot has no key ID vars. This rotation uses the secondary slot. -Upload its signing secret through the approved deploy workflow before adding its vars: - -```sh -pnpm --filter @skilld/artifact-signer-worker exec wrangler secret put ARTIFACT_SIGNING_SECONDARY_PRIVATE_KEY_PKCS8 --config wrangler.jsonc < "$KEYS/skilld-production-2026-11.pkcs8" -``` +Step 2 stages its secret before any vars enable it. +Do not set `stage_artifact_secondary=true` after enabling this slot. Open a pull request adding these vars to `workers/artifact-signer/wrangler.jsonc`: @@ -177,7 +200,7 @@ pnpm exec wrangler d1 execute DB --remote --config wrangler.jsonc --command \ "SELECT json_extract(attestation_json, '$.signature.keyId') AS key_id, COUNT(*) AS attestations, datetime(MAX(created_at), 'unixepoch') AS newest FROM artifact_attestations GROUP BY key_id" ``` -Check signer logs for `SIGNING_KEY_INVALID` and Sentry for `Artifact signer returned an invalid signature`. +Check signer logs for `SIGNING_KEY_INVALID` and [Sentry](https://sentry.io) for `Artifact signer returned an invalid signature`. Either error requires signer rollback while the old window remains open. ## 4. Remove the old signing key @@ -195,14 +218,23 @@ pnpm exec tsx scripts/trusted-root.ts verify \ jq -s '.' "$KEYS/skilld-root-2026-11-after.json" "$KEYS/skilld-root-backup-2026-11-after.json" > "$KEYS/roots-after.json" ``` -Publish `roots-after.json` to `ARTIFACT_TRUSTED_ROOTS_JSON` through the same workflow configuration step. +Publish the reduced array through the same workflow, with signer staging disabled: + +```sh +gh secret set ARTIFACT_ROTATION_ROOTS_JSON --repo skilld-dev/skilld.dev < "$KEYS/roots-after.json" +gh workflow run deploy-cloudflare.yml --repo skilld-dev/skilld.dev --ref main \ + -f target=site -f publish_artifact_roots=true -f stage_artifact_secondary=false +``` + +Wait for the run and confirm its publication summary. Repeat the live endpoint verification from step 2. Preserve the legacy secret. Removing its old key cannot make old CLIs trust the new key. Watch the build queue and failed jobs for one hour as stored Artifacts rebuild. A Resolution held across removal can fail once with `SIGNING_KEY_UNKNOWN`; its next run resolves again. After November 20, remove the three primary slot vars through a pull request and regenerate signer types. -After that deployment, delete `ARTIFACT_SIGNING_PRIVATE_KEY_PKCS8` through the approved configuration workflow. +After that deployment, the unused primary secret signs nothing. +Secret deletion needs a separate approved workflow change; this workflow only uploads rotation secrets. Never delete a secret while vars name its slot. Store the new signing private key offline, or delete the local copy. @@ -210,8 +242,8 @@ Store the new signing private key offline, or delete the local copy. | Change | Recovery | Limit | | --- | --- | --- | -| New array, before signer activation | Restore the previous array and order. For initial activation, remove the array to restore legacy site verification. | Before any new-key attestations exist | -| Secondary secret, before slot vars | Delete the unused secondary secret through the configuration workflow. | Before signer activation | +| New array, before signer activation | Republish the previous two-root array with `publish_artifact_roots=true` and `stage_artifact_secondary=false`. For initial activation, retain the verified roots and leave the secondary slot disabled. | Before any new-key attestations exist | +| Secondary secret, before slot vars | Leave the secondary slot disabled. Its unused secret signs nothing. | Before signer activation | | Signer activation | Revert the vars pull request. Keep the new signing key in both roots because it signed live attestations. | Old key window closes November 20 | | Old key removal | Republish `roots-next.json` to `ARTIFACT_TRUSTED_ROOTS_JSON`, then verify both endpoints against their pins. | Old signatures remain usable only before November 20 | diff --git a/layers/artifact-delivery/server/utils/trusted-root.ts b/layers/artifact-delivery/server/utils/trusted-root.ts index c9c0ac9b..11a57fe8 100644 --- a/layers/artifact-delivery/server/utils/trusted-root.ts +++ b/layers/artifact-delivery/server/utils/trusted-root.ts @@ -38,15 +38,9 @@ function readTrustedRoots(value: string | undefined, now: number): RootResult[] const configs: unknown = JSON.parse(value) if (!Array.isArray(configs) || configs.length === 0) throw new Error('Served trusted roots must be a non-empty JSON array') - const ids = configs.map((config: unknown) => { - if (typeof config === 'object' && config !== null && 'rootKeyId' in config) - return config.rootKeyId - return undefined - }) - return configs.map((config: unknown, index): RootResult => { + // Preserve each position so an invalid primary never selects a later root. + const parsed = configs.map((config: unknown, index): RootResult => { try { - if (ids[index] !== undefined && ids.indexOf(ids[index]) !== ids.lastIndexOf(ids[index])) - throw new Error('Duplicate root ID') return { _tag: 'valid', root: parseTrustedRoot(JSON.stringify(config), now) } } catch { @@ -55,6 +49,18 @@ function readTrustedRoots(value: string | undefined, now: number): RootResult[] return { _tag: 'invalid' } } }) + const counts = new Map() + for (const result of parsed) { + if (result._tag === 'valid') + counts.set(result.root.rootKeyId, (counts.get(result.root.rootKeyId) ?? 0) + 1) + } + return parsed.map((result, index): RootResult => { + if (result._tag === 'valid' && counts.get(result.root.rootKeyId)! > 1) { + console.error(`Rejected trusted root at array index ${index}: duplicate valid entry`) + return { _tag: 'invalid' } + } + return result + }) } interface TrustedRootEnv { diff --git a/test/unit/signing-configuration.test.ts b/test/unit/signing-configuration.test.ts new file mode 100644 index 00000000..9764ceeb --- /dev/null +++ b/test/unit/signing-configuration.test.ts @@ -0,0 +1,135 @@ +import { spawnSync } from 'node:child_process' +import { generateKeyPairSync } from 'node:crypto' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { runInNewContext } from 'node:vm' +import { afterEach, describe, expect, it } from 'vitest' +import { parse } from 'yaml' +import { createTrustedRoot, generateSigningKey } from '../../scripts/lib/trusted-root-ceremony' + +const directories: string[] = [] +afterEach(() => { + for (const directory of directories.splice(0)) + rmSync(directory, { recursive: true, force: true }) +}) + +// Execute the workflow's configuration commands. Only the Cloudflare write +// boundary is replaced; the ceremony verifies real root signatures and keys. +function stage(options: { mismatch?: boolean, enabledSlot?: boolean, stageSecondary?: boolean, publishRoots?: boolean } = {}) { + const directory = mkdtempSync(join(tmpdir(), 'signing-config-')) + directories.push(directory) + const signing = generateSigningKey() + const key = { + keyId: 'rotation-test', + publicKey: signing.publicKey, + notBefore: '2026-11-18T00:00:00.000Z', + notAfter: '2027-05-20T00:00:00.000Z', + status: 'active' as const, + } + const primary = createTrustedRoot('primary', generateKeyPairSync('ed25519').privateKey, key) + const backup = createTrustedRoot('backup', generateKeyPairSync('ed25519').privateKey, key) + const calls = join(directory, 'calls.jsonl') + const realPnpm = spawnSync('which', ['pnpm'], { encoding: 'utf8' }).stdout.trim() + writeFileSync(join(directory, 'pnpm'), `#!/usr/bin/env node +import { readFileSync, appendFileSync } from 'node:fs' +import { spawnSync } from 'node:child_process' +const args = process.argv.slice(2) +if (args.includes('wrangler')) { + const name = args[args.indexOf('put') + 1] + const input = readFileSync(0, 'utf8') + const expected = name === 'ARTIFACT_TRUSTED_ROOTS_JSON' ? process.env.ARTIFACT_ROTATION_ROOTS_JSON : process.env.ARTIFACT_ROTATION_SECONDARY_PKCS8 + appendFileSync(process.env.TEST_CALLS, JSON.stringify({ args, matches: input.trim() === expected.trim() }) + '\\n') +} else { + const result = spawnSync(process.env.TEST_PNPM, args, { stdio: 'inherit' }) + process.exit(result.status ?? 1) +} +`, { mode: 0o700 }) + const config = join(directory, 'signer.json') + writeFileSync(config, JSON.stringify({ vars: options.enabledSlot ? { ARTIFACT_SIGNING_SECONDARY_KEY_ID: 'already-enabled' } : {} })) + const workflow = parse(readFileSync(resolve('.github/workflows/deploy-cloudflare.yml'), 'utf8')) + const steps = workflow.jobs.deploy.steps as { run?: string, if?: string, env?: Record }[] + const context = { + github: { event_name: 'workflow_dispatch' }, + inputs: { publish_artifact_roots: options.publishRoots ?? true, stage_artifact_secondary: options.stageSecondary ?? true }, + secrets: { + ARTIFACT_ROTATION_ROOTS_JSON: JSON.stringify([primary, backup]), + ARTIFACT_ROTATION_PRIMARY_PIN_JSON: JSON.stringify(primary), + ARTIFACT_ROTATION_BACKUP_PIN_JSON: JSON.stringify(backup), + ARTIFACT_ROTATION_SECONDARY_PKCS8: options.mismatch ? generateSigningKey().privateKeyPkcs8 : signing.privateKeyPkcs8, + }, + vars: { ARTIFACT_ROTATION_KEY_ID: key.keyId }, + } + const selected = steps.filter(step => step.env?.PUBLISH_ARTIFACT_ROOTS !== undefined + && (!step.if || runInNewContext(step.if, context, { timeout: 100 }))) + const commands = selected.map(step => step.run).join('\n') + const environment = Object.fromEntries(selected.flatMap(step => Object.entries(step.env ?? {}).map(([name, value]) => { + const expression = value.startsWith('${{') && value.endsWith('}}') ? value.slice(3, -2).trim() : null + return [name, expression ? String(runInNewContext(expression, context, { timeout: 100 }) ?? '') : value] + }))) + const result = spawnSync('bash', ['-e', '-o', 'pipefail', '-c', commands], { + cwd: process.cwd(), + encoding: 'utf8', + env: { + ...process.env, + ...environment, + PATH: `${directory}:${process.env.PATH}`, + RUNNER_TEMP: directory, + GITHUB_STEP_SUMMARY: join(directory, 'summary.md'), + TEST_CALLS: calls, + TEST_PNPM: realPnpm, + ARTIFACT_SIGNER_CONFIG: config, + }, + }) + // Never include captured output or key material in an assertion failure. + const writes: { args: string[], matches: boolean }[] = readFileSyncIfPresent(calls) + return { status: result.status, writes } +} + +function readFileSyncIfPresent(path: string) { + try { + return readFileSync(path, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line)) + } + catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') + return [] + throw error + } +} + +describe('production signing configuration', () => { + it('publishes verified roots and stages the secondary secret before enabling its slot', () => { + const result = stage() + expect(result.status).toBe(0) + expect(result.writes).toEqual([ + { args: ['exec', 'wrangler', 'secret', 'put', 'ARTIFACT_TRUSTED_ROOTS_JSON', '--config', 'wrangler.jsonc'], matches: true }, + { args: ['--filter', '@skilld/artifact-signer-worker', 'exec', 'wrangler', 'secret', 'put', 'ARTIFACT_SIGNING_SECONDARY_PRIVATE_KEY_PKCS8', '--config', 'wrangler.jsonc'], matches: true }, + ]) + }) + + it('rejects a mismatched signing key before either production write', () => { + const result = stage({ mismatch: true }) + expect(result.status).not.toBe(0) + expect(result.writes).toEqual([]) + }) + + it('refuses to overwrite the secret of an enabled slot', () => { + const result = stage({ enabledSlot: true }) + expect(result.status).not.toBe(0) + expect(result.writes).toEqual([]) + }) + + it('publishes roots after activation without replacing the enabled signer secret', () => { + const result = stage({ enabledSlot: true, stageSecondary: false }) + expect(result.status).toBe(0) + expect(result.writes).toEqual([ + { args: ['exec', 'wrangler', 'secret', 'put', 'ARTIFACT_TRUSTED_ROOTS_JSON', '--config', 'wrangler.jsonc'], matches: true }, + ]) + }) + + it('leaves production configuration alone when both dispatch inputs are false', () => { + const result = stage({ publishRoots: false, stageSecondary: false }) + expect(result.status).toBe(0) + expect(result.writes).toEqual([]) + }) +}) diff --git a/test/unit/trusted-root.test.ts b/test/unit/trusted-root.test.ts index 254e6ff6..ef604a4d 100644 --- a/test/unit/trusted-root.test.ts +++ b/test/unit/trusted-root.test.ts @@ -101,6 +101,47 @@ describe('trusted roots by id', () => { expect(roots.map(served => served.rootKeyId)).toEqual(['skilld-root-2026-11', 'skilld-root-backup-2026-11']) }) + it('serves and selects the primary when a malformed backup repeats its ID', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.stubGlobal('defineEventHandler', defineEventHandler) + vi.stubGlobal('createError', createError) + const { default: handler } = await import('../../layers/artifact-delivery/server/api/v1/trusted-roots/[rootKeyId].get') + const primary = root('primary') + const env = { + ARTIFACT_TRUSTED_ROOTS_JSON: JSON.stringify([primary, { ...primary, keys: [] }]), + ARTIFACT_TRUSTED_ROOT_JSON: trustedRoot(), + } + const app = createApp().use(defineEventHandler((event) => { + event.context.platform = { env } as never + })) + app.use(createRouter().get('/api/v1/trusted-roots/:rootKeyId', handler)) + const response = await toWebHandler(app)(new Request('http://localhost/api/v1/trusted-roots/primary')) + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject(primary) + expect(siteTrustedRoot(env, now)).toEqual(parseTrustedRoot(JSON.stringify(primary), now)) + }) + + it('rejects two valid primary roots for both publication and site verification', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const env = { + ARTIFACT_TRUSTED_ROOTS_JSON: JSON.stringify([root('primary'), root('primary')]), + ARTIFACT_TRUSTED_ROOT_JSON: trustedRoot(), + } + expect(parseTrustedRoots(env.ARTIFACT_TRUSTED_ROOTS_JSON, now)).toEqual([]) + expect(() => siteTrustedRoot(env, now)).toThrow('The selected site trusted root is invalid') + }) + + it('keeps an invalid first entry fail-closed when a valid root repeats its ID', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const primary = root('primary') + const env = { + ARTIFACT_TRUSTED_ROOTS_JSON: JSON.stringify([{ ...primary, keys: [] }, primary]), + ARTIFACT_TRUSTED_ROOT_JSON: trustedRoot(), + } + expect(() => siteTrustedRoot(env, now)).toThrow('The selected site trusted root is invalid') + expect(parseTrustedRoots(env.ARTIFACT_TRUSTED_ROOTS_JSON, now)).toEqual([parseTrustedRoot(JSON.stringify(primary), now)]) + }) + it('rejects ambiguous ids without disabling unrelated roots', () => { const report = vi.spyOn(console, 'error').mockImplementation(() => {}) const backup = root('backup') From dcb77a02f7a4455d1ba942a25d51b0f8eeaf5e0c Mon Sep 17 00:00:00 2001 From: Harlan Wilton Date: Thu, 19 Nov 2026 00:07:46 +1100 Subject: [PATCH 4/4] fix(artifacts): drop the optional rotation workflow step The opt-in step that published roots and staged the signing secret through Actions secrets carried every remaining review blocker, and this rotation never uses it. The runbook stages both secrets with wrangler, as before, and sets the signer switch at 2026-11-19T20:00Z. --- .github/workflows/deploy-cloudflare.yml | 61 ----------- docs/runbooks/signing-key-rotation.md | 52 +++------ test/unit/signing-configuration.test.ts | 135 ------------------------ 3 files changed, 16 insertions(+), 232 deletions(-) delete mode 100644 test/unit/signing-configuration.test.ts diff --git a/.github/workflows/deploy-cloudflare.yml b/.github/workflows/deploy-cloudflare.yml index d32bba16..55bcc9cc 100644 --- a/.github/workflows/deploy-cloudflare.yml +++ b/.github/workflows/deploy-cloudflare.yml @@ -15,14 +15,6 @@ on: description: Rotate the registry GitHub fallback token type: boolean default: false - publish_artifact_roots: - description: Publish the verified Artifact trusted roots - type: boolean - default: false - stage_artifact_secondary: - description: Stage the Artifact signing secret in the unused secondary slot - type: boolean - default: false permissions: contents: read @@ -136,59 +128,6 @@ jobs: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - - name: Stage Artifact signing configuration - if: github.event_name == 'workflow_dispatch' && (inputs.publish_artifact_roots || inputs.stage_artifact_secondary) - shell: bash - run: | - set -euo pipefail - umask 077 - staging=$(mktemp -d "$RUNNER_TEMP/artifact-rotation.XXXXXX") - trap 'rm -rf "$staging"' EXIT - if [ "$STAGE_ARTIFACT_SECONDARY" = true ]; then - jq -e '(.vars.ARTIFACT_SIGNING_SECONDARY_KEY_ID // "") == ""' "$ARTIFACT_SIGNER_CONFIG" > /dev/null - test -n "$ARTIFACT_ROTATION_SECONDARY_PKCS8" - test -n "$ARTIFACT_ROTATION_KEY_ID" - fi - printf '%s' "$ARTIFACT_ROTATION_ROOTS_JSON" > "$staging/roots.json" - jq -e 'type == "array" and length == 2' "$staging/roots.json" > /dev/null - jq '.[0]' "$staging/roots.json" > "$staging/primary.json" - jq '.[1]' "$staging/roots.json" > "$staging/backup.json" - printf '%s' "$ARTIFACT_ROTATION_PRIMARY_PIN_JSON" > "$staging/primary-pin.json" - printf '%s' "$ARTIFACT_ROTATION_BACKUP_PIN_JSON" > "$staging/backup-pin.json" - verify_args=( - --root "$staging/primary.json" --pin "$staging/primary-pin.json" - --peer-root "$staging/backup.json" --peer-pin "$staging/backup-pin.json" - ) - if [ "$STAGE_ARTIFACT_SECONDARY" = true ]; then - printf '%s' "$ARTIFACT_ROTATION_SECONDARY_PKCS8" > "$staging/secondary.pkcs8" - verify_args+=(--key-id "$ARTIFACT_ROTATION_KEY_ID" --signing-key "$staging/secondary.pkcs8") - fi - # Verification can include untrusted configuration in diagnostics. - # Keep it private and print only the result. - if ! pnpm exec tsx scripts/trusted-root.ts verify "${verify_args[@]}" > "$staging/verify.log" 2>&1; then - echo 'Artifact signing configuration verification failed.' >&2 - exit 1 - fi - if [ "$PUBLISH_ARTIFACT_ROOTS" = true ]; then - pnpm exec wrangler secret put ARTIFACT_TRUSTED_ROOTS_JSON --config wrangler.jsonc < "$staging/roots.json" - echo 'Published the verified Artifact trusted roots.' >> "$GITHUB_STEP_SUMMARY" - fi - if [ "$STAGE_ARTIFACT_SECONDARY" = true ]; then - pnpm --filter @skilld/artifact-signer-worker exec wrangler secret put ARTIFACT_SIGNING_SECONDARY_PRIVATE_KEY_PKCS8 --config wrangler.jsonc < "$staging/secondary.pkcs8" - echo 'Staged the secondary Artifact signing secret.' >> "$GITHUB_STEP_SUMMARY" - fi - env: - PUBLISH_ARTIFACT_ROOTS: ${{ inputs.publish_artifact_roots }} - STAGE_ARTIFACT_SECONDARY: ${{ inputs.stage_artifact_secondary }} - ARTIFACT_SIGNER_CONFIG: workers/artifact-signer/wrangler.jsonc - ARTIFACT_ROTATION_ROOTS_JSON: ${{ secrets.ARTIFACT_ROTATION_ROOTS_JSON }} - ARTIFACT_ROTATION_PRIMARY_PIN_JSON: ${{ secrets.ARTIFACT_ROTATION_PRIMARY_PIN_JSON }} - ARTIFACT_ROTATION_BACKUP_PIN_JSON: ${{ secrets.ARTIFACT_ROTATION_BACKUP_PIN_JSON }} - ARTIFACT_ROTATION_KEY_ID: ${{ vars.ARTIFACT_ROTATION_KEY_ID }} - ARTIFACT_ROTATION_SECONDARY_PKCS8: ${{ secrets.ARTIFACT_ROTATION_SECONDARY_PKCS8 }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - # Retries a transient Cloudflare API fault, such as code 10013. Any other # failure stops the job at once. - name: Deploy Artifact signer diff --git a/docs/runbooks/signing-key-rotation.md b/docs/runbooks/signing-key-rotation.md index 5e95762e..c094b77b 100644 --- a/docs/runbooks/signing-key-rotation.md +++ b/docs/runbooks/signing-key-rotation.md @@ -123,40 +123,21 @@ If the ceremony date changes, use its UTC midnight for `notBefore` in both roots ## 2. Publish and verify both endpoints -Production deployment uses `.github/workflows/deploy-cloudflare.yml` only. -The `Stage Artifact signing configuration` step accepts files through GitHub Actions secrets. -An operator with production write approval must perform this step. -This does not grant an Agent production write access. - -Confirm the deployed secondary slot has no key ID vars before staging its secret. -The workflow also rejects a named secondary slot in the checked-out signer configuration. -Upload the verified files to these repository secrets: +Run the verification from step 1 on the exact file you upload, then put it: ```sh -gh secret set ARTIFACT_ROTATION_ROOTS_JSON --repo skilld-dev/skilld.dev < "$KEYS/roots-next.json" -gh secret set ARTIFACT_ROTATION_PRIMARY_PIN_JSON --repo skilld-dev/skilld.dev < "$KEYS/primary-pin.json" -gh secret set ARTIFACT_ROTATION_BACKUP_PIN_JSON --repo skilld-dev/skilld.dev < "$KEYS/backup-pin.json" -gh secret set ARTIFACT_ROTATION_SECONDARY_PKCS8 --repo skilld-dev/skilld.dev < "$KEYS/skilld-production-2026-11.pkcs8" -gh variable set ARTIFACT_ROTATION_KEY_ID --repo skilld-dev/skilld.dev --body skilld-production-2026-11 -gh workflow run deploy-cloudflare.yml --repo skilld-dev/skilld.dev --ref main \ - -f target=site -f publish_artifact_roots=true -f stage_artifact_secondary=true +pnpm exec wrangler secret put ARTIFACT_TRUSTED_ROOTS_JSON --config wrangler.jsonc < "$KEYS/roots-next.json" ``` -Use pin files checked against the released CLI, never files fetched from the live endpoints. -The workflow checks both root signatures, matching signer coverage, and the private key before either upload. -It publishes `ARTIFACT_TRUSTED_ROOTS_JSON`, then stages `ARTIFACT_SIGNING_SECONDARY_PRIVATE_KEY_PKCS8`. -It never receives either offline root private key. -Both dispatch inputs default to false for normal deployments. -Secret uploads update live Worker configuration before the signer and site deployment steps. -If a later step fails, uploaded secrets remain. Inspect the completed steps before retrying. - -Open the dispatched run under Actions, then wait for it: +Confirm the deployed secondary slot has no key ID vars, then stage the new signing key there: ```sh -gh run watch --repo skilld-dev/skilld.dev --exit-status +pnpm --filter @skilld/artifact-signer-worker exec wrangler secret put ARTIFACT_SIGNING_SECONDARY_PRIVATE_KEY_PKCS8 --config wrangler.jsonc < "$KEYS/skilld-production-2026-11.pkcs8" +pnpm --filter @skilld/artifact-signer-worker exec wrangler secret list --config wrangler.jsonc ``` -Confirm both publication messages appear in the run summary and both upload commands succeeded. +A secret with no vars naming its slot signs nothing, so staging it early is safe. +Neither offline root private key leaves the ceremony machine. Do not upload either new root to `ARTIFACT_TRUSTED_ROOT_JSON`. After the route deployment, verify both live endpoints against their own independent pins: @@ -176,7 +157,7 @@ Do not use an old CLI's success under the old key as proof of new root support. Confirm slot support passed the production deploy workflow. The free slot has no key ID vars. This rotation uses the secondary slot. Step 2 stages its secret before any vars enable it. -Do not set `stage_artifact_secondary=true` after enabling this slot. +Never put that secret again after vars name the slot. Open a pull request adding these vars to `workers/artifact-signer/wrangler.jsonc`: @@ -184,15 +165,17 @@ Open a pull request adding these vars to `workers/artifact-signer/wrangler.jsonc { "vars": { "ARTIFACT_SIGNING_SECONDARY_KEY_ID": "skilld-production-2026-11", - "ARTIFACT_SIGNING_SECONDARY_KEY_NOT_BEFORE": "2026-11-18T00:00:00.000Z", + "ARTIFACT_SIGNING_SECONDARY_KEY_NOT_BEFORE": "2026-11-19T20:00:00.000Z", "ARTIFACT_SIGNING_SECONDARY_KEY_NOT_AFTER": "2027-05-20T00:00:00.000Z" } } ``` +The signer picks the newest open key, so `NOT_BEFORE` sets the switch time. +2026-11-19T20:00Z leaves four hours to roll back before the old key closes. Run `pnpm --filter @skilld/artifact-signer-worker types` in that pull request. Before merging, confirm both live root checks passed and the secondary secret exists. -The deploy workflow deploys the signer first. New statements then use the new key. +The deploy workflow deploys the signer first. Statements created from `NOT_BEFORE` use the new key. Inspect new attestation key IDs with a read-only D1 query: ```sh @@ -218,15 +201,12 @@ pnpm exec tsx scripts/trusted-root.ts verify \ jq -s '.' "$KEYS/skilld-root-2026-11-after.json" "$KEYS/skilld-root-backup-2026-11-after.json" > "$KEYS/roots-after.json" ``` -Publish the reduced array through the same workflow, with signer staging disabled: +Put the reduced array: ```sh -gh secret set ARTIFACT_ROTATION_ROOTS_JSON --repo skilld-dev/skilld.dev < "$KEYS/roots-after.json" -gh workflow run deploy-cloudflare.yml --repo skilld-dev/skilld.dev --ref main \ - -f target=site -f publish_artifact_roots=true -f stage_artifact_secondary=false +pnpm exec wrangler secret put ARTIFACT_TRUSTED_ROOTS_JSON --config wrangler.jsonc < "$KEYS/roots-after.json" ``` -Wait for the run and confirm its publication summary. Repeat the live endpoint verification from step 2. Preserve the legacy secret. Removing its old key cannot make old CLIs trust the new key. Watch the build queue and failed jobs for one hour as stored Artifacts rebuild. @@ -234,7 +214,7 @@ A Resolution held across removal can fail once with `SIGNING_KEY_UNKNOWN`; its n After November 20, remove the three primary slot vars through a pull request and regenerate signer types. After that deployment, the unused primary secret signs nothing. -Secret deletion needs a separate approved workflow change; this workflow only uploads rotation secrets. +Then delete it with `wrangler secret delete ARTIFACT_SIGNING_PRIVATE_KEY_PKCS8` on the signer. Never delete a secret while vars name its slot. Store the new signing private key offline, or delete the local copy. @@ -242,7 +222,7 @@ Store the new signing private key offline, or delete the local copy. | Change | Recovery | Limit | | --- | --- | --- | -| New array, before signer activation | Republish the previous two-root array with `publish_artifact_roots=true` and `stage_artifact_secondary=false`. For initial activation, retain the verified roots and leave the secondary slot disabled. | Before any new-key attestations exist | +| New array, before signer activation | Put the previous verified array back into `ARTIFACT_TRUSTED_ROOTS_JSON`. For initial activation, keep the verified roots and leave the secondary slot disabled. | Before any new-key attestations exist | | Secondary secret, before slot vars | Leave the secondary slot disabled. Its unused secret signs nothing. | Before signer activation | | Signer activation | Revert the vars pull request. Keep the new signing key in both roots because it signed live attestations. | Old key window closes November 20 | | Old key removal | Republish `roots-next.json` to `ARTIFACT_TRUSTED_ROOTS_JSON`, then verify both endpoints against their pins. | Old signatures remain usable only before November 20 | diff --git a/test/unit/signing-configuration.test.ts b/test/unit/signing-configuration.test.ts deleted file mode 100644 index 9764ceeb..00000000 --- a/test/unit/signing-configuration.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { spawnSync } from 'node:child_process' -import { generateKeyPairSync } from 'node:crypto' -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join, resolve } from 'node:path' -import { runInNewContext } from 'node:vm' -import { afterEach, describe, expect, it } from 'vitest' -import { parse } from 'yaml' -import { createTrustedRoot, generateSigningKey } from '../../scripts/lib/trusted-root-ceremony' - -const directories: string[] = [] -afterEach(() => { - for (const directory of directories.splice(0)) - rmSync(directory, { recursive: true, force: true }) -}) - -// Execute the workflow's configuration commands. Only the Cloudflare write -// boundary is replaced; the ceremony verifies real root signatures and keys. -function stage(options: { mismatch?: boolean, enabledSlot?: boolean, stageSecondary?: boolean, publishRoots?: boolean } = {}) { - const directory = mkdtempSync(join(tmpdir(), 'signing-config-')) - directories.push(directory) - const signing = generateSigningKey() - const key = { - keyId: 'rotation-test', - publicKey: signing.publicKey, - notBefore: '2026-11-18T00:00:00.000Z', - notAfter: '2027-05-20T00:00:00.000Z', - status: 'active' as const, - } - const primary = createTrustedRoot('primary', generateKeyPairSync('ed25519').privateKey, key) - const backup = createTrustedRoot('backup', generateKeyPairSync('ed25519').privateKey, key) - const calls = join(directory, 'calls.jsonl') - const realPnpm = spawnSync('which', ['pnpm'], { encoding: 'utf8' }).stdout.trim() - writeFileSync(join(directory, 'pnpm'), `#!/usr/bin/env node -import { readFileSync, appendFileSync } from 'node:fs' -import { spawnSync } from 'node:child_process' -const args = process.argv.slice(2) -if (args.includes('wrangler')) { - const name = args[args.indexOf('put') + 1] - const input = readFileSync(0, 'utf8') - const expected = name === 'ARTIFACT_TRUSTED_ROOTS_JSON' ? process.env.ARTIFACT_ROTATION_ROOTS_JSON : process.env.ARTIFACT_ROTATION_SECONDARY_PKCS8 - appendFileSync(process.env.TEST_CALLS, JSON.stringify({ args, matches: input.trim() === expected.trim() }) + '\\n') -} else { - const result = spawnSync(process.env.TEST_PNPM, args, { stdio: 'inherit' }) - process.exit(result.status ?? 1) -} -`, { mode: 0o700 }) - const config = join(directory, 'signer.json') - writeFileSync(config, JSON.stringify({ vars: options.enabledSlot ? { ARTIFACT_SIGNING_SECONDARY_KEY_ID: 'already-enabled' } : {} })) - const workflow = parse(readFileSync(resolve('.github/workflows/deploy-cloudflare.yml'), 'utf8')) - const steps = workflow.jobs.deploy.steps as { run?: string, if?: string, env?: Record }[] - const context = { - github: { event_name: 'workflow_dispatch' }, - inputs: { publish_artifact_roots: options.publishRoots ?? true, stage_artifact_secondary: options.stageSecondary ?? true }, - secrets: { - ARTIFACT_ROTATION_ROOTS_JSON: JSON.stringify([primary, backup]), - ARTIFACT_ROTATION_PRIMARY_PIN_JSON: JSON.stringify(primary), - ARTIFACT_ROTATION_BACKUP_PIN_JSON: JSON.stringify(backup), - ARTIFACT_ROTATION_SECONDARY_PKCS8: options.mismatch ? generateSigningKey().privateKeyPkcs8 : signing.privateKeyPkcs8, - }, - vars: { ARTIFACT_ROTATION_KEY_ID: key.keyId }, - } - const selected = steps.filter(step => step.env?.PUBLISH_ARTIFACT_ROOTS !== undefined - && (!step.if || runInNewContext(step.if, context, { timeout: 100 }))) - const commands = selected.map(step => step.run).join('\n') - const environment = Object.fromEntries(selected.flatMap(step => Object.entries(step.env ?? {}).map(([name, value]) => { - const expression = value.startsWith('${{') && value.endsWith('}}') ? value.slice(3, -2).trim() : null - return [name, expression ? String(runInNewContext(expression, context, { timeout: 100 }) ?? '') : value] - }))) - const result = spawnSync('bash', ['-e', '-o', 'pipefail', '-c', commands], { - cwd: process.cwd(), - encoding: 'utf8', - env: { - ...process.env, - ...environment, - PATH: `${directory}:${process.env.PATH}`, - RUNNER_TEMP: directory, - GITHUB_STEP_SUMMARY: join(directory, 'summary.md'), - TEST_CALLS: calls, - TEST_PNPM: realPnpm, - ARTIFACT_SIGNER_CONFIG: config, - }, - }) - // Never include captured output or key material in an assertion failure. - const writes: { args: string[], matches: boolean }[] = readFileSyncIfPresent(calls) - return { status: result.status, writes } -} - -function readFileSyncIfPresent(path: string) { - try { - return readFileSync(path, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line)) - } - catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') - return [] - throw error - } -} - -describe('production signing configuration', () => { - it('publishes verified roots and stages the secondary secret before enabling its slot', () => { - const result = stage() - expect(result.status).toBe(0) - expect(result.writes).toEqual([ - { args: ['exec', 'wrangler', 'secret', 'put', 'ARTIFACT_TRUSTED_ROOTS_JSON', '--config', 'wrangler.jsonc'], matches: true }, - { args: ['--filter', '@skilld/artifact-signer-worker', 'exec', 'wrangler', 'secret', 'put', 'ARTIFACT_SIGNING_SECONDARY_PRIVATE_KEY_PKCS8', '--config', 'wrangler.jsonc'], matches: true }, - ]) - }) - - it('rejects a mismatched signing key before either production write', () => { - const result = stage({ mismatch: true }) - expect(result.status).not.toBe(0) - expect(result.writes).toEqual([]) - }) - - it('refuses to overwrite the secret of an enabled slot', () => { - const result = stage({ enabledSlot: true }) - expect(result.status).not.toBe(0) - expect(result.writes).toEqual([]) - }) - - it('publishes roots after activation without replacing the enabled signer secret', () => { - const result = stage({ enabledSlot: true, stageSecondary: false }) - expect(result.status).toBe(0) - expect(result.writes).toEqual([ - { args: ['exec', 'wrangler', 'secret', 'put', 'ARTIFACT_TRUSTED_ROOTS_JSON', '--config', 'wrangler.jsonc'], matches: true }, - ]) - }) - - it('leaves production configuration alone when both dispatch inputs are false', () => { - const result = stage({ publishRoots: false, stageSecondary: false }) - expect(result.status).toBe(0) - expect(result.writes).toEqual([]) - }) -})