Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,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
Expand Down Expand Up @@ -239,11 +241,11 @@ For an audit or a pull request, `npx cryptificate report <bundle> --format html
| [`lean/`](lean) | Circuit semantics, canonical-minor MDS certificates, counterexample lemmas, offsets, the execution bridge, S-box and exponent certificates, Pratt primality certificates, HADES full-round and partial-round bounds at widths 3 and 4, 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), [CI](docs/ci.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), [CI](docs/ci.md), [research directions](docs/research-directions.md) |

## Built on WideTrail

Expand Down
110 changes: 110 additions & 0 deletions apps/server/src/openapi.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>(); // 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<string, Json>();

/**
* 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;
}
134 changes: 100 additions & 34 deletions apps/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 { REPORT_HTML_CSP, reportHtmlFileName } from '@cryptificate/schema';
Expand All @@ -17,6 +17,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;
Expand Down Expand Up @@ -50,6 +51,48 @@ const MIME: Record<string, string> = {
'.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). 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' },
{ 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' },
{ method: 'GET', path: '/api/jobs/{id}/report.html', operationId: 'getJobReportHtml' },
] 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<string, string> }) | 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<string, string> = {};
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,
Expand Down Expand Up @@ -284,48 +327,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();
Expand All @@ -339,10 +402,16 @@ export function createApp(opts: ServerOptions): Server {
res.end(gz);
return;
}
if (parts.length === 4 && parts[3] === 'report.html' && method === 'GET') {
case 'getJobReportHtml': {
const view = jobs.view(rec);
if (!view.bundle || !view.report) {
sendError(res, 409, 'not-ready', view.state === 'invalid' ? 'invalid requests have no report' : 'the job has not finished');
const message =
view.state === 'invalid'
? 'invalid requests have no report'
: 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;
}
// Byte for byte the bundle's report.html: rendered from the bundled (path-scrubbed) report and pins.
Expand All @@ -358,9 +427,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') {
Expand Down
Loading
Loading