feat: bhl report validate по схемам отчёта аудита (BHL-023)
- packages/bhl/src/report.ts: схема audit-report + ссылки на требования + сверка сводки - EXEMPT без exemption_ref и отчёт вне схемы отклоняются с диагностикой - пакет: 24/24 тестов
This commit is contained in:
@@ -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