diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6b410b2..bd2ef8a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,15 +16,42 @@ jobs: - uses: oven-sh/setup-bun@v2 with: bun-version: 1.3.0 + - name: Test the reviewed contract-selection policy + run: bun test ./.github/workflows/sdk-contract-inputs.test.ts + - name: Select the contract archived by the SDK sync + id: sdk-contract + run: bun run .github/workflows/sdk-contract-inputs.ts - name: Install exact dependencies working-directory: typescript run: bun install --frozen-lockfile - name: Verify signed contract working-directory: typescript - run: bun run verify:contract + env: + CONTRACT_PATH: ${{ steps.sdk-contract.outputs.contract_path }} + MINIMUM_RELEASE_SEQUENCE: ${{ steps.sdk-contract.outputs.minimum_release_sequence }} + REQUIRE_SDK_IDENTITY: ${{ steps.sdk-contract.outputs.require_sdk_identity }} + run: | + strict_identity_args=() + case "${REQUIRE_SDK_IDENTITY}" in + true) strict_identity_args=(--require-sdk-identity) ;; + false) ;; + *) echo "Invalid SDK identity policy output" >&2; exit 1 ;; + esac + bun run verify:contract -- \ + --contract "../${CONTRACT_PATH}" \ + --minimum-release-sequence "${MINIMUM_RELEASE_SEQUENCE}" \ + "${strict_identity_args[@]}" - name: Regenerate public types working-directory: typescript - run: bun run generate:types -- --contract ../contracts/2026.07/public-sdk-contract.json + env: + CONTRACT_PATH: ${{ steps.sdk-contract.outputs.contract_path }} + PREVIOUS_CONTRACTS_JSON: ${{ steps.sdk-contract.outputs.previous_contracts_json }} + run: | + previous_args=() + while IFS= read -r version; do + previous_args+=(--previous-contract "${version}") + done < <(jq -r '.[]' <<< "${PREVIOUS_CONTRACTS_JSON}") + bun run generate:types -- --contract "../${CONTRACT_PATH}" "${previous_args[@]}" - name: Reject generated drift run: git diff --exit-code -- typescript/src/generated/public-api.ts typescript/src/contract.ts - name: Check public boundary diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 270d569..92f76b1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -32,6 +32,17 @@ jobs: with: node-version: "24" package-manager-cache: false + - name: Resolve contract metadata with the pinned workflow implementation + id: sdk-contract + env: + AUTOMATION_COMMIT: ${{ github.workflow_sha }} + run: | + git fetch origin "${AUTOMATION_COMMIT}" --depth=1 + git show "${AUTOMATION_COMMIT}:.github/workflows/sdk-contract-inputs.ts" > "${RUNNER_TEMP}/sdk-contract-inputs.ts" + git show "${AUTOMATION_COMMIT}:.github/workflows/sdk-contract-policy.json" > "${RUNNER_TEMP}/sdk-contract-policy.json" + bun run "${RUNNER_TEMP}/sdk-contract-inputs.ts" \ + --root "${GITHUB_WORKSPACE}" \ + --policy "${RUNNER_TEMP}/sdk-contract-policy.json" - name: Use an OIDC-capable npm CLI run: npm install --global npm@11.18.0 - name: Verify OIDC runtime identity @@ -52,9 +63,27 @@ jobs: run: bun install --frozen-lockfile - name: Verify, test and build working-directory: typescript + env: + CONTRACT_PATH: ${{ steps.sdk-contract.outputs.contract_path }} + MINIMUM_RELEASE_SEQUENCE: ${{ steps.sdk-contract.outputs.minimum_release_sequence }} + REQUIRE_SDK_IDENTITY: ${{ steps.sdk-contract.outputs.require_sdk_identity }} + PREVIOUS_CONTRACTS_JSON: ${{ steps.sdk-contract.outputs.previous_contracts_json }} run: | - bun run verify:contract - bun run generate:types -- --contract ../contracts/2026.07/public-sdk-contract.json + strict_identity_args=() + case "${REQUIRE_SDK_IDENTITY}" in + true) strict_identity_args=(--require-sdk-identity) ;; + false) ;; + *) echo "Invalid SDK identity policy output" >&2; exit 1 ;; + esac + bun run verify:contract -- \ + --contract "../${CONTRACT_PATH}" \ + --minimum-release-sequence "${MINIMUM_RELEASE_SEQUENCE}" \ + "${strict_identity_args[@]}" + previous_args=() + while IFS= read -r version; do + previous_args+=(--previous-contract "${version}") + done < <(jq -r '.[]' <<< "${PREVIOUS_CONTRACTS_JSON}") + bun run generate:types -- --contract "../${CONTRACT_PATH}" "${previous_args[@]}" git diff --exit-code -- src/generated/public-api.ts src/contract.ts bun run typecheck bun test diff --git a/.github/workflows/sdk-contract-inputs.test.ts b/.github/workflows/sdk-contract-inputs.test.ts new file mode 100644 index 0000000..1419121 --- /dev/null +++ b/.github/workflows/sdk-contract-inputs.test.ts @@ -0,0 +1,70 @@ +import { expect, test } from "bun:test"; +import { readFile, unlink } from "node:fs/promises"; +import { randomUUID } from "node:crypto"; +import { tmpdir } from "node:os"; +import { resolve } from "node:path"; +import { resolveContractInputs, resolveContractInputsFromData } from "./sdk-contract-inputs"; + +const root = resolve(import.meta.dir, "../.."); +const policy = JSON.parse(await readFile(resolve(import.meta.dir, "sdk-contract-policy.json"), "utf8")); + +test("selects the current signed archive from source metadata and reviewed policy", async () => { + const result = await resolveContractInputs(root); + const source = JSON.parse(await readFile(resolve(root, ".sdk-source.json"), "utf8")); + const selectedPolicy = policy.contracts[result.contractVersion]; + expect(result.contractPath).toBe(source.contract); + expect(result.contractPath).toBe(`contracts/${result.contractVersion}/public-sdk-contract.json`); + expect(result.minimumReleaseSequence).toBe(selectedPolicy.minimumReleaseSequence); + expect(result.requireSdkIdentity).toBe(selectedPolicy.requireSdkIdentity); + expect(result.previousContracts).toEqual(selectedPolicy.previousContracts); +}); + +test("selects the 2026.11 scenario with explicit predecessors, strict identity, and sequence floor", () => { + const result = resolveContractInputsFromData( + { schemaVersion: 1, contract: "contracts/2026.11/public-sdk-contract.json" }, + policy, + { payload: { contractVersion: "2026.11", releaseSequence: 5 }, signature: { algorithm: "ed25519", keyId: "synthetic-test-key", value: "synthetic" } }, + ); + expect(result).toEqual({ + contractPath: "contracts/2026.11/public-sdk-contract.json", + contractVersion: "2026.11", + minimumReleaseSequence: 5, + requireSdkIdentity: true, + previousContracts: ["2026.10", "2026.09"], + }); +}); + +test("fails closed for unsupported versions, mismatched archive identity, and replayed sequence", () => { + const artifact = (contractVersion: string, releaseSequence: number) => ({ + payload: { contractVersion, releaseSequence }, + signature: { algorithm: "ed25519", keyId: "synthetic-test-key", value: "synthetic" }, + }); + expect(() => resolveContractInputsFromData( + { schemaVersion: 1, contract: "contracts/2026.10/public-sdk-contract.json" }, policy, artifact("2026.10", 4), + )).toThrow("not enabled"); + expect(() => resolveContractInputsFromData( + { schemaVersion: 1, contract: "contracts/2026.11/public-sdk-contract.json" }, policy, artifact("2026.10", 5), + )).toThrow("does not match its signed identity"); + expect(() => resolveContractInputsFromData( + { schemaVersion: 1, contract: "contracts/2026.11/public-sdk-contract.json" }, policy, artifact("2026.11", 4), + )).toThrow("below the reviewed minimum release sequence"); +}); + +test("writes only validated selection outputs for GitHub Actions", async () => { + const outputPath = resolve(tmpdir(), `sdk-contract-output-${randomUUID()}.txt`); + try { + const result = Bun.spawnSync(["bun", "run", resolve(import.meta.dir, "sdk-contract-inputs.ts")], { + cwd: root, + env: { ...process.env, GITHUB_OUTPUT: outputPath }, + }); + expect(result.exitCode).toBe(0); + const output = await readFile(outputPath, "utf8"); + const current = await resolveContractInputs(root); + expect(output).toContain(`contract_path=${current.contractPath}\n`); + expect(output).toContain(`minimum_release_sequence=${current.minimumReleaseSequence}\n`); + expect(output).toContain(`require_sdk_identity=${current.requireSdkIdentity}\n`); + expect(output).toContain(`previous_contracts_json=${JSON.stringify(current.previousContracts)}\n`); + } finally { + await unlink(outputPath).catch(() => undefined); + } +}); diff --git a/.github/workflows/sdk-contract-inputs.ts b/.github/workflows/sdk-contract-inputs.ts new file mode 100644 index 0000000..ba22cf1 --- /dev/null +++ b/.github/workflows/sdk-contract-inputs.ts @@ -0,0 +1,139 @@ +import { appendFile, readFile } from "node:fs/promises"; +import { resolve, sep } from "node:path"; + +// The private sync intentionally preserves .github/workflows. Keep this policy +// beside those workflows; the contracts/ tree is reserved for signed archives. +const contractPathPattern = /^contracts\/(\d{4}\.(?:0[1-9]|1[0-2]))\/public-sdk-contract\.json$/; +const contractVersionPattern = /^\d{4}\.(?:0[1-9]|1[0-2])$/; + +export interface ContractInputs { + contractPath: string; + contractVersion: string; + minimumReleaseSequence: number; + requireSdkIdentity: boolean; + previousContracts: string[]; +} + +type ContractPolicy = { + schemaVersion: number; + contracts: Record; +}; + +export function resolveContractInputsFromData( + sourceMetadata: unknown, + policyValue: unknown, + artifactValue: unknown, +): ContractInputs { + if (!sourceMetadata || typeof sourceMetadata !== "object") { + throw new Error("SDK source metadata must be an object"); + } + const metadata = sourceMetadata as { schemaVersion?: unknown; contract?: unknown }; + if (metadata.schemaVersion !== 1) throw new Error("Unsupported SDK source metadata schema"); + const contractPath = metadata.contract; + if (typeof contractPath !== "string") throw new Error("SDK source metadata has no contract path"); + const pathMatch = contractPathPattern.exec(contractPath); + if (!pathMatch) throw new Error("SDK source metadata must select a versioned public contract archive"); + const contractVersion = pathMatch[1]!; + + if (!policyValue || typeof policyValue !== "object") throw new Error("SDK contract policy must be an object"); + const policy = policyValue as ContractPolicy; + if (policy.schemaVersion !== 1 || !policy.contracts || typeof policy.contracts !== "object") { + throw new Error("Unsupported SDK contract policy schema"); + } + const selectedPolicy = policy.contracts[contractVersion]; + if (!selectedPolicy) throw new Error(`SDK contract version ${contractVersion} is not enabled by the reviewed workflow policy`); + if (!Number.isSafeInteger(selectedPolicy.minimumReleaseSequence) || selectedPolicy.minimumReleaseSequence < 1) { + throw new Error("SDK contract policy minimum release sequence must be a positive integer"); + } + if (typeof selectedPolicy.requireSdkIdentity !== "boolean") { + throw new Error("SDK contract policy must explicitly select strict SDK identity verification"); + } + if (!Array.isArray(selectedPolicy.previousContracts) || selectedPolicy.previousContracts.length === 0) { + throw new Error("SDK contract policy must name at least one predecessor"); + } + const seen = new Set(); + for (const [index, previous] of selectedPolicy.previousContracts.entries()) { + if (typeof previous !== "string" || !contractVersionPattern.test(previous) || previous >= contractVersion || seen.has(previous)) { + throw new Error("SDK contract policy predecessors must be unique earlier calendar revisions"); + } + if (index > 0 && previous >= selectedPolicy.previousContracts[index - 1]!) { + throw new Error("SDK contract policy predecessors must be ordered newest first"); + } + seen.add(previous); + } + + if (!artifactValue || typeof artifactValue !== "object") throw new Error("Selected SDK contract artifact must be an object"); + const artifact = artifactValue as { + payload?: { contractVersion?: unknown; releaseSequence?: unknown }; + signature?: { algorithm?: unknown; keyId?: unknown; value?: unknown } | null; + }; + if (artifact.payload?.contractVersion !== contractVersion) { + throw new Error("Selected SDK contract path does not match its signed identity"); + } + if (!Number.isSafeInteger(artifact.payload.releaseSequence) || + Number(artifact.payload.releaseSequence) < selectedPolicy.minimumReleaseSequence) { + throw new Error("Selected SDK contract is below the reviewed minimum release sequence"); + } + if (artifact.signature?.algorithm !== "ed25519" || typeof artifact.signature.keyId !== "string" || + !artifact.signature.keyId || typeof artifact.signature.value !== "string" || !artifact.signature.value) { + throw new Error("Selected SDK contract must contain an Ed25519 signature"); + } + + return { + contractPath, + contractVersion, + minimumReleaseSequence: selectedPolicy.minimumReleaseSequence, + requireSdkIdentity: selectedPolicy.requireSdkIdentity, + previousContracts: [...selectedPolicy.previousContracts], + }; +} + +export async function resolveContractInputs(rootPath: string, policyPath?: string): Promise { + const root = resolve(rootPath); + const metadata = JSON.parse(await readFile(resolve(root, ".sdk-source.json"), "utf8")) as unknown; + const policyFile = policyPath ? resolve(policyPath) : resolve(root, ".github/workflows/sdk-contract-policy.json"); + const policy = JSON.parse(await readFile(policyFile, "utf8")) as unknown; + const metadataRecord = metadata as { contract?: unknown }; + const contractValue = metadataRecord?.contract; + if (typeof contractValue !== "string" || !contractPathPattern.test(contractValue)) { + throw new Error("SDK source metadata must select a versioned public contract archive"); + } + const absoluteContractPath = resolve(root, contractValue); + if (!absoluteContractPath.startsWith(`${root}${sep}`)) throw new Error("SDK contract path escapes the checkout"); + const artifact = JSON.parse(await readFile(absoluteContractPath, "utf8")) as unknown; + return resolveContractInputsFromData(metadata, policy, artifact); +} + +function argumentValue(args: string[], flag: string): string | undefined { + const index = args.indexOf(flag); + return index < 0 ? undefined : args[index + 1]; +} + +if (import.meta.main) { + try { + const args = process.argv.slice(2); + const root = resolve(argumentValue(args, "--root") ?? process.cwd()); + const policyPath = argumentValue(args, "--policy"); + const inputs = await resolveContractInputs(root, policyPath); + const output = { + contract_path: inputs.contractPath, + contract_version: inputs.contractVersion, + minimum_release_sequence: String(inputs.minimumReleaseSequence), + require_sdk_identity: String(inputs.requireSdkIdentity), + previous_contracts_json: JSON.stringify(inputs.previousContracts), + }; + const destination = process.env.GITHUB_OUTPUT; + if (destination) { + await appendFile(destination, Object.entries(output).map(([key, value]) => `${key}=${value}`).join("\n") + "\n"); + } else { + console.log(JSON.stringify(output)); + } + } catch (error) { + console.error(error instanceof Error ? error.message : "Unable to select the reviewed SDK contract"); + process.exitCode = 1; + } +} diff --git a/.github/workflows/sdk-contract-policy.json b/.github/workflows/sdk-contract-policy.json new file mode 100644 index 0000000..c6ba08d --- /dev/null +++ b/.github/workflows/sdk-contract-policy.json @@ -0,0 +1,15 @@ +{ + "schemaVersion": 1, + "contracts": { + "2026.07": { + "minimumReleaseSequence": 1, + "requireSdkIdentity": false, + "previousContracts": ["2026.06"] + }, + "2026.11": { + "minimumReleaseSequence": 5, + "requireSdkIdentity": true, + "previousContracts": ["2026.10", "2026.09"] + } + } +} diff --git a/typescript/bun.lock b/typescript/bun.lock index 8c0f849..99664f3 100644 --- a/typescript/bun.lock +++ b/typescript/bun.lock @@ -11,6 +11,10 @@ }, }, }, + "overrides": { + "brace-expansion": "^2.1.7", + "js-yaml": "^4.3.2", + }, "packages": { "@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], @@ -34,7 +38,7 @@ "balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], - "brace-expansion": ["brace-expansion@2.1.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA=="], + "brace-expansion": ["brace-expansion@2.1.7", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g=="], "bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], @@ -54,7 +58,7 @@ "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], - "js-yaml": ["js-yaml@4.2.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw=="], + "js-yaml": ["js-yaml@4.3.2", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA=="], "json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], diff --git a/typescript/package.json b/typescript/package.json index 29efe1a..a734e7a 100644 --- a/typescript/package.json +++ b/typescript/package.json @@ -86,5 +86,9 @@ "@types/bun": "latest", "openapi-typescript": "^7.13.0", "typescript": "^5.3.0" + }, + "overrides": { + "brace-expansion": "^2.1.7", + "js-yaml": "^4.3.2" } }