// K559 review-record gate for docs/production-write-guvenlik-incelemesi.md. Validates an independent // human security review of the production-write path: named reviewer with an independence statement, // SHA-256 of every reviewed artifact equal to the current tree, findings with severity and an explicit // sign-off. Model/automated "reviews" and stale or partial records are rejected. Even an accepted // record NEVER lifts the gate: production-write stays a compile_error until maintainers change code // after the review and P12 prerequisites; `--gate` re-runs scripts/test-production-write-gate.mjs. import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import { existsSync, readFileSync } from 'node:fs'; import { basename, dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; const root = join(dirname(fileURLToPath(import.meta.url)), '..'); const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex'); export const REVIEW_ARTIFACTS = Object.freeze([ 'kernel/Cargo.toml', 'kernel/src/lib.rs', 'kernel/src/main.rs', 'kernel/src/write_release.rs', 'kernel/src/journal.rs', 'kernel/src/journal_disk.rs', 'kernel/src/journal_probe.rs', 'kernel/src/virtio_mmio.rs', 'kernel/src/virtio_ring.rs', 'kernel/src/turkfs.rs', 'scripts/test-production-write-gate.mjs', 'scripts/continuation-security.mjs', 'scripts/turkfs-journal-decision.mjs', 'scripts/test-continuation-journal.mjs', ]); export const THREAT_MODEL_POINTERS = Object.freeze([ 'scripts/continuation-security.mjs#recoveryThreatModel', 'scripts/turkfs-journal-decision.mjs#journalDecision', 'kernel/src/write_release.rs#evaluate', 'docs/production-write-guvenlik-incelemesi.md', ]); export const SIGN_OFF = Object.freeze(['kapı-kapalı-kalmalı', 'koşullu-kaldırılabilir']); const SEVERITIES = ['kritik', 'yüksek', 'orta', 'düşük', 'bilgi']; const STATUS = ['açık', 'düzeltildi', 'kabul-edildi']; const word = (list) => new RegExp(`(?]*>|${word('TODO|TBD|örnek|ornek|Ad Soyad|YYYY|XXXX').source}`, 'iu'); const keys = (value, expected, label) => { assert.ok(value && typeof value === 'object' && !Array.isArray(value), `${label} must be an object`); assert.deepEqual(Object.keys(value).sort(), [...expected].sort(), `${label} fields`); }; const text = (value, label, min = 2) => { assert.equal(typeof value, 'string', `${label} must be text`); assert.ok(value.trim().length >= min, `${label} is empty`); assert.doesNotMatch(value, PLACEHOLDER, `${label} still contains a template placeholder`); }; const date = (value, label, today) => { assert.match(value, /^\d{4}-\d\d-\d\d$/, `${label} must be YYYY-MM-DD`); assert.ok(value >= '2026-10-06' && value <= today, `${label} outside 2026-10-06..${today}`); }; export function extractSecurityReview(raw) { const trimmed = raw.trim(); if (trimmed.startsWith('{')) return JSON.parse(trimmed); const blocks = [...raw.matchAll(/```json turkos-security-review\n([\s\S]*?)\n```/g)]; assert.equal(blocks.length, 1, 'exactly one ```json turkos-security-review block'); return JSON.parse(blocks[0][1]); } export function checkSecurityReview(record, options = {}) { const today = options.today ?? new Date().toISOString().slice(0, 10); const currentHash = options.currentHash ?? ((path) => existsSync(join(root, path)) ? sha256(readFileSync(join(root, path))) : null); const failures = []; const attempt = (code, fn) => { try { fn(); } catch (error) { failures.push({ code, detail: error.message.split('\n')[0] }); } }; attempt('schema', () => { keys(record, ['schema', 'record', 'scope', 'reviewer', 'date', 'artifacts', 'threatModelReviewed', 'methods', 'findings', 'signOff', 'signature', ...(options.allowSynthetic ? ['synthetic'] : [])], 'record'); assert.equal(record.schema, 'turkos-security-review/v1'); assert.equal(record.record, 'K559'); assert.equal(record.scope, 'production-write'); }); attempt('synthetic', () => assert.ok(!('synthetic' in record) || options.allowSynthetic, 'synthetic fixture is never a review')); attempt('reviewer', () => { keys(record.reviewer, ['name', 'organisation', 'role', 'contact', 'independence', 'conflictsOfInterest', 'isHuman'], 'reviewer'); text(record.reviewer.name, 'reviewer.name', 5); assert.match(record.reviewer.name, /\S+\s+\S+/u, 'reviewer.name must be a full name'); assert.doesNotMatch(record.reviewer.name, NOT_A_PERSON, 'reviewer is a model, tool or automation: a local model PASS is not a security review'); assert.equal(record.reviewer.isHuman, true, 'reviewer.isHuman must be true'); for (const field of ['organisation', 'role', 'contact', 'conflictsOfInterest']) text(record.reviewer[field], `reviewer.${field}`); text(record.reviewer.independence, 'reviewer.independence', 30); date(record.date, 'date', today); }); attempt('artifacts', () => { assert.ok(Array.isArray(record.artifacts), 'artifacts must be a list'); const listed = new Map(record.artifacts.map((artifact) => { keys(artifact, ['path', 'sha256'], 'artifact'); return [artifact.path, artifact.sha256]; })); const missing = REVIEW_ARTIFACTS.filter((path) => !listed.has(path)); assert.ok(missing.length === 0, `review does not cover: ${missing.join(', ')}`); }); attempt('stale-artifact', () => { const stale = (record.artifacts ?? []).filter((artifact) => artifact.sha256 !== currentHash(artifact.path)).map((artifact) => artifact.path); assert.ok(stale.length === 0, `reviewed bytes differ from the current tree: ${stale.join(', ')}`); }); attempt('threat-model', () => { const missing = THREAT_MODEL_POINTERS.filter((pointer) => !record.threatModelReviewed?.includes(pointer)); assert.ok(missing.length === 0, `threat model pointers not reviewed: ${missing.join(', ')}`); }); attempt('automated-only', () => { assert.ok(Array.isArray(record.methods) && record.methods.length > 0, 'methods must be listed'); for (const method of record.methods) text(method, 'method'); assert.ok(record.methods.includes('kaynak-kod-incelemesi'), 'a manual source review ("kaynak-kod-incelemesi") is required'); assert.ok(!record.methods.some((method) => AUTOMATED_ONLY.test(method)), 'model or automated PASS listed as a review method'); }); attempt('findings', () => { assert.ok(Array.isArray(record.findings), 'findings must be a list'); const ids = new Set(); for (const finding of record.findings) { keys(finding, ['id', 'severity', 'title', 'description', 'affected', 'status'], 'finding'); text(finding.id, 'finding.id'); assert.ok(!ids.has(finding.id), `duplicate finding ${finding.id}`); ids.add(finding.id); assert.ok(SEVERITIES.includes(finding.severity), `finding ${finding.id}: severity`); assert.ok(STATUS.includes(finding.status), `finding ${finding.id}: status`); text(finding.title, `finding ${finding.id} title`, 5); text(finding.description, `finding ${finding.id} description`, 20); assert.ok(Array.isArray(finding.affected) && finding.affected.length > 0 && finding.affected.every((path) => REVIEW_ARTIFACTS.includes(path.split('#')[0])), `finding ${finding.id}: affected artifacts`); } }); attempt('sign-off', () => { keys(record.signOff, ['decision', 'conditions', 'statement'], 'signOff'); assert.ok(SIGN_OFF.includes(record.signOff.decision), `signOff.decision must be ${SIGN_OFF.join(' | ')}`); text(record.signOff.statement, 'signOff.statement', 30); assert.ok(Array.isArray(record.signOff.conditions)); if (record.signOff.decision === 'koşullu-kaldırılabilir') { assert.ok(record.signOff.conditions.length > 0, 'conditional sign-off needs conditions'); const open = (record.findings ?? []).filter((f) => ['kritik', 'yüksek'].includes(f.severity) && f.status === 'açık'); assert.ok(open.length === 0, `conditional sign-off with open critical/high findings: ${open.map((f) => f.id).join(', ')}`); } }); attempt('signature', () => { keys(record.signature, ['name', 'date', 'statement'], 'signature'); assert.equal(record.signature.name, record.reviewer?.name, 'signature must be the reviewer'); date(record.signature.date, 'signature.date', today); assert.ok(record.signature.date >= record.date, 'signature predates the review'); text(record.signature.statement, 'signature.statement', 30); }); return { accepted: failures.length === 0, failures, gateLifted: false, decision: failures.length === 0 ? record.signOff.decision : null, boundary: 'An accepted record is reviewer input only. production-write remains a compile_error; lifting it needs a separate maintainer code change plus the P12 journal/recovery prerequisites.' }; } export function productionWriteGateStillClosed() { const result = spawnSync('node', ['scripts/test-production-write-gate.mjs'], { cwd: root, encoding: 'utf8', timeout: 600_000, maxBuffer: 8 * 1024 * 1024 }); assert.equal(result.status, 0, `production-write gate test failed: ${result.stderr}\n${result.stdout}`); assert.match(result.stdout, /PASS: K400 production flag alone fails closed at compile gate/); return result.stdout.trim().split('\n'); } if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const args = process.argv.slice(2); if (args[0] === '--artifacts') { // Current SHA-256 of every artifact the reviewer must cover, ready to paste into the record. console.log(JSON.stringify(REVIEW_ARTIFACTS.map((path) => ({ path, sha256: sha256(readFileSync(join(root, path))) })), null, 2)); process.exit(0); } const gate = args.includes('--gate'); const input = args.find((arg) => arg !== '--gate'); if (!input || !existsSync(input)) { console.error('usage: node scripts/check-security-review.mjs [--gate] | --artifacts'); process.exit(64); } let verdict; try { verdict = checkSecurityReview(extractSecurityReview(readFileSync(input, 'utf8'))); } catch (error) { verdict = { accepted: false, failures: [{ code: 'parse', detail: error.message }], gateLifted: false }; } console.log(JSON.stringify({ input: basename(input), ...verdict }, null, 2)); if (gate) console.log(productionWriteGateStillClosed().join('\n')); console.log(verdict.accepted ? 'ACCEPTED: complete K559 review record. The production-write gate stays closed; no status was changed.' : `REJECTED: ${[...new Set(verdict.failures.map((f) => f.code))].join(', ')}`); process.exit(verdict.accepted ? 0 : 1); }