@decionis/agentsafe 0.7.0 → 0.9.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 +6 -1
- package/dist/Cli.js +13 -3
- package/dist/Cli.js.map +1 -1
- package/dist/acceptance/AcceptancePlan.d.ts +109 -0
- package/dist/acceptance/AcceptancePlan.d.ts.map +1 -0
- package/dist/acceptance/AcceptancePlan.js +128 -0
- package/dist/acceptance/AcceptancePlan.js.map +1 -0
- package/dist/acceptance/AcceptanceReport.d.ts +596 -0
- package/dist/acceptance/AcceptanceReport.d.ts.map +1 -0
- package/dist/acceptance/AcceptanceReport.js +361 -0
- package/dist/acceptance/AcceptanceReport.js.map +1 -0
- package/dist/acceptance/AcceptanceRun.d.ts +118 -0
- package/dist/acceptance/AcceptanceRun.d.ts.map +1 -0
- package/dist/acceptance/AcceptanceRun.js +419 -0
- package/dist/acceptance/AcceptanceRun.js.map +1 -0
- package/dist/acceptance/Coverage.d.ts +12 -0
- package/dist/acceptance/Coverage.d.ts.map +1 -0
- package/dist/acceptance/Coverage.js +48 -0
- package/dist/acceptance/Coverage.js.map +1 -0
- package/dist/acceptance/OutageDoubles.d.ts +34 -0
- package/dist/acceptance/OutageDoubles.d.ts.map +1 -0
- package/dist/acceptance/OutageDoubles.js +67 -0
- package/dist/acceptance/OutageDoubles.js.map +1 -0
- package/dist/acceptance/ZoneProbes.d.ts +368 -0
- package/dist/acceptance/ZoneProbes.d.ts.map +1 -0
- package/dist/acceptance/ZoneProbes.js +488 -0
- package/dist/acceptance/ZoneProbes.js.map +1 -0
- package/dist/adapters/JcsDigest.d.ts +6 -5
- package/dist/adapters/JcsDigest.d.ts.map +1 -1
- package/dist/adapters/JcsDigest.js +9 -8
- package/dist/adapters/JcsDigest.js.map +1 -1
- package/dist/cli/Accept.d.ts +9 -0
- package/dist/cli/Accept.d.ts.map +1 -0
- package/dist/cli/Accept.js +209 -0
- package/dist/cli/Accept.js.map +1 -0
- package/dist/cli/Actions.d.ts +6 -4
- package/dist/cli/Actions.d.ts.map +1 -1
- package/dist/cli/Actions.js +33 -7
- package/dist/cli/Actions.js.map +1 -1
- package/dist/cli/Commands.d.ts +1 -1
- package/dist/cli/Commands.d.ts.map +1 -1
- package/dist/cli/Commands.js +5 -0
- package/dist/cli/Commands.js.map +1 -1
- package/dist/cli/ConfigCommand.d.ts.map +1 -1
- package/dist/cli/ConfigCommand.js +5 -0
- package/dist/cli/ConfigCommand.js.map +1 -1
- package/dist/cli/Doctor.d.ts.map +1 -1
- package/dist/cli/Doctor.js +67 -1
- package/dist/cli/Doctor.js.map +1 -1
- package/dist/cli/Help.d.ts.map +1 -1
- package/dist/cli/Help.js +6 -1
- package/dist/cli/Help.js.map +1 -1
- package/dist/cli/Identity.d.ts +13 -1
- package/dist/cli/Identity.d.ts.map +1 -1
- package/dist/cli/Identity.js +25 -2
- package/dist/cli/Identity.js.map +1 -1
- package/dist/cli/Status.d.ts +23 -0
- package/dist/cli/Status.d.ts.map +1 -1
- package/dist/cli/Status.js +80 -18
- package/dist/cli/Status.js.map +1 -1
- package/dist/cli/VerifyAcceptance.d.ts +38 -0
- package/dist/cli/VerifyAcceptance.d.ts.map +1 -0
- package/dist/cli/VerifyAcceptance.js +143 -0
- package/dist/cli/VerifyAcceptance.js.map +1 -0
- package/dist/config/ExecutorConfig.d.ts +6 -1
- package/dist/config/ExecutorConfig.d.ts.map +1 -1
- package/dist/config/ExecutorConfig.js.map +1 -1
- package/dist/egress/ZoneHttpClient.d.ts +3 -0
- package/dist/egress/ZoneHttpClient.d.ts.map +1 -0
- package/dist/egress/ZoneHttpClient.js +72 -0
- package/dist/egress/ZoneHttpClient.js.map +1 -0
- package/dist/exposure/DecionisExposureLedger.d.ts +44 -0
- package/dist/exposure/DecionisExposureLedger.d.ts.map +1 -0
- package/dist/exposure/DecionisExposureLedger.js +175 -0
- package/dist/exposure/DecionisExposureLedger.js.map +1 -0
- package/dist/exposure/ExposureDeclaration.d.ts +68 -0
- package/dist/exposure/ExposureDeclaration.d.ts.map +1 -0
- package/dist/exposure/ExposureDeclaration.js +120 -0
- package/dist/exposure/ExposureDeclaration.js.map +1 -0
- package/dist/exposure/ExposureFacts.d.ts +61 -0
- package/dist/exposure/ExposureFacts.d.ts.map +1 -0
- package/dist/exposure/ExposureFacts.js +220 -0
- package/dist/exposure/ExposureFacts.js.map +1 -0
- package/dist/exposure/ExposureGate.d.ts +144 -0
- package/dist/exposure/ExposureGate.d.ts.map +1 -0
- package/dist/exposure/ExposureGate.js +446 -0
- package/dist/exposure/ExposureGate.js.map +1 -0
- package/dist/exposure/ExposureLedger.d.ts +93 -0
- package/dist/exposure/ExposureLedger.d.ts.map +1 -0
- package/dist/exposure/ExposureLedger.js +24 -0
- package/dist/exposure/ExposureLedger.js.map +1 -0
- package/dist/gateway/AttemptStore.d.ts +83 -0
- package/dist/gateway/AttemptStore.d.ts.map +1 -0
- package/dist/gateway/AttemptStore.js +229 -0
- package/dist/gateway/AttemptStore.js.map +1 -0
- package/dist/gateway/ForwardHandler.d.ts +29 -3
- package/dist/gateway/ForwardHandler.d.ts.map +1 -1
- package/dist/gateway/ForwardHandler.js +32 -5
- package/dist/gateway/ForwardHandler.js.map +1 -1
- package/dist/gateway/Gateway.d.ts +229 -17
- package/dist/gateway/Gateway.d.ts.map +1 -1
- package/dist/gateway/Gateway.js +1045 -81
- package/dist/gateway/Gateway.js.map +1 -1
- package/dist/gateway/GatewayConfig.d.ts +186 -0
- package/dist/gateway/GatewayConfig.d.ts.map +1 -1
- package/dist/gateway/GatewayConfig.js +219 -5
- package/dist/gateway/GatewayConfig.js.map +1 -1
- package/dist/gateway/GatewayManifest.d.ts +18 -0
- package/dist/gateway/GatewayManifest.d.ts.map +1 -0
- package/dist/gateway/GatewayManifest.js +42 -0
- package/dist/gateway/GatewayManifest.js.map +1 -0
- package/dist/gateway/GatewayMetrics.d.ts +12 -4
- package/dist/gateway/GatewayMetrics.d.ts.map +1 -1
- package/dist/gateway/GatewayMetrics.js +5 -0
- package/dist/gateway/GatewayMetrics.js.map +1 -1
- package/dist/gateway/GatewayReport.d.ts +34 -1
- package/dist/gateway/GatewayReport.d.ts.map +1 -1
- package/dist/gateway/GatewayReport.js +11 -0
- package/dist/gateway/GatewayReport.js.map +1 -1
- package/dist/gateway/HoldStore.d.ts +89 -0
- package/dist/gateway/HoldStore.d.ts.map +1 -0
- package/dist/gateway/HoldStore.js +280 -0
- package/dist/gateway/HoldStore.js.map +1 -0
- package/dist/gateway/InterceptedRequest.d.ts +10 -0
- package/dist/gateway/InterceptedRequest.d.ts.map +1 -1
- package/dist/gateway/InterceptedRequest.js +20 -0
- package/dist/gateway/InterceptedRequest.js.map +1 -1
- package/dist/gateway/RouteTable.d.ts +33 -5
- package/dist/gateway/RouteTable.d.ts.map +1 -1
- package/dist/gateway/RouteTable.js +76 -1
- package/dist/gateway/RouteTable.js.map +1 -1
- package/dist/gateway/ShadowLedger.d.ts +11 -0
- package/dist/gateway/ShadowLedger.d.ts.map +1 -1
- package/dist/gateway/ShadowLedger.js +11 -0
- package/dist/gateway/ShadowLedger.js.map +1 -1
- package/dist/gateway/TargetEffect.d.ts +74 -0
- package/dist/gateway/TargetEffect.d.ts.map +1 -0
- package/dist/gateway/TargetEffect.js +95 -0
- package/dist/gateway/TargetEffect.js.map +1 -0
- package/dist/gateway/TargetReader.d.ts +70 -0
- package/dist/gateway/TargetReader.d.ts.map +1 -0
- package/dist/gateway/TargetReader.js +106 -0
- package/dist/gateway/TargetReader.js.map +1 -0
- package/dist/gateway/Upstream.d.ts +15 -0
- package/dist/gateway/Upstream.d.ts.map +1 -1
- package/dist/gateway/Upstream.js +24 -2
- package/dist/gateway/Upstream.js.map +1 -1
- package/dist/hosted/TenantHost.d.ts +3 -2
- package/dist/hosted/TenantHost.d.ts.map +1 -1
- package/dist/hosted/TenantHost.js +7 -1
- package/dist/hosted/TenantHost.js.map +1 -1
- package/dist/hosted/TenantRegistry.d.ts +8 -0
- package/dist/hosted/TenantRegistry.d.ts.map +1 -1
- package/dist/hosted/TenantRegistry.js +14 -1
- package/dist/hosted/TenantRegistry.js.map +1 -1
- package/dist/http/GatewayHttpServer.d.ts +7 -0
- package/dist/http/GatewayHttpServer.d.ts.map +1 -1
- package/dist/http/GatewayHttpServer.js +57 -1
- package/dist/http/GatewayHttpServer.js.map +1 -1
- package/dist/outcomes/OutcomeEvidence.d.ts +4 -4
- package/dist/posture/ActionSpaceDrift.d.ts +40 -0
- package/dist/posture/ActionSpaceDrift.d.ts.map +1 -0
- package/dist/posture/ActionSpaceDrift.js +67 -0
- package/dist/posture/ActionSpaceDrift.js.map +1 -0
- package/dist/posture/DeploymentFingerprint.d.ts +88 -0
- package/dist/posture/DeploymentFingerprint.d.ts.map +1 -0
- package/dist/posture/DeploymentFingerprint.js +78 -0
- package/dist/posture/DeploymentFingerprint.js.map +1 -0
- package/dist/secrets/SecretStore.d.ts +6 -1
- package/dist/secrets/SecretStore.d.ts.map +1 -1
- package/dist/secrets/SecretStore.js.map +1 -1
- package/dist/service/EscalationResolver.d.ts +6 -6
- package/dist/service/EscalationResolver.d.ts.map +1 -1
- package/dist/service/EscalationResolver.js +8 -4
- package/dist/service/EscalationResolver.js.map +1 -1
- package/package.json +3 -3
package/dist/gateway/Gateway.js
CHANGED
|
@@ -1,17 +1,27 @@
|
|
|
1
|
-
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
1
|
+
import { createHash, hkdfSync, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
2
|
import { Resolver } from "node:dns/promises";
|
|
3
3
|
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { ActionRegistry, ApiProfiles, AuditRecorder, DecionisGate, DecionisGrantVerifier, IntentCapture, SafeExecutor, ShadowPipeline, } from "@decionis/agent-safe-pipeline";
|
|
5
|
+
import { ActionRegistry, ApiProfiles, AuditRecorder, DecionisGate, DecionisGrantVerifier, IntentCapture, PreDispatchRefusal, SafeExecutor, ShadowPipeline, } from "@decionis/agent-safe-pipeline";
|
|
6
6
|
import { boundarySignal, resolveBoundary, } from "../boundary/BoundaryIdentity.js";
|
|
7
7
|
import { DockerProvenanceProvider } from "../provenance/DockerProvenanceProvider.js";
|
|
8
8
|
import { KubernetesProvenanceProvider } from "../provenance/KubernetesProvenanceProvider.js";
|
|
9
9
|
import { NoneProvenanceProvider } from "../provenance/NoneProvenanceProvider.js";
|
|
10
10
|
import { resolveWorkload } from "../provenance/ProvenanceProvider.js";
|
|
11
|
+
import { splitTarget, writeBody } from "../acceptance/AcceptancePlan.js";
|
|
12
|
+
import { acceptanceSigningKey, signAcceptanceReport, } from "../acceptance/AcceptanceReport.js";
|
|
13
|
+
import { AcceptanceRuns, } from "../acceptance/AcceptanceRun.js";
|
|
14
|
+
import { coverageOf } from "../acceptance/Coverage.js";
|
|
15
|
+
import { AUTHORITY_UNREACHABLE, recordingUpstream } from "../acceptance/OutageDoubles.js";
|
|
16
|
+
import { EffectAwareGrantVerifier } from "../adapters/EffectAwareGrantVerifier.js";
|
|
17
|
+
import { EffectEvidenceRegister } from "../adapters/EffectEvidenceRegister.js";
|
|
11
18
|
import { ChainJournal } from "../audit/ChainJournal.js";
|
|
12
19
|
import { HashChain } from "../audit/HashChain.js";
|
|
13
20
|
import { EVIDENCE_STREAM, HashChainedAuditSink } from "../audit/HashChainedAuditSink.js";
|
|
14
21
|
import { EgressPolicy } from "../egress/EgressPolicy.js";
|
|
22
|
+
import { DecionisExposureLedger } from "../exposure/DecionisExposureLedger.js";
|
|
23
|
+
import { readExposureFacts, readSettledAmount, } from "../exposure/ExposureFacts.js";
|
|
24
|
+
import { ExposureGate, } from "../exposure/ExposureGate.js";
|
|
15
25
|
import { EgressError } from "../egress/EgressError.js";
|
|
16
26
|
import { CLIENT_CERTIFICATE_REFUSED, GuardedFetch, } from "../egress/GuardedFetch.js";
|
|
17
27
|
import { RequestContext } from "../http/RequestContext.js";
|
|
@@ -21,17 +31,22 @@ import { CompositeSecretStore } from "../secrets/CompositeSecretStore.js";
|
|
|
21
31
|
import { Redactor } from "../secrets/Redactor.js";
|
|
22
32
|
import { SecretError } from "../secrets/SecretStore.js";
|
|
23
33
|
import { EscalationResolver } from "../service/EscalationResolver.js";
|
|
34
|
+
import { ActionSpaceDrift } from "../posture/ActionSpaceDrift.js";
|
|
35
|
+
import { deploymentFingerprint, } from "../posture/DeploymentFingerprint.js";
|
|
24
36
|
import { ActivationFunnel } from "./Activation.js";
|
|
25
37
|
import { startDemoAuthority } from "./DemoAuthority.js";
|
|
26
38
|
import { httpForwardHandler, registerHttpActions, RequestHolder, } from "./ForwardHandler.js";
|
|
27
|
-
import { GatewayConfigLoader } from "./GatewayConfig.js";
|
|
39
|
+
import { ACCEPTANCE_KEY_SECRET, ACCEPTANCE_TOKEN_SECRET, GATEWAY_TOKEN_SECRET, GATEWAY_TOKEN_HEADER, GatewayConfigError, GatewayConfigLoader, SESSION_HEADER, SUBJECT_TOKEN_HEADER, TENANT_KEY_HEADER, } from "./GatewayConfig.js";
|
|
40
|
+
import { FileHoldStore, MemoryHoldStore, } from "./HoldStore.js";
|
|
41
|
+
import { ATTEMPT_TTL_MS, FileAttemptStore, MemoryAttemptStore, } from "./AttemptStore.js";
|
|
28
42
|
import { gatewayMetrics } from "./GatewayMetrics.js";
|
|
29
43
|
import { processSurface } from "./InstallSurface.js";
|
|
30
44
|
import { renderHuman, renderJson, } from "./GatewayReport.js";
|
|
31
|
-
import { normalizeFacts, normalizeRequest } from "./InterceptedRequest.js";
|
|
45
|
+
import { idempotencyKeyOf, normalizeFacts, normalizeRequest, retryDigest, } from "./InterceptedRequest.js";
|
|
32
46
|
import { TokenBucket } from "./RateLimit.js";
|
|
33
47
|
import { RefusalSampler } from "./RefusalSampler.js";
|
|
34
48
|
import { RouteTable } from "./RouteTable.js";
|
|
49
|
+
import { TargetReader } from "./TargetReader.js";
|
|
35
50
|
import { IssuerSubjectVerifier, MAX_SUBJECT_TOKEN_AGE_SECONDS, SubjectSessions, } from "./SubjectSessions.js";
|
|
36
51
|
import { WorkloadJwtVerifier } from "../identity/WorkloadJwtVerifier.js";
|
|
37
52
|
import { enforcementSwitch, ShadowLedger } from "./ShadowLedger.js";
|
|
@@ -53,9 +68,9 @@ export const GATEWAY_STREAM = "agent-safe.gateway-events/1";
|
|
|
53
68
|
export const GATEWAY_PREFIX = "/_agentsafe";
|
|
54
69
|
/** The version of the wire shape the gateway answers with on its own responses. */
|
|
55
70
|
export const GATEWAY_RESPONSE_VERSION = "agent-safe.gateway/1";
|
|
56
|
-
/** The most escalations held at once; beyond it a new hold is refused rather than an old one dropped. */
|
|
57
|
-
const MAX_HELD = 1_000;
|
|
58
71
|
const RETRY_AFTER_SECONDS = 5;
|
|
72
|
+
/** What the facts-only digest key is derived for, so the custody key derives nothing else alike. */
|
|
73
|
+
const DIGEST_KEY_INFO = "agentsafe.facts-digest/1";
|
|
59
74
|
/**
|
|
60
75
|
* The transport codes of a send that ended before a connection to the
|
|
61
76
|
* upstream existed: the name did not resolve, or the connection was refused
|
|
@@ -81,20 +96,13 @@ const CERTIFICATE_UNVERIFIED = /^(?:UNABLE_TO_|SELF_SIGNED|DEPTH_ZERO|CERT_|ERR_
|
|
|
81
96
|
export function shortDigest(digest) {
|
|
82
97
|
return digest.slice(0, "sha256:".length + 12);
|
|
83
98
|
}
|
|
99
|
+
/** The response header that names the dossier of the INDETERMINATE attempt a request retries. */
|
|
100
|
+
export const RETRY_OF_HEADER = "agentsafe-retry-of";
|
|
84
101
|
/**
|
|
85
102
|
* The header a resume token travels in. Never the path or the query: those
|
|
86
103
|
* are what proxies, access logs and this gateway's own report write down.
|
|
87
104
|
*/
|
|
88
105
|
export const RESUME_TOKEN_HEADER = "agentsafe-resume-token";
|
|
89
|
-
/**
|
|
90
|
-
* The HTTP-interception ingress over the unchanged lifecycle. A request the
|
|
91
|
-
* route table calls consequential becomes a captured intent; the authority
|
|
92
|
-
* decides; on `ALLOW` the executor claims the grant and the forwarding
|
|
93
|
-
* handler sends the exact bytes the intent bound; the outcome is finalized
|
|
94
|
-
* and every step is chained evidence. In shadow the request goes through
|
|
95
|
-
* unchanged while the authority is asked what it would have decided.
|
|
96
|
-
* Nothing here decides ALLOW, BLOCK or ESCALATE; it asks, enforces and records.
|
|
97
|
-
*/
|
|
98
106
|
export class Gateway {
|
|
99
107
|
config;
|
|
100
108
|
upstream;
|
|
@@ -115,7 +123,13 @@ export class Gateway {
|
|
|
115
123
|
proof;
|
|
116
124
|
sessions;
|
|
117
125
|
jwks;
|
|
118
|
-
|
|
126
|
+
effects;
|
|
127
|
+
replaced;
|
|
128
|
+
acceptance;
|
|
129
|
+
/** The requests held for a person's decision: in memory, or in a directory every replica shares. */
|
|
130
|
+
holds;
|
|
131
|
+
/** The INDETERMINATE attempts a retry with the same idempotency key is linked to: kept where the holds are. */
|
|
132
|
+
attempts;
|
|
119
133
|
/**
|
|
120
134
|
* For each governed request whose operation names where the subject sits
|
|
121
135
|
* in its answer: the session and operation the answer is checked against,
|
|
@@ -125,11 +139,24 @@ export class Gateway {
|
|
|
125
139
|
answerScopes = new WeakMap();
|
|
126
140
|
holder = new RequestHolder();
|
|
127
141
|
/**
|
|
128
|
-
*
|
|
129
|
-
*
|
|
130
|
-
*
|
|
142
|
+
* What the gateway read of each captured write's target before the
|
|
143
|
+
* authority was asked, for the reads after it: once the write lands, or
|
|
144
|
+
* once it is refused. Keyed by the captured intent, which a held
|
|
145
|
+
* escalation keeps, so a resumed write is read back too.
|
|
131
146
|
*/
|
|
132
|
-
|
|
147
|
+
plans = new WeakMap();
|
|
148
|
+
/** The reads after a refusal still waiting for their window; the stop waits for them. */
|
|
149
|
+
observing = new Set();
|
|
150
|
+
/** A profiled write's target reads, in enforcement only; null otherwise. */
|
|
151
|
+
reader;
|
|
152
|
+
/**
|
|
153
|
+
* The key of the facts-only request digest, so the digest an authority
|
|
154
|
+
* receives confirms nothing about the request to anyone without it:
|
|
155
|
+
* derived from the tenant's key in custody (`interception.digestKeyFile`),
|
|
156
|
+
* the same on every replica; otherwise made here and held only here, so a
|
|
157
|
+
* held escalation is resumed by this same gateway.
|
|
158
|
+
*/
|
|
159
|
+
digestKey;
|
|
133
160
|
capture;
|
|
134
161
|
executor;
|
|
135
162
|
shadow;
|
|
@@ -145,7 +172,18 @@ export class Gateway {
|
|
|
145
172
|
/** The tenant keys admitted now: the configuration's, until a host replaces them in place. */
|
|
146
173
|
admitted;
|
|
147
174
|
registry = null;
|
|
148
|
-
|
|
175
|
+
/** What this gateway is: computed once, since nothing it is built from changes while it runs. */
|
|
176
|
+
fingerprint;
|
|
177
|
+
actionSpace;
|
|
178
|
+
/** Acceptance runs, when the configuration names their key and token; null otherwise. */
|
|
179
|
+
runs;
|
|
180
|
+
/** The plan write each request a run sent is, by request. */
|
|
181
|
+
acceptanceWrites = new WeakMap();
|
|
182
|
+
/** The cumulative-limit check, when a route releases money; null otherwise. */
|
|
183
|
+
exposure;
|
|
184
|
+
constructor(config, upstream, routes, audit, gate, verifier, metrics, emitLine, io, security, secrets, demo, journal, evidence, chain, clock, version, surface, boundary, workload, activation, proof, sessions, jwks, effects,
|
|
185
|
+
/** The digest of the gateway this one replaces, when it replaces one. */
|
|
186
|
+
replaced, acceptance, exposureLedger) {
|
|
149
187
|
this.config = config;
|
|
150
188
|
this.upstream = upstream;
|
|
151
189
|
this.routes = routes;
|
|
@@ -165,9 +203,54 @@ export class Gateway {
|
|
|
165
203
|
this.proof = proof;
|
|
166
204
|
this.sessions = sessions;
|
|
167
205
|
this.jwks = jwks;
|
|
206
|
+
this.effects = effects;
|
|
207
|
+
this.replaced = replaced;
|
|
208
|
+
this.acceptance = acceptance;
|
|
168
209
|
this.lastShadowReportAt = clock();
|
|
210
|
+
this.digestKey = Gateway.digestKeyOf(config);
|
|
211
|
+
this.exposure =
|
|
212
|
+
exposureLedger === null
|
|
213
|
+
? null
|
|
214
|
+
: new ExposureGate({
|
|
215
|
+
ledger: exposureLedger,
|
|
216
|
+
orgId: config.authority.tenantId,
|
|
217
|
+
actorType: config.actor.type,
|
|
218
|
+
evidence: (fields) => {
|
|
219
|
+
this.link(fields);
|
|
220
|
+
},
|
|
221
|
+
count: (outcome) => metrics.exposure.inc({ outcome }),
|
|
222
|
+
});
|
|
223
|
+
this.fingerprint = deploymentFingerprint(config, {
|
|
224
|
+
version,
|
|
225
|
+
imageDigest: workload?.digest ?? null,
|
|
226
|
+
});
|
|
227
|
+
metrics.fingerprint.set(1, { digest: this.fingerprint.digest });
|
|
228
|
+
this.actionSpace = new ActionSpaceDrift(this.fingerprint.document.action_manifest_digest, (release, decision) => this.link({
|
|
229
|
+
event: "ACTION_SPACE_DRIFT",
|
|
230
|
+
fingerprint: this.fingerprint.digest,
|
|
231
|
+
loaded: this.fingerprint.document.action_manifest_digest,
|
|
232
|
+
release,
|
|
233
|
+
decision_id: decision.decisionId,
|
|
234
|
+
}));
|
|
235
|
+
// Every first decision, observed or enforced, passes the action-space
|
|
236
|
+
// check before it is used; the check only reports.
|
|
237
|
+
const decides = this.actionSpace.observing(gate);
|
|
169
238
|
this.admitted = config.tenantKeys;
|
|
170
|
-
|
|
239
|
+
// The loader allows an intent over five minutes only for a hold the
|
|
240
|
+
// policy routes; the capture takes the window it was given.
|
|
241
|
+
this.capture = new IntentCapture({
|
|
242
|
+
audit,
|
|
243
|
+
ttlSeconds: config.intentTtlSeconds,
|
|
244
|
+
maxTtlSeconds: config.intentTtlSeconds,
|
|
245
|
+
});
|
|
246
|
+
this.holds =
|
|
247
|
+
config.holds === null
|
|
248
|
+
? new MemoryHoldStore(clock)
|
|
249
|
+
: new FileHoldStore(config.holds.dir, config.holds.keyFile, config.authority.tenantId, clock);
|
|
250
|
+
this.attempts =
|
|
251
|
+
config.holds === null
|
|
252
|
+
? new MemoryAttemptStore(clock)
|
|
253
|
+
: new FileAttemptStore(config.holds.dir, config.holds.keyFile, config.authority.tenantId, clock);
|
|
171
254
|
this.bucket = config.rateLimit === null ? null : new TokenBucket(config.rateLimit, clock);
|
|
172
255
|
this.refusals = new RefusalSampler((code) => security.emit({ event: "AUTH_FAILED", method: "tenant_key", code }), (code, count) => security.emit({ event: "AUTH_FAILED_SUPPRESSED", method: "tenant_key", code, count }));
|
|
173
256
|
// A funnel handed on keeps reporting through the gateway that made it:
|
|
@@ -184,12 +267,23 @@ export class Gateway {
|
|
|
184
267
|
});
|
|
185
268
|
this.shadow =
|
|
186
269
|
config.authority.mode === "SHADOW"
|
|
187
|
-
? new ShadowPipeline(
|
|
270
|
+
? new ShadowPipeline(decides, { audit, timeoutMs: config.authority.timeoutMs })
|
|
188
271
|
: null;
|
|
189
272
|
this.resolver =
|
|
190
273
|
config.authority.mode === "ENFORCEMENT"
|
|
191
|
-
? new EscalationResolver(config.escalation, gate, audit, {})
|
|
274
|
+
? new EscalationResolver(config.escalation, gate, audit, {}, null, decides)
|
|
192
275
|
: null;
|
|
276
|
+
const profile = this.profile();
|
|
277
|
+
// A shadow gateway changes nothing about a call, so it reads nothing for one.
|
|
278
|
+
this.reader =
|
|
279
|
+
this.resolver === null || profile === null
|
|
280
|
+
? null
|
|
281
|
+
: new TargetReader({
|
|
282
|
+
profile,
|
|
283
|
+
upstream,
|
|
284
|
+
clock,
|
|
285
|
+
failure: (error) => this.failureOf(error).code,
|
|
286
|
+
});
|
|
193
287
|
this.stopFollowing =
|
|
194
288
|
journal === null
|
|
195
289
|
? []
|
|
@@ -198,6 +292,27 @@ export class Gateway {
|
|
|
198
292
|
journal.follow(chain, security),
|
|
199
293
|
journal.follow(security.chain, security),
|
|
200
294
|
];
|
|
295
|
+
this.runs = acceptance === null ? null : new AcceptanceRuns(this.acceptanceHost(acceptance));
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* The facts-only digest key: derived from the custody file for this
|
|
299
|
+
* tenant (HKDF-SHA-256, the tenant as salt), so every replica that mounts
|
|
300
|
+
* the file derives the same key and no other use of the file's key shares
|
|
301
|
+
* it; 32 random bytes of this process's own without one. The file's
|
|
302
|
+
* contents are never logged: a refusal names the setting only.
|
|
303
|
+
*/
|
|
304
|
+
static digestKeyOf(config) {
|
|
305
|
+
const file = config.interception.digestKeyFile;
|
|
306
|
+
if (file === null)
|
|
307
|
+
return randomBytes(32);
|
|
308
|
+
let key;
|
|
309
|
+
try {
|
|
310
|
+
key = FileHoldStore.readKey(file);
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
throw new GatewayConfigError("CONFIG_INVALID", "interception.digestKeyFile", "a readable file of 32 bytes, base64 or hex");
|
|
314
|
+
}
|
|
315
|
+
return Buffer.from(hkdfSync("sha256", key, Buffer.from(config.authority.tenantId, "utf8"), DIGEST_KEY_INFO, 32));
|
|
201
316
|
}
|
|
202
317
|
/**
|
|
203
318
|
* Assembles the gateway: the secrets it needs opened, the demo authority
|
|
@@ -238,16 +353,31 @@ export class Gateway {
|
|
|
238
353
|
const securityHead = security.chain.head.seq;
|
|
239
354
|
emitter.reportRedactions((patterns) => security.emit({ event: "LEAK_SUSPECTED", patterns: [...patterns] }));
|
|
240
355
|
if (store === null && config.secrets.required.length > 0) {
|
|
241
|
-
// The upstream credential
|
|
242
|
-
//
|
|
243
|
-
|
|
244
|
-
const
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
356
|
+
// The upstream credential, the gateway token and an acceptance run's key
|
|
357
|
+
// and token are opened from the files the configuration names, and from
|
|
358
|
+
// nowhere else: never a value in the environment.
|
|
359
|
+
const { credential, gatewayToken } = config.upstream;
|
|
360
|
+
const { acceptance } = config;
|
|
361
|
+
const secretEnvironment = {
|
|
362
|
+
...env,
|
|
363
|
+
...(credential === null
|
|
364
|
+
? {}
|
|
365
|
+
: { DOWNSTREAM_CREDENTIAL: undefined, DOWNSTREAM_CREDENTIAL_FILE: credential.file }),
|
|
366
|
+
...(gatewayToken === null
|
|
367
|
+
? {}
|
|
368
|
+
: {
|
|
369
|
+
[GATEWAY_TOKEN_SECRET]: undefined,
|
|
370
|
+
[`${GATEWAY_TOKEN_SECRET}_FILE`]: gatewayToken.file,
|
|
371
|
+
}),
|
|
372
|
+
...(acceptance === null
|
|
373
|
+
? {}
|
|
374
|
+
: {
|
|
375
|
+
[ACCEPTANCE_KEY_SECRET]: undefined,
|
|
376
|
+
[`${ACCEPTANCE_KEY_SECRET}_FILE`]: acceptance.key.file,
|
|
377
|
+
[ACCEPTANCE_TOKEN_SECRET]: undefined,
|
|
378
|
+
[`${ACCEPTANCE_TOKEN_SECRET}_FILE`]: acceptance.operatorToken.file,
|
|
379
|
+
}),
|
|
380
|
+
};
|
|
251
381
|
store = CompositeSecretStore.fromEnvironment(secretEnvironment, config.secrets.required, {
|
|
252
382
|
events: security,
|
|
253
383
|
production: config.production,
|
|
@@ -272,6 +402,18 @@ export class Gateway {
|
|
|
272
402
|
}
|
|
273
403
|
});
|
|
274
404
|
}
|
|
405
|
+
if (config.upstream.gatewayToken !== null) {
|
|
406
|
+
// Likewise the gateway's own token, which the upstream may refuse every
|
|
407
|
+
// request without.
|
|
408
|
+
if (secrets === null || !secrets.has(GATEWAY_TOKEN_SECRET)) {
|
|
409
|
+
throw new SecretError("CONFIG_SECRET_MISSING", GATEWAY_TOKEN_SECRET);
|
|
410
|
+
}
|
|
411
|
+
secrets.get(GATEWAY_TOKEN_SECRET).use((value) => {
|
|
412
|
+
if (!Upstream.isHeaderValue(value.toString("utf8"))) {
|
|
413
|
+
throw new SecretError("CONFIG_SECRET_INVALID", GATEWAY_TOKEN_SECRET);
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
}
|
|
275
417
|
const demo = config.authority.kind === "LOCAL"
|
|
276
418
|
? await (dependencies.demoAuthority ?? startDemoAuthority)()
|
|
277
419
|
: null;
|
|
@@ -308,8 +450,18 @@ export class Gateway {
|
|
|
308
450
|
...(surface === null ? {} : { surface }),
|
|
309
451
|
},
|
|
310
452
|
});
|
|
311
|
-
const verifier = new DecionisGrantVerifier(connection);
|
|
312
453
|
const metrics = gatewayMetrics();
|
|
454
|
+
// The ledger is asked only for a route that releases money, through the
|
|
455
|
+
// same egress and with the same key as the authority itself.
|
|
456
|
+
const exposureLedger = !config.interception.routes.some((route) => route.exposure !== undefined)
|
|
457
|
+
? null
|
|
458
|
+
: (dependencies.exposureLedger ??
|
|
459
|
+
new DecionisExposureLedger({
|
|
460
|
+
baseUrl: authorityUrl,
|
|
461
|
+
apiKey: typeof apiKey === "string" ? () => apiKey : apiKey,
|
|
462
|
+
fetch: egress.fetch,
|
|
463
|
+
timeoutMs: config.authority.timeoutMs,
|
|
464
|
+
}));
|
|
313
465
|
// Evidence lines: always in JSON mode; in human mode to the terminal only
|
|
314
466
|
// when asked, and to the journal directory's file whenever there is one.
|
|
315
467
|
const evidenceFile = config.evidence.enabled && config.evidence.journalDir !== null
|
|
@@ -367,9 +519,14 @@ export class Gateway {
|
|
|
367
519
|
value: () => secrets.get("DOWNSTREAM_CREDENTIAL").use((value) => value.toString("utf8")),
|
|
368
520
|
},
|
|
369
521
|
}),
|
|
522
|
+
...(config.upstream.gatewayToken === null || secrets === null
|
|
523
|
+
? {}
|
|
524
|
+
: {
|
|
525
|
+
gatewayToken: () => secrets.get(GATEWAY_TOKEN_SECRET).use((value) => value.toString("utf8")),
|
|
526
|
+
}),
|
|
370
527
|
...(upstreamGuard === null ? {} : { close: () => upstreamGuard.close() }),
|
|
371
528
|
});
|
|
372
|
-
const routes =
|
|
529
|
+
const routes = RouteTable.of(config);
|
|
373
530
|
const evidence = takeUp(EVIDENCE_STREAM, continues?.evidence);
|
|
374
531
|
const chain = takeUp(GATEWAY_STREAM, continues?.gateway);
|
|
375
532
|
const audit = new AuditRecorder({
|
|
@@ -393,6 +550,15 @@ export class Gateway {
|
|
|
393
550
|
new NoneProvenanceProvider(),
|
|
394
551
|
];
|
|
395
552
|
const workload = resolveWorkload(dependencies.provenance ?? providers, { env });
|
|
553
|
+
// What the gateway reads back of a write rides on the attempt's
|
|
554
|
+
// finalization, under the verifier's own drop rule; it names the
|
|
555
|
+
// configured observer, or the boundary.
|
|
556
|
+
const effects = new EffectEvidenceRegister();
|
|
557
|
+
const verifier = new EffectAwareGrantVerifier({
|
|
558
|
+
verifier: new DecionisGrantVerifier(connection),
|
|
559
|
+
register: effects,
|
|
560
|
+
observer: { id: config.evidence.observer ?? boundary.boundaryId, version },
|
|
561
|
+
});
|
|
396
562
|
const proof = Gateway.upstreamProof(config, dependencies, security, clock, continues !== null);
|
|
397
563
|
const jwks = await Gateway.subjectKeys(config, dependencies, security);
|
|
398
564
|
const sessions = config.subject === null || jwks === null
|
|
@@ -408,7 +574,61 @@ export class Gateway {
|
|
|
408
574
|
if (head > 0)
|
|
409
575
|
security.emit({ event: "CHAIN_RESUMED", chain: stream, head });
|
|
410
576
|
}
|
|
411
|
-
|
|
577
|
+
// An acceptance run's parts (ADR 0009): its key, a client of the same
|
|
578
|
+
// authority in shadow, which decides a plan's write without forwarding
|
|
579
|
+
// it, and the second gateway its outage case runs on.
|
|
580
|
+
let acceptance = null;
|
|
581
|
+
if (config.acceptance !== null) {
|
|
582
|
+
for (const name of [ACCEPTANCE_KEY_SECRET, ACCEPTANCE_TOKEN_SECRET]) {
|
|
583
|
+
if (secrets === null || !secrets.has(name)) {
|
|
584
|
+
throw new SecretError("CONFIG_SECRET_MISSING", name);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
const shared = secrets;
|
|
588
|
+
const { kid } = config.acceptance;
|
|
589
|
+
let key;
|
|
590
|
+
try {
|
|
591
|
+
key = shared
|
|
592
|
+
.get(ACCEPTANCE_KEY_SECRET)
|
|
593
|
+
.use((value) => acceptanceSigningKey(value.toString("utf8"), kid));
|
|
594
|
+
}
|
|
595
|
+
catch {
|
|
596
|
+
throw new SecretError("CONFIG_SECRET_INVALID", ACCEPTANCE_KEY_SECRET);
|
|
597
|
+
}
|
|
598
|
+
const observer = new DecionisGate({
|
|
599
|
+
...connection,
|
|
600
|
+
mode: "SHADOW",
|
|
601
|
+
source: {
|
|
602
|
+
example: dependencies.clientExample ?? `agentsafe-gateway@${version}`,
|
|
603
|
+
...(surface === null ? {} : { surface }),
|
|
604
|
+
},
|
|
605
|
+
});
|
|
606
|
+
acceptance = {
|
|
607
|
+
key,
|
|
608
|
+
shadow: new ShadowPipeline(observer, { audit, timeoutMs: config.authority.timeoutMs }),
|
|
609
|
+
outage: async () => {
|
|
610
|
+
const recorder = recordingUpstream(routes.profile);
|
|
611
|
+
const second = await Gateway.create(Gateway.outageConfig(config), {
|
|
612
|
+
env,
|
|
613
|
+
io: { stdout: () => undefined, stderr: () => undefined, color: false },
|
|
614
|
+
authorityFetch: AUTHORITY_UNREACHABLE,
|
|
615
|
+
upstreamFetch: recorder.fetch,
|
|
616
|
+
secrets: Gateway.borrowed(shared),
|
|
617
|
+
demoAuthority: () => Promise.resolve({
|
|
618
|
+
baseUrl: "http://127.0.0.1:9",
|
|
619
|
+
apiKey: "",
|
|
620
|
+
stop: () => Promise.resolve(),
|
|
621
|
+
}),
|
|
622
|
+
clock,
|
|
623
|
+
version,
|
|
624
|
+
surface,
|
|
625
|
+
provenance: [new NoneProvenanceProvider()],
|
|
626
|
+
});
|
|
627
|
+
return { gateway: second, writes: recorder.writes };
|
|
628
|
+
},
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
const gateway = new Gateway(config, upstream, routes, audit, gate, verifier, metrics, emitLine, io, security, secrets, demo, journal, evidence, chain, clock, version, surface, boundary, workload, continues?.activation ?? null, proof, sessions, jwks, effects, continues?.fingerprint ?? null, acceptance, exposureLedger);
|
|
412
632
|
jwks?.start();
|
|
413
633
|
// The first look at the proof starts once nothing can refuse the gateway;
|
|
414
634
|
// a gateway built to replace another takes the proof over at the swap.
|
|
@@ -447,12 +667,6 @@ export class Gateway {
|
|
|
447
667
|
});
|
|
448
668
|
return { binding, check, monitor, takesOver };
|
|
449
669
|
}
|
|
450
|
-
/** What the gateway does with reads: checked only when it pins subjects. */
|
|
451
|
-
static readPolicy(config) {
|
|
452
|
-
if (config.subject === null)
|
|
453
|
-
return "PASSTHROUGH";
|
|
454
|
-
return config.interception.refuseUnknownReads ? "REFUSE_UNKNOWN" : "CHECK";
|
|
455
|
-
}
|
|
456
670
|
/**
|
|
457
671
|
* The identity provider's key set, when the gateway pins subjects: the file
|
|
458
672
|
* when there is one, else one fetch from the address at start, refused by
|
|
@@ -570,6 +784,14 @@ export class Gateway {
|
|
|
570
784
|
mode: this.config.authority.mode,
|
|
571
785
|
authority: this.demo === null ? "decionis" : "local/demo",
|
|
572
786
|
});
|
|
787
|
+
// On start, and on a reload only when the deployment changed.
|
|
788
|
+
if (this.fingerprint.digest !== this.replaced) {
|
|
789
|
+
this.link({
|
|
790
|
+
event: "DEPLOYMENT_FINGERPRINT",
|
|
791
|
+
digest: this.fingerprint.digest,
|
|
792
|
+
document: this.fingerprint.document,
|
|
793
|
+
});
|
|
794
|
+
}
|
|
573
795
|
this.activation.started({
|
|
574
796
|
mode: this.config.authority.mode,
|
|
575
797
|
authority: this.config.authority.kind,
|
|
@@ -642,12 +864,17 @@ export class Gateway {
|
|
|
642
864
|
failure_policy: this.config.authority.failurePolicy,
|
|
643
865
|
upstream: this.config.upstream.url,
|
|
644
866
|
routes: this.config.interception.routes.length,
|
|
645
|
-
held: this.
|
|
867
|
+
held: this.holds.sweep(),
|
|
646
868
|
counts: { ...this.counts },
|
|
647
869
|
evidence: this.evidence.head,
|
|
648
870
|
activation: this.activation.snapshot(),
|
|
649
871
|
surface: this.surface,
|
|
650
872
|
shadow: this.shadow === null ? null : this.ledger.summary(),
|
|
873
|
+
fingerprint: { digest: this.fingerprint.digest, document: this.fingerprint.document },
|
|
874
|
+
action_space: this.actionSpace.status(),
|
|
875
|
+
acceptance: this.acceptance === null
|
|
876
|
+
? null
|
|
877
|
+
: { kid: this.acceptance.key.kid, public_jwk: this.acceptance.key.publicJwk },
|
|
651
878
|
hosted: this.config.hosted
|
|
652
879
|
? {
|
|
653
880
|
tenant: this.config.hostedTenant,
|
|
@@ -658,6 +885,7 @@ export class Gateway {
|
|
|
658
885
|
upstream_credential: this.config.upstream.credential === null
|
|
659
886
|
? null
|
|
660
887
|
: { header: this.config.upstream.credential.header },
|
|
888
|
+
gateway_token: this.config.upstream.gatewayToken !== null,
|
|
661
889
|
}
|
|
662
890
|
: null,
|
|
663
891
|
};
|
|
@@ -687,6 +915,7 @@ export class Gateway {
|
|
|
687
915
|
gateway: this.chain,
|
|
688
916
|
security: this.security.chain,
|
|
689
917
|
activation: this.activation,
|
|
918
|
+
fingerprint: this.fingerprint.digest,
|
|
690
919
|
};
|
|
691
920
|
}
|
|
692
921
|
/**
|
|
@@ -764,6 +993,7 @@ export class Gateway {
|
|
|
764
993
|
return enforcementSwitch(this.config);
|
|
765
994
|
}
|
|
766
995
|
metricsText() {
|
|
996
|
+
this.metrics.actionSpaceDrift.set(this.actionSpace.state === "DRIFT" ? 1 : 0);
|
|
767
997
|
return this.metrics.registry.render();
|
|
768
998
|
}
|
|
769
999
|
/**
|
|
@@ -799,9 +1029,33 @@ export class Gateway {
|
|
|
799
1029
|
this.answerScopes.set(request, { session, operation: scoped.id, action });
|
|
800
1030
|
}
|
|
801
1031
|
}
|
|
1032
|
+
// A key that promised another operation is refused before anything,
|
|
1033
|
+
// the target read included, reaches the upstream.
|
|
1034
|
+
const retry = this.retryLink(request);
|
|
1035
|
+
if (retry !== null && retry.retryOf !== null && retry.retryOf.requestDigest !== retry.digest) {
|
|
1036
|
+
return this.keyReused(request, action, retry.retryOf);
|
|
1037
|
+
}
|
|
1038
|
+
const retryOf = retry?.retryOf ?? null;
|
|
1039
|
+
const target = await this.targetPlan(request, action);
|
|
1040
|
+
if (target !== null && "reasonCodes" in target) {
|
|
1041
|
+
return this.targetUnreadable(request, action, target);
|
|
1042
|
+
}
|
|
1043
|
+
// A payment whose amount, currency or subject cannot be read cannot be
|
|
1044
|
+
// counted, so it is refused before anyone is asked; in shadow it goes
|
|
1045
|
+
// through as everything does, and the observation says so.
|
|
1046
|
+
const money = this.moneyOf(request);
|
|
1047
|
+
if (money !== null && !money.facts.ok && this.shadow === null) {
|
|
1048
|
+
this.metrics.exposure.inc({ outcome: "UNREADABLE" });
|
|
1049
|
+
return this.own(400, {
|
|
1050
|
+
state: "ERROR",
|
|
1051
|
+
verdict: null,
|
|
1052
|
+
reason_codes: [money.facts.code],
|
|
1053
|
+
execution: "NOT_FORWARDED",
|
|
1054
|
+
});
|
|
1055
|
+
}
|
|
802
1056
|
let captured;
|
|
803
1057
|
try {
|
|
804
|
-
captured = this.captureIntent(request, action, session);
|
|
1058
|
+
captured = this.captureIntent(request, action, session, target, retryOf);
|
|
805
1059
|
}
|
|
806
1060
|
catch (error) {
|
|
807
1061
|
const code = error instanceof Error ? error.message : "INTENT_INVALID";
|
|
@@ -812,13 +1066,98 @@ export class Gateway {
|
|
|
812
1066
|
execution: "NOT_FORWARDED",
|
|
813
1067
|
});
|
|
814
1068
|
}
|
|
1069
|
+
if (target !== null)
|
|
1070
|
+
this.plans.set(captured, target);
|
|
1071
|
+
const accepted = this.acceptanceWrites.get(request);
|
|
1072
|
+
if (accepted !== undefined)
|
|
1073
|
+
this.runs?.captured(accepted, captured.intent.intentId);
|
|
815
1074
|
this.metrics.interceptions.inc({ action });
|
|
816
1075
|
this.count("interceptions");
|
|
817
1076
|
this.activation.intercepted();
|
|
818
1077
|
return await RequestContext.run({ principal: this.principalOf(captured) }, async () => {
|
|
819
1078
|
if (this.shadow !== null)
|
|
820
1079
|
return await this.observe(request, captured, startedAt);
|
|
821
|
-
|
|
1080
|
+
const answer = await this.enforce(request, captured, startedAt);
|
|
1081
|
+
if (retryOf === null || retryOf.dossierId === null)
|
|
1082
|
+
return answer;
|
|
1083
|
+
return { ...answer, headers: [...answer.headers, [RETRY_OF_HEADER, retryOf.dossierId]] };
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
/**
|
|
1087
|
+
* Where an enforced request stands among its idempotency key's attempts:
|
|
1088
|
+
* null without a key, or in shadow, which forwards every request as it
|
|
1089
|
+
* came and so links none.
|
|
1090
|
+
*/
|
|
1091
|
+
retryLink(request) {
|
|
1092
|
+
if (this.resolver === null)
|
|
1093
|
+
return null;
|
|
1094
|
+
const key = idempotencyKeyOf(request);
|
|
1095
|
+
if (key === null)
|
|
1096
|
+
return null;
|
|
1097
|
+
return { key, digest: retryDigest(request), retryOf: this.attempts.find(key) ?? null };
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* The same idempotency key with another request, while the key's last
|
|
1101
|
+
* attempt is INDETERMINATE: the key promised one operation, which may
|
|
1102
|
+
* already have happened, so this one is refused and never forwarded.
|
|
1103
|
+
*/
|
|
1104
|
+
keyReused(request, action, earlier) {
|
|
1105
|
+
this.metrics.requests.inc({ kind: "idempotency_key_reused" });
|
|
1106
|
+
this.count("idempotency_key_reused");
|
|
1107
|
+
this.link({
|
|
1108
|
+
event: "IDEMPOTENCY_KEY_REUSED",
|
|
1109
|
+
method: request.method.toUpperCase(),
|
|
1110
|
+
path: request.path,
|
|
1111
|
+
action,
|
|
1112
|
+
retry_of_intent_id: earlier.intentId,
|
|
1113
|
+
retry_of_dossier_id: earlier.dossierId,
|
|
1114
|
+
});
|
|
1115
|
+
return this.own(409, {
|
|
1116
|
+
state: "ERROR",
|
|
1117
|
+
verdict: null,
|
|
1118
|
+
reason_codes: ["IDEMPOTENCY_KEY_REUSED"],
|
|
1119
|
+
execution: "NOT_FORWARDED",
|
|
1120
|
+
});
|
|
1121
|
+
}
|
|
1122
|
+
/**
|
|
1123
|
+
* The reservation key of the INDETERMINATE attempt this request retries:
|
|
1124
|
+
* the same idempotency key and the same request, so the same payment.
|
|
1125
|
+
* Undefined when it retries none, or none that reserved.
|
|
1126
|
+
*/
|
|
1127
|
+
retriedReservation(request) {
|
|
1128
|
+
const key = idempotencyKeyOf(request);
|
|
1129
|
+
if (key === null)
|
|
1130
|
+
return undefined;
|
|
1131
|
+
const earlier = this.attempts.find(key);
|
|
1132
|
+
if (earlier === undefined || earlier.requestDigest !== retryDigest(request))
|
|
1133
|
+
return undefined;
|
|
1134
|
+
return earlier.reservationKey;
|
|
1135
|
+
}
|
|
1136
|
+
/**
|
|
1137
|
+
* After an enforced execution, what its idempotency key remembers: an
|
|
1138
|
+
* INDETERMINATE attempt is recorded for a retry to be linked to; a
|
|
1139
|
+
* definite outcome (forwarded and answered, or answered with a refusal)
|
|
1140
|
+
* settles the key, so a later request is not linked to an attempt that
|
|
1141
|
+
* is no longer unknown. Anything that sent nothing leaves the record.
|
|
1142
|
+
*/
|
|
1143
|
+
settleAttempt(request, captured, decision, outcome, reservationKey) {
|
|
1144
|
+
const key = idempotencyKeyOf(request);
|
|
1145
|
+
if (key === null)
|
|
1146
|
+
return;
|
|
1147
|
+
const digest = retryDigest(request);
|
|
1148
|
+
if (outcome === "DEFINITE") {
|
|
1149
|
+
this.attempts.forget(key, digest);
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
const now = this.clock();
|
|
1153
|
+
this.attempts.record(key, {
|
|
1154
|
+
requestDigest: digest,
|
|
1155
|
+
intentId: captured.intent.intentId,
|
|
1156
|
+
decisionId: decision.decisionId,
|
|
1157
|
+
dossierId: decision.dossierId,
|
|
1158
|
+
...(reservationKey === undefined ? {} : { reservationKey }),
|
|
1159
|
+
recordedAt: new Date(now).toISOString(),
|
|
1160
|
+
expiresAt: now + ATTEMPT_TTL_MS,
|
|
822
1161
|
});
|
|
823
1162
|
}
|
|
824
1163
|
/**
|
|
@@ -916,8 +1255,8 @@ export class Gateway {
|
|
|
916
1255
|
escalation: resolution.handoff,
|
|
917
1256
|
});
|
|
918
1257
|
}
|
|
919
|
-
this.release(intentId);
|
|
920
1258
|
if (resolution.kind === "REFUSED") {
|
|
1259
|
+
this.release(intentId);
|
|
921
1260
|
const state = resolution.failClosed ? "AUTHORITY_UNAVAILABLE" : "BLOCK";
|
|
922
1261
|
this.link({
|
|
923
1262
|
event: "ESCALATION_REFUSED",
|
|
@@ -933,29 +1272,247 @@ export class Gateway {
|
|
|
933
1272
|
intent_id: intentId,
|
|
934
1273
|
});
|
|
935
1274
|
}
|
|
936
|
-
|
|
1275
|
+
// One resume runs the request: another replica, or a second call, that
|
|
1276
|
+
// reaches this point for the same hold finds it already taken.
|
|
1277
|
+
const claimed = this.holds.claim(intentId);
|
|
1278
|
+
this.metrics.held.set(this.holds.sweep());
|
|
1279
|
+
if (claimed === undefined) {
|
|
1280
|
+
return this.own(409, {
|
|
1281
|
+
state: "ERROR",
|
|
1282
|
+
verdict: null,
|
|
1283
|
+
reason_codes: ["ESCALATION_ALREADY_RESUMED"],
|
|
1284
|
+
execution: "NOT_FORWARDED",
|
|
1285
|
+
intent_id: intentId,
|
|
1286
|
+
});
|
|
1287
|
+
}
|
|
1288
|
+
return await RequestContext.run({ principal: this.principalOf(claimed.captured) }, () => this.execute(claimed.request, claimed.captured, resolution.decision, startedAt, null));
|
|
937
1289
|
}
|
|
938
1290
|
async close() {
|
|
1291
|
+
// A refusal's read finishes before what it reads with is closed.
|
|
1292
|
+
await Promise.allSettled([...this.observing]);
|
|
939
1293
|
this.refusals.flush();
|
|
940
1294
|
this.handedOn();
|
|
941
1295
|
this.proof?.check.close();
|
|
942
1296
|
this.jwks?.stop();
|
|
943
|
-
this.
|
|
1297
|
+
this.holds.close();
|
|
1298
|
+
this.attempts.close();
|
|
944
1299
|
if (this.demo !== null)
|
|
945
1300
|
await this.demo.stop();
|
|
946
1301
|
this.secrets?.close();
|
|
947
1302
|
this.upstream.close();
|
|
948
1303
|
}
|
|
949
|
-
|
|
1304
|
+
/** Whether this gateway serves acceptance runs: its configuration names their key and token. */
|
|
1305
|
+
get servesAcceptance() {
|
|
1306
|
+
return this.runs !== null;
|
|
1307
|
+
}
|
|
1308
|
+
/**
|
|
1309
|
+
* Whether a bearer is the acceptance runs' operator token: compared by
|
|
1310
|
+
* digest, in constant time, against the file as it is now, so a rotated
|
|
1311
|
+
* token takes effect at once. Never an agent's credential.
|
|
1312
|
+
*/
|
|
1313
|
+
acceptanceToken(presented) {
|
|
1314
|
+
if (this.runs === null || this.secrets === null || presented === undefined)
|
|
1315
|
+
return false;
|
|
1316
|
+
const given = createHash("sha256").update(presented).digest();
|
|
1317
|
+
return this.secrets
|
|
1318
|
+
.get(ACCEPTANCE_TOKEN_SECRET)
|
|
1319
|
+
.use((value) => timingSafeEqual(given, createHash("sha256").update(value).digest()));
|
|
1320
|
+
}
|
|
1321
|
+
openAcceptance(body) {
|
|
1322
|
+
return this.runs?.open(body) ?? { status: 404, body: { code: "NOT_FOUND" } };
|
|
1323
|
+
}
|
|
1324
|
+
async decideAcceptance(runId, write) {
|
|
1325
|
+
return (await this.runs?.decide(runId, write)) ?? { status: 404, body: { code: "NOT_FOUND" } };
|
|
1326
|
+
}
|
|
1327
|
+
async closeAcceptance(runId, zone) {
|
|
1328
|
+
return (await this.runs?.close(runId, zone)) ?? { status: 404, body: { code: "NOT_FOUND" } };
|
|
1329
|
+
}
|
|
1330
|
+
/**
|
|
1331
|
+
* Whether a request carrying the run header is a write the open run names,
|
|
1332
|
+
* sent as named: tracked when it is, refused when it is not. A gateway that
|
|
1333
|
+
* serves no run refuses every request carrying the header.
|
|
1334
|
+
*/
|
|
1335
|
+
admitAcceptance(request, tag) {
|
|
1336
|
+
if (tag === undefined)
|
|
1337
|
+
return { kind: "NONE" };
|
|
1338
|
+
if (this.runs === null)
|
|
1339
|
+
return { kind: "REFUSE", code: "ACCEPTANCE_RUN_UNKNOWN" };
|
|
1340
|
+
const admission = this.runs.admit(tag, request);
|
|
1341
|
+
if (admission.kind === "TRACK")
|
|
1342
|
+
this.acceptanceWrites.set(request, admission.name);
|
|
1343
|
+
return admission;
|
|
1344
|
+
}
|
|
1345
|
+
/** The answer to a write a run sent, for one the gateway refused before capturing it. */
|
|
1346
|
+
answeredAcceptance(request, answer) {
|
|
1347
|
+
const name = this.acceptanceWrites.get(request);
|
|
1348
|
+
if (name === undefined)
|
|
1349
|
+
return;
|
|
1350
|
+
const header = (key) => answer.headers.find(([candidate]) => candidate === key)?.[1] ?? null;
|
|
1351
|
+
this.runs?.answered(name, header("agentsafe-state"), header("agentsafe-execution"));
|
|
1352
|
+
}
|
|
1353
|
+
/** What this gateway lends a run: its routes, its reads, its chain and its key. */
|
|
1354
|
+
acceptanceHost(parts) {
|
|
1355
|
+
return {
|
|
1356
|
+
boundaryId: this.boundary.boundaryId,
|
|
1357
|
+
fingerprint: this.fingerprint,
|
|
1358
|
+
failurePolicy: this.config.authority.failurePolicy,
|
|
1359
|
+
coverage: coverageOf(this.routes, this.config),
|
|
1360
|
+
route: (write) => this.acceptanceRoute(write),
|
|
1361
|
+
decide: async (write) => await this.acceptanceDecide(parts.shadow, write),
|
|
1362
|
+
outage: async (write) => await Gateway.acceptanceOutage(parts, write),
|
|
1363
|
+
settled: async () => {
|
|
1364
|
+
await Promise.allSettled([...this.observing]);
|
|
1365
|
+
},
|
|
1366
|
+
link: (fields) => this.link(fields),
|
|
1367
|
+
sign: async (report) => await signAcceptanceReport(report, parts.key),
|
|
1368
|
+
clock: this.clock,
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
/** A plan's write as the listener would have handed it over. */
|
|
1372
|
+
static acceptanceRequest(write) {
|
|
1373
|
+
const { path, search } = splitTarget(write.path);
|
|
1374
|
+
const body = writeBody(write);
|
|
1375
|
+
return {
|
|
1376
|
+
method: write.method,
|
|
1377
|
+
path,
|
|
1378
|
+
search,
|
|
1379
|
+
headers: body.length === 0 ? {} : { "content-type": "application/json" },
|
|
1380
|
+
body,
|
|
1381
|
+
remoteAddress: null,
|
|
1382
|
+
encrypted: false,
|
|
1383
|
+
};
|
|
1384
|
+
}
|
|
1385
|
+
acceptanceRoute(write) {
|
|
1386
|
+
const request = Gateway.acceptanceRequest(write);
|
|
1387
|
+
const plan = this.plan(request.method, request.path, request.search);
|
|
1388
|
+
if (plan.kind !== "GOVERN")
|
|
1389
|
+
return { enforced: false, action: null, targetRead: false };
|
|
1390
|
+
const api = this.profileRequest(request);
|
|
1391
|
+
return {
|
|
1392
|
+
enforced: this.resolver !== null,
|
|
1393
|
+
action: plan.action,
|
|
1394
|
+
targetRead: api !== null && this.profile()?.stateRead(api) != null,
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
/**
|
|
1398
|
+
* A plan's write decided in shadow: captured as its route captures it, with
|
|
1399
|
+
* no read of its target, asked of the authority in shadow, and forwarded
|
|
1400
|
+
* nowhere. The shadow pipeline records the decision on the evidence chain.
|
|
1401
|
+
*/
|
|
1402
|
+
async acceptanceDecide(shadow, write) {
|
|
1403
|
+
const request = Gateway.acceptanceRequest(write);
|
|
1404
|
+
const plan = this.plan(request.method, request.path, request.search);
|
|
1405
|
+
const undecided = (code) => ({
|
|
1406
|
+
verdict: null,
|
|
1407
|
+
reason_codes: [code],
|
|
1408
|
+
decision_id: null,
|
|
1409
|
+
dossier_id: null,
|
|
1410
|
+
});
|
|
1411
|
+
if (plan.kind !== "GOVERN")
|
|
1412
|
+
return undecided("ACCEPTANCE_WRITE_NOT_GOVERNED");
|
|
1413
|
+
let captured;
|
|
1414
|
+
try {
|
|
1415
|
+
captured = this.captureIntent(request, plan.action, null, null, null);
|
|
1416
|
+
}
|
|
1417
|
+
catch (error) {
|
|
1418
|
+
return undecided(error instanceof Error ? error.message : "INTENT_INVALID");
|
|
1419
|
+
}
|
|
1420
|
+
const observation = await RequestContext.run({ principal: this.principalOf(captured) }, async () => await (await shadow.observe(captured, () => Promise.resolve(null))).observation);
|
|
1421
|
+
return {
|
|
1422
|
+
verdict: observation.verdict,
|
|
1423
|
+
reason_codes: [
|
|
1424
|
+
...(observation.status === "OBSERVED" ? [] : [observation.status]),
|
|
1425
|
+
...observation.reasonCodes,
|
|
1426
|
+
],
|
|
1427
|
+
decision_id: observation.decisionId,
|
|
1428
|
+
dossier_id: observation.dossierId,
|
|
1429
|
+
};
|
|
1430
|
+
}
|
|
1431
|
+
/**
|
|
1432
|
+
* A plan's write through a second gateway built from this configuration,
|
|
1433
|
+
* its authority unreachable and its upstream recording, closed after: what
|
|
1434
|
+
* it answered, and how many writes reached its upstream.
|
|
1435
|
+
*/
|
|
1436
|
+
static async acceptanceOutage(parts, write) {
|
|
1437
|
+
let second;
|
|
1438
|
+
try {
|
|
1439
|
+
second = await parts.outage();
|
|
1440
|
+
}
|
|
1441
|
+
catch {
|
|
1442
|
+
return {
|
|
1443
|
+
status: null,
|
|
1444
|
+
execution: null,
|
|
1445
|
+
reason_codes: ["ACCEPTANCE_OUTAGE_UNAVAILABLE"],
|
|
1446
|
+
upstreamWrites: 0,
|
|
1447
|
+
};
|
|
1448
|
+
}
|
|
1449
|
+
try {
|
|
1450
|
+
const request = Gateway.acceptanceRequest(write);
|
|
1451
|
+
const plan = second.gateway.plan(request.method, request.path, request.search);
|
|
1452
|
+
const answer = plan.kind === "GOVERN"
|
|
1453
|
+
? await second.gateway.govern(request, plan.action)
|
|
1454
|
+
: await second.gateway.passthrough(request);
|
|
1455
|
+
let reasonCodes = [];
|
|
1456
|
+
try {
|
|
1457
|
+
const body = JSON.parse(answer.body.toString("utf8"));
|
|
1458
|
+
if (Array.isArray(body.reason_codes)) {
|
|
1459
|
+
reasonCodes = body.reason_codes.filter((code) => typeof code === "string");
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
catch {
|
|
1463
|
+
// An answer that is not the gateway's own JSON carries no reason codes.
|
|
1464
|
+
}
|
|
1465
|
+
return {
|
|
1466
|
+
status: answer.status,
|
|
1467
|
+
execution: answer.headers.find(([name]) => name === "agentsafe-execution")?.[1] ?? null,
|
|
1468
|
+
reason_codes: reasonCodes,
|
|
1469
|
+
upstreamWrites: second.writes(),
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
finally {
|
|
1473
|
+
await second.gateway.close();
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
/**
|
|
1477
|
+
* The configuration the outage case's second gateway is built from: this
|
|
1478
|
+
* one, with nothing it could write to or wait on outside the process. No
|
|
1479
|
+
* evidence file or journal (the deployed gateway's chains are its own), no
|
|
1480
|
+
* upstream proof or public-only resolution, no subject keys to fetch, no
|
|
1481
|
+
* reads after a refusal, and no acceptance runs of its own.
|
|
1482
|
+
*/
|
|
1483
|
+
static outageConfig(config) {
|
|
1484
|
+
return {
|
|
1485
|
+
...config,
|
|
1486
|
+
upstream: { ...config.upstream, proofRequired: false, publicOnly: false },
|
|
1487
|
+
interception: { ...config.interception, observeRefusals: false },
|
|
1488
|
+
subject: null,
|
|
1489
|
+
evidence: { ...config.evidence, enabled: false, journalDir: null },
|
|
1490
|
+
output: { format: "JSON", verbose: false },
|
|
1491
|
+
acceptance: null,
|
|
1492
|
+
};
|
|
1493
|
+
}
|
|
1494
|
+
/** The deployed gateway's secrets, lent: the second gateway reads them and never closes them. */
|
|
1495
|
+
static borrowed(store) {
|
|
1496
|
+
return {
|
|
1497
|
+
has: (name) => store.has(name),
|
|
1498
|
+
get: (name) => store.get(name),
|
|
1499
|
+
onRotate: (name, listener) => store.onRotate(name, listener),
|
|
1500
|
+
reload: async (reason) => await store.reload(reason),
|
|
1501
|
+
close: () => undefined,
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1504
|
+
captureIntent(request, action, session, target, retryOf) {
|
|
950
1505
|
if (this.config.interception.privacy === "FACTS") {
|
|
951
|
-
return this.captureFacts(request, action, session);
|
|
1506
|
+
return this.captureFacts(request, action, session, target, retryOf);
|
|
952
1507
|
}
|
|
953
1508
|
const plan = this.plan(request.method, request.path, request.search);
|
|
954
1509
|
const route = plan.kind === "GOVERN" ? plan.route : null;
|
|
955
1510
|
// A caller of govern() cannot change the action to evade a route's
|
|
956
1511
|
// policy pin. The HTTP listener already uses the route's action.
|
|
957
1512
|
if (route !== null &&
|
|
958
|
-
(route.policyId !== undefined ||
|
|
1513
|
+
(route.policyId !== undefined ||
|
|
1514
|
+
route.policyVersion !== undefined ||
|
|
1515
|
+
route.exposure !== undefined) &&
|
|
959
1516
|
route.action !== action) {
|
|
960
1517
|
throw new Error("ROUTE_ACTION_MISMATCH");
|
|
961
1518
|
}
|
|
@@ -980,6 +1537,7 @@ export class Gateway {
|
|
|
980
1537
|
...(normalized.principal === null ? {} : { claimed_principal: normalized.principal }),
|
|
981
1538
|
...this.profileFacts(request, action),
|
|
982
1539
|
...Gateway.sessionContext(session),
|
|
1540
|
+
...Gateway.retryContext(retryOf),
|
|
983
1541
|
},
|
|
984
1542
|
idempotencyKey: normalized.idempotencyKey ?? randomUUID(),
|
|
985
1543
|
...(normalized.correlationId === null ? {} : { correlationId: normalized.correlationId }),
|
|
@@ -987,6 +1545,7 @@ export class Gateway {
|
|
|
987
1545
|
boundary: boundarySignal(this.boundary),
|
|
988
1546
|
...(this.workload === null ? {} : { workload: this.workload }),
|
|
989
1547
|
},
|
|
1548
|
+
...Gateway.targetBinding(target),
|
|
990
1549
|
};
|
|
991
1550
|
return this.capture.capture(normalized.proposal, trusted);
|
|
992
1551
|
}
|
|
@@ -997,7 +1556,7 @@ export class Gateway {
|
|
|
997
1556
|
* of the request is in the intent; a call the profile does not describe
|
|
998
1557
|
* never reaches here, because the route table refused it.
|
|
999
1558
|
*/
|
|
1000
|
-
captureFacts(request, action, session) {
|
|
1559
|
+
captureFacts(request, action, session, target, retryOf) {
|
|
1001
1560
|
const matched = this.profileMatch(request);
|
|
1002
1561
|
const operation = matched === null ? null : (this.profile()?.operation(matched.operation) ?? null);
|
|
1003
1562
|
if (matched === null || operation === null || matched.action !== action) {
|
|
@@ -1019,20 +1578,143 @@ export class Gateway {
|
|
|
1019
1578
|
...matched.facts,
|
|
1020
1579
|
api_profile: { id: matched.profile, operation: matched.operation },
|
|
1021
1580
|
...Gateway.sessionContext(session),
|
|
1581
|
+
...Gateway.retryContext(retryOf),
|
|
1022
1582
|
},
|
|
1023
1583
|
idempotencyKey: normalized.idempotencyKey ?? randomUUID(),
|
|
1024
1584
|
signals: {
|
|
1025
1585
|
boundary: boundarySignal(this.boundary),
|
|
1026
1586
|
...(this.workload === null ? {} : { workload: this.workload }),
|
|
1027
1587
|
},
|
|
1588
|
+
...Gateway.targetBinding(target),
|
|
1028
1589
|
};
|
|
1029
1590
|
return this.capture.capture(normalized.proposal, trusted);
|
|
1030
1591
|
}
|
|
1592
|
+
/**
|
|
1593
|
+
* What a captured write binds of its target, exactly as an executor binds
|
|
1594
|
+
* it: the version read before the authority is asked, stamped by the
|
|
1595
|
+
* capture into the hashed context as `agent_safe.precondition`, and the
|
|
1596
|
+
* digest of the effect the call asks for, which the grant then commits to.
|
|
1597
|
+
* Nothing for a write whose operation names no read.
|
|
1598
|
+
*/
|
|
1599
|
+
static targetBinding(target) {
|
|
1600
|
+
if (target === null)
|
|
1601
|
+
return {};
|
|
1602
|
+
return {
|
|
1603
|
+
precondition: target.precondition,
|
|
1604
|
+
...(typeof target.effect === "string" ? {} : { expectedEffectDigest: target.effect.digest }),
|
|
1605
|
+
};
|
|
1606
|
+
}
|
|
1607
|
+
/**
|
|
1608
|
+
* The read a profiled write's operation names, made before the authority
|
|
1609
|
+
* is asked, in enforcement only; null when there is none to make: no
|
|
1610
|
+
* profile, a call the profile does not name as this action, or an
|
|
1611
|
+
* operation that names no read.
|
|
1612
|
+
*/
|
|
1613
|
+
async targetPlan(request, action) {
|
|
1614
|
+
if (this.reader === null)
|
|
1615
|
+
return null;
|
|
1616
|
+
const call = this.profileRequest(request);
|
|
1617
|
+
const matched = call === null ? null : (this.profile()?.match(call) ?? null);
|
|
1618
|
+
if (call === null || matched === null || matched.action !== action)
|
|
1619
|
+
return null;
|
|
1620
|
+
return await this.reader.plan(matched.operation, call, this.config.interception.privacy === "FACTS");
|
|
1621
|
+
}
|
|
1622
|
+
/**
|
|
1623
|
+
* A write whose target stated no usable version: refused before the
|
|
1624
|
+
* authority is asked, as an executor's is, rather than decided against no
|
|
1625
|
+
* version at all. A report line, a line on the evidence chain naming the
|
|
1626
|
+
* reason, and the gateway's own `502`, since it is the upstream's answer
|
|
1627
|
+
* that could not be read.
|
|
1628
|
+
*/
|
|
1629
|
+
targetUnreadable(request, action, refusal) {
|
|
1630
|
+
this.metrics.requests.inc({ kind: "target_state_unreadable" });
|
|
1631
|
+
this.count("target_state_unreadable");
|
|
1632
|
+
this.link({
|
|
1633
|
+
event: "TARGET_STATE_UNREADABLE",
|
|
1634
|
+
action,
|
|
1635
|
+
reason_codes: [...refusal.reasonCodes],
|
|
1636
|
+
});
|
|
1637
|
+
this.report({
|
|
1638
|
+
event: "INTERCEPTED",
|
|
1639
|
+
at: new Date(this.clock()).toISOString(),
|
|
1640
|
+
method: request.method.toUpperCase(),
|
|
1641
|
+
path: request.path,
|
|
1642
|
+
action,
|
|
1643
|
+
state: "ERROR",
|
|
1644
|
+
verdict: null,
|
|
1645
|
+
reason_codes: refusal.reasonCodes,
|
|
1646
|
+
execution: "NOT_FORWARDED",
|
|
1647
|
+
mode: this.config.authority.mode,
|
|
1648
|
+
authority: this.demo === null ? "decionis" : "local/demo",
|
|
1649
|
+
intent_id: null,
|
|
1650
|
+
intent_hash: null,
|
|
1651
|
+
decision_id: null,
|
|
1652
|
+
dossier_id: null,
|
|
1653
|
+
upstream_status: null,
|
|
1654
|
+
finalization: null,
|
|
1655
|
+
latency_ms: 0,
|
|
1656
|
+
authority_ms: null,
|
|
1657
|
+
});
|
|
1658
|
+
return this.own(502, {
|
|
1659
|
+
state: "ERROR",
|
|
1660
|
+
verdict: null,
|
|
1661
|
+
reason_codes: refusal.reasonCodes,
|
|
1662
|
+
execution: "NOT_FORWARDED",
|
|
1663
|
+
});
|
|
1664
|
+
}
|
|
1665
|
+
/**
|
|
1666
|
+
* After a refusal of a write whose operation names a read: the target read
|
|
1667
|
+
* again once the window has passed, and a chained `REFUSAL_OBSERVATION`
|
|
1668
|
+
* naming the version before the decision, the version after and both
|
|
1669
|
+
* instants. An unchanged version says no write landed on that resource
|
|
1670
|
+
* between the two reads, by any route; nothing about another resource or
|
|
1671
|
+
* another time. The caller's answer never waits for it; the stop does.
|
|
1672
|
+
*/
|
|
1673
|
+
observeRefusal(captured, refusal) {
|
|
1674
|
+
const plan = this.plans.get(captured);
|
|
1675
|
+
const reader = this.reader;
|
|
1676
|
+
if (plan === undefined || reader === null || !this.config.interception.observeRefusals)
|
|
1677
|
+
return;
|
|
1678
|
+
const window = this.config.interception.refusalWindowMs;
|
|
1679
|
+
const observation = (async () => {
|
|
1680
|
+
await new Promise((resolve) => setTimeout(resolve, window).unref());
|
|
1681
|
+
const read = await reader.refusal(plan);
|
|
1682
|
+
this.metrics.refusalObservations.inc({ outcome: read.outcome });
|
|
1683
|
+
this.link({
|
|
1684
|
+
event: "REFUSAL_OBSERVATION",
|
|
1685
|
+
intent_id: captured.intent.intentId,
|
|
1686
|
+
intent_hash: captured.intentHash,
|
|
1687
|
+
refusal,
|
|
1688
|
+
operation: plan.operation,
|
|
1689
|
+
source: plan.precondition.source,
|
|
1690
|
+
outcome: read.outcome,
|
|
1691
|
+
version_before: plan.precondition.version,
|
|
1692
|
+
version_after: read.version,
|
|
1693
|
+
read_before_at: plan.precondition.read_at,
|
|
1694
|
+
read_after_at: read.readAt,
|
|
1695
|
+
});
|
|
1696
|
+
})();
|
|
1697
|
+
const settle = () => {
|
|
1698
|
+
this.observing.delete(observation);
|
|
1699
|
+
};
|
|
1700
|
+
this.observing.add(observation);
|
|
1701
|
+
void observation.then(settle, settle);
|
|
1702
|
+
}
|
|
1031
1703
|
/**
|
|
1032
1704
|
* The pinned subject as the authority reads it: the fact `session.subject`.
|
|
1033
1705
|
* A verified claim of the identity provider, never a value of the request;
|
|
1034
1706
|
* absent, never null, when the request presented no session.
|
|
1035
1707
|
*/
|
|
1708
|
+
/**
|
|
1709
|
+
* What the intent says of the INDETERMINATE attempt it retries: that
|
|
1710
|
+
* attempt's dossier, so policy can decide a retry of a write that may
|
|
1711
|
+
* already have happened, and the new dossier names the earlier one.
|
|
1712
|
+
*/
|
|
1713
|
+
static retryContext(retryOf) {
|
|
1714
|
+
return retryOf === null
|
|
1715
|
+
? {}
|
|
1716
|
+
: { retry_of: { dossier_id: retryOf.dossierId, outcome: "INDETERMINATE" } };
|
|
1717
|
+
}
|
|
1036
1718
|
static sessionContext(session) {
|
|
1037
1719
|
return session === null ? {} : { session: { subject: session.subject } };
|
|
1038
1720
|
}
|
|
@@ -1290,8 +1972,12 @@ export class Gateway {
|
|
|
1290
1972
|
}
|
|
1291
1973
|
/** What the gateway's API profile says about a call, its JSON body read when there is one. */
|
|
1292
1974
|
profileMatch(request) {
|
|
1293
|
-
const
|
|
1294
|
-
|
|
1975
|
+
const call = this.profileRequest(request);
|
|
1976
|
+
return call === null ? null : (this.profile()?.match(call) ?? null);
|
|
1977
|
+
}
|
|
1978
|
+
/** A call as the gateway's API profile reads it; null when the gateway has no profile. */
|
|
1979
|
+
profileRequest(request) {
|
|
1980
|
+
if (this.profile() === null)
|
|
1295
1981
|
return null;
|
|
1296
1982
|
let body;
|
|
1297
1983
|
if (request.body.length > 0 && /json/i.test(request.headers["content-type"] ?? "")) {
|
|
@@ -1302,12 +1988,37 @@ export class Gateway {
|
|
|
1302
1988
|
body = undefined;
|
|
1303
1989
|
}
|
|
1304
1990
|
}
|
|
1305
|
-
return
|
|
1991
|
+
return {
|
|
1306
1992
|
method: request.method,
|
|
1307
1993
|
path: request.path,
|
|
1308
1994
|
query: Gateway.queryOf(request.search),
|
|
1309
1995
|
...(body === undefined ? {} : { body }),
|
|
1310
|
-
}
|
|
1996
|
+
};
|
|
1997
|
+
}
|
|
1998
|
+
/**
|
|
1999
|
+
* The observation, when it has settled by now or settles within `waitMs`;
|
|
2000
|
+
* otherwise null. With 0 it never waits: an already settled promise wins
|
|
2001
|
+
* the race against the resolved sentinel because it is listed first.
|
|
2002
|
+
*/
|
|
2003
|
+
static async settledWithin(observation, waitMs) {
|
|
2004
|
+
const late = Symbol("late");
|
|
2005
|
+
let timer;
|
|
2006
|
+
const deadline = waitMs <= 0
|
|
2007
|
+
? Promise.resolve(late)
|
|
2008
|
+
: new Promise((resolve) => {
|
|
2009
|
+
timer = setTimeout(() => resolve(late), waitMs);
|
|
2010
|
+
});
|
|
2011
|
+
try {
|
|
2012
|
+
const winner = await Promise.race([observation, deadline]);
|
|
2013
|
+
return winner === late ? null : winner;
|
|
2014
|
+
}
|
|
2015
|
+
catch {
|
|
2016
|
+
return null;
|
|
2017
|
+
}
|
|
2018
|
+
finally {
|
|
2019
|
+
if (timer !== undefined)
|
|
2020
|
+
clearTimeout(timer);
|
|
2021
|
+
}
|
|
1311
2022
|
}
|
|
1312
2023
|
principalOf(captured) {
|
|
1313
2024
|
const claimed = captured.intent.context["claimed_principal"];
|
|
@@ -1326,9 +2037,15 @@ export class Gateway {
|
|
|
1326
2037
|
let answer;
|
|
1327
2038
|
if (production.status === "COMPLETED") {
|
|
1328
2039
|
upstreamStatus = production.result.status;
|
|
2040
|
+
// What the policy would have decided, if it is known by now (or within
|
|
2041
|
+
// the wait the operator allows): the caller sees it, and nothing waits
|
|
2042
|
+
// longer than that for it.
|
|
2043
|
+
const seen = await Gateway.settledWithin(run.observation, this.config.shadowVerdictWaitMs);
|
|
1329
2044
|
answer = this.answer(request, production.result, {
|
|
1330
2045
|
"agentsafe-mode": "SHADOW",
|
|
1331
2046
|
"agentsafe-execution": "PASSTHROUGH",
|
|
2047
|
+
"agentsafe-shadow-verdict": seen === null ? "PENDING" : (seen.verdict ?? "NONE"),
|
|
2048
|
+
...(seen?.decisionId ? { "agentsafe-decision-id": seen.decisionId } : {}),
|
|
1332
2049
|
});
|
|
1333
2050
|
}
|
|
1334
2051
|
else {
|
|
@@ -1336,9 +2053,12 @@ export class Gateway {
|
|
|
1336
2053
|
answer = this.failed(failure);
|
|
1337
2054
|
}
|
|
1338
2055
|
// The observation settles on its own bound and is reported when it does;
|
|
1339
|
-
// the client's response never waits for the authority.
|
|
1340
|
-
|
|
2056
|
+
// the client's response never waits for the authority, nor the ledger.
|
|
2057
|
+
const money = this.moneyOf(request);
|
|
2058
|
+
const settled = (observation, exposure) => {
|
|
1341
2059
|
this.metrics.shadowDecisions.inc({ verdict: observation.verdict ?? "NONE" });
|
|
2060
|
+
if (exposure !== null)
|
|
2061
|
+
this.ledger.recordExposure(exposure.status);
|
|
1342
2062
|
this.count("shadow");
|
|
1343
2063
|
this.ledger.record(captured.intent.action, observation.verdict, new Date(this.clock()).toISOString(), upstreamStatus);
|
|
1344
2064
|
this.report({
|
|
@@ -1358,8 +2078,19 @@ export class Gateway {
|
|
|
1358
2078
|
upstream_status: upstreamStatus,
|
|
1359
2079
|
finalization: null,
|
|
1360
2080
|
authority_ms: observation.durationMs,
|
|
2081
|
+
...(exposure === null ? {} : { exposure }),
|
|
1361
2082
|
});
|
|
1362
2083
|
this.shadowReportOnCadence();
|
|
2084
|
+
};
|
|
2085
|
+
void run.observation.then((observation) => {
|
|
2086
|
+
// The ledger is asked only after an ALLOW, as it would be in enforcement.
|
|
2087
|
+
if (money === null || observation.verdict !== "ALLOW") {
|
|
2088
|
+
settled(observation, null);
|
|
2089
|
+
return;
|
|
2090
|
+
}
|
|
2091
|
+
const probing = this.observeExposure(money, captured).then((exposure) => settled(observation, exposure), () => settled(observation, null));
|
|
2092
|
+
this.observing.add(probing);
|
|
2093
|
+
void probing.finally(() => this.observing.delete(probing));
|
|
1363
2094
|
});
|
|
1364
2095
|
return answer;
|
|
1365
2096
|
}
|
|
@@ -1387,6 +2118,7 @@ export class Gateway {
|
|
|
1387
2118
|
if (decision.verdict === "BLOCK") {
|
|
1388
2119
|
this.metrics.blocks.inc();
|
|
1389
2120
|
this.count("blocks");
|
|
2121
|
+
this.observeRefusal(captured, "BLOCK");
|
|
1390
2122
|
this.report({
|
|
1391
2123
|
...this.interception(request, captured, startedAt),
|
|
1392
2124
|
state: "BLOCK",
|
|
@@ -1424,7 +2156,7 @@ export class Gateway {
|
|
|
1424
2156
|
const resumeToken = randomBytes(32).toString("base64url");
|
|
1425
2157
|
const entry = {
|
|
1426
2158
|
captured,
|
|
1427
|
-
request,
|
|
2159
|
+
request: this.holdable(request),
|
|
1428
2160
|
decision,
|
|
1429
2161
|
handoff: handoff === null ? null : { ...handoff, intent: captured.intent },
|
|
1430
2162
|
heldAt: new Date(this.clock()).toISOString(),
|
|
@@ -1441,6 +2173,7 @@ export class Gateway {
|
|
|
1441
2173
|
resumable: handoff !== null,
|
|
1442
2174
|
held: heldOk,
|
|
1443
2175
|
});
|
|
2176
|
+
this.observeRefusal(captured, "ESCALATE");
|
|
1444
2177
|
this.report({
|
|
1445
2178
|
...this.interception(request, captured, startedAt),
|
|
1446
2179
|
state: "ESCALATE",
|
|
@@ -1503,6 +2236,7 @@ export class Gateway {
|
|
|
1503
2236
|
});
|
|
1504
2237
|
return forwarded;
|
|
1505
2238
|
}
|
|
2239
|
+
this.observeRefusal(captured, "AUTHORITY_UNAVAILABLE");
|
|
1506
2240
|
this.report({
|
|
1507
2241
|
...this.interception(request, captured, startedAt),
|
|
1508
2242
|
state: "AUTHORITY_UNAVAILABLE",
|
|
@@ -1527,7 +2261,35 @@ export class Gateway {
|
|
|
1527
2261
|
/** An ALLOW: the grant claimed, the exact request sent once, the outcome finalized and relayed. */
|
|
1528
2262
|
async execute(request, captured, decision, startedAt, authorityMs) {
|
|
1529
2263
|
const intentId = captured.intent.intentId;
|
|
1530
|
-
this.
|
|
2264
|
+
const plan = this.plans.get(captured) ?? null;
|
|
2265
|
+
// A route that releases money: its reservations, made after the claim
|
|
2266
|
+
// and before the send, and ended once the upstream has answered. Read
|
|
2267
|
+
// again from the request here, so a resumed hold is checked the same way.
|
|
2268
|
+
const money = this.moneyOf(request);
|
|
2269
|
+
const retryOf = money === null ? undefined : this.retriedReservation(request);
|
|
2270
|
+
const binding = {
|
|
2271
|
+
intentId,
|
|
2272
|
+
intentHash: captured.intentHash,
|
|
2273
|
+
capturedAt: captured.intent.capturedAt,
|
|
2274
|
+
...(retryOf === undefined ? {} : { retryOf }),
|
|
2275
|
+
};
|
|
2276
|
+
const reserved = {
|
|
2277
|
+
check: null,
|
|
2278
|
+
refused: false,
|
|
2279
|
+
};
|
|
2280
|
+
// What the read after the write said, when the upstream answered 2xx and
|
|
2281
|
+
// the grant committed to an effect: registered for the finalization, and
|
|
2282
|
+
// kept for the report. Neither the read nor the comparison throws, so
|
|
2283
|
+
// nothing here can make a write that landed read as an unknown one.
|
|
2284
|
+
let observed = null;
|
|
2285
|
+
const effect = plan === null || typeof plan.effect === "string" ? null : plan.effect;
|
|
2286
|
+
const reader = this.reader;
|
|
2287
|
+
this.holder.hold(intentId, request, {}, plan === null || effect === null || reader === null
|
|
2288
|
+
? null
|
|
2289
|
+
: async (authorization) => {
|
|
2290
|
+
observed = await reader.effect(plan, effect);
|
|
2291
|
+
this.effects.attach(authorization, observed.record);
|
|
2292
|
+
}, this.beforeDispatch(money, binding, reserved));
|
|
1531
2293
|
const forwardStarted = this.clock();
|
|
1532
2294
|
let outcome;
|
|
1533
2295
|
let forward;
|
|
@@ -1538,20 +2300,39 @@ export class Gateway {
|
|
|
1538
2300
|
forward = this.holder.release(intentId);
|
|
1539
2301
|
}
|
|
1540
2302
|
this.metrics.observeForwardLatency(this.clock() - forwardStarted);
|
|
2303
|
+
const check = reserved.check;
|
|
2304
|
+
const settlement = check === null || this.exposure === null
|
|
2305
|
+
? null
|
|
2306
|
+
: await this.exposure.conclude(check, outcome.outcome === "COMPLETED"
|
|
2307
|
+
? "COMMITTED"
|
|
2308
|
+
: outcome.outcome === "UNKNOWN_AFTER_DISPATCH"
|
|
2309
|
+
? "INDETERMINATE"
|
|
2310
|
+
: "NOT_EXECUTED", binding, outcome.outcome === "COMPLETED" && money !== null && money.facts.ok
|
|
2311
|
+
? readSettledAmount(money.declaration, money.facts.facts, outcome.result)
|
|
2312
|
+
: null);
|
|
2313
|
+
const exposure = Gateway.exposureReport(check, settlement);
|
|
1541
2314
|
const base = {
|
|
1542
2315
|
...this.interception(request, captured, startedAt),
|
|
1543
2316
|
verdict: "ALLOW",
|
|
1544
2317
|
decision_id: decision.decisionId,
|
|
1545
2318
|
dossier_id: decision.dossierId,
|
|
1546
2319
|
authority_ms: authorityMs,
|
|
2320
|
+
...(exposure === null ? {} : { exposure }),
|
|
1547
2321
|
};
|
|
1548
2322
|
const finalization = "finalization" in outcome ? outcome.finalization : null;
|
|
1549
2323
|
const evidenceHeaders = {
|
|
1550
2324
|
"agentsafe-decision": "ALLOW",
|
|
1551
2325
|
...(decision.dossierId === null ? {} : { "agentsafe-dossier-id": decision.dossierId }),
|
|
1552
2326
|
"agentsafe-intent-hash": captured.intentHash,
|
|
2327
|
+
...(exposure === null ? {} : { "agentsafe-exposure": exposure.status }),
|
|
1553
2328
|
};
|
|
2329
|
+
if (check !== null && reserved.refused) {
|
|
2330
|
+
return this.exposureRefused(captured, decision, base, check, finalization);
|
|
2331
|
+
}
|
|
1554
2332
|
if (outcome.outcome === "COMPLETED") {
|
|
2333
|
+
this.settleAttempt(request, captured, decision, "DEFINITE");
|
|
2334
|
+
const said = this.effectOf(captured, plan, observed);
|
|
2335
|
+
this.metrics.effects.inc({ effect: said.confirmation });
|
|
1555
2336
|
this.report({
|
|
1556
2337
|
...base,
|
|
1557
2338
|
state: "ALLOW",
|
|
@@ -1559,6 +2340,7 @@ export class Gateway {
|
|
|
1559
2340
|
execution: "FORWARDED",
|
|
1560
2341
|
upstream_status: outcome.result.status,
|
|
1561
2342
|
finalization,
|
|
2343
|
+
effect: { confirmation: said.confirmation, reason_codes: said.reasonCodes },
|
|
1562
2344
|
});
|
|
1563
2345
|
return this.answer(request, outcome.result, {
|
|
1564
2346
|
...evidenceHeaders,
|
|
@@ -1566,6 +2348,7 @@ export class Gateway {
|
|
|
1566
2348
|
});
|
|
1567
2349
|
}
|
|
1568
2350
|
if (outcome.outcome === "DEFINITELY_NOT_EXECUTED" && forward.response !== null) {
|
|
2351
|
+
this.settleAttempt(request, captured, decision, "DEFINITE");
|
|
1569
2352
|
this.report({
|
|
1570
2353
|
...base,
|
|
1571
2354
|
state: "EXECUTION_FAILED",
|
|
@@ -1579,6 +2362,7 @@ export class Gateway {
|
|
|
1579
2362
|
if (outcome.outcome === "UNKNOWN_AFTER_DISPATCH") {
|
|
1580
2363
|
this.metrics.indeterminate.inc();
|
|
1581
2364
|
this.count("indeterminate");
|
|
2365
|
+
this.settleAttempt(request, captured, decision, "INDETERMINATE", check === null ? undefined : ExposureGate.reservationKey(binding));
|
|
1582
2366
|
const codes = [outcome.reason, ...(forward.failure === null ? [] : [forward.failure])];
|
|
1583
2367
|
this.report({
|
|
1584
2368
|
...base,
|
|
@@ -1633,13 +2417,191 @@ export class Gateway {
|
|
|
1633
2417
|
finalization,
|
|
1634
2418
|
});
|
|
1635
2419
|
}
|
|
2420
|
+
/**
|
|
2421
|
+
* The route's money declaration and what the request states for it, when
|
|
2422
|
+
* the request is governed by a route that releases money; null otherwise,
|
|
2423
|
+
* and always null for a gateway with no such route.
|
|
2424
|
+
*/
|
|
2425
|
+
moneyOf(request) {
|
|
2426
|
+
if (this.exposure === null)
|
|
2427
|
+
return null;
|
|
2428
|
+
const plan = this.plan(request.method, request.path, request.search);
|
|
2429
|
+
const route = plan.kind === "GOVERN" ? plan.route : null;
|
|
2430
|
+
if (route?.exposure === undefined)
|
|
2431
|
+
return null;
|
|
2432
|
+
return {
|
|
2433
|
+
declaration: route.exposure,
|
|
2434
|
+
facts: readExposureFacts(route.exposure, request, route.path, this.config.actor.id),
|
|
2435
|
+
};
|
|
2436
|
+
}
|
|
2437
|
+
/**
|
|
2438
|
+
* The check run after the grant is claimed and before the payment is sent:
|
|
2439
|
+
* reserve against every covering limit, and refuse, sending nothing, when
|
|
2440
|
+
* one would be exceeded or, unless the route fails open, when the ledger
|
|
2441
|
+
* cannot be asked. What it found is left in `reserved` for the outcome.
|
|
2442
|
+
*/
|
|
2443
|
+
beforeDispatch(money, binding, reserved) {
|
|
2444
|
+
const exposure = this.exposure;
|
|
2445
|
+
if (money === null || exposure === null)
|
|
2446
|
+
return null;
|
|
2447
|
+
return async () => {
|
|
2448
|
+
if (!money.facts.ok)
|
|
2449
|
+
throw new PreDispatchRefusal(money.facts.code);
|
|
2450
|
+
const failOpen = money.declaration.failurePolicy === "FAIL_OPEN";
|
|
2451
|
+
const check = await exposure.reserve(money.facts.facts, binding, failOpen);
|
|
2452
|
+
reserved.check = check;
|
|
2453
|
+
reserved.refused =
|
|
2454
|
+
check.status === "EXCEEDED" || (check.status === "UNAVAILABLE" && !failOpen);
|
|
2455
|
+
if (check.status === "EXCEEDED")
|
|
2456
|
+
throw new PreDispatchRefusal(check.reasonCode);
|
|
2457
|
+
if (reserved.refused)
|
|
2458
|
+
throw new PreDispatchRefusal("EXPOSURE_UNAVAILABLE");
|
|
2459
|
+
};
|
|
2460
|
+
}
|
|
2461
|
+
/** What a report and an answer say about a payment's reservations; null for a route that releases none. */
|
|
2462
|
+
static exposureReport(check, settlement) {
|
|
2463
|
+
if (check === null)
|
|
2464
|
+
return null;
|
|
2465
|
+
switch (check.status) {
|
|
2466
|
+
case "WITHIN_LIMIT":
|
|
2467
|
+
return {
|
|
2468
|
+
status: check.held.length === 0 ? "NOT_APPLICABLE" : "WITHIN_LIMIT",
|
|
2469
|
+
reason_codes: check.unstated.length === 0 ? [] : ["EXPOSURE_SUBJECT_UNSTATED"],
|
|
2470
|
+
limits: check.held.map((entry) => entry.limitKey),
|
|
2471
|
+
unstated: [...check.unstated],
|
|
2472
|
+
settlement,
|
|
2473
|
+
};
|
|
2474
|
+
case "EXCEEDED":
|
|
2475
|
+
return {
|
|
2476
|
+
status: "EXCEEDED",
|
|
2477
|
+
reason_codes: [check.reasonCode, `EXPOSURE_ON_EXCEED_${check.onExceed}`],
|
|
2478
|
+
limits: [check.limitKey],
|
|
2479
|
+
unstated: [...check.unstated],
|
|
2480
|
+
settlement,
|
|
2481
|
+
};
|
|
2482
|
+
case "UNAVAILABLE":
|
|
2483
|
+
return {
|
|
2484
|
+
// Forwarded only when the route explicitly fails open.
|
|
2485
|
+
status: check.ungoverned ? "UNGOVERNED" : "UNAVAILABLE",
|
|
2486
|
+
reason_codes: ["EXPOSURE_UNAVAILABLE", check.code],
|
|
2487
|
+
limits: check.held.map((entry) => entry.limitKey),
|
|
2488
|
+
unstated: [...check.unstated],
|
|
2489
|
+
settlement,
|
|
2490
|
+
};
|
|
2491
|
+
}
|
|
2492
|
+
}
|
|
2493
|
+
/**
|
|
2494
|
+
* The gateway's answer to a payment its cumulative limits refused: the
|
|
2495
|
+
* authority allowed it and its grant was claimed, but nothing was sent.
|
|
2496
|
+
* A limit that escalates is refused as one that holds: the claimed grant
|
|
2497
|
+
* cannot be held for a person, so the answer names the limit and its
|
|
2498
|
+
* `on_exceed`, and a new request is decided afresh once the limit allows.
|
|
2499
|
+
*/
|
|
2500
|
+
exposureRefused(captured, decision, base, check, finalization) {
|
|
2501
|
+
const exceeded = check.status === "EXCEEDED";
|
|
2502
|
+
const state = exceeded ? "EXPOSURE_EXCEEDED" : "EXPOSURE_UNAVAILABLE";
|
|
2503
|
+
const reasonCodes = check.status === "EXCEEDED"
|
|
2504
|
+
? [check.reasonCode, `EXPOSURE_ON_EXCEED_${check.onExceed}`]
|
|
2505
|
+
: ["EXPOSURE_UNAVAILABLE", check.status === "UNAVAILABLE" ? check.code : "EXPOSURE_FAILED"];
|
|
2506
|
+
this.report({
|
|
2507
|
+
...base,
|
|
2508
|
+
state,
|
|
2509
|
+
reason_codes: reasonCodes,
|
|
2510
|
+
execution: "NOT_FORWARDED",
|
|
2511
|
+
upstream_status: null,
|
|
2512
|
+
finalization,
|
|
2513
|
+
});
|
|
2514
|
+
return this.own(exceeded ? 409 : 503, {
|
|
2515
|
+
state,
|
|
2516
|
+
verdict: "ALLOW",
|
|
2517
|
+
reason_codes: reasonCodes,
|
|
2518
|
+
execution: "NOT_FORWARDED",
|
|
2519
|
+
intent_id: captured.intent.intentId,
|
|
2520
|
+
intent_hash: captured.intentHash,
|
|
2521
|
+
decision_id: decision.decisionId,
|
|
2522
|
+
dossier_id: decision.dossierId,
|
|
2523
|
+
finalization,
|
|
2524
|
+
...(check.status === "EXCEEDED"
|
|
2525
|
+
? { exposure: { limit_key: check.limitKey, on_exceed: check.onExceed } }
|
|
2526
|
+
: {}),
|
|
2527
|
+
}, exceeded ? {} : { "retry-after": String(RETRY_AFTER_SECONDS) });
|
|
2528
|
+
}
|
|
2529
|
+
/**
|
|
2530
|
+
* In shadow, after the authority would have allowed a payment: what the
|
|
2531
|
+
* ledger would have said, without counting it.
|
|
2532
|
+
*/
|
|
2533
|
+
async observeExposure(money, captured) {
|
|
2534
|
+
if (!money.facts.ok) {
|
|
2535
|
+
this.metrics.exposure.inc({ outcome: "SHADOW_UNREADABLE" });
|
|
2536
|
+
return {
|
|
2537
|
+
status: "UNREADABLE",
|
|
2538
|
+
reason_codes: [money.facts.code],
|
|
2539
|
+
limits: [],
|
|
2540
|
+
unstated: [],
|
|
2541
|
+
settlement: null,
|
|
2542
|
+
};
|
|
2543
|
+
}
|
|
2544
|
+
const check = await this.exposure.observe(money.facts.facts, {
|
|
2545
|
+
intentId: captured.intent.intentId,
|
|
2546
|
+
intentHash: captured.intentHash,
|
|
2547
|
+
capturedAt: captured.intent.capturedAt,
|
|
2548
|
+
});
|
|
2549
|
+
const report = Gateway.exposureReport(check, null);
|
|
2550
|
+
this.metrics.exposure.inc({ outcome: `SHADOW_${report.status}` });
|
|
2551
|
+
return report;
|
|
2552
|
+
}
|
|
2553
|
+
/**
|
|
2554
|
+
* What a forwarded write's report says of its effect: what the read after
|
|
2555
|
+
* it said, or why nothing was read. A write that names no read, or no
|
|
2556
|
+
* effect, holds only the upstream's acknowledgement.
|
|
2557
|
+
*/
|
|
2558
|
+
effectOf(captured, plan, observed) {
|
|
2559
|
+
if (plan === null)
|
|
2560
|
+
return { confirmation: "PENDING", reasonCodes: ["EFFECT_UNDECLARED"] };
|
|
2561
|
+
if (typeof plan.effect === "string") {
|
|
2562
|
+
return { confirmation: "PENDING", reasonCodes: [plan.effect] };
|
|
2563
|
+
}
|
|
2564
|
+
// An effect the grant committed to and nothing read: the upstream
|
|
2565
|
+
// answered with a redirect, which is not a write to read back after.
|
|
2566
|
+
if (observed === null)
|
|
2567
|
+
return { confirmation: "PENDING", reasonCodes: ["EFFECT_NOT_READ"] };
|
|
2568
|
+
this.link({
|
|
2569
|
+
event: "EFFECT_OBSERVED",
|
|
2570
|
+
intent_id: captured.intent.intentId,
|
|
2571
|
+
intent_hash: captured.intentHash,
|
|
2572
|
+
operation: plan.operation,
|
|
2573
|
+
confirmation: observed.statement.confirmation,
|
|
2574
|
+
mismatched: [...observed.record.mismatched],
|
|
2575
|
+
expected_effect_digest: observed.record.expectedEffectDigest,
|
|
2576
|
+
observed_effect_digest: observed.record.observedEffectDigest,
|
|
2577
|
+
evidence_digest: observed.record.evidenceDigest,
|
|
2578
|
+
});
|
|
2579
|
+
return observed.statement;
|
|
2580
|
+
}
|
|
1636
2581
|
hold(intentId, entry) {
|
|
1637
|
-
this.
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
2582
|
+
const held = this.holds.put(intentId, entry);
|
|
2583
|
+
this.metrics.held.set(this.holds.sweep());
|
|
2584
|
+
return held;
|
|
2585
|
+
}
|
|
2586
|
+
/**
|
|
2587
|
+
* The request as a hold keeps it: without the gateway's own credentials
|
|
2588
|
+
* (they end here, and the caller was admitted when it was held) or the
|
|
2589
|
+
* upstream credential, which the gateway sets again when it forwards.
|
|
2590
|
+
*/
|
|
2591
|
+
holdable(request) {
|
|
2592
|
+
const dropped = new Set([
|
|
2593
|
+
TENANT_KEY_HEADER,
|
|
2594
|
+
SESSION_HEADER,
|
|
2595
|
+
SUBJECT_TOKEN_HEADER,
|
|
2596
|
+
GATEWAY_TOKEN_HEADER,
|
|
2597
|
+
...(this.config.upstream.credential === null
|
|
2598
|
+
? []
|
|
2599
|
+
: [this.config.upstream.credential.header.toLowerCase()]),
|
|
2600
|
+
]);
|
|
2601
|
+
return {
|
|
2602
|
+
...request,
|
|
2603
|
+
headers: Object.fromEntries(Object.entries(request.headers).filter(([name]) => !dropped.has(name))),
|
|
2604
|
+
};
|
|
1643
2605
|
}
|
|
1644
2606
|
/**
|
|
1645
2607
|
* The hold under an id, for the caller presenting its token. A refusal is
|
|
@@ -1647,8 +2609,7 @@ export class Gateway {
|
|
|
1647
2609
|
* someone who read an intent id and is not its caller.
|
|
1648
2610
|
*/
|
|
1649
2611
|
heldFor(intentId, resumeToken) {
|
|
1650
|
-
this.
|
|
1651
|
-
const entry = this.held.get(intentId);
|
|
2612
|
+
const entry = this.holds.get(intentId);
|
|
1652
2613
|
if (entry === undefined)
|
|
1653
2614
|
return "ESCALATION_NOT_HELD";
|
|
1654
2615
|
if (resumeToken === null ||
|
|
@@ -1666,16 +2627,8 @@ export class Gateway {
|
|
|
1666
2627
|
return createHash("sha256").update(resumeToken, "utf8").digest();
|
|
1667
2628
|
}
|
|
1668
2629
|
release(intentId) {
|
|
1669
|
-
this.
|
|
1670
|
-
this.metrics.held.set(this.
|
|
1671
|
-
}
|
|
1672
|
-
expireHeld() {
|
|
1673
|
-
const now = this.clock();
|
|
1674
|
-
for (const [id, entry] of this.held) {
|
|
1675
|
-
if (entry.expiresAt <= now)
|
|
1676
|
-
this.held.delete(id);
|
|
1677
|
-
}
|
|
1678
|
-
this.metrics.held.set(this.held.size);
|
|
2630
|
+
this.holds.delete(intentId);
|
|
2631
|
+
this.metrics.held.set(this.holds.sweep());
|
|
1679
2632
|
}
|
|
1680
2633
|
holdBody(entry) {
|
|
1681
2634
|
return {
|
|
@@ -1823,10 +2776,21 @@ export class Gateway {
|
|
|
1823
2776
|
this.io.stdout(renderJson(report));
|
|
1824
2777
|
else
|
|
1825
2778
|
this.io.stdout(renderHuman(report, { color: this.io.color }));
|
|
2779
|
+
if (report.event === "INTERCEPTED")
|
|
2780
|
+
this.runs?.intercepted(report);
|
|
1826
2781
|
}
|
|
1827
|
-
/** One chained line on the gateway's own stream. */
|
|
2782
|
+
/** One chained line on the gateway's own stream, and where it went. */
|
|
1828
2783
|
link(fields) {
|
|
1829
|
-
this.chain.link({ at: new Date(this.clock()).toISOString(), ...fields }, this.emitLine);
|
|
2784
|
+
const record = this.chain.link({ at: new Date(this.clock()).toISOString(), ...fields }, this.emitLine);
|
|
2785
|
+
const line = {
|
|
2786
|
+
stream: GATEWAY_STREAM,
|
|
2787
|
+
seq: record.seq,
|
|
2788
|
+
hash: record.hash,
|
|
2789
|
+
event: String(fields["event"]),
|
|
2790
|
+
};
|
|
2791
|
+
// Assigned last in the constructor: a line linked before then has no run to belong to.
|
|
2792
|
+
this.runs?.linked(fields, line);
|
|
2793
|
+
return line;
|
|
1830
2794
|
}
|
|
1831
2795
|
count(name) {
|
|
1832
2796
|
this.counts[name] = (this.counts[name] ?? 0) + 1;
|