@emilia-protocol/gate 0.8.0 → 0.9.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/README.md +7 -0
- package/action-control-manifest.js +9 -3
- package/breakglass.js +349 -0
- package/demo.mjs +10 -1
- package/deploy/helm/README.md +110 -0
- package/deploy/helm/emilia-gate/Chart.yaml +39 -0
- package/deploy/helm/emilia-gate/templates/NOTES.txt +48 -0
- package/deploy/helm/emilia-gate/templates/configmap.yaml +27 -0
- package/deploy/helm/emilia-gate/templates/deployment.yaml +134 -0
- package/deploy/helm/emilia-gate/templates/service.yaml +28 -0
- package/deploy/helm/emilia-gate/templates/servicemonitor.yaml +41 -0
- package/deploy/helm/emilia-gate/values.yaml +169 -0
- package/deploy/terraform/README.md +138 -0
- package/deploy/terraform/main.tf +256 -0
- package/deploy/terraform/outputs.tf +33 -0
- package/deploy/terraform/variables.tf +205 -0
- package/deploy/terraform/versions.tf +18 -0
- package/eg1-conformance.js +111 -13
- package/enterprise.js +174 -0
- package/index.js +257 -28
- package/metering.js +227 -0
- package/metrics.js +232 -0
- package/package.json +41 -5
- package/reliance-packet.js +80 -2
- package/reports/art14.js +0 -0
- package/reports/auditor-workpaper.js +538 -0
- package/reports/reperform.js +365 -0
- package/reports/underwriter.js +340 -0
- package/roster.js +265 -0
- package/siem.js +236 -0
- package/store-postgres.js +129 -0
package/metering.js
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* EMILIA Gate — usage metering (the value metric, EP-GATE-USAGE-v1).
|
|
4
|
+
*
|
|
5
|
+
* Pricing scales with what the gate actually protects: PROTECTED IRREVERSIBLE
|
|
6
|
+
* ACTIONS (guarded decisions — allows AND denies both consume enforcement) plus
|
|
7
|
+
* RECEIPT-YEARS under retention (one receipt kept one year = one receipt-year;
|
|
8
|
+
* horizons follow retention.js, default 6y = 2190 days). NEVER seats.
|
|
9
|
+
*
|
|
10
|
+
* Pure functions over evidence-log entries (`evidence.all()`); no clock, no
|
|
11
|
+
* network. The billing period is an explicit [periodStart, periodEnd) window —
|
|
12
|
+
* INCLUSIVE start, EXCLUSIVE end — so adjacent periods never double-count an
|
|
13
|
+
* entry sitting exactly on a boundary.
|
|
14
|
+
*
|
|
15
|
+
* Fail-closed posture for billing: an unbounded or reversed period is refused
|
|
16
|
+
* (thrown); malformed entries are surfaced in `integrity_warnings` rather than
|
|
17
|
+
* silently dropped; an entry whose allow flag is not literally `true` is
|
|
18
|
+
* counted as a deny; a statement over foreign or malformed usage is refused.
|
|
19
|
+
* `buildUsageStatement` output is deterministic (sorted keys + content hash)
|
|
20
|
+
* and UNSIGNED — the deployer signs it; the content hash binds that signature
|
|
21
|
+
* to exactly these numbers for billing reconciliation.
|
|
22
|
+
*/
|
|
23
|
+
import crypto from 'node:crypto';
|
|
24
|
+
|
|
25
|
+
export const USAGE_VERSION = 'EP-GATE-USAGE-v1';
|
|
26
|
+
|
|
27
|
+
const DAYS_PER_YEAR = 365;
|
|
28
|
+
// Mirrors retention.js's cold-horizon default (coldDays = 2190 = 6y): a receipt
|
|
29
|
+
// is presumed retained for the full audit horizon unless the entry states its own.
|
|
30
|
+
const DEFAULT_RETENTION_YEARS = 2190 / DAYS_PER_YEAR;
|
|
31
|
+
|
|
32
|
+
function sha256hex(s) {
|
|
33
|
+
return crypto.createHash('sha256').update(s).digest('hex');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Canonical JSON (recursive sorted keys) — matches evidence.js / @emilia-protocol/verify. */
|
|
37
|
+
function canonical(v) {
|
|
38
|
+
if (v === null || v === undefined) return JSON.stringify(v);
|
|
39
|
+
if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`;
|
|
40
|
+
if (typeof v === 'object') {
|
|
41
|
+
return `{${Object.keys(v).sort().map((k) => JSON.stringify(k) + ':' + canonical(v[k])).join(',')}}`;
|
|
42
|
+
}
|
|
43
|
+
return JSON.stringify(v);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function toMs(t) {
|
|
47
|
+
if (t == null) return null;
|
|
48
|
+
const ms = typeof t === 'number' ? t : Date.parse(t);
|
|
49
|
+
return Number.isFinite(ms) ? ms : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Key-sorted copy so output is byte-stable regardless of entry order. */
|
|
53
|
+
function sortedCounts(map) {
|
|
54
|
+
const out = {};
|
|
55
|
+
for (const k of Object.keys(map).sort()) out[k] = map[k];
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Entry-level day resolution (1/365y ≈ 0.00274) without float noise. */
|
|
60
|
+
function round6(x) {
|
|
61
|
+
return Math.round(x * 1e6) / 1e6;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The retention this entry STATES for itself, in years.
|
|
66
|
+
* @returns {number|null|NaN} years, `null` when unstated (default applies),
|
|
67
|
+
* `NaN` when stated but invalid (default applies + integrity warning — a
|
|
68
|
+
* malformed stated value must never silently shrink the metered total).
|
|
69
|
+
*/
|
|
70
|
+
function statedRetentionYears(e) {
|
|
71
|
+
if (e.retention_years != null) {
|
|
72
|
+
const y = Number(e.retention_years);
|
|
73
|
+
return Number.isFinite(y) && y >= 0 ? y : NaN;
|
|
74
|
+
}
|
|
75
|
+
if (e.retention_days != null) {
|
|
76
|
+
const d = Number(e.retention_days);
|
|
77
|
+
return Number.isFinite(d) && d >= 0 ? d / DAYS_PER_YEAR : NaN;
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Meter a billing period over evidence entries.
|
|
84
|
+
*
|
|
85
|
+
* Billable = `kind: 'decision'` entries on GUARDED actions (`not_guarded`
|
|
86
|
+
* pass-throughs are free; execution records are provenance, not enforcement).
|
|
87
|
+
* Window is [periodStart, periodEnd): inclusive start, exclusive end.
|
|
88
|
+
*
|
|
89
|
+
* @param {Array<object>} entries evidence.all()
|
|
90
|
+
* @param {object} o
|
|
91
|
+
* @param {string|number} o.periodStart ISO or ms — required
|
|
92
|
+
* @param {string|number} o.periodEnd ISO or ms — required, >= periodStart
|
|
93
|
+
* @param {number} [o.retentionYearsDefault=6] applied when an entry states no retention
|
|
94
|
+
* @returns {{protected_actions:number, allows:number, denies:number,
|
|
95
|
+
* replays_blocked:number, by_action_type:object, by_tier:object,
|
|
96
|
+
* receipt_years:number, period:object, integrity_warnings:object[]}}
|
|
97
|
+
*/
|
|
98
|
+
export function meterUsage(entries = [], { periodStart, periodEnd, retentionYearsDefault = DEFAULT_RETENTION_YEARS } = {}) {
|
|
99
|
+
const startMs = toMs(periodStart);
|
|
100
|
+
const endMs = toMs(periodEnd);
|
|
101
|
+
// An unbounded or reversed period is not meterable — refuse rather than emit
|
|
102
|
+
// a statement whose window cannot be reconciled.
|
|
103
|
+
if (startMs == null || endMs == null) {
|
|
104
|
+
throw new Error('meterUsage: periodStart and periodEnd are required (ISO string or ms)');
|
|
105
|
+
}
|
|
106
|
+
if (endMs < startMs) throw new Error('meterUsage: periodEnd must be >= periodStart');
|
|
107
|
+
if (!Number.isFinite(retentionYearsDefault) || retentionYearsDefault < 0) {
|
|
108
|
+
throw new Error('meterUsage: retentionYearsDefault must be a finite number >= 0');
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const warnings = [];
|
|
112
|
+
const byAction = Object.create(null);
|
|
113
|
+
const byTier = Object.create(null);
|
|
114
|
+
let protectedActions = 0;
|
|
115
|
+
let allows = 0;
|
|
116
|
+
let denies = 0;
|
|
117
|
+
let replaysBlocked = 0;
|
|
118
|
+
let receiptYears = 0;
|
|
119
|
+
|
|
120
|
+
entries.forEach((e, index) => {
|
|
121
|
+
if (!e || typeof e !== 'object' || Array.isArray(e)) {
|
|
122
|
+
warnings.push({ index, reason: 'not_an_object' });
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const t = toMs(e.at);
|
|
126
|
+
if (t == null) {
|
|
127
|
+
// Unplaceable in ANY period — surfaced, never silently dropped.
|
|
128
|
+
warnings.push({ index, reason: 'unparseable_at' });
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (t < startMs || t >= endMs) return; // outside [start, end)
|
|
132
|
+
if (typeof e.kind !== 'string' || e.kind.length === 0) {
|
|
133
|
+
warnings.push({ index, reason: 'missing_kind' });
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (e.kind !== 'decision') return; // execution/other records are not billable
|
|
137
|
+
if (e.reason === 'not_guarded') return; // pass-throughs are free by design
|
|
138
|
+
|
|
139
|
+
protectedActions += 1;
|
|
140
|
+
// Fail closed: only a literal `true` counts as an allow.
|
|
141
|
+
if (e.allow === true) allows += 1; else denies += 1;
|
|
142
|
+
if (e.reason === 'replay_refused') replaysBlocked += 1;
|
|
143
|
+
|
|
144
|
+
const action = typeof e.action === 'string' && e.action ? e.action : 'unknown';
|
|
145
|
+
byAction[action] = (byAction[action] || 0) + 1;
|
|
146
|
+
const tier = typeof e.required_tier === 'string' && e.required_tier ? e.required_tier : 'unknown';
|
|
147
|
+
byTier[tier] = (byTier[tier] || 0) + 1;
|
|
148
|
+
|
|
149
|
+
const stated = statedRetentionYears(e);
|
|
150
|
+
if (Number.isNaN(stated)) {
|
|
151
|
+
warnings.push({ index, reason: 'invalid_stated_retention' });
|
|
152
|
+
receiptYears += retentionYearsDefault;
|
|
153
|
+
} else {
|
|
154
|
+
receiptYears += stated ?? retentionYearsDefault;
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
return {
|
|
159
|
+
'@version': USAGE_VERSION,
|
|
160
|
+
period: {
|
|
161
|
+
start: new Date(startMs).toISOString(),
|
|
162
|
+
end: new Date(endMs).toISOString(),
|
|
163
|
+
bounds: 'inclusive_start_exclusive_end',
|
|
164
|
+
},
|
|
165
|
+
protected_actions: protectedActions,
|
|
166
|
+
allows,
|
|
167
|
+
denies,
|
|
168
|
+
replays_blocked: replaysBlocked,
|
|
169
|
+
by_action_type: sortedCounts(byAction),
|
|
170
|
+
by_tier: sortedCounts(byTier),
|
|
171
|
+
receipt_years: round6(receiptYears),
|
|
172
|
+
retention_years_default: retentionYearsDefault,
|
|
173
|
+
integrity_warnings: warnings,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Build the signed-ready usage statement handed to billing reconciliation.
|
|
179
|
+
* UNSIGNED — the deployer signs it; `content_hash` (sha256 over the canonical
|
|
180
|
+
* JSON of everything else) binds that signature to exactly these numbers.
|
|
181
|
+
* Deterministic: same usage + org → byte-identical statement, regardless of
|
|
182
|
+
* the entry order the usage was metered from.
|
|
183
|
+
*/
|
|
184
|
+
export function buildUsageStatement(usage, { org } = {}) {
|
|
185
|
+
// Never emit a statement over an artifact of a different or unknown format,
|
|
186
|
+
// and never one that fails to name who it bills.
|
|
187
|
+
if (!usage || usage['@version'] !== USAGE_VERSION) {
|
|
188
|
+
throw new Error(`buildUsageStatement: usage must be a ${USAGE_VERSION} object from meterUsage`);
|
|
189
|
+
}
|
|
190
|
+
if (!org || typeof org !== 'string') {
|
|
191
|
+
throw new Error('buildUsageStatement: org is required — a statement must name the billed party');
|
|
192
|
+
}
|
|
193
|
+
if (!usage.period || !usage.period.start || !usage.period.end) {
|
|
194
|
+
throw new Error('buildUsageStatement: usage.period is missing');
|
|
195
|
+
}
|
|
196
|
+
for (const k of ['protected_actions', 'allows', 'denies', 'replays_blocked', 'receipt_years']) {
|
|
197
|
+
if (!Number.isFinite(usage[k]) || usage[k] < 0) {
|
|
198
|
+
throw new Error(`buildUsageStatement: usage.${k} must be a finite number >= 0`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const warningCount = Array.isArray(usage.integrity_warnings) ? usage.integrity_warnings.length : 0;
|
|
202
|
+
const body = {
|
|
203
|
+
'@version': USAGE_VERSION,
|
|
204
|
+
kind: 'usage_statement',
|
|
205
|
+
org,
|
|
206
|
+
period: {
|
|
207
|
+
start: usage.period.start,
|
|
208
|
+
end: usage.period.end,
|
|
209
|
+
bounds: 'inclusive_start_exclusive_end',
|
|
210
|
+
},
|
|
211
|
+
protected_actions: usage.protected_actions,
|
|
212
|
+
allows: usage.allows,
|
|
213
|
+
denies: usage.denies,
|
|
214
|
+
replays_blocked: usage.replays_blocked,
|
|
215
|
+
by_action_type: sortedCounts(usage.by_action_type || {}),
|
|
216
|
+
by_tier: sortedCounts(usage.by_tier || {}),
|
|
217
|
+
receipt_years: usage.receipt_years,
|
|
218
|
+
retention_years_default: usage.retention_years_default ?? DEFAULT_RETENTION_YEARS,
|
|
219
|
+
// Data-quality signal for the reconciler: a statement metered over a log
|
|
220
|
+
// with integrity warnings is flagged incomplete, never silently clean.
|
|
221
|
+
integrity_warning_count: warningCount,
|
|
222
|
+
complete: warningCount === 0,
|
|
223
|
+
};
|
|
224
|
+
return { ...body, content_hash: sha256hex(canonical(body)) };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export default { meterUsage, buildUsageStatement, USAGE_VERSION };
|
package/metrics.js
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* EMILIA Gate — Prometheus metrics exposition (EP-GATE-METRICS-v1).
|
|
4
|
+
*
|
|
5
|
+
* Zero-dependency operational metrics over gate decisions, rendered in the
|
|
6
|
+
* Prometheus text exposition format 0.0.4 (HELP/TYPE lines, escaped label
|
|
7
|
+
* values, stable sorted output). Feed it the gate's decision entries — either
|
|
8
|
+
* the evidence-log entry ({ allow, action, reason, have_tier/required_tier,
|
|
9
|
+
* at }) or the `check()` output — via `onDecision`; scrape via `render()` or
|
|
10
|
+
* mount `handler()` on any framework.
|
|
11
|
+
*
|
|
12
|
+
* CONSTRAINT (enforced): metrics must NEVER throw into the enforcement path.
|
|
13
|
+
* `onDecision` sits on the gate's decision hot path; observability is never
|
|
14
|
+
* allowed to break enforcement. Any entry it cannot interpret — wrong type,
|
|
15
|
+
* underivable outcome, even a poisoned object whose property getters throw —
|
|
16
|
+
* increments ep_gate_metrics_malformed_total and returns. No exception
|
|
17
|
+
* escapes `onDecision`, ever.
|
|
18
|
+
*
|
|
19
|
+
* CARDINALITY GUARD: the action_type label is capped to a bounded set via the
|
|
20
|
+
* `maxSeries` option (default 64 distinct values). Once the cap is reached,
|
|
21
|
+
* new action types bucket to action_type="_other" so a hostile or buggy
|
|
22
|
+
* caller cannot blow up the time-series database. All label values are also
|
|
23
|
+
* length-capped. outcome and reason_class are bounded by construction.
|
|
24
|
+
*
|
|
25
|
+
* Deterministic and pure: time is injected (`now`), used only when an entry
|
|
26
|
+
* carries no usable timestamp. Same entries in, same exposition text out.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
export const METRICS_VERSION = 'EP-GATE-METRICS-v1';
|
|
30
|
+
|
|
31
|
+
/** Prometheus text exposition format 0.0.4 content type. */
|
|
32
|
+
export const METRICS_CONTENT_TYPE = 'text/plain; version=0.0.4; charset=utf-8';
|
|
33
|
+
|
|
34
|
+
/** Bounded denial reason classes — every gate refusal maps into exactly one. */
|
|
35
|
+
export const REASON_CLASSES = [
|
|
36
|
+
'replay', // replay_refused — one-time consumption caught a reuse
|
|
37
|
+
'receipt_missing', // receipt_required — guarded action arrived with no receipt
|
|
38
|
+
'receipt_invalid', // receipt_rejected:* — signature/freshness/scope/id failures
|
|
39
|
+
'assurance', // assurance_too_low | unknown_required_tier
|
|
40
|
+
'execution_binding', // execution_binding_failed — claim != observed mutation
|
|
41
|
+
'infrastructure', // evidence_log_failed | consumption_store_lacks_reserve
|
|
42
|
+
'other', // anything this version does not model
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
/** Longest label value we will expose; longer values are truncated (bounded exposition size). */
|
|
46
|
+
const MAX_LABEL_VALUE_LEN = 128;
|
|
47
|
+
|
|
48
|
+
/** Overflow bucket for the action_type cardinality guard. */
|
|
49
|
+
const OTHER_BUCKET = '_other';
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Classify a gate denial reason string into one of REASON_CLASSES. Bounded by
|
|
53
|
+
* construction: unknown reasons land in 'other', never in a fresh label value.
|
|
54
|
+
* @param {string} reason e.g. 'replay_refused', 'receipt_rejected:bad_signature'
|
|
55
|
+
* @returns {string} one of REASON_CLASSES
|
|
56
|
+
*/
|
|
57
|
+
export function classifyDenialReason(reason) {
|
|
58
|
+
if (typeof reason !== 'string') return 'other';
|
|
59
|
+
if (reason === 'replay_refused' || reason.includes('replay')) return 'replay';
|
|
60
|
+
if (reason === 'receipt_required') return 'receipt_missing';
|
|
61
|
+
if (reason.startsWith('receipt_rejected')) return 'receipt_invalid';
|
|
62
|
+
if (reason === 'assurance_too_low' || reason === 'unknown_required_tier') return 'assurance';
|
|
63
|
+
if (reason === 'execution_binding_failed') return 'execution_binding';
|
|
64
|
+
if (reason === 'evidence_log_failed' || reason === 'consumption_store_lacks_reserve') return 'infrastructure';
|
|
65
|
+
return 'other';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Escape a label value per the exposition format: backslash, quote, newline. */
|
|
69
|
+
function escapeLabelValue(v) {
|
|
70
|
+
return String(v)
|
|
71
|
+
.replace(/\\/g, '\\\\')
|
|
72
|
+
.replace(/"/g, '\\"')
|
|
73
|
+
.replace(/\n/g, '\\n');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Escape HELP text per the exposition format: backslash and newline only. */
|
|
77
|
+
function escapeHelp(v) {
|
|
78
|
+
return String(v).replace(/\\/g, '\\\\').replace(/\n/g, '\\n');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Normalize a raw value into a safe, length-capped label value. */
|
|
82
|
+
function normLabel(raw, fallback) {
|
|
83
|
+
if (typeof raw !== 'string' || raw.length === 0) return fallback;
|
|
84
|
+
return raw.length > MAX_LABEL_VALUE_LEN ? raw.slice(0, MAX_LABEL_VALUE_LEN) : raw;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Render a sorted, escaped label set: {a="x",b="y"} — stable key order. */
|
|
88
|
+
function renderLabels(obj) {
|
|
89
|
+
const keys = Object.keys(obj).sort();
|
|
90
|
+
return `{${keys.map((k) => `${k}="${escapeLabelValue(obj[k])}"`).join(',')}}`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const METRICS = [
|
|
94
|
+
{ name: 'ep_gate_decisions_total', type: 'counter', help: 'Gate decisions by outcome, action type, and credited assurance tier.' },
|
|
95
|
+
{ name: 'ep_gate_denials_total', type: 'counter', help: 'Denied gate decisions by bounded denial reason class.' },
|
|
96
|
+
{ name: 'ep_gate_evidence_entries_total', type: 'counter', help: 'Evidence-log entries recorded for gate decisions.' },
|
|
97
|
+
{ name: 'ep_gate_last_decision_timestamp_seconds', type: 'gauge', help: 'Unix timestamp (seconds) of the most recent gate decision.' },
|
|
98
|
+
{ name: 'ep_gate_metrics_malformed_total', type: 'counter', help: 'Decision entries the metrics layer could not interpret (dropped, never thrown).' },
|
|
99
|
+
{ name: 'ep_gate_replays_blocked_total', type: 'counter', help: 'Receipt replays refused by one-time consumption.' },
|
|
100
|
+
];
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Create a metrics registry for one gate.
|
|
104
|
+
* @param {object} [o]
|
|
105
|
+
* @param {number} [o.maxSeries=64] cap on distinct action_type label values; overflow buckets to "_other"
|
|
106
|
+
* @param {number|function} [o.now=Date.now] injected clock (ms or () => ms) — used only when an entry has no usable timestamp
|
|
107
|
+
* @returns {{ onDecision: (entry: object) => void, render: () => string, handler: () => { status: number, headers: object, body: string } }}
|
|
108
|
+
*/
|
|
109
|
+
export function createMetrics({ maxSeries = 64, now = Date.now } = {}) {
|
|
110
|
+
// Config is clamped, not thrown: a bad option must not brick metrics either.
|
|
111
|
+
const cap = (Number.isInteger(maxSeries) && maxSeries > 0) ? maxSeries : 64;
|
|
112
|
+
|
|
113
|
+
const decisions = new Map(); // rendered label set -> count
|
|
114
|
+
const denials = new Map(); // rendered label set -> count
|
|
115
|
+
let replaysBlocked = 0;
|
|
116
|
+
let evidenceEntries = 0;
|
|
117
|
+
let malformed = 0;
|
|
118
|
+
let lastDecisionSeconds = null; // gauge; no sample until the first decision
|
|
119
|
+
|
|
120
|
+
const actionTypes = new Set(); // cardinality guard for action_type
|
|
121
|
+
|
|
122
|
+
function boundedActionType(raw) {
|
|
123
|
+
const v = normLabel(raw, 'unknown');
|
|
124
|
+
if (actionTypes.has(v)) return v;
|
|
125
|
+
if (actionTypes.size < cap) { actionTypes.add(v); return v; }
|
|
126
|
+
return OTHER_BUCKET;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function inc(map, key) {
|
|
130
|
+
map.set(key, (map.get(key) || 0) + 1);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Observe one gate decision. NEVER throws — see the module constraint. A
|
|
135
|
+
* malformed entry (non-object, underivable outcome, throwing getters, ...)
|
|
136
|
+
* increments ep_gate_metrics_malformed_total and returns.
|
|
137
|
+
*/
|
|
138
|
+
function onDecision(entry) {
|
|
139
|
+
try {
|
|
140
|
+
if (!entry || typeof entry !== 'object') { malformed += 1; return; }
|
|
141
|
+
|
|
142
|
+
// Outcome: the authoritative field is the boolean `allow` (evidence
|
|
143
|
+
// entry and check() output both carry it). A string outcome is accepted
|
|
144
|
+
// only if it is exactly 'allow'/'deny'. Anything else is malformed.
|
|
145
|
+
let outcome;
|
|
146
|
+
if (entry.allow === true) outcome = 'allow';
|
|
147
|
+
else if (entry.allow === false) outcome = 'deny';
|
|
148
|
+
else if (entry.outcome === 'allow' || entry.outcome === 'deny') outcome = entry.outcome;
|
|
149
|
+
else { malformed += 1; return; }
|
|
150
|
+
|
|
151
|
+
const actionType = boundedActionType(entry.action_type ?? entry.action);
|
|
152
|
+
const tier = normLabel(entry.tier ?? entry.have_tier ?? entry.required_tier, 'unknown');
|
|
153
|
+
|
|
154
|
+
inc(decisions, renderLabels({ outcome, action_type: actionType, tier }));
|
|
155
|
+
|
|
156
|
+
if (outcome === 'deny') {
|
|
157
|
+
const reasonClass = classifyDenialReason(entry.reason);
|
|
158
|
+
inc(denials, renderLabels({ reason_class: reasonClass }));
|
|
159
|
+
if (reasonClass === 'replay') replaysBlocked += 1;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Each decision appends one evidence record — unless the entry says the
|
|
163
|
+
// write failed outright (check() output carries evidence: null then).
|
|
164
|
+
if (entry.evidence !== null) evidenceEntries += 1;
|
|
165
|
+
|
|
166
|
+
// Gauge: prefer the entry's own timestamp (`at` ISO/ms), else the
|
|
167
|
+
// injected clock. An unusable clock skips the gauge — never throws.
|
|
168
|
+
const at = entry.at ?? entry.created_at ?? null;
|
|
169
|
+
let ms = null;
|
|
170
|
+
if (typeof at === 'number' && Number.isFinite(at)) ms = at;
|
|
171
|
+
else if (typeof at === 'string') { const p = Date.parse(at); if (Number.isFinite(p)) ms = p; }
|
|
172
|
+
if (ms == null) {
|
|
173
|
+
try {
|
|
174
|
+
const n = typeof now === 'function' ? now() : now;
|
|
175
|
+
if (typeof n === 'number' && Number.isFinite(n)) ms = n;
|
|
176
|
+
} catch { /* unusable injected clock: skip the gauge update */ }
|
|
177
|
+
}
|
|
178
|
+
if (ms != null) lastDecisionSeconds = ms / 1000;
|
|
179
|
+
} catch {
|
|
180
|
+
// The never-throw guarantee: a poisoned entry (throwing getter, hostile
|
|
181
|
+
// proxy) lands here. Count it, drop it, return. Enforcement continues.
|
|
182
|
+
malformed += 1;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Render Prometheus text format 0.0.4. Deterministic: metrics in fixed order, series sorted. */
|
|
187
|
+
function render() {
|
|
188
|
+
const lines = [];
|
|
189
|
+
for (const m of METRICS) {
|
|
190
|
+
lines.push(`# HELP ${m.name} ${escapeHelp(m.help)}`);
|
|
191
|
+
lines.push(`# TYPE ${m.name} ${m.type}`);
|
|
192
|
+
switch (m.name) {
|
|
193
|
+
case 'ep_gate_decisions_total':
|
|
194
|
+
for (const k of [...decisions.keys()].sort()) lines.push(`${m.name}${k} ${decisions.get(k)}`);
|
|
195
|
+
break;
|
|
196
|
+
case 'ep_gate_denials_total':
|
|
197
|
+
for (const k of [...denials.keys()].sort()) lines.push(`${m.name}${k} ${denials.get(k)}`);
|
|
198
|
+
break;
|
|
199
|
+
case 'ep_gate_evidence_entries_total':
|
|
200
|
+
lines.push(`${m.name} ${evidenceEntries}`);
|
|
201
|
+
break;
|
|
202
|
+
case 'ep_gate_last_decision_timestamp_seconds':
|
|
203
|
+
// No sample until the first decision — a fabricated 0 would read as 1970.
|
|
204
|
+
if (lastDecisionSeconds != null) lines.push(`${m.name} ${lastDecisionSeconds}`);
|
|
205
|
+
break;
|
|
206
|
+
case 'ep_gate_metrics_malformed_total':
|
|
207
|
+
lines.push(`${m.name} ${malformed}`);
|
|
208
|
+
break;
|
|
209
|
+
case 'ep_gate_replays_blocked_total':
|
|
210
|
+
lines.push(`${m.name} ${replaysBlocked}`);
|
|
211
|
+
break;
|
|
212
|
+
/* c8 ignore next 2 -- METRICS is a module constant; no other names exist */
|
|
213
|
+
default:
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return lines.join('\n') + '\n';
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Framework-agnostic scrape response: mount on any router/handler. */
|
|
221
|
+
function handler() {
|
|
222
|
+
return {
|
|
223
|
+
status: 200,
|
|
224
|
+
headers: { 'content-type': METRICS_CONTENT_TYPE },
|
|
225
|
+
body: render(),
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
return { onDecision, render, handler };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export default { createMetrics, classifyDenialReason, METRICS_VERSION, METRICS_CONTENT_TYPE, REASON_CLASSES };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@emilia-protocol/gate",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "EMILIA Gate
|
|
3
|
+
"version": "0.9.1",
|
|
4
|
+
"description": "EMILIA Gate \u2014 the Trusted Action Firewall. Deny-by-default enforcement for consequential machine actions: an action runs only with a valid, in-scope, sufficiently-assured, non-replayed EMILIA authorization receipt (proof a named human authorized this exact action). Composes require-receipt + verify; adds assurance-tier enforcement, one-time consumption (replay defense), a tamper-evident evidence log, default high-risk action packs, execution-field binding, reliance packets, an MCP drop-in, a GitHub system-of-record adapter, and EG-1 conformance. Framework-agnostic, fails closed. Reference implementation, experimental.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "index.js",
|
|
@@ -23,7 +23,18 @@
|
|
|
23
23
|
"./adapters/salesforce": "./adapters/salesforce.js",
|
|
24
24
|
"./key-registry": "./key-registry.js",
|
|
25
25
|
"./retention": "./retention.js",
|
|
26
|
-
"./package.json": "./package.json"
|
|
26
|
+
"./package.json": "./package.json",
|
|
27
|
+
"./enterprise": "./enterprise.js",
|
|
28
|
+
"./metering": "./metering.js",
|
|
29
|
+
"./siem": "./siem.js",
|
|
30
|
+
"./roster": "./roster.js",
|
|
31
|
+
"./reports/art14": "./reports/art14.js",
|
|
32
|
+
"./reports/underwriter": "./reports/underwriter.js",
|
|
33
|
+
"./metrics": "./metrics.js",
|
|
34
|
+
"./breakglass": "./breakglass.js",
|
|
35
|
+
"./store-postgres": "./store-postgres.js",
|
|
36
|
+
"./reports/auditor-workpaper": "./reports/auditor-workpaper.js",
|
|
37
|
+
"./reports/reperform": "./reports/reperform.js"
|
|
27
38
|
},
|
|
28
39
|
"files": [
|
|
29
40
|
"index.js",
|
|
@@ -56,7 +67,31 @@
|
|
|
56
67
|
"adapters/salesforce.js",
|
|
57
68
|
"demo.mjs",
|
|
58
69
|
"custody-demo.mjs",
|
|
59
|
-
"README.md"
|
|
70
|
+
"README.md",
|
|
71
|
+
"enterprise.js",
|
|
72
|
+
"metering.js",
|
|
73
|
+
"siem.js",
|
|
74
|
+
"roster.js",
|
|
75
|
+
"reports/art14.js",
|
|
76
|
+
"reports/underwriter.js",
|
|
77
|
+
"metrics.js",
|
|
78
|
+
"breakglass.js",
|
|
79
|
+
"store-postgres.js",
|
|
80
|
+
"deploy/helm/emilia-gate/Chart.yaml",
|
|
81
|
+
"deploy/helm/emilia-gate/values.yaml",
|
|
82
|
+
"deploy/helm/emilia-gate/templates/deployment.yaml",
|
|
83
|
+
"deploy/helm/emilia-gate/templates/service.yaml",
|
|
84
|
+
"deploy/helm/emilia-gate/templates/configmap.yaml",
|
|
85
|
+
"deploy/helm/emilia-gate/templates/servicemonitor.yaml",
|
|
86
|
+
"deploy/helm/emilia-gate/templates/NOTES.txt",
|
|
87
|
+
"deploy/helm/README.md",
|
|
88
|
+
"deploy/terraform/main.tf",
|
|
89
|
+
"deploy/terraform/variables.tf",
|
|
90
|
+
"deploy/terraform/outputs.tf",
|
|
91
|
+
"deploy/terraform/versions.tf",
|
|
92
|
+
"deploy/terraform/README.md",
|
|
93
|
+
"reports/auditor-workpaper.js",
|
|
94
|
+
"reports/reperform.js"
|
|
60
95
|
],
|
|
61
96
|
"scripts": {
|
|
62
97
|
"test": "node --test",
|
|
@@ -65,7 +100,8 @@
|
|
|
65
100
|
"cf1": "node cf1.mjs"
|
|
66
101
|
},
|
|
67
102
|
"dependencies": {
|
|
68
|
-
"@emilia-protocol/require-receipt": "^0.5.0"
|
|
103
|
+
"@emilia-protocol/require-receipt": "^0.5.0",
|
|
104
|
+
"@emilia-protocol/verify": "^3.3.0"
|
|
69
105
|
},
|
|
70
106
|
"keywords": [
|
|
71
107
|
"emilia",
|
package/reliance-packet.js
CHANGED
|
@@ -3,6 +3,54 @@
|
|
|
3
3
|
|
|
4
4
|
export const RELIANCE_PACKET_VERSION = 'EP-GATE-RELIANCE-PACKET-v1';
|
|
5
5
|
|
|
6
|
+
// The CLOSED admissibility verdict set (mirror of lib/evidence/admissibility.js
|
|
7
|
+
// ADMISSIBILITY_VERDICTS). The gate does NOT import that app module — it stays a
|
|
8
|
+
// dependency-light published package — so the closed set is restated here as a
|
|
9
|
+
// value contract. 'admissible' is the ONLY verdict that reads as success; every
|
|
10
|
+
// other member, and anything not in this set, fails closed. Precedence lives in
|
|
11
|
+
// the evaluator; the gate never re-derives a verdict, it only checks the one the
|
|
12
|
+
// relying party's offline evaluator already computed.
|
|
13
|
+
export const ADMISSIBILITY_VERDICTS = Object.freeze([
|
|
14
|
+
'admissible', 'missing_evidence', 'stale', 'conflicted', 'unverifiable',
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Normalize an admissibility block onto the packet. FAIL CLOSED: a missing block,
|
|
19
|
+
* a missing/unrecognized verdict, or a non-'admissible' verdict all produce
|
|
20
|
+
* admissible:false. The block is only carried when the caller supplies one; when
|
|
21
|
+
* absent, `admissibility` is null and no admissibility gating applies (backwards
|
|
22
|
+
* compatible with pre-profile packets).
|
|
23
|
+
*
|
|
24
|
+
* @param {object|null} adm the relying-party evaluator's result, carrying
|
|
25
|
+
* { admissibility_profile:{id,version}, profile_hash, verdict, replay_digest, challenge_id?, challenge_digest? }
|
|
26
|
+
*/
|
|
27
|
+
function normalizeAdmissibility(adm) {
|
|
28
|
+
if (!adm || typeof adm !== 'object') return null;
|
|
29
|
+
const verdict = typeof adm.verdict === 'string' ? adm.verdict : null;
|
|
30
|
+
const recognized = verdict !== null && ADMISSIBILITY_VERDICTS.includes(verdict);
|
|
31
|
+
// Only a recognized 'admissible' verdict reads as success. Missing, malformed,
|
|
32
|
+
// or any other closed-set member (missing_evidence/stale/conflicted/unverifiable)
|
|
33
|
+
// is non-admissible.
|
|
34
|
+
const admissible = recognized && verdict === 'admissible';
|
|
35
|
+
const profile = adm.admissibility_profile && typeof adm.admissibility_profile === 'object'
|
|
36
|
+
? { id: adm.admissibility_profile.id ?? null, version: adm.admissibility_profile.version ?? null }
|
|
37
|
+
: null;
|
|
38
|
+
return {
|
|
39
|
+
admissibility_profile: profile,
|
|
40
|
+
profile_hash: typeof adm.profile_hash === 'string' ? adm.profile_hash : null,
|
|
41
|
+
verdict: verdict, // preserved verbatim (including null / unrecognized) for the auditor
|
|
42
|
+
verdict_recognized: recognized,
|
|
43
|
+
admissible,
|
|
44
|
+
replay_digest: typeof adm.replay_digest === 'string' ? adm.replay_digest : null,
|
|
45
|
+
// The evidence-challenge loop (lib/negotiate/evidence-challenge.js) keys each
|
|
46
|
+
// round by challenge_id; challenge_digest is carried through when the caller
|
|
47
|
+
// hashes the challenge. Either identifies which challenge round this verdict
|
|
48
|
+
// answers. Both null-safe.
|
|
49
|
+
challenge_id: adm.challenge_id ?? null,
|
|
50
|
+
challenge_digest: typeof adm.challenge_digest === 'string' ? adm.challenge_digest : null,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
6
54
|
function evidenceStatus(evidence) {
|
|
7
55
|
if (!evidence) return { ok: null, length: null, head: null };
|
|
8
56
|
if (typeof evidence.verify === 'function') return evidence.verify();
|
|
@@ -19,6 +67,7 @@ export function buildReliancePacket({
|
|
|
19
67
|
evidence = null,
|
|
20
68
|
manifest = null,
|
|
21
69
|
binding = null,
|
|
70
|
+
admissibility = null,
|
|
22
71
|
verifier = '@emilia-protocol/gate',
|
|
23
72
|
} = {}) {
|
|
24
73
|
const evidenceCheck = evidenceStatus(evidence);
|
|
@@ -28,7 +77,15 @@ export function buildReliancePacket({
|
|
|
28
77
|
const allowed = decision?.allow === true;
|
|
29
78
|
const evidenceOk = evidenceCheck.ok !== false;
|
|
30
79
|
const bindingOk = bindingCheck ? bindingCheck.ok === true : true;
|
|
31
|
-
|
|
80
|
+
|
|
81
|
+
// Admissibility block (relying-party evaluator output, computed OFFLINE against
|
|
82
|
+
// its PINNED profile — never re-derived here). When present it is an additional
|
|
83
|
+
// gate on 'rely': a non-'admissible' verdict (or a missing/unrecognized one)
|
|
84
|
+
// fails closed. When absent, admissibility does not affect the verdict.
|
|
85
|
+
const adm = normalizeAdmissibility(admissibility);
|
|
86
|
+
const admissibilityOk = adm === null ? true : adm.admissible === true;
|
|
87
|
+
|
|
88
|
+
const verdict = allowed && executionBound && evidenceOk && bindingOk && admissibilityOk ? 'rely' : 'do_not_rely';
|
|
32
89
|
|
|
33
90
|
return {
|
|
34
91
|
'@version': RELIANCE_PACKET_VERSION,
|
|
@@ -44,7 +101,17 @@ export function buildReliancePacket({
|
|
|
44
101
|
decision_hash: decisionHash,
|
|
45
102
|
execution_hash: execution?.hash || null,
|
|
46
103
|
evidence_head: evidenceCheck.head || null,
|
|
104
|
+
// Surface the admissibility verdict + pinned profile in the summary so an
|
|
105
|
+
// auditor sees WHICH bar was cleared without digging into checks. Null when
|
|
106
|
+
// no admissibility block was supplied.
|
|
107
|
+
admissibility_verdict: adm ? adm.verdict : null,
|
|
108
|
+
admissibility_profile: adm ? adm.admissibility_profile : null,
|
|
109
|
+
admissibility_profile_hash: adm ? adm.profile_hash : null,
|
|
47
110
|
},
|
|
111
|
+
// Full admissibility block (or null). The auditor / gate can re-check
|
|
112
|
+
// {profile_hash, verdict, replay_digest} against the profile the relying party
|
|
113
|
+
// pinned. Carried verbatim, fail-closed by construction (see normalizeAdmissibility).
|
|
114
|
+
admissibility: adm,
|
|
48
115
|
checks: [
|
|
49
116
|
check('receipt_present_and_valid', allowed && !String(decision?.reason || '').startsWith('receipt_rejected'), decision?.reason || null),
|
|
50
117
|
check('assurance_sufficient', allowed || decision?.reason !== 'assurance_too_low', decision?.reason === 'assurance_too_low' ? 'receipt tier below action requirement' : null),
|
|
@@ -52,14 +119,25 @@ export function buildReliancePacket({
|
|
|
52
119
|
check('execution_fields_bound', bindingCheck ? bindingCheck.ok === true : null, bindingCheck ? { missing_observed_fields: bindingCheck.missing_observed_fields || [], mismatched_fields: bindingCheck.mismatched_fields || [] } : 'no material execution-field binding required by this action'),
|
|
53
120
|
check('execution_attests_decision', execution ? executionBound : null, execution ? null : 'no execution record supplied'),
|
|
54
121
|
check('evidence_log_intact', evidenceCheck.ok === undefined ? null : evidenceCheck.ok, evidenceCheck.reason || null),
|
|
122
|
+
// Admissibility verdict against the relying party's PINNED profile. null when
|
|
123
|
+
// no profile/verdict was supplied (this reliance did not gate on admissibility);
|
|
124
|
+
// true only for a recognized 'admissible' verdict; false otherwise (fail closed).
|
|
125
|
+
check(
|
|
126
|
+
'admissibility_verdict_admissible',
|
|
127
|
+
adm === null ? null : adm.admissible === true,
|
|
128
|
+
adm === null
|
|
129
|
+
? 'no admissibility profile / verdict supplied for this reliance'
|
|
130
|
+
: { verdict: adm.verdict, verdict_recognized: adm.verdict_recognized, profile: adm.admissibility_profile, profile_hash: adm.profile_hash, replay_digest: adm.replay_digest },
|
|
131
|
+
),
|
|
55
132
|
],
|
|
56
133
|
manifest_version: manifest?.['@version'] || null,
|
|
57
134
|
limitations: [
|
|
58
135
|
'The packet proves the gate verified a receipt and enforced its configured policy; it does not prove the human made a wise decision.',
|
|
59
136
|
'Identity, authority enrollment, and key custody remain external trust roots that must be operated correctly.',
|
|
60
137
|
'For execution-field binding, observedAction must come from the system of record, not from attacker-controlled request input.',
|
|
138
|
+
'An admissible verdict means the evidence bundle cleared the bar THIS relying party pinned; it does not establish the action is correct, safe, or currently valid beyond the freshness bounds evaluated. The verdict is computed OFFLINE by the relying party against its own pinned profile — EMILIA neither hosts the authoritative registry nor adjudicates.',
|
|
61
139
|
],
|
|
62
140
|
};
|
|
63
141
|
}
|
|
64
142
|
|
|
65
|
-
export default { RELIANCE_PACKET_VERSION, buildReliancePacket };
|
|
143
|
+
export default { RELIANCE_PACKET_VERSION, ADMISSIBILITY_VERDICTS, buildReliancePacket };
|
package/reports/art14.js
ADDED
|
Binary file
|