@intellectual-frontiers/grc 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/assess.d.ts +247 -0
- package/dist/assess.js +289 -0
- package/dist/attest.d.ts +164 -0
- package/dist/attest.js +213 -0
- package/dist/evidence.d.ts +212 -0
- package/dist/evidence.js +453 -0
- package/dist/grc.d.ts +356 -0
- package/dist/grc.js +487 -0
- package/dist/host/grc.d.ts +159 -0
- package/dist/host/grc.js +358 -0
- package/dist/host/mod.d.ts +14 -0
- package/dist/host/mod.js +15 -0
- package/dist/host/sign.d.ts +141 -0
- package/dist/host/sign.js +282 -0
- package/dist/mod.d.ts +19 -0
- package/dist/mod.js +20 -0
- package/dist/ocsf-types.auto.d.ts +4374 -0
- package/dist/ocsf-types.auto.js +24 -0
- package/dist/ocsf.d.ts +160 -0
- package/dist/ocsf.js +257 -0
- package/dist/oscal.d.ts +356 -0
- package/dist/oscal.js +513 -0
- package/package.json +87 -4
- package/src/assess.ts +472 -0
- package/src/attest.ts +354 -0
- package/src/evidence.ts +551 -0
- package/src/grc.ts +771 -0
- package/src/host/grc.ts +435 -0
- package/src/host/mod.ts +15 -0
- package/src/host/sign.ts +364 -0
- package/src/mod.ts +20 -0
- package/src/ocsf-types.auto.ts +4680 -0
- package/src/ocsf.ts +471 -0
- package/src/oscal.ts +850 -0
package/dist/grc.js
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
// Spec: 0001-grc-engineering FR-001
|
|
2
|
+
/**
|
|
3
|
+
* Governance, risk and compliance as code: catalogs, controls, verdicts, findings and waivers (commons 0001-grc-engineering FR-001 to FR-005), with
|
|
4
|
+
* the time values they all share (an `Instant`, an ISO 8601 `Duration`; FR-011 uses them) and the globs that waivers and change-impact
|
|
5
|
+
* declarations match with (FR-005, FR-013). Pure: the kernel reads no clock, so every "now" is a value the caller gives.
|
|
6
|
+
*
|
|
7
|
+
* - A **catalog** is a framework's controls as a constant tuple (`defineCatalog`), so `catalog.control("XX-99")` does not compile where the
|
|
8
|
+
* catalog has no `XX-99` (FR-001). Two catalogs are related by a **crosswalk** of Set Theory Relationship Mappings (NIST IR 8477), each
|
|
9
|
+
* end typed by its catalog.
|
|
10
|
+
* - A **control** (`defineControl`) checks one type of subject `S` and implements catalog controls; a **pack** (`definePack`) groups the
|
|
11
|
+
* controls of one subject type, and `runPack` runs each over each subject, a check that throws giving `error` for that subject (FR-002).
|
|
12
|
+
* - A **status** is `pass | fail | warn | error | not-applicable | gap`; an **outcome** adds `accepted` (a waived `fail` or `warn`).
|
|
13
|
+
* `join` is the least upper bound in `not-applicable < pass < accepted < warn < gap < fail < error`, a join-semilattice, so a roll-up
|
|
14
|
+
* does not depend on its order (FR-003).
|
|
15
|
+
* - A **finding** is one type for every harness, grouped into sections by `sections` (FR-004).
|
|
16
|
+
* - A **waiver** names a control, the subjects it covers (exact ids or globs), a reason, the role that approved it, when it was granted and
|
|
17
|
+
* when it expires; `defineWaiver` refuses one without an expiry or expiring before its grant, and `applyWaivers` turns an applying
|
|
18
|
+
* waiver's `fail` or `warn` into `accepted`, never an `error` or a `gap` (FR-005).
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* import { defineCatalog, defineControl, definePack, duration, instantOf, runPack, verdict } from "./grc.ts";
|
|
23
|
+
* const catalog = defineCatalog("example", "1.0", [{ id: "EX-1", title: "Disks are encrypted" }] as const);
|
|
24
|
+
* type Host = { readonly name: string; readonly encrypted: boolean };
|
|
25
|
+
* const encrypted = defineControl({
|
|
26
|
+
* id: "disk-encryption", title: "Disk encryption", implements: [catalog.control("EX-1")], severity: "high", cadence: duration("P1D"),
|
|
27
|
+
* check: (h: Host) => verdict(h.encrypted ? "pass" : "fail"),
|
|
28
|
+
* });
|
|
29
|
+
* const pack = definePack({ id: "hosts", title: "Hosts", subjectKind: "host", subjectId: (h: Host) => h.name, controls: [encrypted] });
|
|
30
|
+
* const at = instantOf("2026-03-01T00:00:00Z");
|
|
31
|
+
* if (at !== undefined) await runPack(pack, [{ name: "a", encrypted: false }], { at }); // one finding, status "fail"
|
|
32
|
+
* ```
|
|
33
|
+
*
|
|
34
|
+
* @module
|
|
35
|
+
*/
|
|
36
|
+
import { absurd, array, literal, mapDecoder, object, string, err, ok, } from "@intellectual-frontiers/core";
|
|
37
|
+
const INSTANT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/i;
|
|
38
|
+
const CANONICAL_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
39
|
+
/**
|
|
40
|
+
* ISO 8601 date-time text with a `Z` or a `±HH:MM` offset as an `Instant` in UTC (fractions past milliseconds dropped), or undefined where
|
|
41
|
+
* it is not one: a day the month does not have, an hour past 23, a leap second, or a year outside 0000 to 9999 once in UTC.
|
|
42
|
+
*/
|
|
43
|
+
export function instantOf(text) {
|
|
44
|
+
const m = INSTANT.exec(text.trim());
|
|
45
|
+
if (m === null)
|
|
46
|
+
return undefined;
|
|
47
|
+
const [y, mo, d, h, mi, s] = [m[1], m[2], m[3], m[4], m[5], m[6]].map((x) => Number(x ?? ""));
|
|
48
|
+
if (y === undefined || mo === undefined || d === undefined || h === undefined || mi === undefined || s === undefined)
|
|
49
|
+
return undefined;
|
|
50
|
+
const ms = Number((m[7] ?? "").padEnd(3, "0").slice(0, 3));
|
|
51
|
+
if (mo < 1 || mo > 12 || d < 1 || d > daysInMonth(y, mo) || h > 23 || mi > 59 || s > 59)
|
|
52
|
+
return undefined;
|
|
53
|
+
const zone = (m[8] ?? "Z").toUpperCase();
|
|
54
|
+
let offset = 0;
|
|
55
|
+
if (zone !== "Z") {
|
|
56
|
+
const oh = Number(zone.slice(1, 3));
|
|
57
|
+
const om = Number(zone.slice(4, 6));
|
|
58
|
+
if (oh > 23 || om > 59)
|
|
59
|
+
return undefined;
|
|
60
|
+
offset = (zone.startsWith("-") ? -1 : 1) * (oh * 60 + om) * 60_000;
|
|
61
|
+
}
|
|
62
|
+
const date = new Date(0);
|
|
63
|
+
date.setUTCFullYear(y, mo - 1, d);
|
|
64
|
+
date.setUTCHours(h, mi, s, ms);
|
|
65
|
+
return instantFromEpochMs(date.getTime() - offset);
|
|
66
|
+
}
|
|
67
|
+
/** Milliseconds since 1970-01-01T00:00:00Z as an `Instant`, or undefined where it is not finite or falls outside the years 0000 to 9999. */
|
|
68
|
+
export function instantFromEpochMs(ms) {
|
|
69
|
+
if (!Number.isFinite(ms))
|
|
70
|
+
return undefined;
|
|
71
|
+
const date = new Date(Math.trunc(ms));
|
|
72
|
+
if (Number.isNaN(date.getTime()))
|
|
73
|
+
return undefined;
|
|
74
|
+
const text = date.toISOString();
|
|
75
|
+
return CANONICAL_INSTANT.test(text) ? text : undefined;
|
|
76
|
+
}
|
|
77
|
+
/** An instant as milliseconds since 1970-01-01T00:00:00Z. */
|
|
78
|
+
export function epochMs(instant) {
|
|
79
|
+
return Date.parse(instant);
|
|
80
|
+
}
|
|
81
|
+
/** Negative where `a` is before `b`, zero where they are the same instant, positive where `a` is after. */
|
|
82
|
+
export function compareInstants(a, b) {
|
|
83
|
+
return epochMs(a) - epochMs(b);
|
|
84
|
+
}
|
|
85
|
+
/** The latest of some instants, or undefined where there are none. */
|
|
86
|
+
export function latestInstant(instants) {
|
|
87
|
+
let best;
|
|
88
|
+
for (const i of instants)
|
|
89
|
+
if (best === undefined || compareInstants(i, best) > 0)
|
|
90
|
+
best = i;
|
|
91
|
+
return best;
|
|
92
|
+
}
|
|
93
|
+
function daysInMonth(year, month) {
|
|
94
|
+
const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
|
95
|
+
return month === 2 ? (leap ? 29 : 28) : [4, 6, 9, 11].includes(month) ? 30 : 31;
|
|
96
|
+
}
|
|
97
|
+
const DURATION = /^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:[.,]\d+)?)S)?)?$/;
|
|
98
|
+
/** ISO 8601 duration text as a `Duration`: whole years, months, weeks, days, hours and minutes, and seconds with an optional fraction. */
|
|
99
|
+
export function parseDuration(text) {
|
|
100
|
+
const m = DURATION.exec(text);
|
|
101
|
+
if (m === null || text === "P" || text.endsWith("T"))
|
|
102
|
+
return err({ kind: "duration", text });
|
|
103
|
+
const n = (i) => Number((m[i] ?? "0").replace(",", "."));
|
|
104
|
+
return ok({ text, years: n(1), months: n(2), weeks: n(3), days: n(4), hours: n(5), minutes: n(6), seconds: n(7) });
|
|
105
|
+
}
|
|
106
|
+
/** A duration from a literal in code, such as a control's cadence; it throws where the literal is not one (a mistake in the code, not in data). */
|
|
107
|
+
export function duration(text) {
|
|
108
|
+
const r = parseDuration(text);
|
|
109
|
+
if (r.kind === "err")
|
|
110
|
+
throw new Error(`not an ISO 8601 duration: ${JSON.stringify(text)}`);
|
|
111
|
+
return r.value;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* The instant a duration after another, in UTC: years and months first (a day the month lacks becomes its last, so 31 January plus `P1M`
|
|
115
|
+
* is 28 or 29 February), then weeks, days, hours, minutes and seconds; undefined past the year 9999.
|
|
116
|
+
*/
|
|
117
|
+
export function addDuration(start, d) {
|
|
118
|
+
const date = new Date(epochMs(start));
|
|
119
|
+
const months = date.getUTCFullYear() * 12 + date.getUTCMonth() + d.years * 12 + d.months;
|
|
120
|
+
const year = Math.floor(months / 12);
|
|
121
|
+
const month = months - year * 12;
|
|
122
|
+
if (year > 9999)
|
|
123
|
+
return undefined;
|
|
124
|
+
date.setUTCFullYear(year, month, Math.min(date.getUTCDate(), daysInMonth(year, month + 1)));
|
|
125
|
+
const span = ((d.weeks * 7 + d.days) * 24 * 3600 + d.hours * 3600 + d.minutes * 60 + d.seconds) * 1000;
|
|
126
|
+
return instantFromEpochMs(date.getTime() + Math.round(span));
|
|
127
|
+
}
|
|
128
|
+
const ROLE = /^[a-z][a-z0-9]*(?:[-_./][a-z0-9]+)*$/;
|
|
129
|
+
/** Text as a `Role` where it is one (lower-case words joined by `-`, `_`, `.` or `/`), else undefined. An e-mail address is not a role. */
|
|
130
|
+
export function roleOf(text) {
|
|
131
|
+
return ROLE.test(text) ? text : undefined;
|
|
132
|
+
}
|
|
133
|
+
/** A glob compiled once, to test many paths or ids. */
|
|
134
|
+
export function glob(pattern) {
|
|
135
|
+
let source = "";
|
|
136
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
137
|
+
const c = pattern.charAt(i);
|
|
138
|
+
if (c === "*" && pattern.charAt(i + 1) === "*") {
|
|
139
|
+
if (pattern.charAt(i + 2) === "/") {
|
|
140
|
+
source += "(?:.*/)?";
|
|
141
|
+
i += 2;
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
source += ".*";
|
|
145
|
+
i += 1;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
else if (c === "*")
|
|
149
|
+
source += "[^/]*";
|
|
150
|
+
else if (c === "?")
|
|
151
|
+
source += "[^/]";
|
|
152
|
+
else
|
|
153
|
+
source += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
154
|
+
}
|
|
155
|
+
const re = new RegExp(`^${source}$`, "s");
|
|
156
|
+
return { pattern, test: (text) => re.test(text) };
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* A catalog from its id, its version and a constant tuple of its controls (`[...] as const`, or inline). Two controls with one id are a
|
|
160
|
+
* mistake in the code, and throw.
|
|
161
|
+
*/
|
|
162
|
+
export function defineCatalog(id, version, controls) {
|
|
163
|
+
const byId = new Map();
|
|
164
|
+
for (const c of controls) {
|
|
165
|
+
if (byId.has(c.id))
|
|
166
|
+
throw new Error(`catalog ${id} holds ${c.id} twice`);
|
|
167
|
+
byId.set(c.id, c);
|
|
168
|
+
}
|
|
169
|
+
const has = (x) => byId.has(x);
|
|
170
|
+
return {
|
|
171
|
+
id,
|
|
172
|
+
version,
|
|
173
|
+
controls,
|
|
174
|
+
ids: controls.map((c) => c.id),
|
|
175
|
+
control: (cid) => ({ catalog: id, id: cid }),
|
|
176
|
+
// The id is one of the catalog's by its type, so the entry is there and is the member of `E` with that id.
|
|
177
|
+
get: (cid) => byId.get(cid),
|
|
178
|
+
has,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/** The relationships of NIST IR 8477's Set Theory Relationship Mapping. */
|
|
182
|
+
export const STRM_RELATIONSHIPS = ["equal", "subset-of", "superset-of", "intersects-with", "no-relationship"];
|
|
183
|
+
/** Whether a number is a strength (an integer from 1 to 10), for values read at run time. */
|
|
184
|
+
export function isStrmStrength(n) {
|
|
185
|
+
return Number.isInteger(n) && n >= 1 && n <= 10;
|
|
186
|
+
}
|
|
187
|
+
/** A crosswalk between two catalogs; an id either catalog does not hold does not compile. */
|
|
188
|
+
export function defineCrosswalk(from, to, rows) {
|
|
189
|
+
return {
|
|
190
|
+
from: { catalog: from.id, version: from.version },
|
|
191
|
+
to: { catalog: to.id, version: to.version },
|
|
192
|
+
mappings: rows.map((r) => ({
|
|
193
|
+
from: from.control(r.from),
|
|
194
|
+
to: to.control(r.to),
|
|
195
|
+
relationship: r.relationship,
|
|
196
|
+
strength: r.strength,
|
|
197
|
+
...(r.rationale === undefined ? {} : { rationale: r.rationale }),
|
|
198
|
+
})),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
/** The relationship read the other way: `subset-of` becomes `superset-of` and back; the others are symmetric. */
|
|
202
|
+
export function inverseRelationship(r) {
|
|
203
|
+
switch (r) {
|
|
204
|
+
case "subset-of":
|
|
205
|
+
return "superset-of";
|
|
206
|
+
case "superset-of":
|
|
207
|
+
return "subset-of";
|
|
208
|
+
case "equal":
|
|
209
|
+
case "intersects-with":
|
|
210
|
+
case "no-relationship":
|
|
211
|
+
return r;
|
|
212
|
+
default:
|
|
213
|
+
return absurd(r);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
/** A crosswalk read from its other end. */
|
|
217
|
+
export function invertCrosswalk(c) {
|
|
218
|
+
return {
|
|
219
|
+
from: c.to,
|
|
220
|
+
to: c.from,
|
|
221
|
+
mappings: c.mappings.map((m) => ({ ...m, from: m.to, to: m.from, relationship: inverseRelationship(m.relationship) })),
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
// ---------------------------------------------------------------------------------------------------------------------------- statuses (FR-003)
|
|
225
|
+
/** Every outcome, from the least to the greatest in the order `join` takes. */
|
|
226
|
+
export const OUTCOMES = ["not-applicable", "pass", "accepted", "warn", "gap", "fail", "error"];
|
|
227
|
+
/** Every status. */
|
|
228
|
+
export const STATUSES = ["pass", "fail", "warn", "error", "not-applicable", "gap"];
|
|
229
|
+
const RANK = { "not-applicable": 0, pass: 1, accepted: 2, warn: 3, gap: 4, fail: 5, error: 6 };
|
|
230
|
+
/** An outcome's place in the order, from 0 (`not-applicable`) to 6 (`error`). */
|
|
231
|
+
export function outcomeRank(o) {
|
|
232
|
+
return RANK[o];
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* The least upper bound of two outcomes in `not-applicable < pass < accepted < warn < gap < fail < error`: associative, commutative and
|
|
236
|
+
* idempotent, with `not-applicable` its identity and `pass` the identity among the applicable. Two statuses join to a status.
|
|
237
|
+
*/
|
|
238
|
+
export function join(a, b) {
|
|
239
|
+
return RANK[a] >= RANK[b] ? a : b;
|
|
240
|
+
}
|
|
241
|
+
/** The join of every outcome, in any order; `not-applicable` where there are none. */
|
|
242
|
+
export function joinAll(outcomes) {
|
|
243
|
+
let acc = "not-applicable";
|
|
244
|
+
for (const o of outcomes)
|
|
245
|
+
acc = join(acc, o);
|
|
246
|
+
return acc;
|
|
247
|
+
}
|
|
248
|
+
/** Every severity, from the least to the greatest. */
|
|
249
|
+
export const SEVERITIES = ["info", "low", "medium", "high", "critical"];
|
|
250
|
+
/** The greater of two severities. */
|
|
251
|
+
export function maxSeverity(a, b) {
|
|
252
|
+
return SEVERITIES.indexOf(a) >= SEVERITIES.indexOf(b) ? a : b;
|
|
253
|
+
}
|
|
254
|
+
/** A verdict from its status and the fields to say beside it. */
|
|
255
|
+
export function verdict(status, fields = {}) {
|
|
256
|
+
return { status, ...fields };
|
|
257
|
+
}
|
|
258
|
+
/** A control from its declaration; the subject type is what its check takes. */
|
|
259
|
+
export function defineControl(control) {
|
|
260
|
+
return control;
|
|
261
|
+
}
|
|
262
|
+
/** A control without its check. */
|
|
263
|
+
export function controlSummary(c) {
|
|
264
|
+
return {
|
|
265
|
+
id: c.id,
|
|
266
|
+
title: c.title,
|
|
267
|
+
...(c.description === undefined ? {} : { description: c.description }),
|
|
268
|
+
implements: c.implements,
|
|
269
|
+
severity: c.severity,
|
|
270
|
+
cadence: c.cadence.text,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
/** A pack from its declaration. Two controls with one id are a mistake in the code, and throw. */
|
|
274
|
+
export function definePack(pack) {
|
|
275
|
+
const ids = new Set();
|
|
276
|
+
for (const c of pack.controls) {
|
|
277
|
+
if (ids.has(c.id))
|
|
278
|
+
throw new Error(`pack ${pack.id} holds control ${c.id} twice`);
|
|
279
|
+
ids.add(c.id);
|
|
280
|
+
}
|
|
281
|
+
return pack;
|
|
282
|
+
}
|
|
283
|
+
/** A stable key of a finding's control and subject, for maps and for names a rendering derives identifiers from. */
|
|
284
|
+
export function findingKey(f) {
|
|
285
|
+
return JSON.stringify([f.control.id, f.subject.kind, f.subject.id]);
|
|
286
|
+
}
|
|
287
|
+
/** The findings of a check's verdicts for one subject, each verdict filled in from its control. */
|
|
288
|
+
export function findingsOf(control, subject, checked, at) {
|
|
289
|
+
const summary = controlSummary(control);
|
|
290
|
+
const verdicts = isVerdictList(checked) ? checked : [checked];
|
|
291
|
+
const list = verdicts.length === 0 ? [verdict("not-applicable", { detail: "the check gave no verdict for this subject" })] : verdicts;
|
|
292
|
+
return list.map((v) => {
|
|
293
|
+
const remediation = v.remediation ?? control.remediation;
|
|
294
|
+
return {
|
|
295
|
+
control: summary,
|
|
296
|
+
subject,
|
|
297
|
+
status: v.status,
|
|
298
|
+
outcome: v.status,
|
|
299
|
+
severity: v.severity ?? control.severity,
|
|
300
|
+
title: v.title ?? control.title,
|
|
301
|
+
detail: v.detail ?? "",
|
|
302
|
+
evidence: v.evidence ?? [],
|
|
303
|
+
...(remediation === undefined ? {} : { remediation }),
|
|
304
|
+
at,
|
|
305
|
+
};
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
function isVerdictList(c) {
|
|
309
|
+
return Array.isArray(c);
|
|
310
|
+
}
|
|
311
|
+
function message(thrown) {
|
|
312
|
+
return thrown instanceof Error ? thrown.message : String(thrown);
|
|
313
|
+
}
|
|
314
|
+
/** One control's check of one subject, as findings; a check that throws or rejects gives one `error` finding and never a rejection. */
|
|
315
|
+
export async function runCheck(control, subject, ref, context) {
|
|
316
|
+
try {
|
|
317
|
+
return findingsOf(control, ref, await control.check(subject, context), context.at);
|
|
318
|
+
}
|
|
319
|
+
catch (thrown) {
|
|
320
|
+
return findingsOf(control, ref, verdict("error", { detail: `the check failed: ${message(thrown)}` }), context.at);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
/** The reference of a subject in a pack; a `subjectId` that throws names it by its place, `#0`, `#1`... */
|
|
324
|
+
export function subjectRef(pack, subject, index) {
|
|
325
|
+
try {
|
|
326
|
+
return { kind: pack.subjectKind, id: pack.subjectId(subject) };
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
return { kind: pack.subjectKind, id: `#${index}` };
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
/** Every control of a pack over every subject (a check that throws is `error` for that subject alone), then the waivers given applied. */
|
|
333
|
+
export async function runPack(pack, subjects, context, options = {}) {
|
|
334
|
+
const refs = subjects.map((s, i) => subjectRef(pack, s, i));
|
|
335
|
+
const findings = [];
|
|
336
|
+
for (const control of pack.controls) {
|
|
337
|
+
for (const [i, subject] of subjects.entries()) {
|
|
338
|
+
const ref = refs[i] ?? { kind: pack.subjectKind, id: `#${i}` };
|
|
339
|
+
findings.push(...(await runCheck(control, subject, ref, context)));
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return {
|
|
343
|
+
pack: { id: pack.id, title: pack.title },
|
|
344
|
+
at: context.at,
|
|
345
|
+
controls: pack.controls.map(controlSummary),
|
|
346
|
+
subjects: refs,
|
|
347
|
+
findings: applyWaivers(findings, options.waivers ?? [], context.at),
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
/** Findings grouped by the key or keys each one has (a finding with two keys is in both sections), in the order `compare` gives the keys (text order by default). */
|
|
351
|
+
export function sections(findings, keyOf, compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) {
|
|
352
|
+
const groups = new Map();
|
|
353
|
+
for (const f of findings) {
|
|
354
|
+
const k = keyOf(f);
|
|
355
|
+
for (const key of typeof k === "string" ? [k] : k) {
|
|
356
|
+
const g = groups.get(key);
|
|
357
|
+
if (g === undefined)
|
|
358
|
+
groups.set(key, [f]);
|
|
359
|
+
else
|
|
360
|
+
g.push(f);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return [...groups.keys()].sort(compare).map((key) => {
|
|
364
|
+
const group = groups.get(key) ?? [];
|
|
365
|
+
return { key, outcome: joinAll(group.map((f) => f.outcome)), counts: countOutcomes(group), findings: group };
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
/** How many findings have each outcome. */
|
|
369
|
+
export function countOutcomes(findings) {
|
|
370
|
+
const counts = { "not-applicable": 0, pass: 0, accepted: 0, warn: 0, gap: 0, fail: 0, error: 0 };
|
|
371
|
+
for (const f of findings)
|
|
372
|
+
counts[f.outcome] += 1;
|
|
373
|
+
return counts;
|
|
374
|
+
}
|
|
375
|
+
/** A section key: the finding's control id. */
|
|
376
|
+
export const byControl = (f) => f.control.id;
|
|
377
|
+
/** A section key: the finding's subject, `kind:id`. */
|
|
378
|
+
export const bySubject = (f) => `${f.subject.kind}:${f.subject.id}`;
|
|
379
|
+
/** A section key: the finding's outcome (sort with `compareOutcomeKeys` for the semilattice's order). */
|
|
380
|
+
export const byOutcome = (f) => f.outcome;
|
|
381
|
+
/** A section key: the finding's severity. */
|
|
382
|
+
export const bySeverity = (f) => f.severity;
|
|
383
|
+
/** Section keys: each catalog control the finding's control implements, `catalog:id`. */
|
|
384
|
+
export const byRequirement = (f) => f.control.implements.map((r) => `${r.catalog}:${r.id}`);
|
|
385
|
+
/** Outcome keys from the greatest to the least, for `sections(findings, byOutcome, compareOutcomeKeys)`. */
|
|
386
|
+
export function compareOutcomeKeys(a, b) {
|
|
387
|
+
const rank = (k) => (Object.hasOwn(RANK, k) ? RANK[k] : -1);
|
|
388
|
+
return rank(b) - rank(a);
|
|
389
|
+
}
|
|
390
|
+
/** A waiver error as one sentence. */
|
|
391
|
+
export function formatWaiverError(e) {
|
|
392
|
+
switch (e.kind) {
|
|
393
|
+
case "no-expiry":
|
|
394
|
+
return `waiver ${e.waiver} has no expiry`;
|
|
395
|
+
case "expires-before-grant":
|
|
396
|
+
return `waiver ${e.waiver} expires before it was granted`;
|
|
397
|
+
case "no-subjects":
|
|
398
|
+
return `waiver ${e.waiver} covers no subject`;
|
|
399
|
+
case "no-reason":
|
|
400
|
+
return `waiver ${e.waiver} gives no reason`;
|
|
401
|
+
default:
|
|
402
|
+
return absurd(e);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
/** A waiver, or why it is refused: it has no expiry, expires before (or when) it is granted, covers no subject or gives no reason. */
|
|
406
|
+
export function defineWaiver(w) {
|
|
407
|
+
if (w.expiresAt === undefined)
|
|
408
|
+
return err({ kind: "no-expiry", waiver: w.id });
|
|
409
|
+
if (compareInstants(w.expiresAt, w.grantedAt) <= 0)
|
|
410
|
+
return err({ kind: "expires-before-grant", waiver: w.id });
|
|
411
|
+
if (w.subjects.length === 0)
|
|
412
|
+
return err({ kind: "no-subjects", waiver: w.id });
|
|
413
|
+
if (w.reason.trim() === "")
|
|
414
|
+
return err({ kind: "no-reason", waiver: w.id });
|
|
415
|
+
return ok({ ...w, expiresAt: w.expiresAt });
|
|
416
|
+
}
|
|
417
|
+
/** Where a waiver stands at an instant: not yet granted, in force (from its grant, up to but not including its expiry), or expired. */
|
|
418
|
+
export function waiverState(w, at) {
|
|
419
|
+
if (compareInstants(at, w.grantedAt) < 0)
|
|
420
|
+
return "pending";
|
|
421
|
+
return compareInstants(at, w.expiresAt) < 0 ? "active" : "expired";
|
|
422
|
+
}
|
|
423
|
+
/** Whether a waiver covers a finding's control and subject and is in force at the instant (whatever the finding's status). */
|
|
424
|
+
export function waiverCovers(w, f, at) {
|
|
425
|
+
return (w.control === f.control.id &&
|
|
426
|
+
waiverState(w, at) === "active" &&
|
|
427
|
+
w.subjects.some((p) => p === f.subject.id || glob(p).test(f.subject.id)));
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* The findings with the waivers applied at an instant: a `fail` or `warn` that an active waiver covers becomes `accepted` and carries the
|
|
431
|
+
* waiver's id (the first in id order where several apply); every other finding has its status as its outcome and no waiver.
|
|
432
|
+
*/
|
|
433
|
+
export function applyWaivers(findings, waivers, at) {
|
|
434
|
+
const ordered = [...waivers].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
435
|
+
return findings.map((f) => {
|
|
436
|
+
const { waiver: _old, ...rest } = f;
|
|
437
|
+
const base = { ...rest, outcome: f.status };
|
|
438
|
+
if (f.status !== "fail" && f.status !== "warn")
|
|
439
|
+
return base;
|
|
440
|
+
const w = ordered.find((x) => waiverCovers(x, f, at));
|
|
441
|
+
return w === undefined ? base : { ...base, outcome: "accepted", waiver: w.id };
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
// ---------------------------------------------------------------------------------------------------------------------------- decoders
|
|
445
|
+
const refined = (name, f) => {
|
|
446
|
+
return (input, path = "$") => {
|
|
447
|
+
if (typeof input === "string") {
|
|
448
|
+
const v = f(input);
|
|
449
|
+
if (v !== undefined)
|
|
450
|
+
return ok(v);
|
|
451
|
+
}
|
|
452
|
+
return err({
|
|
453
|
+
kind: "decode",
|
|
454
|
+
path,
|
|
455
|
+
expected: name,
|
|
456
|
+
found: typeof input === "string" ? `the string ${JSON.stringify(input).slice(0, 60)}` : typeof input,
|
|
457
|
+
});
|
|
458
|
+
};
|
|
459
|
+
};
|
|
460
|
+
/** An ISO 8601 date-time with a zone, as an `Instant`. */
|
|
461
|
+
export const instantDecoder = refined("an ISO 8601 date-time with a zone", instantOf);
|
|
462
|
+
/** A role. */
|
|
463
|
+
export const roleDecoder = refined("a role (lower-case words joined by - _ . or /)", roleOf);
|
|
464
|
+
/** An ISO 8601 duration. */
|
|
465
|
+
export const durationDecoder = refined("an ISO 8601 duration", (t) => {
|
|
466
|
+
const r = parseDuration(t);
|
|
467
|
+
return r.kind === "ok" ? r.value : undefined;
|
|
468
|
+
});
|
|
469
|
+
/** A severity. */
|
|
470
|
+
export const severityDecoder = literal(...SEVERITIES);
|
|
471
|
+
const waiverInput = mapDecoder(object({ id: string, control: string, subjects: array(string), reason: string, approvedBy: roleDecoder, grantedAt: instantDecoder }, { expiresAt: instantDecoder }), (w) => w);
|
|
472
|
+
/** A waiver as a file holds it, refused as `defineWaiver` refuses (the error at its path names why). */
|
|
473
|
+
export const waiverDecoder = (input, path = "$") => {
|
|
474
|
+
const r = waiverInput(input, path);
|
|
475
|
+
if (r.kind === "err")
|
|
476
|
+
return r;
|
|
477
|
+
const w = defineWaiver(r.value);
|
|
478
|
+
if (w.kind === "ok")
|
|
479
|
+
return w;
|
|
480
|
+
const e = {
|
|
481
|
+
kind: "decode",
|
|
482
|
+
path,
|
|
483
|
+
expected: "a waiver with a reason, a subject and an expiry after its grant",
|
|
484
|
+
found: formatWaiverError(w.error),
|
|
485
|
+
};
|
|
486
|
+
return err(e);
|
|
487
|
+
};
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The GRC host (commons 0001-grc-engineering FR-021): waivers, risk registers, impact declarations and any other data the caller has a decoder for,
|
|
3
|
+
* loaded from TOML, YAML, JSON or JSON5 files (chosen by the file's extension) with the kernel's parsers and decoders. An error names the
|
|
4
|
+
* file and either where its text stops parsing (line and column) or the path of the value that does not decode (`$.waivers[1].expiresAt`).
|
|
5
|
+
* A list file holds its items either as its top-level array or under one key (`waivers`, `risks`, `declarations`), so TOML, whose top
|
|
6
|
+
* level is a table, writes them as `[[waivers]]`. TOML dates and times are read as their ISO 8601 text, so a TOML offset date-time
|
|
7
|
+
* decodes as an `Instant`. Packs are code (their checks are functions), so a harness defines them in TypeScript and loads a pack's
|
|
8
|
+
* settings with `loadData` and a decoder of its own.
|
|
9
|
+
*
|
|
10
|
+
* Its signals (FR-019): `runPackObserved` runs a pack as `runPack` does, to the same assessment, and says so in the signals of
|
|
11
|
+
* `GRC_SIGNALS` (0006-signals): a `grc.pack` span for the run, ending `error` where any finding's outcome is `fail` or `error` (its
|
|
12
|
+
* message how many) and `ok` otherwise; a `grc.control` span under it for each control and subject checked, ending `error` where the check's
|
|
13
|
+
* outcome is `fail` or `error` and `ok` otherwise; and each finding a `grc.finding` log record in its check's span whose body is its OCSF
|
|
14
|
+
* Compliance Finding (`ocsfBody`; an integer is an OTLP `intValue`). The record's severity is the finding's (`FINDING_SEVERITY`):
|
|
15
|
+
*
|
|
16
|
+
* | finding severity | log record severity |
|
|
17
|
+
* | --- | --- |
|
|
18
|
+
* | `info`, `low` | 9 `INFO` |
|
|
19
|
+
* | `medium` | 13 `WARN` |
|
|
20
|
+
* | `high` | 17 `ERROR` |
|
|
21
|
+
* | `critical` | 21 `FATAL` |
|
|
22
|
+
*
|
|
23
|
+
* The finding's own severity is the record's `grc.severity` attribute, which tells `info` from `low`.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* import { formatLoadError, loadWaivers } from "./grc.js";
|
|
28
|
+
* const w = await loadWaivers("grc/waivers.toml");
|
|
29
|
+
* if (w.kind === "err") console.error(formatLoadError(w.error));
|
|
30
|
+
* ```
|
|
31
|
+
*
|
|
32
|
+
* @module
|
|
33
|
+
*/
|
|
34
|
+
import { type DecodeError, type Decoder, type Result } from "@intellectual-frontiers/core";
|
|
35
|
+
import { type ImpactDeclaration, type RiskInput } from "../assess.js";
|
|
36
|
+
import { type Assessment, type CheckContext, type Pack, type Severity, type Waiver } from "../grc.js";
|
|
37
|
+
import { type OcsfComplianceFinding, type OcsfProduct } from "../ocsf.js";
|
|
38
|
+
import { type AnyMap, type AnyValue, type Scope, type SeverityNumber } from "@intellectual-frontiers/telemetry/otel";
|
|
39
|
+
import { type Telemetry } from "@intellectual-frontiers/telemetry/signals";
|
|
40
|
+
/** A data file's format. */
|
|
41
|
+
export type DataFormat = "toml" | "yaml" | "json" | "json5";
|
|
42
|
+
/** The format of a file by its extension (`.toml`, `.yaml` or `.yml`, `.json`, `.json5`, in any case), or undefined for any other. */
|
|
43
|
+
export declare function formatOf(path: string): DataFormat | undefined;
|
|
44
|
+
/** Why a data file could not be loaded, each naming the file. */
|
|
45
|
+
export type LoadError = {
|
|
46
|
+
readonly kind: "read";
|
|
47
|
+
readonly file: string;
|
|
48
|
+
readonly reason: string;
|
|
49
|
+
} | {
|
|
50
|
+
readonly kind: "format";
|
|
51
|
+
readonly file: string;
|
|
52
|
+
} | {
|
|
53
|
+
readonly kind: "parse";
|
|
54
|
+
readonly file: string;
|
|
55
|
+
readonly format: DataFormat;
|
|
56
|
+
readonly line: number;
|
|
57
|
+
readonly column: number;
|
|
58
|
+
readonly message: string;
|
|
59
|
+
} | {
|
|
60
|
+
readonly kind: "decode";
|
|
61
|
+
readonly file: string;
|
|
62
|
+
readonly error: DecodeError;
|
|
63
|
+
};
|
|
64
|
+
/** A load error as one line: `grc/waivers.toml: $.waivers[0].expiresAt: expected ...`. */
|
|
65
|
+
export declare function formatLoadError(e: LoadError): string;
|
|
66
|
+
/** A text of a format as plain data, or where it stops being that format; `file` names it in the error. */
|
|
67
|
+
export declare function parseData(text: string, format: DataFormat, file: string): Result<unknown, LoadError>;
|
|
68
|
+
/** A text of a format decoded, or the error naming `file` and where the text or the value goes wrong. */
|
|
69
|
+
export declare function decodeData<T>(text: string, format: DataFormat, file: string, decoder: Decoder<T>): Result<T, LoadError>;
|
|
70
|
+
/** A file read, parsed by its extension's format and decoded; or the error naming the file and what went wrong where. */
|
|
71
|
+
export declare function loadData<T>(path: string, decoder: Decoder<T>): Promise<Result<T, LoadError>>;
|
|
72
|
+
/** A list of items decoded from either a top-level array or the array under `key` of a top-level table (`[[key]]` in TOML). */
|
|
73
|
+
export declare function listOf<T>(key: string, item: Decoder<T>): Decoder<readonly T[]>;
|
|
74
|
+
/** The waivers a file holds (a list, or under `waivers`), each refused as `defineWaiver` refuses (no expiry, an expiry before its grant, ...). */
|
|
75
|
+
export declare function loadWaivers(path: string): Promise<Result<readonly Waiver[], LoadError>>;
|
|
76
|
+
/** The risks a file holds (a list, or under `risks`), for `riskRegister`. */
|
|
77
|
+
export declare function loadRisks(path: string): Promise<Result<readonly RiskInput[], LoadError>>;
|
|
78
|
+
/** The impact declarations a file holds (a list, or under `declarations`), for `gate`. */
|
|
79
|
+
export declare function loadImpactDeclarations(path: string): Promise<Result<readonly ImpactDeclaration[], LoadError>>;
|
|
80
|
+
/** The signals of a pack run (0006-signals FR-009): the run's span, a span for each check, and a log record for each finding. */
|
|
81
|
+
export declare const GRC_SIGNALS: import("@intellectual-frontiers/telemetry/signals").Registry<{
|
|
82
|
+
readonly "grc.pack": {
|
|
83
|
+
readonly signal: "span";
|
|
84
|
+
readonly role: "step";
|
|
85
|
+
readonly description: "A pack run: its id, how many controls and subjects, and how many findings of each outcome.";
|
|
86
|
+
readonly attributes: {
|
|
87
|
+
readonly "grc.pack.id": "string";
|
|
88
|
+
readonly "grc.pack.controls": "int";
|
|
89
|
+
readonly "grc.pack.subjects": "int";
|
|
90
|
+
readonly "grc.pack.findings?": "int";
|
|
91
|
+
readonly "grc.outcome?": "string";
|
|
92
|
+
readonly "grc.findings.not-applicable?": "int";
|
|
93
|
+
readonly "grc.findings.pass?": "int";
|
|
94
|
+
readonly "grc.findings.accepted?": "int";
|
|
95
|
+
readonly "grc.findings.warn?": "int";
|
|
96
|
+
readonly "grc.findings.gap?": "int";
|
|
97
|
+
readonly "grc.findings.fail?": "int";
|
|
98
|
+
readonly "grc.findings.error?": "int";
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
readonly "grc.control": {
|
|
102
|
+
readonly signal: "span";
|
|
103
|
+
readonly role: "detail";
|
|
104
|
+
readonly description: "One control's check of one subject: the join of its findings' statuses and of their outcomes, waivers applied.";
|
|
105
|
+
readonly attributes: {
|
|
106
|
+
readonly "grc.pack.id": "string";
|
|
107
|
+
readonly "grc.control.id": "string";
|
|
108
|
+
readonly "grc.subject.kind": "string";
|
|
109
|
+
readonly "grc.subject.id": "string";
|
|
110
|
+
readonly "grc.status?": "string";
|
|
111
|
+
readonly "grc.outcome?": "string";
|
|
112
|
+
readonly "grc.findings?": "int";
|
|
113
|
+
};
|
|
114
|
+
};
|
|
115
|
+
readonly "grc.finding": {
|
|
116
|
+
readonly signal: "log";
|
|
117
|
+
readonly severity: 9;
|
|
118
|
+
readonly role: "none";
|
|
119
|
+
readonly description: "A finding; its body is the finding's OCSF Compliance Finding (class 2003), its severity the finding's.";
|
|
120
|
+
readonly attributes: {
|
|
121
|
+
readonly "grc.pack.id": "string";
|
|
122
|
+
readonly "grc.control.id": "string";
|
|
123
|
+
readonly "grc.subject.kind": "string";
|
|
124
|
+
readonly "grc.subject.id": "string";
|
|
125
|
+
readonly "grc.status": "string";
|
|
126
|
+
readonly "grc.outcome": "string";
|
|
127
|
+
readonly "grc.severity": "string";
|
|
128
|
+
readonly "grc.waiver.id?": "string";
|
|
129
|
+
};
|
|
130
|
+
};
|
|
131
|
+
}>;
|
|
132
|
+
/** The kinds of the GRC registry. */
|
|
133
|
+
export type GrcKinds = (typeof GRC_SIGNALS)["kinds"];
|
|
134
|
+
/** The scope of the GRC signals. */
|
|
135
|
+
export declare const GRC_SCOPE: Scope;
|
|
136
|
+
/** The log record severity of a finding of each severity (the table in the module's documentation). */
|
|
137
|
+
export declare const FINDING_SEVERITY: Readonly<Record<Severity, SeverityNumber>>;
|
|
138
|
+
/** A JSON value as an OTLP `AnyValue`: an integer as an `intValue` (a `bigint`), any other number a `doubleValue`, `null` left out. */
|
|
139
|
+
export declare function toAnyValue(json: unknown): AnyValue | undefined;
|
|
140
|
+
/** An OTLP `AnyValue` as JSON, undoing `toAnyValue`: an integer a `number`, bytes a list of numbers (an OCSF body holds none). */
|
|
141
|
+
export declare function fromAnyValue(value: AnyValue): unknown;
|
|
142
|
+
/** An OCSF Compliance Finding as a log record's body: an OTLP map, each integer an `intValue`. */
|
|
143
|
+
export declare function ocsfBody(doc: OcsfComplianceFinding): AnyMap;
|
|
144
|
+
/** What `runPackObserved` takes beside the pack, its subjects and the context. */
|
|
145
|
+
export type ObservedOptions = {
|
|
146
|
+
readonly waivers?: readonly Waiver[];
|
|
147
|
+
/** The telemetry to say the run in; the installed pipeline's by default, and none (the run unobserved) where none is installed. */
|
|
148
|
+
readonly telemetry?: Telemetry<GrcKinds>;
|
|
149
|
+
/** The product the OCSF documents name as their writer. */
|
|
150
|
+
readonly product: OcsfProduct;
|
|
151
|
+
};
|
|
152
|
+
/** The GRC telemetry of the installed pipeline (one for each pipeline), or undefined where none is installed. */
|
|
153
|
+
export declare function installedGrcTelemetry(): Telemetry<GrcKinds> | undefined;
|
|
154
|
+
/**
|
|
155
|
+
* A pack run as `runPack` runs it, to the same assessment, said in signals (FR-019): a `grc.pack` span, a `grc.control` span for each
|
|
156
|
+
* control and subject in the order `runPack` checks them (`error` where its outcome is `fail` or `error`, else `ok`), and a log record of
|
|
157
|
+
* each finding, waivers applied, whose body is its OCSF Compliance Finding. With no telemetry given or installed, it is `runPack`.
|
|
158
|
+
*/
|
|
159
|
+
export declare function runPackObserved<S, C extends CheckContext>(pack: Pack<S, C>, subjects: readonly S[], context: C, options: ObservedOptions): Promise<Assessment>;
|