feat: bhl report validate по схемам отчёта аудита (BHL-023)
- packages/bhl/src/report.ts: схема audit-report + ссылки на требования + сверка сводки - EXEMPT без exemption_ref и отчёт вне схемы отклоняются с диагностикой - пакет: 24/24 тестов
This commit is contained in:
+64
-1
@@ -1,11 +1,13 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts';
|
||||
import { resolveProfiles } from './resolve.ts';
|
||||
import { validateReport } from './report.ts';
|
||||
import { validateSpec } from './validate.ts';
|
||||
|
||||
const USAGE_MESSAGE =
|
||||
'Usage: bhl <version|validate|spec|profile|report|audit> [args]; ' +
|
||||
'profile resolve <spec-root> [--profile <id>] [--preset <id>]; ' +
|
||||
'report validate <report.json> [--spec-root <path>]; ' +
|
||||
'JSON envelope on stdout; exit codes: 0 ok, 1 validation failed, 2 usage, ' +
|
||||
'3 not implemented, 4 internal.';
|
||||
|
||||
@@ -138,6 +140,64 @@ function runProfile(command: string, rest: readonly string[]): number {
|
||||
return ExitCode.ValidationFailed;
|
||||
}
|
||||
|
||||
function parseReportArgs(
|
||||
args: readonly string[],
|
||||
): { file: string; specRoot: string } | { error: string } {
|
||||
let specRoot = 'spec';
|
||||
const positional: string[] = [];
|
||||
let cursor = 0;
|
||||
while (cursor < args.length) {
|
||||
const arg = args[cursor] ?? '';
|
||||
if (arg === '--spec-root') {
|
||||
const value = args[cursor + 1];
|
||||
if (value === undefined) {
|
||||
return { error: 'missing value for --spec-root' };
|
||||
}
|
||||
specRoot = value;
|
||||
cursor += 2;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--')) {
|
||||
return { error: `unknown flag ${arg}` };
|
||||
}
|
||||
positional.push(arg);
|
||||
cursor += 1;
|
||||
}
|
||||
if (positional.length !== 1) {
|
||||
return { error: 'report validate requires exactly one report file' };
|
||||
}
|
||||
return { file: positional[0] ?? '', specRoot };
|
||||
}
|
||||
|
||||
function runReport(command: string, rest: readonly string[]): number {
|
||||
const [sub, ...args] = rest;
|
||||
if (sub !== 'validate') {
|
||||
emit(failEnvelope(command, 'USAGE', 'report requires the subcommand validate'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const parsed = parseReportArgs(args);
|
||||
if ('error' in parsed) {
|
||||
emit(failEnvelope(command, 'USAGE', parsed.error));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const result = validateReport(parsed.file, parsed.specRoot);
|
||||
const data = { file: parsed.file, spec_root: parsed.specRoot, errors: result.diagnostics };
|
||||
if (result.ok) {
|
||||
emit(okEnvelope(command, data));
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
emit({
|
||||
ok: false,
|
||||
command,
|
||||
data,
|
||||
error: {
|
||||
code: 'VALIDATION_FAILED',
|
||||
message: `${String(result.diagnostics.length)} diagnostic(s)`,
|
||||
},
|
||||
});
|
||||
return ExitCode.ValidationFailed;
|
||||
}
|
||||
|
||||
function runValidate(command: string, rest: readonly string[]): number {
|
||||
const [root] = rest;
|
||||
if (root === undefined || root.startsWith('--')) {
|
||||
@@ -179,7 +239,10 @@ export function run(argv: readonly string[]): number {
|
||||
if (command === 'validate') {
|
||||
return runValidate(command, rest);
|
||||
}
|
||||
if (command === 'spec' || command === 'report' || command === 'audit') {
|
||||
if (command === 'report') {
|
||||
return runReport(command, rest);
|
||||
}
|
||||
if (command === 'spec' || command === 'audit') {
|
||||
emit(failEnvelope(command, 'NOT_IMPLEMENTED', `${command} is not implemented yet`));
|
||||
return ExitCode.NotImplemented;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Ajv2020 } from 'ajv/dist/2020.js';
|
||||
import type { Schema } from 'ajv';
|
||||
import { parseDocument } from 'yaml';
|
||||
import type { Diagnostic } from './validate.ts';
|
||||
|
||||
export interface ReportValidationResult {
|
||||
ok: boolean;
|
||||
diagnostics: Diagnostic[];
|
||||
}
|
||||
|
||||
const SCHEMA_BASE = 'https://baseline-harness.dev/spec/schemas/';
|
||||
|
||||
const FINDING_STATUSES: readonly string[] = [
|
||||
'PASS',
|
||||
'FAIL',
|
||||
'PARTIAL',
|
||||
'EXEMPT',
|
||||
'NOT_APPLICABLE',
|
||||
'UNKNOWN',
|
||||
'BLOCKED',
|
||||
];
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isSchema(value: unknown): value is Schema {
|
||||
return (typeof value === 'object' && value !== null) || typeof value === 'boolean';
|
||||
}
|
||||
|
||||
function isString(value: unknown): value is string {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
|
||||
function schemaFiles(schemasDir: string): string[] {
|
||||
return readdirSync(schemasDir, { withFileTypes: true })
|
||||
.filter((entry) => entry.isFile() && entry.name.endsWith('.schema.json'))
|
||||
.map((entry) => path.join(schemasDir, entry.name))
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
function loadAjv(schemasDir: string, diagnostics: Diagnostic[]): Ajv2020 | undefined {
|
||||
if (!existsSync(schemasDir)) {
|
||||
diagnostics.push({
|
||||
file: schemasDir,
|
||||
code: 'missing-directory',
|
||||
message: 'schemas/ is required',
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
const ajv = new Ajv2020({ strict: true, strictTypes: false, allErrors: true });
|
||||
for (const file of schemaFiles(schemasDir)) {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(file, 'utf8'));
|
||||
} catch {
|
||||
diagnostics.push({ file, code: 'parse-error', message: 'schema file is not valid JSON' });
|
||||
continue;
|
||||
}
|
||||
if (isSchema(parsed)) {
|
||||
ajv.addSchema(parsed);
|
||||
}
|
||||
}
|
||||
return ajv;
|
||||
}
|
||||
|
||||
function readReport(file: string, diagnostics: Diagnostic[]): unknown {
|
||||
let text: string;
|
||||
try {
|
||||
text = readFileSync(file, 'utf8');
|
||||
} catch {
|
||||
diagnostics.push({ file, code: 'read-error', message: 'report file is not readable' });
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
diagnostics.push({ file, code: 'parse-error', message: 'report is not valid JSON' });
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function requirementIds(specRoot: string, diagnostics: Diagnostic[]): Set<string> {
|
||||
const ids = new Set<string>();
|
||||
const dir = path.join(specRoot, 'requirements');
|
||||
if (!existsSync(dir)) {
|
||||
diagnostics.push({
|
||||
file: dir,
|
||||
code: 'missing-directory',
|
||||
message: 'requirements/ is required',
|
||||
});
|
||||
return ids;
|
||||
}
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (!name.endsWith('.yaml')) {
|
||||
continue;
|
||||
}
|
||||
const file = path.join(dir, name);
|
||||
try {
|
||||
const doc: unknown = parseDocument(readFileSync(file, 'utf8'), { logLevel: 'silent' }).toJS({
|
||||
maxAliasCount: 5,
|
||||
});
|
||||
if (isRecord(doc) && isString(doc['id'])) {
|
||||
ids.add(doc['id']);
|
||||
}
|
||||
} catch {
|
||||
diagnostics.push({ file, code: 'parse-error', message: 'requirement file is not parseable' });
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function checkSchema(ajv: Ajv2020, report: unknown, file: string, diagnostics: Diagnostic[]): void {
|
||||
const validateFn = ajv.getSchema(`${SCHEMA_BASE}audit-report.schema.json`);
|
||||
if (validateFn === undefined) {
|
||||
diagnostics.push({
|
||||
file,
|
||||
code: 'missing-schema',
|
||||
message: 'audit-report schema is not loaded',
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (validateFn(report) === true) {
|
||||
return;
|
||||
}
|
||||
for (const err of validateFn.errors ?? []) {
|
||||
const where = err.instancePath === '' ? '/' : err.instancePath;
|
||||
diagnostics.push({
|
||||
file,
|
||||
pointer: err.instancePath,
|
||||
code: 'schema-error',
|
||||
message: `${where}: ${err.message ?? 'invalid'}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function checkFindingReferences(
|
||||
report: Record<string, unknown>,
|
||||
file: string,
|
||||
requirements: Set<string>,
|
||||
diagnostics: Diagnostic[],
|
||||
): void {
|
||||
const findings = Array.isArray(report['findings']) ? report['findings'] : [];
|
||||
const items: readonly unknown[] = findings;
|
||||
for (const finding of items) {
|
||||
if (!isRecord(finding) || !isString(finding['requirement'])) {
|
||||
continue;
|
||||
}
|
||||
if (!requirements.has(finding['requirement'])) {
|
||||
diagnostics.push({
|
||||
file,
|
||||
code: 'unknown-requirement',
|
||||
message: `finding references undefined requirement ${finding['requirement']}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function statusCounts(report: Record<string, unknown>): Map<string, number> {
|
||||
const counts = new Map<string, number>();
|
||||
const findings = Array.isArray(report['findings']) ? report['findings'] : [];
|
||||
const items: readonly unknown[] = findings;
|
||||
for (const finding of items) {
|
||||
if (isRecord(finding) && isString(finding['status'])) {
|
||||
counts.set(finding['status'], (counts.get(finding['status']) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
function checkSummary(
|
||||
report: Record<string, unknown>,
|
||||
file: string,
|
||||
diagnostics: Diagnostic[],
|
||||
): void {
|
||||
const summary = report['summary'];
|
||||
if (!isRecord(summary)) {
|
||||
return;
|
||||
}
|
||||
const counts = statusCounts(report);
|
||||
for (const status of FINDING_STATUSES) {
|
||||
const declared = summary[status];
|
||||
const actual = counts.get(status) ?? 0;
|
||||
if (typeof declared === 'number' && declared !== actual) {
|
||||
diagnostics.push({
|
||||
file,
|
||||
code: 'summary-mismatch',
|
||||
message: `summary ${status}=${String(declared)} but findings contain ${String(actual)}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
const extra = Object.keys(summary).filter((key) => !FINDING_STATUSES.includes(key));
|
||||
for (const key of extra) {
|
||||
diagnostics.push({
|
||||
file,
|
||||
code: 'summary-mismatch',
|
||||
message: `summary has unknown status ${key}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function validateReport(reportFile: string, specRoot: string): ReportValidationResult {
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
const report = readReport(reportFile, diagnostics);
|
||||
if (report === undefined) {
|
||||
return { ok: false, diagnostics };
|
||||
}
|
||||
const ajv = loadAjv(path.join(specRoot, 'schemas'), diagnostics);
|
||||
if (ajv === undefined) {
|
||||
return { ok: false, diagnostics };
|
||||
}
|
||||
checkSchema(ajv, report, reportFile, diagnostics);
|
||||
if (isRecord(report)) {
|
||||
checkFindingReferences(report, reportFile, requirementIds(specRoot, diagnostics), diagnostics);
|
||||
checkSummary(report, reportFile, diagnostics);
|
||||
}
|
||||
diagnostics.sort((a, b) =>
|
||||
`${a.file} ${a.code} ${a.pointer ?? ''}`.localeCompare(
|
||||
`${b.file} ${b.code} ${b.pointer ?? ''}`,
|
||||
),
|
||||
);
|
||||
return { ok: diagnostics.length === 0, diagnostics };
|
||||
}
|
||||
Reference in New Issue
Block a user