@intentrax/sdk 1.2.0 → 1.6.0
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 +136 -0
- package/cli/intentrax.mjs +312 -6
- package/index.d.ts +156 -2
- package/index.js +987 -9
- package/index.ts +987 -9
- package/package.json +1 -1
- package/trust/policies/94b421ad2a0eb71e0fc558697ae099967d7ff3d0780ca7c089f0ba53e76894b2.json +57 -0
package/index.ts
CHANGED
|
@@ -4,6 +4,7 @@ export const SDK_VERSION = "1.0.0";
|
|
|
4
4
|
export const API_VERSION = "v1";
|
|
5
5
|
export const VERIFY_REQUEST_HASH_DOMAIN = "INTENTRAX_PUBLIC_SDK_VERIFY_REQUEST_V1";
|
|
6
6
|
export const IDEMPOTENCY_KEY_DOMAIN = "INTENTRAX_PUBLIC_SDK_IDEMPOTENCY_V1";
|
|
7
|
+
export const AGENT_HOOK_IDEMPOTENCY_KEY_DOMAIN = "INTENTRAX_AGENT_HOOK_IDEMPOTENCY_V1";
|
|
7
8
|
export const AGENT_GATEWAY_ADMISSION_REQUEST_HASH_DOMAIN = "INTENTRAX_AGENT_GATEWAY_ADMISSION_REQUEST_V1";
|
|
8
9
|
export const AGENT_ADMISSION_SCHEMA_VERSION = "intentrax.runtime.agent_admission_request/1.0";
|
|
9
10
|
export const AGENT_ADMISSION_ENDPOINT = "/v1/agent/admissions";
|
|
@@ -12,6 +13,12 @@ export const AGENT_ADMISSION_ENDPOINT = "/v1/agent/admissions";
|
|
|
12
13
|
// (HTTP 423 until LiveExecutionEnabled, HTTP 403 until the tenant is
|
|
13
14
|
// allowlisted). See engine/internal/runtime/intentexecute/intentexecute.go.
|
|
14
15
|
export const INTENT_EXECUTE_REQUEST_SCHEMA_VERSION = "intentrax.runtime.intent_execute.request/1.0";
|
|
16
|
+
// /1.1 adds exactly one OPTIONAL field to /1.0: output_binding, the
|
|
17
|
+
// producer-declared `intentrax-content/1.0` hash of the rendered output. The
|
|
18
|
+
// engine seals it into the signed proof (aep.output_binding,
|
|
19
|
+
// binding_source PRODUCER_DECLARED_AT_ISSUANCE); see
|
|
20
|
+
// engine/internal/runtime/intentexecute/output_binding.go.
|
|
21
|
+
export const INTENT_EXECUTE_REQUEST_SCHEMA_VERSION_V11 = "intentrax.runtime.intent_execute.request/1.1";
|
|
15
22
|
export const INTENT_EXECUTE_ENDPOINT = "/v1/intents/execute";
|
|
16
23
|
// Mirrors intentexecute.MaxRequestBytes: the engine rejects a canonical body
|
|
17
24
|
// larger than this with HTTP 400.
|
|
@@ -65,6 +72,10 @@ const INTENT_EXECUTE_REQUIRED_FIELDS = [
|
|
|
65
72
|
"proof_chain_fixture_ref",
|
|
66
73
|
];
|
|
67
74
|
|
|
75
|
+
// The engine decodes a /1.1 output_binding with DisallowUnknownFields into
|
|
76
|
+
// exactly these three string fields (intentexecute.OutputBinding).
|
|
77
|
+
const INTENT_EXECUTE_OUTPUT_BINDING_FIELDS = ["content_hash", "hash_algorithm", "normalization"];
|
|
78
|
+
|
|
68
79
|
const RECEIPT_VERIFICATION_REQUIRED_FIELDS = [
|
|
69
80
|
"schema_version",
|
|
70
81
|
"receipt_id",
|
|
@@ -168,7 +179,36 @@ export function createIdempotencyKey(request) {
|
|
|
168
179
|
// one raw, one hashed — so a durable admission receipt can be correlated against
|
|
169
180
|
// the execution that carried the same key.
|
|
170
181
|
export function admissionIdempotencyKeyHash(request) {
|
|
171
|
-
return
|
|
182
|
+
return executeIdempotencyKeyHash(createIdempotencyKey(request));
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// executeIdempotencyKeyHash is the ONE idempotency-key rule shared by the
|
|
186
|
+
// admission and execute lanes. The engine records SHA-256(raw execute
|
|
187
|
+
// idempotency_key), with no domain prefix, as the execution's link key; an
|
|
188
|
+
// admission receipt correlates with an execution only when its
|
|
189
|
+
// idempotency_key_hash equals that value. So send the raw key K as the execute
|
|
190
|
+
// request's idempotency_key and executeIdempotencyKeyHash(K) as the admission
|
|
191
|
+
// request's idempotency_key_hash. Any other derivation (for example a
|
|
192
|
+
// domain-prefixed hash of a payload hash with no raw key the caller can send to
|
|
193
|
+
// execute) can never match, and every such execution reads as unadmitted.
|
|
194
|
+
export function executeIdempotencyKeyHash(idempotencyKey) {
|
|
195
|
+
if (!isNonEmptyStable(idempotencyKey)) {
|
|
196
|
+
throw new TypeError("executeIdempotencyKeyHash: idempotencyKey must be a non-empty string without leading or trailing whitespace");
|
|
197
|
+
}
|
|
198
|
+
return sha256Hex(idempotencyKey);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// agentHookExecuteIdempotencyKey returns the raw execute idempotency key that
|
|
202
|
+
// hooks generated by `intentrax agent init` derive from an admission
|
|
203
|
+
// request_payload_hash. The hook's admission idempotency_key_hash is
|
|
204
|
+
// executeIdempotencyKeyHash of this key, and the hook result exposes the key as
|
|
205
|
+
// execute_idempotency_key, so the execution that follows the admission carries
|
|
206
|
+
// the matching key.
|
|
207
|
+
export function agentHookExecuteIdempotencyKey(requestPayloadHash) {
|
|
208
|
+
if (!isSha256Hex(requestPayloadHash)) {
|
|
209
|
+
throw new TypeError("agentHookExecuteIdempotencyKey: requestPayloadHash must be 64 lowercase hex");
|
|
210
|
+
}
|
|
211
|
+
return AGENT_HOOK_IDEMPOTENCY_KEY_DOMAIN + requestPayloadHash;
|
|
172
212
|
}
|
|
173
213
|
|
|
174
214
|
export function buildVerificationEnvelope(request) {
|
|
@@ -562,25 +602,31 @@ export function buildAgentGatewayAdmissionEnvelope(request) {
|
|
|
562
602
|
}
|
|
563
603
|
|
|
564
604
|
// validateIntentExecuteRequest mirrors the engine's intentexecute.validateRequest
|
|
565
|
-
// (and its DecodeRequest strictness): exactly the six fields
|
|
566
|
-
// action, and a canonical body
|
|
567
|
-
// NO proof/hash truth —
|
|
568
|
-
// response_hash are the
|
|
605
|
+
// (and its DecodeRequest strictness): exactly the six fields (plus an optional
|
|
606
|
+
// output_binding under /1.1 only), an UPPER_SNAKE action, and a canonical body
|
|
607
|
+
// no larger than the engine's limit. It computes NO proof/hash truth —
|
|
608
|
+
// receipt_id, request_hash, registry_proof_id, and response_hash are the
|
|
609
|
+
// engine's to produce.
|
|
569
610
|
export function validateIntentExecuteRequest(request) {
|
|
570
611
|
if (request === null || typeof request !== "object" || Array.isArray(request)) {
|
|
571
612
|
return ["intent_execute_request"];
|
|
572
613
|
}
|
|
573
614
|
const invalid = [];
|
|
615
|
+
const isV11 = request.schema_version === INTENT_EXECUTE_REQUEST_SCHEMA_VERSION_V11;
|
|
574
616
|
// Unknown fields are a 400 at the engine (DisallowUnknownFields); reject them
|
|
575
|
-
// here too so the SDK never emits a body the engine would refuse.
|
|
617
|
+
// here too so the SDK never emits a body the engine would refuse. A /1.0 body
|
|
618
|
+
// carrying output_binding is such an unknown field.
|
|
576
619
|
for (const key of Object.keys(request)) {
|
|
577
|
-
if (!INTENT_EXECUTE_REQUIRED_FIELDS.includes(key)) {
|
|
620
|
+
if (!INTENT_EXECUTE_REQUIRED_FIELDS.includes(key) && !(isV11 && key === "output_binding")) {
|
|
578
621
|
invalid.push("body");
|
|
579
622
|
}
|
|
580
623
|
}
|
|
581
|
-
if (request.schema_version !== INTENT_EXECUTE_REQUEST_SCHEMA_VERSION) {
|
|
624
|
+
if (request.schema_version !== INTENT_EXECUTE_REQUEST_SCHEMA_VERSION && !isV11) {
|
|
582
625
|
invalid.push("schema_version");
|
|
583
626
|
}
|
|
627
|
+
if (isV11 && Object.prototype.hasOwnProperty.call(request, "output_binding")) {
|
|
628
|
+
invalid.push(...validateIntentExecuteOutputBinding(request.output_binding));
|
|
629
|
+
}
|
|
584
630
|
if (!isNonEmptyStable(request.intent_id)) {
|
|
585
631
|
invalid.push("intent_id");
|
|
586
632
|
}
|
|
@@ -598,7 +644,10 @@ export function validateIntentExecuteRequest(request) {
|
|
|
598
644
|
if (!isNonEmptyStable(request.proof_chain_fixture_ref)) {
|
|
599
645
|
invalid.push("proof_chain_fixture_ref");
|
|
600
646
|
}
|
|
601
|
-
|
|
647
|
+
// Size-check only an otherwise-valid body: an invalid field (e.g. an explicit
|
|
648
|
+
// `undefined`) may not be canonicalizable, and must surface as a structured
|
|
649
|
+
// FAIL naming that field rather than a canonical_json throw.
|
|
650
|
+
if (invalid.length === 0) {
|
|
602
651
|
const canonicalBytes = Buffer.byteLength(canonicalJson(request), "utf8");
|
|
603
652
|
if (canonicalBytes > INTENT_EXECUTE_MAX_REQUEST_BYTES) {
|
|
604
653
|
invalid.push("body");
|
|
@@ -607,6 +656,58 @@ export function validateIntentExecuteRequest(request) {
|
|
|
607
656
|
return [...new Set(invalid)].sort();
|
|
608
657
|
}
|
|
609
658
|
|
|
659
|
+
// validateIntentExecuteOutputBinding mirrors the engine's decodeOutputBinding +
|
|
660
|
+
// validateOutputBinding: a non-null object of exactly the three string fields
|
|
661
|
+
// (anything else is a decode error, reported as "output_binding"), then a
|
|
662
|
+
// sealable content_hash, the SHA-256 algorithm and the intentrax-content/1.0
|
|
663
|
+
// normalization.
|
|
664
|
+
function validateIntentExecuteOutputBinding(binding) {
|
|
665
|
+
if (binding === null || typeof binding !== "object" || Array.isArray(binding)) {
|
|
666
|
+
return ["output_binding"];
|
|
667
|
+
}
|
|
668
|
+
for (const key of Object.keys(binding)) {
|
|
669
|
+
if (!INTENT_EXECUTE_OUTPUT_BINDING_FIELDS.includes(key) || typeof binding[key] !== "string") {
|
|
670
|
+
return ["output_binding"];
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
const invalid = [];
|
|
674
|
+
if (!isSealableOutputContentHash(binding.content_hash)) {
|
|
675
|
+
invalid.push("output_binding.content_hash");
|
|
676
|
+
}
|
|
677
|
+
if (binding.hash_algorithm !== CANONICAL_OUTPUT_HASH_ALGORITHM) {
|
|
678
|
+
invalid.push("output_binding.hash_algorithm");
|
|
679
|
+
}
|
|
680
|
+
if (binding.normalization !== CANONICAL_OUTPUT_NORMALIZATION) {
|
|
681
|
+
invalid.push("output_binding.normalization");
|
|
682
|
+
}
|
|
683
|
+
return invalid;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// isSealableOutputContentHash mirrors the engine's sealedContentHash: the bare
|
|
687
|
+
// 64 lowercase hex the SDK emits, or the same with a "sha256:" prefix. Uppercase,
|
|
688
|
+
// other prefixes, other lengths, and a degenerate digest (one repeated digit)
|
|
689
|
+
// are refused.
|
|
690
|
+
function isSealableOutputContentHash(value) {
|
|
691
|
+
if (typeof value !== "string") return false;
|
|
692
|
+
const digest = value.startsWith("sha256:") ? value.slice("sha256:".length) : value;
|
|
693
|
+
if (!SHA256_RE.test(digest)) return false;
|
|
694
|
+
return digest.split("").some((char) => char !== digest[0]);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// bindIntentExecuteOutput returns a NEW /1.1 execute request: the caller's
|
|
698
|
+
// request with schema_version /1.1 and output_binding = buildOutputBinding of
|
|
699
|
+
// the output the producer is about to render. The input is not mutated. Pass
|
|
700
|
+
// the result to buildIntentExecuteEnvelope / executeIntentHttp, which validate
|
|
701
|
+
// it. Bind exactly what the page will show inside its data-intentrax-output
|
|
702
|
+
// region(s): the browser extension recomputes this hash over that visible text.
|
|
703
|
+
export function bindIntentExecuteOutput(request, renderedOutput) {
|
|
704
|
+
return {
|
|
705
|
+
...request,
|
|
706
|
+
schema_version: INTENT_EXECUTE_REQUEST_SCHEMA_VERSION_V11,
|
|
707
|
+
output_binding: buildOutputBinding(renderedOutput),
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
|
|
610
711
|
// buildIntentExecuteEnvelope is a THIN envelope builder: it validates and
|
|
611
712
|
// passes the caller-supplied body through verbatim. It performs no hashing and
|
|
612
713
|
// asserts no proof truth.
|
|
@@ -928,3 +1029,880 @@ export function verificationPointerMetaTag({ proof_id: proofId, verify_url: veri
|
|
|
928
1029
|
if (href.includes(";")) return null;
|
|
929
1030
|
return `<meta name="${VERIFICATION_POINTER_META_NAME}" content="${escapeVerificationPointerAttribute(`proof_id=${proofId};verify_url=${href}`)}">`;
|
|
930
1031
|
}
|
|
1032
|
+
|
|
1033
|
+
// Evidence-quality model (INTENTRAX_ASSURANCE_GAP_ANALYSIS.md §5,
|
|
1034
|
+
// implementation plan P0-6 / P1-D).
|
|
1035
|
+
//
|
|
1036
|
+
// A verification result is a set of per-dimension assessments. The overall
|
|
1037
|
+
// verdict is COMPUTED from them by the fixed rule in deriveAssuranceVerdict();
|
|
1038
|
+
// no signer asserts it. The rule, dimensions, results, profiles and verdict
|
|
1039
|
+
// precedence are ported unchanged from examples/effect-assurance-demo
|
|
1040
|
+
// (src/model.mjs), plus the LEGACY_DECISION_RECORD profile that every proof
|
|
1041
|
+
// issued today maps to. The Go offline verifier carries the same model
|
|
1042
|
+
// (engine/internal/verificationinfra/offlineproof/assessment.go); the two must
|
|
1043
|
+
// stay in step.
|
|
1044
|
+
export const VERIFICATION_ASSESSMENT_SCHEMA_VERSION = "intentrax.verification.assessment/0.1";
|
|
1045
|
+
|
|
1046
|
+
export const ASSURANCE_DIMENSIONS = Object.freeze([
|
|
1047
|
+
"RECORD_INTEGRITY",
|
|
1048
|
+
"SIGNER_AUTHENTICITY",
|
|
1049
|
+
"AUTHORIZATION",
|
|
1050
|
+
"EXECUTION_REPORTED",
|
|
1051
|
+
"EXECUTION_ATTESTED",
|
|
1052
|
+
"EFFECT_OBSERVED",
|
|
1053
|
+
"EFFECT_CONFIRMED",
|
|
1054
|
+
"CAUSAL_CHAIN",
|
|
1055
|
+
]);
|
|
1056
|
+
|
|
1057
|
+
// §5.2, plus OBSERVED for the EFFECT_OBSERVED dimension.
|
|
1058
|
+
export const ASSESSMENT_RESULTS = Object.freeze([
|
|
1059
|
+
"VERIFIED",
|
|
1060
|
+
"REPORTED",
|
|
1061
|
+
"ATTESTED",
|
|
1062
|
+
"OBSERVED",
|
|
1063
|
+
"CONFIRMED",
|
|
1064
|
+
"CONTRADICTED",
|
|
1065
|
+
"PENDING",
|
|
1066
|
+
"INSUFFICIENT_EVIDENCE",
|
|
1067
|
+
"NOT_ASSESSED",
|
|
1068
|
+
"NOT_APPLICABLE",
|
|
1069
|
+
"FAILED",
|
|
1070
|
+
]);
|
|
1071
|
+
|
|
1072
|
+
export const ASSESSMENT_PROVENANCE = Object.freeze({
|
|
1073
|
+
SELF_REPORTED: "SELF_REPORTED",
|
|
1074
|
+
INTENTRAX_DECISION: "INTENTRAX_DECISION",
|
|
1075
|
+
ENFORCEMENT_ATTESTED: "ENFORCEMENT_ATTESTED",
|
|
1076
|
+
AUTHORITATIVE_SOURCE: "AUTHORITATIVE_SOURCE",
|
|
1077
|
+
THIRD_PARTY_ATTESTED: "THIRD_PARTY_ATTESTED",
|
|
1078
|
+
VERIFIER_COMPUTED: "VERIFIER_COMPUTED",
|
|
1079
|
+
});
|
|
1080
|
+
|
|
1081
|
+
// Required dimensions per assurance profile. EXECUTION_REPORTED is
|
|
1082
|
+
// deliberately never required: a self-report can never satisfy a profile
|
|
1083
|
+
// (invariant 1).
|
|
1084
|
+
export const ASSURANCE_PROFILES = Object.freeze({
|
|
1085
|
+
LEGACY_DECISION_RECORD: Object.freeze(["RECORD_INTEGRITY"]),
|
|
1086
|
+
DECISION_RECORD: Object.freeze(["RECORD_INTEGRITY", "SIGNER_AUTHENTICITY", "AUTHORIZATION"]),
|
|
1087
|
+
AUTHORIZED_AND_ATTESTED: Object.freeze(["RECORD_INTEGRITY", "SIGNER_AUTHENTICITY", "AUTHORIZATION", "EXECUTION_ATTESTED"]),
|
|
1088
|
+
EFFECT_CONFIRMED: Object.freeze(["RECORD_INTEGRITY", "SIGNER_AUTHENTICITY", "AUTHORIZATION", "EFFECT_OBSERVED", "EFFECT_CONFIRMED"]),
|
|
1089
|
+
CAUSAL_CHAIN: Object.freeze([
|
|
1090
|
+
"RECORD_INTEGRITY", "SIGNER_AUTHENTICITY", "AUTHORIZATION", "EFFECT_OBSERVED", "EFFECT_CONFIRMED", "CAUSAL_CHAIN",
|
|
1091
|
+
]),
|
|
1092
|
+
});
|
|
1093
|
+
|
|
1094
|
+
export const ASSURANCE_VERDICTS = Object.freeze({
|
|
1095
|
+
VERIFICATION_FAILED: "VERIFICATION_FAILED",
|
|
1096
|
+
INTEGRITY_ONLY: "INTEGRITY_ONLY",
|
|
1097
|
+
CONFLICTING_EVIDENCE: "CONFLICTING_EVIDENCE",
|
|
1098
|
+
PENDING_FINALITY: "PENDING_FINALITY",
|
|
1099
|
+
INSUFFICIENT_EVIDENCE: "INSUFFICIENT_EVIDENCE",
|
|
1100
|
+
VERIFIED_FOR_SCOPE: "VERIFIED_FOR_SCOPE",
|
|
1101
|
+
});
|
|
1102
|
+
|
|
1103
|
+
// Rule precedence, first-matching rule = 0. Weakening any dimension must
|
|
1104
|
+
// never move the verdict to a later rule.
|
|
1105
|
+
export const ASSURANCE_VERDICT_PRECEDENCE = Object.freeze({
|
|
1106
|
+
VERIFICATION_FAILED: 0,
|
|
1107
|
+
INTEGRITY_ONLY: 1,
|
|
1108
|
+
CONFLICTING_EVIDENCE: 2,
|
|
1109
|
+
PENDING_FINALITY: 3,
|
|
1110
|
+
INSUFFICIENT_EVIDENCE: 4,
|
|
1111
|
+
VERIFIED_FOR_SCOPE: 5,
|
|
1112
|
+
});
|
|
1113
|
+
|
|
1114
|
+
const WEAK_ASSESSMENT_RESULTS = new Set(["REPORTED", "INSUFFICIENT_EVIDENCE", "NOT_ASSESSED"]);
|
|
1115
|
+
const SATISFYING_ASSESSMENT_RESULTS = new Set(["VERIFIED", "ATTESTED", "OBSERVED", "CONFIRMED"]);
|
|
1116
|
+
|
|
1117
|
+
// §5.4, verbatim order. `assessments` is { [dimension]: result }. A required
|
|
1118
|
+
// dimension that is missing or NOT_APPLICABLE counts as INSUFFICIENT_EVIDENCE
|
|
1119
|
+
// (invariant 4: never a bare pass).
|
|
1120
|
+
export function deriveAssuranceVerdict(assessments, profile) {
|
|
1121
|
+
const required = Object.hasOwn(ASSURANCE_PROFILES, profile) ? ASSURANCE_PROFILES[profile] : undefined;
|
|
1122
|
+
if (!required) {
|
|
1123
|
+
throw new Error("unknown assurance profile " + profile);
|
|
1124
|
+
}
|
|
1125
|
+
const all = Object.values(assessments);
|
|
1126
|
+
const req = required.map((d) => assessments[d] ?? "INSUFFICIENT_EVIDENCE");
|
|
1127
|
+
if (all.includes("FAILED")) return ASSURANCE_VERDICTS.VERIFICATION_FAILED;
|
|
1128
|
+
if (assessments.SIGNER_AUTHENTICITY !== "VERIFIED") return ASSURANCE_VERDICTS.INTEGRITY_ONLY;
|
|
1129
|
+
if (req.includes("CONTRADICTED")) return ASSURANCE_VERDICTS.CONFLICTING_EVIDENCE;
|
|
1130
|
+
if (req.includes("PENDING")) return ASSURANCE_VERDICTS.PENDING_FINALITY;
|
|
1131
|
+
if (req.some((r) => WEAK_ASSESSMENT_RESULTS.has(r) || !SATISFYING_ASSESSMENT_RESULTS.has(r))) return ASSURANCE_VERDICTS.INSUFFICIENT_EVIDENCE;
|
|
1132
|
+
return ASSURANCE_VERDICTS.VERIFIED_FOR_SCOPE;
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
// Published wording of each limitation code; identical to the Go verifier.
|
|
1136
|
+
export const ASSURANCE_LIMITATION_TEXT = Object.freeze({
|
|
1137
|
+
EXECUTION_NOT_ATTESTED: "No trusted in-path enforcement component observed the action. The proof records an Intentrax decision, not an attested execution.",
|
|
1138
|
+
EFFECT_NOT_VERIFIED: "No authoritative downstream system was queried. The proof does not show that any external effect happened.",
|
|
1139
|
+
POLICY_BINDING_SYNTHETIC: "The policy reference in this proof is a fixed value of the proof pipeline, not a binding to an evaluated customer policy or mandate.",
|
|
1140
|
+
COMPLETENESS_NOT_ESTABLISHED: "Nothing proves that every consequential agent action was routed through Intentrax. A proof covers only the action it records.",
|
|
1141
|
+
SIGNER_AUTHENTICITY_REQUIRES_PINNED_ANCHORS: "Signatures were checked against public keys carried inside the proof. Who signed is established only when every signing key is pinned to a trust-bearing key in a published Intentrax key set.",
|
|
1142
|
+
// Used instead of POLICY_BINDING_SYNTHETIC when the signed AEP seals a
|
|
1143
|
+
// policy binding (AEP 1.1 policy-binding profile, RECORD_ONLY).
|
|
1144
|
+
POLICY_EVALUATION_NOT_RECHECKABLE: "The proof seals Intentrax's evaluation of a hash-pinned policy, but this verifier did not re-run it: the evaluated event cannot be rebuilt from this proof, or the policy document was not available. The recorded decision is Intentrax's statement, not an independently checked result.",
|
|
1145
|
+
POLICY_DECISION_NOT_ENFORCED: "The policy binding is RECORD_ONLY: the evaluation was recorded with the action, and nothing shows the action was gated on its result.",
|
|
1146
|
+
POLICY_CONSTRAINT_NOT_EVALUATED: "At least one constraint of the matched policy rule was not checked. This proof binds no evidence that it was met.",
|
|
1147
|
+
// Used instead of POLICY_EVALUATION_NOT_RECHECKABLE when the verifier
|
|
1148
|
+
// re-ran the sealed evaluation and it matched.
|
|
1149
|
+
POLICY_EVENT_SELF_REPORTED: "The verifier re-ran the published policy over the facts sealed in this proof and got the same evaluation: the decision follows from those facts and the published rule. The re-check does not independently witness that the facts (such as mutation_performed) are true; the runtime's signature attests to them.",
|
|
1150
|
+
});
|
|
1151
|
+
|
|
1152
|
+
// Limitations every proof under LEGACY_DECISION_RECORD carries.
|
|
1153
|
+
export const LEGACY_DECISION_RECORD_LIMITATIONS = Object.freeze([
|
|
1154
|
+
"EXECUTION_NOT_ATTESTED",
|
|
1155
|
+
"EFFECT_NOT_VERIFIED",
|
|
1156
|
+
"POLICY_BINDING_SYNTHETIC",
|
|
1157
|
+
"COMPLETENESS_NOT_ESTABLISHED",
|
|
1158
|
+
]);
|
|
1159
|
+
|
|
1160
|
+
// Maps a verifier's signer-trust outcome to the SIGNER_AUTHENTICITY result.
|
|
1161
|
+
// Only TRUSTED against a supplied key set is VERIFIED. Without any key set the
|
|
1162
|
+
// dimension is NOT_ASSESSED; a REVOKED signer is FAILED; every other outcome
|
|
1163
|
+
// is INSUFFICIENT_EVIDENCE. Accepts the CLI's labels (UNPINNED_SIGNER,
|
|
1164
|
+
// MIXED_TRUST) and the Go verifier's (UNPINNED).
|
|
1165
|
+
export function signerAuthenticityAssessment(signerTrust, keySetSupplied) {
|
|
1166
|
+
if (!keySetSupplied) return { result: "NOT_ASSESSED", reasons: ["NO_TRUSTED_KEY_SET"] };
|
|
1167
|
+
switch (signerTrust) {
|
|
1168
|
+
case "TRUSTED":
|
|
1169
|
+
return { result: "VERIFIED", reasons: [] };
|
|
1170
|
+
case "REVOKED_SIGNER":
|
|
1171
|
+
return { result: "FAILED", reasons: ["REVOKED_SIGNER"] };
|
|
1172
|
+
case "SANDBOX_NON_TRUST_BEARING":
|
|
1173
|
+
case "INSUFFICIENT_TRUSTED_SIGNERS":
|
|
1174
|
+
case "MIXED_TRUST":
|
|
1175
|
+
return { result: "INSUFFICIENT_EVIDENCE", reasons: [signerTrust] };
|
|
1176
|
+
default:
|
|
1177
|
+
return { result: "INSUFFICIENT_EVIDENCE", reasons: ["UNPINNED_SIGNER"] };
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
// Maps the policy binding sealed in the signed AEP (null when there is none)
|
|
1182
|
+
// and the outcome of re-running it (null when no re-run was attempted) to the
|
|
1183
|
+
// AUTHORIZATION result, provenance, reasons and limitations. Same rule as the
|
|
1184
|
+
// Go verifier. Without a binding nothing is assessed. Only a re-run that
|
|
1185
|
+
// MATCHed lifts the dimension above REPORTED: a re-checked COMPLIANT decision
|
|
1186
|
+
// with no unchecked constraint is VERIFIED (VERIFIER_COMPUTED); with an
|
|
1187
|
+
// unchecked constraint it stays REPORTED. Without a matching re-run COMPLIANT
|
|
1188
|
+
// is REPORTED (INTENTRAX_DECISION). NON_COMPLIANT is CONTRADICTED and ERROR is
|
|
1189
|
+
// INSUFFICIENT_EVIDENCE either way.
|
|
1190
|
+
export function authorizationAssessment(policyBinding, policyReevaluation = null) {
|
|
1191
|
+
if (policyBinding === null || policyBinding === undefined) {
|
|
1192
|
+
return { result: "NOT_ASSESSED", provenance: "INTENTRAX_DECISION", reasons: ["DECISION_NOT_REEVALUATED_OFFLINE"], limitations: ["POLICY_BINDING_SYNTHETIC"] };
|
|
1193
|
+
}
|
|
1194
|
+
const rechecked = policyReevaluation !== null && policyReevaluation !== undefined && policyReevaluation.status === "MATCH";
|
|
1195
|
+
const unchecked = (Array.isArray(policyBinding.constraints) ? policyBinding.constraints : []).filter((constraint) => constraint.status !== "SATISFIED");
|
|
1196
|
+
let result = "INSUFFICIENT_EVIDENCE";
|
|
1197
|
+
const reasons = [];
|
|
1198
|
+
if (policyBinding.decision === "COMPLIANT") {
|
|
1199
|
+
result = rechecked && unchecked.length === 0 ? "VERIFIED" : "REPORTED";
|
|
1200
|
+
reasons.push("POLICY_DECISION_COMPLIANT");
|
|
1201
|
+
} else if (policyBinding.decision === "NON_COMPLIANT") {
|
|
1202
|
+
result = "CONTRADICTED";
|
|
1203
|
+
reasons.push("POLICY_DECISION_NON_COMPLIANT");
|
|
1204
|
+
} else {
|
|
1205
|
+
reasons.push("POLICY_DECISION_ERROR");
|
|
1206
|
+
}
|
|
1207
|
+
let limitations;
|
|
1208
|
+
if (rechecked) {
|
|
1209
|
+
reasons.push("POLICY_EVALUATION_RECHECKED");
|
|
1210
|
+
limitations = ["POLICY_EVENT_SELF_REPORTED", "POLICY_DECISION_NOT_ENFORCED"];
|
|
1211
|
+
} else {
|
|
1212
|
+
reasons.push("POLICY_EVALUATION_NOT_RECHECKED_OFFLINE");
|
|
1213
|
+
const reason = policyReevaluation === null || policyReevaluation === undefined ? "" : policyReevaluation.reason;
|
|
1214
|
+
if (typeof reason === "string" && reason !== "") reasons.push(`POLICY_REEVALUATION_${reason}`);
|
|
1215
|
+
limitations = ["POLICY_EVALUATION_NOT_RECHECKABLE", "POLICY_DECISION_NOT_ENFORCED"];
|
|
1216
|
+
}
|
|
1217
|
+
for (const constraint of unchecked) reasons.push(`POLICY_CONSTRAINT_NOT_EVALUATED:${constraint.constraint_id}`);
|
|
1218
|
+
if (unchecked.length > 0) limitations.push("POLICY_CONSTRAINT_NOT_EVALUATED");
|
|
1219
|
+
return { result, provenance: rechecked ? "VERIFIER_COMPUTED" : "INTENTRAX_DECISION", reasons, limitations };
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
// Builds the verification_assessment block for a proof whose record
|
|
1223
|
+
// integrity has been verified, under the LEGACY_DECISION_RECORD profile.
|
|
1224
|
+
// policyBinding is the binding sealed in the signed AEP, or null;
|
|
1225
|
+
// policyReevaluation is the outcome of re-running it, or null. Nothing beyond
|
|
1226
|
+
// the record, its signers and the (re-checked or recorded) policy decision is
|
|
1227
|
+
// claimed.
|
|
1228
|
+
export function buildLegacyVerificationAssessment({ signerTrust, keySetSupplied, policyBinding = null, policyReevaluation = null } = {}) {
|
|
1229
|
+
const signer = signerAuthenticityAssessment(signerTrust, keySetSupplied === true);
|
|
1230
|
+
const authorization = authorizationAssessment(policyBinding, policyReevaluation);
|
|
1231
|
+
const signerVerified = signer.result === "VERIFIED";
|
|
1232
|
+
const row = (dimension, result, provenance, reasons, limitations) => ({ dimension, result, provenance, reasons, limitations });
|
|
1233
|
+
const assessments = [
|
|
1234
|
+
row("RECORD_INTEGRITY", "VERIFIED", "VERIFIER_COMPUTED", [], []),
|
|
1235
|
+
row("SIGNER_AUTHENTICITY", signer.result, "VERIFIER_COMPUTED", signer.reasons, signerVerified ? [] : ["SIGNER_AUTHENTICITY_REQUIRES_PINNED_ANCHORS"]),
|
|
1236
|
+
row("AUTHORIZATION", authorization.result, authorization.provenance, authorization.reasons, authorization.limitations),
|
|
1237
|
+
row("EXECUTION_REPORTED", "NOT_ASSESSED", null, ["NO_EXECUTION_REPORT_IN_PROOF"], []),
|
|
1238
|
+
row("EXECUTION_ATTESTED", "NOT_ASSESSED", null, ["NO_IN_PATH_ENFORCEMENT_ATTESTATION"], ["EXECUTION_NOT_ATTESTED"]),
|
|
1239
|
+
row("EFFECT_OBSERVED", "NOT_ASSESSED", null, ["NO_EFFECT_EVIDENCE"], ["EFFECT_NOT_VERIFIED"]),
|
|
1240
|
+
row("EFFECT_CONFIRMED", "NOT_ASSESSED", null, ["NO_EFFECT_EVIDENCE"], ["EFFECT_NOT_VERIFIED"]),
|
|
1241
|
+
row("CAUSAL_CHAIN", "NOT_ASSESSED", null, ["NO_DELEGATION_CHAIN_IN_PROOF"], []),
|
|
1242
|
+
];
|
|
1243
|
+
const verdict = deriveAssuranceVerdict(Object.fromEntries(assessments.map((a) => [a.dimension, a.result])), "LEGACY_DECISION_RECORD");
|
|
1244
|
+
// The fixed legacy set, with POLICY_BINDING_SYNTHETIC replaced by the
|
|
1245
|
+
// AUTHORIZATION limitations when the proof seals a policy binding.
|
|
1246
|
+
const codes = [
|
|
1247
|
+
...LEGACY_DECISION_RECORD_LIMITATIONS.flatMap((code) => (code === "POLICY_BINDING_SYNTHETIC" ? authorization.limitations : [code])),
|
|
1248
|
+
...(signerVerified ? [] : ["SIGNER_AUTHENTICITY_REQUIRES_PINNED_ANCHORS"]),
|
|
1249
|
+
];
|
|
1250
|
+
return {
|
|
1251
|
+
schema_version: VERIFICATION_ASSESSMENT_SCHEMA_VERSION,
|
|
1252
|
+
assurance_profile: "LEGACY_DECISION_RECORD",
|
|
1253
|
+
required_dimensions: [...ASSURANCE_PROFILES.LEGACY_DECISION_RECORD],
|
|
1254
|
+
verdict,
|
|
1255
|
+
assessments,
|
|
1256
|
+
limitations: codes.map((code) => ({ code, text: ASSURANCE_LIMITATION_TEXT[code] })),
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
// ---------------------------------------------------------------------------
|
|
1261
|
+
// Policy re-evaluation (AEP 1.1 policy-binding profile, P1-C step 2).
|
|
1262
|
+
//
|
|
1263
|
+
// A port of the Go policy engine pipeline (engine/internal/policyengine:
|
|
1264
|
+
// C2.1 DSL -> C2.2 parser -> C2.3 bytecode compiler -> C2.4 VM) that
|
|
1265
|
+
// recomputes every value an aep.policy_binding seals: source_policy_hash,
|
|
1266
|
+
// compiled_policy_hash, execution_event_hash, evaluation_hash, decision,
|
|
1267
|
+
// rule_id and the matched rule's constraints. A verifier fetches the policy by
|
|
1268
|
+
// hash (GET /v1/policies/{source_policy_hash}), rebuilds the evaluated event,
|
|
1269
|
+
// re-runs it here, and requires identical values instead of trusting them.
|
|
1270
|
+
//
|
|
1271
|
+
// It must reproduce the Go engine byte for byte: the shared vectors in
|
|
1272
|
+
// test-fixtures/policy-binding/policy-reevaluation-vectors.json are
|
|
1273
|
+
// generated by the Go engine and checked by policy-reevaluation.test.mjs. Any
|
|
1274
|
+
// divergence fails closed (a hash mismatch), never open.
|
|
1275
|
+
// ---------------------------------------------------------------------------
|
|
1276
|
+
|
|
1277
|
+
export const POLICY_HASH_DOMAIN = "INTENTRAX_POLICY_V1";
|
|
1278
|
+
export const POLICY_BYTECODE_HASH_DOMAIN = "INTENTRAX_BYTECODE_V1";
|
|
1279
|
+
export const POLICY_VM_TRACE_HASH_DOMAIN = "INTENTRAX_TRACE_V1";
|
|
1280
|
+
export const POLICY_VM_EVENT_HASH_DOMAIN = "INTENTRAX_POLICY_VM_EVENT_V1";
|
|
1281
|
+
export const POLICY_VM_EVALUATION_HASH_DOMAIN = "INTENTRAX_POLICY_VM_EVALUATION_V1";
|
|
1282
|
+
|
|
1283
|
+
const POLICY_BYTECODE_SCHEMA_VERSION = "1.0";
|
|
1284
|
+
const POLICY_BYTECODE_VERSION = "1.0";
|
|
1285
|
+
const POLICY_COMPILER_VERSION = "C2.3-1.0.0";
|
|
1286
|
+
const POLICY_VM_RUNTIME_VERSION = "PVM-1";
|
|
1287
|
+
const POLICY_MAX_RULES = 100;
|
|
1288
|
+
const POLICY_MAX_CONDITIONS_PER_RULE = 20;
|
|
1289
|
+
const POLICY_MAX_INSTRUCTIONS = 10000;
|
|
1290
|
+
const POLICY_MAX_CONSTANTS = 1000;
|
|
1291
|
+
const POLICY_MAX_STACK_DEPTH = 256;
|
|
1292
|
+
const POLICY_VM_MAX_EXECUTION_COST = 10000;
|
|
1293
|
+
const POLICY_VM_TASK_IDS = Object.freeze([
|
|
1294
|
+
"C2.4-S1-T1", "C2.4-S1-T2", "C2.4-S1-T3",
|
|
1295
|
+
"C2.4-S2-T1", "C2.4-S2-T2", "C2.4-S2-T3",
|
|
1296
|
+
"C2.4-S3-T1", "C2.4-S3-T2", "C2.4-S3-T3",
|
|
1297
|
+
]);
|
|
1298
|
+
|
|
1299
|
+
const POLICY_IDENTIFIER_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{2,127}$/;
|
|
1300
|
+
const POLICY_VERSION_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;
|
|
1301
|
+
const POLICY_FIELDS = new Set(["policy_id", "policy_version", "rules", "default_effect"]);
|
|
1302
|
+
const POLICY_RULE_FIELDS = new Set(["rule_id", "effect", "conditions", "constraints", "priority"]);
|
|
1303
|
+
const POLICY_CONDITION_FIELDS = new Set(["field", "operator", "value"]);
|
|
1304
|
+
const POLICY_CONSTRAINT_FIELDS = new Set(["constraint_id", "type", "value"]);
|
|
1305
|
+
const POLICY_EFFECTS = new Set(["ALLOW", "DENY", "CONDITIONAL"]);
|
|
1306
|
+
const POLICY_CONDITION_OPERATORS = new Set(["EQUALS", "NOT_EQUALS", "IN", "NOT_IN", "EXISTS", "GREATER_THAN", "GREATER_THAN_OR_EQUAL", "LESS_THAN", "LESS_THAN_OR_EQUAL"]);
|
|
1307
|
+
const POLICY_CONSTRAINT_TYPES = new Set(["MAX_AMOUNT", "MAX_RETRIES", "TIMEOUT_MS", "REQUIRE_APPROVAL", "REQUIRE_GUARDRAIL_PASS", "RESTRICT_TARGET"]);
|
|
1308
|
+
const POLICY_FORBIDDEN_TOKENS = Object.freeze(["clock", "command", "dynamic", "eval", "external", "function", "http://", "https://", "latest", "now", "random", "script", "webhook"]);
|
|
1309
|
+
const POLICY_COMPARISON_OPCODES = Object.freeze({
|
|
1310
|
+
EQUALS: "CMP_EQ",
|
|
1311
|
+
NOT_EQUALS: "CMP_NEQ",
|
|
1312
|
+
GREATER_THAN: "CMP_GT",
|
|
1313
|
+
GREATER_THAN_OR_EQUAL: "CMP_GTE",
|
|
1314
|
+
LESS_THAN: "CMP_LT",
|
|
1315
|
+
LESS_THAN_OR_EQUAL: "CMP_LTE",
|
|
1316
|
+
});
|
|
1317
|
+
const POLICY_OPCODE_VALUES = Object.freeze({
|
|
1318
|
+
LOAD_FIELD: 0x01, LOAD_CONST: 0x02, CMP_EQ: 0x03, CMP_NEQ: 0x04, CMP_GT: 0x05, CMP_GTE: 0x06,
|
|
1319
|
+
CMP_LT: 0x07, CMP_LTE: 0x08, AND: 0x09, OR: 0x0a, NOT: 0x0b, JUMP: 0x0c, JUMP_IF_FALSE: 0x0d,
|
|
1320
|
+
RULE_ALLOW: 0x0e, RULE_DENY: 0x0f, RULE_END: 0x10,
|
|
1321
|
+
});
|
|
1322
|
+
|
|
1323
|
+
class PolicyReevaluationError extends Error {
|
|
1324
|
+
constructor(code, message) {
|
|
1325
|
+
super(message);
|
|
1326
|
+
this.name = "PolicyReevaluationError";
|
|
1327
|
+
this.code = code;
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
// Members of an ordered object are emitted in declaration order (Go
|
|
1332
|
+
// canonicaljson.OrderedObject); plain objects are emitted with keys sorted
|
|
1333
|
+
// bytewise (Go maps).
|
|
1334
|
+
const ORDERED_MEMBERS = Symbol("intentrax.policy.ordered");
|
|
1335
|
+
|
|
1336
|
+
function orderedObject(...members) {
|
|
1337
|
+
return { [ORDERED_MEMBERS]: members };
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
function utf8Compare(left, right) {
|
|
1341
|
+
return Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8"));
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
// Go encoding/json string encoding: HTML-safe escapes and U+2028/U+2029.
|
|
1345
|
+
function goJSONString(value) {
|
|
1346
|
+
if (/[\ud800-\udfff]/.test(value.replace(/[\ud800-\udbff][\udc00-\udfff]/g, ""))) {
|
|
1347
|
+
throw new PolicyReevaluationError("POLICY_ENCODING_UNSUPPORTED", "lone surrogate in a policy string");
|
|
1348
|
+
}
|
|
1349
|
+
return JSON.stringify(value)
|
|
1350
|
+
.replace(/</g, "\\u003c")
|
|
1351
|
+
.replace(/>/g, "\\u003e")
|
|
1352
|
+
.replace(/&/g, "\\u0026")
|
|
1353
|
+
.replace(new RegExp(String.fromCharCode(0x2028), "g"), "\\u2028")
|
|
1354
|
+
.replace(new RegExp(String.fromCharCode(0x2029), "g"), "\\u2029");
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
function policyCanonical(value) {
|
|
1358
|
+
if (value === null) return "null";
|
|
1359
|
+
if (typeof value === "string") return goJSONString(value);
|
|
1360
|
+
if (typeof value === "boolean") return value ? "true" : "false";
|
|
1361
|
+
if (typeof value === "number") {
|
|
1362
|
+
if (!Number.isSafeInteger(value)) throw new PolicyReevaluationError("POLICY_ENCODING_UNSUPPORTED", "only safe integers are supported");
|
|
1363
|
+
return String(value);
|
|
1364
|
+
}
|
|
1365
|
+
if (Array.isArray(value)) return "[" + value.map(policyCanonical).join(",") + "]";
|
|
1366
|
+
if (typeof value === "object") {
|
|
1367
|
+
const members = value[ORDERED_MEMBERS];
|
|
1368
|
+
if (members !== undefined) {
|
|
1369
|
+
return "{" + members.map(([key, member]) => goJSONString(key) + ":" + policyCanonical(member)).join(",") + "}";
|
|
1370
|
+
}
|
|
1371
|
+
const keys = Object.keys(value).sort(utf8Compare);
|
|
1372
|
+
return "{" + keys.map((key) => goJSONString(key) + ":" + policyCanonical(value[key])).join(",") + "}";
|
|
1373
|
+
}
|
|
1374
|
+
throw new PolicyReevaluationError("POLICY_ENCODING_UNSUPPORTED", "unsupported value");
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
function isPlainPolicyObject(value) {
|
|
1378
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
function policyNonEmpty(value) {
|
|
1382
|
+
return typeof value === "string" && value !== "" && value.trim() === value;
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
function hasForbiddenPolicyToken(value) {
|
|
1386
|
+
const lower = value.toLowerCase();
|
|
1387
|
+
return POLICY_FORBIDDEN_TOKENS.some((token) => lower.includes(token));
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
function policyLiteral(value) {
|
|
1391
|
+
if (typeof value === "string") return policyNonEmpty(value) && !hasForbiddenPolicyToken(value) ? { ok: true, value } : { ok: false };
|
|
1392
|
+
if (typeof value === "boolean") return { ok: true, value };
|
|
1393
|
+
if (typeof value === "number") return Number.isSafeInteger(value) ? { ok: true, value } : { ok: false };
|
|
1394
|
+
if (Array.isArray(value)) {
|
|
1395
|
+
if (value.length === 0) return { ok: false };
|
|
1396
|
+
const out = [];
|
|
1397
|
+
for (const item of value) {
|
|
1398
|
+
const literal = policyLiteral(item);
|
|
1399
|
+
if (!literal.ok) return { ok: false };
|
|
1400
|
+
out.push(literal.value);
|
|
1401
|
+
}
|
|
1402
|
+
return { ok: true, value: out };
|
|
1403
|
+
}
|
|
1404
|
+
return { ok: false };
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
function onlyKnownFields(object, allowed) {
|
|
1408
|
+
return Object.keys(object).every((key) => allowed.has(key));
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
function invalidPolicy(message) {
|
|
1412
|
+
return new PolicyReevaluationError("POLICY_DOCUMENT_INVALID", message);
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
// C2.1: validate the policy document and return the normalized definition.
|
|
1416
|
+
function validatePolicyDefinition(policy, allowedEventFields) {
|
|
1417
|
+
if (!isPlainPolicyObject(policy)) throw invalidPolicy("policy must be a JSON object");
|
|
1418
|
+
if (!onlyKnownFields(policy, POLICY_FIELDS)) throw invalidPolicy("policy contains unknown top-level fields");
|
|
1419
|
+
if (typeof policy.policy_id !== "string" || !POLICY_IDENTIFIER_RE.test(policy.policy_id)) throw invalidPolicy("policy_id invalid");
|
|
1420
|
+
if (typeof policy.policy_version !== "string" || !POLICY_VERSION_RE.test(policy.policy_version)) throw invalidPolicy("policy_version invalid");
|
|
1421
|
+
if (policy.default_effect !== "DENY") throw invalidPolicy("default_effect must be DENY");
|
|
1422
|
+
const allowedFields = new Set(allowedEventFields);
|
|
1423
|
+
if (!Array.isArray(policy.rules) || policy.rules.length === 0) throw invalidPolicy("rules must be a non-empty array");
|
|
1424
|
+
const seenRuleIDs = new Set();
|
|
1425
|
+
const rules = policy.rules.map((rule, ruleIndex) => {
|
|
1426
|
+
if (!isPlainPolicyObject(rule) || !onlyKnownFields(rule, POLICY_RULE_FIELDS)) throw invalidPolicy(`rules[${ruleIndex}] invalid`);
|
|
1427
|
+
if (typeof rule.rule_id !== "string" || !POLICY_IDENTIFIER_RE.test(rule.rule_id) || seenRuleIDs.has(rule.rule_id)) throw invalidPolicy(`rules[${ruleIndex}].rule_id invalid`);
|
|
1428
|
+
seenRuleIDs.add(rule.rule_id);
|
|
1429
|
+
if (!POLICY_EFFECTS.has(rule.effect)) throw invalidPolicy(`rules[${ruleIndex}].effect invalid`);
|
|
1430
|
+
if (!Number.isSafeInteger(rule.priority)) throw invalidPolicy(`rules[${ruleIndex}].priority invalid`);
|
|
1431
|
+
if (!Array.isArray(rule.conditions)) throw invalidPolicy(`rules[${ruleIndex}].conditions invalid`);
|
|
1432
|
+
const conditions = rule.conditions.map((condition, conditionIndex) => {
|
|
1433
|
+
const at = `rules[${ruleIndex}].conditions[${conditionIndex}]`;
|
|
1434
|
+
if (!isPlainPolicyObject(condition) || !onlyKnownFields(condition, POLICY_CONDITION_FIELDS)) throw invalidPolicy(`${at} invalid`);
|
|
1435
|
+
if (!policyNonEmpty(condition.field) || !allowedFields.has(condition.field)) throw invalidPolicy(`${at}.field invalid`);
|
|
1436
|
+
if (!POLICY_CONDITION_OPERATORS.has(condition.operator)) throw invalidPolicy(`${at}.operator invalid`);
|
|
1437
|
+
const literal = policyLiteral(condition.value);
|
|
1438
|
+
if (!literal.ok) throw invalidPolicy(`${at}.value invalid`);
|
|
1439
|
+
return { field: condition.field, operator: condition.operator, value: literal.value, sourcePath: `policy.rules[${ruleIndex}].conditions[${conditionIndex}]` };
|
|
1440
|
+
});
|
|
1441
|
+
if (!Array.isArray(rule.constraints)) throw invalidPolicy(`rules[${ruleIndex}].constraints invalid`);
|
|
1442
|
+
const seenConstraintIDs = new Set();
|
|
1443
|
+
const constraints = rule.constraints.map((constraint, constraintIndex) => {
|
|
1444
|
+
const at = `rules[${ruleIndex}].constraints[${constraintIndex}]`;
|
|
1445
|
+
if (!isPlainPolicyObject(constraint) || !onlyKnownFields(constraint, POLICY_CONSTRAINT_FIELDS)) throw invalidPolicy(`${at} invalid`);
|
|
1446
|
+
if (typeof constraint.constraint_id !== "string" || !POLICY_IDENTIFIER_RE.test(constraint.constraint_id) || seenConstraintIDs.has(constraint.constraint_id)) throw invalidPolicy(`${at}.constraint_id invalid`);
|
|
1447
|
+
seenConstraintIDs.add(constraint.constraint_id);
|
|
1448
|
+
if (!POLICY_CONSTRAINT_TYPES.has(constraint.type)) throw invalidPolicy(`${at}.type invalid`);
|
|
1449
|
+
const literal = policyLiteral(constraint.value);
|
|
1450
|
+
if (!literal.ok) throw invalidPolicy(`${at}.value invalid`);
|
|
1451
|
+
return { constraint_id: constraint.constraint_id, type: constraint.type, value: literal.value };
|
|
1452
|
+
});
|
|
1453
|
+
if (rule.effect === "CONDITIONAL" && constraints.length === 0) throw invalidPolicy(`rules[${ruleIndex}] CONDITIONAL needs a constraint`);
|
|
1454
|
+
return { rule_id: rule.rule_id, effect: rule.effect, conditions, constraints, priority: rule.priority };
|
|
1455
|
+
});
|
|
1456
|
+
const seenPriorities = new Set();
|
|
1457
|
+
rules.forEach((rule, index) => {
|
|
1458
|
+
if (seenPriorities.has(rule.priority) || (index > 0 && rule.priority > rules[index - 1].priority)) throw invalidPolicy("rule priorities must be unique and descending");
|
|
1459
|
+
seenPriorities.add(rule.priority);
|
|
1460
|
+
});
|
|
1461
|
+
return { policy_id: policy.policy_id, policy_version: policy.policy_version, rules, default_effect: policy.default_effect };
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
function canonicalPolicyDefinition(definition) {
|
|
1465
|
+
return policyCanonical(orderedObject(
|
|
1466
|
+
["policy_id", definition.policy_id],
|
|
1467
|
+
["policy_version", definition.policy_version],
|
|
1468
|
+
["rules", definition.rules.map((rule) => orderedObject(
|
|
1469
|
+
["rule_id", rule.rule_id],
|
|
1470
|
+
["effect", rule.effect],
|
|
1471
|
+
["conditions", rule.conditions.map((condition) => orderedObject(["field", condition.field], ["operator", condition.operator], ["value", condition.value]))],
|
|
1472
|
+
["constraints", rule.constraints.map((constraint) => orderedObject(["constraint_id", constraint.constraint_id], ["type", constraint.type], ["value", constraint.value]))],
|
|
1473
|
+
["priority", rule.priority],
|
|
1474
|
+
))],
|
|
1475
|
+
["default_effect", definition.default_effect],
|
|
1476
|
+
));
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
function literalConstantType(value) {
|
|
1480
|
+
if (typeof value === "number") return "NUMBER";
|
|
1481
|
+
if (typeof value === "boolean") return "BOOLEAN";
|
|
1482
|
+
if (typeof value === "string") return "STRING";
|
|
1483
|
+
return "STRUCTURED";
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
function constantTypeRank(type) {
|
|
1487
|
+
return { FIELD: 1, STRING: 2, NUMBER: 3, BOOLEAN: 4 }[type] ?? 5;
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
function sortedPolicyConditions(conditions) {
|
|
1491
|
+
return [...conditions].sort((left, right) =>
|
|
1492
|
+
utf8Compare(left.field, right.field)
|
|
1493
|
+
|| utf8Compare(left.operator, right.operator)
|
|
1494
|
+
|| utf8Compare(policyCanonical(left.value), policyCanonical(right.value))
|
|
1495
|
+
|| utf8Compare(left.sourcePath, right.sourcePath));
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
function constraintsPayload(constraints) {
|
|
1499
|
+
return constraints
|
|
1500
|
+
.map((constraint) => ({ constraint_id: constraint.constraint_id, type: constraint.type, value: constraint.value }))
|
|
1501
|
+
.sort((left, right) => utf8Compare(policyCanonical(left), policyCanonical(right)));
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
function estimatePolicyStackDepth(rules) {
|
|
1505
|
+
let maxDepth = 0;
|
|
1506
|
+
for (const rule of rules) {
|
|
1507
|
+
let depth = 0;
|
|
1508
|
+
rule.conditions.forEach((_, conditionIndex) => {
|
|
1509
|
+
depth += 1;
|
|
1510
|
+
maxDepth = Math.max(maxDepth, depth);
|
|
1511
|
+
depth += 1;
|
|
1512
|
+
maxDepth = Math.max(maxDepth, depth);
|
|
1513
|
+
depth -= 1;
|
|
1514
|
+
if (conditionIndex > 0) depth -= 1;
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
return maxDepth;
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
function compiledPolicyHash(bytecode) {
|
|
1521
|
+
const header = bytecode.bytecode_header_domain;
|
|
1522
|
+
return sha256Hex(POLICY_BYTECODE_HASH_DOMAIN + policyCanonical(orderedObject(
|
|
1523
|
+
["bytecode_header_domain", orderedObject(
|
|
1524
|
+
["bytecode_schema_version", header.bytecode_schema_version],
|
|
1525
|
+
["bytecode_version", header.bytecode_version],
|
|
1526
|
+
["policy_hash", header.policy_hash],
|
|
1527
|
+
["compiler_version", header.compiler_version],
|
|
1528
|
+
["instruction_count", header.instruction_count],
|
|
1529
|
+
)],
|
|
1530
|
+
["constant_pool", bytecode.constant_pool.map((constant) => orderedObject(
|
|
1531
|
+
["index", constant.index], ["constant_type", constant.constant_type], ["value", constant.value], ["value_hash", constant.value_hash],
|
|
1532
|
+
))],
|
|
1533
|
+
["instruction_stream", bytecode.instruction_stream.map((instruction) => orderedObject(
|
|
1534
|
+
["index", instruction.index], ["opcode", instruction.opcode], ["opcode_value", instruction.opcode_value],
|
|
1535
|
+
["operand_a_type", instruction.operand_a_type], ["operand_a", instruction.operand_a],
|
|
1536
|
+
["operand_b_type", instruction.operand_b_type], ["operand_b", instruction.operand_b],
|
|
1537
|
+
))],
|
|
1538
|
+
)));
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
// C2.1 -> C2.3: compile a policy document (its JSON text) to bytecode.
|
|
1542
|
+
export function compilePolicyDocument(policyJSON, allowedEventFields) {
|
|
1543
|
+
if (typeof policyJSON !== "string") throw invalidPolicy("policy document must be JSON text");
|
|
1544
|
+
if (!Array.isArray(allowedEventFields) || allowedEventFields.length === 0 || !allowedEventFields.every(policyNonEmpty)) {
|
|
1545
|
+
throw invalidPolicy("allowed event fields are required");
|
|
1546
|
+
}
|
|
1547
|
+
let parsed;
|
|
1548
|
+
try {
|
|
1549
|
+
parsed = JSON.parse(policyJSON);
|
|
1550
|
+
} catch {
|
|
1551
|
+
throw invalidPolicy("policy document is not JSON");
|
|
1552
|
+
}
|
|
1553
|
+
const definition = validatePolicyDefinition(parsed, allowedEventFields);
|
|
1554
|
+
const sourcePolicyHash = sha256Hex(POLICY_HASH_DOMAIN + canonicalPolicyDefinition(definition));
|
|
1555
|
+
// C2.3 supports ALLOW/DENY with comparison operators only.
|
|
1556
|
+
for (const rule of definition.rules) {
|
|
1557
|
+
if (rule.effect !== "ALLOW" && rule.effect !== "DENY") throw new PolicyReevaluationError("POLICY_COMPILE_FAILED", `rule ${rule.rule_id}: effect not compilable`);
|
|
1558
|
+
for (const condition of rule.conditions) {
|
|
1559
|
+
if (!(condition.operator in POLICY_COMPARISON_OPCODES)) throw new PolicyReevaluationError("POLICY_COMPILE_FAILED", `rule ${rule.rule_id}: operator not compilable`);
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
const entries = new Map();
|
|
1563
|
+
const addConstant = (type, value) => {
|
|
1564
|
+
const canonical = policyCanonical(value);
|
|
1565
|
+
const key = type + "\u0000" + canonical;
|
|
1566
|
+
if (!entries.has(key)) entries.set(key, { type, canonical, value, value_hash: sha256Hex(type + "|" + canonical) });
|
|
1567
|
+
};
|
|
1568
|
+
for (const rule of definition.rules) {
|
|
1569
|
+
addConstant("STRING", rule.rule_id);
|
|
1570
|
+
addConstant("STRUCTURED", constraintsPayload(rule.constraints));
|
|
1571
|
+
for (const condition of sortedPolicyConditions(rule.conditions)) {
|
|
1572
|
+
addConstant("FIELD", condition.field);
|
|
1573
|
+
addConstant(literalConstantType(condition.value), condition.value);
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
addConstant("STRING", "__default__");
|
|
1577
|
+
addConstant("STRUCTURED", []);
|
|
1578
|
+
if (entries.size > POLICY_MAX_CONSTANTS) throw new PolicyReevaluationError("POLICY_COMPILE_FAILED", "constant pool too large");
|
|
1579
|
+
const constants = [...entries.values()]
|
|
1580
|
+
.sort((left, right) => (constantTypeRank(left.type) - constantTypeRank(right.type)) || utf8Compare(left.canonical, right.canonical) || utf8Compare(left.type, right.type))
|
|
1581
|
+
.map((entry, index) => ({ index, constant_type: entry.type, value: entry.value, value_hash: entry.value_hash, canonical: entry.canonical }));
|
|
1582
|
+
const constantIndex = (type, value) => {
|
|
1583
|
+
const canonical = policyCanonical(value);
|
|
1584
|
+
const found = constants.find((constant) => constant.constant_type === type && constant.canonical === canonical);
|
|
1585
|
+
if (found === undefined) throw new PolicyReevaluationError("POLICY_COMPILE_FAILED", "constant missing");
|
|
1586
|
+
return found.index;
|
|
1587
|
+
};
|
|
1588
|
+
const instructions = [];
|
|
1589
|
+
const add = (opcode, operandAType, operandA, operandBType, operandB) => {
|
|
1590
|
+
instructions.push({ index: instructions.length, opcode, opcode_value: POLICY_OPCODE_VALUES[opcode], operand_a_type: operandAType, operand_a: operandA, operand_b_type: operandBType, operand_b: operandB });
|
|
1591
|
+
return instructions.length - 1;
|
|
1592
|
+
};
|
|
1593
|
+
for (const rule of definition.rules) {
|
|
1594
|
+
sortedPolicyConditions(rule.conditions).forEach((condition, conditionIndex) => {
|
|
1595
|
+
add("LOAD_FIELD", "FIELD_INDEX", constantIndex("FIELD", condition.field), "NONE", 0);
|
|
1596
|
+
add("LOAD_CONST", "CONST_INDEX", constantIndex(literalConstantType(condition.value), condition.value), "NONE", 0);
|
|
1597
|
+
add(POLICY_COMPARISON_OPCODES[condition.operator], "NONE", 0, "NONE", 0);
|
|
1598
|
+
if (conditionIndex > 0) add("AND", "NONE", 0, "NONE", 0);
|
|
1599
|
+
});
|
|
1600
|
+
const jumpIndex = rule.conditions.length > 0 ? add("JUMP_IF_FALSE", "JUMP_OFFSET", 0, "NONE", 0) : -1;
|
|
1601
|
+
const ruleIDIndex = constantIndex("STRING", rule.rule_id);
|
|
1602
|
+
const constraintIndex = constantIndex("STRUCTURED", constraintsPayload(rule.constraints));
|
|
1603
|
+
add(rule.effect === "ALLOW" ? "RULE_ALLOW" : "RULE_DENY", "CONST_INDEX", ruleIDIndex, "CONST_INDEX", constraintIndex);
|
|
1604
|
+
const ruleEndIndex = add("RULE_END", "NONE", 0, "NONE", 0);
|
|
1605
|
+
if (jumpIndex >= 0) instructions[jumpIndex].operand_a = ruleEndIndex - jumpIndex;
|
|
1606
|
+
}
|
|
1607
|
+
add("RULE_DENY", "CONST_INDEX", constantIndex("STRING", "__default__"), "CONST_INDEX", constantIndex("STRUCTURED", []));
|
|
1608
|
+
add("RULE_END", "NONE", 0, "NONE", 0);
|
|
1609
|
+
if (definition.rules.length > POLICY_MAX_RULES
|
|
1610
|
+
|| definition.rules.some((rule) => rule.conditions.length > POLICY_MAX_CONDITIONS_PER_RULE)
|
|
1611
|
+
|| instructions.length > POLICY_MAX_INSTRUCTIONS
|
|
1612
|
+
|| estimatePolicyStackDepth(definition.rules) > POLICY_MAX_STACK_DEPTH) {
|
|
1613
|
+
throw new PolicyReevaluationError("POLICY_COMPILE_FAILED", "policy exceeds compiler safety limits");
|
|
1614
|
+
}
|
|
1615
|
+
const bytecode = {
|
|
1616
|
+
bytecode_header_domain: {
|
|
1617
|
+
bytecode_schema_version: POLICY_BYTECODE_SCHEMA_VERSION,
|
|
1618
|
+
bytecode_version: POLICY_BYTECODE_VERSION,
|
|
1619
|
+
policy_hash: sourcePolicyHash,
|
|
1620
|
+
compiled_policy_hash: "",
|
|
1621
|
+
compiler_version: POLICY_COMPILER_VERSION,
|
|
1622
|
+
instruction_count: instructions.length,
|
|
1623
|
+
},
|
|
1624
|
+
constant_pool: constants.map(({ canonical, ...constant }) => constant),
|
|
1625
|
+
instruction_stream: instructions,
|
|
1626
|
+
};
|
|
1627
|
+
bytecode.bytecode_header_domain.compiled_policy_hash = compiledPolicyHash(bytecode);
|
|
1628
|
+
return {
|
|
1629
|
+
policy_id: definition.policy_id,
|
|
1630
|
+
policy_version: definition.policy_version,
|
|
1631
|
+
source_policy_hash: sourcePolicyHash,
|
|
1632
|
+
compiled_policy_hash: bytecode.bytecode_header_domain.compiled_policy_hash,
|
|
1633
|
+
bytecode,
|
|
1634
|
+
};
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
function cloneStackValue(value) {
|
|
1638
|
+
return { value_type: value.value_type, value: clonePolicyValue(value.value) };
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
function clonePolicyValue(value) {
|
|
1642
|
+
if (Array.isArray(value)) return value.map(clonePolicyValue);
|
|
1643
|
+
if (isPlainPolicyObject(value)) return Object.fromEntries(Object.entries(value).map(([key, member]) => [key, clonePolicyValue(member)]));
|
|
1644
|
+
return value;
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
function stackValueFromEventValue(value) {
|
|
1648
|
+
if (typeof value === "string") return { value_type: "string", value };
|
|
1649
|
+
if (typeof value === "boolean") return { value_type: "boolean", value };
|
|
1650
|
+
if (typeof value === "number" && Number.isSafeInteger(value)) return { value_type: "number", value };
|
|
1651
|
+
return { value_type: "unsupported", value: null };
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
function resolveEventField(event, field) {
|
|
1655
|
+
let current = event;
|
|
1656
|
+
for (const part of field.split(".")) {
|
|
1657
|
+
if (!isPlainPolicyObject(current) || !Object.hasOwn(current, part)) return { value_type: "NULL_VALUE", value: null };
|
|
1658
|
+
current = current[part];
|
|
1659
|
+
}
|
|
1660
|
+
if (current === null) return { value_type: "NULL_LITERAL", value: null };
|
|
1661
|
+
return stackValueFromEventValue(current);
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
function stackValueFromConstant(constant) {
|
|
1665
|
+
switch (constant.constant_type) {
|
|
1666
|
+
case "STRING": return typeof constant.value === "string" ? { value_type: "string", value: constant.value } : null;
|
|
1667
|
+
case "NUMBER": return Number.isSafeInteger(constant.value) ? { value_type: "number", value: constant.value } : null;
|
|
1668
|
+
case "BOOLEAN": return typeof constant.value === "boolean" ? { value_type: "boolean", value: constant.value } : null;
|
|
1669
|
+
default: return null;
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
function isNullStackValue(value) {
|
|
1674
|
+
return value.value_type === "NULL_VALUE" || value.value_type === "NULL_LITERAL";
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
function compareStackValues(left, right, opcode) {
|
|
1678
|
+
if (isNullStackValue(left) || isNullStackValue(right)) {
|
|
1679
|
+
if (opcode === "CMP_EQ") return { value: left.value_type === right.value_type };
|
|
1680
|
+
if (opcode === "CMP_NEQ") return { value: left.value_type !== right.value_type };
|
|
1681
|
+
return { error: "ERR_TYPE_MISMATCH" };
|
|
1682
|
+
}
|
|
1683
|
+
if (left.value_type !== right.value_type) return { error: "ERR_TYPE_MISMATCH" };
|
|
1684
|
+
if (left.value_type === "string" || left.value_type === "boolean") {
|
|
1685
|
+
if (opcode === "CMP_EQ") return { value: left.value === right.value };
|
|
1686
|
+
if (opcode === "CMP_NEQ") return { value: left.value !== right.value };
|
|
1687
|
+
return { error: "ERR_TYPE_MISMATCH" };
|
|
1688
|
+
}
|
|
1689
|
+
if (left.value_type === "number") {
|
|
1690
|
+
switch (opcode) {
|
|
1691
|
+
case "CMP_EQ": return { value: left.value === right.value };
|
|
1692
|
+
case "CMP_NEQ": return { value: left.value !== right.value };
|
|
1693
|
+
case "CMP_GT": return { value: left.value > right.value };
|
|
1694
|
+
case "CMP_GTE": return { value: left.value >= right.value };
|
|
1695
|
+
case "CMP_LT": return { value: left.value < right.value };
|
|
1696
|
+
case "CMP_LTE": return { value: left.value <= right.value };
|
|
1697
|
+
default: return { error: "ERR_INVALID_INSTRUCTION" };
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
return { error: "ERR_TYPE_MISMATCH" };
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
function policyInstructionCost(opcode) {
|
|
1704
|
+
if (opcode === "LOAD_FIELD") return 3;
|
|
1705
|
+
if (opcode.startsWith("CMP_")) return 2;
|
|
1706
|
+
return 1;
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
function policyRuntimeError(errorCode) {
|
|
1710
|
+
return { decision: "ERROR", rule_id: "", constraints: [], error_code: errorCode };
|
|
1711
|
+
}
|
|
1712
|
+
|
|
1713
|
+
// C2.4: run the bytecode over the event; returns the evaluation result and
|
|
1714
|
+
// the VM trace exactly as the Go VM records them.
|
|
1715
|
+
function executePolicyBytecode(bytecode, event) {
|
|
1716
|
+
const instructions = bytecode.instruction_stream;
|
|
1717
|
+
const constants = bytecode.constant_pool;
|
|
1718
|
+
const stack = [];
|
|
1719
|
+
const trace = [];
|
|
1720
|
+
let ip = 0;
|
|
1721
|
+
let step = 0;
|
|
1722
|
+
let cost = 0;
|
|
1723
|
+
const constantAt = (index, type) => {
|
|
1724
|
+
const constant = Number.isInteger(index) && index >= 0 && index < constants.length ? constants[index] : undefined;
|
|
1725
|
+
if (constant === undefined || (type !== "" && constant.constant_type !== type)) return undefined;
|
|
1726
|
+
return constant;
|
|
1727
|
+
};
|
|
1728
|
+
const push = (value) => {
|
|
1729
|
+
if (stack.length + 1 > POLICY_MAX_STACK_DEPTH) return "ERR_STACK_OVERFLOW";
|
|
1730
|
+
stack.push(value);
|
|
1731
|
+
return "";
|
|
1732
|
+
};
|
|
1733
|
+
const pop = () => (stack.length === 0 ? { error: "ERR_STACK_UNDERFLOW" } : { value: stack.pop() });
|
|
1734
|
+
const popBool = () => {
|
|
1735
|
+
const popped = pop();
|
|
1736
|
+
if (popped.error) return popped;
|
|
1737
|
+
if (popped.value.value_type !== "boolean" || typeof popped.value.value !== "boolean") return { error: "ERR_TYPE_MISMATCH" };
|
|
1738
|
+
return { value: popped.value.value };
|
|
1739
|
+
};
|
|
1740
|
+
const apply = (instruction) => {
|
|
1741
|
+
const next = ip + 1;
|
|
1742
|
+
switch (instruction.opcode) {
|
|
1743
|
+
case "LOAD_FIELD": {
|
|
1744
|
+
const constant = constantAt(instruction.operand_a, "FIELD");
|
|
1745
|
+
if (constant === undefined || typeof constant.value !== "string" || constant.value === "") return { next, error: "ERR_INVALID_CONSTANT" };
|
|
1746
|
+
return { next, error: push(resolveEventField(event, constant.value)) };
|
|
1747
|
+
}
|
|
1748
|
+
case "LOAD_CONST": {
|
|
1749
|
+
const constant = constantAt(instruction.operand_a, "");
|
|
1750
|
+
if (constant === undefined || constant.constant_type === "FIELD" || constant.constant_type === "STRUCTURED") return { next, error: "ERR_INVALID_CONSTANT" };
|
|
1751
|
+
const value = stackValueFromConstant(constant);
|
|
1752
|
+
if (value === null) return { next, error: "ERR_INVALID_CONSTANT" };
|
|
1753
|
+
return { next, error: push(value) };
|
|
1754
|
+
}
|
|
1755
|
+
case "CMP_EQ": case "CMP_NEQ": case "CMP_GT": case "CMP_GTE": case "CMP_LT": case "CMP_LTE": {
|
|
1756
|
+
const right = pop();
|
|
1757
|
+
if (right.error) return { next, error: right.error };
|
|
1758
|
+
const left = pop();
|
|
1759
|
+
if (left.error) return { next, error: left.error };
|
|
1760
|
+
const compared = compareStackValues(left.value, right.value, instruction.opcode);
|
|
1761
|
+
if (compared.error) return { next, error: compared.error };
|
|
1762
|
+
return { next, error: push({ value_type: "boolean", value: compared.value }) };
|
|
1763
|
+
}
|
|
1764
|
+
case "AND": case "OR": {
|
|
1765
|
+
const right = popBool();
|
|
1766
|
+
if (right.error) return { next, error: right.error };
|
|
1767
|
+
const left = popBool();
|
|
1768
|
+
if (left.error) return { next, error: left.error };
|
|
1769
|
+
const value = instruction.opcode === "AND" ? left.value && right.value : left.value || right.value;
|
|
1770
|
+
return { next, error: push({ value_type: "boolean", value }) };
|
|
1771
|
+
}
|
|
1772
|
+
case "NOT": {
|
|
1773
|
+
const value = popBool();
|
|
1774
|
+
if (value.error) return { next, error: value.error };
|
|
1775
|
+
return { next, error: push({ value_type: "boolean", value: !value.value }) };
|
|
1776
|
+
}
|
|
1777
|
+
case "JUMP": {
|
|
1778
|
+
const target = ip + instruction.operand_a;
|
|
1779
|
+
if (target < 0 || target >= instructions.length) return { next, error: "ERR_INVALID_JUMP" };
|
|
1780
|
+
return { next: target, error: "" };
|
|
1781
|
+
}
|
|
1782
|
+
case "JUMP_IF_FALSE": {
|
|
1783
|
+
const condition = popBool();
|
|
1784
|
+
if (condition.error) return { next, error: condition.error };
|
|
1785
|
+
if (condition.value) return { next, error: "" };
|
|
1786
|
+
const target = ip + instruction.operand_a;
|
|
1787
|
+
if (target < 0 || target >= instructions.length) return { next, error: "ERR_INVALID_JUMP" };
|
|
1788
|
+
return { next: target, error: "" };
|
|
1789
|
+
}
|
|
1790
|
+
case "RULE_ALLOW": case "RULE_DENY": {
|
|
1791
|
+
const ruleConstant = constantAt(instruction.operand_a, "STRING");
|
|
1792
|
+
if (ruleConstant === undefined || typeof ruleConstant.value !== "string" || ruleConstant.value === "") return { next, error: "ERR_INVALID_CONSTANT" };
|
|
1793
|
+
const constraintConstant = constantAt(instruction.operand_b, "STRUCTURED");
|
|
1794
|
+
if (constraintConstant === undefined || !Array.isArray(constraintConstant.value)) return { next, error: "ERR_INVALID_CONSTANT" };
|
|
1795
|
+
return {
|
|
1796
|
+
next,
|
|
1797
|
+
error: "",
|
|
1798
|
+
result: {
|
|
1799
|
+
decision: instruction.opcode === "RULE_DENY" ? "NON_COMPLIANT" : "COMPLIANT",
|
|
1800
|
+
rule_id: ruleConstant.value,
|
|
1801
|
+
constraints: clonePolicyValue(constraintConstant.value),
|
|
1802
|
+
error_code: "",
|
|
1803
|
+
},
|
|
1804
|
+
};
|
|
1805
|
+
}
|
|
1806
|
+
case "RULE_END":
|
|
1807
|
+
return { next, error: "" };
|
|
1808
|
+
default:
|
|
1809
|
+
return { next, error: "ERR_INVALID_INSTRUCTION" };
|
|
1810
|
+
}
|
|
1811
|
+
};
|
|
1812
|
+
while (ip >= 0 && ip < instructions.length) {
|
|
1813
|
+
const instruction = instructions[ip];
|
|
1814
|
+
if (step >= POLICY_MAX_INSTRUCTIONS || cost + policyInstructionCost(instruction.opcode) > POLICY_VM_MAX_EXECUTION_COST) return { result: policyRuntimeError("ERR_RUNTIME_LIMIT_EXCEEDED"), trace };
|
|
1815
|
+
if (trace.length + 1 > POLICY_MAX_INSTRUCTIONS) return { result: policyRuntimeError("ERR_RUNTIME_LIMIT_EXCEEDED"), trace };
|
|
1816
|
+
const before = stack.map(cloneStackValue);
|
|
1817
|
+
const applied = apply(instruction);
|
|
1818
|
+
const after = stack.map(cloneStackValue);
|
|
1819
|
+
step += 1;
|
|
1820
|
+
cost += policyInstructionCost(instruction.opcode);
|
|
1821
|
+
trace.push({ step, instruction_index: instruction.index, opcode: instruction.opcode, stack_before: before, stack_after: after });
|
|
1822
|
+
if (applied.error) return { result: policyRuntimeError(applied.error), trace };
|
|
1823
|
+
if (applied.result) return { result: applied.result, trace };
|
|
1824
|
+
ip = applied.next;
|
|
1825
|
+
}
|
|
1826
|
+
return { result: policyRuntimeError("ERR_NO_TERMINAL_RULE"), trace };
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
function orderedPolicyTrace(trace) {
|
|
1830
|
+
const stackOrdered = (stack) => stack.map((value) => orderedObject(["value_type", value.value_type], ["value", value.value]));
|
|
1831
|
+
return trace.map((entry) => orderedObject(
|
|
1832
|
+
["step", entry.step],
|
|
1833
|
+
["instruction_index", entry.instruction_index],
|
|
1834
|
+
["opcode", entry.opcode],
|
|
1835
|
+
["stack_before", stackOrdered(entry.stack_before)],
|
|
1836
|
+
["stack_after", stackOrdered(entry.stack_after)],
|
|
1837
|
+
));
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
// The C2.4 execution-event hash of an event object.
|
|
1841
|
+
export function policyExecutionEventHash(event) {
|
|
1842
|
+
return sha256Hex(POLICY_VM_EVENT_HASH_DOMAIN + policyCanonical(event));
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
// C2.4: evaluate a compiled policy over an execution event and return every
|
|
1846
|
+
// value a policy binding seals.
|
|
1847
|
+
export function evaluateCompiledPolicy(compiled, event) {
|
|
1848
|
+
if (!isPlainPolicyObject(event) || Object.keys(event).length === 0) throw new PolicyReevaluationError("POLICY_EVENT_INVALID", "execution event must be a non-empty object");
|
|
1849
|
+
const header = compiled.bytecode.bytecode_header_domain;
|
|
1850
|
+
const { result, trace } = executePolicyBytecode(compiled.bytecode, event);
|
|
1851
|
+
const vmTrace = orderedPolicyTrace(trace);
|
|
1852
|
+
const traceHash = sha256Hex(POLICY_VM_TRACE_HASH_DOMAIN + policyCanonical(vmTrace));
|
|
1853
|
+
const executionEventHash = policyExecutionEventHash(event);
|
|
1854
|
+
const evaluationHash = sha256Hex(POLICY_VM_EVALUATION_HASH_DOMAIN + policyCanonical(orderedObject(
|
|
1855
|
+
["evaluation_result", orderedObject(["decision", result.decision], ["rule_id", result.rule_id], ["constraints", result.constraints], ["error_code", result.error_code])],
|
|
1856
|
+
["vm_trace", vmTrace],
|
|
1857
|
+
["trace_hash", traceHash],
|
|
1858
|
+
["runtime_fingerprint", orderedObject(["pvm_runtime_version", POLICY_VM_RUNTIME_VERSION], ["compiler_version", header.compiler_version], ["bytecode_version", header.bytecode_version])],
|
|
1859
|
+
["integrity", orderedObject(
|
|
1860
|
+
["source_policy_hash", header.policy_hash],
|
|
1861
|
+
["compiled_policy_hash", header.compiled_policy_hash],
|
|
1862
|
+
["execution_event_hash", executionEventHash],
|
|
1863
|
+
["trace_hash", traceHash],
|
|
1864
|
+
["hash_algorithm", "SHA-256"],
|
|
1865
|
+
)],
|
|
1866
|
+
["task_ids", [...POLICY_VM_TASK_IDS]],
|
|
1867
|
+
["valid", true],
|
|
1868
|
+
)));
|
|
1869
|
+
const constraints = result.constraints.map((constraint) => {
|
|
1870
|
+
if (!isPlainPolicyObject(constraint) || !policyNonEmpty(constraint.constraint_id) || !policyNonEmpty(constraint.type)) {
|
|
1871
|
+
throw new PolicyReevaluationError("POLICY_EVALUATION_INVALID", "evaluation constraint has no id or type");
|
|
1872
|
+
}
|
|
1873
|
+
return { constraint_id: constraint.constraint_id, type: constraint.type };
|
|
1874
|
+
}).sort((left, right) => utf8Compare(left.constraint_id, right.constraint_id));
|
|
1875
|
+
return {
|
|
1876
|
+
policy_id: compiled.policy_id,
|
|
1877
|
+
policy_version: compiled.policy_version,
|
|
1878
|
+
source_policy_hash: header.policy_hash,
|
|
1879
|
+
compiled_policy_hash: header.compiled_policy_hash,
|
|
1880
|
+
execution_event_hash: executionEventHash,
|
|
1881
|
+
evaluation_hash: evaluationHash,
|
|
1882
|
+
decision: result.decision,
|
|
1883
|
+
rule_id: result.rule_id,
|
|
1884
|
+
error_code: result.error_code,
|
|
1885
|
+
constraints,
|
|
1886
|
+
};
|
|
1887
|
+
}
|
|
1888
|
+
|
|
1889
|
+
// Compiles policyJSON and evaluates event in one step.
|
|
1890
|
+
export function reevaluatePolicy({ policyJSON, allowedEventFields, event }) {
|
|
1891
|
+
return evaluateCompiledPolicy(compilePolicyDocument(policyJSON, allowedEventFields), event);
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
// Lists every sealed policy-binding member the recomputed evaluation
|
|
1895
|
+
// disagrees with (sorted policy_binding.<member> paths). Constraint statuses
|
|
1896
|
+
// are not part of the evaluation and are not compared.
|
|
1897
|
+
export function policyReevaluationMismatches(binding, recomputed) {
|
|
1898
|
+
const fields = [];
|
|
1899
|
+
for (const member of ["compiled_policy_hash", "decision", "evaluation_hash", "execution_event_hash", "policy_id", "policy_version", "rule_id", "source_policy_hash"]) {
|
|
1900
|
+
if (binding[member] !== recomputed[member]) fields.push(`policy_binding.${member}`);
|
|
1901
|
+
}
|
|
1902
|
+
const sealed = Array.isArray(binding.constraints) ? binding.constraints : [];
|
|
1903
|
+
if (sealed.length !== recomputed.constraints.length
|
|
1904
|
+
|| sealed.some((constraint, index) => constraint.constraint_id !== recomputed.constraints[index].constraint_id || constraint.type !== recomputed.constraints[index].type)) {
|
|
1905
|
+
fields.push("policy_binding.constraints");
|
|
1906
|
+
}
|
|
1907
|
+
return fields.sort();
|
|
1908
|
+
}
|