From 9cad09db91ee435d87e4b232fa330a5a3bcd49cc Mon Sep 17 00:00:00 2001 From: tyler-turnpike <188578979+tyler-turnpike@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:22:53 +0000 Subject: [PATCH 1/9] feat(schema): dependency-free JSON Schema validator for the published schemas SchemaRegistry implements the draft 2020-12 keywords used in schemas/ and fails closed on any other keyword. Tests validate every recorded report, example design and example program against the published schemas. --- packages/schema/README.md | 17 ++ packages/schema/src/index.ts | 1 + packages/schema/src/jsonschema.ts | 349 ++++++++++++++++++++++++ packages/schema/test/jsonschema.test.ts | 140 ++++++++++ 4 files changed, 507 insertions(+) create mode 100644 packages/schema/src/jsonschema.ts create mode 100644 packages/schema/test/jsonschema.test.ts diff --git a/packages/schema/README.md b/packages/schema/README.md index 909a7e2..ad32827 100644 --- a/packages/schema/README.md +++ b/packages/schema/README.md @@ -16,4 +16,21 @@ canonical decimal strings below the modulus. The validators reject numbers in th unknown members, out-of-range offsets, rounds and exponents, forward register references and programs longer than 256 instructions. Semantic checks (MDS, equivalence) belong to the engine. +`SchemaRegistry` validates any document against the JSON Schemas in `schemas/` without a +third-party dependency. It implements the draft 2020-12 keywords those schemas and +`schemas/openapi.json` use (`$ref` across files, `type`, `enum`, `const`, object, array, number +and string bounds, `allOf`/`anyOf`/`oneOf`/`not`, `if`/`then`/`else`) and throws +`UnsupportedSchemaError` on any other keyword rather than ignoring it. `format` is an annotation +only. `assertSupported` walks a whole schema to check that every keyword is implemented and +every reference resolves. + +```ts +import { SchemaRegistry } from '@cryptificate/schema'; + +const base = 'https://github.com/4waan/Cryptificate/schemas/'; +const reg = new SchemaRegistry(); +for (const file of files) reg.add(base + file, JSON.parse(read(file))); +reg.validate(base + 'job.schema.json', job); // [] when valid, else [{ path, schemaPath, message }] +``` + `npm run build` compiles to `dist/`; `npm test` runs the validator and schema tests. diff --git a/packages/schema/src/index.ts b/packages/schema/src/index.ts index a4ead78..a14062d 100644 --- a/packages/schema/src/index.ts +++ b/packages/schema/src/index.ts @@ -1,3 +1,4 @@ export * from './types.js'; export * from './constants.js'; export * from './validate.js'; +export * from './jsonschema.js'; diff --git a/packages/schema/src/jsonschema.ts b/packages/schema/src/jsonschema.ts new file mode 100644 index 0000000..80560cd --- /dev/null +++ b/packages/schema/src/jsonschema.ts @@ -0,0 +1,349 @@ +/** + * A small JSON Schema (draft 2020-12) validator for the schemas in + * `schemas/`. It implements the assertion keywords those schemas and the + * OpenAPI description use and fails closed: a schema with any other keyword + * makes validation throw instead of silently ignoring the keyword. + * + * It exists so that tests and integrators can check documents against the + * published schemas without a third-party validator. It is not a complete + * implementation of the specification: `format` is an annotation only, + * there is no `unevaluated*`, `dependent*`, `contains` or dynamic reference + * support, and `$id` is honoured only at the root of a registered document. + */ + +export interface SchemaIssue { + /** JSON Pointer into the instance. */ + path: string; + /** JSON Pointer into the schema (relative to the schema resource). */ + schemaPath: string; + message: string; +} + +/** Keywords that carry no assertion; they are accepted and ignored. */ +const ANNOTATIONS = new Set([ + '$schema', + '$id', + '$comment', + '$defs', + 'title', + 'description', + 'examples', + 'default', + 'deprecated', + 'readOnly', + 'writeOnly', + 'format', + 'contentMediaType', + 'contentEncoding', +]); + +/** Keywords this validator asserts. */ +const ASSERTIONS = new Set([ + '$ref', + 'type', + 'enum', + 'const', + 'properties', + 'patternProperties', + 'additionalProperties', + 'required', + 'minProperties', + 'maxProperties', + 'items', + 'prefixItems', + 'minItems', + 'maxItems', + 'uniqueItems', + 'minimum', + 'maximum', + 'exclusiveMinimum', + 'exclusiveMaximum', + 'multipleOf', + 'minLength', + 'maxLength', + 'pattern', + 'allOf', + 'anyOf', + 'oneOf', + 'not', + 'if', + 'then', + 'else', +]); + +export const SUPPORTED_SCHEMA_KEYWORDS: readonly string[] = [...ANNOTATIONS, ...ASSERTIONS]; + +export class UnsupportedSchemaError extends Error {} + +type Schema = boolean | Record; + +function escape(key: string): string { + return key.replace(/~/g, '~0').replace(/\//g, '~1'); +} + +function typeOf(value: unknown): string { + if (value === null) return 'null'; + if (Array.isArray(value)) return 'array'; + if (typeof value === 'number') return Number.isInteger(value) ? 'integer' : 'number'; + return typeof value; +} + +function hasType(value: unknown, type: string): boolean { + const t = typeOf(value); + return t === type || (type === 'number' && t === 'integer'); +} + +/** Structural equality of JSON values (object key order is irrelevant). */ +export function jsonEqual(a: unknown, b: unknown): boolean { + if (a === b) return true; + if (typeof a !== typeof b || a === null || b === null || typeof a !== 'object') return false; + if (Array.isArray(a) !== Array.isArray(b)) return false; + if (Array.isArray(a)) { + const bb = b as unknown[]; + return a.length === bb.length && a.every((x, i) => jsonEqual(x, bb[i])); + } + const ao = a as Record; + const bo = b as Record; + const ak = Object.keys(ao); + const bk = Object.keys(bo); + return ak.length === bk.length && ak.every((k) => Object.prototype.hasOwnProperty.call(bo, k) && jsonEqual(ao[k], bo[k])); +} + +/** Resolve a JSON Pointer (without the leading '#') inside a document. */ +export function resolveJsonPointer(doc: unknown, pointer: string): unknown { + if (pointer === '') return doc; + if (!pointer.startsWith('/')) return undefined; + let cur: unknown = doc; + for (const raw of pointer.slice(1).split('/')) { + const part = decodeURIComponent(raw).replace(/~1/g, '/').replace(/~0/g, '~'); + if (cur === null || typeof cur !== 'object') return undefined; + if (Array.isArray(cur)) { + if (!/^(0|[1-9][0-9]*)$/.test(part)) return undefined; + cur = cur[Number(part)]; + } else { + if (!Object.prototype.hasOwnProperty.call(cur, part)) return undefined; + cur = (cur as Record)[part]; + } + } + return cur; +} + +/** + * A set of schema documents addressed by absolute URI. `$ref` values are + * resolved against the `$id` of the document that holds them (or the URI the + * document was registered under). + */ +export class SchemaRegistry { + private readonly docs = new Map(); + + /** Register a document; its root `$id`, when present, is registered too. */ + add(uri: string, doc: unknown): this { + this.docs.set(stripFragment(uri), doc); + if (doc && typeof doc === 'object' && typeof (doc as Record)['$id'] === 'string') { + this.docs.set(stripFragment(new URL((doc as Record)['$id'] as string, uri).href), doc); + } + return this; + } + + has(uri: string): boolean { + return this.docs.has(stripFragment(uri)); + } + + /** Resolve a reference against a base URI to the schema it names. */ + resolve(ref: string, base: string): { schema: unknown; base: string } { + const abs = new URL(ref, base); + const fragment = abs.hash.replace(/^#/, ''); + abs.hash = ''; + const doc = this.docs.get(abs.href); + if (doc === undefined) throw new UnsupportedSchemaError(`unresolvable $ref ${ref} (from ${base})`); + const target = resolveJsonPointer(doc, fragment); + if (target === undefined) throw new UnsupportedSchemaError(`unresolvable $ref ${ref} (from ${base})`); + const docBase = typeof (doc as Record)['$id'] === 'string' ? new URL((doc as Record)['$id'] as string, abs.href).href : abs.href; + return { schema: target, base: docBase }; + } + + /** + * Validate `value` against the schema at `ref` (an absolute URI, possibly + * with a JSON Pointer fragment). Returns the list of issues, empty when the + * value is valid. Throws UnsupportedSchemaError for a schema this validator + * cannot evaluate faithfully. + */ + validate(ref: string, value: unknown): SchemaIssue[] { + const { schema, base } = this.resolve(ref, ref); + const issues: SchemaIssue[] = []; + this.check(schema as Schema, base, value, '', '', issues, 0); + return issues; + } + + /** + * Walk the whole schema at `ref` (not only the branches a value takes) and + * throw UnsupportedSchemaError for any keyword this validator does not + * implement or any `$ref` that does not resolve. Returns the number of + * subschemas visited. + */ + assertSupported(ref: string): number { + const { schema, base } = this.resolve(ref, ref); + const seen = new Set(); + let count = 0; + const walk = (s: unknown, b: string, at: string): void => { + if (typeof s === 'boolean') return; + if (s === null || typeof s !== 'object' || Array.isArray(s)) throw new UnsupportedSchemaError(`not a schema at ${at}`); + if (seen.has(s)) return; + seen.add(s); + count++; + const o = s as Record; + for (const kw of Object.keys(o)) { + if (!ANNOTATIONS.has(kw) && !ASSERTIONS.has(kw)) throw new UnsupportedSchemaError(`unsupported keyword "${kw}" at ${at}`); + } + if (typeof o['$id'] === 'string') b = new URL(o['$id'], b).href; + if (typeof o['$ref'] === 'string') { + const r = this.resolve(o['$ref'], b); + walk(r.schema, r.base, `${at}/$ref`); + } + for (const kw of ['properties', 'patternProperties', '$defs']) { + for (const [k, v] of Object.entries((o[kw] ?? {}) as Record)) walk(v, b, `${at}/${kw}/${escape(k)}`); + } + for (const kw of ['items', 'additionalProperties', 'not', 'if', 'then', 'else']) if (kw in o) walk(o[kw], b, `${at}/${kw}`); + for (const kw of ['allOf', 'anyOf', 'oneOf', 'prefixItems']) { + ((o[kw] ?? []) as unknown[]).forEach((v, i) => walk(v, b, `${at}/${kw}/${i}`)); + } + }; + walk(schema, base, ''); + return count; + } + + private check(schema: Schema, base: string, value: unknown, path: string, spath: string, out: SchemaIssue[], depth: number): void { + if (depth > 64) throw new UnsupportedSchemaError(`schema nesting deeper than 64 at ${spath}`); + const fail = (kw: string, message: string): void => { + out.push({ path: path || '/', schemaPath: `${spath}/${kw}`, message }); + }; + if (schema === true) return; + if (schema === false) { + out.push({ path: path || '/', schemaPath: spath || '/', message: 'no value is allowed here' }); + return; + } + if (typeof schema !== 'object' || schema === null || Array.isArray(schema)) { + throw new UnsupportedSchemaError(`not a schema at ${spath || '/'}`); + } + for (const kw of Object.keys(schema)) { + if (!ANNOTATIONS.has(kw) && !ASSERTIONS.has(kw)) throw new UnsupportedSchemaError(`unsupported keyword "${kw}" at ${spath || '/'}`); + } + if (typeof schema['$id'] === 'string') base = new URL(schema['$id'], base).href; + const sub = (s: unknown, v: unknown, p: string, sp: string, into: SchemaIssue[] = out): void => + this.check(s as Schema, base, v, p, sp, into, depth + 1); + const passes = (s: unknown, sp: string): boolean => { + const tmp: SchemaIssue[] = []; + sub(s, value, path, sp, tmp); + return tmp.length === 0; + }; + + if (typeof schema['$ref'] === 'string') { + const r = this.resolve(schema['$ref'], base); + this.check(r.schema as Schema, r.base, value, path, `${spath}/$ref`, out, depth + 1); + } + if ('type' in schema) { + const types = Array.isArray(schema['type']) ? (schema['type'] as string[]) : [schema['type'] as string]; + if (!types.some((t) => hasType(value, t))) fail('type', `expected ${types.join(' or ')}, got ${typeOf(value)}`); + } + if ('enum' in schema) { + const allowed = schema['enum'] as unknown[]; + if (!allowed.some((a) => jsonEqual(a, value))) fail('enum', `expected one of ${allowed.map((a) => JSON.stringify(a)).join(', ')}`); + } + if ('const' in schema && !jsonEqual(schema['const'], value)) fail('const', `expected ${JSON.stringify(schema['const'])}`); + + if (typeOf(value) === 'object') { + const obj = value as Record; + const props = (schema['properties'] ?? {}) as Record; + const patterns = Object.entries((schema['patternProperties'] ?? {}) as Record).map( + ([p, s]) => [new RegExp(p, 'u'), s, p] as const, + ); + for (const key of (schema['required'] ?? []) as string[]) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) fail('required', `missing member "${key}"`); + } + const n = Object.keys(obj).length; + if (typeof schema['minProperties'] === 'number' && n < schema['minProperties']) fail('minProperties', `expected at least ${schema['minProperties']} members`); + if (typeof schema['maxProperties'] === 'number' && n > schema['maxProperties']) fail('maxProperties', `expected at most ${schema['maxProperties']} members`); + for (const [key, v] of Object.entries(obj)) { + const kp = `${path}/${escape(key)}`; + let matched = false; + if (Object.prototype.hasOwnProperty.call(props, key)) { + matched = true; + sub(props[key], v, kp, `${spath}/properties/${escape(key)}`); + } + for (const [re, s, p] of patterns) { + if (re.test(key)) { + matched = true; + sub(s, v, kp, `${spath}/patternProperties/${escape(p)}`); + } + } + if (!matched && 'additionalProperties' in schema) { + const ap = schema['additionalProperties']; + if (ap === false) out.push({ path: kp, schemaPath: `${spath}/additionalProperties`, message: `unknown member "${key}"` }); + else sub(ap, v, kp, `${spath}/additionalProperties`); + } + } + } + + if (Array.isArray(value)) { + const prefix = (schema['prefixItems'] ?? []) as unknown[]; + value.forEach((v, i) => { + if (i < prefix.length) sub(prefix[i], v, `${path}/${i}`, `${spath}/prefixItems/${i}`); + else if ('items' in schema) sub(schema['items'], v, `${path}/${i}`, `${spath}/items`); + }); + if (typeof schema['minItems'] === 'number' && value.length < schema['minItems']) fail('minItems', `expected at least ${schema['minItems']} items, got ${value.length}`); + if (typeof schema['maxItems'] === 'number' && value.length > schema['maxItems']) fail('maxItems', `expected at most ${schema['maxItems']} items, got ${value.length}`); + if (schema['uniqueItems'] === true) { + for (let i = 0; i < value.length; i++) { + for (let j = i + 1; j < value.length; j++) { + if (jsonEqual(value[i], value[j])) { + fail('uniqueItems', `items ${i} and ${j} are equal`); + i = j = value.length; + } + } + } + } + } + + if (typeof value === 'number') { + const num = (kw: string): number | undefined => (typeof schema[kw] === 'number' ? (schema[kw] as number) : undefined); + const min = num('minimum'); + const max = num('maximum'); + const xmin = num('exclusiveMinimum'); + const xmax = num('exclusiveMaximum'); + const mult = num('multipleOf'); + if (min !== undefined && value < min) fail('minimum', `expected at least ${min}`); + if (max !== undefined && value > max) fail('maximum', `expected at most ${max}`); + if (xmin !== undefined && value <= xmin) fail('exclusiveMinimum', `expected more than ${xmin}`); + if (xmax !== undefined && value >= xmax) fail('exclusiveMaximum', `expected less than ${xmax}`); + if (mult !== undefined && !Number.isInteger(value / mult)) fail('multipleOf', `expected a multiple of ${mult}`); + } + + if (typeof value === 'string') { + const len = [...value].length; + if (typeof schema['minLength'] === 'number' && len < schema['minLength']) fail('minLength', `expected at least ${schema['minLength']} characters`); + if (typeof schema['maxLength'] === 'number' && len > schema['maxLength']) fail('maxLength', `expected at most ${schema['maxLength']} characters`); + if (typeof schema['pattern'] === 'string' && !new RegExp(schema['pattern'], 'u').test(value)) fail('pattern', `does not match ${schema['pattern']}`); + } + + if (Array.isArray(schema['allOf'])) (schema['allOf'] as unknown[]).forEach((s, i) => sub(s, value, path, `${spath}/allOf/${i}`)); + if (Array.isArray(schema['anyOf'])) { + if (!(schema['anyOf'] as unknown[]).some((s, i) => passes(s, `${spath}/anyOf/${i}`))) fail('anyOf', 'matches none of the alternatives'); + } + if (Array.isArray(schema['oneOf'])) { + const n = (schema['oneOf'] as unknown[]).filter((s, i) => passes(s, `${spath}/oneOf/${i}`)).length; + if (n !== 1) fail('oneOf', n === 0 ? 'matches none of the alternatives' : `matches ${n} alternatives, expected exactly one`); + } + if ('not' in schema && passes(schema['not'], `${spath}/not`)) fail('not', 'matches a schema it must not match'); + if ('if' in schema) { + if (passes(schema['if'], `${spath}/if`)) { + if ('then' in schema) sub(schema['then'], value, path, `${spath}/then`); + } else if ('else' in schema) sub(schema['else'], value, path, `${spath}/else`); + } + } +} + +function stripFragment(uri: string): string { + const u = new URL(uri); + u.hash = ''; + return u.href; +} diff --git a/packages/schema/test/jsonschema.test.ts b/packages/schema/test/jsonschema.test.ts new file mode 100644 index 0000000..f61f502 --- /dev/null +++ b/packages/schema/test/jsonschema.test.ts @@ -0,0 +1,140 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readdirSync, readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { join } from 'node:path'; +import { SchemaRegistry, UnsupportedSchemaError, jsonEqual, resolveJsonPointer } from '../src/index.js'; + +const BASE = 'https://github.com/4waan/Cryptificate/schemas/'; +const schemasDir = fileURLToPath(new URL('../../../../schemas/', import.meta.url)); +const examplesDir = fileURLToPath(new URL('../../../../examples/', import.meta.url)); + +function registry(): SchemaRegistry { + const reg = new SchemaRegistry(); + for (const f of readdirSync(schemasDir).filter((n) => n.endsWith('.schema.json'))) { + reg.add(BASE + f, JSON.parse(readFileSync(join(schemasDir, f), 'utf8')) as unknown); + } + return reg; +} + +function check(schema: unknown, value: unknown): string[] { + return new SchemaRegistry() + .add('https://example.invalid/s.json', schema) + .validate('https://example.invalid/s.json', value) + .map((i) => `${i.path} ${i.schemaPath.split('/').pop()}`); +} + +test('jsonschema: type, enum, const and numeric bounds', () => { + assert.deepEqual(check({ type: 'integer' }, 3), []); + assert.deepEqual(check({ type: 'integer' }, 3.5), ['/ type']); + assert.deepEqual(check({ type: 'number' }, 3), []); + assert.deepEqual(check({ type: ['string', 'null'] }, null), []); + assert.deepEqual(check({ type: 'object' }, []), ['/ type']); + assert.deepEqual(check({ enum: ['a', 1, { x: [1] }] }, { x: [1] }), []); + assert.deepEqual(check({ enum: ['a', 1] }, '1'), ['/ enum']); + assert.deepEqual(check({ const: { a: 1, b: 2 } }, { b: 2, a: 1 }), []); + assert.deepEqual(check({ minimum: 1, maximum: 3 }, 0), ['/ minimum']); + assert.deepEqual(check({ exclusiveMaximum: 3 }, 3), ['/ exclusiveMaximum']); + assert.deepEqual(check({ multipleOf: 2 }, 6), []); + assert.deepEqual(check({ multipleOf: 2 }, 5), ['/ multipleOf']); + assert.deepEqual(check({ minimum: 1 }, 'not a number'), [], 'numeric keywords ignore other types'); +}); + +test('jsonschema: strings, objects and arrays', () => { + assert.deepEqual(check({ pattern: '^[0-9a-f]{4}$' }, 'beef'), []); + assert.deepEqual(check({ pattern: '^[0-9a-f]{4}$' }, 'BEEF'), ['/ pattern']); + assert.deepEqual(check({ maxLength: 2 }, 'abc'), ['/ maxLength']); + const obj = { type: 'object', required: ['a'], properties: { a: { type: 'string' } }, additionalProperties: false }; + assert.deepEqual(check(obj, { a: 'x' }), []); + assert.deepEqual(check(obj, {}), ['/ required']); + assert.deepEqual(check(obj, { a: 1, b: 2 }), ['/a type', '/b additionalProperties']); + assert.deepEqual(check({ patternProperties: { '^x': { type: 'integer' } }, additionalProperties: { type: 'string' } }, { x1: 1, y: 's' }), []); + assert.deepEqual(check({ items: { type: 'integer' }, minItems: 2, maxItems: 3 }, [1]), ['/ minItems']); + assert.deepEqual(check({ items: { type: 'integer' } }, [1, 'a']), ['/1 type']); + assert.deepEqual(check({ prefixItems: [{ type: 'string' }], items: { type: 'integer' } }, ['a', 1, 2]), []); + assert.deepEqual(check({ uniqueItems: true }, [[1], [1]]), ['/ uniqueItems']); + assert.deepEqual(check({ properties: { 'a/b': { type: 'string' } } }, { 'a/b': 1 }), ['/a~1b type']); +}); + +test('jsonschema: combinators, conditionals and boolean schemas', () => { + const one = { oneOf: [{ type: 'integer' }, { type: 'number' }] }; + assert.deepEqual(check(one, 1.5), []); + assert.deepEqual(check(one, 1), ['/ oneOf'], 'an integer matches both alternatives'); + assert.deepEqual(check({ anyOf: [{ type: 'string' }, { type: 'null' }] }, 1), ['/ anyOf']); + assert.deepEqual(check({ allOf: [{ minimum: 1 }, { maximum: 2 }] }, 3), ['/ maximum']); + assert.deepEqual(check({ not: { type: 'string' } }, 's'), ['/ not']); + const cond = { if: { properties: { k: { const: 'a' } } }, then: { required: ['x'] }, else: { required: ['y'] } }; + assert.deepEqual(check(cond, { k: 'a', x: 1 }), []); + assert.deepEqual(check(cond, { k: 'b', x: 1 }), ['/ required']); + assert.deepEqual(check(true, 1), []); + assert.deepEqual(check({ properties: { a: false } }, { a: 1 }), ['/a a']); +}); + +test('jsonschema: references resolve against $id across documents', () => { + const reg = new SchemaRegistry() + .add('https://example.invalid/dir/a.json', { $id: 'https://example.invalid/dir/a.json', $ref: 'b.json#/$defs/n' }) + .add('https://example.invalid/dir/b.json', { $defs: { n: { type: 'integer', minimum: 0 }, m: { $ref: '#/$defs/n' } } }); + assert.deepEqual(reg.validate('https://example.invalid/dir/a.json', 4), []); + assert.equal(reg.validate('https://example.invalid/dir/a.json', -1).length, 1); + assert.equal(reg.validate('https://example.invalid/dir/b.json#/$defs/m', 'x').length, 1); + assert.throws(() => reg.validate('https://example.invalid/dir/c.json', 1), UnsupportedSchemaError); + assert.throws(() => reg.validate('https://example.invalid/dir/b.json#/$defs/missing', 1), UnsupportedSchemaError); +}); + +test('jsonschema: fails closed on keywords it does not implement', () => { + assert.throws(() => check({ unevaluatedProperties: false }, {}), /unsupported keyword "unevaluatedProperties"/); + assert.throws(() => check({ properties: { a: { contains: {} } } }, { a: [] }), /unsupported keyword "contains"/); + assert.throws(() => check({ discriminator: { propertyName: 'k' } }, {}), UnsupportedSchemaError); + const reg = new SchemaRegistry().add('https://example.invalid/s.json', { anyOf: [{ type: 'string' }, { items: { $ref: '#/$defs/nope' } }] }); + assert.deepEqual(reg.validate('https://example.invalid/s.json', 'a'), [], 'the bad branch is not reached by this value'); + assert.throws(() => reg.assertSupported('https://example.invalid/s.json'), /unresolvable \$ref/); +}); + +test('jsonschema: pointer helpers and structural equality', () => { + const doc = { a: [{ 'b/c': 1, '~d': 2 }] }; + assert.equal(resolveJsonPointer(doc, '/a/0/b~1c'), 1); + assert.equal(resolveJsonPointer(doc, '/a/0/~0d'), 2); + assert.equal(resolveJsonPointer(doc, '/a/01'), undefined); + assert.equal(resolveJsonPointer(doc, ''), doc); + assert.ok(jsonEqual({ a: [1, { b: null }] }, { a: [1, { b: null }] })); + assert.ok(!jsonEqual({ a: 1 }, { a: 1, b: undefined })); + assert.ok(!jsonEqual([1], { 0: 1 })); +}); + +test('jsonschema: every schema file evaluates with this validator', () => { + const reg = registry(); + for (const f of readdirSync(schemasDir).filter((n) => n.endsWith('.schema.json'))) { + // throws on an unsupported keyword or an unresolvable reference anywhere in the schema + assert.ok(reg.assertSupported(BASE + f) > 0, f); + } +}); + +test('jsonschema: recorded reports and example inputs validate against the published schemas', () => { + const reg = registry(); + let reports = 0; + for (const name of readdirSync(join(examplesDir, 'bundles'))) { + let text: string; + try { + text = readFileSync(join(examplesDir, 'bundles', name, 'report.json'), 'utf8'); + } catch { + continue; + } + const report = JSON.parse(text) as { kind: string }; + const schema = report.kind === 'analysis' ? 'analysis-report.schema.json' : 'experiment-report.schema.json'; + assert.deepEqual(reg.validate(BASE + schema, report), [], name); + reports++; + } + assert.ok(reports >= 8, `${reports} recorded reports`); + for (const f of readdirSync(join(examplesDir, 'designs')).filter((n) => n.endsWith('.json'))) { + const doc = JSON.parse(readFileSync(join(examplesDir, 'designs', f), 'utf8')) as unknown; + assert.deepEqual(reg.validate(BASE + 'candidate-design.schema.json', doc), [], f); + } + for (const f of readdirSync(join(examplesDir, 'programs')).filter((n) => n.endsWith('.json'))) { + const doc = JSON.parse(readFileSync(join(examplesDir, 'programs', f), 'utf8')) as unknown; + assert.deepEqual(reg.validate(BASE + 'program.schema.json', doc), [], f); + } + // and a broken report is caught + const broken = JSON.parse(readFileSync(join(examplesDir, 'bundles', 'identity', 'report.json'), 'utf8')) as { claims: Array<{ status: string }> }; + broken.claims[0]!.status = 'probably'; + assert.ok(reg.validate(BASE + 'analysis-report.schema.json', broken).some((i) => i.path === '/claims/0/status')); +}); From 853e8fc64fd6bc886a2a18bb34e6e46fb07ba88d Mon Sep 17 00:00:00 2001 From: tyler-turnpike <188578979+tyler-turnpike@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:23:25 +0000 Subject: [PATCH 2/9] feat(schema): describe error responses and job summaries error.schema.json describes the body of every error response; job.schema.json gains the job summary and the {job} envelope returned on submission and stop. --- schemas/error.schema.json | 31 +++++++++++++++++++++++++++++++ schemas/job.schema.json | 18 ++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 schemas/error.schema.json diff --git a/schemas/error.schema.json b/schemas/error.schema.json new file mode 100644 index 0000000..61beca4 --- /dev/null +++ b/schemas/error.schema.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/4waan/Cryptificate/schemas/error.schema.json", + "title": "ErrorResponse", + "description": "Body of every 4xx and 5xx JSON response of the HTTP API. error.code is a stable machine-readable string (forbidden, bad-json, invalid-request, unsupported-media-type, body-too-large, not-found, method-not-allowed, queue-full, not-ready, internal); error.message is for people and may change. A 400 invalid-request response also lists every shape problem found in errors.", + "type": "object", + "required": ["error"], + "properties": { + "error": { + "type": "object", + "required": ["code", "message"], + "properties": { + "code": { "type": "string" }, + "message": { "type": "string" }, + "path": { "type": "string" } + } + }, + "errors": { "type": "array", "maxItems": 50, "items": { "$ref": "#/$defs/issue" } } + }, + "$defs": { + "issue": { + "type": "object", + "required": ["path", "code", "message"], + "properties": { + "path": { "description": "JSON Pointer into the request, e.g. /design/matrix/0/1.", "type": "string" }, + "code": { "type": "string" }, + "message": { "type": "string" } + } + } + } +} diff --git a/schemas/job.schema.json b/schemas/job.schema.json index 9560f9c..f535168 100644 --- a/schemas/job.schema.json +++ b/schemas/job.schema.json @@ -21,5 +21,23 @@ "properties": { "code": { "type": "string" }, "message": { "type": "string" }, "path": { "type": "string" } } }, "bundle": { "type": "boolean" } + }, + "$defs": { + "summary": { + "type": "object", + "required": ["id", "kind", "state", "origin"], + "properties": { + "id": { "$ref": "#/properties/id" }, + "kind": { "$ref": "#/properties/kind" }, + "state": { "$ref": "#/properties/state" }, + "origin": { "$ref": "#/properties/origin" } + } + }, + "envelope": { + "description": "Response of POST /api/analyses, POST /api/experiments and POST /api/jobs/:id/stop.", + "type": "object", + "required": ["job"], + "properties": { "job": { "$ref": "#/$defs/summary" } } + } } } From c27d45c8b6e0cf793b23754bcef16730546bdfe1 Mon Sep 17 00:00:00 2001 From: tyler-turnpike <188578979+tyler-turnpike@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:23:45 +0000 Subject: [PATCH 3/9] feat(server): route table and GET /api/openapi.json API_ROUTES lists every API operation and the handler dispatches through it, so the routes can be compared with the API description. GET /api/openapi.json serves schemas/openapi.json bundled into one document: the referenced JSON Schemas are embedded under components/schemas and every reference is rewritten to a local pointer. A bundle request for a job that ended without a report now says so instead of reporting that the job has not finished. --- apps/server/src/openapi.ts | 110 +++++++++++++++++++++++++++++++++ apps/server/src/server.ts | 122 +++++++++++++++++++++++++++---------- 2 files changed, 200 insertions(+), 32 deletions(-) create mode 100644 apps/server/src/openapi.ts diff --git a/apps/server/src/openapi.ts b/apps/server/src/openapi.ts new file mode 100644 index 0000000..7c619bb --- /dev/null +++ b/apps/server/src/openapi.ts @@ -0,0 +1,110 @@ +/** + * The OpenAPI description served at GET /api/openapi.json. + * + * The source of truth is schemas/openapi.json, which refers to the JSON + * Schemas next to it by relative `$ref` ("job.schema.json"). A client that + * fetches the document over HTTP cannot follow those file references, so the + * service serves a bundled copy: every referenced schema file is embedded + * under components/schemas (named after the file, without `$id` and + * `$schema`) and every reference is rewritten to a local JSON Pointer. The + * bundled document has no external references. + */ +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +export const OPENAPI_FILE = 'openapi.json'; + +type Json = null | boolean | number | string | Json[] | { [k: string]: Json }; + +/** "analysis-report.schema.json" -> "AnalysisReport". */ +export function componentName(file: string): string { + return file + .replace(/\.schema\.json$/, '') + .split(/[^A-Za-z0-9]+/) + .filter(Boolean) + .map((w) => w[0]!.toUpperCase() + w.slice(1)) + .join(''); +} + +function isExternal(ref: string): boolean { + return !ref.startsWith('#'); +} + +function splitRef(ref: string): { file: string; fragment: string } { + const i = ref.indexOf('#'); + return i < 0 ? { file: ref, fragment: '' } : { file: ref.slice(0, i), fragment: ref.slice(i + 1) }; +} + +/** + * Bundle an OpenAPI document whose schemas refer to sibling files. + * `read(file)` returns the parsed JSON of a file in the same directory. + */ +export function bundleOpenApi(doc: Json, read: (file: string) => Json): Json { + const embedded = new Map(); // file -> component name + const pending: string[] = []; + + const nameFor = (file: string): string => { + if (!/^[a-z0-9-]+\.schema\.json$/.test(file)) throw new Error(`unexpected schema reference ${file}`); + let name = embedded.get(file); + if (!name) { + name = componentName(file); + embedded.set(file, name); + pending.push(file); + } + return name; + }; + + /** Rewrite references in `node`; `self` is the component of the file being embedded. */ + const rewrite = (node: Json, self: string | null): Json => { + if (Array.isArray(node)) return node.map((n) => rewrite(n, self)); + if (node === null || typeof node !== 'object') return node; + const res: { [k: string]: Json } = {}; + for (const [k, v] of Object.entries(node)) { + if (k === '$ref' && typeof v === 'string') { + if (isExternal(v)) { + const { file, fragment } = splitRef(v); + res[k] = `#/components/schemas/${nameFor(file)}${fragment}`; + } else if (self !== null) { + res[k] = `#/components/schemas/${self}${v.slice(1)}`; + } else res[k] = v; + } else res[k] = rewrite(v, self); + } + return res; + }; + + const out = rewrite(doc, null) as { [k: string]: Json }; + const added: { [k: string]: Json } = {}; + while (pending.length > 0) { + const file = pending.shift()!; + const schema = read(file); + if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) throw new Error(`${file} is not a schema object`); + const { $schema: _s, $id: _i, ...rest } = schema; + const name = embedded.get(file)!; + added[name] = rewrite(rest, name); + } + const components = (out['components'] ??= {}) as { [k: string]: Json }; + const schemas = (components['schemas'] ??= {}) as { [k: string]: Json }; + for (const [name, schema] of Object.entries(added)) { + if (Object.prototype.hasOwnProperty.call(schemas, name)) throw new Error(`component name ${name} is already taken`); + schemas[name] = schema; + } + return out; +} + +const cache = new Map(); + +/** + * The bundled OpenAPI document of the checkout at `root` (read once), or + * null when the checkout has no schemas/openapi.json. + */ +export function openApiDocument(root: string): Json | null { + const dir = join(root, 'schemas'); + let doc = cache.get(dir); + if (doc === undefined) { + if (!existsSync(join(dir, OPENAPI_FILE))) return null; + const read = (file: string): Json => JSON.parse(readFileSync(join(dir, file), 'utf8')) as Json; + doc = bundleOpenApi(read(OPENAPI_FILE), read); + cache.set(dir, doc); + } + return doc; +} diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 0826baf..5ee6a6b 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -8,7 +8,7 @@ import { createReadStream, existsSync, readFileSync, statSync } from 'node:fs'; import { createServer } from 'node:http'; import type { IncomingMessage, Server, ServerResponse } from 'node:http'; import { extname, join, normalize, sep } from 'node:path'; -import { LIMITS, MODELS, validateAnalysisRequest, validateExperimentRequest } from '@cryptificate/schema'; +import { LIMITS, MODELS, TERMINAL_JOB_STATES, validateAnalysisRequest, validateExperimentRequest } from '@cryptificate/schema'; import type { Capabilities, ErrorResponse, ExperimentProfile, ValidationIssue } from '@cryptificate/schema'; import { ANALYSIS_BUDGET_MS } from './analysis.js'; import { buildBundle } from './bundle.js'; @@ -16,6 +16,7 @@ import type { PipelineEnv } from './context.js'; import { PROFILE_BUDGETS } from './experiment.js'; import { JobManager, QueueFullError } from './jobs.js'; import { LEAN_TIMEOUT_MS } from './leanrun.js'; +import { openApiDocument } from './openapi.js'; export interface ServerOptions { env: PipelineEnv; @@ -49,6 +50,46 @@ const MIME: Record = { '.mp4': 'video/mp4', }; +/** + * Every API route the service answers. The handler dispatches through this + * table, and schemas/openapi.json describes exactly these operations (a test + * checks both directions). Any other path under /api/ answers 404 for GET and + * POST and 405 for other methods. + */ +export const API_ROUTES = [ + { method: 'GET', path: '/api/capabilities', operationId: 'getCapabilities' }, + { method: 'GET', path: '/api/openapi.json', operationId: 'getOpenApi' }, + { method: 'POST', path: '/api/analyses', operationId: 'submitAnalysis' }, + { method: 'POST', path: '/api/experiments', operationId: 'submitExperiment' }, + { method: 'GET', path: '/api/jobs/{id}', operationId: 'getJob' }, + { method: 'POST', path: '/api/jobs/{id}/stop', operationId: 'stopJob' }, + { method: 'GET', path: '/api/jobs/{id}/bundle', operationId: 'getJobBundle' }, +] as const; + +export type ApiRoute = (typeof API_ROUTES)[number]; + +/** Match a request against API_ROUTES; `{name}` matches one non-empty path segment. */ +export function matchApiRoute(method: string, path: string): (ApiRoute & { params: Record }) | null { + const segments = path.split('/'); + for (const route of API_ROUTES) { + if (route.method !== method) continue; + const pattern = route.path.split('/'); + if (pattern.length !== segments.length) continue; + const params: Record = {}; + let ok = true; + for (let i = 0; i < pattern.length && ok; i++) { + const p = pattern[i] ?? ''; + const seg = segments[i] ?? ''; + if (p.startsWith('{') && p.endsWith('}')) { + if (seg === '') ok = false; + else params[p.slice(1, -1)] = seg; + } else ok = p === seg; + } + if (ok) return { ...route, params }; + } + return null; +} + export class HttpError extends Error { constructor( readonly status: number, @@ -283,48 +324,68 @@ export function createApp(opts: ServerOptions): Server { const path = url.pathname; if (path.startsWith('/api/')) { - const parts = path.split('/').filter(Boolean); // ['api', ...] - if (path === '/api/capabilities' && method === 'GET') { - send(res, 200, await capabilities(env)); + const route = matchApiRoute(method, path); + if (!route) { + const known = method === 'GET' || method === 'POST'; + sendError(res, known ? 404 : 405, known ? 'not-found' : 'method-not-allowed', 'no such endpoint'); + req.resume(); return; } - if ((path === '/api/analyses' || path === '/api/experiments') && method === 'POST') { - const body = await parseJsonBody(req); - const kind = path === '/api/analyses' ? 'analysis' : 'experiment'; - const v = kind === 'analysis' ? validateAnalysisRequest(body) : validateExperimentRequest(body); - if (!v.ok) throw invalid(v.errors); - try { - const rec = jobs.submit(kind, v.value); - send(res, 202, { job: jobs.summary(rec) }, { location: `/api/jobs/${rec.id}` }); - } catch (e) { - if (e instanceof QueueFullError) { - sendError(res, 429, 'queue-full', 'one job is running and the queue is full; try again later', {}, { 'retry-after': '30' }); - return; + switch (route.operationId) { + case 'getCapabilities': + send(res, 200, await capabilities(env)); + return; + case 'getOpenApi': { + const doc = openApiDocument(env.paths.root); + if (doc === null) sendError(res, 404, 'not-found', 'this installation has no schemas/openapi.json'); + else send(res, 200, doc, { 'cache-control': 'no-cache' }); + return; + } + case 'submitAnalysis': + case 'submitExperiment': { + const body = await parseJsonBody(req); + const kind = route.operationId === 'submitAnalysis' ? 'analysis' : 'experiment'; + const v = kind === 'analysis' ? validateAnalysisRequest(body) : validateExperimentRequest(body); + if (!v.ok) throw invalid(v.errors); + try { + const rec = jobs.submit(kind, v.value); + send(res, 202, { job: jobs.summary(rec) }, { location: `/api/jobs/${rec.id}` }); + } catch (e) { + if (e instanceof QueueFullError) { + sendError(res, 429, 'queue-full', 'one job is running and the queue is full; try again later', {}, { 'retry-after': '30' }); + return; + } + throw e; } - throw e; + return; } + } + // the remaining routes address one job + const rec = jobs.get(route.params['id'] ?? ''); + if (!rec) { + sendError(res, 404, 'not-found', 'no such job'); + req.resume(); return; } - if (parts[1] === 'jobs' && parts.length >= 3) { - const rec = jobs.get(parts[2] ?? ''); - if (!rec) { - sendError(res, 404, 'not-found', 'no such job'); - return; - } - if (parts.length === 3 && method === 'GET') { + switch (route.operationId) { + case 'getJob': send(res, 200, jobs.view(rec)); return; - } - if (parts.length === 4 && parts[3] === 'stop' && method === 'POST') { + case 'stopJob': req.resume(); jobs.stop(rec.id); send(res, 200, { job: jobs.summary(rec) }); return; - } - if (parts.length === 4 && parts[3] === 'bundle' && method === 'GET') { + case 'getJobBundle': { const view = jobs.view(rec); if (!view.bundle || !view.report) { - sendError(res, 409, 'not-ready', view.state === 'invalid' ? 'invalid requests have no bundle' : 'the job has not finished'); + const message = + view.state === 'invalid' + ? 'invalid requests have no bundle' + : TERMINAL_JOB_STATES.includes(view.state) + ? 'the job ended before it produced a report' + : 'the job has not finished'; + sendError(res, 409, 'not-ready', message); return; } const tc = await env.toolchain(); @@ -339,9 +400,6 @@ export function createApp(opts: ServerOptions): Server { return; } } - sendError(res, method === 'GET' || method === 'POST' ? 404 : 405, method === 'GET' || method === 'POST' ? 'not-found' : 'method-not-allowed', 'no such endpoint'); - req.resume(); - return; } if (method !== 'GET' && method !== 'HEAD') { From 6b453fc8eb259eef27ff0239375a153400c7f946 Mon Sep 17 00:00:00 2001 From: tyler-turnpike <188578979+tyler-turnpike@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:26:42 +0000 Subject: [PATCH 4/9] feat(schema): OpenAPI 3.1 description of the HTTP API schemas/openapi.json describes every route the service answers, reuses the JSON Schemas by $ref, lists the error responses each operation returns and states the Host/Origin policy, the queue limit and the job lifecycle. Examples are responses recorded from a live service. The test checks the description against API_ROUTES in both directions, validates every example against its schema, checks that every error code the handler can produce is documented, and validates live responses of an in-process service against the description. --- apps/server/test/openapi.test.ts | 361 ++++++ schemas/openapi.json | 1755 ++++++++++++++++++++++++++++++ 2 files changed, 2116 insertions(+) create mode 100644 apps/server/test/openapi.test.ts create mode 100644 schemas/openapi.json diff --git a/apps/server/test/openapi.test.ts b/apps/server/test/openapi.test.ts new file mode 100644 index 0000000..e28e65f --- /dev/null +++ b/apps/server/test/openapi.test.ts @@ -0,0 +1,361 @@ +/** + * The OpenAPI description (schemas/openapi.json) against the service: the + * same routes in both, recorded examples valid against the referenced + * schemas, every error code the handler can produce documented, and live + * responses of an in-process service valid against the description. + */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { cpSync, readdirSync, readFileSync, rmSync } from 'node:fs'; +import { request } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { SchemaRegistry, resolveJsonPointer, validateAnalysisRequest, validateExperimentRequest } from '@cryptificate/schema'; +import { JobManager } from '../src/jobs.js'; +import { bundleOpenApi, componentName } from '../src/openapi.js'; +import { API_ROUTES, createApp, matchApiRoute } from '../src/server.js'; +import { AES_DESIGN, makeFixture } from './helpers.js'; + +const REPO = fileURLToPath(new URL('../../../../', import.meta.url)); +const SCHEMAS = join(REPO, 'schemas'); +const BASE = 'https://github.com/4waan/Cryptificate/schemas/'; +const DOC_URI = `${BASE}openapi.json`; +const METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'] as const; + +type Obj = Record; + +function readJson(file: string): Obj { + return JSON.parse(readFileSync(file, 'utf8')) as Obj; +} + +const spec = readJson(join(SCHEMAS, 'openapi.json')); +const paths = spec['paths'] as Record; + +function registry(doc: Obj = spec, withFiles = true): SchemaRegistry { + const reg = new SchemaRegistry().add(DOC_URI, doc); + if (withFiles) { + for (const f of readdirSync(SCHEMAS).filter((n) => n.endsWith('.schema.json'))) reg.add(BASE + f, readJson(join(SCHEMAS, f))); + } + return reg; +} + +function escape(s: string): string { + return s.replace(/~/g, '~0').replace(/\//g, '~1'); +} + +/** Follow an OpenAPI Reference Object ({"$ref": "#/components/..."}) to its target and pointer. */ +function deref(doc: Obj, node: unknown, pointer: string): { node: Obj; pointer: string } { + let cur = node as Obj; + let ptr = pointer; + for (let i = 0; i < 10 && typeof cur['$ref'] === 'string'; i++) { + const ref = cur['$ref'] as string; + assert.ok(ref.startsWith('#/'), `${ptr}: non-local reference ${ref}`); + ptr = ref.slice(1); + cur = resolveJsonPointer(doc, ptr) as Obj; + assert.ok(cur, `${pointer}: unresolvable ${ref}`); + } + return { node: cur, pointer: ptr }; +} + +interface Operation { + method: string; + path: string; + op: Obj; + pointer: string; +} + +function operations(doc: Obj = spec): Operation[] { + const out: Operation[] = []; + for (const [path, item] of Object.entries(doc['paths'] as Record)) { + for (const m of METHODS) { + if (item[m]) out.push({ method: m.toUpperCase(), path, op: item[m] as Obj, pointer: `/paths/${escape(path)}/${m}` }); + } + } + return out; +} + +/** JSON Pointer (in `doc`) of the schema for a response, or null if undocumented. */ +function responseSchema(doc: Obj, o: Operation, status: number, mediaType: string): { pointer: string | null; documented: boolean } { + const responses = o.op['responses'] as Obj; + if (!(String(status) in responses)) return { pointer: null, documented: false }; + const r = deref(doc, responses[String(status)], `${o.pointer}/responses/${status}`); + const content = (r.node['content'] ?? {}) as Obj; + const media = content[mediaType] as Obj | undefined; + if (!media) return { pointer: null, documented: false }; + return { pointer: `${r.pointer}/content/${escape(mediaType)}/schema`, documented: true }; +} + +test('openapi: the document is OpenAPI 3.1 and versioned like the service', () => { + assert.equal(spec['openapi'], '3.1.0'); + assert.equal(spec['jsonSchemaDialect'], 'https://json-schema.org/draft/2020-12/schema'); + const pkg = readJson(join(REPO, 'apps', 'server', 'package.json')); + assert.equal((spec['info'] as Obj)['version'], pkg['version']); + const ids = operations().map((o) => o.op['operationId']); + assert.equal(new Set(ids).size, ids.length, 'operationIds are unique'); +}); + +test('openapi: every route the service dispatches is described, and nothing else', () => { + const described = operations() + .filter((o) => o.path.startsWith('/api/')) + .map((o) => `${o.method} ${o.path} ${String(o.op['operationId'])}`) + .sort(); + const served = API_ROUTES.map((r) => `${r.method} ${r.path} ${r.operationId}`).sort(); + assert.deepEqual(described, served); + // outside /api/ the description has only the web UI entry point + const other = operations().filter((o) => !o.path.startsWith('/api/')); + assert.deepEqual( + other.map((o) => `${o.method} ${o.path}`), + ['GET /'], + ); + assert.deepEqual(other[0]!.op['tags'], ['web']); + // path parameters are declared for every templated segment + for (const o of operations()) { + const names = [...o.path.matchAll(/\{([^}]+)\}/g)].map((m) => m[1]); + const item = paths[o.path]!; + const params = [...((item['parameters'] ?? []) as unknown[]), ...((o.op['parameters'] ?? []) as unknown[])].map( + (p) => deref(spec, p, o.pointer).node, + ); + for (const n of names) assert.ok(params.some((p) => p['name'] === n && p['in'] === 'path' && p['required'] === true), `${o.path}: ${n}`); + } +}); + +test('openapi: the route matcher accepts the described paths only', () => { + const id = 'a'.repeat(32); + assert.equal(matchApiRoute('GET', `/api/jobs/${id}`)?.params['id'], id); + assert.equal(matchApiRoute('POST', `/api/jobs/${id}/stop`)?.operationId, 'stopJob'); + assert.equal(matchApiRoute('GET', `/api/jobs/${id}/stop`), null); + assert.equal(matchApiRoute('GET', '/api/jobs/'), null); + assert.equal(matchApiRoute('GET', '/api/jobs//bundle'), null); + assert.equal(matchApiRoute('GET', '/api/capabilities/'), null); + assert.equal(matchApiRoute('HEAD', '/api/capabilities'), null); +}); + +test('openapi: every reference resolves and every schema is supported by the validator', () => { + const reg = registry(); + const walk = (node: unknown, ptr: string, inSchema: boolean): void => { + if (Array.isArray(node)) return node.forEach((n, i) => walk(n, `${ptr}/${i}`, inSchema)); + if (!node || typeof node !== 'object') return; + const o = node as Obj; + if (typeof o['$ref'] === 'string' && !inSchema) deref(spec, o, ptr); + for (const [k, v] of Object.entries(o)) { + if (k === 'example' || k === 'examples') continue; + if (k === 'schema' && !inSchema) { + reg.assertSupported(`${DOC_URI}#${ptr}/schema`); + continue; + } + walk(v, `${ptr}/${escape(k)}`, inSchema); + } + }; + walk(spec, '', false); + const schemas = ((spec['components'] as Obj)['schemas'] ?? {}) as Obj; + for (const name of Object.keys(schemas)) reg.assertSupported(`${DOC_URI}#/components/schemas/${name}`); +}); + +test('openapi: recorded examples validate against the referenced schemas', () => { + const reg = registry(); + let checked = 0; + for (const o of operations()) { + const body = o.op['requestBody'] as Obj | undefined; + if (body) { + const media = (body['content'] as Obj)['application/json'] as Obj; + for (const [name, e] of Object.entries((media['examples'] ?? {}) as Record)) { + const where = `${o.op['operationId']} request ${name}`; + assert.deepEqual(reg.validate(`${DOC_URI}#${o.pointer}/requestBody/content/application~1json/schema`, e['value']), [], where); + const v = o.op['operationId'] === 'submitAnalysis' ? validateAnalysisRequest(e['value']) : validateExperimentRequest(e['value']); + assert.ok(v.ok, `${where}: ${JSON.stringify(v.ok ? null : v.errors)}`); + checked++; + } + } + for (const status of Object.keys(o.op['responses'] as Obj)) { + const r = deref(spec, (o.op['responses'] as Obj)[status], `${o.pointer}/responses/${status}`); + for (const [mediaType, media] of Object.entries((r.node['content'] ?? {}) as Record)) { + for (const [name, e] of Object.entries((media['examples'] ?? {}) as Record)) { + const issues = reg.validate(`${DOC_URI}#${r.pointer}/content/${escape(mediaType)}/schema`, e['value']); + assert.deepEqual(issues, [], `${o.op['operationId']} ${status} ${name}`); + checked++; + } + } + } + } + assert.ok(checked >= 25, `${checked} examples checked`); + // a corrupted example is caught + const job = (resolveJsonPointer(spec, '/paths/~1api~1jobs~1{id}/get/responses/200/content/application~1json/examples/completed/value') as Obj); + const broken = { ...job, state: 'finished' }; + assert.ok(reg.validate(`${DOC_URI}#/paths/~1api~1jobs~1{id}/get/responses/200/content/application~1json/schema`, broken).length > 0); +}); + +test('openapi: every error code the handler can produce is documented', () => { + const src = readFileSync(join(REPO, 'apps', 'server', 'src', 'server.ts'), 'utf8'); + const codes = new Set(); + const statuses = new Set(); + for (const m of src.matchAll(/(?:sendError\(res, |new HttpError\()(\d{3}), '([a-z-]+)'/g)) { + statuses.add(Number(m[1])); + codes.add(m[2]!); + } + // the fallback for unknown API paths picks 404 or 405 + for (const m of src.matchAll(/\? (\d{3}) : (\d{3}), \w+ \? '([a-z-]+)' : '([a-z-]+)'/g)) { + statuses.add(Number(m[1])).add(Number(m[2])); + codes.add(m[3]!).add(m[4]!); + } + for (const c of ['forbidden', 'bad-json', 'invalid-request', 'unsupported-media-type', 'body-too-large', 'not-found', 'method-not-allowed', 'queue-full', 'not-ready', 'internal']) { + assert.ok(codes.has(c), `the handler source no longer produces ${c}; update this test and the description`); + } + const errorSchema = readJson(join(SCHEMAS, 'error.schema.json')); + for (const c of codes) assert.ok(String(errorSchema['description']).includes(c), `error code ${c} is not documented in error.schema.json`); + const documented = new Set(operations().flatMap((o) => Object.keys(o.op['responses'] as Obj).map(Number))); + const info = String((spec['info'] as Obj)['description']); + for (const s of statuses) assert.ok(documented.has(s) || info.includes(String(s)), `status ${s} is not documented`); +}); + +test('openapi: the bundled document is self-contained and equivalent', () => { + const read = (f: string) => readJson(join(SCHEMAS, f)) as never; + const bundled = bundleOpenApi(spec as never, read) as Obj; + const text = JSON.stringify(bundled); + assert.ok(!/"\$ref":"[^#]/.test(text), 'no external references remain'); + assert.ok(!text.includes('"$id"'), 'embedded schemas carry no $id'); + const schemas = (bundled['components'] as Obj)['schemas'] as Obj; + for (const f of ['job.schema.json', 'capabilities.schema.json', 'error.schema.json', 'analysis-report.schema.json']) { + assert.ok(schemas[componentName(f)], f); + } + // validate the examples against the bundled document alone: no schema files registered + const reg = registry(bundled, false); + for (const o of operations(bundled)) { + for (const status of Object.keys(o.op['responses'] as Obj)) { + const r = deref(bundled, (o.op['responses'] as Obj)[status], `${o.pointer}/responses/${status}`); + for (const [mediaType, media] of Object.entries((r.node['content'] ?? {}) as Record)) { + reg.assertSupported(`${DOC_URI}#${r.pointer}/content/${escape(mediaType)}/schema`); + for (const [name, e] of Object.entries((media['examples'] ?? {}) as Record)) { + assert.deepEqual(reg.validate(`${DOC_URI}#${r.pointer}/content/${escape(mediaType)}/schema`, e['value']), [], `${o.pointer} ${status} ${name}`); + } + } + } + } + assert.throws(() => bundleOpenApi({ a: { $ref: '../secret.json' } }, read), /unexpected schema reference/); +}); + +interface Res { + status: number; + headers: Record; + body: Buffer; +} + +function call(port: number, method: string, path: string, opts: { body?: string | Buffer; headers?: Record } = {}): Promise { + return new Promise((resolve, reject) => { + const req = request({ host: '127.0.0.1', port, method, path, headers: { ...(opts.body !== undefined ? { 'content-type': 'application/json' } : {}), ...opts.headers } }, (res) => { + const chunks: Buffer[] = []; + res.on('data', (c: Buffer) => chunks.push(c)); + res.on('end', () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body: Buffer.concat(chunks) })); + }); + req.on('error', (e: NodeJS.ErrnoException) => { + if (e.code === 'EPIPE' || e.code === 'ECONNRESET') resolve({ status: -1, headers: {}, body: Buffer.alloc(0) }); + else reject(e); + }); + if (opts.body !== undefined) req.end(opts.body); + else req.end(); + }); +} + +test('openapi: live responses of the service conform to the description', async () => { + const { root, env } = makeFixture(); + cpSync(SCHEMAS, join(root, 'schemas'), { recursive: true }); + const jobs = new JobManager({ env }); + const server = createApp({ env, jobs, host: '127.0.0.1', port: 0, webDist: null }); + await new Promise((r) => server.listen(0, '127.0.0.1', () => r())); + const port = (server.address() as AddressInfo).port; + const reg = registry(); + const byId = new Map(operations().map((o) => [String(o.op['operationId']), o])); + const seen = new Set(); + const conform = (operationId: string, res: Res): unknown => { + const o = byId.get(operationId)!; + const type = String(res.headers['content-type'] ?? '').split(';')[0]!.trim(); + const { pointer, documented } = responseSchema(spec, o, res.status, type); + assert.ok(documented, `${operationId}: ${res.status} ${type} is not documented`); + seen.add(`${operationId} ${res.status}`); + if (type !== 'application/json') return null; + const body = JSON.parse(res.body.toString('utf8')) as unknown; + assert.deepEqual(reg.validate(`${DOC_URI}#${pointer}`, body), [], `${operationId} ${res.status}`); + return body; + }; + try { + conform('getCapabilities', await call(port, 'GET', '/api/capabilities')); + const served = conform('getOpenApi', await call(port, 'GET', '/api/openapi.json')) as Obj; + assert.equal(served['openapi'], '3.1.0'); + assert.ok(!/"\$ref":"[^#]/.test(JSON.stringify(served)), 'the served document has no external references'); + conform('getWebUi', await call(port, 'GET', '/')); + + conform('submitAnalysis', await call(port, 'POST', '/api/analyses', { body: '{not json' })); + conform('submitAnalysis', await call(port, 'POST', '/api/analyses', { body: JSON.stringify({ design: { ...AES_DESIGN, rounds: 3 } }) })); + conform('submitAnalysis', await call(port, 'POST', '/api/analyses', { body: '{}', headers: { 'content-type': 'text/plain' } })); + const big = await call(port, 'POST', '/api/analyses', { body: Buffer.alloc(300 * 1024, 0x20) }); + if (big.status !== -1) conform('submitAnalysis', big); + conform('submitExperiment', await call(port, 'POST', '/api/experiments', { body: JSON.stringify({ design: AES_DESIGN, profile: 'fast' }) })); + conform('submitAnalysis', await call(port, 'POST', '/api/analyses', { body: JSON.stringify({ design: AES_DESIGN }), headers: { origin: 'http://evil.example' } })); + conform('getCapabilities', await call(port, 'GET', '/api/capabilities', { headers: { host: `evil.example:${port}` } })); + + const accepted = await call(port, 'POST', '/api/analyses', { body: JSON.stringify({ design: AES_DESIGN }) }); + const id = (conform('submitAnalysis', accepted) as { job: { id: string } }).job.id; + assert.equal(accepted.headers['location'], `/api/jobs/${id}`); + const early = await call(port, 'GET', `/api/jobs/${id}/bundle`); + if (early.status === 409) conform('getJobBundle', early); + await jobs.idle(); + const done = conform('getJob', await call(port, 'GET', `/api/jobs/${id}`)) as { state: string; bundle: boolean }; + assert.equal(done.state, 'completed'); + assert.equal(done.bundle, true); + const bundle = await call(port, 'GET', `/api/jobs/${id}/bundle`); + conform('getJobBundle', bundle); + assert.match(String(bundle.headers['content-disposition']), new RegExp(`cryptificate-${id}\\.tar\\.gz`)); + conform('stopJob', await call(port, 'POST', `/api/jobs/${id}/stop`)); + + const missing = 'f'.repeat(32); + conform('getJob', await call(port, 'GET', `/api/jobs/${missing}`)); + conform('stopJob', await call(port, 'POST', `/api/jobs/${missing}/stop`)); + conform('getJobBundle', await call(port, 'GET', `/api/jobs/${missing}/bundle`)); + + // a cancelled job without a report has no bundle + const exp = await call(port, 'POST', '/api/experiments', { body: JSON.stringify({ design: AES_DESIGN, profile: 'quick' }) }); + const expId = (conform('submitExperiment', exp) as { job: { id: string } }).job.id; + conform('stopJob', await call(port, 'POST', `/api/jobs/${expId}/stop`)); + await jobs.idle(); + const stopped = conform('getJob', await call(port, 'GET', `/api/jobs/${expId}`)) as { state: string; bundle: boolean }; + if (!stopped.bundle) { + const none = await call(port, 'GET', `/api/jobs/${expId}/bundle`); + conform('getJobBundle', none); + assert.equal(JSON.parse(none.body.toString()).error.code, 'not-ready'); + } + + // methods the description does not list are not served on described paths + for (const [path, item] of Object.entries(paths)) { + if (!path.startsWith('/api/')) continue; + const concrete = path.replace('{id}', id); + for (const m of ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']) { + if (item[m.toLowerCase()]) continue; + const r = await call(port, m, concrete, m === 'POST' || m === 'PUT' || m === 'PATCH' ? { body: '{}' } : {}); + assert.ok(r.status === 404 || r.status === 405, `${m} ${path} answered ${r.status}`); + } + } + for (const s of ['submitAnalysis 400', 'submitAnalysis 403', 'submitAnalysis 415', 'getCapabilities 403', 'getJob 404', 'getJobBundle 200', 'stopJob 200']) { + assert.ok(seen.has(s), `not exercised: ${s}`); + } + } finally { + jobs.stopAll(); + await jobs.idle(); + await new Promise((r) => server.close(() => r())); + rmSync(root, { recursive: true, force: true }); + } +}); + +test('openapi: a checkout without the description answers 404', async () => { + const { root, env } = makeFixture(); + const jobs = new JobManager({ env }); + const server = createApp({ env, jobs, host: '127.0.0.1', port: 0, webDist: null }); + await new Promise((r) => server.listen(0, '127.0.0.1', () => r())); + try { + const res = await call((server.address() as AddressInfo).port, 'GET', '/api/openapi.json'); + assert.equal(res.status, 404); + assert.equal(JSON.parse(res.body.toString()).error.code, 'not-found'); + } finally { + await new Promise((r) => server.close(() => r())); + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/schemas/openapi.json b/schemas/openapi.json new file mode 100644 index 0000000..3157a38 --- /dev/null +++ b/schemas/openapi.json @@ -0,0 +1,1755 @@ +{ + "openapi": "3.1.0", + "jsonSchemaDialect": "https://json-schema.org/draft/2020-12/schema", + "info": { + "title": "Cryptificate local service", + "version": "0.1.0", + "summary": "Submit designs and circuits for Lean-checked analysis, run experiments, poll jobs and download evidence bundles.", + "description": "HTTP API of `cryptificate serve`, the local Cryptificate service. The web workbench, the `cryptificate` command line and the Python client (`python/cryptificate`) all use it.\n\n**Scope.** This document describes every route the service answers. Request and report bodies are described by the JSON Schemas in `schemas/` (referenced here with `$ref`); the served copy at `GET /api/openapi.json` embeds them under `components/schemas`. Examples are responses recorded from a live service (version 0.1.0, release engine, Lean checker), except the 500 example, which shows the fixed body of that response. Field elements are strings: two hex digits for GF(2^8), canonical decimals below the modulus for BN254.\n\n**Security model.** The service is a single-user local tool and has no authentication. It binds to 127.0.0.1 by default; `--host` can bind elsewhere, and then anyone who can reach the address can run jobs. Every request must carry a `Host` header naming a loopback address (`127.0.0.1`, `localhost`, `::1`) or the bound host, which rejects DNS-rebinding pages. State-changing requests (every method other than GET, HEAD and OPTIONS) are accepted only same-origin: when an `Origin` header is present it must be `http://:` of this service or one of the origins given with `--allow-origin` / `CRYPTIFICATE_ALLOWED_ORIGINS`; without `Origin`, a `Sec-Fetch-Site` header other than `same-origin` or `none` is rejected. Clients outside a browser (curl, Python) send neither header and are accepted. A rejected request gets 403 `forbidden`. There are no CORS headers: cross-origin browser reads are not supported. Every response carries `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer` and `Cross-Origin-Resource-Policy: same-origin`.\n\n**Limits.** JSON bodies are at most 256 KiB (413 beyond, and the connection is closed). One job runs at a time and at most two wait behind it (`limits.maxQueued` in the capabilities); a further submission gets 429 with `Retry-After: 30`. There is no per-client rate limit beyond this queue. Each job runs under a time budget (`limits.analysisBudgetSeconds`, or the experiment profile's `budget.totalSeconds`), and each Lean run under `limits.leanTimeoutSeconds`.\n\n**Job lifecycle.** `POST /api/analyses` or `POST /api/experiments` answers 202 with a job summary and a `Location` header. The job moves `queued` -> `running` -> one of `completed`, `failed`, `timeout`, `cancelled` or `invalid` (terminal). Poll `GET /api/jobs/{id}`: while it runs, `steps` and a partial `report` are visible. When the state is terminal and `bundle` is true, `GET /api/jobs/{id}/bundle` returns the evidence bundle. Jobs survive a restart of the service; a job that was running when the service stopped is reported as `failed` with error code `interrupted`. There is no endpoint that lists jobs; keep the ids you submit.\n\n**Errors.** Every error is JSON with a stable `error.code` (see `ErrorResponse`). Any other path under `/api/` answers 404 `not-found` to GET and POST and 405 `method-not-allowed` to other methods. An unexpected failure answers 500 `internal`.\n\n**Stability.** Paths, status codes, error codes and the members described in the schemas are the supported surface. New optional members may be added to responses; clients should ignore members they do not know. Requests are checked strictly: unknown members are rejected.", + "license": { + "name": "MIT", + "identifier": "MIT" + } + }, + "servers": [ + { + "url": "http://{host}:{port}", + "description": "cryptificate serve (default 127.0.0.1:4173)", + "variables": { + "host": { + "default": "127.0.0.1", + "description": "Bound address; loopback by default." + }, + "port": { + "default": "4173", + "description": "--port or PORT." + } + } + } + ], + "security": [], + "tags": [ + { + "name": "service", + "description": "Service description and capabilities." + }, + { + "name": "jobs", + "description": "Submit, poll and stop analyses and experiments." + }, + { + "name": "bundles", + "description": "Evidence bundles of finished jobs." + }, + { + "name": "web", + "description": "The built web workbench (not part of the JSON API)." + } + ], + "paths": { + "/api/capabilities": { + "get": { + "operationId": "getCapabilities", + "tags": [ + "service" + ], + "summary": "Models, profiles, limits and toolchain availability", + "description": "Reports what this installation can do: the supported design models, the experiment profiles and their budgets, the request and queue limits, and whether the Lean toolchain, rustc and the engine are available. Cheap; the workbench polls it every 15 s.", + "responses": { + "200": { + "description": "Capabilities of this installation.", + "content": { + "application/json": { + "schema": { + "$ref": "capabilities.schema.json" + }, + "examples": { + "live": { + "summary": "A fully installed service", + "value": { + "name": "cryptificate", + "version": "0.1.0", + "checker": "cryptificate 0.1.0 (c27d45c)", + "models": [ + "aes-like/gf256/v1", + "hades/bn254/v1" + ], + "profiles": [ + { + "id": "quick", + "label": "Quick", + "budget": { + "totalSeconds": 180, + "searchMs": 10000, + "maxCandidates": 8, + "shortlist": 1, + "sessions": 3 + } + }, + { + "id": "research", + "label": "Research", + "budget": { + "totalSeconds": 900, + "searchMs": 60000, + "maxCandidates": 64, + "shortlist": 3, + "sessions": 3 + } + } + ], + "limits": { + "maxBodyBytes": 262144, + "maxInstructions": 256, + "maxQueued": 2, + "leanTimeoutSeconds": 180, + "analysisBudgetSeconds": 300 + }, + "toolchain": { + "lean": { + "available": true, + "version": "v4.33.1" + }, + "rust": { + "available": true, + "version": "rustc 1.97.0 (2d8144b78)" + }, + "engine": { + "available": true, + "subcommands": [ + "validate", + "diagnose", + "emit-lean", + "search", + "codegen", + "native" + ], + "version": "cryptificate-engine 0.1.0" + }, + "pins": { + "lean": "v4.33.1", + "mathlib": "v4.33.1", + "widetrail": "162c0f8a9e59841032ec5d66874fee31cf3b6298", + "rustc": "rustc 1.97.0 (2d8144b78)" + } + } + } + } + } + } + } + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "500": { + "$ref": "#/components/responses/Internal" + } + } + } + }, + "/api/openapi.json": { + "get": { + "operationId": "getOpenApi", + "tags": [ + "service" + ], + "summary": "This OpenAPI description", + "description": "The OpenAPI 3.1 description of this API, self-contained: the JSON Schemas from `schemas/` are embedded under `components/schemas` and every `$ref` is local.", + "responses": { + "200": { + "description": "The bundled OpenAPI document.", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "openapi", + "info", + "paths", + "components" + ], + "properties": { + "openapi": { + "const": "3.1.0" + } + } + } + } + } + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "description": "This installation has no schemas/openapi.json (`not-found`).", + "content": { + "application/json": { + "schema": { + "$ref": "error.schema.json" + }, + "examples": { + "missing": { + "summary": "Service started from a checkout without the description", + "value": { + "error": { + "code": "not-found", + "message": "this installation has no schemas/openapi.json" + } + } + } + } + } + } + }, + "500": { + "$ref": "#/components/responses/Internal" + } + } + } + }, + "/api/analyses": { + "post": { + "operationId": "submitAnalysis", + "tags": [ + "jobs" + ], + "summary": "Submit an analysis", + "description": "Checks a candidate design, and optionally a linear circuit against one of its matrices. The body is shape-checked before a job is created (400 on any problem, with every issue listed); the engine then validates it in depth as the job's first step, so a request that passes the shape check can still end in state `invalid`.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "analysis-request.schema.json" + }, + "examples": { + "wrong-wire": { + "summary": "AES design with a mis-wired MixColumns circuit", + "value": { + "design": { + "model": "aes-like/gf256/v1", + "field": "gf256", + "width": 4, + "matrix": [ + [ + "02", + "03", + "01", + "01" + ], + [ + "01", + "02", + "03", + "01" + ], + [ + "01", + "01", + "02", + "03" + ], + [ + "03", + "01", + "01", + "02" + ] + ], + "offsets": [ + 0, + 1, + 2, + 3 + ], + "rounds": 4, + "sbox": { + "kind": "aes" + } + }, + "program": { + "field": "gf256", + "width": 4, + "name": "aes-shared-sum-wrong-wire", + "instructions": [ + { + "op": "add", + "a": 0, + "b": 1 + }, + { + "op": "add", + "a": 4, + "b": 2 + }, + { + "op": "add", + "a": 5, + "b": 3 + }, + { + "op": "add", + "a": 0, + "b": 2 + }, + { + "op": "mul", + "k": "02", + "a": 7 + }, + { + "op": "add", + "a": 0, + "b": 8 + }, + { + "op": "add", + "a": 9, + "b": 6 + }, + { + "op": "add", + "a": 1, + "b": 2 + }, + { + "op": "mul", + "k": "02", + "a": 11 + }, + { + "op": "add", + "a": 1, + "b": 12 + }, + { + "op": "add", + "a": 13, + "b": 6 + }, + { + "op": "add", + "a": 2, + "b": 3 + }, + { + "op": "mul", + "k": "02", + "a": 15 + }, + { + "op": "add", + "a": 2, + "b": 16 + }, + { + "op": "add", + "a": 17, + "b": 6 + }, + { + "op": "add", + "a": 3, + "b": 0 + }, + { + "op": "mul", + "k": "02", + "a": 19 + }, + { + "op": "add", + "a": 3, + "b": 20 + }, + { + "op": "add", + "a": 21, + "b": 6 + } + ], + "outputs": [ + 10, + 14, + 18, + 22 + ] + } + } + }, + "design-only": { + "summary": "Row-scaled AES matrix, no circuit", + "value": { + "design": { + "model": "aes-like/gf256/v1", + "field": "gf256", + "width": 4, + "matrix": [ + [ + "04", + "06", + "02", + "02" + ], + [ + "01", + "02", + "03", + "01" + ], + [ + "01", + "01", + "02", + "03" + ], + [ + "03", + "01", + "01", + "02" + ] + ], + "offsets": [ + 0, + 1, + 2, + 3 + ], + "rounds": 4, + "sbox": { + "kind": "aes" + } + } + } + } + } + } + } + }, + "responses": { + "202": { + "$ref": "#/components/responses/Accepted" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "413": { + "$ref": "#/components/responses/TooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, + "429": { + "$ref": "#/components/responses/QueueFull" + }, + "500": { + "$ref": "#/components/responses/Internal" + } + } + } + }, + "/api/experiments": { + "post": { + "operationId": "submitExperiment", + "tags": [ + "jobs" + ], + "summary": "Submit an experiment", + "description": "Searches for cheaper circuits for the design's matrix, checks each shortlisted candidate's equivalence in Lean, tests the generated Rust and times it against baselines under the chosen profile's budget. Same submission rules as analyses.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "experiment-request.schema.json" + }, + "examples": { + "quick": { + "summary": "Quick profile with a fixed seed", + "value": { + "design": { + "model": "aes-like/gf256/v1", + "field": "gf256", + "width": 4, + "matrix": [ + [ + "02", + "03", + "01", + "01" + ], + [ + "01", + "02", + "03", + "01" + ], + [ + "01", + "01", + "02", + "03" + ], + [ + "03", + "01", + "01", + "02" + ] + ], + "offsets": [ + 0, + 1, + 2, + 3 + ], + "rounds": 4, + "sbox": { + "kind": "aes" + } + }, + "profile": "quick", + "seed": "c0ffee" + } + } + } + } + } + }, + "responses": { + "202": { + "$ref": "#/components/responses/Accepted" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "413": { + "$ref": "#/components/responses/TooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, + "429": { + "$ref": "#/components/responses/QueueFull" + }, + "500": { + "$ref": "#/components/responses/Internal" + } + } + } + }, + "/api/jobs/{id}": { + "parameters": [ + { + "$ref": "#/components/parameters/JobId" + } + ], + "get": { + "operationId": "getJob", + "tags": [ + "jobs" + ], + "summary": "Poll a job", + "description": "Current state, progress steps, queue position (while queued), error (when one occurred) and the report, which is partial while the job runs and final once the state is terminal. Poll until `state` is one of completed, failed, timeout, cancelled or invalid; the workbench polls every 800 ms, and once a second is plenty for scripts.", + "responses": { + "200": { + "description": "The job.", + "content": { + "application/json": { + "schema": { + "$ref": "job.schema.json" + }, + "examples": { + "queued": { + "summary": "Waiting behind other jobs", + "value": { + "id": "9393c161324a988ffe38d84fc90e3b93", + "kind": "experiment", + "state": "queued", + "origin": "live", + "steps": [ + { + "name": "validate", + "state": "pending" + }, + { + "name": "search", + "state": "pending" + }, + { + "name": "equivalence", + "state": "pending" + }, + { + "name": "native-correctness", + "state": "pending" + }, + { + "name": "benchmark-1", + "state": "pending" + }, + { + "name": "benchmark-2", + "state": "pending" + }, + { + "name": "benchmark-3", + "state": "pending" + }, + { + "name": "report", + "state": "pending" + } + ], + "report": null, + "bundle": false, + "queuePosition": 2 + } + }, + "running": { + "summary": "Running, with checkpoints and a partial report", + "value": { + "id": "9d4777dbeae6b987f0e2ce28b7993cfe", + "kind": "analysis", + "state": "running", + "origin": "live", + "steps": [ + { + "name": "validate", + "state": "completed", + "ms": 5 + }, + { + "name": "diagnose", + "state": "completed", + "ms": 4 + }, + { + "name": "emit-lean", + "state": "completed", + "ms": 9, + "detail": "5 theorem(s)" + }, + { + "name": "lean", + "state": "running", + "detail": "limit 180 s" + }, + { + "name": "native", + "state": "pending" + }, + { + "name": "report", + "state": "pending" + } + ], + "report": { + "kind": "analysis", + "id": "9d4777dbeae6b987f0e2ce28b7993cfe", + "inputDigest": "sha256:fb9a76f86cec3c4047858db76c1f6e3b2ea8ce785ddefc6480b1858609b0b698", + "inputs": { + "design": { + "field": "gf256", + "matrix": [ + [ + "02", + "03", + "01", + "01" + ], + [ + "01", + "02", + "03", + "01" + ], + [ + "01", + "01", + "02", + "03" + ], + [ + "03", + "01", + "01", + "02" + ] + ], + "model": "aes-like/gf256/v1", + "offsets": [ + 0, + 1, + 2, + 3 + ], + "rounds": 4, + "sbox": { + "kind": "aes" + }, + "width": 4 + }, + "program": { + "field": "gf256", + "instructions": [ + { + "a": 0, + "b": 1, + "op": "add" + }, + { + "a": 4, + "b": 2, + "op": "add" + }, + { + "a": 5, + "b": 3, + "op": "add" + }, + { + "a": 0, + "b": 2, + "op": "add" + }, + { + "a": 7, + "k": "02", + "op": "mul" + }, + { + "a": 0, + "b": 8, + "op": "add" + }, + { + "a": 9, + "b": 6, + "op": "add" + }, + { + "a": 1, + "b": 2, + "op": "add" + }, + { + "a": 11, + "k": "02", + "op": "mul" + }, + { + "a": 1, + "b": 12, + "op": "add" + }, + { + "a": 13, + "b": 6, + "op": "add" + }, + { + "a": 2, + "b": 3, + "op": "add" + }, + { + "a": 15, + "k": "02", + "op": "mul" + }, + { + "a": 2, + "b": 16, + "op": "add" + }, + { + "a": 17, + "b": 6, + "op": "add" + }, + { + "a": 3, + "b": 0, + "op": "add" + }, + { + "a": 19, + "k": "02", + "op": "mul" + }, + { + "a": 3, + "b": 20, + "op": "add" + }, + { + "a": 21, + "b": 6, + "op": "add" + } + ], + "name": "aes-shared-sum-wrong-wire", + "outputs": [ + 10, + 14, + 18, + 22 + ], + "width": 4 + }, + "target": "matrix" + }, + "claims": [], + "execution": { + "state": "running", + "steps": [ + { + "name": "validate", + "state": "completed", + "ms": 5 + } + ] + }, + "provenance": { + "origin": "live", + "checker": "cryptificate 0.1.0 (c27d45c)", + "toolchain": { + "lean": "v4.33.1", + "mathlib": "v4.33.1", + "widetrail": "162c0f8a9e59841032ec5d66874fee31cf3b6298", + "rustc": "rustc 1.97.0 (2d8144b78)" + } + } + }, + "bundle": false + } + }, + "completed": { + "summary": "Finished: design claims proved, the mis-wired circuit refuted with a witness", + "value": { + "id": "9d4777dbeae6b987f0e2ce28b7993cfe", + "kind": "analysis", + "state": "completed", + "origin": "live", + "steps": [ + { + "name": "validate", + "state": "completed", + "ms": 5 + }, + { + "name": "diagnose", + "state": "completed", + "ms": 4 + }, + { + "name": "emit-lean", + "state": "completed", + "ms": 9, + "detail": "5 theorem(s)" + }, + { + "name": "lean", + "state": "completed", + "detail": "5/5 theorem(s) accepted", + "ms": 5242 + }, + { + "name": "native", + "state": "completed", + "ms": 25268 + }, + { + "name": "report", + "state": "completed", + "ms": 1 + } + ], + "report": { + "kind": "analysis", + "id": "9d4777dbeae6b987f0e2ce28b7993cfe", + "inputDigest": "sha256:fb9a76f86cec3c4047858db76c1f6e3b2ea8ce785ddefc6480b1858609b0b698", + "inputs": { + "design": { + "field": "gf256", + "matrix": [ + [ + "02", + "03", + "01", + "01" + ], + [ + "01", + "02", + "03", + "01" + ], + [ + "01", + "01", + "02", + "03" + ], + [ + "03", + "01", + "01", + "02" + ] + ], + "model": "aes-like/gf256/v1", + "offsets": [ + 0, + 1, + 2, + 3 + ], + "rounds": 4, + "sbox": { + "kind": "aes" + }, + "width": 4 + }, + "program": { + "field": "gf256", + "instructions": [ + { + "a": 0, + "b": 1, + "op": "add" + }, + { + "a": 4, + "b": 2, + "op": "add" + }, + { + "a": 5, + "b": 3, + "op": "add" + }, + { + "a": 0, + "b": 2, + "op": "add" + }, + { + "a": 7, + "k": "02", + "op": "mul" + }, + { + "a": 0, + "b": 8, + "op": "add" + }, + { + "a": 9, + "b": 6, + "op": "add" + }, + { + "a": 1, + "b": 2, + "op": "add" + }, + { + "a": 11, + "k": "02", + "op": "mul" + }, + { + "a": 1, + "b": 12, + "op": "add" + }, + { + "a": 13, + "b": 6, + "op": "add" + }, + { + "a": 2, + "b": 3, + "op": "add" + }, + { + "a": 15, + "k": "02", + "op": "mul" + }, + { + "a": 2, + "b": 16, + "op": "add" + }, + { + "a": 17, + "b": 6, + "op": "add" + }, + { + "a": 3, + "b": 0, + "op": "add" + }, + { + "a": 19, + "k": "02", + "op": "mul" + }, + { + "a": 3, + "b": 20, + "op": "add" + }, + { + "a": 21, + "b": 6, + "op": "add" + } + ], + "name": "aes-shared-sum-wrong-wire", + "outputs": [ + 10, + 14, + 18, + 22 + ], + "width": 4 + }, + "target": "matrix" + }, + "claims": [ + { + "id": "matrix.mds", + "chain": "design", + "title": "Matrix is MDS (branch number 5)", + "status": "proved", + "evidence": { + "kind": "lean", + "label": "Lean-checked proof", + "theorem": "CryptificateJob.matrix_mds", + "type": "IsMDS CryptificateJob.candMatrix", + "axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "witness": null, + "note": "Lean checked CryptificateJob.matrix_mds using only the standard axioms." + }, + { + "id": "offsets.dispersion", + "chain": "design", + "title": "Row offsets are pairwise distinct", + "status": "proved", + "evidence": { + "kind": "lean", + "label": "Lean-checked proof", + "theorem": "CryptificateJob.offsets_optimal", + "type": "DiffusionOptimal (gridCol 4 4) (shiftRowsPerm 4 4 CryptificateJob.candOffsets)", + "axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "witness": null, + "note": "Lean checked CryptificateJob.offsets_optimal using only the standard axioms." + }, + { + "id": "sbox.bijective", + "chain": "design", + "title": "S-box is a permutation", + "status": "proved", + "evidence": { + "kind": "lean", + "label": "Lean-checked proof", + "theorem": "CryptificateJob.sbox_bijective", + "type": "Function.Bijective CryptificateJob.candSboxTable", + "axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "witness": null, + "note": "Lean checked CryptificateJob.sbox_bijective using only the standard axioms." + }, + { + "id": "activity.bound", + "chain": "design", + "title": "At least 25 active S-boxes over 4 rounds", + "status": "proved", + "evidence": { + "kind": "lean", + "label": "Lean-checked proof", + "theorem": "CryptificateJob.activity_bound", + "type": "∀ (sbox : GF256 → GF256), Function.Injective sbox → ∀ (keys : ℕ → Fin 16 → GF256) (x y : Fin 16 → GF256), x ≠ y → (CryptificateJob.candRounds / 4 * 25 + if 2 ≤ CryptificateJob.candRounds % 4 then 5 else 0) ≤ Cryptificate.activeSboxes CryptificateJob.candMatrix CryptificateJob.candOffsets sbox keys x y CryptificateJob.candRounds", + "axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "witness": null, + "note": "Lean checked CryptificateJob.activity_bound using only the standard axioms." + }, + { + "id": "circuit.equivalence", + "chain": "implementation", + "title": "Circuit computes the design matrix", + "status": "refuted", + "evidence": { + "kind": "lean", + "label": "Lean-checked counterexample", + "theorem": "CryptificateJob.circuit_mismatch", + "type": "CryptificateJob.candProgram.WellFormed ∧ CryptificateJob.candMatrix.mulVec CryptificateJob.witnessInput = CryptificateJob.witnessExpected ∧ CryptificateJob.candProgram.eval CryptificateJob.witnessInput = CryptificateJob.witnessActual ∧ ¬∀ (x : Fin 4 → GF256), CryptificateJob.candProgram.eval x = CryptificateJob.candMatrix.mulVec x", + "axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "witness": { + "actual": [ + "01", + "02", + "01", + "01" + ], + "differing": [ + 0 + ], + "expected": [ + "03", + "02", + "01", + "01" + ], + "input": [ + "00", + "01", + "00", + "00" + ], + "kind": "distinguishing-input" + }, + "note": "Lean checked a counterexample (CryptificateJob.circuit_mismatch)." + }, + { + "id": "native.correctness", + "chain": "implementation", + "title": "Generated Rust matches the reference", + "status": "refuted", + "evidence": { + "kind": "native", + "label": "Generated Rust passed 549 correctness cases", + "cases": 9215 + }, + "witness": { + "actual": [ + "01", + "02", + "01", + "01" + ], + "differing": [ + 0 + ], + "expected": [ + "03", + "02", + "01", + "01" + ], + "input": [ + "00", + "01", + "00", + "00" + ], + "kind": "distinguishing-input" + }, + "note": "8666 of 9215 cases gave a wrong output." + }, + { + "id": "rust.refinement", + "chain": "implementation", + "title": "Rust kernel refines the Lean model", + "status": "not_established", + "evidence": { + "kind": "diagnostic", + "label": "Unchecked diagnostic" + }, + "witness": null, + "note": "The refinement proofs have not been checked on this machine (scripts/setup.sh --with-refinement).", + "reason": "out-of-scope" + }, + { + "id": "native.timing", + "chain": "implementation", + "title": "Native speed on this machine", + "status": "not_established", + "evidence": { + "kind": "diagnostic", + "label": "Unchecked diagnostic" + }, + "witness": null, + "note": "Timing is measured by experiments, not by an analysis.", + "reason": "not-run" + } + ], + "execution": { + "state": "completed", + "steps": [ + { + "name": "validate", + "state": "completed", + "ms": 5 + }, + { + "name": "diagnose", + "state": "completed", + "ms": 4 + }, + { + "name": "emit-lean", + "state": "completed", + "ms": 9, + "detail": "5 theorem(s)" + }, + { + "name": "lean", + "state": "completed", + "detail": "5/5 theorem(s) accepted", + "ms": 5242 + }, + { + "name": "native", + "state": "completed", + "ms": 25268 + }, + { + "name": "report", + "state": "completed", + "ms": 1 + } + ] + }, + "provenance": { + "origin": "live", + "checker": "cryptificate 0.1.0 (c27d45c)", + "toolchain": { + "lean": "v4.33.1", + "mathlib": "v4.33.1", + "widetrail": "162c0f8a9e59841032ec5d66874fee31cf3b6298", + "rustc": "rustc 1.97.0 (2d8144b78)" + }, + "leanSourceSha256": "cd40d3bf3407a7c13554c6be4d9b1a17f8d03e69aa4f5dca6bee8fb5ffb9fa86", + "cacheKey": "dcfd3d75e30c71346967c36af9b78b043e1571dd40f5756710e83a8526512910" + } + }, + "bundle": true + } + }, + "cancelled": { + "summary": "Stopped while queued", + "value": { + "id": "9393c161324a988ffe38d84fc90e3b93", + "kind": "experiment", + "state": "cancelled", + "origin": "live", + "steps": [ + { + "name": "validate", + "state": "not_run" + }, + { + "name": "search", + "state": "not_run" + }, + { + "name": "equivalence", + "state": "not_run" + }, + { + "name": "native-correctness", + "state": "not_run" + }, + { + "name": "benchmark-1", + "state": "not_run" + }, + { + "name": "benchmark-2", + "state": "not_run" + }, + { + "name": "benchmark-3", + "state": "not_run" + }, + { + "name": "report", + "state": "not_run" + } + ], + "report": null, + "bundle": false + } + } + } + } + } + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NoSuchJob" + }, + "500": { + "$ref": "#/components/responses/Internal" + } + } + } + }, + "/api/jobs/{id}/stop": { + "parameters": [ + { + "$ref": "#/components/parameters/JobId" + } + ], + "post": { + "operationId": "stopJob", + "tags": [ + "jobs" + ], + "summary": "Stop a job", + "description": "A queued job is removed from the queue and becomes `cancelled` at once. A running job is signalled (its whole process group is killed) and becomes `cancelled` shortly after; completed checkpoints and the partial report are kept. Stopping a finished job changes nothing. The request body is ignored and no Content-Type is required. The response is the summary at the time of the call, so a running job may still read `running`: poll to see the final state.", + "responses": { + "200": { + "description": "The job summary after the stop request.", + "content": { + "application/json": { + "schema": { + "$ref": "job.schema.json#/$defs/envelope" + }, + "examples": { + "queued": { + "summary": "A queued experiment, stopped", + "value": { + "job": { + "id": "9393c161324a988ffe38d84fc90e3b93", + "kind": "experiment", + "state": "cancelled", + "origin": "live" + } + } + } + } + } + } + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NoSuchJob" + }, + "500": { + "$ref": "#/components/responses/Internal" + } + } + } + }, + "/api/jobs/{id}/bundle": { + "parameters": [ + { + "$ref": "#/components/parameters/JobId" + } + ], + "get": { + "operationId": "getJobBundle", + "tags": [ + "bundles" + ], + "summary": "Download the evidence bundle", + "description": "A deterministic gzip-compressed tar archive with the normalized inputs, the report, the generated Lean certificates and the checker output, the toolchain pins, native sources and measurements when those steps ran, and VERIFY.md. Available when the job is terminal, not `invalid`, and has a report (`bundle: true` in the job). The same job always yields the same bytes. `cryptificate verify ` re-checks it.", + "responses": { + "200": { + "description": "The bundle.", + "headers": { + "Content-Disposition": { + "$ref": "#/components/headers/ContentDisposition" + } + }, + "content": { + "application/gzip": { + "schema": { + "contentMediaType": "application/gzip" + } + } + } + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NoSuchJob" + }, + "409": { + "description": "There is no bundle: the job is still queued or running, ended before producing a report, or its request was invalid.", + "content": { + "application/json": { + "schema": { + "$ref": "error.schema.json" + }, + "examples": { + "running": { + "summary": "The job is still running", + "value": { + "error": { + "code": "not-ready", + "message": "the job has not finished" + } + } + }, + "no-report": { + "summary": "The job was stopped before it produced a report", + "value": { + "error": { + "code": "not-ready", + "message": "the job ended before it produced a report" + } + } + } + } + } + } + }, + "500": { + "$ref": "#/components/responses/Internal" + } + } + } + }, + "/": { + "get": { + "operationId": "getWebUi", + "tags": [ + "web" + ], + "summary": "The web workbench", + "description": "Serves the built workbench from apps/web/dist when it exists: static files, with index.html for any other path without a file extension (client-side routes). Without a built UI, `/` returns a short page that points to the API. HEAD is answered like GET; other methods on non-API paths answer 405. Not part of the JSON API.", + "responses": { + "200": { + "description": "The workbench page.", + "content": { + "text/html": { + "schema": { + "type": "string" + } + } + } + }, + "403": { + "$ref": "#/components/responses/Forbidden" + } + } + } + } + }, + "components": { + "parameters": { + "JobId": { + "name": "id", + "in": "path", + "required": true, + "description": "Job id as returned at submission: 32 lowercase hex digits. Any other value is answered with 404.", + "schema": { + "type": "string", + "pattern": "^[0-9a-f]{32}$" + }, + "example": "9d4777dbeae6b987f0e2ce28b7993cfe" + } + }, + "headers": { + "Location": { + "description": "Path of the new job: /api/jobs/{id}.", + "schema": { + "type": "string" + } + }, + "RetryAfter": { + "description": "Seconds to wait before submitting again (always 30).", + "schema": { + "type": "integer", + "const": 30 + } + }, + "ContentDisposition": { + "description": "attachment; filename=\"cryptificate-.tar.gz\"", + "schema": { + "type": "string" + } + }, + "Connection": { + "description": "close: the service stops reading the oversized body.", + "schema": { + "const": "close" + } + } + }, + "responses": { + "Accepted": { + "description": "The job was created and queued. Poll the job at the `Location` path.", + "headers": { + "Location": { + "$ref": "#/components/headers/Location" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "job.schema.json#/$defs/envelope" + }, + "examples": { + "analysis": { + "summary": "An analysis was queued", + "value": { + "job": { + "id": "9d4777dbeae6b987f0e2ce28b7993cfe", + "kind": "analysis", + "state": "queued", + "origin": "live" + } + } + }, + "experiment": { + "summary": "An experiment was queued", + "value": { + "job": { + "id": "9393c161324a988ffe38d84fc90e3b93", + "kind": "experiment", + "state": "queued", + "origin": "live" + } + } + } + } + } + } + }, + "BadRequest": { + "description": "The body is not JSON (`bad-json`) or not a request of the documented shape (`invalid-request`, with every issue in `errors`, at most 50).", + "content": { + "application/json": { + "schema": { + "$ref": "error.schema.json" + }, + "examples": { + "bad-json": { + "summary": "Not JSON", + "value": { + "error": { + "code": "bad-json", + "message": "request body is not valid JSON" + } + } + }, + "invalid-request": { + "summary": "A number where a field element string belongs, and too few rounds", + "value": { + "error": { + "code": "invalid-request", + "message": "/design/matrix/0/1: field elements are strings, not numbers" + }, + "errors": [ + { + "path": "/design/matrix/0/1", + "code": "type", + "message": "field elements are strings, not numbers" + }, + { + "path": "/design/rounds", + "code": "range", + "message": "expected an integer in 4..32" + } + ] + } + } + } + } + } + }, + "TooLarge": { + "description": "The body exceeds 256 KiB (`body-too-large`). The connection is closed; a client still uploading may see the connection reset instead of this response.", + "content": { + "application/json": { + "schema": { + "$ref": "error.schema.json" + }, + "examples": { + "body-too-large": { + "summary": "300 000 bytes", + "value": { + "error": { + "code": "body-too-large", + "message": "request body exceeds 262144 bytes" + } + } + } + } + } + }, + "headers": { + "Connection": { + "$ref": "#/components/headers/Connection" + } + } + }, + "UnsupportedMediaType": { + "description": "The Content-Type is not application/json (`unsupported-media-type`).", + "content": { + "application/json": { + "schema": { + "$ref": "error.schema.json" + }, + "examples": { + "text-plain": { + "summary": "Content-Type: text/plain", + "value": { + "error": { + "code": "unsupported-media-type", + "message": "expected Content-Type: application/json" + } + } + } + } + } + } + }, + "QueueFull": { + "description": "One job is running and two are queued (`queue-full`). Retry after the indicated delay.", + "content": { + "application/json": { + "schema": { + "$ref": "error.schema.json" + }, + "examples": { + "queue-full": { + "summary": "Fourth submission", + "value": { + "error": { + "code": "queue-full", + "message": "one job is running and the queue is full; try again later" + } + } + } + } + } + }, + "headers": { + "Retry-After": { + "$ref": "#/components/headers/RetryAfter" + } + } + }, + "NoSuchJob": { + "description": "No job has this id (`not-found`). Ids are random. After a restart the service loads the 200 most recently updated jobs from its state directory; older ids answer 404.", + "content": { + "application/json": { + "schema": { + "$ref": "error.schema.json" + }, + "examples": { + "not-found": { + "summary": "Unknown id", + "value": { + "error": { + "code": "not-found", + "message": "no such job" + } + } + } + } + } + } + }, + "Forbidden": { + "description": "The request failed the Host/Origin policy (see the security model above).", + "content": { + "application/json": { + "schema": { + "$ref": "error.schema.json" + }, + "examples": { + "host": { + "summary": "Host header is not a loopback address", + "value": { + "error": { + "code": "forbidden", + "message": "Host header is not a loopback address" + } + } + }, + "origin": { + "summary": "Origin of another site", + "value": { + "error": { + "code": "forbidden", + "message": "cross-origin request rejected" + } + } + }, + "site": { + "summary": "Sec-Fetch-Site: cross-site without Origin", + "value": { + "error": { + "code": "forbidden", + "message": "cross-site request rejected" + } + } + } + } + } + } + }, + "Internal": { + "description": "An unexpected failure in the service (`internal`). Job failures are not reported this way: they are a job in state `failed` with an `error`.", + "content": { + "application/json": { + "schema": { + "$ref": "error.schema.json" + }, + "examples": { + "internal": { + "summary": "Unexpected failure", + "value": { + "error": { + "code": "internal", + "message": "internal error" + } + } + } + } + } + } + } + }, + "schemas": {} + } +} From d574125ec724f86e24a00bbf50341694af8a749b Mon Sep 17 00:00:00 2001 From: tyler-turnpike <188578979+tyler-turnpike@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:28:45 +0000 Subject: [PATCH 5/9] feat(python): a client method for every API operation Adds Client.openapi(), CryptificateError.retry_after for 429 responses, the job, stop and openapi commands, and OPERATIONS mapping each operationId to its method. New tests check that mapping against schemas/openapi.json and run the client against the responses recorded there. The README documents every method, the error fields and every command. --- python/README.md | 53 ++++++++- python/cryptificate/__init__.py | 3 +- python/cryptificate/__main__.py | 19 +++- python/cryptificate/client.py | 43 ++++++- python/tests/test_openapi.py | 193 ++++++++++++++++++++++++++++++++ 5 files changed, 301 insertions(+), 10 deletions(-) create mode 100644 python/tests/test_openapi.py diff --git a/python/README.md b/python/README.md index ae3c2d6..7c6fc52 100644 --- a/python/README.md +++ b/python/README.md @@ -17,18 +17,65 @@ for claim in final["report"]["claims"]: client.bundle(job["id"], "evidence.tar.gz") ``` -Command line (the service must be running): +## Methods + +`Client(base_url="http://127.0.0.1:4173", timeout=30.0)` has one method per operation of the +HTTP API ([`docs/api.md`](../docs/api.md), [`schemas/openapi.json`](../schemas/openapi.json)). +Every method returns the decoded JSON body. + +| Method | Request | Returns | +| --- | --- | --- | +| `capabilities()` | `GET /api/capabilities` | models, profiles, limits, toolchain availability | +| `openapi()` | `GET /api/openapi.json` | the OpenAPI 3.1 description, schemas embedded | +| `analyze(design, program=None, target=None)` | `POST /api/analyses` | the job summary `{id, kind, state, origin}` | +| `experiment(design, program=None, profile="quick", seed=None)` | `POST /api/experiments` | the job summary | +| `job(job_id)` | `GET /api/jobs/{id}` | state, steps, queue position, error and the (partial) report | +| `stop(job_id)` | `POST /api/jobs/{id}/stop` | the job summary at the time of the call | +| `bundle(job_id, path)` | `GET /api/jobs/{id}/bundle` | the path the `.tar.gz` bundle was written to | +| `wait(job_id, poll=1.0, timeout=None, on_progress=None)` | polls `GET /api/jobs/{id}` | the job once its state is terminal | + +`cryptificate.OPERATIONS` maps each `operationId` of the description to its method. + +Error responses raise `CryptificateError` with `status` (the HTTP status, 0 when the service +cannot be reached), `code` (the stable error code: `invalid-request`, `queue-full`, +`not-found`, `not-ready`, ...), `message`, `errors` (the `{path, code, message}` issues of a +400 response) and `retry_after` (seconds, on 429). `wait` raises `wait-timeout` when its own +`timeout` passes; the job keeps running. + +```python +from cryptificate import CryptificateError + +try: + job = client.analyze(design) +except CryptificateError as e: + if e.code == "queue-full": + time.sleep(e.retry_after or 30) # one job runs and two wait; retry later + elif e.code == "invalid-request": + for issue in e.errors: + print(issue["path"], issue["message"]) +``` + +## Command line + +The service must be running: ```sh python -m cryptificate check examples/designs/aes.json --program examples/programs/aes-known-shared-sum.json python -m cryptificate experiment examples/designs/aes.json --profile quick +python -m cryptificate job # print the job as JSON +python -m cryptificate stop +python -m cryptificate bundle evidence.tar.gz python -m cryptificate capabilities +python -m cryptificate openapi ``` -`--url` (or `CRYPTIFICATE_URL`) selects another service address. +`check` and `experiment` submit, wait and print the claims (`--json` and `--bundle` save the +final job and its bundle). `--url` (or `CRYPTIFICATE_URL`) selects another service address. Helpers build requests in the wire format, where field elements are strings: `gf(0x1b) == "1B"`, `bn(-1)` is the canonical decimal of `p - 1`. `ProgramBuilder` assembles linear programs register by register (`add`, `mul`, `xtime`, `sum`). -Tests: `python -m unittest discover -s tests` from this directory. +Tests: `python -m unittest discover -s tests` from this directory. `tests/test_openapi.py` +checks that every operation in `schemas/openapi.json` has a method and runs the client against +the responses recorded there. diff --git a/python/cryptificate/__init__.py b/python/cryptificate/__init__.py index f9d38c5..304f873 100644 --- a/python/cryptificate/__init__.py +++ b/python/cryptificate/__init__.py @@ -5,7 +5,7 @@ is faster. This package talks to `cryptificate serve` over HTTP. """ -from .client import DEFAULT_URL, TERMINAL_STATES, Client, CryptificateError +from .client import DEFAULT_URL, OPERATIONS, TERMINAL_STATES, Client, CryptificateError from .designs import ( AES_MIXCOLUMNS, BN254_MODULUS, @@ -25,6 +25,7 @@ "AES_MIXCOLUMNS", "BN254_MODULUS", "DEFAULT_URL", + "OPERATIONS", "POSEIDON2_EXTERNAL_3", "POSEIDON2_INTERNAL_3", "TERMINAL_STATES", diff --git a/python/cryptificate/__main__.py b/python/cryptificate/__main__.py index 001d991..987676a 100644 --- a/python/cryptificate/__main__.py +++ b/python/cryptificate/__main__.py @@ -1,4 +1,4 @@ -"""Command line: python -m cryptificate check|experiment|capabilities|bundle ...""" +"""Command line: python -m cryptificate check|experiment|job|stop|bundle|capabilities|openapi ...""" from __future__ import annotations @@ -98,6 +98,13 @@ def main(argv: Optional[List[str]] = None) -> int: exp.add_argument("--quiet", "-q", action="store_true") sub.add_parser("capabilities", help="print the service capabilities") + sub.add_parser("openapi", help="print the OpenAPI description of the HTTP API") + + job = sub.add_parser("job", help="print a job (state, steps, report) as JSON") + job.add_argument("job_id") + + stop = sub.add_parser("stop", help="stop a queued or running job") + stop.add_argument("job_id") bundle = sub.add_parser("bundle", help="download a job's evidence bundle") bundle.add_argument("job_id") @@ -109,6 +116,16 @@ def main(argv: Optional[List[str]] = None) -> int: if args.command == "capabilities": print(json.dumps(client.capabilities(), indent=2)) return 0 + if args.command == "openapi": + print(json.dumps(client.openapi(), indent=2)) + return 0 + if args.command == "job": + print(json.dumps(client.job(args.job_id), indent=2)) + return 0 + if args.command == "stop": + summary = client.stop(args.job_id) + print(f"job {summary['id']}: {summary['state']}") + return 0 if args.command == "bundle": print(client.bundle(args.job_id, args.path)) return 0 diff --git a/python/cryptificate/client.py b/python/cryptificate/client.py index 9da893e..5af0b9d 100644 --- a/python/cryptificate/client.py +++ b/python/cryptificate/client.py @@ -15,15 +15,36 @@ JsonDict = Dict[str, Any] +# Each operation of the HTTP API (schemas/openapi.json, operationId) and the +# Client method that calls it. getWebUi serves the web workbench, not JSON. +OPERATIONS = { + "getCapabilities": "capabilities", + "getOpenApi": "openapi", + "submitAnalysis": "analyze", + "submitExperiment": "experiment", + "getJob": "job", + "stopJob": "stop", + "getJobBundle": "bundle", +} + + class CryptificateError(Exception): - """An error response from the service, or a transport failure.""" + """An error response from the service, or a transport failure. + + `status` is the HTTP status (0 when the service could not be reached), + `code` the stable error code from the response body (for example + "invalid-request", "queue-full", "not-found", "not-ready"), `errors` the + list of {path, code, message} issues of a 400 invalid-request response, and + `retry_after` the Retry-After delay in seconds of a 429 response. + """ - def __init__(self, status: int, code: str, message: str, errors: Optional[list] = None): + def __init__(self, status: int, code: str, message: str, errors: Optional[list] = None, retry_after: Optional[int] = None): super().__init__(f"{status} {code}: {message}") self.status = status self.code = code self.message = message self.errors = errors or [] + self.retry_after = retry_after class Client: @@ -61,7 +82,11 @@ def _request(self, method: str, path: str, body: Optional[Mapping[str, Any]] = N errors = doc.get("errors", []) except (ValueError, AttributeError): pass - raise CryptificateError(e.code, code, str(message), errors) from None + retry_after = None + header = e.headers.get("Retry-After") if e.headers is not None else None + if header is not None and header.strip().isdigit(): + retry_after = int(header.strip()) + raise CryptificateError(e.code, code, str(message), errors, retry_after) from None except urllib.error.URLError as e: raise CryptificateError(0, "unreachable", f"cannot reach {self.base_url}: {e.reason}") from None @@ -75,6 +100,10 @@ def capabilities(self) -> JsonDict: """Profiles, limits and toolchain availability of the service.""" return self._json("GET", "/api/capabilities") + def openapi(self) -> JsonDict: + """The OpenAPI 3.1 description of the HTTP API, with the JSON Schemas embedded.""" + return self._json("GET", "/api/openapi.json") + def analyze(self, design: Mapping[str, Any], program: Optional[Mapping[str, Any]] = None, target: Optional[str] = None) -> JsonDict: """Submit an analysis; returns the job summary {id, kind, state, origin}.""" body: JsonDict = {"design": dict(design)} @@ -104,7 +133,8 @@ def job(self, job_id: str) -> JsonDict: return self._json("GET", f"/api/jobs/{job_id}") def stop(self, job_id: str) -> JsonDict: - """Stop a job; completed checkpoints are kept.""" + """Stop a job; completed checkpoints are kept. Returns the job summary at the + time of the call: a running job may still read "running" until it has stopped.""" return self._json("POST", f"/api/jobs/{job_id}/stop", {})["job"] def wait(self, job_id: str, poll: float = 1.0, timeout: Optional[float] = None, on_progress=None) -> JsonDict: @@ -121,7 +151,10 @@ def wait(self, job_id: str, poll: float = 1.0, timeout: Optional[float] = None, time.sleep(poll) def bundle(self, job_id: str, path: Union[str, Path]) -> Path: - """Download the evidence bundle (.tar.gz) of a finished job to `path`.""" + """Download the evidence bundle (.tar.gz) of a finished job to `path`. + + Raises CryptificateError with status 409 (code "not-ready") while the job is + queued or running, or when it ended without a report or was invalid.""" target = Path(path) with self._request("GET", f"/api/jobs/{job_id}/bundle") as res: data = res.read() diff --git a/python/tests/test_openapi.py b/python/tests/test_openapi.py new file mode 100644 index 0000000..4c915de --- /dev/null +++ b/python/tests/test_openapi.py @@ -0,0 +1,193 @@ +"""The client against the OpenAPI description and its recorded responses. + +A stand-in service answers every operation with the response recorded in +schemas/openapi.json, so these tests exercise the client on the real bodies, +status codes and headers of the service. +""" + +import io +import json +import re +import tempfile +import threading +import unittest +from contextlib import redirect_stderr, redirect_stdout +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +from cryptificate import OPERATIONS, Client, CryptificateError +from cryptificate.__main__ import main + +ROOT = Path(__file__).resolve().parents[2] +SPEC = json.loads((ROOT / "schemas" / "openapi.json").read_text(encoding="utf-8")) +README = (ROOT / "python" / "README.md").read_text(encoding="utf-8") + + +def deref(node): + while "$ref" in node: + cur = SPEC + for part in node["$ref"][2:].split("/"): + cur = cur[part.replace("~1", "/").replace("~0", "~")] + node = cur + return node + + +def example(path, method, status, name): + response = deref(SPEC["paths"][path][method]["responses"][str(status)]) + return response["content"]["application/json"]["examples"][name]["value"] + + +COMPLETED = example("/api/jobs/{id}", "get", 200, "completed") +JOB_ID = COMPLETED["id"] +GZIP = b"\x1f\x8b\x08\x00recorded" + + +class RecordedService(BaseHTTPRequestHandler): + """Answers with the responses recorded in the OpenAPI description.""" + + mode = "normal" + seen = [] + + def log_message(self, *args): + pass + + def _send(self, status, body, ctype="application/json; charset=utf-8", headers=None): + data = body if isinstance(body, bytes) else json.dumps(body).encode() + self.send_response(status) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(data))) + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + RecordedService.seen.append(("GET", self.path)) + if self.path == "/api/capabilities": + return self._send(200, example("/api/capabilities", "get", 200, "live")) + if self.path == "/api/openapi.json": + return self._send(200, SPEC) + m = re.fullmatch(r"/api/jobs/([0-9a-f]{32})(/bundle)?", self.path) + if m and m.group(1) == JOB_ID: + if m.group(2): + if self.mode == "running": + return self._send(409, example("/api/jobs/{id}/bundle", "get", 409, "running")) + return self._send(200, GZIP, "application/gzip", {"Content-Disposition": f'attachment; filename="cryptificate-{JOB_ID}.tar.gz"'}) + return self._send(200, example("/api/jobs/{id}", "get", 200, "running" if self.mode == "running" else "completed")) + return self._send(404, example("/api/jobs/{id}", "get", 404, "not-found")) + + def do_POST(self): + length = int(self.headers.get("Content-Length", "0")) + body = self.rfile.read(length) + RecordedService.seen.append(("POST", self.path)) + if self.path in ("/api/analyses", "/api/experiments"): + if self.mode == "full": + return self._send(429, example("/api/analyses", "post", 429, "queue-full"), headers={"Retry-After": "30"}) + if json.loads(body or b"{}").get("design", {}).get("rounds") == 3: + return self._send(400, example("/api/analyses", "post", 400, "invalid-request")) + name = "analysis" if self.path == "/api/analyses" else "experiment" + accepted = example("/api/analyses", "post", 202, name) + return self._send(202, accepted, headers={"Location": f"/api/jobs/{accepted['job']['id']}"}) + if self.path == f"/api/jobs/{JOB_ID}/stop": + return self._send(200, {"job": {k: COMPLETED[k] for k in ("id", "kind", "state", "origin")}}) + return self._send(404, example("/api/jobs/{id}", "get", 404, "not-found")) + + +class OpenApiCoverageTest(unittest.TestCase): + def test_every_operation_has_a_client_method(self): + ops = { + op["operationId"] + for path, item in SPEC["paths"].items() + for method, op in item.items() + if method in ("get", "post", "put", "delete", "patch") and path.startswith("/api/") + } + self.assertEqual(ops, set(OPERATIONS)) + for operation_id, method in OPERATIONS.items(): + self.assertTrue(callable(getattr(Client, method, None)), f"{operation_id}: Client.{method}") + + def test_readme_documents_every_method_and_command(self): + for method in list(OPERATIONS.values()) + ["wait"]: + self.assertRegex(README, rf"`(client\.)?{method}\(", f"README does not document {method}()") + for command in ("check", "experiment", "job", "stop", "bundle", "capabilities", "openapi"): + self.assertIn(f"python -m cryptificate {command}", README) + + +class RecordedResponsesTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.server = ThreadingHTTPServer(("127.0.0.1", 0), RecordedService) + cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) + cls.thread.start() + cls.url = f"http://127.0.0.1:{cls.server.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server.server_close() + + def setUp(self): + RecordedService.mode = "normal" + RecordedService.seen.clear() + self.client = Client(self.url, timeout=5) + + def test_capabilities_and_openapi(self): + caps = self.client.capabilities() + self.assertEqual(caps["limits"]["maxQueued"], 2) + doc = self.client.openapi() + self.assertEqual(doc["openapi"], "3.1.0") + self.assertIn("/api/jobs/{id}/bundle", doc["paths"]) + + def test_submit_poll_stop_and_bundle(self): + job = self.client.analyze({"model": "aes-like/gf256/v1", "rounds": 4}) + self.assertEqual((job["kind"], job["state"]), ("analysis", "queued")) + exp = self.client.experiment({"model": "aes-like/gf256/v1"}, profile="quick") + self.assertEqual(exp["kind"], "experiment") + final = self.client.wait(JOB_ID, poll=0.01) + self.assertEqual(final["state"], "completed") + statuses = {c["id"]: c["status"] for c in final["report"]["claims"]} + self.assertEqual(statuses["circuit.equivalence"], "refuted") + self.assertEqual(self.client.stop(JOB_ID)["id"], JOB_ID) + with tempfile.TemporaryDirectory() as d: + out = self.client.bundle(JOB_ID, Path(d) / "b.tar.gz") + self.assertEqual(out.read_bytes(), GZIP) + self.assertIn(("POST", f"/api/jobs/{JOB_ID}/stop"), RecordedService.seen) + + def test_recorded_errors(self): + with self.assertRaises(CryptificateError) as cm: + self.client.analyze({"rounds": 3}) + self.assertEqual((cm.exception.status, cm.exception.code), (400, "invalid-request")) + self.assertEqual([e["path"] for e in cm.exception.errors], ["/design/matrix/0/1", "/design/rounds"]) + RecordedService.mode = "full" + with self.assertRaises(CryptificateError) as cm: + self.client.experiment({"model": "aes-like/gf256/v1"}) + self.assertEqual((cm.exception.status, cm.exception.code, cm.exception.retry_after), (429, "queue-full", 30)) + RecordedService.mode = "running" + with tempfile.TemporaryDirectory() as d: + with self.assertRaises(CryptificateError) as cm: + self.client.bundle(JOB_ID, Path(d) / "b.tar.gz") + self.assertEqual((cm.exception.status, cm.exception.code), (409, "not-ready")) + self.assertFalse((Path(d) / "b.tar.gz").exists()) + with self.assertRaises(CryptificateError) as cm: + self.client.job("0" * 32) + self.assertEqual((cm.exception.status, cm.exception.code, cm.exception.retry_after), (404, "not-found", None)) + + def test_command_line_job_stop_and_openapi(self): + for argv, expect in ( + (["job", JOB_ID], '"state": "completed"'), + (["stop", JOB_ID], f"job {JOB_ID}: completed"), + (["openapi"], '"openapi": "3.1.0"'), + ): + stdout, stderr = io.StringIO(), io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + code = main(["--url", self.url] + argv) + self.assertEqual(code, 0, stderr.getvalue()) + self.assertIn(expect, stdout.getvalue()) + stdout, stderr = io.StringIO(), io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + code = main(["--url", self.url, "job", "0" * 32]) + self.assertEqual(code, 2) + self.assertIn("404 not-found", stderr.getvalue()) + + +if __name__ == "__main__": + unittest.main() From d518b6600f637fc6d63e846ddcf6162e9ce10eb8 Mon Sep 17 00:00:00 2001 From: tyler-turnpike <188578979+tyler-turnpike@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:30:24 +0000 Subject: [PATCH 6/9] docs: describe the HTTP API docs/api.md covers the endpoints, the Host/Origin security model, the job lifecycle, polling, the queue limit and the other limits, bundle download and the error codes, with curl examples. The README and the architecture page link it, and the description states which jobs survive a restart. --- README.md | 6 +- docs/api.md | 246 +++++++++++++++++++++++++++++++++++++++++++ docs/architecture.md | 2 +- schemas/openapi.json | 2 +- 4 files changed, 252 insertions(+), 4 deletions(-) create mode 100644 docs/api.md diff --git a/README.md b/README.md index ac6b48e..d793250 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,8 @@ for claim in final["report"]["claims"]: client.bundle(job["id"], "evidence.tar.gz") ``` +Over HTTP, from any language: the service's API is described in [docs/api.md](docs/api.md) and, machine-readably, in [`schemas/openapi.json`](schemas/openapi.json) (OpenAPI 3.1, also served at `GET /api/openapi.json`). + The [adopter guide](docs/adopter-guide.md) walks through a first design end to end. ## What it proves @@ -190,11 +192,11 @@ npx cryptificate verify examples/bundles/aes-wrong-wire/aes-wrong-wire.tar.gz | [`lean/`](lean) | Circuit semantics, canonical-minor MDS certificates, counterexample lemmas, offsets, the execution bridge, S-box and exponent certificates, HADES bounds, the audit command and the certificate templates | | [`refinement/`](refinement) | Charon/Aeneas translations of `crates/kernels` and the gf256 crate, with their Lean proofs | | [`crates/`](crates) | `core` (validation, diagnostics, certificate emission), `cli` (`cryptificate-engine`), `search`, `native` (code generation and timing harness), `kernels` | -| [`apps/server`](apps/server) | HTTP API, job queue, proof acceptance, bundles and the `cryptificate` CLI | +| [`apps/server`](apps/server) | [HTTP API](docs/api.md), job queue, proof acceptance, bundles and the `cryptificate` CLI | | [`apps/web`](apps/web) | The workbench, also published online | | [`python/`](python) | Python client | | [`examples/`](examples) | Designs, circuits, evidence bundles and measurements | -| [`docs/`](docs) | [Evidence model](docs/evidence-model.md), [architecture](docs/architecture.md), [batch interface](docs/batch-interface.md), [adopter guide](docs/adopter-guide.md), [research directions](docs/research-directions.md) | +| [`docs/`](docs) | [Evidence model](docs/evidence-model.md), [architecture](docs/architecture.md), [batch interface](docs/batch-interface.md), [HTTP API](docs/api.md), [adopter guide](docs/adopter-guide.md), [research directions](docs/research-directions.md) | ## Built on WideTrail diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..8398272 --- /dev/null +++ b/docs/api.md @@ -0,0 +1,246 @@ +# HTTP API + +`cryptificate serve` runs a local HTTP service. The web workbench and the +[Python client](../python) use it, and other tools can too. (The `cryptificate check` and +`experiment` commands run the same pipelines in-process, without the service.) + +- The machine-readable description is [`schemas/openapi.json`](../schemas/openapi.json) + (OpenAPI 3.1). It refers to the JSON Schemas next to it by `$ref`. +- A running service serves the same description at `GET /api/openapi.json`, as one + self-contained document: the schemas are embedded under `components/schemas` and every + reference is local, so code generators and API browsers can load it from the URL. +- Every example in the description is a response recorded from a live service (version 0.1.0, + release engine, Lean checker), except the fixed body of the 500 response. + +The test `apps/server/test/openapi.test.ts` keeps the description and the service in step: the +routes the handler dispatches and the operations described are the same set, every example +validates against its schema, every error code the handler can produce is documented, and live +responses of an in-process service validate against the description. + +## Endpoints + +| Method and path | Operation | Success | +|---|---|---| +| `GET /api/capabilities` | models, experiment profiles and budgets, limits, toolchain availability | 200 | +| `GET /api/openapi.json` | this description | 200 | +| `POST /api/analyses` | submit an analysis (design, optional circuit) | 202 | +| `POST /api/experiments` | submit an experiment (search, check and time circuits) | 202 | +| `GET /api/jobs/{id}` | poll a job: state, steps, partial or final report | 200 | +| `POST /api/jobs/{id}/stop` | stop a queued or running job | 200 | +| `GET /api/jobs/{id}/bundle` | download the evidence bundle of a finished job | 200 | +| `GET /` and other non-API paths | the built web workbench (static files) | 200 | + +There is no endpoint that lists jobs and no streaming endpoint: keep the ids you submit and poll. + +Request bodies are [`AnalysisRequest`](../schemas/analysis-request.schema.json) and +[`ExperimentRequest`](../schemas/experiment-request.schema.json). The job is +[`Job`](../schemas/job.schema.json), its report an +[`AnalysisReport`](../schemas/analysis-report.schema.json) or +[`ExperimentReport`](../schemas/experiment-report.schema.json), and every error an +[`ErrorResponse`](../schemas/error.schema.json). Field elements are strings: two hex digits for +GF(2⁸) (`"1B"`), canonical decimals below the modulus for BN254. Requests are checked strictly +(unknown members are rejected); responses may gain new optional members, which clients should +ignore. + +## Security model + +The service is a single-user local tool. It has **no authentication**: whoever can send it a +request can run jobs on the machine. + +- **Binding.** It listens on `127.0.0.1:4173` by default (`--port`, `PORT`, `--host`). Binding + to another address prints a warning, because anyone who can reach it can then run jobs. +- **Host check (every request).** The `Host` header must name a loopback address (`127.0.0.1`, + `localhost`, `::1`) or the address the service is bound to; otherwise the answer is 403 + `forbidden`. This defeats DNS rebinding, where a web page on another name reaches the local + port. When the service is bound to `0.0.0.0` or `::`, only loopback names are accepted. +- **Same-origin writes.** For every method other than GET, HEAD and OPTIONS: an `Origin` + header, when present, must be `http://:` or one of the origins given + with `--allow-origin URL` (repeatable) or `CRYPTIFICATE_ALLOWED_ORIGINS` (comma-separated); + without `Origin`, a `Sec-Fetch-Site` header other than `same-origin` or `none` is rejected. + A web page on another site therefore cannot submit or stop jobs. +- **Non-browser clients** (curl, Python, scripts) send neither `Origin` nor `Sec-Fetch-Site` and + are accepted. +- **No CORS.** The service sends no `Access-Control-*` headers, so pages on other origins cannot + read its responses either. `--allow-origin` exists for a development UI server that proxies + to the service. +- **Response headers.** Every response carries `X-Content-Type-Options: nosniff`, + `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer` and + `Cross-Origin-Resource-Policy: same-origin`. JSON responses are `Cache-Control: no-store` + (the description itself is `no-cache`). + +```sh +curl -sS -H 'Host: evil.example:4173' http://127.0.0.1:4173/api/capabilities +# {"error":{"code":"forbidden","message":"Host header is not a loopback address"}} +curl -sS -X POST -H 'Origin: http://evil.example' -H 'Content-Type: application/json' \ + -d '{}' http://127.0.0.1:4173/api/analyses +# {"error":{"code":"forbidden","message":"cross-origin request rejected"}} +``` + +## Submitting a job + +```sh +B=http://127.0.0.1:4173 +printf '{"design":%s,"program":%s}' \ + "$(cat examples/designs/aes.json)" "$(cat examples/programs/aes-wrong-wire.json)" > request.json +curl -sS -i -X POST "$B/api/analyses" -H 'Content-Type: application/json' -d @request.json +``` + +```http +HTTP/1.1 202 Accepted +location: /api/jobs/9d4777dbeae6b987f0e2ce28b7993cfe + +{"job":{"id":"9d4777dbeae6b987f0e2ce28b7993cfe","kind":"analysis","state":"queued","origin":"live"}} +``` + +An experiment takes a `profile` (`quick` or `research`, budgets in +`GET /api/capabilities`) and an optional hex `seed`: + +```sh +printf '{"design":%s,"profile":"quick","seed":"c0ffee"}' "$(cat examples/designs/aes.json)" \ + | curl -sS -X POST "$B/api/experiments" -H 'Content-Type: application/json' -d @- +``` + +The body must be `Content-Type: application/json`, at most 256 KiB, and of the documented shape. +The service checks the shape before it creates a job and answers 400 `invalid-request` with +every problem found (up to 50), each with a JSON Pointer into the request: + +```json +{"error":{"code":"invalid-request","message":"/design/matrix/0/1: field elements are strings, not numbers"}, + "errors":[{"path":"/design/matrix/0/1","code":"type","message":"field elements are strings, not numbers"}, + {"path":"/design/rounds","code":"range","message":"expected an integer in 4..32"}]} +``` + +The engine then validates the request in depth as the job's first step (matrix and circuit +semantics), so a request that passes the shape check can still end in state `invalid`, with the +reason in the job's `error`. + +## Job lifecycle + +```text +queued ──► running ──► completed | failed | timeout | cancelled | invalid + └──────────────────► cancelled (stopped while queued) +``` + +| State | Meaning | +|---|---| +| `queued` | waiting; `queuePosition` is 1 for the next job to run | +| `running` | executing; `steps` and a partial `report` are visible | +| `completed` | the run finished; the claims say what was proved, refuted or not established | +| `failed` | a step failed (`error` says which); completed checkpoints are kept | +| `timeout` | the job's time budget ran out; unchecked claims are `not_established`, never refuted | +| `cancelled` | stopped; completed checkpoints are kept | +| `invalid` | the engine rejected the request; no bundle | + +The steps of an analysis are `validate`, `diagnose`, `emit-lean`, `lean`, `native` and +`report`; those of an experiment are `validate`, `search`, `equivalence`, +`native-correctness`, `benchmark-1`, `benchmark-2`, `benchmark-3` and `report`. Each step has +a state (`pending`, `running`, `completed`, `failed`, `timeout`, `cancelled`, `skipped`, +`not_run`, ...), and once it ends, its duration in `ms` and sometimes a `detail`. + +`origin` is `live` for a fresh run and `cached` when an identical analysis (same inputs, toolchain pins, +checker version and certificate sources) was answered from the proof cache. + +Finished jobs survive a restart of the service: the 200 most recently updated jobs in the state +directory (`CRYPTIFICATE_HOME`, by default `.cryptificate/` in the checkout) are loaded at +start. Jobs that were queued or running when the service stopped are not resumed: they read +`cancelled`, or `failed` with error code `interrupted`. + +## Polling + +Poll `GET /api/jobs/{id}` until the state is terminal. The workbench polls every 800 ms; once a +second is enough for scripts. The response is the whole job each time. + +```sh +ID=9d4777dbeae6b987f0e2ce28b7993cfe +while :; do + STATE=$(curl -fsS "$B/api/jobs/$ID" | python3 -c 'import json,sys; print(json.load(sys.stdin)["state"])') + case $STATE in queued|running) sleep 1 ;; *) break ;; esac +done +curl -fsS "$B/api/jobs/$ID" | python3 -c ' +import json, sys +for c in json.load(sys.stdin)["report"]["claims"]: + print(c["id"], c["status"], c["evidence"]["label"])' +``` + +```text +matrix.mds proved Lean-checked proof +offsets.dispersion proved Lean-checked proof +sbox.bijective proved Lean-checked proof +activity.bound proved Lean-checked proof +circuit.equivalence refuted Lean-checked counterexample +... +``` + +`POST /api/jobs/{id}/stop` (no body needed) removes a queued job at once and signals a running +one, whose whole process group is killed; the job then becomes `cancelled`. The response is the +summary at the time of the call, so poll to see the final state. Stopping a finished job +changes nothing. + +## Limits and the queue + +| Limit | Value | Where to read it | +|---|---|---| +| Request body | 256 KiB; beyond, 413 `body-too-large` and the connection is closed | `limits.maxBodyBytes` | +| Circuit length | 256 instructions | `limits.maxInstructions` | +| Concurrency | one job runs at a time | | +| Queue | two jobs wait behind it; a further submission gets 429 `queue-full` with `Retry-After: 30` | `limits.maxQueued` | +| Analysis budget | 300 s per analysis | `limits.analysisBudgetSeconds` | +| Experiment budget | per profile (`quick` 180 s, `research` 900 s) | `profiles[].budget.totalSeconds` | +| One Lean run | 180 s, and never beyond the remaining budget | `limits.leanTimeoutSeconds` | + +The queue is the only rate limit: there is no per-client accounting. On 429, wait for the +`Retry-After` delay (or for one of your jobs to finish) and submit again. + +```sh +curl -sS -i -X POST "$B/api/analyses" -H 'Content-Type: application/json' -d @request.json +# HTTP/1.1 429 Too Many Requests +# retry-after: 30 +# {"error":{"code":"queue-full","message":"one job is running and the queue is full; try again later"}} +``` + +## Downloading the bundle + +When a job is terminal, not `invalid` and has a report, its `bundle` member is `true` and +`GET /api/jobs/{id}/bundle` returns a gzip-compressed tar archive: + +```sh +curl -fsS -OJ "$B/api/jobs/$ID/bundle" # saves cryptificate-.tar.gz +npx cryptificate verify "cryptificate-$ID.tar.gz" +``` + +The bundle holds the normalized inputs, the report, the generated Lean certificates and the +checker's output, the toolchain pins, native sources and measurements when those steps ran, and +`VERIFY.md` ([contents](../examples/bundles/README.md)). It is deterministic: the same job +always yields the same bytes. Before the job is terminal, or when it ended without a report, +the answer is 409 `not-ready`: + +```json +{"error":{"code":"not-ready","message":"the job has not finished"}} +``` + +## Errors + +Every error is JSON, `{"error": {"code", "message"}}`, plus `errors` for 400 +`invalid-request`. `code` is stable; `message` is for people and may change. + +| Status | `code` | When | +|---|---|---| +| 400 | `bad-json` | the body is not JSON | +| 400 | `invalid-request` | the body is not a request of the documented shape (`errors` lists each issue) | +| 403 | `forbidden` | the request failed the Host or Origin check | +| 404 | `not-found` | no such job, no such API path (GET or POST), or no `schemas/openapi.json` in this installation | +| 405 | `method-not-allowed` | another method on an API path, or a method other than GET and HEAD on a non-API path | +| 409 | `not-ready` | bundle requested before the job finished, or for a job without a report or with an invalid request | +| 413 | `body-too-large` | the body exceeds 256 KiB (a client still uploading may see the connection reset instead) | +| 415 | `unsupported-media-type` | the body is not `Content-Type: application/json` | +| 429 | `queue-full` | one job runs and two are queued | +| 500 | `internal` | an unexpected failure in the service | + +A job that fails does not produce an HTTP error: it is a job in state `failed`, `timeout` or +`invalid` with an `error` member. + +## Checking documents against the schemas + +`@cryptificate/schema` exports `SchemaRegistry`, a dependency-free validator for the JSON +Schemas in `schemas/` (see [its README](../packages/schema/README.md)). The Python client +documents its methods, one per operation, in [`python/README.md`](../python/README.md). diff --git a/docs/architecture.md b/docs/architecture.md index a9fe7f0..46a1eb4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -28,7 +28,7 @@ Cryptificate is a local application. A loopback Node service orchestrates three | `crates/native` | Rust code generation, native correctness corpus, measurement protocol and statistics. | Tests only | | `crates/kernels` | Arithmetic and parametric round kernels used by every native variant; the GF(2⁸) arithmetic and the AES-like round are the subject of the refinement proofs, the BN254 arithmetic (arkworks) is not. | GF(2⁸) and AES-like parts, via `refinement/` | | `refinement/` | Charon/Aeneas extraction and Lean proofs that the GF(2⁸) and AES-like Rust source equals the model. | Yes, with Charon, Aeneas and rustc trusted | -| `apps/server` | HTTP API, job queue, Lean runner, proof acceptance, bundles, CLI. | Acceptance logic only | +| `apps/server` | HTTP API ([api.md](api.md), described by `schemas/openapi.json`), job queue, Lean runner, proof acceptance, bundles, CLI. | Acceptance logic only | | `apps/web` | Workbench and static replay viewer. | No | | `python/` | Thin client for research scripts. | No | diff --git a/schemas/openapi.json b/schemas/openapi.json index 3157a38..8361048 100644 --- a/schemas/openapi.json +++ b/schemas/openapi.json @@ -5,7 +5,7 @@ "title": "Cryptificate local service", "version": "0.1.0", "summary": "Submit designs and circuits for Lean-checked analysis, run experiments, poll jobs and download evidence bundles.", - "description": "HTTP API of `cryptificate serve`, the local Cryptificate service. The web workbench, the `cryptificate` command line and the Python client (`python/cryptificate`) all use it.\n\n**Scope.** This document describes every route the service answers. Request and report bodies are described by the JSON Schemas in `schemas/` (referenced here with `$ref`); the served copy at `GET /api/openapi.json` embeds them under `components/schemas`. Examples are responses recorded from a live service (version 0.1.0, release engine, Lean checker), except the 500 example, which shows the fixed body of that response. Field elements are strings: two hex digits for GF(2^8), canonical decimals below the modulus for BN254.\n\n**Security model.** The service is a single-user local tool and has no authentication. It binds to 127.0.0.1 by default; `--host` can bind elsewhere, and then anyone who can reach the address can run jobs. Every request must carry a `Host` header naming a loopback address (`127.0.0.1`, `localhost`, `::1`) or the bound host, which rejects DNS-rebinding pages. State-changing requests (every method other than GET, HEAD and OPTIONS) are accepted only same-origin: when an `Origin` header is present it must be `http://:` of this service or one of the origins given with `--allow-origin` / `CRYPTIFICATE_ALLOWED_ORIGINS`; without `Origin`, a `Sec-Fetch-Site` header other than `same-origin` or `none` is rejected. Clients outside a browser (curl, Python) send neither header and are accepted. A rejected request gets 403 `forbidden`. There are no CORS headers: cross-origin browser reads are not supported. Every response carries `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer` and `Cross-Origin-Resource-Policy: same-origin`.\n\n**Limits.** JSON bodies are at most 256 KiB (413 beyond, and the connection is closed). One job runs at a time and at most two wait behind it (`limits.maxQueued` in the capabilities); a further submission gets 429 with `Retry-After: 30`. There is no per-client rate limit beyond this queue. Each job runs under a time budget (`limits.analysisBudgetSeconds`, or the experiment profile's `budget.totalSeconds`), and each Lean run under `limits.leanTimeoutSeconds`.\n\n**Job lifecycle.** `POST /api/analyses` or `POST /api/experiments` answers 202 with a job summary and a `Location` header. The job moves `queued` -> `running` -> one of `completed`, `failed`, `timeout`, `cancelled` or `invalid` (terminal). Poll `GET /api/jobs/{id}`: while it runs, `steps` and a partial `report` are visible. When the state is terminal and `bundle` is true, `GET /api/jobs/{id}/bundle` returns the evidence bundle. Jobs survive a restart of the service; a job that was running when the service stopped is reported as `failed` with error code `interrupted`. There is no endpoint that lists jobs; keep the ids you submit.\n\n**Errors.** Every error is JSON with a stable `error.code` (see `ErrorResponse`). Any other path under `/api/` answers 404 `not-found` to GET and POST and 405 `method-not-allowed` to other methods. An unexpected failure answers 500 `internal`.\n\n**Stability.** Paths, status codes, error codes and the members described in the schemas are the supported surface. New optional members may be added to responses; clients should ignore members they do not know. Requests are checked strictly: unknown members are rejected.", + "description": "HTTP API of `cryptificate serve`, the local Cryptificate service. The web workbench and the Python client (`python/cryptificate`) use it; the `cryptificate check` and `experiment` commands run the same pipelines in-process instead.\n\n**Scope.** This document describes every route the service answers. Request and report bodies are described by the JSON Schemas in `schemas/` (referenced here with `$ref`); the served copy at `GET /api/openapi.json` embeds them under `components/schemas`. Examples are responses recorded from a live service (version 0.1.0, release engine, Lean checker), except the 500 example, which shows the fixed body of that response. Field elements are strings: two hex digits for GF(2^8), canonical decimals below the modulus for BN254.\n\n**Security model.** The service is a single-user local tool and has no authentication. It binds to 127.0.0.1 by default; `--host` can bind elsewhere, and then anyone who can reach the address can run jobs. Every request must carry a `Host` header naming a loopback address (`127.0.0.1`, `localhost`, `::1`) or the bound host, which rejects DNS-rebinding pages. State-changing requests (every method other than GET, HEAD and OPTIONS) are accepted only same-origin: when an `Origin` header is present it must be `http://:` of this service or one of the origins given with `--allow-origin` / `CRYPTIFICATE_ALLOWED_ORIGINS`; without `Origin`, a `Sec-Fetch-Site` header other than `same-origin` or `none` is rejected. Clients outside a browser (curl, Python) send neither header and are accepted. A rejected request gets 403 `forbidden`. There are no CORS headers: cross-origin browser reads are not supported. Every response carries `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer` and `Cross-Origin-Resource-Policy: same-origin`.\n\n**Limits.** JSON bodies are at most 256 KiB (413 beyond, and the connection is closed). One job runs at a time and at most two wait behind it (`limits.maxQueued` in the capabilities); a further submission gets 429 with `Retry-After: 30`. There is no per-client rate limit beyond this queue. Each job runs under a time budget (`limits.analysisBudgetSeconds`, or the experiment profile's `budget.totalSeconds`), and each Lean run under `limits.leanTimeoutSeconds`.\n\n**Job lifecycle.** `POST /api/analyses` or `POST /api/experiments` answers 202 with a job summary and a `Location` header. The job moves `queued` -> `running` -> one of `completed`, `failed`, `timeout`, `cancelled` or `invalid` (terminal). Poll `GET /api/jobs/{id}`: while it runs, `steps` and a partial `report` are visible. When the state is terminal and `bundle` is true, `GET /api/jobs/{id}/bundle` returns the evidence bundle. Finished jobs survive a restart of the service (the 200 most recently updated are loaded at start). Jobs that were queued or running when the service stopped are not resumed: they read `cancelled`, or `failed` with error code `interrupted`. There is no endpoint that lists jobs; keep the ids you submit.\n\n**Errors.** Every error is JSON with a stable `error.code` (see `ErrorResponse`). Any other path under `/api/` answers 404 `not-found` to GET and POST and 405 `method-not-allowed` to other methods. An unexpected failure answers 500 `internal`.\n\n**Stability.** Paths, status codes, error codes and the members described in the schemas are the supported surface. New optional members may be added to responses; clients should ignore members they do not know. Requests are checked strictly: unknown members are rejected.", "license": { "name": "MIT", "identifier": "MIT" From 0f20187c5c854ddf3b91c951e586da7fcbc76d7b Mon Sep 17 00:00:00 2001 From: tyler-turnpike <188578979+tyler-turnpike@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:39:45 +0000 Subject: [PATCH 7/9] fix(schema): percent-decode $ref fragments only, not plain JSON Pointers resolveJsonPointer takes an RFC 6901 pointer in its plain string form, where '%' is an ordinary character. SchemaRegistry.resolve now decodes the URI fragment of a $ref before resolving it and reports a malformed fragment as UnsupportedSchemaError. --- packages/schema/src/jsonschema.ts | 15 ++++++++++++--- packages/schema/test/jsonschema.test.ts | 12 ++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/packages/schema/src/jsonschema.ts b/packages/schema/src/jsonschema.ts index 80560cd..48c8745 100644 --- a/packages/schema/src/jsonschema.ts +++ b/packages/schema/src/jsonschema.ts @@ -109,13 +109,16 @@ export function jsonEqual(a: unknown, b: unknown): boolean { return ak.length === bk.length && ak.every((k) => Object.prototype.hasOwnProperty.call(bo, k) && jsonEqual(ao[k], bo[k])); } -/** Resolve a JSON Pointer (without the leading '#') inside a document. */ +/** + * Resolve a JSON Pointer (RFC 6901, plain string form: no leading '#' and no + * percent-decoding) inside a document. Returns undefined when nothing is there. + */ export function resolveJsonPointer(doc: unknown, pointer: string): unknown { if (pointer === '') return doc; if (!pointer.startsWith('/')) return undefined; let cur: unknown = doc; for (const raw of pointer.slice(1).split('/')) { - const part = decodeURIComponent(raw).replace(/~1/g, '/').replace(/~0/g, '~'); + const part = raw.replace(/~1/g, '/').replace(/~0/g, '~'); if (cur === null || typeof cur !== 'object') return undefined; if (Array.isArray(cur)) { if (!/^(0|[1-9][0-9]*)$/.test(part)) return undefined; @@ -152,7 +155,13 @@ export class SchemaRegistry { /** Resolve a reference against a base URI to the schema it names. */ resolve(ref: string, base: string): { schema: unknown; base: string } { const abs = new URL(ref, base); - const fragment = abs.hash.replace(/^#/, ''); + // A URI fragment is percent-encoded (RFC 6901 section 6); the pointer inside it is not. + let fragment: string; + try { + fragment = decodeURIComponent(abs.hash.replace(/^#/, '')); + } catch { + throw new UnsupportedSchemaError(`malformed fragment in $ref ${ref} (from ${base})`); + } abs.hash = ''; const doc = this.docs.get(abs.href); if (doc === undefined) throw new UnsupportedSchemaError(`unresolvable $ref ${ref} (from ${base})`); diff --git a/packages/schema/test/jsonschema.test.ts b/packages/schema/test/jsonschema.test.ts index f61f502..6bffa27 100644 --- a/packages/schema/test/jsonschema.test.ts +++ b/packages/schema/test/jsonschema.test.ts @@ -96,6 +96,18 @@ test('jsonschema: pointer helpers and structural equality', () => { assert.equal(resolveJsonPointer(doc, '/a/0/~0d'), 2); assert.equal(resolveJsonPointer(doc, '/a/01'), undefined); assert.equal(resolveJsonPointer(doc, ''), doc); + // a plain JSON Pointer is not percent-decoded: '%' is an ordinary character + const pct = { 'a%20b': 1, '100%': 2, 'a b': 3 }; + assert.equal(resolveJsonPointer(pct, '/a%20b'), 1); + assert.equal(resolveJsonPointer(pct, '/100%'), 2); + assert.equal(resolveJsonPointer(pct, '/a b'), 3); + assert.equal(resolveJsonPointer(pct, '/100%25'), undefined); + // in a $ref the pointer sits in a URI fragment, which is percent-decoded once + const reg = new SchemaRegistry().add('https://example.invalid/p.json', { $defs: { 'a b': { type: 'string' }, '100%': { type: 'integer' } } }); + assert.deepEqual(reg.validate('https://example.invalid/p.json#/$defs/a%20b', 'x'), []); + assert.deepEqual(reg.validate('https://example.invalid/p.json#/$defs/100%25', 7), []); + assert.equal(reg.validate('https://example.invalid/p.json#/$defs/100%25', 'x').length, 1); + assert.throws(() => reg.validate('https://example.invalid/p.json#/$defs/100%', 7), UnsupportedSchemaError); assert.ok(jsonEqual({ a: [1, { b: null }] }, { a: [1, { b: null }] })); assert.ok(!jsonEqual({ a: 1 }, { a: 1, b: undefined })); assert.ok(!jsonEqual([1], { 0: 1 })); From 1525132283a3abed8dee08ae837389ad2ddb014f Mon Sep 17 00:00:00 2001 From: tyler-turnpike <188578979+tyler-turnpike@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:40:56 +0000 Subject: [PATCH 8/9] test(server): check queued and cancelled job responses deterministically A pipeline that holds the run slot keeps a second job queued, so the 409 not-ready answers ('the job has not finished' and 'the job ended before it produced a report') and 429 queue-full are checked against the OpenAPI description on every run. The 413 check now sends a declared length over the limit, and both live tests assert every operation/status pair they are meant to exercise. Local $ref fragments are percent-decoded before pointer resolution. --- apps/server/test/openapi.test.ts | 168 +++++++++++++++++++++++++++---- 1 file changed, 146 insertions(+), 22 deletions(-) diff --git a/apps/server/test/openapi.test.ts b/apps/server/test/openapi.test.ts index e28e65f..782401a 100644 --- a/apps/server/test/openapi.test.ts +++ b/apps/server/test/openapi.test.ts @@ -12,6 +12,8 @@ import type { AddressInfo } from 'node:net'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { SchemaRegistry, resolveJsonPointer, validateAnalysisRequest, validateExperimentRequest } from '@cryptificate/schema'; +import type { AnalysisReport } from '@cryptificate/schema'; +import type { JobContext, PipelineEnv, PipelineResult } from '../src/context.js'; import { JobManager } from '../src/jobs.js'; import { bundleOpenApi, componentName } from '../src/openapi.js'; import { API_ROUTES, createApp, matchApiRoute } from '../src/server.js'; @@ -51,7 +53,8 @@ function deref(doc: Obj, node: unknown, pointer: string): { node: Obj; pointer: for (let i = 0; i < 10 && typeof cur['$ref'] === 'string'; i++) { const ref = cur['$ref'] as string; assert.ok(ref.startsWith('#/'), `${ptr}: non-local reference ${ref}`); - ptr = ref.slice(1); + // the reference is a URI fragment: percent-decode it to get the JSON Pointer + ptr = decodeURIComponent(ref.slice(1)); cur = resolveJsonPointer(doc, ptr) as Obj; assert.ok(cur, `${pointer}: unresolvable ${ref}`); } @@ -256,13 +259,12 @@ function call(port: number, method: string, path: string, opts: { body?: string }); } -test('openapi: live responses of the service conform to the description', async () => { - const { root, env } = makeFixture(); - cpSync(SCHEMAS, join(root, 'schemas'), { recursive: true }); - const jobs = new JobManager({ env }); - const server = createApp({ env, jobs, host: '127.0.0.1', port: 0, webDist: null }); - await new Promise((r) => server.listen(0, '127.0.0.1', () => r())); - const port = (server.address() as AddressInfo).port; +/** + * Checks a live response against the description: its status and media type + * are documented for the operation, and a JSON body validates against the + * schema. `seen` records each operation/status pair checked. + */ +function conformer(): { conform: (operationId: string, res: Res) => unknown; seen: Set } { const reg = registry(); const byId = new Map(operations().map((o) => [String(o.op['operationId']), o])); const seen = new Set(); @@ -277,6 +279,21 @@ test('openapi: live responses of the service conform to the description', async assert.deepEqual(reg.validate(`${DOC_URI}#${pointer}`, body), [], `${operationId} ${res.status}`); return body; }; + return { conform, seen }; +} + +function assertExercised(seen: Set, required: string[]): void { + for (const s of required) assert.ok(seen.has(s), `not exercised: ${s}`); +} + +test('openapi: live responses of the service conform to the description', async () => { + const { root, env } = makeFixture(); + cpSync(SCHEMAS, join(root, 'schemas'), { recursive: true }); + const jobs = new JobManager({ env }); + const server = createApp({ env, jobs, host: '127.0.0.1', port: 0, webDist: null }); + await new Promise((r) => server.listen(0, '127.0.0.1', () => r())); + const port = (server.address() as AddressInfo).port; + const { conform, seen } = conformer(); try { conform('getCapabilities', await call(port, 'GET', '/api/capabilities')); const served = conform('getOpenApi', await call(port, 'GET', '/api/openapi.json')) as Obj; @@ -287,6 +304,11 @@ test('openapi: live responses of the service conform to the description', async conform('submitAnalysis', await call(port, 'POST', '/api/analyses', { body: '{not json' })); conform('submitAnalysis', await call(port, 'POST', '/api/analyses', { body: JSON.stringify({ design: { ...AES_DESIGN, rounds: 3 } }) })); conform('submitAnalysis', await call(port, 'POST', '/api/analyses', { body: '{}', headers: { 'content-type': 'text/plain' } })); + // a declared length over the limit is refused before any body is read + const declared = await call(port, 'POST', '/api/analyses', { body: '', headers: { 'content-length': String(300 * 1024) } }); + assert.equal(declared.status, 413); + conform('submitAnalysis', declared); + // an oversized upload may instead see the connection closed before the answer arrives const big = await call(port, 'POST', '/api/analyses', { body: Buffer.alloc(300 * 1024, 0x20) }); if (big.status !== -1) conform('submitAnalysis', big); conform('submitExperiment', await call(port, 'POST', '/api/experiments', { body: JSON.stringify({ design: AES_DESIGN, profile: 'fast' }) })); @@ -296,6 +318,7 @@ test('openapi: live responses of the service conform to the description', async const accepted = await call(port, 'POST', '/api/analyses', { body: JSON.stringify({ design: AES_DESIGN }) }); const id = (conform('submitAnalysis', accepted) as { job: { id: string } }).job.id; assert.equal(accepted.headers['location'], `/api/jobs/${id}`); + // 409 while the job runs is checked deterministically in the next test const early = await call(port, 'GET', `/api/jobs/${id}/bundle`); if (early.status === 409) conform('getJobBundle', early); await jobs.idle(); @@ -312,18 +335,6 @@ test('openapi: live responses of the service conform to the description', async conform('stopJob', await call(port, 'POST', `/api/jobs/${missing}/stop`)); conform('getJobBundle', await call(port, 'GET', `/api/jobs/${missing}/bundle`)); - // a cancelled job without a report has no bundle - const exp = await call(port, 'POST', '/api/experiments', { body: JSON.stringify({ design: AES_DESIGN, profile: 'quick' }) }); - const expId = (conform('submitExperiment', exp) as { job: { id: string } }).job.id; - conform('stopJob', await call(port, 'POST', `/api/jobs/${expId}/stop`)); - await jobs.idle(); - const stopped = conform('getJob', await call(port, 'GET', `/api/jobs/${expId}`)) as { state: string; bundle: boolean }; - if (!stopped.bundle) { - const none = await call(port, 'GET', `/api/jobs/${expId}/bundle`); - conform('getJobBundle', none); - assert.equal(JSON.parse(none.body.toString()).error.code, 'not-ready'); - } - // methods the description does not list are not served on described paths for (const [path, item] of Object.entries(paths)) { if (!path.startsWith('/api/')) continue; @@ -334,10 +345,123 @@ test('openapi: live responses of the service conform to the description', async assert.ok(r.status === 404 || r.status === 405, `${m} ${path} answered ${r.status}`); } } - for (const s of ['submitAnalysis 400', 'submitAnalysis 403', 'submitAnalysis 415', 'getCapabilities 403', 'getJob 404', 'getJobBundle 200', 'stopJob 200']) { - assert.ok(seen.has(s), `not exercised: ${s}`); + assertExercised(seen, [ + 'getCapabilities 200', + 'getCapabilities 403', + 'getOpenApi 200', + 'getWebUi 200', + 'submitAnalysis 202', + 'submitAnalysis 400', + 'submitAnalysis 403', + 'submitAnalysis 413', + 'submitAnalysis 415', + 'submitExperiment 400', + 'getJob 200', + 'getJob 404', + 'getJobBundle 200', + 'getJobBundle 404', + 'stopJob 200', + 'stopJob 404', + ]); + } finally { + jobs.stopAll(); + await jobs.idle(); + await new Promise((r) => server.close(() => r())); + rmSync(root, { recursive: true, force: true }); + } +}); + +/** A pipeline that holds the single run slot until stopped or released, publishing a partial report. */ +function blockingPipeline(release: Promise) { + return async (_env: PipelineEnv, ctx: JobContext): Promise => { + ctx.start('validate'); + ctx.finish('validate', 'completed'); + const partial: AnalysisReport = { + kind: 'analysis', + id: ctx.id, + inputDigest: `sha256:${'0'.repeat(64)}`, + inputs: { design: AES_DESIGN }, + claims: [], + execution: { state: 'running', steps: ctx.executionSteps() }, + provenance: { origin: 'live', checker: 'cryptificate test', toolchain: { lean: 'v', mathlib: 'm', widetrail: 'w', rustc: 'r' } }, + }; + ctx.setReport(partial); + await new Promise((resolve) => { + ctx.signal.addEventListener('abort', () => resolve(), { once: true }); + void release.then(resolve); + }); + const state = ctx.cancelled ? ('cancelled' as const) : ('completed' as const); + ctx.closeRemaining(ctx.cancelled ? 'cancelled' : 'not_run'); + const r = { ...partial, execution: { state, steps: ctx.executionSteps() } }; + ctx.setReport(r); + return { state, report: r }; + }; +} + +test('openapi: queued, running and cancelled jobs answer as described', async () => { + const { root, env } = makeFixture(); + let release!: () => void; + const gate = new Promise((r) => (release = r)); + const pipeline = blockingPipeline(gate); + const jobs = new JobManager({ env, pipelines: { analysis: pipeline, experiment: pipeline } }); + const server = createApp({ env, jobs, host: '127.0.0.1', port: 0, webDist: null }); + await new Promise((r) => server.listen(0, '127.0.0.1', () => r())); + const port = (server.address() as AddressInfo).port; + const { conform, seen } = conformer(); + const submit = async (operationId: 'submitAnalysis' | 'submitExperiment'): Promise => + operationId === 'submitAnalysis' + ? call(port, 'POST', '/api/analyses', { body: JSON.stringify({ design: AES_DESIGN }) }) + : call(port, 'POST', '/api/experiments', { body: JSON.stringify({ design: AES_DESIGN, profile: 'quick' }) }); + const error = (res: Res): { code: string; message: string } => (JSON.parse(res.body.toString('utf8')) as { error: { code: string; message: string } }).error; + try { + // the first job takes the run slot and holds it until stopped + const first = (conform('submitAnalysis', await submit('submitAnalysis')) as { job: { id: string } }).job.id; + const second = (conform('submitExperiment', await submit('submitExperiment')) as { job: { id: string } }).job.id; + const running = conform('getJob', await call(port, 'GET', `/api/jobs/${first}`)) as { state: string }; + assert.equal(running.state, 'running'); + const queued = conform('getJob', await call(port, 'GET', `/api/jobs/${second}`)) as { state: string; queuePosition?: number }; + assert.equal(queued.state, 'queued'); + assert.equal(queued.queuePosition, 1); + + for (const id of [first, second]) { + const notYet = await call(port, 'GET', `/api/jobs/${id}/bundle`); + assert.equal(notYet.status, 409); + conform('getJobBundle', notYet); + assert.deepEqual(error(notYet), { code: 'not-ready', message: 'the job has not finished' }); } + + // one job runs and two wait: a further submission is refused + const third = (conform('submitAnalysis', await submit('submitAnalysis')) as { job: { id: string } }).job.id; + for (const operationId of ['submitAnalysis', 'submitExperiment'] as const) { + const full = await submit(operationId); + assert.equal(full.status, 429); + assert.equal(full.headers['retry-after'], '30'); + conform(operationId, full); + assert.equal(error(full).code, 'queue-full'); + } + + // a queued job that is stopped never runs and has no report, hence no bundle + conform('stopJob', await call(port, 'POST', `/api/jobs/${second}/stop`)); + const cancelled = conform('getJob', await call(port, 'GET', `/api/jobs/${second}`)) as { state: string; bundle: boolean; report: unknown }; + assert.deepEqual([cancelled.state, cancelled.bundle, cancelled.report], ['cancelled', false, null]); + const none = await call(port, 'GET', `/api/jobs/${second}/bundle`); + assert.equal(none.status, 409); + conform('getJobBundle', none); + assert.deepEqual(error(none), { code: 'not-ready', message: 'the job ended before it produced a report' }); + + // a running job that is stopped keeps its partial report, which has a bundle + conform('stopJob', await call(port, 'POST', `/api/jobs/${first}/stop`)); + release(); + await jobs.idle(); + const stopped = conform('getJob', await call(port, 'GET', `/api/jobs/${first}`)) as { state: string; bundle: boolean }; + assert.deepEqual([stopped.state, stopped.bundle], ['cancelled', true]); + conform('getJobBundle', await call(port, 'GET', `/api/jobs/${first}/bundle`)); + const after = conform('getJob', await call(port, 'GET', `/api/jobs/${third}`)) as { state: string }; + assert.equal(after.state, 'completed'); + + assertExercised(seen, ['submitAnalysis 202', 'submitExperiment 202', 'submitAnalysis 429', 'submitExperiment 429', 'getJob 200', 'getJobBundle 409', 'getJobBundle 200', 'stopJob 200']); } finally { + release(); jobs.stopAll(); await jobs.idle(); await new Promise((r) => server.close(() => r())); From 8a7adcdc8dcf7e25f6586c93226dbad0a424ae35 Mon Sep 17 00:00:00 2001 From: tyler-turnpike <188578979+tyler-turnpike@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:41:25 +0000 Subject: [PATCH 9/9] docs: state the 404/405 rule for unmatched API requests exactly A GET or POST under /api/ that matches no route answers 404, also on a documented path with the other method; every other method, HEAD included, answers 405, and no Allow header is sent. The error table in docs/api.md now says this, matching the OpenAPI info text, and the live test checks each case. --- apps/server/src/server.ts | 5 +++-- apps/server/test/openapi.test.ts | 13 ++++++++++--- docs/api.md | 4 ++-- schemas/openapi.json | 2 +- 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 5ee6a6b..448948a 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -53,8 +53,9 @@ const MIME: Record = { /** * Every API route the service answers. The handler dispatches through this * table, and schemas/openapi.json describes exactly these operations (a test - * checks both directions). Any other path under /api/ answers 404 for GET and - * POST and 405 for other methods. + * checks both directions). A request under /api/ that matches no route (an + * unknown path, or a listed path with another method) answers 404 for GET and + * POST and 405 for any other method, HEAD included; no Allow header is sent. */ export const API_ROUTES = [ { method: 'GET', path: '/api/capabilities', operationId: 'getCapabilities' }, diff --git a/apps/server/test/openapi.test.ts b/apps/server/test/openapi.test.ts index 782401a..c5399d6 100644 --- a/apps/server/test/openapi.test.ts +++ b/apps/server/test/openapi.test.ts @@ -335,16 +335,23 @@ test('openapi: live responses of the service conform to the description', async conform('stopJob', await call(port, 'POST', `/api/jobs/${missing}/stop`)); conform('getJobBundle', await call(port, 'GET', `/api/jobs/${missing}/bundle`)); - // methods the description does not list are not served on described paths + // methods the description does not list are not served on described paths: + // GET and POST answer 404 (as for an unknown path), every other method 405, + // and no answer carries an Allow header (as the info description states) for (const [path, item] of Object.entries(paths)) { if (!path.startsWith('/api/')) continue; const concrete = path.replace('{id}', id); - for (const m of ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']) { + for (const m of ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']) { if (item[m.toLowerCase()]) continue; const r = await call(port, m, concrete, m === 'POST' || m === 'PUT' || m === 'PATCH' ? { body: '{}' } : {}); - assert.ok(r.status === 404 || r.status === 405, `${m} ${path} answered ${r.status}`); + const want = m === 'GET' || m === 'POST' ? [404, 'not-found'] : [405, 'method-not-allowed']; + assert.equal(r.status, want[0], `${m} ${path}`); + assert.equal(r.headers['allow'], undefined, `${m} ${path}`); + if (m !== 'HEAD') assert.equal(JSON.parse(r.body.toString('utf8')).error.code, want[1], `${m} ${path}`); } } + const info = String((spec['info'] as Obj)['description']); + assert.ok(info.includes('404 `not-found` when its method is GET or POST, and 405 `method-not-allowed` for any other method'), 'the fallback rule is stated in info.description'); assertExercised(seen, [ 'getCapabilities 200', 'getCapabilities 403', diff --git a/docs/api.md b/docs/api.md index 8398272..3fae502 100644 --- a/docs/api.md +++ b/docs/api.md @@ -228,8 +228,8 @@ Every error is JSON, `{"error": {"code", "message"}}`, plus `errors` for 400 | 400 | `bad-json` | the body is not JSON | | 400 | `invalid-request` | the body is not a request of the documented shape (`errors` lists each issue) | | 403 | `forbidden` | the request failed the Host or Origin check | -| 404 | `not-found` | no such job, no such API path (GET or POST), or no `schemas/openapi.json` in this installation | -| 405 | `method-not-allowed` | another method on an API path, or a method other than GET and HEAD on a non-API path | +| 404 | `not-found` | no such job; a GET or POST under `/api/` that matches no route, including a documented path with the other method (`GET /api/analyses`, `POST /api/capabilities`); or no `schemas/openapi.json` in this installation | +| 405 | `method-not-allowed` | any method other than GET and POST under `/api/` (PUT, DELETE, PATCH, OPTIONS, and HEAD even on a GET endpoint), or a method other than GET and HEAD outside `/api/`; no `Allow` header is sent | | 409 | `not-ready` | bundle requested before the job finished, or for a job without a report or with an invalid request | | 413 | `body-too-large` | the body exceeds 256 KiB (a client still uploading may see the connection reset instead) | | 415 | `unsupported-media-type` | the body is not `Content-Type: application/json` | diff --git a/schemas/openapi.json b/schemas/openapi.json index 8361048..56a7b8b 100644 --- a/schemas/openapi.json +++ b/schemas/openapi.json @@ -5,7 +5,7 @@ "title": "Cryptificate local service", "version": "0.1.0", "summary": "Submit designs and circuits for Lean-checked analysis, run experiments, poll jobs and download evidence bundles.", - "description": "HTTP API of `cryptificate serve`, the local Cryptificate service. The web workbench and the Python client (`python/cryptificate`) use it; the `cryptificate check` and `experiment` commands run the same pipelines in-process instead.\n\n**Scope.** This document describes every route the service answers. Request and report bodies are described by the JSON Schemas in `schemas/` (referenced here with `$ref`); the served copy at `GET /api/openapi.json` embeds them under `components/schemas`. Examples are responses recorded from a live service (version 0.1.0, release engine, Lean checker), except the 500 example, which shows the fixed body of that response. Field elements are strings: two hex digits for GF(2^8), canonical decimals below the modulus for BN254.\n\n**Security model.** The service is a single-user local tool and has no authentication. It binds to 127.0.0.1 by default; `--host` can bind elsewhere, and then anyone who can reach the address can run jobs. Every request must carry a `Host` header naming a loopback address (`127.0.0.1`, `localhost`, `::1`) or the bound host, which rejects DNS-rebinding pages. State-changing requests (every method other than GET, HEAD and OPTIONS) are accepted only same-origin: when an `Origin` header is present it must be `http://:` of this service or one of the origins given with `--allow-origin` / `CRYPTIFICATE_ALLOWED_ORIGINS`; without `Origin`, a `Sec-Fetch-Site` header other than `same-origin` or `none` is rejected. Clients outside a browser (curl, Python) send neither header and are accepted. A rejected request gets 403 `forbidden`. There are no CORS headers: cross-origin browser reads are not supported. Every response carries `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer` and `Cross-Origin-Resource-Policy: same-origin`.\n\n**Limits.** JSON bodies are at most 256 KiB (413 beyond, and the connection is closed). One job runs at a time and at most two wait behind it (`limits.maxQueued` in the capabilities); a further submission gets 429 with `Retry-After: 30`. There is no per-client rate limit beyond this queue. Each job runs under a time budget (`limits.analysisBudgetSeconds`, or the experiment profile's `budget.totalSeconds`), and each Lean run under `limits.leanTimeoutSeconds`.\n\n**Job lifecycle.** `POST /api/analyses` or `POST /api/experiments` answers 202 with a job summary and a `Location` header. The job moves `queued` -> `running` -> one of `completed`, `failed`, `timeout`, `cancelled` or `invalid` (terminal). Poll `GET /api/jobs/{id}`: while it runs, `steps` and a partial `report` are visible. When the state is terminal and `bundle` is true, `GET /api/jobs/{id}/bundle` returns the evidence bundle. Finished jobs survive a restart of the service (the 200 most recently updated are loaded at start). Jobs that were queued or running when the service stopped are not resumed: they read `cancelled`, or `failed` with error code `interrupted`. There is no endpoint that lists jobs; keep the ids you submit.\n\n**Errors.** Every error is JSON with a stable `error.code` (see `ErrorResponse`). Any other path under `/api/` answers 404 `not-found` to GET and POST and 405 `method-not-allowed` to other methods. An unexpected failure answers 500 `internal`.\n\n**Stability.** Paths, status codes, error codes and the members described in the schemas are the supported surface. New optional members may be added to responses; clients should ignore members they do not know. Requests are checked strictly: unknown members are rejected.", + "description": "HTTP API of `cryptificate serve`, the local Cryptificate service. The web workbench and the Python client (`python/cryptificate`) use it; the `cryptificate check` and `experiment` commands run the same pipelines in-process instead.\n\n**Scope.** This document describes every route the service answers. Request and report bodies are described by the JSON Schemas in `schemas/` (referenced here with `$ref`); the served copy at `GET /api/openapi.json` embeds them under `components/schemas`. Examples are responses recorded from a live service (version 0.1.0, release engine, Lean checker), except the 500 example, which shows the fixed body of that response. Field elements are strings: two hex digits for GF(2^8), canonical decimals below the modulus for BN254.\n\n**Security model.** The service is a single-user local tool and has no authentication. It binds to 127.0.0.1 by default; `--host` can bind elsewhere, and then anyone who can reach the address can run jobs. Every request must carry a `Host` header naming a loopback address (`127.0.0.1`, `localhost`, `::1`) or the bound host, which rejects DNS-rebinding pages. State-changing requests (every method other than GET, HEAD and OPTIONS) are accepted only same-origin: when an `Origin` header is present it must be `http://:` of this service or one of the origins given with `--allow-origin` / `CRYPTIFICATE_ALLOWED_ORIGINS`; without `Origin`, a `Sec-Fetch-Site` header other than `same-origin` or `none` is rejected. Clients outside a browser (curl, Python) send neither header and are accepted. A rejected request gets 403 `forbidden`. There are no CORS headers: cross-origin browser reads are not supported. Every response carries `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer` and `Cross-Origin-Resource-Policy: same-origin`.\n\n**Limits.** JSON bodies are at most 256 KiB (413 beyond, and the connection is closed). One job runs at a time and at most two wait behind it (`limits.maxQueued` in the capabilities); a further submission gets 429 with `Retry-After: 30`. There is no per-client rate limit beyond this queue. Each job runs under a time budget (`limits.analysisBudgetSeconds`, or the experiment profile's `budget.totalSeconds`), and each Lean run under `limits.leanTimeoutSeconds`.\n\n**Job lifecycle.** `POST /api/analyses` or `POST /api/experiments` answers 202 with a job summary and a `Location` header. The job moves `queued` -> `running` -> one of `completed`, `failed`, `timeout`, `cancelled` or `invalid` (terminal). Poll `GET /api/jobs/{id}`: while it runs, `steps` and a partial `report` are visible. When the state is terminal and `bundle` is true, `GET /api/jobs/{id}/bundle` returns the evidence bundle. Finished jobs survive a restart of the service (the 200 most recently updated are loaded at start). Jobs that were queued or running when the service stopped are not resumed: they read `cancelled`, or `failed` with error code `interrupted`. There is no endpoint that lists jobs; keep the ids you submit.\n\n**Errors.** Every error is JSON with a stable `error.code` (see `ErrorResponse`). A request under `/api/` that matches no operation described here (an unknown path, or a described path with a method it does not list) answers 404 `not-found` when its method is GET or POST, and 405 `method-not-allowed` for any other method, HEAD and OPTIONS included. No response sends an `Allow` header. An unexpected failure answers 500 `internal`.\n\n**Stability.** Paths, status codes, error codes and the members described in the schemas are the supported surface. New optional members may be added to responses; clients should ignore members they do not know. Requests are checked strictly: unknown members are rejected.", "license": { "name": "MIT", "identifier": "MIT"