@decionis/agentsafe 0.6.0 → 0.8.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 +68 -20
- package/dist/Cli.js +30 -3
- package/dist/Cli.js.map +1 -1
- package/dist/Index.d.ts +5 -3
- package/dist/Index.d.ts.map +1 -1
- package/dist/Index.js +3 -1
- package/dist/Index.js.map +1 -1
- package/dist/TrustedExecutor.d.ts.map +1 -1
- package/dist/TrustedExecutor.js +2 -0
- package/dist/TrustedExecutor.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/adapters/mcp/McpGuard.d.ts +32 -3
- package/dist/adapters/mcp/McpGuard.d.ts.map +1 -1
- package/dist/adapters/mcp/McpGuard.js +29 -5
- package/dist/adapters/mcp/McpGuard.js.map +1 -1
- package/dist/adapters/mcp/McpIntentBinder.d.ts +18 -3
- package/dist/adapters/mcp/McpIntentBinder.d.ts.map +1 -1
- package/dist/adapters/mcp/McpIntentBinder.js +48 -1
- package/dist/adapters/mcp/McpIntentBinder.js.map +1 -1
- package/dist/adapters/mcp/McpInvocation.d.ts +9 -2
- package/dist/adapters/mcp/McpInvocation.d.ts.map +1 -1
- package/dist/adapters/mcp/McpInvocation.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 +16 -0
- package/dist/cli/Actions.d.ts.map +1 -0
- package/dist/cli/Actions.js +194 -0
- package/dist/cli/Actions.js.map +1 -0
- package/dist/cli/Arguments.d.ts +4 -0
- package/dist/cli/Arguments.d.ts.map +1 -1
- package/dist/cli/Arguments.js +12 -3
- package/dist/cli/Arguments.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 +10 -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 +18 -1
- package/dist/cli/Help.js.map +1 -1
- package/dist/cli/Host.d.ts +5 -2
- package/dist/cli/Host.d.ts.map +1 -1
- package/dist/cli/Host.js +24 -2
- package/dist/cli/Host.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/Profile.d.ts +24 -0
- package/dist/cli/Profile.d.ts.map +1 -0
- package/dist/cli/Profile.js +168 -0
- package/dist/cli/Profile.js.map +1 -0
- package/dist/cli/Records.d.ts +15 -0
- package/dist/cli/Records.d.ts.map +1 -0
- package/dist/cli/Records.js +205 -0
- package/dist/cli/Records.js.map +1 -0
- 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/ConfigKeys.d.ts +2 -2
- package/dist/config/ConfigKeys.d.ts.map +1 -1
- package/dist/config/ConfigKeys.js +6 -0
- package/dist/config/ConfigKeys.js.map +1 -1
- package/dist/config/ExecutorConfig.d.ts +35 -1
- package/dist/config/ExecutorConfig.d.ts.map +1 -1
- package/dist/config/ExecutorConfig.js +53 -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 +83 -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 +201 -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 +50 -6
- package/dist/gateway/ForwardHandler.d.ts.map +1 -1
- package/dist/gateway/ForwardHandler.js +58 -14
- package/dist/gateway/ForwardHandler.js.map +1 -1
- package/dist/gateway/Gateway.d.ts +347 -15
- package/dist/gateway/Gateway.d.ts.map +1 -1
- package/dist/gateway/Gateway.js +1524 -63
- package/dist/gateway/Gateway.js.map +1 -1
- package/dist/gateway/GatewayConfig.d.ts +295 -0
- package/dist/gateway/GatewayConfig.d.ts.map +1 -1
- package/dist/gateway/GatewayConfig.js +485 -13
- 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 +39 -2
- package/dist/gateway/GatewayReport.d.ts.map +1 -1
- package/dist/gateway/GatewayReport.js +14 -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 +55 -1
- package/dist/gateway/InterceptedRequest.d.ts.map +1 -1
- package/dist/gateway/InterceptedRequest.js +63 -1
- package/dist/gateway/InterceptedRequest.js.map +1 -1
- package/dist/gateway/PolicySelector.d.ts +5 -0
- package/dist/gateway/PolicySelector.d.ts.map +1 -0
- package/dist/gateway/PolicySelector.js +9 -0
- package/dist/gateway/PolicySelector.js.map +1 -0
- package/dist/gateway/RouteTable.d.ts +72 -7
- package/dist/gateway/RouteTable.d.ts.map +1 -1
- package/dist/gateway/RouteTable.js +133 -9
- 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/SubjectSessions.d.ts +113 -0
- package/dist/gateway/SubjectSessions.d.ts.map +1 -0
- package/dist/gateway/SubjectSessions.js +219 -0
- package/dist/gateway/SubjectSessions.js.map +1 -0
- 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 +26 -0
- package/dist/gateway/Upstream.d.ts.map +1 -1
- package/dist/gateway/Upstream.js +42 -3
- package/dist/gateway/Upstream.js.map +1 -1
- package/dist/hosted/TenantHost.d.ts +26 -6
- package/dist/hosted/TenantHost.d.ts.map +1 -1
- package/dist/hosted/TenantHost.js +45 -10
- package/dist/hosted/TenantHost.js.map +1 -1
- package/dist/hosted/TenantRegistry.d.ts +28 -0
- package/dist/hosted/TenantRegistry.d.ts.map +1 -1
- package/dist/hosted/TenantRegistry.js +60 -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 +103 -3
- package/dist/http/GatewayHttpServer.js.map +1 -1
- package/dist/identity/WorkloadJwtVerifier.d.ts +13 -0
- package/dist/identity/WorkloadJwtVerifier.d.ts.map +1 -1
- package/dist/identity/WorkloadJwtVerifier.js +40 -8
- package/dist/identity/WorkloadJwtVerifier.js.map +1 -1
- package/dist/incident/HaltSwitch.d.ts +10 -2
- package/dist/incident/HaltSwitch.d.ts.map +1 -1
- package/dist/incident/HaltSwitch.js +22 -2
- package/dist/incident/HaltSwitch.js.map +1 -1
- package/dist/incident/SecurityEvents.d.ts +18 -0
- package/dist/incident/SecurityEvents.d.ts.map +1 -1
- package/dist/incident/SecurityEvents.js +17 -0
- package/dist/incident/SecurityEvents.js.map +1 -1
- package/dist/limits/HardLimits.d.ts.map +1 -1
- package/dist/limits/HardLimits.js.map +1 -1
- package/dist/outcomes/CardOutcomeEvidence.d.ts +56 -0
- package/dist/outcomes/CardOutcomeEvidence.d.ts.map +1 -0
- package/dist/outcomes/CardOutcomeEvidence.js +211 -0
- package/dist/outcomes/CardOutcomeEvidence.js.map +1 -0
- package/dist/outcomes/CardOutcomeFact.d.ts +90 -0
- package/dist/outcomes/CardOutcomeFact.d.ts.map +1 -0
- package/dist/outcomes/CardOutcomeFact.js +76 -0
- package/dist/outcomes/CardOutcomeFact.js.map +1 -0
- package/dist/outcomes/CardOutcomeLedger.d.ts +26 -0
- package/dist/outcomes/CardOutcomeLedger.d.ts.map +1 -0
- package/dist/outcomes/CardOutcomeLedger.js +31 -0
- package/dist/outcomes/CardOutcomeLedger.js.map +1 -0
- package/dist/outcomes/CardOutcomeRecorder.d.ts +35 -0
- package/dist/outcomes/CardOutcomeRecorder.d.ts.map +1 -0
- package/dist/outcomes/CardOutcomeRecorder.js +84 -0
- package/dist/outcomes/CardOutcomeRecorder.js.map +1 -0
- package/dist/outcomes/CardOutcomes.d.ts +68 -0
- package/dist/outcomes/CardOutcomes.d.ts.map +1 -0
- package/dist/outcomes/CardOutcomes.js +191 -0
- package/dist/outcomes/CardOutcomes.js.map +1 -0
- package/dist/outcomes/CoreOutcomeEvidenceClient.d.ts +54 -0
- package/dist/outcomes/CoreOutcomeEvidenceClient.d.ts.map +1 -0
- package/dist/outcomes/CoreOutcomeEvidenceClient.js +116 -0
- package/dist/outcomes/CoreOutcomeEvidenceClient.js.map +1 -0
- package/dist/outcomes/FileCardOutcomeLedger.d.ts +36 -0
- package/dist/outcomes/FileCardOutcomeLedger.d.ts.map +1 -0
- package/dist/outcomes/FileCardOutcomeLedger.js +152 -0
- package/dist/outcomes/FileCardOutcomeLedger.js.map +1 -0
- package/dist/outcomes/OutcomeEvidence.d.ts +238 -0
- package/dist/outcomes/OutcomeEvidence.d.ts.map +1 -0
- package/dist/outcomes/OutcomeEvidence.js +130 -0
- package/dist/outcomes/OutcomeEvidence.js.map +1 -0
- package/dist/outcomes/OutcomeEvidencePublisher.d.ts +81 -0
- package/dist/outcomes/OutcomeEvidencePublisher.d.ts.map +1 -0
- package/dist/outcomes/OutcomeEvidencePublisher.js +189 -0
- package/dist/outcomes/OutcomeEvidencePublisher.js.map +1 -0
- package/dist/outcomes/OutcomeEvidenceStore.d.ts +57 -0
- package/dist/outcomes/OutcomeEvidenceStore.d.ts.map +1 -0
- package/dist/outcomes/OutcomeEvidenceStore.js +191 -0
- package/dist/outcomes/OutcomeEvidenceStore.js.map +1 -0
- 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/dist/service/Requests.d.ts +6 -0
- package/dist/service/Requests.d.ts.map +1 -1
- package/dist/service/Requests.js +9 -1
- package/dist/service/Requests.js.map +1 -1
- package/dist/service/TrustedExecutorService.d.ts +21 -1
- package/dist/service/TrustedExecutorService.d.ts.map +1 -1
- package/dist/service/TrustedExecutorService.js +54 -13
- package/dist/service/TrustedExecutorService.js.map +1 -1
- package/dist/verify/VerifyingProvider.d.ts +32 -6
- package/dist/verify/VerifyingProvider.d.ts.map +1 -1
- package/dist/verify/VerifyingProvider.js +16 -2
- package/dist/verify/VerifyingProvider.js.map +1 -1
- package/package.json +7 -6
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
|
-
import { appendFileSync, mkdirSync } from "node:fs";
|
|
3
|
+
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { ActionRegistry, 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";
|
|
@@ -19,18 +29,26 @@ import { SECURITY_STREAM, SecurityEvents } from "../incident/SecurityEvents.js";
|
|
|
19
29
|
import { LineEmitter } from "../logging/LineEmitter.js";
|
|
20
30
|
import { CompositeSecretStore } from "../secrets/CompositeSecretStore.js";
|
|
21
31
|
import { Redactor } from "../secrets/Redactor.js";
|
|
32
|
+
import { SecretError } from "../secrets/SecretStore.js";
|
|
22
33
|
import { EscalationResolver } from "../service/EscalationResolver.js";
|
|
34
|
+
import { ActionSpaceDrift } from "../posture/ActionSpaceDrift.js";
|
|
35
|
+
import { deploymentFingerprint, } from "../posture/DeploymentFingerprint.js";
|
|
23
36
|
import { ActivationFunnel } from "./Activation.js";
|
|
24
37
|
import { startDemoAuthority } from "./DemoAuthority.js";
|
|
25
38
|
import { httpForwardHandler, registerHttpActions, RequestHolder, } from "./ForwardHandler.js";
|
|
26
|
-
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";
|
|
27
42
|
import { gatewayMetrics } from "./GatewayMetrics.js";
|
|
28
43
|
import { processSurface } from "./InstallSurface.js";
|
|
29
44
|
import { renderHuman, renderJson, } from "./GatewayReport.js";
|
|
30
|
-
import { normalizeRequest } from "./InterceptedRequest.js";
|
|
45
|
+
import { idempotencyKeyOf, normalizeFacts, normalizeRequest, retryDigest, } from "./InterceptedRequest.js";
|
|
31
46
|
import { TokenBucket } from "./RateLimit.js";
|
|
32
47
|
import { RefusalSampler } from "./RefusalSampler.js";
|
|
33
48
|
import { RouteTable } from "./RouteTable.js";
|
|
49
|
+
import { TargetReader } from "./TargetReader.js";
|
|
50
|
+
import { IssuerSubjectVerifier, MAX_SUBJECT_TOKEN_AGE_SECONDS, SubjectSessions, } from "./SubjectSessions.js";
|
|
51
|
+
import { WorkloadJwtVerifier } from "../identity/WorkloadJwtVerifier.js";
|
|
34
52
|
import { enforcementSwitch, ShadowLedger } from "./ShadowLedger.js";
|
|
35
53
|
import { PROOF_PENDING_RETRY_MS, sameBinding, UpstreamProofCheck, UpstreamProofMonitor, } from "./UpstreamProof.js";
|
|
36
54
|
/**
|
|
@@ -50,9 +68,9 @@ export const GATEWAY_STREAM = "agent-safe.gateway-events/1";
|
|
|
50
68
|
export const GATEWAY_PREFIX = "/_agentsafe";
|
|
51
69
|
/** The version of the wire shape the gateway answers with on its own responses. */
|
|
52
70
|
export const GATEWAY_RESPONSE_VERSION = "agent-safe.gateway/1";
|
|
53
|
-
/** The most escalations held at once; beyond it a new hold is refused rather than an old one dropped. */
|
|
54
|
-
const MAX_HELD = 1_000;
|
|
55
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";
|
|
56
74
|
/**
|
|
57
75
|
* The transport codes of a send that ended before a connection to the
|
|
58
76
|
* upstream existed: the name did not resolve, or the connection was refused
|
|
@@ -78,20 +96,13 @@ const CERTIFICATE_UNVERIFIED = /^(?:UNABLE_TO_|SELF_SIGNED|DEPTH_ZERO|CERT_|ERR_
|
|
|
78
96
|
export function shortDigest(digest) {
|
|
79
97
|
return digest.slice(0, "sha256:".length + 12);
|
|
80
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";
|
|
81
101
|
/**
|
|
82
102
|
* The header a resume token travels in. Never the path or the query: those
|
|
83
103
|
* are what proxies, access logs and this gateway's own report write down.
|
|
84
104
|
*/
|
|
85
105
|
export const RESUME_TOKEN_HEADER = "agentsafe-resume-token";
|
|
86
|
-
/**
|
|
87
|
-
* The HTTP-interception ingress over the unchanged lifecycle. A request the
|
|
88
|
-
* route table calls consequential becomes a captured intent; the authority
|
|
89
|
-
* decides; on `ALLOW` the executor claims the grant and the forwarding
|
|
90
|
-
* handler sends the exact bytes the intent bound; the outcome is finalized
|
|
91
|
-
* and every step is chained evidence. In shadow the request goes through
|
|
92
|
-
* unchanged while the authority is asked what it would have decided.
|
|
93
|
-
* Nothing here decides ALLOW, BLOCK or ESCALATE; it asks, enforces and records.
|
|
94
|
-
*/
|
|
95
106
|
export class Gateway {
|
|
96
107
|
config;
|
|
97
108
|
upstream;
|
|
@@ -110,8 +121,42 @@ export class Gateway {
|
|
|
110
121
|
boundary;
|
|
111
122
|
workload;
|
|
112
123
|
proof;
|
|
113
|
-
|
|
124
|
+
sessions;
|
|
125
|
+
jwks;
|
|
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;
|
|
133
|
+
/**
|
|
134
|
+
* For each governed request whose operation names where the subject sits
|
|
135
|
+
* in its answer: the session and operation the answer is checked against,
|
|
136
|
+
* wherever it is relayed (enforced, observed in shadow, forwarded failing
|
|
137
|
+
* open, or after a resumed escalation, which holds the same request).
|
|
138
|
+
*/
|
|
139
|
+
answerScopes = new WeakMap();
|
|
114
140
|
holder = new RequestHolder();
|
|
141
|
+
/**
|
|
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.
|
|
146
|
+
*/
|
|
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;
|
|
115
160
|
capture;
|
|
116
161
|
executor;
|
|
117
162
|
shadow;
|
|
@@ -127,7 +172,18 @@ export class Gateway {
|
|
|
127
172
|
/** The tenant keys admitted now: the configuration's, until a host replaces them in place. */
|
|
128
173
|
admitted;
|
|
129
174
|
registry = null;
|
|
130
|
-
|
|
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) {
|
|
131
187
|
this.config = config;
|
|
132
188
|
this.upstream = upstream;
|
|
133
189
|
this.routes = routes;
|
|
@@ -145,9 +201,56 @@ export class Gateway {
|
|
|
145
201
|
this.boundary = boundary;
|
|
146
202
|
this.workload = workload;
|
|
147
203
|
this.proof = proof;
|
|
204
|
+
this.sessions = sessions;
|
|
205
|
+
this.jwks = jwks;
|
|
206
|
+
this.effects = effects;
|
|
207
|
+
this.replaced = replaced;
|
|
208
|
+
this.acceptance = acceptance;
|
|
148
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);
|
|
149
238
|
this.admitted = config.tenantKeys;
|
|
150
|
-
|
|
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);
|
|
151
254
|
this.bucket = config.rateLimit === null ? null : new TokenBucket(config.rateLimit, clock);
|
|
152
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 }));
|
|
153
256
|
// A funnel handed on keeps reporting through the gateway that made it:
|
|
@@ -155,7 +258,7 @@ export class Gateway {
|
|
|
155
258
|
this.activation =
|
|
156
259
|
activation ??
|
|
157
260
|
new ActivationFunnel((milestone, at) => this.report({ event: "ACTIVATION", milestone, at }), clock);
|
|
158
|
-
const registry = registerHttpActions(new ActionRegistry(), routes.actions(), httpForwardHandler(upstream, this.holder));
|
|
261
|
+
const registry = registerHttpActions(new ActionRegistry(), routes.actions(), httpForwardHandler(upstream, this.holder, this.digestKey));
|
|
159
262
|
// The executor refuses an intent captured through another boundary: an
|
|
160
263
|
// authority issued at one door is not presentable at the next.
|
|
161
264
|
this.executor = new SafeExecutor(registry, verifier, audit, {
|
|
@@ -164,12 +267,23 @@ export class Gateway {
|
|
|
164
267
|
});
|
|
165
268
|
this.shadow =
|
|
166
269
|
config.authority.mode === "SHADOW"
|
|
167
|
-
? new ShadowPipeline(
|
|
270
|
+
? new ShadowPipeline(decides, { audit, timeoutMs: config.authority.timeoutMs })
|
|
168
271
|
: null;
|
|
169
272
|
this.resolver =
|
|
170
273
|
config.authority.mode === "ENFORCEMENT"
|
|
171
|
-
? new EscalationResolver(config.escalation, gate, audit, {})
|
|
274
|
+
? new EscalationResolver(config.escalation, gate, audit, {}, null, decides)
|
|
172
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
|
+
});
|
|
173
287
|
this.stopFollowing =
|
|
174
288
|
journal === null
|
|
175
289
|
? []
|
|
@@ -178,6 +292,27 @@ export class Gateway {
|
|
|
178
292
|
journal.follow(chain, security),
|
|
179
293
|
journal.follow(security.chain, security),
|
|
180
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));
|
|
181
316
|
}
|
|
182
317
|
/**
|
|
183
318
|
* Assembles the gateway: the secrets it needs opened, the demo authority
|
|
@@ -218,7 +353,32 @@ export class Gateway {
|
|
|
218
353
|
const securityHead = security.chain.head.seq;
|
|
219
354
|
emitter.reportRedactions((patterns) => security.emit({ event: "LEAK_SUSPECTED", patterns: [...patterns] }));
|
|
220
355
|
if (store === null && config.secrets.required.length > 0) {
|
|
221
|
-
|
|
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
|
+
};
|
|
381
|
+
store = CompositeSecretStore.fromEnvironment(secretEnvironment, config.secrets.required, {
|
|
222
382
|
events: security,
|
|
223
383
|
production: config.production,
|
|
224
384
|
enforcePermissions: config.production,
|
|
@@ -229,6 +389,31 @@ export class Gateway {
|
|
|
229
389
|
});
|
|
230
390
|
}
|
|
231
391
|
const secrets = store;
|
|
392
|
+
if (config.upstream.credential !== null) {
|
|
393
|
+
// The value travels as one header, so it is checked once here: a
|
|
394
|
+
// gateway that could not send it refuses to start rather than fail
|
|
395
|
+
// each request after its grant was claimed.
|
|
396
|
+
if (secrets === null || !secrets.has("DOWNSTREAM_CREDENTIAL")) {
|
|
397
|
+
throw new SecretError("CONFIG_SECRET_MISSING", "DOWNSTREAM_CREDENTIAL");
|
|
398
|
+
}
|
|
399
|
+
secrets.get("DOWNSTREAM_CREDENTIAL").use((value) => {
|
|
400
|
+
if (!Upstream.isHeaderValue(value.toString("utf8"))) {
|
|
401
|
+
throw new SecretError("CONFIG_SECRET_INVALID", "DOWNSTREAM_CREDENTIAL");
|
|
402
|
+
}
|
|
403
|
+
});
|
|
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
|
+
}
|
|
232
417
|
const demo = config.authority.kind === "LOCAL"
|
|
233
418
|
? await (dependencies.demoAuthority ?? startDemoAuthority)()
|
|
234
419
|
: null;
|
|
@@ -265,8 +450,18 @@ export class Gateway {
|
|
|
265
450
|
...(surface === null ? {} : { surface }),
|
|
266
451
|
},
|
|
267
452
|
});
|
|
268
|
-
const verifier = new DecionisGrantVerifier(connection);
|
|
269
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
|
+
}));
|
|
270
465
|
// Evidence lines: always in JSON mode; in human mode to the terminal only
|
|
271
466
|
// when asked, and to the journal directory's file whenever there is one.
|
|
272
467
|
const evidenceFile = config.evidence.enabled && config.evidence.journalDir !== null
|
|
@@ -315,9 +510,23 @@ export class Gateway {
|
|
|
315
510
|
fetch: upstreamGuard?.fetch ?? dependencies.upstreamFetch ?? fetch,
|
|
316
511
|
hostOnlyCookies: config.hosted,
|
|
317
512
|
sandboxed: config.hosted,
|
|
513
|
+
...(config.upstream.credential === null || secrets === null
|
|
514
|
+
? {}
|
|
515
|
+
: {
|
|
516
|
+
credential: {
|
|
517
|
+
header: config.upstream.credential.header,
|
|
518
|
+
// Read at the moment of use, so a rotated file takes effect at once.
|
|
519
|
+
value: () => secrets.get("DOWNSTREAM_CREDENTIAL").use((value) => value.toString("utf8")),
|
|
520
|
+
},
|
|
521
|
+
}),
|
|
522
|
+
...(config.upstream.gatewayToken === null || secrets === null
|
|
523
|
+
? {}
|
|
524
|
+
: {
|
|
525
|
+
gatewayToken: () => secrets.get(GATEWAY_TOKEN_SECRET).use((value) => value.toString("utf8")),
|
|
526
|
+
}),
|
|
318
527
|
...(upstreamGuard === null ? {} : { close: () => upstreamGuard.close() }),
|
|
319
528
|
});
|
|
320
|
-
const routes =
|
|
529
|
+
const routes = RouteTable.of(config);
|
|
321
530
|
const evidence = takeUp(EVIDENCE_STREAM, continues?.evidence);
|
|
322
531
|
const chain = takeUp(GATEWAY_STREAM, continues?.gateway);
|
|
323
532
|
const audit = new AuditRecorder({
|
|
@@ -341,7 +550,20 @@ export class Gateway {
|
|
|
341
550
|
new NoneProvenanceProvider(),
|
|
342
551
|
];
|
|
343
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
|
+
});
|
|
344
562
|
const proof = Gateway.upstreamProof(config, dependencies, security, clock, continues !== null);
|
|
563
|
+
const jwks = await Gateway.subjectKeys(config, dependencies, security);
|
|
564
|
+
const sessions = config.subject === null || jwks === null
|
|
565
|
+
? null
|
|
566
|
+
: new SubjectSessions(new IssuerSubjectVerifier(jwks, config.subject.issuer, config.subject.claim), { ttlSeconds: config.subject.sessionTtlSeconds, clock });
|
|
345
567
|
// A chain that does not start at genesis says where it was taken up, once
|
|
346
568
|
// nothing is left that can refuse the gateway.
|
|
347
569
|
for (const [stream, head] of [
|
|
@@ -352,7 +574,62 @@ export class Gateway {
|
|
|
352
574
|
if (head > 0)
|
|
353
575
|
security.emit({ event: "CHAIN_RESUMED", chain: stream, head });
|
|
354
576
|
}
|
|
355
|
-
|
|
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);
|
|
632
|
+
jwks?.start();
|
|
356
633
|
// The first look at the proof starts once nothing can refuse the gateway;
|
|
357
634
|
// a gateway built to replace another takes the proof over at the swap.
|
|
358
635
|
if (proof !== null && !proof.takesOver)
|
|
@@ -390,6 +667,63 @@ export class Gateway {
|
|
|
390
667
|
});
|
|
391
668
|
return { binding, check, monitor, takesOver };
|
|
392
669
|
}
|
|
670
|
+
/**
|
|
671
|
+
* The identity provider's key set, when the gateway pins subjects: the file
|
|
672
|
+
* when there is one, else one fetch from the address at start, refused by
|
|
673
|
+
* name when it fails; refreshed from the address through the guarded
|
|
674
|
+
* egress, sealed to its origin, with the last good set kept on a failure.
|
|
675
|
+
*/
|
|
676
|
+
static async subjectKeys(config, dependencies, security) {
|
|
677
|
+
const subject = config.subject;
|
|
678
|
+
if (subject === null)
|
|
679
|
+
return null;
|
|
680
|
+
const egress = subject.jwksUrl === null
|
|
681
|
+
? null
|
|
682
|
+
: new GuardedFetch({
|
|
683
|
+
policy: new EgressPolicy([
|
|
684
|
+
{ origin: new URL(subject.jwksUrl).origin, pathPrefixes: ["/"], ca: null, pins: [] },
|
|
685
|
+
]),
|
|
686
|
+
events: security,
|
|
687
|
+
maxResponseBytes: 256 * 1024,
|
|
688
|
+
...(dependencies.subjectJwksFetch === undefined
|
|
689
|
+
? {}
|
|
690
|
+
: { transport: dependencies.subjectJwksFetch }),
|
|
691
|
+
});
|
|
692
|
+
const refresh = egress === null || subject.jwksUrl === null
|
|
693
|
+
? undefined
|
|
694
|
+
: { url: subject.jwksUrl, fetch: egress.fetch, intervalSeconds: 300, events: security };
|
|
695
|
+
let text = null;
|
|
696
|
+
if (subject.jwksFile !== null) {
|
|
697
|
+
try {
|
|
698
|
+
text = readFileSync(subject.jwksFile, "utf8");
|
|
699
|
+
}
|
|
700
|
+
catch {
|
|
701
|
+
throw new Error("JWKS_UNAVAILABLE: subject.jwksFile");
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
else if (refresh !== undefined) {
|
|
705
|
+
try {
|
|
706
|
+
const response = await refresh.fetch(refresh.url, {
|
|
707
|
+
method: "GET",
|
|
708
|
+
headers: { accept: "application/json" },
|
|
709
|
+
signal: AbortSignal.timeout(10_000),
|
|
710
|
+
});
|
|
711
|
+
text = response.status === 200 ? await response.text() : null;
|
|
712
|
+
}
|
|
713
|
+
catch {
|
|
714
|
+
text = null;
|
|
715
|
+
}
|
|
716
|
+
if (text === null)
|
|
717
|
+
throw new Error("JWKS_UNAVAILABLE: subject.jwksUrl");
|
|
718
|
+
}
|
|
719
|
+
return new WorkloadJwtVerifier({
|
|
720
|
+
audiences: [subject.audience],
|
|
721
|
+
keys: WorkloadJwtVerifier.parseJwks(text ?? ""),
|
|
722
|
+
clockToleranceSeconds: 60,
|
|
723
|
+
maxTokenAgeSeconds: MAX_SUBJECT_TOKEN_AGE_SECONDS,
|
|
724
|
+
...(refresh === undefined ? {} : { refresh }),
|
|
725
|
+
});
|
|
726
|
+
}
|
|
393
727
|
/** TXT through the system's resolver, bounded, so a check never waits on DNS for long. */
|
|
394
728
|
static systemTxt() {
|
|
395
729
|
const resolver = new Resolver({ timeout: 2_000, tries: 2 });
|
|
@@ -450,6 +784,14 @@ export class Gateway {
|
|
|
450
784
|
mode: this.config.authority.mode,
|
|
451
785
|
authority: this.demo === null ? "decionis" : "local/demo",
|
|
452
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
|
+
}
|
|
453
795
|
this.activation.started({
|
|
454
796
|
mode: this.config.authority.mode,
|
|
455
797
|
authority: this.config.authority.kind,
|
|
@@ -486,8 +828,22 @@ export class Gateway {
|
|
|
486
828
|
this.shadowReport(new Date(now).toISOString());
|
|
487
829
|
}
|
|
488
830
|
}
|
|
489
|
-
plan(method, path) {
|
|
490
|
-
return this.routes.plan(method, path);
|
|
831
|
+
plan(method, path, search = "") {
|
|
832
|
+
return this.routes.plan(method, path, Gateway.queryOf(search));
|
|
833
|
+
}
|
|
834
|
+
/** A query for planning only; a name the intent contract forbids is left out, and refused later. */
|
|
835
|
+
static queryOf(search) {
|
|
836
|
+
const query = {};
|
|
837
|
+
for (const [key, value] of new URLSearchParams(search)) {
|
|
838
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype")
|
|
839
|
+
continue;
|
|
840
|
+
const current = query[key];
|
|
841
|
+
if (current === undefined)
|
|
842
|
+
query[key] = value;
|
|
843
|
+
else
|
|
844
|
+
query[key] = Array.isArray(current) ? [...current, value] : [current, value];
|
|
845
|
+
}
|
|
846
|
+
return query;
|
|
491
847
|
}
|
|
492
848
|
readiness() {
|
|
493
849
|
return {
|
|
@@ -508,18 +864,28 @@ export class Gateway {
|
|
|
508
864
|
failure_policy: this.config.authority.failurePolicy,
|
|
509
865
|
upstream: this.config.upstream.url,
|
|
510
866
|
routes: this.config.interception.routes.length,
|
|
511
|
-
held: this.
|
|
867
|
+
held: this.holds.sweep(),
|
|
512
868
|
counts: { ...this.counts },
|
|
513
869
|
evidence: this.evidence.head,
|
|
514
870
|
activation: this.activation.snapshot(),
|
|
515
871
|
surface: this.surface,
|
|
516
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 },
|
|
517
878
|
hosted: this.config.hosted
|
|
518
879
|
? {
|
|
519
880
|
tenant: this.config.hostedTenant,
|
|
520
881
|
tenant_keys: this.admitted.map(shortDigest),
|
|
521
882
|
registry: this.registry,
|
|
522
883
|
upstream_proof: this.proof?.monitor.snapshot() ?? null,
|
|
884
|
+
dedicated: this.config.hostedDedicated,
|
|
885
|
+
upstream_credential: this.config.upstream.credential === null
|
|
886
|
+
? null
|
|
887
|
+
: { header: this.config.upstream.credential.header },
|
|
888
|
+
gateway_token: this.config.upstream.gatewayToken !== null,
|
|
523
889
|
}
|
|
524
890
|
: null,
|
|
525
891
|
};
|
|
@@ -549,6 +915,7 @@ export class Gateway {
|
|
|
549
915
|
gateway: this.chain,
|
|
550
916
|
security: this.security.chain,
|
|
551
917
|
activation: this.activation,
|
|
918
|
+
fingerprint: this.fingerprint.digest,
|
|
552
919
|
};
|
|
553
920
|
}
|
|
554
921
|
/**
|
|
@@ -626,6 +993,7 @@ export class Gateway {
|
|
|
626
993
|
return enforcementSwitch(this.config);
|
|
627
994
|
}
|
|
628
995
|
metricsText() {
|
|
996
|
+
this.metrics.actionSpaceDrift.set(this.actionSpace.state === "DRIFT" ? 1 : 0);
|
|
629
997
|
return this.metrics.registry.render();
|
|
630
998
|
}
|
|
631
999
|
/**
|
|
@@ -636,14 +1004,58 @@ export class Gateway {
|
|
|
636
1004
|
async passthrough(request) {
|
|
637
1005
|
return await this.forwardUnchanged(request, { "agentsafe-execution": "PASSTHROUGH" });
|
|
638
1006
|
}
|
|
639
|
-
/**
|
|
1007
|
+
/**
|
|
1008
|
+
* A consequential request, through the whole lifecycle. When the gateway
|
|
1009
|
+
* pins subjects, a session the request presents is resolved first: one
|
|
1010
|
+
* that does not stand is refused before anything else, and the subject of
|
|
1011
|
+
* one that does is stated to the authority as `session.subject`, so a
|
|
1012
|
+
* write's policy can compare a fact with it.
|
|
1013
|
+
*/
|
|
640
1014
|
async govern(request, action) {
|
|
641
1015
|
this.metrics.requests.inc({ kind: "governed" });
|
|
642
1016
|
this.count("governed");
|
|
643
1017
|
const startedAt = this.clock();
|
|
1018
|
+
const session = await this.sessionOf(request);
|
|
1019
|
+
if (typeof session === "string")
|
|
1020
|
+
return this.subjectRefused(request, action, null, session, null);
|
|
1021
|
+
// A write whose operation names a subject is for one subject: without a
|
|
1022
|
+
// session there is nothing to state to policy or to check its answer by.
|
|
1023
|
+
const scoped = this.sessions === null ? null : this.scopedOperation(request, action);
|
|
1024
|
+
if (scoped !== null) {
|
|
1025
|
+
if (session === null) {
|
|
1026
|
+
return this.subjectRefused(request, action, scoped.id, "SUBJECT_SESSION_REQUIRED", null);
|
|
1027
|
+
}
|
|
1028
|
+
if (scoped.subject?.response !== undefined) {
|
|
1029
|
+
this.answerScopes.set(request, { session, operation: scoped.id, action });
|
|
1030
|
+
}
|
|
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
|
+
}
|
|
644
1056
|
let captured;
|
|
645
1057
|
try {
|
|
646
|
-
captured = this.captureIntent(request, action);
|
|
1058
|
+
captured = this.captureIntent(request, action, session, target, retryOf);
|
|
647
1059
|
}
|
|
648
1060
|
catch (error) {
|
|
649
1061
|
const code = error instanceof Error ? error.message : "INTENT_INVALID";
|
|
@@ -654,13 +1066,98 @@ export class Gateway {
|
|
|
654
1066
|
execution: "NOT_FORWARDED",
|
|
655
1067
|
});
|
|
656
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);
|
|
657
1074
|
this.metrics.interceptions.inc({ action });
|
|
658
1075
|
this.count("interceptions");
|
|
659
1076
|
this.activation.intercepted();
|
|
660
1077
|
return await RequestContext.run({ principal: this.principalOf(captured) }, async () => {
|
|
661
1078
|
if (this.shadow !== null)
|
|
662
1079
|
return await this.observe(request, captured, startedAt);
|
|
663
|
-
|
|
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,
|
|
664
1161
|
});
|
|
665
1162
|
}
|
|
666
1163
|
/**
|
|
@@ -758,8 +1255,8 @@ export class Gateway {
|
|
|
758
1255
|
escalation: resolution.handoff,
|
|
759
1256
|
});
|
|
760
1257
|
}
|
|
761
|
-
this.release(intentId);
|
|
762
1258
|
if (resolution.kind === "REFUSED") {
|
|
1259
|
+
this.release(intentId);
|
|
763
1260
|
const state = resolution.failClosed ? "AUTHORITY_UNAVAILABLE" : "BLOCK";
|
|
764
1261
|
this.link({
|
|
765
1262
|
event: "ESCALATION_REFUSED",
|
|
@@ -775,22 +1272,255 @@ export class Gateway {
|
|
|
775
1272
|
intent_id: intentId,
|
|
776
1273
|
});
|
|
777
1274
|
}
|
|
778
|
-
|
|
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));
|
|
779
1289
|
}
|
|
780
1290
|
async close() {
|
|
1291
|
+
// A refusal's read finishes before what it reads with is closed.
|
|
1292
|
+
await Promise.allSettled([...this.observing]);
|
|
781
1293
|
this.refusals.flush();
|
|
782
1294
|
this.handedOn();
|
|
783
1295
|
this.proof?.check.close();
|
|
784
|
-
this.
|
|
1296
|
+
this.jwks?.stop();
|
|
1297
|
+
this.holds.close();
|
|
1298
|
+
this.attempts.close();
|
|
785
1299
|
if (this.demo !== null)
|
|
786
1300
|
await this.demo.stop();
|
|
787
1301
|
this.secrets?.close();
|
|
788
1302
|
this.upstream.close();
|
|
789
1303
|
}
|
|
790
|
-
|
|
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) {
|
|
1505
|
+
if (this.config.interception.privacy === "FACTS") {
|
|
1506
|
+
return this.captureFacts(request, action, session, target, retryOf);
|
|
1507
|
+
}
|
|
1508
|
+
const plan = this.plan(request.method, request.path, request.search);
|
|
1509
|
+
const route = plan.kind === "GOVERN" ? plan.route : null;
|
|
1510
|
+
// A caller of govern() cannot change the action to evade a route's
|
|
1511
|
+
// policy pin. The HTTP listener already uses the route's action.
|
|
1512
|
+
if (route !== null &&
|
|
1513
|
+
(route.policyId !== undefined ||
|
|
1514
|
+
route.policyVersion !== undefined ||
|
|
1515
|
+
route.exposure !== undefined) &&
|
|
1516
|
+
route.action !== action) {
|
|
1517
|
+
throw new Error("ROUTE_ACTION_MISMATCH");
|
|
1518
|
+
}
|
|
791
1519
|
const normalized = normalizeRequest(request, action, {
|
|
792
1520
|
maxEmbeddedBodyBytes: this.config.interception.maxEmbeddedBodyBytes,
|
|
793
1521
|
principalHeader: this.config.interception.principalHeader,
|
|
1522
|
+
...(route?.policyId === undefined ? {} : { policyId: route.policyId }),
|
|
1523
|
+
...(route?.policyVersion === undefined ? {} : { policyVersion: route.policyVersion }),
|
|
794
1524
|
});
|
|
795
1525
|
const trusted = {
|
|
796
1526
|
tenantId: this.config.authority.tenantId,
|
|
@@ -805,6 +1535,9 @@ export class Gateway {
|
|
|
805
1535
|
...normalized.context,
|
|
806
1536
|
ingress: "http",
|
|
807
1537
|
...(normalized.principal === null ? {} : { claimed_principal: normalized.principal }),
|
|
1538
|
+
...this.profileFacts(request, action),
|
|
1539
|
+
...Gateway.sessionContext(session),
|
|
1540
|
+
...Gateway.retryContext(retryOf),
|
|
808
1541
|
},
|
|
809
1542
|
idempotencyKey: normalized.idempotencyKey ?? randomUUID(),
|
|
810
1543
|
...(normalized.correlationId === null ? {} : { correlationId: normalized.correlationId }),
|
|
@@ -812,9 +1545,481 @@ export class Gateway {
|
|
|
812
1545
|
boundary: boundarySignal(this.boundary),
|
|
813
1546
|
...(this.workload === null ? {} : { workload: this.workload }),
|
|
814
1547
|
},
|
|
1548
|
+
...Gateway.targetBinding(target),
|
|
1549
|
+
};
|
|
1550
|
+
return this.capture.capture(normalized.proposal, trusted);
|
|
1551
|
+
}
|
|
1552
|
+
/**
|
|
1553
|
+
* Facts-only privacy: the authority receives the profile operation that
|
|
1554
|
+
* named the call, its path template and the facts it names, and the keyed
|
|
1555
|
+
* digest that binds the held request. No path, query, header or body byte
|
|
1556
|
+
* of the request is in the intent; a call the profile does not describe
|
|
1557
|
+
* never reaches here, because the route table refused it.
|
|
1558
|
+
*/
|
|
1559
|
+
captureFacts(request, action, session, target, retryOf) {
|
|
1560
|
+
const matched = this.profileMatch(request);
|
|
1561
|
+
const operation = matched === null ? null : (this.profile()?.operation(matched.operation) ?? null);
|
|
1562
|
+
if (matched === null || operation === null || matched.action !== action) {
|
|
1563
|
+
throw new Error("PROFILE_OPERATION_UNMATCHED");
|
|
1564
|
+
}
|
|
1565
|
+
const normalized = normalizeFacts(request, action, operation, this.digestKey);
|
|
1566
|
+
const trusted = {
|
|
1567
|
+
tenantId: this.config.authority.tenantId,
|
|
1568
|
+
actor: this.config.actor,
|
|
1569
|
+
downstreamTarget: {
|
|
1570
|
+
system: this.config.upstream.system,
|
|
1571
|
+
operation: action,
|
|
1572
|
+
environment: this.config.upstream.environment,
|
|
1573
|
+
endpoint: this.config.upstream.url,
|
|
1574
|
+
},
|
|
1575
|
+
context: {
|
|
1576
|
+
...normalized.context,
|
|
1577
|
+
ingress: "http",
|
|
1578
|
+
...matched.facts,
|
|
1579
|
+
api_profile: { id: matched.profile, operation: matched.operation },
|
|
1580
|
+
...Gateway.sessionContext(session),
|
|
1581
|
+
...Gateway.retryContext(retryOf),
|
|
1582
|
+
},
|
|
1583
|
+
idempotencyKey: normalized.idempotencyKey ?? randomUUID(),
|
|
1584
|
+
signals: {
|
|
1585
|
+
boundary: boundarySignal(this.boundary),
|
|
1586
|
+
...(this.workload === null ? {} : { workload: this.workload }),
|
|
1587
|
+
},
|
|
1588
|
+
...Gateway.targetBinding(target),
|
|
815
1589
|
};
|
|
816
1590
|
return this.capture.capture(normalized.proposal, trusted);
|
|
817
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
|
+
}
|
|
1703
|
+
/**
|
|
1704
|
+
* The pinned subject as the authority reads it: the fact `session.subject`.
|
|
1705
|
+
* A verified claim of the identity provider, never a value of the request;
|
|
1706
|
+
* absent, never null, when the request presented no session.
|
|
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
|
+
}
|
|
1718
|
+
static sessionContext(session) {
|
|
1719
|
+
return session === null ? {} : { session: { subject: session.subject } };
|
|
1720
|
+
}
|
|
1721
|
+
/** The session a request presents, when the gateway pins subjects; null when it presents none. */
|
|
1722
|
+
async sessionOf(request) {
|
|
1723
|
+
return this.sessions === null ? null : await this.sessions.resolve(request.headers);
|
|
1724
|
+
}
|
|
1725
|
+
/**
|
|
1726
|
+
* A read a profile operation names, checked against the session's subject
|
|
1727
|
+
* and never decided. Before it is sent: the request must present a session
|
|
1728
|
+
* that stands, and when the operation says where the subject sits in the
|
|
1729
|
+
* call, it must be the session's. After: when the operation says where the
|
|
1730
|
+
* subject sits in each item of a successful answer, every item must name
|
|
1731
|
+
* the session's subject, or the whole answer is refused and none of it is
|
|
1732
|
+
* relayed; nothing is filtered, since a partial answer would look complete.
|
|
1733
|
+
* An answer that is not a success is relayed as it came. Every refusal is
|
|
1734
|
+
* a reason code and a line on the gateway's evidence chain.
|
|
1735
|
+
*/
|
|
1736
|
+
async check(request, operationId) {
|
|
1737
|
+
this.metrics.requests.inc({ kind: "checked" });
|
|
1738
|
+
this.count("checked");
|
|
1739
|
+
const profile = this.profile();
|
|
1740
|
+
const operation = profile?.operation(operationId) ?? null;
|
|
1741
|
+
if (profile === null || operation === null) {
|
|
1742
|
+
return this.subjectRefused(request, operationId, null, "READ_OPERATION_UNMATCHED", null);
|
|
1743
|
+
}
|
|
1744
|
+
const session = await this.sessionOf(request);
|
|
1745
|
+
if (session === null || typeof session === "string") {
|
|
1746
|
+
return this.subjectRefused(request, operation.action, operationId, session ?? "SUBJECT_SESSION_REQUIRED", null);
|
|
1747
|
+
}
|
|
1748
|
+
const query = Gateway.strictQuery(request.search);
|
|
1749
|
+
if (query === null) {
|
|
1750
|
+
return this.subjectRefused(request, operation.action, operationId, "QUERY_PARAMETER_REFUSED", session);
|
|
1751
|
+
}
|
|
1752
|
+
const matched = profile.match({ method: request.method, path: request.path, query });
|
|
1753
|
+
if (matched === null || matched.operation !== operationId) {
|
|
1754
|
+
return this.subjectRefused(request, operation.action, operationId, "READ_OPERATION_UNMATCHED", session);
|
|
1755
|
+
}
|
|
1756
|
+
const asked = profile.checkRequest(matched, query, session.subject);
|
|
1757
|
+
if (asked !== "MATCH") {
|
|
1758
|
+
return this.subjectRefused(request, operation.action, operationId, asked, session);
|
|
1759
|
+
}
|
|
1760
|
+
let result;
|
|
1761
|
+
try {
|
|
1762
|
+
result = await this.upstream.send(request.method.toUpperCase(), request.path, request.search, this.upstream.headersFor(request), request.body, this.upstream.signal());
|
|
1763
|
+
}
|
|
1764
|
+
catch (error) {
|
|
1765
|
+
return this.failed(this.failureOf(error));
|
|
1766
|
+
}
|
|
1767
|
+
const answered = this.answerRefusal(operationId, session, result);
|
|
1768
|
+
if (answered !== null) {
|
|
1769
|
+
return this.subjectRefused(request, operation.action, operationId, answered, session, result.status);
|
|
1770
|
+
}
|
|
1771
|
+
return this.relay(result, {
|
|
1772
|
+
"agentsafe-execution": "PASSTHROUGH",
|
|
1773
|
+
"agentsafe-subject": "CHECKED",
|
|
1774
|
+
});
|
|
1775
|
+
}
|
|
1776
|
+
/**
|
|
1777
|
+
* Why a successful answer may not be relayed for this session, or null when
|
|
1778
|
+
* it may: every item the operation's response pointer reaches must name the
|
|
1779
|
+
* session's subject, and beside a list only the envelope's keys may stand.
|
|
1780
|
+
* An answer that is not a success is relayed as it came.
|
|
1781
|
+
*/
|
|
1782
|
+
answerRefusal(operationId, session, result) {
|
|
1783
|
+
if (result.status < 200 || result.status >= 300)
|
|
1784
|
+
return null;
|
|
1785
|
+
let body;
|
|
1786
|
+
try {
|
|
1787
|
+
body =
|
|
1788
|
+
result.body.length === 0
|
|
1789
|
+
? undefined
|
|
1790
|
+
: JSON.parse(result.body.toString("utf8"));
|
|
1791
|
+
}
|
|
1792
|
+
catch {
|
|
1793
|
+
body = undefined;
|
|
1794
|
+
}
|
|
1795
|
+
const answered = this.profile()?.checkResponse(operationId, body, session.subject) ?? null;
|
|
1796
|
+
return answered === null || answered === "MATCH" ? null : answered;
|
|
1797
|
+
}
|
|
1798
|
+
/**
|
|
1799
|
+
* A forwarded answer, relayed: as it came, or, when the request's operation
|
|
1800
|
+
* names where the subject sits in its answer and the answer names another
|
|
1801
|
+
* subject, withheld. The effect, if any, has happened; the response says
|
|
1802
|
+
* the call reached the upstream (`WITHHELD`) and with what status, so a
|
|
1803
|
+
* caller never takes it for a call that was not made.
|
|
1804
|
+
*/
|
|
1805
|
+
answer(request, result, extra) {
|
|
1806
|
+
const scope = this.answerScopes.get(request);
|
|
1807
|
+
const refused = scope === undefined ? null : this.answerRefusal(scope.operation, scope.session, result);
|
|
1808
|
+
if (scope !== undefined && refused !== null) {
|
|
1809
|
+
return this.subjectRefused(request, scope.action, scope.operation, refused, scope.session, result.status);
|
|
1810
|
+
}
|
|
1811
|
+
return this.relay(result, extra);
|
|
1812
|
+
}
|
|
1813
|
+
/** The profile operation that named a governed call, when it names a subject; else null. */
|
|
1814
|
+
scopedOperation(request, action) {
|
|
1815
|
+
const matched = this.profileMatch(request);
|
|
1816
|
+
if (matched === null || matched.action !== action)
|
|
1817
|
+
return null;
|
|
1818
|
+
const operation = this.profile()?.operation(matched.operation) ?? null;
|
|
1819
|
+
return operation?.subject === undefined ? null : operation;
|
|
1820
|
+
}
|
|
1821
|
+
/**
|
|
1822
|
+
* A checked read's query, decoded as RFC 3986 writes it: each name and
|
|
1823
|
+
* value percent-decoded once, and a `+` refused rather than read as a space
|
|
1824
|
+
* or a plus, since an upstream may read it either way and a subject check
|
|
1825
|
+
* must see what the upstream sees. Null when a component does not decode,
|
|
1826
|
+
* holds a `+`, or is a name the intent contract forbids.
|
|
1827
|
+
*/
|
|
1828
|
+
static strictQuery(search) {
|
|
1829
|
+
const query = {};
|
|
1830
|
+
const text = search.startsWith("?") ? search.slice(1) : search;
|
|
1831
|
+
for (const pair of text.split("&")) {
|
|
1832
|
+
if (pair === "")
|
|
1833
|
+
continue;
|
|
1834
|
+
if (pair.includes("+"))
|
|
1835
|
+
return null;
|
|
1836
|
+
const at = pair.indexOf("=");
|
|
1837
|
+
let name;
|
|
1838
|
+
let value;
|
|
1839
|
+
try {
|
|
1840
|
+
name = decodeURIComponent(at === -1 ? pair : pair.slice(0, at));
|
|
1841
|
+
value = at === -1 ? "" : decodeURIComponent(pair.slice(at + 1));
|
|
1842
|
+
}
|
|
1843
|
+
catch {
|
|
1844
|
+
return null;
|
|
1845
|
+
}
|
|
1846
|
+
if (name === "__proto__" || name === "constructor" || name === "prototype")
|
|
1847
|
+
return null;
|
|
1848
|
+
const current = query[name];
|
|
1849
|
+
query[name] =
|
|
1850
|
+
current === undefined
|
|
1851
|
+
? value
|
|
1852
|
+
: Array.isArray(current)
|
|
1853
|
+
? [...current, value]
|
|
1854
|
+
: [current, value];
|
|
1855
|
+
}
|
|
1856
|
+
return query;
|
|
1857
|
+
}
|
|
1858
|
+
/**
|
|
1859
|
+
* RFC 8693 token exchange at the gateway: the identity provider's subject
|
|
1860
|
+
* token in, a session token for this gateway out. The answer is the RFC's,
|
|
1861
|
+
* never cached; issuing and refusing are both lines on the evidence chain,
|
|
1862
|
+
* with the session's short digest and never a token or the subject.
|
|
1863
|
+
*/
|
|
1864
|
+
async exchange(form) {
|
|
1865
|
+
this.metrics.requests.inc({ kind: "control" });
|
|
1866
|
+
if (this.sessions === null) {
|
|
1867
|
+
return this.oauth(404, {
|
|
1868
|
+
error: "invalid_request",
|
|
1869
|
+
error_description: "SUBJECT_NOT_CONFIGURED",
|
|
1870
|
+
});
|
|
1871
|
+
}
|
|
1872
|
+
const answer = await this.sessions.exchange(form);
|
|
1873
|
+
if (answer.status === 200) {
|
|
1874
|
+
this.link({
|
|
1875
|
+
event: "SUBJECT_SESSION_ISSUED",
|
|
1876
|
+
session: answer.session.id,
|
|
1877
|
+
expires_at: new Date(answer.session.expiresAt).toISOString(),
|
|
1878
|
+
});
|
|
1879
|
+
return this.oauth(200, answer.body);
|
|
1880
|
+
}
|
|
1881
|
+
this.link({
|
|
1882
|
+
event: "SUBJECT_SESSION_REFUSED",
|
|
1883
|
+
reason_codes: [answer.body.error_description],
|
|
1884
|
+
});
|
|
1885
|
+
return this.oauth(answer.status, answer.body);
|
|
1886
|
+
}
|
|
1887
|
+
/** An OAuth token endpoint's answer: JSON, never stored by anything between. */
|
|
1888
|
+
oauth(status, body) {
|
|
1889
|
+
return {
|
|
1890
|
+
status,
|
|
1891
|
+
headers: [
|
|
1892
|
+
["content-type", "application/json; charset=utf-8"],
|
|
1893
|
+
["cache-control", "no-store"],
|
|
1894
|
+
["pragma", "no-cache"],
|
|
1895
|
+
["x-content-type-options", "nosniff"],
|
|
1896
|
+
],
|
|
1897
|
+
body: Buffer.from(JSON.stringify(body), "utf8"),
|
|
1898
|
+
};
|
|
1899
|
+
}
|
|
1900
|
+
/**
|
|
1901
|
+
* A subject refusal: the gateway's own answer, a report line and a line on
|
|
1902
|
+
* the evidence chain naming the operation, the reason and the session by
|
|
1903
|
+
* its short digest. `WITHHELD`, with the upstream's status, when the call
|
|
1904
|
+
* reached the upstream and its answer was not relayed; `NOT_FORWARDED`
|
|
1905
|
+
* otherwise.
|
|
1906
|
+
*/
|
|
1907
|
+
subjectRefused(request, action, operation, code, session, upstreamStatus = null) {
|
|
1908
|
+
const execution = upstreamStatus === null ? "NOT_FORWARDED" : "WITHHELD";
|
|
1909
|
+
const status = code === "SUBJECT_TOKEN_AMBIGUOUS"
|
|
1910
|
+
? 400
|
|
1911
|
+
: code === "SUBJECT_SESSION_REQUIRED" ||
|
|
1912
|
+
code === "SUBJECT_SESSION_INVALID" ||
|
|
1913
|
+
code === "SUBJECT_TOKEN_INVALID"
|
|
1914
|
+
? 401
|
|
1915
|
+
: 403;
|
|
1916
|
+
this.metrics.requests.inc({ kind: "subject_refused" });
|
|
1917
|
+
this.count("subject_refused");
|
|
1918
|
+
this.link({
|
|
1919
|
+
event: "SUBJECT_REFUSED",
|
|
1920
|
+
operation,
|
|
1921
|
+
reason_codes: [code],
|
|
1922
|
+
session: session?.id ?? null,
|
|
1923
|
+
execution,
|
|
1924
|
+
});
|
|
1925
|
+
this.report({
|
|
1926
|
+
event: "INTERCEPTED",
|
|
1927
|
+
at: new Date(this.clock()).toISOString(),
|
|
1928
|
+
method: request.method.toUpperCase(),
|
|
1929
|
+
path: request.path,
|
|
1930
|
+
action,
|
|
1931
|
+
state: "REFUSED",
|
|
1932
|
+
verdict: null,
|
|
1933
|
+
reason_codes: [code],
|
|
1934
|
+
execution,
|
|
1935
|
+
mode: this.config.authority.mode,
|
|
1936
|
+
authority: this.demo === null ? "decionis" : "local/demo",
|
|
1937
|
+
intent_id: null,
|
|
1938
|
+
intent_hash: null,
|
|
1939
|
+
decision_id: null,
|
|
1940
|
+
dossier_id: null,
|
|
1941
|
+
upstream_status: upstreamStatus,
|
|
1942
|
+
finalization: null,
|
|
1943
|
+
latency_ms: 0,
|
|
1944
|
+
authority_ms: null,
|
|
1945
|
+
});
|
|
1946
|
+
return this.own(status, {
|
|
1947
|
+
state: "REFUSED",
|
|
1948
|
+
verdict: null,
|
|
1949
|
+
reason_codes: [code],
|
|
1950
|
+
execution,
|
|
1951
|
+
...(upstreamStatus === null ? {} : { upstream_status: upstreamStatus }),
|
|
1952
|
+
}, status === 401 ? { "www-authenticate": "AgentSafe-Session" } : {});
|
|
1953
|
+
}
|
|
1954
|
+
/**
|
|
1955
|
+
* The facts the gateway's API profile names for this call, when the profile
|
|
1956
|
+
* named its action: each at the top level of the trusted context, beside the
|
|
1957
|
+
* operation, exactly as a native executor reading the same profile states
|
|
1958
|
+
* them. The body is read for facts whether or not it is embedded.
|
|
1959
|
+
*/
|
|
1960
|
+
profileFacts(request, action) {
|
|
1961
|
+
const matched = this.profileMatch(request);
|
|
1962
|
+
if (matched === null || matched.action !== action)
|
|
1963
|
+
return {};
|
|
1964
|
+
return {
|
|
1965
|
+
...matched.facts,
|
|
1966
|
+
api_profile: { id: matched.profile, operation: matched.operation },
|
|
1967
|
+
};
|
|
1968
|
+
}
|
|
1969
|
+
profile() {
|
|
1970
|
+
const profileId = this.config.interception.profile;
|
|
1971
|
+
return profileId === null ? null : ApiProfiles.get(profileId);
|
|
1972
|
+
}
|
|
1973
|
+
/** What the gateway's API profile says about a call, its JSON body read when there is one. */
|
|
1974
|
+
profileMatch(request) {
|
|
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)
|
|
1981
|
+
return null;
|
|
1982
|
+
let body;
|
|
1983
|
+
if (request.body.length > 0 && /json/i.test(request.headers["content-type"] ?? "")) {
|
|
1984
|
+
try {
|
|
1985
|
+
body = JSON.parse(request.body.toString("utf8"));
|
|
1986
|
+
}
|
|
1987
|
+
catch {
|
|
1988
|
+
body = undefined;
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
return {
|
|
1992
|
+
method: request.method,
|
|
1993
|
+
path: request.path,
|
|
1994
|
+
query: Gateway.queryOf(request.search),
|
|
1995
|
+
...(body === undefined ? {} : { body }),
|
|
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
|
+
}
|
|
2022
|
+
}
|
|
818
2023
|
principalOf(captured) {
|
|
819
2024
|
const claimed = captured.intent.context["claimed_principal"];
|
|
820
2025
|
return typeof claimed === "string" ? claimed : this.config.actor.id;
|
|
@@ -832,9 +2037,15 @@ export class Gateway {
|
|
|
832
2037
|
let answer;
|
|
833
2038
|
if (production.status === "COMPLETED") {
|
|
834
2039
|
upstreamStatus = production.result.status;
|
|
835
|
-
|
|
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);
|
|
2044
|
+
answer = this.answer(request, production.result, {
|
|
836
2045
|
"agentsafe-mode": "SHADOW",
|
|
837
2046
|
"agentsafe-execution": "PASSTHROUGH",
|
|
2047
|
+
"agentsafe-shadow-verdict": seen === null ? "PENDING" : (seen.verdict ?? "NONE"),
|
|
2048
|
+
...(seen?.decisionId ? { "agentsafe-decision-id": seen.decisionId } : {}),
|
|
838
2049
|
});
|
|
839
2050
|
}
|
|
840
2051
|
else {
|
|
@@ -842,9 +2053,12 @@ export class Gateway {
|
|
|
842
2053
|
answer = this.failed(failure);
|
|
843
2054
|
}
|
|
844
2055
|
// The observation settles on its own bound and is reported when it does;
|
|
845
|
-
// the client's response never waits for the authority.
|
|
846
|
-
|
|
2056
|
+
// the client's response never waits for the authority, nor the ledger.
|
|
2057
|
+
const money = this.moneyOf(request);
|
|
2058
|
+
const settled = (observation, exposure) => {
|
|
847
2059
|
this.metrics.shadowDecisions.inc({ verdict: observation.verdict ?? "NONE" });
|
|
2060
|
+
if (exposure !== null)
|
|
2061
|
+
this.ledger.recordExposure(exposure.status);
|
|
848
2062
|
this.count("shadow");
|
|
849
2063
|
this.ledger.record(captured.intent.action, observation.verdict, new Date(this.clock()).toISOString(), upstreamStatus);
|
|
850
2064
|
this.report({
|
|
@@ -864,8 +2078,19 @@ export class Gateway {
|
|
|
864
2078
|
upstream_status: upstreamStatus,
|
|
865
2079
|
finalization: null,
|
|
866
2080
|
authority_ms: observation.durationMs,
|
|
2081
|
+
...(exposure === null ? {} : { exposure }),
|
|
867
2082
|
});
|
|
868
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));
|
|
869
2094
|
});
|
|
870
2095
|
return answer;
|
|
871
2096
|
}
|
|
@@ -893,6 +2118,7 @@ export class Gateway {
|
|
|
893
2118
|
if (decision.verdict === "BLOCK") {
|
|
894
2119
|
this.metrics.blocks.inc();
|
|
895
2120
|
this.count("blocks");
|
|
2121
|
+
this.observeRefusal(captured, "BLOCK");
|
|
896
2122
|
this.report({
|
|
897
2123
|
...this.interception(request, captured, startedAt),
|
|
898
2124
|
state: "BLOCK",
|
|
@@ -930,7 +2156,7 @@ export class Gateway {
|
|
|
930
2156
|
const resumeToken = randomBytes(32).toString("base64url");
|
|
931
2157
|
const entry = {
|
|
932
2158
|
captured,
|
|
933
|
-
request,
|
|
2159
|
+
request: this.holdable(request),
|
|
934
2160
|
decision,
|
|
935
2161
|
handoff: handoff === null ? null : { ...handoff, intent: captured.intent },
|
|
936
2162
|
heldAt: new Date(this.clock()).toISOString(),
|
|
@@ -947,6 +2173,7 @@ export class Gateway {
|
|
|
947
2173
|
resumable: handoff !== null,
|
|
948
2174
|
held: heldOk,
|
|
949
2175
|
});
|
|
2176
|
+
this.observeRefusal(captured, "ESCALATE");
|
|
950
2177
|
this.report({
|
|
951
2178
|
...this.interception(request, captured, startedAt),
|
|
952
2179
|
state: "ESCALATE",
|
|
@@ -1009,6 +2236,7 @@ export class Gateway {
|
|
|
1009
2236
|
});
|
|
1010
2237
|
return forwarded;
|
|
1011
2238
|
}
|
|
2239
|
+
this.observeRefusal(captured, "AUTHORITY_UNAVAILABLE");
|
|
1012
2240
|
this.report({
|
|
1013
2241
|
...this.interception(request, captured, startedAt),
|
|
1014
2242
|
state: "AUTHORITY_UNAVAILABLE",
|
|
@@ -1033,7 +2261,35 @@ export class Gateway {
|
|
|
1033
2261
|
/** An ALLOW: the grant claimed, the exact request sent once, the outcome finalized and relayed. */
|
|
1034
2262
|
async execute(request, captured, decision, startedAt, authorityMs) {
|
|
1035
2263
|
const intentId = captured.intent.intentId;
|
|
1036
|
-
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));
|
|
1037
2293
|
const forwardStarted = this.clock();
|
|
1038
2294
|
let outcome;
|
|
1039
2295
|
let forward;
|
|
@@ -1044,20 +2300,39 @@ export class Gateway {
|
|
|
1044
2300
|
forward = this.holder.release(intentId);
|
|
1045
2301
|
}
|
|
1046
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);
|
|
1047
2314
|
const base = {
|
|
1048
2315
|
...this.interception(request, captured, startedAt),
|
|
1049
2316
|
verdict: "ALLOW",
|
|
1050
2317
|
decision_id: decision.decisionId,
|
|
1051
2318
|
dossier_id: decision.dossierId,
|
|
1052
2319
|
authority_ms: authorityMs,
|
|
2320
|
+
...(exposure === null ? {} : { exposure }),
|
|
1053
2321
|
};
|
|
1054
2322
|
const finalization = "finalization" in outcome ? outcome.finalization : null;
|
|
1055
2323
|
const evidenceHeaders = {
|
|
1056
2324
|
"agentsafe-decision": "ALLOW",
|
|
1057
2325
|
...(decision.dossierId === null ? {} : { "agentsafe-dossier-id": decision.dossierId }),
|
|
1058
2326
|
"agentsafe-intent-hash": captured.intentHash,
|
|
2327
|
+
...(exposure === null ? {} : { "agentsafe-exposure": exposure.status }),
|
|
1059
2328
|
};
|
|
2329
|
+
if (check !== null && reserved.refused) {
|
|
2330
|
+
return this.exposureRefused(captured, decision, base, check, finalization);
|
|
2331
|
+
}
|
|
1060
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 });
|
|
1061
2336
|
this.report({
|
|
1062
2337
|
...base,
|
|
1063
2338
|
state: "ALLOW",
|
|
@@ -1065,10 +2340,15 @@ export class Gateway {
|
|
|
1065
2340
|
execution: "FORWARDED",
|
|
1066
2341
|
upstream_status: outcome.result.status,
|
|
1067
2342
|
finalization,
|
|
2343
|
+
effect: { confirmation: said.confirmation, reason_codes: said.reasonCodes },
|
|
2344
|
+
});
|
|
2345
|
+
return this.answer(request, outcome.result, {
|
|
2346
|
+
...evidenceHeaders,
|
|
2347
|
+
"agentsafe-execution": "FORWARDED",
|
|
1068
2348
|
});
|
|
1069
|
-
return this.relay(outcome.result, { ...evidenceHeaders, "agentsafe-execution": "FORWARDED" });
|
|
1070
2349
|
}
|
|
1071
2350
|
if (outcome.outcome === "DEFINITELY_NOT_EXECUTED" && forward.response !== null) {
|
|
2351
|
+
this.settleAttempt(request, captured, decision, "DEFINITE");
|
|
1072
2352
|
this.report({
|
|
1073
2353
|
...base,
|
|
1074
2354
|
state: "EXECUTION_FAILED",
|
|
@@ -1082,6 +2362,7 @@ export class Gateway {
|
|
|
1082
2362
|
if (outcome.outcome === "UNKNOWN_AFTER_DISPATCH") {
|
|
1083
2363
|
this.metrics.indeterminate.inc();
|
|
1084
2364
|
this.count("indeterminate");
|
|
2365
|
+
this.settleAttempt(request, captured, decision, "INDETERMINATE", check === null ? undefined : ExposureGate.reservationKey(binding));
|
|
1085
2366
|
const codes = [outcome.reason, ...(forward.failure === null ? [] : [forward.failure])];
|
|
1086
2367
|
this.report({
|
|
1087
2368
|
...base,
|
|
@@ -1136,13 +2417,191 @@ export class Gateway {
|
|
|
1136
2417
|
finalization,
|
|
1137
2418
|
});
|
|
1138
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
|
+
}
|
|
1139
2581
|
hold(intentId, entry) {
|
|
1140
|
-
this.
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
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
|
+
};
|
|
1146
2605
|
}
|
|
1147
2606
|
/**
|
|
1148
2607
|
* The hold under an id, for the caller presenting its token. A refusal is
|
|
@@ -1150,8 +2609,7 @@ export class Gateway {
|
|
|
1150
2609
|
* someone who read an intent id and is not its caller.
|
|
1151
2610
|
*/
|
|
1152
2611
|
heldFor(intentId, resumeToken) {
|
|
1153
|
-
this.
|
|
1154
|
-
const entry = this.held.get(intentId);
|
|
2612
|
+
const entry = this.holds.get(intentId);
|
|
1155
2613
|
if (entry === undefined)
|
|
1156
2614
|
return "ESCALATION_NOT_HELD";
|
|
1157
2615
|
if (resumeToken === null ||
|
|
@@ -1169,16 +2627,8 @@ export class Gateway {
|
|
|
1169
2627
|
return createHash("sha256").update(resumeToken, "utf8").digest();
|
|
1170
2628
|
}
|
|
1171
2629
|
release(intentId) {
|
|
1172
|
-
this.
|
|
1173
|
-
this.metrics.held.set(this.
|
|
1174
|
-
}
|
|
1175
|
-
expireHeld() {
|
|
1176
|
-
const now = this.clock();
|
|
1177
|
-
for (const [id, entry] of this.held) {
|
|
1178
|
-
if (entry.expiresAt <= now)
|
|
1179
|
-
this.held.delete(id);
|
|
1180
|
-
}
|
|
1181
|
-
this.metrics.held.set(this.held.size);
|
|
2630
|
+
this.holds.delete(intentId);
|
|
2631
|
+
this.metrics.held.set(this.holds.sweep());
|
|
1182
2632
|
}
|
|
1183
2633
|
holdBody(entry) {
|
|
1184
2634
|
return {
|
|
@@ -1229,7 +2679,7 @@ export class Gateway {
|
|
|
1229
2679
|
try {
|
|
1230
2680
|
const result = await this.upstream.send(request.method.toUpperCase(), request.path, request.search, this.upstream.headersFor(request), request.body, this.upstream.signal());
|
|
1231
2681
|
this.metrics.observeForwardLatency(this.clock() - startedAt);
|
|
1232
|
-
return this.
|
|
2682
|
+
return this.answer(request, result, extra);
|
|
1233
2683
|
}
|
|
1234
2684
|
catch (error) {
|
|
1235
2685
|
return this.failed(this.failureOf(error));
|
|
@@ -1326,10 +2776,21 @@ export class Gateway {
|
|
|
1326
2776
|
this.io.stdout(renderJson(report));
|
|
1327
2777
|
else
|
|
1328
2778
|
this.io.stdout(renderHuman(report, { color: this.io.color }));
|
|
2779
|
+
if (report.event === "INTERCEPTED")
|
|
2780
|
+
this.runs?.intercepted(report);
|
|
1329
2781
|
}
|
|
1330
|
-
/** One chained line on the gateway's own stream. */
|
|
2782
|
+
/** One chained line on the gateway's own stream, and where it went. */
|
|
1331
2783
|
link(fields) {
|
|
1332
|
-
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;
|
|
1333
2794
|
}
|
|
1334
2795
|
count(name) {
|
|
1335
2796
|
this.counts[name] = (this.counts[name] ?? 0) + 1;
|