feat: схемы отчёта аудита, профили/пресеты и движок разрешения (BHL-019, BHL-012, BHL-013)
- spec/schemas: evidence, audit-finding, audit-report (BHL-019) - spec/schemas: profile, preset с явным relax_to (BHL-012) - packages/bhl: resolve.ts + bhl profile resolve — порядок не влияет, конфликты параметров и ослаблений, provenance и applicability (BHL-012, BHL-013) - tests: корневые схемы 13/13, пакет 17/17
This commit is contained in:
@@ -0,0 +1,574 @@
|
||||
import { existsSync, readdirSync, readFileSync } 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 EffectiveParameter {
|
||||
parameter: string;
|
||||
value: unknown;
|
||||
source: string;
|
||||
}
|
||||
|
||||
export interface EffectiveRequirement {
|
||||
requirement: string;
|
||||
level: string;
|
||||
sources: string[];
|
||||
applicability: { when: string; unless?: string }[];
|
||||
parameters: EffectiveParameter[];
|
||||
}
|
||||
|
||||
export interface ResolveResult {
|
||||
ok: boolean;
|
||||
profiles: string[];
|
||||
effective: EffectiveRequirement[];
|
||||
diagnostics: Diagnostic[];
|
||||
}
|
||||
|
||||
interface ParamDef {
|
||||
type: string;
|
||||
default: unknown;
|
||||
constraints: Record<string, unknown>;
|
||||
file: string;
|
||||
}
|
||||
|
||||
interface ProfileEntry {
|
||||
requirement: string;
|
||||
relax_to?: string;
|
||||
}
|
||||
|
||||
interface ProfileDoc {
|
||||
id: string;
|
||||
file: string;
|
||||
requirements: ProfileEntry[];
|
||||
overrides: { parameter: string; value: unknown }[];
|
||||
}
|
||||
|
||||
const SCHEMA_BASE = 'https://baseline-harness.dev/spec/schemas/';
|
||||
|
||||
const LEVEL_RANK: Readonly<Record<string, number>> = {
|
||||
MUST: 3,
|
||||
'MUST NOT': 3,
|
||||
SHOULD: 2,
|
||||
'SHOULD NOT': 2,
|
||||
MAY: 1,
|
||||
};
|
||||
|
||||
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 sameValue(a: unknown, b: unknown): boolean {
|
||||
return JSON.stringify(a) === JSON.stringify(b);
|
||||
}
|
||||
|
||||
function readYaml(file: string, diagnostics: Diagnostic[]): unknown {
|
||||
let text: string;
|
||||
try {
|
||||
text = readFileSync(file, 'utf8');
|
||||
} catch {
|
||||
diagnostics.push({ file, code: 'read-error', message: 'file is not readable' });
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const doc = parseDocument(text, { prettyErrors: false, logLevel: 'silent' });
|
||||
if (doc.errors.length > 0) {
|
||||
const first = doc.errors[0];
|
||||
diagnostics.push({
|
||||
file,
|
||||
code: 'parse-error',
|
||||
message: `YAML error at line ${String(first?.linePos?.[0]?.line ?? 1)}: ${first?.message ?? 'invalid'}`,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
return doc.toJS({ maxAliasCount: 5 });
|
||||
} catch {
|
||||
diagnostics.push({ file, code: 'parse-error', message: 'YAML is not parseable' });
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function filesIn(dir: string, suffix: string): string[] {
|
||||
if (!existsSync(dir)) {
|
||||
return [];
|
||||
}
|
||||
return readdirSync(dir, { withFileTypes: true })
|
||||
.filter((entry) => entry.isFile() && entry.name.endsWith(suffix))
|
||||
.map((entry) => path.join(dir, entry.name))
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
function validateWith(
|
||||
ajv: Ajv2020,
|
||||
kind: string,
|
||||
value: Record<string, unknown>,
|
||||
file: string,
|
||||
diagnostics: Diagnostic[],
|
||||
): boolean {
|
||||
const validateFn = ajv.getSchema(`${SCHEMA_BASE}${kind}.schema.json`);
|
||||
if (validateFn === undefined) {
|
||||
diagnostics.push({ file, code: 'missing-schema', message: `schema ${kind} is not loaded` });
|
||||
return false;
|
||||
}
|
||||
if (validateFn(value) === true) {
|
||||
return true;
|
||||
}
|
||||
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'}`,
|
||||
});
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function loadDocs(
|
||||
dir: string,
|
||||
kind: string,
|
||||
ajv: Ajv2020,
|
||||
diagnostics: Diagnostic[],
|
||||
): Record<string, Record<string, unknown>> {
|
||||
const docs: Record<string, Record<string, unknown>> = {};
|
||||
for (const file of filesIn(dir, '.yaml')) {
|
||||
const value = readYaml(file, diagnostics);
|
||||
if (!isRecord(value)) {
|
||||
if (value !== undefined) {
|
||||
diagnostics.push({ file, code: 'parse-error', message: 'top level must be a mapping' });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!validateWith(ajv, kind, value, file, diagnostics)) {
|
||||
continue;
|
||||
}
|
||||
const id = value['id'];
|
||||
if (isString(id)) {
|
||||
docs[id] = value;
|
||||
}
|
||||
}
|
||||
return docs;
|
||||
}
|
||||
|
||||
function paramDef(value: Record<string, unknown>, file: string): ParamDef {
|
||||
return {
|
||||
type: isString(value['type']) ? value['type'] : 'string',
|
||||
default: value['default'],
|
||||
constraints: isRecord(value['constraints']) ? value['constraints'] : {},
|
||||
file,
|
||||
};
|
||||
}
|
||||
|
||||
function collectParamDefs(
|
||||
requirements: Record<string, Record<string, unknown>>,
|
||||
registry: Record<string, ParamDef>,
|
||||
): Record<string, ParamDef> {
|
||||
const defs: Record<string, ParamDef> = { ...registry };
|
||||
for (const [reqId, requirement] of Object.entries(requirements)) {
|
||||
const items = Array.isArray(requirement['parameters']) ? requirement['parameters'] : [];
|
||||
const known: readonly unknown[] = items;
|
||||
for (const item of known) {
|
||||
if (isRecord(item) && isString(item['id'])) {
|
||||
defs[item['id']] = paramDef(item, `requirement ${reqId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return defs;
|
||||
}
|
||||
|
||||
function numericOk(value: unknown, c: Record<string, unknown>): boolean {
|
||||
const min = c['minimum'];
|
||||
const max = c['maximum'];
|
||||
if (typeof min !== 'number' && typeof max !== 'number') {
|
||||
return true;
|
||||
}
|
||||
if (typeof value !== 'number') {
|
||||
return false;
|
||||
}
|
||||
if (typeof min === 'number' && value < min) {
|
||||
return false;
|
||||
}
|
||||
return !(typeof max === 'number' && value > max);
|
||||
}
|
||||
|
||||
function enumOk(value: unknown, c: Record<string, unknown>): boolean {
|
||||
const values = c['values'];
|
||||
return !Array.isArray(values) || values.some((item) => sameValue(item, value));
|
||||
}
|
||||
|
||||
function stringOk(value: unknown, c: Record<string, unknown>): boolean {
|
||||
const pattern = c['pattern'];
|
||||
if (
|
||||
typeof pattern === 'string' &&
|
||||
(typeof value !== 'string' || !new RegExp(pattern).test(value))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const min = c['minLength'];
|
||||
const max = c['maxLength'];
|
||||
if (typeof min === 'number' && (typeof value !== 'string' || value.length < min)) {
|
||||
return false;
|
||||
}
|
||||
return !(typeof max === 'number' && typeof value === 'string' && value.length > max);
|
||||
}
|
||||
|
||||
function valueInConstraints(value: unknown, def: ParamDef): boolean {
|
||||
const c = def.constraints;
|
||||
return numericOk(value, c) && enumOk(value, c) && stringOk(value, c);
|
||||
}
|
||||
|
||||
function isWeaker(base: string, relaxed: string): boolean {
|
||||
if (base !== 'MUST' && base !== 'SHOULD') {
|
||||
return false;
|
||||
}
|
||||
return (LEVEL_RANK[relaxed] ?? 0) < (LEVEL_RANK[base] ?? 0);
|
||||
}
|
||||
|
||||
class Resolver {
|
||||
private readonly ajv = new Ajv2020({ strict: true, strictTypes: false, allErrors: true });
|
||||
private readonly diagnostics: Diagnostic[] = [];
|
||||
private readonly root: string;
|
||||
|
||||
constructor(root: string) {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
run(profileIds: string[], presetIds: string[]): ResolveResult {
|
||||
if (!this.addSchemas()) {
|
||||
return { ok: false, profiles: [], effective: [], diagnostics: this.diagnostics };
|
||||
}
|
||||
const requirements = loadDocs(
|
||||
path.join(this.root, 'requirements'),
|
||||
'requirement',
|
||||
this.ajv,
|
||||
this.diagnostics,
|
||||
);
|
||||
const registry = loadParameterRegistry(this.root, this.diagnostics);
|
||||
const profiles = this.loadProfiles();
|
||||
const presets = loadPresets(this.root, this.ajv, this.diagnostics);
|
||||
const selected = this.selectProfiles(profileIds, presetIds, profiles, presets);
|
||||
const defs = collectParamDefs(requirements, registry);
|
||||
const applied = this.applyOverrides(selected, defs);
|
||||
const effective = this.buildEffective(selected, requirements, defs, applied);
|
||||
this.diagnostics.sort((a, b) => `${a.file}${a.code}`.localeCompare(`${b.file}${b.code}`));
|
||||
return {
|
||||
ok: this.diagnostics.length === 0,
|
||||
profiles: selected.map((profile) => profile.id),
|
||||
effective,
|
||||
diagnostics: this.diagnostics,
|
||||
};
|
||||
}
|
||||
|
||||
private push(file: string, code: string, message: string): void {
|
||||
this.diagnostics.push({ file, code, message });
|
||||
}
|
||||
|
||||
private addSchemas(): boolean {
|
||||
const schemasDir = path.join(this.root, 'schemas');
|
||||
const names = filesIn(schemasDir, '.schema.json');
|
||||
if (names.length === 0) {
|
||||
this.push(
|
||||
'schemas/',
|
||||
'missing-directory',
|
||||
'spec root must contain schemas/ with *.schema.json',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
for (const file of names) {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(file, 'utf8'));
|
||||
} catch {
|
||||
this.push(file, 'parse-error', 'schema file is not valid JSON');
|
||||
continue;
|
||||
}
|
||||
if (isSchema(parsed)) {
|
||||
this.ajv.addSchema(parsed);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private loadProfiles(): Record<string, ProfileDoc> {
|
||||
const docs = loadDocs(path.join(this.root, 'profiles'), 'profile', this.ajv, this.diagnostics);
|
||||
const profiles: Record<string, ProfileDoc> = {};
|
||||
for (const [id, value] of Object.entries(docs)) {
|
||||
profiles[id] = {
|
||||
id,
|
||||
file: `profiles/${id}.yaml`,
|
||||
requirements: profileEntries(value),
|
||||
overrides: profileOverrides(value),
|
||||
};
|
||||
}
|
||||
return profiles;
|
||||
}
|
||||
|
||||
private selectProfiles(
|
||||
profileIds: string[],
|
||||
presetIds: string[],
|
||||
profiles: Record<string, ProfileDoc>,
|
||||
presets: Record<string, string[]>,
|
||||
): ProfileDoc[] {
|
||||
const ids = new Set<string>(profileIds);
|
||||
for (const presetId of presetIds) {
|
||||
const expanded = presets[presetId];
|
||||
if (expanded === undefined) {
|
||||
this.push('presets/', 'unknown-preset', `preset ${presetId} is not defined`);
|
||||
continue;
|
||||
}
|
||||
for (const profileId of expanded) {
|
||||
ids.add(profileId);
|
||||
}
|
||||
}
|
||||
const selected: ProfileDoc[] = [];
|
||||
for (const id of [...ids].sort((a, b) => a.localeCompare(b))) {
|
||||
const profile = profiles[id];
|
||||
if (profile === undefined) {
|
||||
this.push('profiles/', 'unknown-profile', `profile ${id} is not defined`);
|
||||
continue;
|
||||
}
|
||||
selected.push(profile);
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
private applyOverrides(
|
||||
selected: ProfileDoc[],
|
||||
defs: Record<string, ParamDef>,
|
||||
): Map<string, { value: unknown; source: string }> {
|
||||
const applied = new Map<string, { value: unknown; source: string }>();
|
||||
for (const profile of selected) {
|
||||
for (const override of profile.overrides) {
|
||||
this.applyOne(profile, override, defs, applied);
|
||||
}
|
||||
}
|
||||
return applied;
|
||||
}
|
||||
|
||||
private applyOne(
|
||||
profile: ProfileDoc,
|
||||
override: { parameter: string; value: unknown },
|
||||
defs: Record<string, ParamDef>,
|
||||
applied: Map<string, { value: unknown; source: string }>,
|
||||
): void {
|
||||
const def = defs[override.parameter];
|
||||
if (def === undefined) {
|
||||
this.push(
|
||||
profile.file,
|
||||
'unknown-parameter',
|
||||
`parameter ${override.parameter} is not defined`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const previous = applied.get(override.parameter);
|
||||
if (previous !== undefined && !sameValue(previous.value, override.value)) {
|
||||
this.push(
|
||||
profile.file,
|
||||
'parameter-conflict',
|
||||
`${override.parameter} overridden differently by ${previous.source} and ${profile.id}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!valueInConstraints(override.value, def)) {
|
||||
this.push(
|
||||
profile.file,
|
||||
'parameter-out-of-range',
|
||||
`${override.parameter} value is outside its constraints`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
applied.set(override.parameter, { value: override.value, source: profile.id });
|
||||
}
|
||||
|
||||
private buildEffective(
|
||||
selected: ProfileDoc[],
|
||||
requirements: Record<string, Record<string, unknown>>,
|
||||
defs: Record<string, ParamDef>,
|
||||
applied: Map<string, { value: unknown; source: string }>,
|
||||
): EffectiveRequirement[] {
|
||||
const effective: EffectiveRequirement[] = [];
|
||||
const ids = new Set<string>();
|
||||
for (const profile of selected) {
|
||||
for (const item of profile.requirements) {
|
||||
ids.add(item.requirement);
|
||||
}
|
||||
}
|
||||
for (const id of [...ids].sort((a, b) => a.localeCompare(b))) {
|
||||
const requirement = requirements[id];
|
||||
if (requirement === undefined) {
|
||||
this.push(
|
||||
'profiles/',
|
||||
'unknown-requirement',
|
||||
`profile references undefined requirement ${id}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
effective.push(this.buildOne(id, requirement, selected, defs, applied));
|
||||
}
|
||||
return effective;
|
||||
}
|
||||
|
||||
private buildOne(
|
||||
id: string,
|
||||
requirement: Record<string, unknown>,
|
||||
selected: ProfileDoc[],
|
||||
defs: Record<string, ParamDef>,
|
||||
applied: Map<string, { value: unknown; source: string }>,
|
||||
): EffectiveRequirement {
|
||||
const baseLevel = isString(requirement['level']) ? requirement['level'] : 'MUST';
|
||||
return {
|
||||
requirement: id,
|
||||
level: this.effectiveLevel(id, baseLevel, selected),
|
||||
sources: selected
|
||||
.filter((profile) => profile.requirements.some((item) => item.requirement === id))
|
||||
.map((profile) => profile.id),
|
||||
applicability: requirementApplicability(requirement),
|
||||
parameters: requirementParameters(requirement, defs, applied),
|
||||
};
|
||||
}
|
||||
|
||||
private effectiveLevel(id: string, baseLevel: string, selected: ProfileDoc[]): string {
|
||||
const relaxations = new Set<string>();
|
||||
for (const profile of selected) {
|
||||
for (const item of profile.requirements) {
|
||||
if (item.requirement === id && isString(item.relax_to)) {
|
||||
relaxations.add(item.relax_to);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (relaxations.size > 1) {
|
||||
this.push('profiles/', 'relaxation-conflict', `${id} relaxed in conflicting ways`);
|
||||
return baseLevel;
|
||||
}
|
||||
const only = [...relaxations][0];
|
||||
if (only === undefined) {
|
||||
return baseLevel;
|
||||
}
|
||||
if (!isWeaker(baseLevel, only)) {
|
||||
this.push(
|
||||
'profiles/',
|
||||
'invalid-relaxation',
|
||||
`${id}: ${only} is not weaker than ${baseLevel}`,
|
||||
);
|
||||
return baseLevel;
|
||||
}
|
||||
return only;
|
||||
}
|
||||
}
|
||||
|
||||
function loadParameterRegistry(root: string, diagnostics: Diagnostic[]): Record<string, ParamDef> {
|
||||
const registry: Record<string, ParamDef> = {};
|
||||
for (const file of filesIn(path.join(root, 'parameters'), '.yaml')) {
|
||||
const value = readYaml(file, diagnostics);
|
||||
if (isRecord(value) && isString(value['id'])) {
|
||||
registry[value['id']] = paramDef(value, file);
|
||||
}
|
||||
}
|
||||
return registry;
|
||||
}
|
||||
|
||||
function loadPresets(
|
||||
root: string,
|
||||
ajv: Ajv2020,
|
||||
diagnostics: Diagnostic[],
|
||||
): Record<string, string[]> {
|
||||
const docs = loadDocs(path.join(root, 'presets'), 'preset', ajv, diagnostics);
|
||||
const presets: Record<string, string[]> = {};
|
||||
for (const [id, value] of Object.entries(docs)) {
|
||||
const items = Array.isArray(value['profiles']) ? value['profiles'] : [];
|
||||
presets[id] = items.filter(isString);
|
||||
}
|
||||
return presets;
|
||||
}
|
||||
|
||||
function profileEntries(value: Record<string, unknown>): ProfileEntry[] {
|
||||
const items = Array.isArray(value['requirements']) ? value['requirements'] : [];
|
||||
const entries: ProfileEntry[] = [];
|
||||
const known: readonly unknown[] = items;
|
||||
for (const item of known) {
|
||||
if (!isRecord(item) || !isString(item['requirement'])) {
|
||||
continue;
|
||||
}
|
||||
const entry: ProfileEntry = isString(item['relax_to'])
|
||||
? { requirement: item['requirement'], relax_to: item['relax_to'] }
|
||||
: { requirement: item['requirement'] };
|
||||
entries.push(entry);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function profileOverrides(value: Record<string, unknown>): { parameter: string; value: unknown }[] {
|
||||
const items = Array.isArray(value['parameter_overrides']) ? value['parameter_overrides'] : [];
|
||||
const overrides: { parameter: string; value: unknown }[] = [];
|
||||
const known: readonly unknown[] = items;
|
||||
for (const item of known) {
|
||||
if (isRecord(item) && isString(item['parameter'])) {
|
||||
overrides.push({ parameter: item['parameter'], value: item['value'] });
|
||||
}
|
||||
}
|
||||
return overrides;
|
||||
}
|
||||
|
||||
function requirementApplicability(
|
||||
requirement: Record<string, unknown>,
|
||||
): { when: string; unless?: string }[] {
|
||||
const items = Array.isArray(requirement['applicability']) ? requirement['applicability'] : [];
|
||||
const result: { when: string; unless?: string }[] = [];
|
||||
const known: readonly unknown[] = items;
|
||||
for (const item of known) {
|
||||
if (!isRecord(item) || !isString(item['when'])) {
|
||||
continue;
|
||||
}
|
||||
result.push(
|
||||
isString(item['unless'])
|
||||
? { when: item['when'], unless: item['unless'] }
|
||||
: { when: item['when'] },
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function requirementParameters(
|
||||
requirement: Record<string, unknown>,
|
||||
defs: Record<string, ParamDef>,
|
||||
applied: Map<string, { value: unknown; source: string }>,
|
||||
): EffectiveParameter[] {
|
||||
const result: EffectiveParameter[] = [];
|
||||
const items = Array.isArray(requirement['parameters']) ? requirement['parameters'] : [];
|
||||
const known: readonly unknown[] = items;
|
||||
for (const item of known) {
|
||||
if (!isRecord(item) || !isString(item['id'])) {
|
||||
continue;
|
||||
}
|
||||
const parameter = item['id'];
|
||||
const override = applied.get(parameter);
|
||||
if (override !== undefined) {
|
||||
result.push({ parameter, value: override.value, source: override.source });
|
||||
continue;
|
||||
}
|
||||
const def = defs[parameter];
|
||||
if (def !== undefined && def.default !== undefined) {
|
||||
result.push({ parameter, value: def.default, source: 'spec' });
|
||||
}
|
||||
}
|
||||
result.sort((a, b) => a.parameter.localeCompare(b.parameter));
|
||||
return result;
|
||||
}
|
||||
|
||||
export function resolveProfiles(
|
||||
root: string,
|
||||
profileIds: string[],
|
||||
presetIds: string[],
|
||||
): ResolveResult {
|
||||
return new Resolver(root).run(profileIds, presetIds);
|
||||
}
|
||||
Reference in New Issue
Block a user