@gpustack/loopwright 0.0.0-stage → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +191 -0
- package/README.md +356 -2
- package/bin/loopwright.js +3 -0
- package/node_modules/@loopwright/agent-pi/dist/adapter-v2.d.ts +9 -0
- package/node_modules/@loopwright/agent-pi/dist/adapter-v2.js +122 -0
- package/node_modules/@loopwright/agent-pi/dist/adapter.d.ts +30 -0
- package/node_modules/@loopwright/agent-pi/dist/adapter.js +340 -0
- package/node_modules/@loopwright/agent-pi/dist/admission.d.ts +25 -0
- package/node_modules/@loopwright/agent-pi/dist/admission.js +65 -0
- package/node_modules/@loopwright/agent-pi/dist/artifacts.d.ts +15 -0
- package/node_modules/@loopwright/agent-pi/dist/artifacts.js +76 -0
- package/node_modules/@loopwright/agent-pi/dist/boundary.d.ts +18 -0
- package/node_modules/@loopwright/agent-pi/dist/boundary.js +113 -0
- package/node_modules/@loopwright/agent-pi/dist/broker-channel.d.ts +4 -0
- package/node_modules/@loopwright/agent-pi/dist/broker-channel.js +121 -0
- package/node_modules/@loopwright/agent-pi/dist/candidate.d.ts +96 -0
- package/node_modules/@loopwright/agent-pi/dist/candidate.js +1712 -0
- package/node_modules/@loopwright/agent-pi/dist/capture.d.ts +39 -0
- package/node_modules/@loopwright/agent-pi/dist/capture.js +146 -0
- package/node_modules/@loopwright/agent-pi/dist/cas.d.ts +51 -0
- package/node_modules/@loopwright/agent-pi/dist/cas.js +836 -0
- package/node_modules/@loopwright/agent-pi/dist/catalog-api.d.ts +3 -0
- package/node_modules/@loopwright/agent-pi/dist/catalog-api.js +2 -0
- package/node_modules/@loopwright/agent-pi/dist/catalog.d.ts +39 -0
- package/node_modules/@loopwright/agent-pi/dist/catalog.js +280 -0
- package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.d.ts +9 -0
- package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.js +12 -0
- package/node_modules/@loopwright/agent-pi/dist/containers.d.ts +29 -0
- package/node_modules/@loopwright/agent-pi/dist/containers.js +160 -0
- package/node_modules/@loopwright/agent-pi/dist/context.d.ts +56 -0
- package/node_modules/@loopwright/agent-pi/dist/context.js +351 -0
- package/node_modules/@loopwright/agent-pi/dist/daemon.d.ts +8 -0
- package/node_modules/@loopwright/agent-pi/dist/daemon.js +52 -0
- package/node_modules/@loopwright/agent-pi/dist/deadline.d.ts +6 -0
- package/node_modules/@loopwright/agent-pi/dist/deadline.js +18 -0
- package/node_modules/@loopwright/agent-pi/dist/decode-capture.d.ts +39 -0
- package/node_modules/@loopwright/agent-pi/dist/decode-capture.js +287 -0
- package/node_modules/@loopwright/agent-pi/dist/descriptor.d.ts +12 -0
- package/node_modules/@loopwright/agent-pi/dist/descriptor.js +17 -0
- package/node_modules/@loopwright/agent-pi/dist/docker-absence.d.ts +2 -0
- package/node_modules/@loopwright/agent-pi/dist/docker-absence.js +9 -0
- package/node_modules/@loopwright/agent-pi/dist/errors.d.ts +7 -0
- package/node_modules/@loopwright/agent-pi/dist/errors.js +19 -0
- package/node_modules/@loopwright/agent-pi/dist/event-sequence.d.ts +6 -0
- package/node_modules/@loopwright/agent-pi/dist/event-sequence.js +64 -0
- package/node_modules/@loopwright/agent-pi/dist/events.d.ts +19 -0
- package/node_modules/@loopwright/agent-pi/dist/events.js +132 -0
- package/node_modules/@loopwright/agent-pi/dist/execution-guard.d.ts +9 -0
- package/node_modules/@loopwright/agent-pi/dist/execution-guard.js +25 -0
- package/node_modules/@loopwright/agent-pi/dist/execution-lease.d.ts +24 -0
- package/node_modules/@loopwright/agent-pi/dist/execution-lease.js +316 -0
- package/node_modules/@loopwright/agent-pi/dist/execution.d.ts +32 -0
- package/node_modules/@loopwright/agent-pi/dist/execution.js +476 -0
- package/node_modules/@loopwright/agent-pi/dist/external-mcp.d.ts +87 -0
- package/node_modules/@loopwright/agent-pi/dist/external-mcp.js +526 -0
- package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.d.ts +15 -0
- package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.js +74 -0
- package/node_modules/@loopwright/agent-pi/dist/host-session.d.ts +51 -0
- package/node_modules/@loopwright/agent-pi/dist/host-session.js +2094 -0
- package/node_modules/@loopwright/agent-pi/dist/http-mcp.d.ts +32 -0
- package/node_modules/@loopwright/agent-pi/dist/http-mcp.js +353 -0
- package/node_modules/@loopwright/agent-pi/dist/index.d.ts +7 -0
- package/node_modules/@loopwright/agent-pi/dist/index.js +4 -0
- package/node_modules/@loopwright/agent-pi/dist/lifecycle.d.ts +13 -0
- package/node_modules/@loopwright/agent-pi/dist/lifecycle.js +11 -0
- package/node_modules/@loopwright/agent-pi/dist/mcp-process.d.ts +35 -0
- package/node_modules/@loopwright/agent-pi/dist/mcp-process.js +92 -0
- package/node_modules/@loopwright/agent-pi/dist/mcp-transport.d.ts +25 -0
- package/node_modules/@loopwright/agent-pi/dist/mcp-transport.js +63 -0
- package/node_modules/@loopwright/agent-pi/dist/mcp.d.ts +23 -0
- package/node_modules/@loopwright/agent-pi/dist/mcp.js +212 -0
- package/node_modules/@loopwright/agent-pi/dist/operation.d.ts +5 -0
- package/node_modules/@loopwright/agent-pi/dist/operation.js +28 -0
- package/node_modules/@loopwright/agent-pi/dist/policy-v2.d.ts +10 -0
- package/node_modules/@loopwright/agent-pi/dist/policy-v2.js +64 -0
- package/node_modules/@loopwright/agent-pi/dist/policy.d.ts +13 -0
- package/node_modules/@loopwright/agent-pi/dist/policy.js +260 -0
- package/node_modules/@loopwright/agent-pi/dist/preflight.d.ts +60 -0
- package/node_modules/@loopwright/agent-pi/dist/preflight.js +700 -0
- package/node_modules/@loopwright/agent-pi/dist/progress-summary.d.ts +1 -0
- package/node_modules/@loopwright/agent-pi/dist/progress-summary.js +119 -0
- package/node_modules/@loopwright/agent-pi/dist/protocol.d.ts +17 -0
- package/node_modules/@loopwright/agent-pi/dist/protocol.js +131 -0
- package/node_modules/@loopwright/agent-pi/dist/provider.d.ts +62 -0
- package/node_modules/@loopwright/agent-pi/dist/provider.js +217 -0
- package/node_modules/@loopwright/agent-pi/dist/receipt.d.ts +3 -0
- package/node_modules/@loopwright/agent-pi/dist/receipt.js +64 -0
- package/node_modules/@loopwright/agent-pi/dist/recovery.d.ts +6 -0
- package/node_modules/@loopwright/agent-pi/dist/recovery.js +188 -0
- package/node_modules/@loopwright/agent-pi/dist/resources.d.ts +13 -0
- package/node_modules/@loopwright/agent-pi/dist/resources.js +81 -0
- package/node_modules/@loopwright/agent-pi/dist/response.d.ts +20 -0
- package/node_modules/@loopwright/agent-pi/dist/response.js +259 -0
- package/node_modules/@loopwright/agent-pi/dist/runtime-profile.d.ts +6 -0
- package/node_modules/@loopwright/agent-pi/dist/runtime-profile.js +37 -0
- package/node_modules/@loopwright/agent-pi/dist/sdk-worker.d.ts +14 -0
- package/node_modules/@loopwright/agent-pi/dist/sdk-worker.js +633 -0
- package/node_modules/@loopwright/agent-pi/dist/sender.d.ts +46 -0
- package/node_modules/@loopwright/agent-pi/dist/sender.js +553 -0
- package/node_modules/@loopwright/agent-pi/dist/session-host.d.ts +21 -0
- package/node_modules/@loopwright/agent-pi/dist/session-host.js +315 -0
- package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.d.ts +14 -0
- package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.js +102 -0
- package/node_modules/@loopwright/agent-pi/dist/snapshot.d.ts +19 -0
- package/node_modules/@loopwright/agent-pi/dist/snapshot.js +121 -0
- package/node_modules/@loopwright/agent-pi/dist/tool-process.d.ts +32 -0
- package/node_modules/@loopwright/agent-pi/dist/tool-process.js +85 -0
- package/node_modules/@loopwright/agent-pi/dist/tool-worker.d.ts +2 -0
- package/node_modules/@loopwright/agent-pi/dist/tool-worker.js +105 -0
- package/node_modules/@loopwright/agent-pi/dist/tools.d.ts +36 -0
- package/node_modules/@loopwright/agent-pi/dist/tools.js +128 -0
- package/node_modules/@loopwright/agent-pi/dist/types-v2.d.ts +71 -0
- package/node_modules/@loopwright/agent-pi/dist/types-v2.js +1 -0
- package/node_modules/@loopwright/agent-pi/dist/types.d.ts +314 -0
- package/node_modules/@loopwright/agent-pi/dist/types.js +1 -0
- package/node_modules/@loopwright/agent-pi/dist/usage.d.ts +18 -0
- package/node_modules/@loopwright/agent-pi/dist/usage.js +314 -0
- package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.d.ts +27 -0
- package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.js +142 -0
- package/node_modules/@loopwright/agent-pi/package.json +24 -0
- package/node_modules/@loopwright/agent-pi/runtime/Dockerfile +8 -0
- package/node_modules/@loopwright/agent-pi/runtime/seccomp.json +1 -0
- package/node_modules/@loopwright/cli/dist/arguments.d.ts +19 -0
- package/node_modules/@loopwright/cli/dist/arguments.js +358 -0
- package/node_modules/@loopwright/cli/dist/closure.d.ts +93 -0
- package/node_modules/@loopwright/cli/dist/closure.js +230 -0
- package/node_modules/@loopwright/cli/dist/draft.d.ts +9 -0
- package/node_modules/@loopwright/cli/dist/draft.js +106 -0
- package/node_modules/@loopwright/cli/dist/failure-matrix.d.ts +9 -0
- package/node_modules/@loopwright/cli/dist/failure-matrix.js +701 -0
- package/node_modules/@loopwright/cli/dist/index.d.ts +6 -0
- package/node_modules/@loopwright/cli/dist/index.js +5 -0
- package/node_modules/@loopwright/cli/dist/main.d.ts +22 -0
- package/node_modules/@loopwright/cli/dist/main.js +1855 -0
- package/node_modules/@loopwright/cli/package.json +16 -0
- package/node_modules/@loopwright/controller/dist/acceptance.d.ts +43 -0
- package/node_modules/@loopwright/controller/dist/acceptance.js +446 -0
- package/node_modules/@loopwright/controller/dist/benchmark-gate.d.ts +273 -0
- package/node_modules/@loopwright/controller/dist/benchmark-gate.js +3147 -0
- package/node_modules/@loopwright/controller/dist/budget-observations.d.ts +25 -0
- package/node_modules/@loopwright/controller/dist/budget-observations.js +139 -0
- package/node_modules/@loopwright/controller/dist/bundle.d.ts +26 -0
- package/node_modules/@loopwright/controller/dist/bundle.js +64 -0
- package/node_modules/@loopwright/controller/dist/capture.d.ts +89 -0
- package/node_modules/@loopwright/controller/dist/capture.js +587 -0
- package/node_modules/@loopwright/controller/dist/compile.d.ts +3 -0
- package/node_modules/@loopwright/controller/dist/compile.js +402 -0
- package/node_modules/@loopwright/controller/dist/config.d.ts +22 -0
- package/node_modules/@loopwright/controller/dist/config.js +255 -0
- package/node_modules/@loopwright/controller/dist/controller.d.ts +177 -0
- package/node_modules/@loopwright/controller/dist/controller.js +2135 -0
- package/node_modules/@loopwright/controller/dist/credentials.d.ts +29 -0
- package/node_modules/@loopwright/controller/dist/credentials.js +189 -0
- package/node_modules/@loopwright/controller/dist/deadlines.d.ts +18 -0
- package/node_modules/@loopwright/controller/dist/deadlines.js +71 -0
- package/node_modules/@loopwright/controller/dist/errors.d.ts +27 -0
- package/node_modules/@loopwright/controller/dist/errors.js +41 -0
- package/node_modules/@loopwright/controller/dist/events.d.ts +52 -0
- package/node_modules/@loopwright/controller/dist/events.js +228 -0
- package/node_modules/@loopwright/controller/dist/files.d.ts +51 -0
- package/node_modules/@loopwright/controller/dist/files.js +386 -0
- package/node_modules/@loopwright/controller/dist/finalize.d.ts +25 -0
- package/node_modules/@loopwright/controller/dist/finalize.js +32 -0
- package/node_modules/@loopwright/controller/dist/gate.d.ts +84 -0
- package/node_modules/@loopwright/controller/dist/gate.js +640 -0
- package/node_modules/@loopwright/controller/dist/git-objects.d.ts +11 -0
- package/node_modules/@loopwright/controller/dist/git-objects.js +59 -0
- package/node_modules/@loopwright/controller/dist/git-reader.d.ts +17 -0
- package/node_modules/@loopwright/controller/dist/git-reader.js +40 -0
- package/node_modules/@loopwright/controller/dist/handlers.d.ts +6 -0
- package/node_modules/@loopwright/controller/dist/handlers.js +45 -0
- package/node_modules/@loopwright/controller/dist/handoff.d.ts +71 -0
- package/node_modules/@loopwright/controller/dist/handoff.js +554 -0
- package/node_modules/@loopwright/controller/dist/index.d.ts +41 -0
- package/node_modules/@loopwright/controller/dist/index.js +21 -0
- package/node_modules/@loopwright/controller/dist/inspect.d.ts +30 -0
- package/node_modules/@loopwright/controller/dist/inspect.js +372 -0
- package/node_modules/@loopwright/controller/dist/interpolation.d.ts +9 -0
- package/node_modules/@loopwright/controller/dist/interpolation.js +79 -0
- package/node_modules/@loopwright/controller/dist/ownership.d.ts +41 -0
- package/node_modules/@loopwright/controller/dist/ownership.js +666 -0
- package/node_modules/@loopwright/controller/dist/parser.d.ts +5 -0
- package/node_modules/@loopwright/controller/dist/parser.js +200 -0
- package/node_modules/@loopwright/controller/dist/progress.d.ts +41 -0
- package/node_modules/@loopwright/controller/dist/progress.js +904 -0
- package/node_modules/@loopwright/controller/dist/publication.d.ts +60 -0
- package/node_modules/@loopwright/controller/dist/publication.js +329 -0
- package/node_modules/@loopwright/controller/dist/reconcile.d.ts +26 -0
- package/node_modules/@loopwright/controller/dist/reconcile.js +1378 -0
- package/node_modules/@loopwright/controller/dist/recovery.d.ts +10 -0
- package/node_modules/@loopwright/controller/dist/recovery.js +315 -0
- package/node_modules/@loopwright/controller/dist/refusal-record.d.ts +43 -0
- package/node_modules/@loopwright/controller/dist/refusal-record.js +150 -0
- package/node_modules/@loopwright/controller/dist/registry.d.ts +6 -0
- package/node_modules/@loopwright/controller/dist/registry.js +374 -0
- package/node_modules/@loopwright/controller/dist/repair.d.ts +31 -0
- package/node_modules/@loopwright/controller/dist/repair.js +102 -0
- package/node_modules/@loopwright/controller/dist/report.d.ts +64 -0
- package/node_modules/@loopwright/controller/dist/report.js +596 -0
- package/node_modules/@loopwright/controller/dist/retained.d.ts +284 -0
- package/node_modules/@loopwright/controller/dist/retained.js +193 -0
- package/node_modules/@loopwright/controller/dist/rules.d.ts +31 -0
- package/node_modules/@loopwright/controller/dist/rules.js +110 -0
- package/node_modules/@loopwright/controller/dist/run-eval.d.ts +115 -0
- package/node_modules/@loopwright/controller/dist/run-eval.js +959 -0
- package/node_modules/@loopwright/controller/dist/scheduler.d.ts +10 -0
- package/node_modules/@loopwright/controller/dist/scheduler.js +41 -0
- package/node_modules/@loopwright/controller/dist/schema.d.ts +17 -0
- package/node_modules/@loopwright/controller/dist/schema.js +78 -0
- package/node_modules/@loopwright/controller/dist/source.d.ts +69 -0
- package/node_modules/@loopwright/controller/dist/source.js +872 -0
- package/node_modules/@loopwright/controller/dist/step.d.ts +38 -0
- package/node_modules/@loopwright/controller/dist/step.js +1776 -0
- package/node_modules/@loopwright/controller/dist/storage.d.ts +90 -0
- package/node_modules/@loopwright/controller/dist/storage.js +1345 -0
- package/node_modules/@loopwright/controller/dist/submission.d.ts +51 -0
- package/node_modules/@loopwright/controller/dist/submission.js +292 -0
- package/node_modules/@loopwright/controller/dist/types.d.ts +585 -0
- package/node_modules/@loopwright/controller/dist/types.js +9 -0
- package/node_modules/@loopwright/controller/dist/verification.d.ts +124 -0
- package/node_modules/@loopwright/controller/dist/verification.js +1308 -0
- package/node_modules/@loopwright/controller/dist/verifier-protocol.d.ts +105 -0
- package/node_modules/@loopwright/controller/dist/verifier-protocol.js +1312 -0
- package/node_modules/@loopwright/controller/dist/verifier-worker.d.ts +1 -0
- package/node_modules/@loopwright/controller/dist/verifier-worker.js +33 -0
- package/node_modules/@loopwright/controller/package.json +12 -0
- package/node_modules/@loopwright/core/dist/acceptance.d.ts +108 -0
- package/node_modules/@loopwright/core/dist/acceptance.js +327 -0
- package/node_modules/@loopwright/core/dist/artifacts.d.ts +63 -0
- package/node_modules/@loopwright/core/dist/artifacts.js +356 -0
- package/node_modules/@loopwright/core/dist/boundary.d.ts +21 -0
- package/node_modules/@loopwright/core/dist/boundary.js +484 -0
- package/node_modules/@loopwright/core/dist/contracts.d.ts +287 -0
- package/node_modules/@loopwright/core/dist/contracts.js +694 -0
- package/node_modules/@loopwright/core/dist/diagnostics.d.ts +21 -0
- package/node_modules/@loopwright/core/dist/diagnostics.js +51 -0
- package/node_modules/@loopwright/core/dist/evidence.d.ts +92 -0
- package/node_modules/@loopwright/core/dist/evidence.js +85 -0
- package/node_modules/@loopwright/core/dist/graph.d.ts +8 -0
- package/node_modules/@loopwright/core/dist/graph.js +44 -0
- package/node_modules/@loopwright/core/dist/identity.d.ts +162 -0
- package/node_modules/@loopwright/core/dist/identity.js +80 -0
- package/node_modules/@loopwright/core/dist/index.d.ts +30 -0
- package/node_modules/@loopwright/core/dist/index.js +39 -0
- package/node_modules/@loopwright/core/dist/limits.d.ts +99 -0
- package/node_modules/@loopwright/core/dist/limits.js +59 -0
- package/node_modules/@loopwright/core/dist/results.d.ts +161 -0
- package/node_modules/@loopwright/core/dist/results.js +98 -0
- package/node_modules/@loopwright/core/dist/scope.d.ts +13 -0
- package/node_modules/@loopwright/core/dist/scope.js +154 -0
- package/node_modules/@loopwright/core/dist/scrubber.d.ts +13 -0
- package/node_modules/@loopwright/core/dist/scrubber.js +63 -0
- package/node_modules/@loopwright/core/dist/usage.d.ts +68 -0
- package/node_modules/@loopwright/core/dist/usage.js +56 -0
- package/node_modules/@loopwright/core/package.json +12 -0
- package/node_modules/@loopwright/decisions/dist/benchmark.d.ts +23 -0
- package/node_modules/@loopwright/decisions/dist/benchmark.js +337 -0
- package/node_modules/@loopwright/decisions/dist/client.d.ts +74 -0
- package/node_modules/@loopwright/decisions/dist/client.js +292 -0
- package/node_modules/@loopwright/decisions/dist/index.d.ts +15 -0
- package/node_modules/@loopwright/decisions/dist/index.js +8 -0
- package/node_modules/@loopwright/decisions/dist/nodes.d.ts +63 -0
- package/node_modules/@loopwright/decisions/dist/nodes.js +282 -0
- package/node_modules/@loopwright/decisions/dist/primitives.d.ts +36 -0
- package/node_modules/@loopwright/decisions/dist/primitives.js +300 -0
- package/node_modules/@loopwright/decisions/dist/redaction.d.ts +23 -0
- package/node_modules/@loopwright/decisions/dist/redaction.js +146 -0
- package/node_modules/@loopwright/decisions/dist/router.d.ts +55 -0
- package/node_modules/@loopwright/decisions/dist/router.js +248 -0
- package/node_modules/@loopwright/decisions/dist/schema.d.ts +25 -0
- package/node_modules/@loopwright/decisions/dist/schema.js +536 -0
- package/node_modules/@loopwright/decisions/dist/types.d.ts +394 -0
- package/node_modules/@loopwright/decisions/dist/types.js +80 -0
- package/node_modules/@loopwright/decisions/package.json +12 -0
- package/node_modules/@loopwright/github-app/dist/action.d.ts +90 -0
- package/node_modules/@loopwright/github-app/dist/action.js +2429 -0
- package/node_modules/@loopwright/github-app/dist/config.d.ts +23 -0
- package/node_modules/@loopwright/github-app/dist/config.js +297 -0
- package/node_modules/@loopwright/github-app/dist/digests.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/digests.js +1 -0
- package/node_modules/@loopwright/github-app/dist/index.d.ts +14 -0
- package/node_modules/@loopwright/github-app/dist/index.js +13 -0
- package/node_modules/@loopwright/github-app/dist/models-config.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/models-config.js +1 -0
- package/node_modules/@loopwright/github-app/dist/output-format.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/output-format.js +1 -0
- package/node_modules/@loopwright/github-app/dist/preflight.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/preflight.js +1 -0
- package/node_modules/@loopwright/github-app/dist/publisher.d.ts +58 -0
- package/node_modules/@loopwright/github-app/dist/publisher.js +1368 -0
- package/node_modules/@loopwright/github-app/dist/qualification.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/qualification.js +1 -0
- package/node_modules/@loopwright/github-app/dist/sandbox.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/sandbox.js +1 -0
- package/node_modules/@loopwright/github-app/dist/schema.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/schema.js +1 -0
- package/node_modules/@loopwright/github-app/dist/service.d.ts +52 -0
- package/node_modules/@loopwright/github-app/dist/service.js +1658 -0
- package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.d.ts +90 -0
- package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.js +392 -0
- package/node_modules/@loopwright/github-app/dist/taskpack.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/taskpack.js +1 -0
- package/node_modules/@loopwright/github-app/dist/tenant-queue.d.ts +44 -0
- package/node_modules/@loopwright/github-app/dist/tenant-queue.js +423 -0
- package/node_modules/@loopwright/github-app/dist/token-broker.d.ts +50 -0
- package/node_modules/@loopwright/github-app/dist/token-broker.js +262 -0
- package/node_modules/@loopwright/github-app/dist/turnkey-memory.d.ts +35 -0
- package/node_modules/@loopwright/github-app/dist/turnkey-memory.js +1654 -0
- package/node_modules/@loopwright/github-app/dist/turnkey.d.ts +16 -0
- package/node_modules/@loopwright/github-app/dist/turnkey.js +34 -0
- package/node_modules/@loopwright/github-app/dist/types.d.ts +220 -0
- package/node_modules/@loopwright/github-app/dist/types.js +14 -0
- package/node_modules/@loopwright/github-app/dist/upstreams.d.ts +13 -0
- package/node_modules/@loopwright/github-app/dist/upstreams.js +65 -0
- package/node_modules/@loopwright/github-app/dist/webhook.d.ts +34 -0
- package/node_modules/@loopwright/github-app/dist/webhook.js +241 -0
- package/node_modules/@loopwright/github-app/dist/yaml.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/yaml.js +1 -0
- package/node_modules/@loopwright/github-app/package.json +12 -0
- package/node_modules/@loopwright/hardware-runner/dist/config.d.ts +48 -0
- package/node_modules/@loopwright/hardware-runner/dist/config.js +719 -0
- package/node_modules/@loopwright/hardware-runner/dist/evaluator.d.ts +230 -0
- package/node_modules/@loopwright/hardware-runner/dist/evaluator.js +3178 -0
- package/node_modules/@loopwright/hardware-runner/dist/index.d.ts +13 -0
- package/node_modules/@loopwright/hardware-runner/dist/index.js +9 -0
- package/node_modules/@loopwright/hardware-runner/dist/provenance.d.ts +128 -0
- package/node_modules/@loopwright/hardware-runner/dist/provenance.js +1500 -0
- package/node_modules/@loopwright/hardware-runner/dist/queue.d.ts +81 -0
- package/node_modules/@loopwright/hardware-runner/dist/queue.js +1081 -0
- package/node_modules/@loopwright/hardware-runner/dist/relay-server.d.ts +13 -0
- package/node_modules/@loopwright/hardware-runner/dist/relay-server.js +2997 -0
- package/node_modules/@loopwright/hardware-runner/dist/types.d.ts +239 -0
- package/node_modules/@loopwright/hardware-runner/dist/types.js +12 -0
- package/node_modules/@loopwright/hardware-runner/dist/worker.d.ts +49 -0
- package/node_modules/@loopwright/hardware-runner/dist/worker.js +1648 -0
- package/node_modules/@loopwright/hardware-runner/package.json +12 -0
- package/node_modules/@loopwright/memory/dist/cas.d.ts +21 -0
- package/node_modules/@loopwright/memory/dist/cas.js +510 -0
- package/node_modules/@loopwright/memory/dist/compaction.d.ts +18 -0
- package/node_modules/@loopwright/memory/dist/compaction.js +110 -0
- package/node_modules/@loopwright/memory/dist/finalizer.d.ts +23 -0
- package/node_modules/@loopwright/memory/dist/finalizer.js +538 -0
- package/node_modules/@loopwright/memory/dist/index.d.ts +9 -0
- package/node_modules/@loopwright/memory/dist/index.js +8 -0
- package/node_modules/@loopwright/memory/dist/schema.d.ts +36 -0
- package/node_modules/@loopwright/memory/dist/schema.js +510 -0
- package/node_modules/@loopwright/memory/dist/selector.d.ts +7 -0
- package/node_modules/@loopwright/memory/dist/selector.js +157 -0
- package/node_modules/@loopwright/memory/dist/store.d.ts +51 -0
- package/node_modules/@loopwright/memory/dist/store.js +554 -0
- package/node_modules/@loopwright/memory/dist/types.d.ts +442 -0
- package/node_modules/@loopwright/memory/dist/types.js +8 -0
- package/node_modules/@loopwright/memory/dist/verifier.d.ts +5 -0
- package/node_modules/@loopwright/memory/dist/verifier.js +328 -0
- package/node_modules/@loopwright/memory/package.json +12 -0
- package/node_modules/@loopwright/state/dist/admission.d.ts +321 -0
- package/node_modules/@loopwright/state/dist/admission.js +199 -0
- package/node_modules/@loopwright/state/dist/boundary.d.ts +53 -0
- package/node_modules/@loopwright/state/dist/boundary.js +194 -0
- package/node_modules/@loopwright/state/dist/checkpoint.d.ts +16 -0
- package/node_modules/@loopwright/state/dist/checkpoint.js +84 -0
- package/node_modules/@loopwright/state/dist/clock.d.ts +8 -0
- package/node_modules/@loopwright/state/dist/clock.js +27 -0
- package/node_modules/@loopwright/state/dist/connection.d.ts +55 -0
- package/node_modules/@loopwright/state/dist/connection.js +391 -0
- package/node_modules/@loopwright/state/dist/errors.d.ts +13 -0
- package/node_modules/@loopwright/state/dist/errors.js +34 -0
- package/node_modules/@loopwright/state/dist/index.d.ts +3 -0
- package/node_modules/@loopwright/state/dist/index.js +1 -0
- package/node_modules/@loopwright/state/dist/journal.d.ts +119 -0
- package/node_modules/@loopwright/state/dist/journal.js +72 -0
- package/node_modules/@loopwright/state/dist/model.d.ts +40 -0
- package/node_modules/@loopwright/state/dist/model.js +58 -0
- package/node_modules/@loopwright/state/dist/ownership.d.ts +14 -0
- package/node_modules/@loopwright/state/dist/ownership.js +45 -0
- package/node_modules/@loopwright/state/dist/pages.d.ts +11 -0
- package/node_modules/@loopwright/state/dist/pages.js +41 -0
- package/node_modules/@loopwright/state/dist/receipts.d.ts +33 -0
- package/node_modules/@loopwright/state/dist/receipts.js +97 -0
- package/node_modules/@loopwright/state/dist/schema.d.ts +28 -0
- package/node_modules/@loopwright/state/dist/schema.js +41 -0
- package/node_modules/@loopwright/state/dist/settlement.d.ts +10 -0
- package/node_modules/@loopwright/state/dist/settlement.js +129 -0
- package/node_modules/@loopwright/state/dist/store.d.ts +52 -0
- package/node_modules/@loopwright/state/dist/store.js +100 -0
- package/node_modules/@loopwright/state/dist/types.d.ts +315 -0
- package/node_modules/@loopwright/state/dist/types.js +1 -0
- package/node_modules/@loopwright/state/package.json +12 -0
- package/node_modules/@loopwright/taskpack/dist/baseline-align.d.ts +195 -0
- package/node_modules/@loopwright/taskpack/dist/baseline-align.js +1847 -0
- package/node_modules/@loopwright/taskpack/dist/digests.d.ts +61 -0
- package/node_modules/@loopwright/taskpack/dist/digests.js +715 -0
- package/node_modules/@loopwright/taskpack/dist/index.d.ts +18 -0
- package/node_modules/@loopwright/taskpack/dist/index.js +17 -0
- package/node_modules/@loopwright/taskpack/dist/models-config.d.ts +112 -0
- package/node_modules/@loopwright/taskpack/dist/models-config.js +1026 -0
- package/node_modules/@loopwright/taskpack/dist/output-format.d.ts +28 -0
- package/node_modules/@loopwright/taskpack/dist/output-format.js +157 -0
- package/node_modules/@loopwright/taskpack/dist/preflight.d.ts +130 -0
- package/node_modules/@loopwright/taskpack/dist/preflight.js +1497 -0
- package/node_modules/@loopwright/taskpack/dist/qualification.d.ts +23 -0
- package/node_modules/@loopwright/taskpack/dist/qualification.js +120 -0
- package/node_modules/@loopwright/taskpack/dist/sandbox.d.ts +121 -0
- package/node_modules/@loopwright/taskpack/dist/sandbox.js +2642 -0
- package/node_modules/@loopwright/taskpack/dist/schema.d.ts +197 -0
- package/node_modules/@loopwright/taskpack/dist/schema.js +4189 -0
- package/node_modules/@loopwright/taskpack/dist/scrubber.d.ts +47 -0
- package/node_modules/@loopwright/taskpack/dist/scrubber.js +283 -0
- package/node_modules/@loopwright/taskpack/dist/suite.d.ts +124 -0
- package/node_modules/@loopwright/taskpack/dist/suite.js +3256 -0
- package/node_modules/@loopwright/taskpack/dist/taskpack.d.ts +154 -0
- package/node_modules/@loopwright/taskpack/dist/taskpack.js +3634 -0
- package/node_modules/@loopwright/taskpack/dist/turnkey-memory.d.ts +122 -0
- package/node_modules/@loopwright/taskpack/dist/turnkey-memory.js +483 -0
- package/node_modules/@loopwright/taskpack/dist/turnkey.d.ts +437 -0
- package/node_modules/@loopwright/taskpack/dist/turnkey.js +7335 -0
- package/node_modules/@loopwright/taskpack/dist/types.d.ts +1274 -0
- package/node_modules/@loopwright/taskpack/dist/types.js +99 -0
- package/node_modules/@loopwright/taskpack/dist/upstreams.d.ts +261 -0
- package/node_modules/@loopwright/taskpack/dist/upstreams.js +2242 -0
- package/node_modules/@loopwright/taskpack/dist/yaml.d.ts +18 -0
- package/node_modules/@loopwright/taskpack/dist/yaml.js +167 -0
- package/node_modules/@loopwright/taskpack/package.json +12 -0
- package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.d.ts +137 -0
- package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.js +474 -0
- package/node_modules/@loopwright/taskpack-runner/dist/corpus.d.ts +8 -0
- package/node_modules/@loopwright/taskpack-runner/dist/corpus.js +129 -0
- package/node_modules/@loopwright/taskpack-runner/dist/index.d.ts +13 -0
- package/node_modules/@loopwright/taskpack-runner/dist/index.js +7 -0
- package/node_modules/@loopwright/taskpack-runner/dist/intake.d.ts +149 -0
- package/node_modules/@loopwright/taskpack-runner/dist/intake.js +135 -0
- package/node_modules/@loopwright/taskpack-runner/dist/parity.d.ts +130 -0
- package/node_modules/@loopwright/taskpack-runner/dist/parity.js +927 -0
- package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.d.ts +68 -0
- package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.js +517 -0
- package/node_modules/@loopwright/taskpack-runner/dist/service.d.ts +149 -0
- package/node_modules/@loopwright/taskpack-runner/dist/service.js +1796 -0
- package/node_modules/@loopwright/taskpack-runner/dist/types.d.ts +29 -0
- package/node_modules/@loopwright/taskpack-runner/dist/types.js +11 -0
- package/node_modules/@loopwright/taskpack-runner/package.json +12 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/README.md +77 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/support-records.md +57 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/supported-runners.md +98 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/manifest.json +205 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/expand_matrix.sh +273 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/matrix.yaml +280 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/resolve_dockerfile.sh +24 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pyproject.toml +46 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/runtime_runner/runner.py.json +5270 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/discovery/legacy-support.md +86 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/github/service.py +401 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/analysis.json +95 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/ready.json +109 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_assemble.py +263 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_check_draft.py +333 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_checks.py +1099 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_discovery.py +817 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_proposal.py +658 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_publish.py +987 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_summary.py +107 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/agent.py +610 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/assemble.py +84 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/check_draft.py +94 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/checks.py +1002 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/discovery.py +789 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/model.py +557 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/progress.py +174 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/analysis.md +40 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/proposal.md +65 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/repair.md +17 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/proposal.py +903 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/publish.py +997 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/summary.py +131 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/tool-versions.json +133 -0
- package/node_modules/package-lock.json +3025 -0
- package/package-lock.json +3025 -0
- package/package.json +52 -4
|
@@ -0,0 +1,2997 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { constants, linkSync, lstatSync, realpathSync, statSync, unlinkSync } from 'node:fs';
|
|
3
|
+
import { chmod, link, lstat, mkdir, open, opendir, unlink } from 'node:fs/promises';
|
|
4
|
+
import { createServer as createHttpServer, } from 'node:http';
|
|
5
|
+
import { createServer as createHttpsServer } from 'node:https';
|
|
6
|
+
import { dirname, join, resolve } from 'node:path';
|
|
7
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
8
|
+
import { isVerifierNamespacePath, LIMITS, SecretScrubber, validateRelativePath, VERIFIER_ARTIFACT_LIMITS, } from '@loopwright/core';
|
|
9
|
+
import { readBoundedRegularFile } from '@loopwright/taskpack';
|
|
10
|
+
import { assertNoSymlinkAncestors, canonicalJson, expectNullProtoRecord, hasLoneSurrogate, normalizeRelayServerConfig, parseStrictJsonBytes, toNullPrototypeValue, validateWorkerCapabilitiesObject, } from './config.js';
|
|
11
|
+
import { MAX_ACQUIRE_WAIT_MS, RelayPullQueue, timingSafeEqualStrings, verdictMatchesRequestBinding, } from './queue.js';
|
|
12
|
+
import { HardwareRunnerError, } from './types.js';
|
|
13
|
+
export const MAX_CONTROL_BODY_BYTES = 65_536;
|
|
14
|
+
export const MAX_RECEIPT_FILE_BYTES = MAX_CONTROL_BODY_BYTES + 256;
|
|
15
|
+
export const MAX_OPERATION_FILE_BYTES = MAX_CONTROL_BODY_BYTES + 512;
|
|
16
|
+
export const MAX_CAS_CHUNK_BYTES = 1_048_576;
|
|
17
|
+
export const EMPTY_SHA256_HEX = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
|
|
18
|
+
const SHA256_HEX_RE = /^[0-9a-f]{64}$/;
|
|
19
|
+
const SHA1_HEX_RE = /^[0-9a-f]{40}$/;
|
|
20
|
+
const IDENTIFIER_RE = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/;
|
|
21
|
+
const SAFE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
22
|
+
const SAFE_FILENAME_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
23
|
+
const REPOSITORY_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/;
|
|
24
|
+
const REVISION_RE = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;
|
|
25
|
+
const METRIC_KEY_RE = /^[A-Za-z_][A-Za-z0-9._-]*$/;
|
|
26
|
+
const DOTTED_VERSION_RE = /^\d+(?:\.\d+)*$/;
|
|
27
|
+
const PRINTABLE_ASCII_RE = /^[\x20-\x7E]+$/;
|
|
28
|
+
const CONTROL_CHAR_RE = /[\r\n\t\p{C}]/u;
|
|
29
|
+
const FORBIDDEN_METRIC_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
30
|
+
const DARWIN_ROOT_SYMLINKS = new Set(['/var', '/tmp', '/etc']);
|
|
31
|
+
const SECRET_SCAN_MIN_OVERLAP_BYTES = 16_384;
|
|
32
|
+
const SECRET_SCAN_MAX_OVERLAP_BYTES = 262_144;
|
|
33
|
+
function isAllowedOsRootSymlink(targetPath) {
|
|
34
|
+
return process.platform === 'darwin' && DARWIN_ROOT_SYMLINKS.has(targetPath);
|
|
35
|
+
}
|
|
36
|
+
function encodedSecretForms(secret) {
|
|
37
|
+
return [
|
|
38
|
+
secret,
|
|
39
|
+
JSON.stringify(secret).slice(1, -1),
|
|
40
|
+
encodeURIComponent(secret),
|
|
41
|
+
Buffer.from(secret, 'utf8').toString('base64'),
|
|
42
|
+
];
|
|
43
|
+
}
|
|
44
|
+
export function computeSecretScanOverlapBytes(secrets) {
|
|
45
|
+
let maxEncodedBytes = 0;
|
|
46
|
+
for (const secret of secrets) {
|
|
47
|
+
if (typeof secret !== 'string' || secret.length === 0)
|
|
48
|
+
continue;
|
|
49
|
+
for (const form of encodedSecretForms(secret)) {
|
|
50
|
+
const len = Buffer.byteLength(form, 'utf8');
|
|
51
|
+
if (len > maxEncodedBytes) {
|
|
52
|
+
maxEncodedBytes = len;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return Math.min(SECRET_SCAN_MAX_OVERLAP_BYTES, Math.max(SECRET_SCAN_MIN_OVERLAP_BYTES, maxEncodedBytes + 4));
|
|
57
|
+
}
|
|
58
|
+
export function signRelayPayload(secret, payload) {
|
|
59
|
+
return createHmac('sha256', secret).update(payload).digest('hex');
|
|
60
|
+
}
|
|
61
|
+
export function verifyRelaySignature(secret, payload, signatureHeader) {
|
|
62
|
+
const hex = signatureHeader.startsWith('sha256=') ? signatureHeader.slice(7) : signatureHeader;
|
|
63
|
+
if (!SHA256_HEX_RE.test(hex))
|
|
64
|
+
return false;
|
|
65
|
+
const expected = Buffer.from(hex, 'hex');
|
|
66
|
+
const observed = createHmac('sha256', secret).update(payload).digest();
|
|
67
|
+
return expected.byteLength === observed.byteLength && timingSafeEqual(expected, observed);
|
|
68
|
+
}
|
|
69
|
+
export function signBenchmarkVerdict(secret, verdict) {
|
|
70
|
+
return signRelayPayload(secret, canonicalJson(verdict));
|
|
71
|
+
}
|
|
72
|
+
export function verifyBenchmarkVerdictSignature(secret, receiptOrVerdict, signatureHex) {
|
|
73
|
+
const stripped = Object.create(null);
|
|
74
|
+
for (const key of Object.keys(receiptOrVerdict)) {
|
|
75
|
+
if (key === 'signature' || !Object.hasOwn(receiptOrVerdict, key) || receiptOrVerdict[key] === undefined)
|
|
76
|
+
continue;
|
|
77
|
+
stripped[key] = receiptOrVerdict[key];
|
|
78
|
+
}
|
|
79
|
+
let serialized;
|
|
80
|
+
try {
|
|
81
|
+
serialized = canonicalJson(stripped);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
return verifyRelaySignature(secret, serialized, signatureHex);
|
|
87
|
+
}
|
|
88
|
+
function wireInvalid(message, path = '/') {
|
|
89
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', message, path);
|
|
90
|
+
}
|
|
91
|
+
function parseIntStrict(value, min, max, path) {
|
|
92
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || Object.is(value, -0) || value < min || value > max) {
|
|
93
|
+
wireInvalid(`expected integer in ${min}..${max}`, path);
|
|
94
|
+
}
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
97
|
+
function parseStringStrict(value, min, max, path) {
|
|
98
|
+
if (typeof value !== 'string' || value.length < min || value.length > max || hasLoneSurrogate(value)) {
|
|
99
|
+
wireInvalid(`expected string length ${min}..${max}`, path);
|
|
100
|
+
}
|
|
101
|
+
return value;
|
|
102
|
+
}
|
|
103
|
+
function parsePrintableText(value, min, max, path, asciiOnly = false) {
|
|
104
|
+
const s = parseStringStrict(value, min, max, path);
|
|
105
|
+
if (s.trim() !== s)
|
|
106
|
+
wireInvalid('leading or trailing whitespace forbidden', path);
|
|
107
|
+
if (asciiOnly) {
|
|
108
|
+
if (!PRINTABLE_ASCII_RE.test(s))
|
|
109
|
+
wireInvalid('expected printable ASCII', path);
|
|
110
|
+
}
|
|
111
|
+
else if (CONTROL_CHAR_RE.test(s)) {
|
|
112
|
+
wireInvalid('control characters forbidden', path);
|
|
113
|
+
}
|
|
114
|
+
return s;
|
|
115
|
+
}
|
|
116
|
+
function parseIdentifier(value, path) {
|
|
117
|
+
const s = parseStringStrict(value, 1, LIMITS.identifier, path);
|
|
118
|
+
if (!IDENTIFIER_RE.test(s))
|
|
119
|
+
wireInvalid('invalid identifier', path);
|
|
120
|
+
return s;
|
|
121
|
+
}
|
|
122
|
+
function parseSafeId(value, path) {
|
|
123
|
+
const s = parseStringStrict(value, 1, 128, path);
|
|
124
|
+
if (!SAFE_ID_RE.test(s))
|
|
125
|
+
wireInvalid('invalid identifier token', path);
|
|
126
|
+
return s;
|
|
127
|
+
}
|
|
128
|
+
function parseOperationId(value, path) {
|
|
129
|
+
const s = parseStringStrict(value, 1, 128, path);
|
|
130
|
+
if (!SAFE_FILENAME_ID_RE.test(s) || s === '.' || s === '..') {
|
|
131
|
+
wireInvalid('invalid operationId', path);
|
|
132
|
+
}
|
|
133
|
+
return s;
|
|
134
|
+
}
|
|
135
|
+
function parseSha256Hex(value, path) {
|
|
136
|
+
const s = parseStringStrict(value, 64, 64, path);
|
|
137
|
+
if (!SHA256_HEX_RE.test(s))
|
|
138
|
+
wireInvalid('expected 64-char lowercase sha256 hex', path);
|
|
139
|
+
return s;
|
|
140
|
+
}
|
|
141
|
+
const DIGEST_KEYS = new Set(['algorithm', 'hex']);
|
|
142
|
+
function parseDigest(value, path) {
|
|
143
|
+
const obj = expectNullProtoRecord(value, DIGEST_KEYS, ['algorithm', 'hex'], 'ARTIFACT_INVALID', path);
|
|
144
|
+
if (obj.algorithm !== 'sha256')
|
|
145
|
+
wireInvalid('digest algorithm must be sha256', `${path}/algorithm`);
|
|
146
|
+
const hex = parseSha256Hex(obj.hex, `${path}/hex`);
|
|
147
|
+
return Object.freeze({ algorithm: 'sha256', hex });
|
|
148
|
+
}
|
|
149
|
+
const SUBJECT_KEYS = new Set([
|
|
150
|
+
'lockHash',
|
|
151
|
+
'contractHash',
|
|
152
|
+
'repository',
|
|
153
|
+
'baseRevision',
|
|
154
|
+
'sourceRevision',
|
|
155
|
+
'candidateDigest',
|
|
156
|
+
'targetMatrixDigest',
|
|
157
|
+
]);
|
|
158
|
+
function parseSubject(value, path) {
|
|
159
|
+
const obj = expectNullProtoRecord(value, SUBJECT_KEYS, ['lockHash', 'contractHash', 'repository', 'baseRevision', 'sourceRevision', 'candidateDigest', 'targetMatrixDigest'], 'ARTIFACT_INVALID', path);
|
|
160
|
+
const repository = parseStringStrict(obj.repository, 1, 256, `${path}/repository`);
|
|
161
|
+
if (!REPOSITORY_RE.test(repository))
|
|
162
|
+
wireInvalid('invalid subject.repository', `${path}/repository`);
|
|
163
|
+
const baseRevision = parseStringStrict(obj.baseRevision, 1, 128, `${path}/baseRevision`);
|
|
164
|
+
if (!REVISION_RE.test(baseRevision))
|
|
165
|
+
wireInvalid('invalid subject.baseRevision', `${path}/baseRevision`);
|
|
166
|
+
const sourceRevision = parseStringStrict(obj.sourceRevision, 1, 128, `${path}/sourceRevision`);
|
|
167
|
+
if (!REVISION_RE.test(sourceRevision))
|
|
168
|
+
wireInvalid('invalid subject.sourceRevision', `${path}/sourceRevision`);
|
|
169
|
+
return Object.freeze({
|
|
170
|
+
lockHash: parseDigest(obj.lockHash, `${path}/lockHash`),
|
|
171
|
+
contractHash: parseDigest(obj.contractHash, `${path}/contractHash`),
|
|
172
|
+
repository,
|
|
173
|
+
baseRevision,
|
|
174
|
+
sourceRevision,
|
|
175
|
+
candidateDigest: parseDigest(obj.candidateDigest, `${path}/candidateDigest`),
|
|
176
|
+
targetMatrixDigest: obj.targetMatrixDigest === null
|
|
177
|
+
? null
|
|
178
|
+
: parseDigest(obj.targetMatrixDigest, `${path}/targetMatrixDigest`),
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
const HARDWARE_TARGET_KEYS = new Set([
|
|
182
|
+
'accelerator',
|
|
183
|
+
'isolationMode',
|
|
184
|
+
'deviceCount',
|
|
185
|
+
'driverConstraint',
|
|
186
|
+
'topology',
|
|
187
|
+
]);
|
|
188
|
+
function isValidDottedVersion(value) {
|
|
189
|
+
if (!value.length || !DOTTED_VERSION_RE.test(value))
|
|
190
|
+
return false;
|
|
191
|
+
return value.split('.').every(seg => {
|
|
192
|
+
const n = Number(seg);
|
|
193
|
+
return Number.isSafeInteger(n) && n >= 0;
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
function parseHardwareTarget(value, path) {
|
|
197
|
+
const obj = expectNullProtoRecord(value, HARDWARE_TARGET_KEYS, ['accelerator', 'isolationMode'], 'ARTIFACT_INVALID', path);
|
|
198
|
+
const accelerator = parsePrintableText(obj.accelerator, 1, 64, `${path}/accelerator`, true);
|
|
199
|
+
if (obj.isolationMode !== 'whole_device' && obj.isolationMode !== 'sliced') {
|
|
200
|
+
wireInvalid('isolationMode must be "whole_device" or "sliced"', `${path}/isolationMode`);
|
|
201
|
+
}
|
|
202
|
+
const deviceCount = Object.hasOwn(obj, 'deviceCount')
|
|
203
|
+
? parseIntStrict(obj.deviceCount, 1, 64, `${path}/deviceCount`)
|
|
204
|
+
: undefined;
|
|
205
|
+
let driverConstraint;
|
|
206
|
+
if (Object.hasOwn(obj, 'driverConstraint')) {
|
|
207
|
+
driverConstraint = parsePrintableText(obj.driverConstraint, 1, 128, `${path}/driverConstraint`, false);
|
|
208
|
+
if (driverConstraint.startsWith('>=') && !isValidDottedVersion(driverConstraint.slice(2))) {
|
|
209
|
+
wireInvalid('invalid >= dotted version driverConstraint', `${path}/driverConstraint`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
const topology = Object.hasOwn(obj, 'topology')
|
|
213
|
+
? parsePrintableText(obj.topology, 1, 128, `${path}/topology`, false)
|
|
214
|
+
: undefined;
|
|
215
|
+
return Object.freeze({
|
|
216
|
+
accelerator,
|
|
217
|
+
isolationMode: obj.isolationMode,
|
|
218
|
+
...(deviceCount !== undefined ? { deviceCount } : {}),
|
|
219
|
+
...(driverConstraint !== undefined ? { driverConstraint } : {}),
|
|
220
|
+
...(topology !== undefined ? { topology } : {}),
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
const BOUNDS_RULE_KEYS = new Set(['kind', 'metric', 'min', 'max']);
|
|
224
|
+
const COMPARATIVE_RULE_KEYS = new Set(['kind', 'metric', 'baselineMetric', 'operator', 'threshold']);
|
|
225
|
+
function parseMetricKey(value, path) {
|
|
226
|
+
const key = parseStringStrict(value, 1, LIMITS.metricKey, path);
|
|
227
|
+
if (FORBIDDEN_METRIC_KEYS.has(key) || !METRIC_KEY_RE.test(key)) {
|
|
228
|
+
wireInvalid('invalid metric key', path);
|
|
229
|
+
}
|
|
230
|
+
return key;
|
|
231
|
+
}
|
|
232
|
+
function parseFiniteControlNumber(value, path) {
|
|
233
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || Object.is(value, -0)) {
|
|
234
|
+
wireInvalid('expected finite number (not -0)', path);
|
|
235
|
+
}
|
|
236
|
+
return value;
|
|
237
|
+
}
|
|
238
|
+
function parseMetricThresholdRule(value, path) {
|
|
239
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
240
|
+
wireInvalid('expected threshold rule object', path);
|
|
241
|
+
}
|
|
242
|
+
const rawObj = value;
|
|
243
|
+
if (!Object.hasOwn(rawObj, 'kind'))
|
|
244
|
+
wireInvalid('missing threshold rule kind', `${path}/kind`);
|
|
245
|
+
if (rawObj.kind === 'bounds') {
|
|
246
|
+
const obj = expectNullProtoRecord(value, BOUNDS_RULE_KEYS, ['kind', 'metric'], 'ARTIFACT_INVALID', path);
|
|
247
|
+
const metric = parseMetricKey(obj.metric, `${path}/metric`);
|
|
248
|
+
const min = Object.hasOwn(obj, 'min') ? parseFiniteControlNumber(obj.min, `${path}/min`) : undefined;
|
|
249
|
+
const max = Object.hasOwn(obj, 'max') ? parseFiniteControlNumber(obj.max, `${path}/max`) : undefined;
|
|
250
|
+
if (min === undefined && max === undefined) {
|
|
251
|
+
wireInvalid('bounds threshold rule requires min or max', path);
|
|
252
|
+
}
|
|
253
|
+
if (min !== undefined && max !== undefined && min > max) {
|
|
254
|
+
wireInvalid('bounds min must not exceed max', path);
|
|
255
|
+
}
|
|
256
|
+
return Object.freeze({
|
|
257
|
+
kind: 'bounds',
|
|
258
|
+
metric,
|
|
259
|
+
...(min !== undefined ? { min } : {}),
|
|
260
|
+
...(max !== undefined ? { max } : {}),
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
if (rawObj.kind === 'comparative') {
|
|
264
|
+
const obj = expectNullProtoRecord(value, COMPARATIVE_RULE_KEYS, ['kind', 'metric', 'baselineMetric', 'operator', 'threshold'], 'ARTIFACT_INVALID', path);
|
|
265
|
+
const metric = parseMetricKey(obj.metric, `${path}/metric`);
|
|
266
|
+
const baselineMetric = parseMetricKey(obj.baselineMetric, `${path}/baselineMetric`);
|
|
267
|
+
if (obj.operator !== 'min_ratio' && obj.operator !== 'max_ratio' && obj.operator !== 'max_delta') {
|
|
268
|
+
wireInvalid('invalid comparative operator', `${path}/operator`);
|
|
269
|
+
}
|
|
270
|
+
const threshold = parseFiniteControlNumber(obj.threshold, `${path}/threshold`);
|
|
271
|
+
return Object.freeze({
|
|
272
|
+
kind: 'comparative',
|
|
273
|
+
metric,
|
|
274
|
+
baselineMetric,
|
|
275
|
+
operator: obj.operator,
|
|
276
|
+
threshold,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
wireInvalid('unsupported threshold rule kind', `${path}/kind`);
|
|
280
|
+
}
|
|
281
|
+
const BASE_TREE_KEYS = new Set(['objectFormat', 'commitOid', 'treeOid']);
|
|
282
|
+
const BASE_TREE_BUNDLE_KEYS = new Set(['digest', 'byteLength']);
|
|
283
|
+
const CANDIDATE_ENTRY_KEYS = new Set(['name', 'digest', 'byteLength', 'mode']);
|
|
284
|
+
const CANDIDATE_ARTIFACTS_KEYS = new Set(['entries', 'deleted', 'baseTree', 'baseTreeBundle']);
|
|
285
|
+
function parseBaseTreeAnchor(value, path) {
|
|
286
|
+
const obj = expectNullProtoRecord(value, BASE_TREE_KEYS, ['objectFormat', 'commitOid', 'treeOid'], 'ARTIFACT_INVALID', path);
|
|
287
|
+
if (obj.objectFormat !== 'sha1' && obj.objectFormat !== 'sha256') {
|
|
288
|
+
wireInvalid('objectFormat must be sha1 or sha256', `${path}/objectFormat`);
|
|
289
|
+
}
|
|
290
|
+
const oidRe = obj.objectFormat === 'sha1' ? SHA1_HEX_RE : SHA256_HEX_RE;
|
|
291
|
+
const commitOid = parseStringStrict(obj.commitOid, 40, 64, `${path}/commitOid`);
|
|
292
|
+
const treeOid = parseStringStrict(obj.treeOid, 40, 64, `${path}/treeOid`);
|
|
293
|
+
if (!oidRe.test(commitOid) || !oidRe.test(treeOid)) {
|
|
294
|
+
wireInvalid('invalid baseTree oid hex', path);
|
|
295
|
+
}
|
|
296
|
+
return Object.freeze({ objectFormat: obj.objectFormat, commitOid, treeOid });
|
|
297
|
+
}
|
|
298
|
+
function parseBaseTreeBundle(value, maxBlobBytes, path) {
|
|
299
|
+
const obj = expectNullProtoRecord(value, BASE_TREE_BUNDLE_KEYS, ['digest', 'byteLength'], 'ARTIFACT_INVALID', path);
|
|
300
|
+
const digest = parseDigest(obj.digest, `${path}/digest`);
|
|
301
|
+
const upperBound = Math.min(maxBlobBytes, VERIFIER_ARTIFACT_LIMITS.maxFileBytes);
|
|
302
|
+
const byteLength = parseIntStrict(obj.byteLength, 12, upperBound, `${path}/byteLength`);
|
|
303
|
+
return Object.freeze({ digest, byteLength });
|
|
304
|
+
}
|
|
305
|
+
function collectDeclaredInputBlobs(artifacts) {
|
|
306
|
+
if (artifacts.baseTreeBundle === undefined) {
|
|
307
|
+
return artifacts.entries;
|
|
308
|
+
}
|
|
309
|
+
return [...artifacts.entries, artifacts.baseTreeBundle];
|
|
310
|
+
}
|
|
311
|
+
function parseCandidateRelativeName(value, path) {
|
|
312
|
+
const raw = parseStringStrict(value, 1, LIMITS.path, path);
|
|
313
|
+
const res = validateRelativePath(raw);
|
|
314
|
+
if (!res.ok || isVerifierNamespacePath(res.value) || res.value.split('/').some(seg => seg.toLowerCase() === '.git')) {
|
|
315
|
+
wireInvalid('invalid candidate relative path', path);
|
|
316
|
+
}
|
|
317
|
+
return res.value;
|
|
318
|
+
}
|
|
319
|
+
function parseCandidateArtifacts(value, maxBlobBytes, path) {
|
|
320
|
+
const obj = expectNullProtoRecord(value, CANDIDATE_ARTIFACTS_KEYS, ['entries', 'deleted'], 'ARTIFACT_INVALID', path);
|
|
321
|
+
if (!Array.isArray(obj.entries) || obj.entries.length > 4_096) {
|
|
322
|
+
wireInvalid('candidateArtifacts.entries must be a bounded array', `${path}/entries`);
|
|
323
|
+
}
|
|
324
|
+
if (!Array.isArray(obj.deleted) || obj.deleted.length > 4_096) {
|
|
325
|
+
wireInvalid('candidateArtifacts.deleted must be a bounded array', `${path}/deleted`);
|
|
326
|
+
}
|
|
327
|
+
const seenPaths = new Set();
|
|
328
|
+
const entries = obj.entries.map((rawEntry, idx) => {
|
|
329
|
+
const entryPath = `${path}/entries/${idx}`;
|
|
330
|
+
const item = expectNullProtoRecord(rawEntry, CANDIDATE_ENTRY_KEYS, ['name', 'digest', 'byteLength'], 'ARTIFACT_INVALID', entryPath);
|
|
331
|
+
const name = parseCandidateRelativeName(item.name, `${entryPath}/name`);
|
|
332
|
+
const folded = name.toLowerCase();
|
|
333
|
+
if (seenPaths.has(folded))
|
|
334
|
+
wireInvalid('duplicate candidate path', `${entryPath}/name`);
|
|
335
|
+
seenPaths.add(folded);
|
|
336
|
+
const digest = parseDigest(item.digest, `${entryPath}/digest`);
|
|
337
|
+
const byteLength = parseIntStrict(item.byteLength, 0, maxBlobBytes, `${entryPath}/byteLength`);
|
|
338
|
+
if ((byteLength === 0) !== (digest.hex === EMPTY_SHA256_HEX)) {
|
|
339
|
+
wireInvalid('empty-file digest mismatch', `${entryPath}/digest`);
|
|
340
|
+
}
|
|
341
|
+
let mode;
|
|
342
|
+
if (Object.hasOwn(item, 'mode')) {
|
|
343
|
+
if (item.mode !== '100644' && item.mode !== '100755') {
|
|
344
|
+
wireInvalid('candidate entry mode must be "100644" or "100755"', `${entryPath}/mode`);
|
|
345
|
+
}
|
|
346
|
+
mode = item.mode;
|
|
347
|
+
}
|
|
348
|
+
return Object.freeze({
|
|
349
|
+
name,
|
|
350
|
+
digest,
|
|
351
|
+
byteLength,
|
|
352
|
+
...(mode !== undefined ? { mode } : {}),
|
|
353
|
+
});
|
|
354
|
+
});
|
|
355
|
+
const deleted = obj.deleted.map((rawName, idx) => {
|
|
356
|
+
const delPath = `${path}/deleted/${idx}`;
|
|
357
|
+
const name = parseCandidateRelativeName(rawName, delPath);
|
|
358
|
+
const folded = name.toLowerCase();
|
|
359
|
+
if (seenPaths.has(folded))
|
|
360
|
+
wireInvalid('duplicate or overlapping deleted path', delPath);
|
|
361
|
+
seenPaths.add(folded);
|
|
362
|
+
return name;
|
|
363
|
+
});
|
|
364
|
+
const baseTree = Object.hasOwn(obj, 'baseTree')
|
|
365
|
+
? parseBaseTreeAnchor(obj.baseTree, `${path}/baseTree`)
|
|
366
|
+
: undefined;
|
|
367
|
+
const baseTreeBundle = Object.hasOwn(obj, 'baseTreeBundle')
|
|
368
|
+
? parseBaseTreeBundle(obj.baseTreeBundle, maxBlobBytes, `${path}/baseTreeBundle`)
|
|
369
|
+
: undefined;
|
|
370
|
+
if (baseTreeBundle !== undefined && baseTree === undefined) {
|
|
371
|
+
wireInvalid('baseTreeBundle requires baseTree anchor', `${path}/baseTreeBundle`);
|
|
372
|
+
}
|
|
373
|
+
return Object.freeze({
|
|
374
|
+
entries: Object.freeze(entries),
|
|
375
|
+
deleted: Object.freeze(deleted),
|
|
376
|
+
...(baseTree !== undefined ? { baseTree } : {}),
|
|
377
|
+
...(baseTreeBundle !== undefined ? { baseTreeBundle } : {}),
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
const BENCHMARK_REQUEST_KEYS = new Set([
|
|
381
|
+
'version',
|
|
382
|
+
'kind',
|
|
383
|
+
'storeId',
|
|
384
|
+
'runId',
|
|
385
|
+
'lockHash',
|
|
386
|
+
'operationId',
|
|
387
|
+
'dispatchId',
|
|
388
|
+
'dispatchGeneration',
|
|
389
|
+
'requestDigest',
|
|
390
|
+
'gateId',
|
|
391
|
+
'checkId',
|
|
392
|
+
'candidateDigest',
|
|
393
|
+
'subject',
|
|
394
|
+
'targetCellId',
|
|
395
|
+
'targetHardware',
|
|
396
|
+
'heldOutWorkloadId',
|
|
397
|
+
'metricThresholds',
|
|
398
|
+
'maxPreemptions',
|
|
399
|
+
'candidateArtifacts',
|
|
400
|
+
]);
|
|
401
|
+
export function parseBenchmarkRequest(rawInput, maxBlobBytes = VERIFIER_ARTIFACT_LIMITS.maxFileBytes) {
|
|
402
|
+
const normalized = toNullPrototypeValue(rawInput, 'ARTIFACT_INVALID', '/');
|
|
403
|
+
const root = expectNullProtoRecord(normalized, BENCHMARK_REQUEST_KEYS, [
|
|
404
|
+
'version',
|
|
405
|
+
'kind',
|
|
406
|
+
'storeId',
|
|
407
|
+
'runId',
|
|
408
|
+
'lockHash',
|
|
409
|
+
'operationId',
|
|
410
|
+
'dispatchId',
|
|
411
|
+
'dispatchGeneration',
|
|
412
|
+
'requestDigest',
|
|
413
|
+
'gateId',
|
|
414
|
+
'checkId',
|
|
415
|
+
'candidateDigest',
|
|
416
|
+
'subject',
|
|
417
|
+
'targetCellId',
|
|
418
|
+
'targetHardware',
|
|
419
|
+
'heldOutWorkloadId',
|
|
420
|
+
'candidateArtifacts',
|
|
421
|
+
], 'ARTIFACT_INVALID', '/');
|
|
422
|
+
if (root.version !== 1)
|
|
423
|
+
wireInvalid('version must be 1', '/version');
|
|
424
|
+
if (root.kind !== 'benchmark_request')
|
|
425
|
+
wireInvalid('kind must be benchmark_request', '/kind');
|
|
426
|
+
const storeId = parseSafeId(root.storeId, '/storeId');
|
|
427
|
+
const runId = parseIdentifier(root.runId, '/runId');
|
|
428
|
+
const lockHash = parseDigest(root.lockHash, '/lockHash');
|
|
429
|
+
const operationId = parseOperationId(root.operationId, '/operationId');
|
|
430
|
+
const dispatchId = parseSafeId(root.dispatchId, '/dispatchId');
|
|
431
|
+
const dispatchGeneration = parseIntStrict(root.dispatchGeneration, 0, Number.MAX_SAFE_INTEGER, '/dispatchGeneration');
|
|
432
|
+
const requestDigest = parseSha256Hex(root.requestDigest, '/requestDigest');
|
|
433
|
+
const gateId = parsePrintableText(root.gateId, 1, 128, '/gateId', true);
|
|
434
|
+
const checkId = parseIdentifier(root.checkId, '/checkId');
|
|
435
|
+
const candidateDigest = parseSha256Hex(root.candidateDigest, '/candidateDigest');
|
|
436
|
+
const subject = parseSubject(root.subject, '/subject');
|
|
437
|
+
if (subject.candidateDigest.hex !== candidateDigest || subject.lockHash.hex !== lockHash.hex) {
|
|
438
|
+
wireInvalid('subject bindings do not match candidateDigest or lockHash', '/subject');
|
|
439
|
+
}
|
|
440
|
+
const targetCellId = parseIdentifier(root.targetCellId, '/targetCellId');
|
|
441
|
+
const targetHardware = parseHardwareTarget(root.targetHardware, '/targetHardware');
|
|
442
|
+
const heldOutWorkloadId = parsePrintableText(root.heldOutWorkloadId, 1, 128, '/heldOutWorkloadId', true);
|
|
443
|
+
if (!SAFE_FILENAME_ID_RE.test(heldOutWorkloadId)) {
|
|
444
|
+
wireInvalid('invalid heldOutWorkloadId', '/heldOutWorkloadId');
|
|
445
|
+
}
|
|
446
|
+
let metricThresholds = Object.freeze([]);
|
|
447
|
+
if (Object.hasOwn(root, 'metricThresholds')) {
|
|
448
|
+
if (!Array.isArray(root.metricThresholds) || root.metricThresholds.length > LIMITS.metricThresholds) {
|
|
449
|
+
wireInvalid(`metricThresholds must contain 0..${LIMITS.metricThresholds} rules`, '/metricThresholds');
|
|
450
|
+
}
|
|
451
|
+
metricThresholds = Object.freeze(root.metricThresholds.map((r, idx) => parseMetricThresholdRule(r, `/metricThresholds/${idx}`)));
|
|
452
|
+
}
|
|
453
|
+
const maxPreemptions = Object.hasOwn(root, 'maxPreemptions')
|
|
454
|
+
? parseIntStrict(root.maxPreemptions, 0, 16, '/maxPreemptions')
|
|
455
|
+
: 3;
|
|
456
|
+
const candidateArtifacts = parseCandidateArtifacts(root.candidateArtifacts, maxBlobBytes, '/candidateArtifacts');
|
|
457
|
+
return Object.freeze({
|
|
458
|
+
version: 1,
|
|
459
|
+
kind: 'benchmark_request',
|
|
460
|
+
storeId,
|
|
461
|
+
runId,
|
|
462
|
+
lockHash,
|
|
463
|
+
operationId,
|
|
464
|
+
dispatchId,
|
|
465
|
+
dispatchGeneration,
|
|
466
|
+
requestDigest,
|
|
467
|
+
gateId,
|
|
468
|
+
checkId,
|
|
469
|
+
candidateDigest,
|
|
470
|
+
subject,
|
|
471
|
+
targetCellId,
|
|
472
|
+
targetHardware,
|
|
473
|
+
heldOutWorkloadId,
|
|
474
|
+
metricThresholds,
|
|
475
|
+
maxPreemptions,
|
|
476
|
+
candidateArtifacts,
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
const ACQUIRE_KEYS = new Set(['workerId', 'capabilities', 'waitMs']);
|
|
480
|
+
const HEARTBEAT_KEYS = new Set(['relayBootId', 'leaseEpoch', 'leaseToken', 'state']);
|
|
481
|
+
const PREEMPT_KEYS = new Set(['relayBootId', 'leaseEpoch', 'leaseToken', 'reason']);
|
|
482
|
+
const COMPLETE_KEYS = new Set([
|
|
483
|
+
'relayBootId',
|
|
484
|
+
'leaseEpoch',
|
|
485
|
+
'leaseToken',
|
|
486
|
+
'status',
|
|
487
|
+
'reason',
|
|
488
|
+
'detail',
|
|
489
|
+
'metrics',
|
|
490
|
+
'findings',
|
|
491
|
+
'hardwareProvenance',
|
|
492
|
+
'outputArtifacts',
|
|
493
|
+
]);
|
|
494
|
+
const PROVENANCE_KEYS = new Set([
|
|
495
|
+
'targetCellId',
|
|
496
|
+
'probeKind',
|
|
497
|
+
'vendor',
|
|
498
|
+
'deviceModel',
|
|
499
|
+
'accelerator',
|
|
500
|
+
'isolationMode',
|
|
501
|
+
'deviceCount',
|
|
502
|
+
'driverVersion',
|
|
503
|
+
'runtimeVersion',
|
|
504
|
+
'topology',
|
|
505
|
+
'workloadDigest',
|
|
506
|
+
'clockLockMode',
|
|
507
|
+
]);
|
|
508
|
+
const FINDING_KEYS = new Set(['title', 'severity', 'path', 'line', 'evidence']);
|
|
509
|
+
const OUTPUT_ARTIFACT_KEYS = new Set(['name', 'digest', 'byteLength', 'mediaType']);
|
|
510
|
+
const SIGNED_RECEIPT_KEYS = new Set([
|
|
511
|
+
'version',
|
|
512
|
+
'kind',
|
|
513
|
+
'storeId',
|
|
514
|
+
'runId',
|
|
515
|
+
'lockHash',
|
|
516
|
+
'operationId',
|
|
517
|
+
'dispatchId',
|
|
518
|
+
'dispatchGeneration',
|
|
519
|
+
'gateId',
|
|
520
|
+
'checkId',
|
|
521
|
+
'candidateDigest',
|
|
522
|
+
'status',
|
|
523
|
+
'reason',
|
|
524
|
+
'expiresAtMs',
|
|
525
|
+
'preemptionCount',
|
|
526
|
+
'retryablePreemption',
|
|
527
|
+
'detail',
|
|
528
|
+
'metrics',
|
|
529
|
+
'findings',
|
|
530
|
+
'hardwareProvenance',
|
|
531
|
+
'outputArtifacts',
|
|
532
|
+
'signature',
|
|
533
|
+
]);
|
|
534
|
+
const OPERATION_RECORD_KEYS = new Set([
|
|
535
|
+
'version',
|
|
536
|
+
'kind',
|
|
537
|
+
'request',
|
|
538
|
+
'signature',
|
|
539
|
+
]);
|
|
540
|
+
function parseAcquireInput(raw) {
|
|
541
|
+
const obj = expectNullProtoRecord(raw, ACQUIRE_KEYS, ['workerId', 'capabilities'], 'ARTIFACT_INVALID', '/');
|
|
542
|
+
const workerId = parseSafeId(obj.workerId, '/workerId');
|
|
543
|
+
const capabilities = validateWorkerCapabilitiesObject(obj.capabilities, 'ARTIFACT_INVALID', '/capabilities');
|
|
544
|
+
const waitMs = Object.hasOwn(obj, 'waitMs')
|
|
545
|
+
? Math.min(MAX_ACQUIRE_WAIT_MS, parseIntStrict(obj.waitMs, 0, 300_000, '/waitMs'))
|
|
546
|
+
: undefined;
|
|
547
|
+
return Object.freeze({
|
|
548
|
+
workerId,
|
|
549
|
+
capabilities,
|
|
550
|
+
...(waitMs !== undefined ? { waitMs } : {}),
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
function parseLeaseCredsFromObject(obj) {
|
|
554
|
+
if (typeof obj.relayBootId !== 'string'
|
|
555
|
+
|| typeof obj.leaseToken !== 'string'
|
|
556
|
+
|| typeof obj.leaseEpoch !== 'number'
|
|
557
|
+
|| !Number.isSafeInteger(obj.leaseEpoch)
|
|
558
|
+
|| Object.is(obj.leaseEpoch, -0)
|
|
559
|
+
|| obj.leaseEpoch < 1) {
|
|
560
|
+
throw new HardwareRunnerError('QUEUE_LEASE_FENCED', 'invalid lease credentials');
|
|
561
|
+
}
|
|
562
|
+
return {
|
|
563
|
+
relayBootId: obj.relayBootId,
|
|
564
|
+
leaseEpoch: obj.leaseEpoch,
|
|
565
|
+
leaseToken: obj.leaseToken,
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
function parseHeartbeatInput(raw) {
|
|
569
|
+
const obj = expectNullProtoRecord(raw, HEARTBEAT_KEYS, ['relayBootId', 'leaseEpoch', 'leaseToken'], 'ARTIFACT_INVALID', '/');
|
|
570
|
+
const creds = parseLeaseCredsFromObject(obj);
|
|
571
|
+
if (Object.hasOwn(obj, 'state') && obj.state !== 'running') {
|
|
572
|
+
wireInvalid('heartbeat state must be "running"', '/state');
|
|
573
|
+
}
|
|
574
|
+
return Object.freeze({
|
|
575
|
+
...creds,
|
|
576
|
+
...(Object.hasOwn(obj, 'state') ? { state: 'running' } : {}),
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
function parsePreemptInput(raw) {
|
|
580
|
+
const obj = expectNullProtoRecord(raw, PREEMPT_KEYS, ['relayBootId', 'leaseEpoch', 'leaseToken'], 'ARTIFACT_INVALID', '/');
|
|
581
|
+
const creds = parseLeaseCredsFromObject(obj);
|
|
582
|
+
const reason = Object.hasOwn(obj, 'reason')
|
|
583
|
+
? parseStringStrict(obj.reason, 1, 256, '/reason')
|
|
584
|
+
: undefined;
|
|
585
|
+
return Object.freeze({
|
|
586
|
+
...creds,
|
|
587
|
+
...(reason !== undefined ? { reason } : {}),
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
function parseMetricsMap(value, path) {
|
|
591
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
592
|
+
wireInvalid('metrics must be an object', path);
|
|
593
|
+
}
|
|
594
|
+
const src = value;
|
|
595
|
+
const keys = Object.keys(src).sort();
|
|
596
|
+
if (keys.length > LIMITS.metricEntries) {
|
|
597
|
+
wireInvalid('metrics exceeds maximum entry count', path);
|
|
598
|
+
}
|
|
599
|
+
const out = Object.create(null);
|
|
600
|
+
for (const key of keys) {
|
|
601
|
+
parseMetricKey(key, `${path}/${key}`);
|
|
602
|
+
const entry = src[key];
|
|
603
|
+
if (typeof entry === 'number') {
|
|
604
|
+
out[key] = parseFiniteControlNumber(entry, `${path}/${key}`);
|
|
605
|
+
}
|
|
606
|
+
else if (typeof entry === 'string') {
|
|
607
|
+
out[key] = parseStringStrict(entry, 0, LIMITS.metricStringValue, `${path}/${key}`);
|
|
608
|
+
}
|
|
609
|
+
else if (typeof entry === 'boolean') {
|
|
610
|
+
out[key] = entry;
|
|
611
|
+
}
|
|
612
|
+
else {
|
|
613
|
+
wireInvalid('unsupported metric value type', `${path}/${key}`);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
return Object.freeze(out);
|
|
617
|
+
}
|
|
618
|
+
function parseFindingsList(value, path) {
|
|
619
|
+
if (!Array.isArray(value) || value.length > LIMITS.findings) {
|
|
620
|
+
wireInvalid('findings must be a bounded array', path);
|
|
621
|
+
}
|
|
622
|
+
const out = value.map((item, idx) => {
|
|
623
|
+
const fPath = `${path}/${idx}`;
|
|
624
|
+
const obj = expectNullProtoRecord(item, FINDING_KEYS, ['title', 'severity', 'evidence'], 'ARTIFACT_INVALID', fPath);
|
|
625
|
+
const title = parseStringStrict(obj.title, 1, LIMITS.findingTitle, `${fPath}/title`);
|
|
626
|
+
if (obj.severity !== 'critical' && obj.severity !== 'high' && obj.severity !== 'medium' && obj.severity !== 'low') {
|
|
627
|
+
wireInvalid('invalid finding severity', `${fPath}/severity`);
|
|
628
|
+
}
|
|
629
|
+
const severity = obj.severity;
|
|
630
|
+
const evidence = parseStringStrict(obj.evidence, 1, LIMITS.findingEvidence, `${fPath}/evidence`);
|
|
631
|
+
let relPath;
|
|
632
|
+
if (Object.hasOwn(obj, 'path')) {
|
|
633
|
+
if (obj.path === null)
|
|
634
|
+
relPath = null;
|
|
635
|
+
else {
|
|
636
|
+
const s = parseStringStrict(obj.path, 1, LIMITS.path, `${fPath}/path`);
|
|
637
|
+
const valid = validateRelativePath(s);
|
|
638
|
+
if (!valid.ok)
|
|
639
|
+
wireInvalid('invalid finding path', `${fPath}/path`);
|
|
640
|
+
relPath = valid.value;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
let line;
|
|
644
|
+
if (Object.hasOwn(obj, 'line')) {
|
|
645
|
+
line = obj.line === null ? null : parseIntStrict(obj.line, 1, Number.MAX_SAFE_INTEGER, `${fPath}/line`);
|
|
646
|
+
}
|
|
647
|
+
const built = Object.create(null);
|
|
648
|
+
built.title = title;
|
|
649
|
+
built.severity = severity;
|
|
650
|
+
if (relPath !== undefined)
|
|
651
|
+
built.path = relPath;
|
|
652
|
+
if (line !== undefined)
|
|
653
|
+
built.line = line;
|
|
654
|
+
built.evidence = evidence;
|
|
655
|
+
return Object.freeze(built);
|
|
656
|
+
});
|
|
657
|
+
return Object.freeze(out);
|
|
658
|
+
}
|
|
659
|
+
function parseHardwareProvenance(value, path) {
|
|
660
|
+
const obj = expectNullProtoRecord(value, PROVENANCE_KEYS, [
|
|
661
|
+
'targetCellId',
|
|
662
|
+
'probeKind',
|
|
663
|
+
'vendor',
|
|
664
|
+
'deviceModel',
|
|
665
|
+
'accelerator',
|
|
666
|
+
'isolationMode',
|
|
667
|
+
'deviceCount',
|
|
668
|
+
'driverVersion',
|
|
669
|
+
'runtimeVersion',
|
|
670
|
+
'workloadDigest',
|
|
671
|
+
'clockLockMode',
|
|
672
|
+
], 'ARTIFACT_INVALID', path);
|
|
673
|
+
const targetCellId = parseIdentifier(obj.targetCellId, `${path}/targetCellId`);
|
|
674
|
+
if (obj.probeKind !== 'physical' && obj.probeKind !== 'synthetic_fixture') {
|
|
675
|
+
wireInvalid('invalid probeKind', `${path}/probeKind`);
|
|
676
|
+
}
|
|
677
|
+
const vendor = parsePrintableText(obj.vendor, 1, 128, `${path}/vendor`, false);
|
|
678
|
+
const deviceModel = parsePrintableText(obj.deviceModel, 1, 128, `${path}/deviceModel`, false);
|
|
679
|
+
const accelerator = parsePrintableText(obj.accelerator, 1, 64, `${path}/accelerator`, true);
|
|
680
|
+
if (obj.isolationMode !== 'whole_device' && obj.isolationMode !== 'sliced') {
|
|
681
|
+
wireInvalid('invalid isolationMode', `${path}/isolationMode`);
|
|
682
|
+
}
|
|
683
|
+
const deviceCount = parseIntStrict(obj.deviceCount, 1, 64, `${path}/deviceCount`);
|
|
684
|
+
const driverVersion = parsePrintableText(obj.driverVersion, 1, 128, `${path}/driverVersion`, false);
|
|
685
|
+
const runtimeVersion = parsePrintableText(obj.runtimeVersion, 1, 128, `${path}/runtimeVersion`, false);
|
|
686
|
+
const topology = Object.hasOwn(obj, 'topology')
|
|
687
|
+
? parsePrintableText(obj.topology, 1, 128, `${path}/topology`, false)
|
|
688
|
+
: undefined;
|
|
689
|
+
const workloadDigest = parseDigest(obj.workloadDigest, `${path}/workloadDigest`);
|
|
690
|
+
if (obj.clockLockMode !== 'locked' && obj.clockLockMode !== 'unlocked' && obj.clockLockMode !== 'unknown') {
|
|
691
|
+
wireInvalid('invalid clockLockMode', `${path}/clockLockMode`);
|
|
692
|
+
}
|
|
693
|
+
return Object.freeze({
|
|
694
|
+
targetCellId,
|
|
695
|
+
probeKind: obj.probeKind,
|
|
696
|
+
vendor,
|
|
697
|
+
deviceModel,
|
|
698
|
+
accelerator,
|
|
699
|
+
isolationMode: obj.isolationMode,
|
|
700
|
+
deviceCount,
|
|
701
|
+
driverVersion,
|
|
702
|
+
runtimeVersion,
|
|
703
|
+
...(topology !== undefined ? { topology } : {}),
|
|
704
|
+
workloadDigest,
|
|
705
|
+
clockLockMode: obj.clockLockMode,
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
function validateMediaType(value, path) {
|
|
709
|
+
const mime = parseStringStrict(value, 1, LIMITS.mediaType, path);
|
|
710
|
+
if (CONTROL_CHAR_RE.test(mime))
|
|
711
|
+
wireInvalid('invalid mediaType', path);
|
|
712
|
+
const parts = mime.split(';');
|
|
713
|
+
const essence = parts[0].trim();
|
|
714
|
+
if (essence !== parts[0]
|
|
715
|
+
|| !/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*$/.test(essence)) {
|
|
716
|
+
wireInvalid('invalid mediaType essence', path);
|
|
717
|
+
}
|
|
718
|
+
for (let idx = 1; idx < parts.length; idx += 1) {
|
|
719
|
+
const param = parts[idx].trim();
|
|
720
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*=[A-Za-z0-9!#$&^_.+-]+$/.test(param)) {
|
|
721
|
+
wireInvalid('invalid mediaType parameter', path);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
return mime;
|
|
725
|
+
}
|
|
726
|
+
function parseOutputArtifacts(value, maxBlobBytes, path) {
|
|
727
|
+
if (!Array.isArray(value) || value.length > VERIFIER_ARTIFACT_LIMITS.maxFilesPerSlot) {
|
|
728
|
+
wireInvalid(`outputArtifacts must contain 0..${VERIFIER_ARTIFACT_LIMITS.maxFilesPerSlot} entries`, path);
|
|
729
|
+
}
|
|
730
|
+
const perFileMax = Math.min(maxBlobBytes, VERIFIER_ARTIFACT_LIMITS.maxFileBytes);
|
|
731
|
+
const seen = new Set();
|
|
732
|
+
let totalBytes = 0;
|
|
733
|
+
const out = value.map((item, idx) => {
|
|
734
|
+
const aPath = `${path}/${idx}`;
|
|
735
|
+
const obj = expectNullProtoRecord(item, OUTPUT_ARTIFACT_KEYS, ['name', 'digest', 'byteLength'], 'ARTIFACT_INVALID', aPath);
|
|
736
|
+
const name = parseCandidateRelativeName(obj.name, `${aPath}/name`);
|
|
737
|
+
const folded = name.toLowerCase();
|
|
738
|
+
if (seen.has(folded))
|
|
739
|
+
wireInvalid('duplicate outputArtifact path', `${aPath}/name`);
|
|
740
|
+
seen.add(folded);
|
|
741
|
+
const digest = parseDigest(obj.digest, `${aPath}/digest`);
|
|
742
|
+
const byteLength = parseIntStrict(obj.byteLength, 0, perFileMax, `${aPath}/byteLength`);
|
|
743
|
+
if ((byteLength === 0) !== (digest.hex === EMPTY_SHA256_HEX)) {
|
|
744
|
+
wireInvalid('empty outputArtifact digest mismatch', `${aPath}/digest`);
|
|
745
|
+
}
|
|
746
|
+
if (byteLength > VERIFIER_ARTIFACT_LIMITS.maxTotalBytes - totalBytes) {
|
|
747
|
+
throw new HardwareRunnerError('PAYLOAD_TOO_LARGE', `outputArtifacts total byteLength exceeds ${VERIFIER_ARTIFACT_LIMITS.maxTotalBytes} bytes`, `${aPath}/byteLength`);
|
|
748
|
+
}
|
|
749
|
+
totalBytes += byteLength;
|
|
750
|
+
let mediaType;
|
|
751
|
+
if (Object.hasOwn(obj, 'mediaType')) {
|
|
752
|
+
mediaType = obj.mediaType === null ? null : validateMediaType(obj.mediaType, `${aPath}/mediaType`);
|
|
753
|
+
}
|
|
754
|
+
return Object.freeze({
|
|
755
|
+
name,
|
|
756
|
+
digest,
|
|
757
|
+
byteLength,
|
|
758
|
+
...(mediaType !== undefined ? { mediaType } : {}),
|
|
759
|
+
});
|
|
760
|
+
});
|
|
761
|
+
return Object.freeze(out);
|
|
762
|
+
}
|
|
763
|
+
function parseCompleteInput(raw, maxBlobBytes) {
|
|
764
|
+
const obj = expectNullProtoRecord(raw, COMPLETE_KEYS, ['relayBootId', 'leaseEpoch', 'leaseToken', 'status', 'reason'], 'ARTIFACT_INVALID', '/');
|
|
765
|
+
const creds = parseLeaseCredsFromObject(obj);
|
|
766
|
+
if (obj.status !== 'approved' && obj.status !== 'denied') {
|
|
767
|
+
wireInvalid('status must be "approved" or "denied"', '/status');
|
|
768
|
+
}
|
|
769
|
+
const reason = obj.reason === null ? null : parseStringStrict(obj.reason, 1, 256, '/reason');
|
|
770
|
+
if (obj.status === 'approved' && reason !== null) {
|
|
771
|
+
wireInvalid('approved verdict must carry reason: null', '/reason');
|
|
772
|
+
}
|
|
773
|
+
if (obj.status === 'denied' && reason === null) {
|
|
774
|
+
wireInvalid('denied verdict requires non-null reason', '/reason');
|
|
775
|
+
}
|
|
776
|
+
const detail = Object.hasOwn(obj, 'detail')
|
|
777
|
+
? obj.detail === null ? null : parseStringStrict(obj.detail, 1, LIMITS.string, '/detail')
|
|
778
|
+
: undefined;
|
|
779
|
+
const metrics = Object.hasOwn(obj, 'metrics') ? parseMetricsMap(obj.metrics, '/metrics') : undefined;
|
|
780
|
+
const findings = Object.hasOwn(obj, 'findings') ? parseFindingsList(obj.findings, '/findings') : undefined;
|
|
781
|
+
const hardwareProvenance = Object.hasOwn(obj, 'hardwareProvenance')
|
|
782
|
+
? parseHardwareProvenance(obj.hardwareProvenance, '/hardwareProvenance')
|
|
783
|
+
: undefined;
|
|
784
|
+
if (obj.status === 'approved' && hardwareProvenance === undefined) {
|
|
785
|
+
wireInvalid('approved verdict requires hardwareProvenance', '/hardwareProvenance');
|
|
786
|
+
}
|
|
787
|
+
const outputArtifacts = Object.hasOwn(obj, 'outputArtifacts')
|
|
788
|
+
? parseOutputArtifacts(obj.outputArtifacts, maxBlobBytes, '/outputArtifacts')
|
|
789
|
+
: undefined;
|
|
790
|
+
return Object.freeze({
|
|
791
|
+
...creds,
|
|
792
|
+
status: obj.status,
|
|
793
|
+
reason,
|
|
794
|
+
...(detail !== undefined ? { detail } : {}),
|
|
795
|
+
...(metrics !== undefined ? { metrics } : {}),
|
|
796
|
+
...(findings !== undefined ? { findings } : {}),
|
|
797
|
+
...(hardwareProvenance !== undefined ? { hardwareProvenance } : {}),
|
|
798
|
+
...(outputArtifacts !== undefined ? { outputArtifacts } : {}),
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
function parseAuthenticatedReceiptBytes(bytes, expectedOperationId, signingSecret, maxBlobBytes, scrubber) {
|
|
802
|
+
const raw = parseStrictJsonBytes(bytes, MAX_RECEIPT_FILE_BYTES, 'ARTIFACT_INVALID', '/receipt');
|
|
803
|
+
const obj = expectNullProtoRecord(raw, SIGNED_RECEIPT_KEYS, [
|
|
804
|
+
'version',
|
|
805
|
+
'kind',
|
|
806
|
+
'storeId',
|
|
807
|
+
'runId',
|
|
808
|
+
'lockHash',
|
|
809
|
+
'operationId',
|
|
810
|
+
'dispatchId',
|
|
811
|
+
'dispatchGeneration',
|
|
812
|
+
'gateId',
|
|
813
|
+
'checkId',
|
|
814
|
+
'candidateDigest',
|
|
815
|
+
'status',
|
|
816
|
+
'reason',
|
|
817
|
+
'expiresAtMs',
|
|
818
|
+
'preemptionCount',
|
|
819
|
+
'signature',
|
|
820
|
+
], 'ARTIFACT_INVALID', '/receipt');
|
|
821
|
+
const signature = parseSha256Hex(obj.signature, '/receipt/signature');
|
|
822
|
+
if (!verifyBenchmarkVerdictSignature(signingSecret, obj, signature)) {
|
|
823
|
+
wireInvalid('receipt HMAC signature verification failed', '/receipt/signature');
|
|
824
|
+
}
|
|
825
|
+
if (obj.version !== 1)
|
|
826
|
+
wireInvalid('receipt version must be 1', '/receipt/version');
|
|
827
|
+
if (obj.kind !== 'benchmark_verdict')
|
|
828
|
+
wireInvalid('receipt kind must be benchmark_verdict', '/receipt/kind');
|
|
829
|
+
const storeId = parseSafeId(obj.storeId, '/receipt/storeId');
|
|
830
|
+
const runId = parseIdentifier(obj.runId, '/receipt/runId');
|
|
831
|
+
const lockHash = parseDigest(obj.lockHash, '/receipt/lockHash');
|
|
832
|
+
const operationId = parseOperationId(obj.operationId, '/receipt/operationId');
|
|
833
|
+
if (operationId !== expectedOperationId) {
|
|
834
|
+
wireInvalid('receipt operationId does not match filename', '/receipt/operationId');
|
|
835
|
+
}
|
|
836
|
+
const dispatchId = parseSafeId(obj.dispatchId, '/receipt/dispatchId');
|
|
837
|
+
const dispatchGeneration = parseIntStrict(obj.dispatchGeneration, 0, Number.MAX_SAFE_INTEGER, '/receipt/dispatchGeneration');
|
|
838
|
+
const gateId = parsePrintableText(obj.gateId, 1, 128, '/receipt/gateId', true);
|
|
839
|
+
const checkId = parseIdentifier(obj.checkId, '/receipt/checkId');
|
|
840
|
+
const candidateDigest = parseSha256Hex(obj.candidateDigest, '/receipt/candidateDigest');
|
|
841
|
+
if (obj.status !== 'approved' && obj.status !== 'denied' && obj.status !== 'expired') {
|
|
842
|
+
wireInvalid('durable receipt status must be terminal', '/receipt/status');
|
|
843
|
+
}
|
|
844
|
+
const status = obj.status;
|
|
845
|
+
const reason = obj.reason === null ? null : parseStringStrict(obj.reason, 1, 256, '/receipt/reason');
|
|
846
|
+
if (status === 'approved' && reason !== null) {
|
|
847
|
+
wireInvalid('approved receipt must carry null reason', '/receipt/reason');
|
|
848
|
+
}
|
|
849
|
+
const expiresAtMs = parseStringStrict(obj.expiresAtMs, 1, 19, '/receipt/expiresAtMs');
|
|
850
|
+
if (!/^(?:0|[1-9][0-9]{0,17})$/.test(expiresAtMs)) {
|
|
851
|
+
wireInvalid('invalid receipt expiresAtMs', '/receipt/expiresAtMs');
|
|
852
|
+
}
|
|
853
|
+
const preemptionCount = parseIntStrict(obj.preemptionCount, 0, 16, '/receipt/preemptionCount');
|
|
854
|
+
let retryablePreemption;
|
|
855
|
+
if (Object.hasOwn(obj, 'retryablePreemption')) {
|
|
856
|
+
if (typeof obj.retryablePreemption !== 'boolean' || (obj.retryablePreemption === true && status === 'approved')) {
|
|
857
|
+
wireInvalid('invalid retryablePreemption on receipt', '/receipt/retryablePreemption');
|
|
858
|
+
}
|
|
859
|
+
retryablePreemption = obj.retryablePreemption;
|
|
860
|
+
}
|
|
861
|
+
const detail = Object.hasOwn(obj, 'detail')
|
|
862
|
+
? obj.detail === null ? null : parseStringStrict(obj.detail, 1, LIMITS.string, '/receipt/detail')
|
|
863
|
+
: undefined;
|
|
864
|
+
const metrics = Object.hasOwn(obj, 'metrics') ? parseMetricsMap(obj.metrics, '/receipt/metrics') : undefined;
|
|
865
|
+
const findings = Object.hasOwn(obj, 'findings') ? parseFindingsList(obj.findings, '/receipt/findings') : undefined;
|
|
866
|
+
const hardwareProvenance = Object.hasOwn(obj, 'hardwareProvenance')
|
|
867
|
+
? parseHardwareProvenance(obj.hardwareProvenance, '/receipt/hardwareProvenance')
|
|
868
|
+
: undefined;
|
|
869
|
+
if (status === 'approved' && hardwareProvenance === undefined) {
|
|
870
|
+
wireInvalid('approved receipt requires hardwareProvenance', '/receipt/hardwareProvenance');
|
|
871
|
+
}
|
|
872
|
+
const outputArtifacts = Object.hasOwn(obj, 'outputArtifacts')
|
|
873
|
+
? parseOutputArtifacts(obj.outputArtifacts, maxBlobBytes, '/receipt/outputArtifacts')
|
|
874
|
+
: undefined;
|
|
875
|
+
const verdict = Object.freeze({
|
|
876
|
+
version: 1,
|
|
877
|
+
kind: 'benchmark_verdict',
|
|
878
|
+
storeId,
|
|
879
|
+
runId,
|
|
880
|
+
lockHash,
|
|
881
|
+
operationId,
|
|
882
|
+
dispatchId,
|
|
883
|
+
dispatchGeneration,
|
|
884
|
+
gateId,
|
|
885
|
+
checkId,
|
|
886
|
+
candidateDigest,
|
|
887
|
+
status,
|
|
888
|
+
reason,
|
|
889
|
+
expiresAtMs,
|
|
890
|
+
preemptionCount,
|
|
891
|
+
...(retryablePreemption !== undefined ? { retryablePreemption } : {}),
|
|
892
|
+
...(detail !== undefined ? { detail } : {}),
|
|
893
|
+
...(metrics !== undefined ? { metrics } : {}),
|
|
894
|
+
...(findings !== undefined ? { findings } : {}),
|
|
895
|
+
...(hardwareProvenance !== undefined ? { hardwareProvenance } : {}),
|
|
896
|
+
...(outputArtifacts !== undefined ? { outputArtifacts } : {}),
|
|
897
|
+
});
|
|
898
|
+
const canonical = canonicalJson(verdict);
|
|
899
|
+
if (Buffer.byteLength(canonical, 'utf8') > MAX_CONTROL_BODY_BYTES) {
|
|
900
|
+
wireInvalid('receipt verdict exceeds 65536 bytes', '/receipt');
|
|
901
|
+
}
|
|
902
|
+
if (scrubber.containsSecret(canonical)) {
|
|
903
|
+
wireInvalid('receipt verdict rejected by SecretScrubber', '/receipt');
|
|
904
|
+
}
|
|
905
|
+
return verdict;
|
|
906
|
+
}
|
|
907
|
+
function parseAuthenticatedOperationBytes(bytes, expectedOperationId, signingSecret, maxBlobBytes) {
|
|
908
|
+
const raw = parseStrictJsonBytes(bytes, MAX_OPERATION_FILE_BYTES, 'ARTIFACT_INVALID', '/operation');
|
|
909
|
+
const obj = expectNullProtoRecord(raw, OPERATION_RECORD_KEYS, ['version', 'kind', 'request', 'signature'], 'ARTIFACT_INVALID', '/operation');
|
|
910
|
+
if (obj.version !== 1 || obj.kind !== 'benchmark_operation_request') {
|
|
911
|
+
wireInvalid('invalid operation record kind or version', '/operation');
|
|
912
|
+
}
|
|
913
|
+
const signature = parseSha256Hex(obj.signature, '/operation/signature');
|
|
914
|
+
const req = parseBenchmarkRequest(obj.request, maxBlobBytes);
|
|
915
|
+
if (req.operationId !== expectedOperationId) {
|
|
916
|
+
wireInvalid('operationId mismatch in persisted operation record', '/operation/request/operationId');
|
|
917
|
+
}
|
|
918
|
+
const signingInput = `REQ\n${canonicalJson(req)}`;
|
|
919
|
+
if (!verifyRelaySignature(signingSecret, signingInput, signature)) {
|
|
920
|
+
wireInvalid('operation record HMAC signature verification failed', '/operation/signature');
|
|
921
|
+
}
|
|
922
|
+
return req;
|
|
923
|
+
}
|
|
924
|
+
function singleHeader(req, name) {
|
|
925
|
+
const val = req.headers[name];
|
|
926
|
+
if (typeof val === 'string')
|
|
927
|
+
return val;
|
|
928
|
+
return null;
|
|
929
|
+
}
|
|
930
|
+
function parseLeaseHeaders(req) {
|
|
931
|
+
const relayBootId = singleHeader(req, 'x-loopwright-relay-boot-id');
|
|
932
|
+
const epochRaw = singleHeader(req, 'x-loopwright-lease-epoch');
|
|
933
|
+
const leaseToken = singleHeader(req, 'x-loopwright-lease-token');
|
|
934
|
+
if (relayBootId === null
|
|
935
|
+
|| epochRaw === null
|
|
936
|
+
|| leaseToken === null
|
|
937
|
+
|| relayBootId.length === 0
|
|
938
|
+
|| leaseToken.length === 0
|
|
939
|
+
|| !/^[1-9][0-9]{0,14}$/.test(epochRaw)) {
|
|
940
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'missing or malformed lease fencing headers');
|
|
941
|
+
}
|
|
942
|
+
const leaseEpoch = Number(epochRaw);
|
|
943
|
+
if (!Number.isSafeInteger(leaseEpoch) || leaseEpoch < 1) {
|
|
944
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid x-loopwright-lease-epoch header');
|
|
945
|
+
}
|
|
946
|
+
return { relayBootId, leaseEpoch, leaseToken };
|
|
947
|
+
}
|
|
948
|
+
function extractBearerToken(req) {
|
|
949
|
+
const auth = singleHeader(req, 'authorization');
|
|
950
|
+
if (auth === null || !auth.startsWith('Bearer '))
|
|
951
|
+
return null;
|
|
952
|
+
const token = auth.slice(7);
|
|
953
|
+
return token.length > 0 ? token : null;
|
|
954
|
+
}
|
|
955
|
+
function verifyBearerAgainstList(req, validTokens) {
|
|
956
|
+
const token = extractBearerToken(req);
|
|
957
|
+
if (token === null)
|
|
958
|
+
return false;
|
|
959
|
+
let matched = false;
|
|
960
|
+
for (const candidate of validTokens) {
|
|
961
|
+
if (timingSafeEqualStrings(token, candidate)) {
|
|
962
|
+
matched = true;
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
return matched;
|
|
966
|
+
}
|
|
967
|
+
async function readBoundedRequestBody(req, maxBytes) {
|
|
968
|
+
const clHeader = singleHeader(req, 'content-length');
|
|
969
|
+
if (clHeader !== null) {
|
|
970
|
+
if (!/^(?:0|[1-9][0-9]{0,14})$/.test(clHeader)) {
|
|
971
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid content-length header');
|
|
972
|
+
}
|
|
973
|
+
if (Number(clHeader) > maxBytes) {
|
|
974
|
+
throw new HardwareRunnerError('PAYLOAD_TOO_LARGE', `request body exceeds ${maxBytes} bytes`);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
const chunks = [];
|
|
978
|
+
let total = 0;
|
|
979
|
+
for await (const rawChunk of req) {
|
|
980
|
+
const chunk = Buffer.isBuffer(rawChunk) ? rawChunk : Buffer.from(rawChunk);
|
|
981
|
+
total += chunk.byteLength;
|
|
982
|
+
if (total > maxBytes) {
|
|
983
|
+
throw new HardwareRunnerError('PAYLOAD_TOO_LARGE', `request body exceeds ${maxBytes} bytes`);
|
|
984
|
+
}
|
|
985
|
+
chunks.push(chunk);
|
|
986
|
+
}
|
|
987
|
+
return chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, total);
|
|
988
|
+
}
|
|
989
|
+
async function readRecordFileOrNull(filePath, maxBytes, phase) {
|
|
990
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
991
|
+
const failIntegrity = (message, cause) => {
|
|
992
|
+
if (phase === 'startup') {
|
|
993
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', message, filePath);
|
|
994
|
+
}
|
|
995
|
+
throw new Error(message, cause !== undefined ? { cause } : undefined);
|
|
996
|
+
};
|
|
997
|
+
let handle;
|
|
998
|
+
try {
|
|
999
|
+
handle = await open(filePath, constants.O_RDONLY | noFollow);
|
|
1000
|
+
}
|
|
1001
|
+
catch (err) {
|
|
1002
|
+
const errCode = err?.code;
|
|
1003
|
+
if (errCode === 'ENOENT') {
|
|
1004
|
+
const lst = await lstat(filePath).catch((lstatErr) => {
|
|
1005
|
+
if (lstatErr?.code === 'ENOENT')
|
|
1006
|
+
return null;
|
|
1007
|
+
throw lstatErr;
|
|
1008
|
+
});
|
|
1009
|
+
if (lst === null) {
|
|
1010
|
+
return null;
|
|
1011
|
+
}
|
|
1012
|
+
return failIntegrity('symlink or irregular file at record path', err);
|
|
1013
|
+
}
|
|
1014
|
+
if (errCode === 'ELOOP' || errCode === 'EMLINK' || errCode === 'EFTYPE' || errCode === 'EISDIR') {
|
|
1015
|
+
return failIntegrity('failed to open file without following symlinks', err);
|
|
1016
|
+
}
|
|
1017
|
+
throw err;
|
|
1018
|
+
}
|
|
1019
|
+
try {
|
|
1020
|
+
const st = await handle.stat();
|
|
1021
|
+
if (!st.isFile()
|
|
1022
|
+
|| st.isSymbolicLink()
|
|
1023
|
+
|| st.nlink !== 1
|
|
1024
|
+
|| (typeof process.getuid === 'function' && st.uid !== process.getuid())
|
|
1025
|
+
|| (st.mode & 0o022) !== 0
|
|
1026
|
+
|| st.size > maxBytes) {
|
|
1027
|
+
return failIntegrity('file failed ownership, nlink, mode, or size check');
|
|
1028
|
+
}
|
|
1029
|
+
const buf = Buffer.allocUnsafe(st.size);
|
|
1030
|
+
let offset = 0;
|
|
1031
|
+
while (offset < st.size) {
|
|
1032
|
+
const { bytesRead } = await handle.read(buf, offset, st.size - offset, offset);
|
|
1033
|
+
if (bytesRead <= 0)
|
|
1034
|
+
break;
|
|
1035
|
+
offset += bytesRead;
|
|
1036
|
+
}
|
|
1037
|
+
const after = await handle.stat();
|
|
1038
|
+
if (offset !== st.size || after.ino !== st.ino || after.dev !== st.dev || after.size !== st.size) {
|
|
1039
|
+
return failIntegrity('file changed during bounded read');
|
|
1040
|
+
}
|
|
1041
|
+
return buf;
|
|
1042
|
+
}
|
|
1043
|
+
finally {
|
|
1044
|
+
await handle.close();
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
async function readRequiredStartupRecord(filePath, maxBytes) {
|
|
1048
|
+
const bytes = await readRecordFileOrNull(filePath, maxBytes, 'startup');
|
|
1049
|
+
if (bytes === null) {
|
|
1050
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'expected CAS record missing during startup', filePath);
|
|
1051
|
+
}
|
|
1052
|
+
return bytes;
|
|
1053
|
+
}
|
|
1054
|
+
async function writeAllToFileHandle(handle, chunk) {
|
|
1055
|
+
let offset = 0;
|
|
1056
|
+
while (offset < chunk.byteLength) {
|
|
1057
|
+
const { bytesWritten } = await handle.write(chunk, offset, chunk.byteLength - offset);
|
|
1058
|
+
if (bytesWritten <= 0) {
|
|
1059
|
+
throw new Error('Zero bytes written to CAS temp file');
|
|
1060
|
+
}
|
|
1061
|
+
offset += bytesWritten;
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
async function syncDir(dirPath) {
|
|
1065
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
1066
|
+
const dirHandle = await open(dirPath, constants.O_RDONLY | noFollow);
|
|
1067
|
+
try {
|
|
1068
|
+
await dirHandle.sync();
|
|
1069
|
+
}
|
|
1070
|
+
finally {
|
|
1071
|
+
await dirHandle.close();
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
function assertTrustedAncestorStatSync(st, ancPath, myUid) {
|
|
1075
|
+
if (!st.isDirectory() || st.isSymbolicLink()) {
|
|
1076
|
+
throw new HardwareRunnerError('CONFIG_INVALID', `CAS ancestor "${ancPath}" is not a regular directory`, '/casDir');
|
|
1077
|
+
}
|
|
1078
|
+
if (myUid !== null) {
|
|
1079
|
+
const trustedRootSticky = st.uid === 0 && (st.mode & 0o1000) !== 0;
|
|
1080
|
+
if (st.uid === myUid) {
|
|
1081
|
+
if ((st.mode & 0o022) !== 0 && !trustedRootSticky) {
|
|
1082
|
+
throw new HardwareRunnerError('CONFIG_INVALID', `CAS ancestor directory "${ancPath}" must not be group or world writable`, '/casDir');
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
else {
|
|
1086
|
+
const trustedRootDir = st.uid === 0 && ((st.mode & 0o022) === 0 || (st.mode & 0o1000) !== 0);
|
|
1087
|
+
if (!trustedRootDir) {
|
|
1088
|
+
throw new HardwareRunnerError('CONFIG_INVALID', `CAS ancestor directory "${ancPath}" is owned by an untrusted principal or is non-sticky writable`, '/casDir');
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
function inspectExistingAncestorSync(ancPath, myUid) {
|
|
1094
|
+
let st;
|
|
1095
|
+
try {
|
|
1096
|
+
st = lstatSync(ancPath);
|
|
1097
|
+
}
|
|
1098
|
+
catch (err) {
|
|
1099
|
+
if (err?.code === 'ENOENT') {
|
|
1100
|
+
return false;
|
|
1101
|
+
}
|
|
1102
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'failed to inspect CAS directory ancestor', '/casDir');
|
|
1103
|
+
}
|
|
1104
|
+
if (st.isSymbolicLink()) {
|
|
1105
|
+
if (!isAllowedOsRootSymlink(ancPath) || (myUid !== null && st.uid !== 0)) {
|
|
1106
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'symlinked CAS ancestor is forbidden', '/casDir');
|
|
1107
|
+
}
|
|
1108
|
+
let realTarget;
|
|
1109
|
+
try {
|
|
1110
|
+
realTarget = realpathSync(ancPath);
|
|
1111
|
+
}
|
|
1112
|
+
catch {
|
|
1113
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'failed to resolve OS root symlink target', '/casDir');
|
|
1114
|
+
}
|
|
1115
|
+
const targetParent = dirname(realTarget);
|
|
1116
|
+
if (targetParent !== realTarget) {
|
|
1117
|
+
assertTrustedAncestorStatSync(lstatSync(targetParent), targetParent, myUid);
|
|
1118
|
+
}
|
|
1119
|
+
assertTrustedAncestorStatSync(lstatSync(realTarget), realTarget, myUid);
|
|
1120
|
+
return true;
|
|
1121
|
+
}
|
|
1122
|
+
assertTrustedAncestorStatSync(st, ancPath, myUid);
|
|
1123
|
+
return true;
|
|
1124
|
+
}
|
|
1125
|
+
async function verifyAndTightenCreatedDir(targetPath, myUid, requireExact0700) {
|
|
1126
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
1127
|
+
let dirHandle;
|
|
1128
|
+
try {
|
|
1129
|
+
dirHandle = await open(targetPath, constants.O_RDONLY | noFollow);
|
|
1130
|
+
}
|
|
1131
|
+
catch {
|
|
1132
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'CAS directory cannot be opened without following symlinks', '/casDir');
|
|
1133
|
+
}
|
|
1134
|
+
try {
|
|
1135
|
+
const info = await dirHandle.stat();
|
|
1136
|
+
if (!info.isDirectory() || info.isSymbolicLink()) {
|
|
1137
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'CAS path is not a regular directory', '/casDir');
|
|
1138
|
+
}
|
|
1139
|
+
if (myUid !== null && info.uid !== myUid) {
|
|
1140
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'CAS directory is not owned by the current user', '/casDir');
|
|
1141
|
+
}
|
|
1142
|
+
if ((info.mode & 0o022) !== 0 || (info.mode & 0o700) !== 0o700) {
|
|
1143
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'CAS directory must be owner-accessible and not group/world writable', '/casDir');
|
|
1144
|
+
}
|
|
1145
|
+
if ((info.mode & 0o077) !== 0) {
|
|
1146
|
+
await dirHandle.chmod(0o700);
|
|
1147
|
+
}
|
|
1148
|
+
if (requireExact0700 || (info.mode & 0o077) !== 0) {
|
|
1149
|
+
const after = await dirHandle.stat();
|
|
1150
|
+
if ((after.mode & 0o777) !== 0o700) {
|
|
1151
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'failed to enforce 0o700 mode on CAS directory', '/casDir');
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
finally {
|
|
1156
|
+
await dirHandle.close();
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
async function ensurePrivateDir(dirPath) {
|
|
1160
|
+
const normalized = resolve(dirPath);
|
|
1161
|
+
await assertNoSymlinkAncestors(normalized, { checkLeaf: true, code: 'CONFIG_INVALID', diagPath: '/casDir' });
|
|
1162
|
+
const myUid = typeof process.getuid === 'function' ? process.getuid() : null;
|
|
1163
|
+
const allSegments = [];
|
|
1164
|
+
let cursor = normalized;
|
|
1165
|
+
while (true) {
|
|
1166
|
+
allSegments.push(cursor);
|
|
1167
|
+
const parent = dirname(cursor);
|
|
1168
|
+
if (parent === cursor)
|
|
1169
|
+
break;
|
|
1170
|
+
cursor = parent;
|
|
1171
|
+
}
|
|
1172
|
+
allSegments.reverse();
|
|
1173
|
+
const missingChain = [];
|
|
1174
|
+
let missingStarted = false;
|
|
1175
|
+
for (let idx = 0; idx < allSegments.length - 1; idx += 1) {
|
|
1176
|
+
const seg = allSegments[idx];
|
|
1177
|
+
if (missingStarted) {
|
|
1178
|
+
missingChain.push(seg);
|
|
1179
|
+
continue;
|
|
1180
|
+
}
|
|
1181
|
+
if (!inspectExistingAncestorSync(seg, myUid)) {
|
|
1182
|
+
missingStarted = true;
|
|
1183
|
+
missingChain.push(seg);
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
if (missingStarted) {
|
|
1187
|
+
missingChain.push(normalized);
|
|
1188
|
+
}
|
|
1189
|
+
else {
|
|
1190
|
+
let leafStat = null;
|
|
1191
|
+
try {
|
|
1192
|
+
leafStat = lstatSync(normalized);
|
|
1193
|
+
}
|
|
1194
|
+
catch (err) {
|
|
1195
|
+
if (err?.code !== 'ENOENT') {
|
|
1196
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'failed to inspect CAS directory', '/casDir');
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
if (leafStat === null) {
|
|
1200
|
+
missingChain.push(normalized);
|
|
1201
|
+
}
|
|
1202
|
+
else {
|
|
1203
|
+
if (leafStat.isSymbolicLink() || !leafStat.isDirectory()) {
|
|
1204
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'CAS path is not a regular directory', '/casDir');
|
|
1205
|
+
}
|
|
1206
|
+
if (myUid !== null && leafStat.uid !== myUid) {
|
|
1207
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'CAS directory is not owned by the current user', '/casDir');
|
|
1208
|
+
}
|
|
1209
|
+
if ((leafStat.mode & 0o022) !== 0 || (leafStat.mode & 0o700) !== 0o700) {
|
|
1210
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'CAS directory must be owner-accessible and not group/world writable', '/casDir');
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
for (const segPath of missingChain) {
|
|
1215
|
+
const parentPath = dirname(segPath);
|
|
1216
|
+
if (!inspectExistingAncestorSync(parentPath, myUid)) {
|
|
1217
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'missing parent during CAS directory creation', '/casDir');
|
|
1218
|
+
}
|
|
1219
|
+
let created = false;
|
|
1220
|
+
try {
|
|
1221
|
+
await mkdir(segPath, { mode: 0o700 });
|
|
1222
|
+
created = true;
|
|
1223
|
+
}
|
|
1224
|
+
catch (err) {
|
|
1225
|
+
if (err?.code !== 'EEXIST') {
|
|
1226
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'failed to create private CAS directory', '/casDir');
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
await verifyAndTightenCreatedDir(segPath, myUid, true);
|
|
1230
|
+
if (created && parentPath !== segPath) {
|
|
1231
|
+
const parentStat = lstatSync(parentPath);
|
|
1232
|
+
const syncTarget = parentStat.isSymbolicLink() && isAllowedOsRootSymlink(parentPath)
|
|
1233
|
+
? realpathSync(parentPath)
|
|
1234
|
+
: parentPath;
|
|
1235
|
+
assertTrustedAncestorStatSync(lstatSync(syncTarget), syncTarget, myUid);
|
|
1236
|
+
await syncDir(syncTarget);
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
await verifyAndTightenCreatedDir(normalized, myUid, true);
|
|
1240
|
+
}
|
|
1241
|
+
async function cleanStaleTempFiles(dirPath) {
|
|
1242
|
+
const dir = await opendir(dirPath);
|
|
1243
|
+
try {
|
|
1244
|
+
for await (const dirent of dir) {
|
|
1245
|
+
if (!dirent.name.startsWith('.tmp-'))
|
|
1246
|
+
continue;
|
|
1247
|
+
const target = join(dirPath, dirent.name);
|
|
1248
|
+
const st = await lstat(target).catch(() => null);
|
|
1249
|
+
if (st !== null && !st.isSymbolicLink() && st.isFile()) {
|
|
1250
|
+
await unlink(target).catch(() => { });
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
finally {
|
|
1255
|
+
await dir.close().catch(() => { });
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
async function waitForDrainOrClose(res, signal) {
|
|
1259
|
+
if (res.destroyed || res.writableEnded || signal.aborted)
|
|
1260
|
+
return false;
|
|
1261
|
+
return new Promise(resolveWait => {
|
|
1262
|
+
const cleanup = () => {
|
|
1263
|
+
res.removeListener('drain', onDrain);
|
|
1264
|
+
res.removeListener('close', onClose);
|
|
1265
|
+
res.removeListener('error', onClose);
|
|
1266
|
+
signal.removeEventListener('abort', onClose);
|
|
1267
|
+
};
|
|
1268
|
+
const onDrain = () => {
|
|
1269
|
+
cleanup();
|
|
1270
|
+
resolveWait(!res.destroyed && !res.writableEnded && !signal.aborted);
|
|
1271
|
+
};
|
|
1272
|
+
const onClose = () => {
|
|
1273
|
+
cleanup();
|
|
1274
|
+
resolveWait(false);
|
|
1275
|
+
};
|
|
1276
|
+
res.once('drain', onDrain);
|
|
1277
|
+
res.once('close', onClose);
|
|
1278
|
+
res.once('error', onClose);
|
|
1279
|
+
signal.addEventListener('abort', onClose, { once: true });
|
|
1280
|
+
});
|
|
1281
|
+
}
|
|
1282
|
+
function sendJson(res, status, body, extraHeaders = {}) {
|
|
1283
|
+
if (res.headersSent || res.destroyed || res.writableEnded)
|
|
1284
|
+
return;
|
|
1285
|
+
const bytes = Buffer.from(canonicalJson(body), 'utf8');
|
|
1286
|
+
res.writeHead(status, {
|
|
1287
|
+
'content-type': 'application/json; charset=utf-8',
|
|
1288
|
+
'content-length': String(bytes.byteLength),
|
|
1289
|
+
...(status === 413 ? { connection: 'close' } : {}),
|
|
1290
|
+
...extraHeaders,
|
|
1291
|
+
});
|
|
1292
|
+
res.end(bytes);
|
|
1293
|
+
}
|
|
1294
|
+
function sendError(res, scrubber, status, code, message) {
|
|
1295
|
+
const safeMessage = scrubber.scrub(message);
|
|
1296
|
+
sendJson(res, status, {
|
|
1297
|
+
code,
|
|
1298
|
+
error: { code, message: safeMessage },
|
|
1299
|
+
});
|
|
1300
|
+
}
|
|
1301
|
+
function decodeSegment(segment) {
|
|
1302
|
+
try {
|
|
1303
|
+
return decodeURIComponent(segment);
|
|
1304
|
+
}
|
|
1305
|
+
catch {
|
|
1306
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'malformed URI component');
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
const ACTIVE_CAS_DIR_LOCKS = new Set();
|
|
1310
|
+
export async function startRelayServer(options) {
|
|
1311
|
+
const config = normalizeRelayServerConfig(options);
|
|
1312
|
+
const casLockPath = join(config.casDir, '.relay.lock');
|
|
1313
|
+
const blobsDir = join(config.casDir, 'blobs');
|
|
1314
|
+
const sha256Dir = join(blobsDir, 'sha256');
|
|
1315
|
+
const tmpDir = join(config.casDir, 'tmp');
|
|
1316
|
+
const receiptsDir = join(config.casDir, 'receipts');
|
|
1317
|
+
const operationsDir = join(config.casDir, 'operations');
|
|
1318
|
+
await ensurePrivateDir(config.casDir);
|
|
1319
|
+
// Register Relay credentials into SecretScrubber and derive scan overlap from longest encoded form.
|
|
1320
|
+
const secretScrubber = new SecretScrubber();
|
|
1321
|
+
const registeredSecrets = [config.controllerSigningSecret, ...config.workerTokens];
|
|
1322
|
+
if (config.controllerAuthToken !== undefined) {
|
|
1323
|
+
registeredSecrets.push(config.controllerAuthToken);
|
|
1324
|
+
}
|
|
1325
|
+
for (const sec of registeredSecrets) {
|
|
1326
|
+
secretScrubber.register(sec);
|
|
1327
|
+
}
|
|
1328
|
+
const secretOverlapBytes = computeSecretScanOverlapBytes(registeredSecrets);
|
|
1329
|
+
const stagedInputBlobsByOperation = new Map();
|
|
1330
|
+
const activeOperations = new Map();
|
|
1331
|
+
const terminalCache = new Map();
|
|
1332
|
+
const undurableTerminalByOperation = new Map();
|
|
1333
|
+
const inFlightReceiptWrites = new Map();
|
|
1334
|
+
const inFlightByOperation = new Map();
|
|
1335
|
+
const activeDurabilityTasks = new Set();
|
|
1336
|
+
const activeRequestTasks = new Set();
|
|
1337
|
+
const jobCompletionChains = new Map();
|
|
1338
|
+
const admissionChains = new Map();
|
|
1339
|
+
const openSockets = new Set();
|
|
1340
|
+
const serverAbort = new AbortController();
|
|
1341
|
+
let casLockDb = null;
|
|
1342
|
+
let casLockInodeKey = null;
|
|
1343
|
+
const recordRecoveryFenceStrict = (operationId, reason) => {
|
|
1344
|
+
if (casLockDb === null) {
|
|
1345
|
+
throw new HardwareRunnerError('QUEUE_STATE_INVALID', 'CAS lock database unavailable for recovery fence');
|
|
1346
|
+
}
|
|
1347
|
+
options.onBeforeFenceUpdate?.(operationId, reason);
|
|
1348
|
+
casLockDb
|
|
1349
|
+
.prepare('INSERT OR REPLACE INTO recovery_fence (operation_id, reason, created_at_ms) VALUES (?, ?, ?)')
|
|
1350
|
+
.run(operationId, reason, Date.now());
|
|
1351
|
+
};
|
|
1352
|
+
const recordRecoveryFence = (operationId, reason) => {
|
|
1353
|
+
if (casLockDb === null)
|
|
1354
|
+
return;
|
|
1355
|
+
try {
|
|
1356
|
+
options.onBeforeFenceUpdate?.(operationId, reason);
|
|
1357
|
+
casLockDb
|
|
1358
|
+
.prepare('INSERT OR REPLACE INTO recovery_fence (operation_id, reason, created_at_ms) VALUES (?, ?, ?)')
|
|
1359
|
+
.run(operationId, reason, Date.now());
|
|
1360
|
+
}
|
|
1361
|
+
catch {
|
|
1362
|
+
// Pre-admission recovery_fence row is already persisted on disk before work begins;
|
|
1363
|
+
// shutdown also propagates persistence errors and fails closed.
|
|
1364
|
+
}
|
|
1365
|
+
};
|
|
1366
|
+
const clearRecoveryFence = (operationId) => {
|
|
1367
|
+
if (casLockDb === null)
|
|
1368
|
+
return;
|
|
1369
|
+
try {
|
|
1370
|
+
casLockDb.prepare('DELETE FROM recovery_fence WHERE operation_id = ?').run(operationId);
|
|
1371
|
+
}
|
|
1372
|
+
catch {
|
|
1373
|
+
// Ignore cleanup errors if lock database is already closing.
|
|
1374
|
+
}
|
|
1375
|
+
};
|
|
1376
|
+
const withSerialLock = async (map, key, fn) => {
|
|
1377
|
+
const prev = map.get(key) ?? Promise.resolve();
|
|
1378
|
+
let release;
|
|
1379
|
+
const gate = new Promise(r => {
|
|
1380
|
+
release = r;
|
|
1381
|
+
});
|
|
1382
|
+
const chained = prev.catch(() => { }).then(() => gate);
|
|
1383
|
+
map.set(key, chained);
|
|
1384
|
+
await prev.catch(() => { });
|
|
1385
|
+
try {
|
|
1386
|
+
return await fn();
|
|
1387
|
+
}
|
|
1388
|
+
finally {
|
|
1389
|
+
release();
|
|
1390
|
+
if (map.get(key) === chained) {
|
|
1391
|
+
map.delete(key);
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
};
|
|
1395
|
+
const withAdmissionLock = (fn) => withSerialLock(admissionChains, '__global_admission__', fn);
|
|
1396
|
+
let maxRetainedTerminalOps = Math.max(4_096, config.maxJobs * 16);
|
|
1397
|
+
if (config.maxRetainedTerminalOps !== undefined) {
|
|
1398
|
+
maxRetainedTerminalOps = config.maxRetainedTerminalOps;
|
|
1399
|
+
}
|
|
1400
|
+
const countRetainedTerminalEntries = () => {
|
|
1401
|
+
let uniqueCount = terminalCache.size;
|
|
1402
|
+
for (const opId of undurableTerminalByOperation.keys()) {
|
|
1403
|
+
if (!terminalCache.has(opId))
|
|
1404
|
+
uniqueCount += 1;
|
|
1405
|
+
}
|
|
1406
|
+
return uniqueCount;
|
|
1407
|
+
};
|
|
1408
|
+
const putBoundedTerminalCache = (entry) => {
|
|
1409
|
+
terminalCache.delete(entry.operationId);
|
|
1410
|
+
terminalCache.set(entry.operationId, entry);
|
|
1411
|
+
while (countRetainedTerminalEntries() > maxRetainedTerminalOps && terminalCache.size > 0) {
|
|
1412
|
+
let evictKey;
|
|
1413
|
+
for (const candidateKey of terminalCache.keys()) {
|
|
1414
|
+
if (!undurableTerminalByOperation.has(candidateKey)) {
|
|
1415
|
+
evictKey = candidateKey;
|
|
1416
|
+
break;
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
if (evictKey === undefined)
|
|
1420
|
+
break;
|
|
1421
|
+
terminalCache.delete(evictKey);
|
|
1422
|
+
}
|
|
1423
|
+
};
|
|
1424
|
+
const buildTerminalEntry = (verdict, request, flags) => {
|
|
1425
|
+
const committedOutputs = new Map();
|
|
1426
|
+
for (const art of verdict.outputArtifacts ?? []) {
|
|
1427
|
+
committedOutputs.set(art.digest.hex, art.byteLength);
|
|
1428
|
+
}
|
|
1429
|
+
let frozenInputs = null;
|
|
1430
|
+
if (request !== null) {
|
|
1431
|
+
frozenInputs = new Map();
|
|
1432
|
+
for (const item of collectDeclaredInputBlobs(request.candidateArtifacts)) {
|
|
1433
|
+
frozenInputs.set(item.digest.hex, item.byteLength);
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
return {
|
|
1437
|
+
operationId: verdict.operationId,
|
|
1438
|
+
verdict,
|
|
1439
|
+
verdictCanonical: canonicalJson(verdict),
|
|
1440
|
+
request,
|
|
1441
|
+
requestCanonical: request !== null ? canonicalJson(request) : null,
|
|
1442
|
+
frozenInputs,
|
|
1443
|
+
committedOutputs,
|
|
1444
|
+
linkedOnDisk: flags.linkedOnDisk,
|
|
1445
|
+
durableOnDisk: flags.durableOnDisk,
|
|
1446
|
+
};
|
|
1447
|
+
};
|
|
1448
|
+
const recordCommittedTerminalTransition = (verdict, flags) => {
|
|
1449
|
+
const vCanonical = canonicalJson(verdict);
|
|
1450
|
+
const existing = undurableTerminalByOperation.get(verdict.operationId) ?? terminalCache.get(verdict.operationId);
|
|
1451
|
+
if (existing !== undefined && existing.verdictCanonical === vCanonical) {
|
|
1452
|
+
if (flags.linkedOnDisk)
|
|
1453
|
+
existing.linkedOnDisk = true;
|
|
1454
|
+
if (flags.durableOnDisk)
|
|
1455
|
+
existing.durableOnDisk = true;
|
|
1456
|
+
if (existing.durableOnDisk) {
|
|
1457
|
+
undurableTerminalByOperation.delete(verdict.operationId);
|
|
1458
|
+
}
|
|
1459
|
+
else {
|
|
1460
|
+
undurableTerminalByOperation.set(verdict.operationId, existing);
|
|
1461
|
+
}
|
|
1462
|
+
activeOperations.delete(verdict.operationId);
|
|
1463
|
+
putBoundedTerminalCache(existing);
|
|
1464
|
+
return existing;
|
|
1465
|
+
}
|
|
1466
|
+
const active = activeOperations.get(verdict.operationId);
|
|
1467
|
+
activeOperations.delete(verdict.operationId);
|
|
1468
|
+
const entry = buildTerminalEntry(verdict, active?.request ?? null, flags);
|
|
1469
|
+
if (!entry.durableOnDisk) {
|
|
1470
|
+
undurableTerminalByOperation.set(verdict.operationId, entry);
|
|
1471
|
+
}
|
|
1472
|
+
putBoundedTerminalCache(entry);
|
|
1473
|
+
return entry;
|
|
1474
|
+
};
|
|
1475
|
+
const assertVerdictPublishable = (verdict) => {
|
|
1476
|
+
const canonical = canonicalJson(verdict);
|
|
1477
|
+
if (Buffer.byteLength(canonical, 'utf8') > MAX_CONTROL_BODY_BYTES) {
|
|
1478
|
+
throw new HardwareRunnerError('PAYLOAD_TOO_LARGE', `benchmark_verdict exceeds ${MAX_CONTROL_BODY_BYTES} bytes`);
|
|
1479
|
+
}
|
|
1480
|
+
if (secretScrubber.containsSecret(canonical)) {
|
|
1481
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'completion verdict rejected by SecretScrubber');
|
|
1482
|
+
}
|
|
1483
|
+
return canonical;
|
|
1484
|
+
};
|
|
1485
|
+
const stageSignedVerdictReceiptTemp = async (verdict) => {
|
|
1486
|
+
const operationId = parseOperationId(verdict.operationId, '/operationId');
|
|
1487
|
+
const verdictCanonical = assertVerdictPublishable(verdict);
|
|
1488
|
+
await assertNoSymlinkAncestors(receiptsDir, { checkLeaf: true, code: 'ARTIFACT_INVALID', diagPath: '/receipts' });
|
|
1489
|
+
const signature = signRelayPayload(config.controllerSigningSecret, verdictCanonical);
|
|
1490
|
+
const receiptObj = Object.create(null);
|
|
1491
|
+
for (const key of Object.keys(verdict)) {
|
|
1492
|
+
const val = verdict[key];
|
|
1493
|
+
if (val !== undefined)
|
|
1494
|
+
receiptObj[key] = val;
|
|
1495
|
+
}
|
|
1496
|
+
receiptObj.signature = signature;
|
|
1497
|
+
const receiptBytes = Buffer.from(canonicalJson(receiptObj), 'utf8');
|
|
1498
|
+
if (receiptBytes.byteLength > MAX_RECEIPT_FILE_BYTES) {
|
|
1499
|
+
throw new HardwareRunnerError('PAYLOAD_TOO_LARGE', `signed receipt exceeds ${MAX_RECEIPT_FILE_BYTES} bytes`);
|
|
1500
|
+
}
|
|
1501
|
+
const tmpReceiptPath = join(receiptsDir, `.tmp-${operationId}-${randomBytes(8).toString('hex')}.json`);
|
|
1502
|
+
const finalReceiptPath = join(receiptsDir, `${operationId}.json`);
|
|
1503
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
1504
|
+
const handle = await open(tmpReceiptPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | noFollow, 0o600);
|
|
1505
|
+
let closed = false;
|
|
1506
|
+
try {
|
|
1507
|
+
await writeAllToFileHandle(handle, receiptBytes);
|
|
1508
|
+
await handle.sync();
|
|
1509
|
+
await handle.close();
|
|
1510
|
+
closed = true;
|
|
1511
|
+
return { operationId, tmpReceiptPath, finalReceiptPath, receiptBytes };
|
|
1512
|
+
}
|
|
1513
|
+
catch (err) {
|
|
1514
|
+
if (!closed)
|
|
1515
|
+
await handle.close().catch(() => { });
|
|
1516
|
+
await unlink(tmpReceiptPath).catch(() => { });
|
|
1517
|
+
throw err;
|
|
1518
|
+
}
|
|
1519
|
+
};
|
|
1520
|
+
const ensureReceiptDurable = (verdict) => {
|
|
1521
|
+
const operationId = verdict.operationId;
|
|
1522
|
+
const vCanonical = canonicalJson(verdict);
|
|
1523
|
+
const writeKey = `${operationId}\0${vCanonical}`;
|
|
1524
|
+
const cached = undurableTerminalByOperation.get(operationId) ?? terminalCache.get(operationId);
|
|
1525
|
+
if (cached !== undefined && cached.verdictCanonical === vCanonical && cached.durableOnDisk) {
|
|
1526
|
+
putBoundedTerminalCache(cached);
|
|
1527
|
+
return Promise.resolve();
|
|
1528
|
+
}
|
|
1529
|
+
const existingTask = inFlightReceiptWrites.get(writeKey);
|
|
1530
|
+
if (existingTask !== undefined) {
|
|
1531
|
+
return existingTask;
|
|
1532
|
+
}
|
|
1533
|
+
// If the operation already left activeOperations and is not in undurableTerminalByOperation,
|
|
1534
|
+
// it was previously settled and evicted from terminalCache; reload full receipt + descriptor from disk.
|
|
1535
|
+
if (!activeOperations.has(operationId) && !undurableTerminalByOperation.has(operationId)) {
|
|
1536
|
+
const reloadTask = (async () => {
|
|
1537
|
+
const resolved = await resolveDiskOperationState(operationId);
|
|
1538
|
+
if (resolved.kind !== 'terminal' || resolved.entry.verdictCanonical !== vCanonical) {
|
|
1539
|
+
throw new Error('evicted terminal receipt missing or mismatched on disk');
|
|
1540
|
+
}
|
|
1541
|
+
})().finally(() => {
|
|
1542
|
+
if (inFlightReceiptWrites.get(writeKey) === reloadTask) {
|
|
1543
|
+
inFlightReceiptWrites.delete(writeKey);
|
|
1544
|
+
}
|
|
1545
|
+
activeDurabilityTasks.delete(reloadTask);
|
|
1546
|
+
});
|
|
1547
|
+
inFlightReceiptWrites.set(writeKey, reloadTask);
|
|
1548
|
+
activeDurabilityTasks.add(reloadTask);
|
|
1549
|
+
return reloadTask;
|
|
1550
|
+
}
|
|
1551
|
+
const entry = recordCommittedTerminalTransition(verdict, { linkedOnDisk: false, durableOnDisk: false });
|
|
1552
|
+
const task = (async () => {
|
|
1553
|
+
try {
|
|
1554
|
+
if (options.onBeforeReceiptPersist !== undefined) {
|
|
1555
|
+
await options.onBeforeReceiptPersist(operationId);
|
|
1556
|
+
}
|
|
1557
|
+
const finalReceiptPath = join(receiptsDir, `${operationId}.json`);
|
|
1558
|
+
if (!entry.linkedOnDisk) {
|
|
1559
|
+
const existingBytes = await readRecordFileOrNull(finalReceiptPath, MAX_RECEIPT_FILE_BYTES, 'runtime');
|
|
1560
|
+
if (existingBytes !== null) {
|
|
1561
|
+
let parsedExisting;
|
|
1562
|
+
try {
|
|
1563
|
+
parsedExisting = parseAuthenticatedReceiptBytes(existingBytes, operationId, config.controllerSigningSecret, config.maxBlobBytes, secretScrubber);
|
|
1564
|
+
}
|
|
1565
|
+
catch (parseErr) {
|
|
1566
|
+
throw new Error('corrupted persisted receipt on disk', { cause: parseErr });
|
|
1567
|
+
}
|
|
1568
|
+
if (canonicalJson(parsedExisting) !== vCanonical) {
|
|
1569
|
+
throw new Error('conflicting durable receipt already exists on disk');
|
|
1570
|
+
}
|
|
1571
|
+
entry.linkedOnDisk = true;
|
|
1572
|
+
}
|
|
1573
|
+
else {
|
|
1574
|
+
const staged = await stageSignedVerdictReceiptTemp(verdict);
|
|
1575
|
+
try {
|
|
1576
|
+
linkSync(staged.tmpReceiptPath, staged.finalReceiptPath);
|
|
1577
|
+
entry.linkedOnDisk = true;
|
|
1578
|
+
}
|
|
1579
|
+
catch (linkErr) {
|
|
1580
|
+
await unlink(staged.tmpReceiptPath).catch(() => { });
|
|
1581
|
+
if (linkErr?.code === 'EEXIST') {
|
|
1582
|
+
const racedBytes = await readRecordFileOrNull(finalReceiptPath, MAX_RECEIPT_FILE_BYTES, 'runtime');
|
|
1583
|
+
if (racedBytes === null) {
|
|
1584
|
+
throw linkErr;
|
|
1585
|
+
}
|
|
1586
|
+
let racedVerdict;
|
|
1587
|
+
try {
|
|
1588
|
+
racedVerdict = parseAuthenticatedReceiptBytes(racedBytes, operationId, config.controllerSigningSecret, config.maxBlobBytes, secretScrubber);
|
|
1589
|
+
}
|
|
1590
|
+
catch (parseErr) {
|
|
1591
|
+
throw new Error('corrupted persisted receipt after EEXIST', { cause: parseErr });
|
|
1592
|
+
}
|
|
1593
|
+
if (canonicalJson(racedVerdict) !== vCanonical) {
|
|
1594
|
+
throw new Error('conflicting durable receipt already exists after EEXIST', { cause: linkErr });
|
|
1595
|
+
}
|
|
1596
|
+
entry.linkedOnDisk = true;
|
|
1597
|
+
}
|
|
1598
|
+
else {
|
|
1599
|
+
throw linkErr;
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
await unlink(staged.tmpReceiptPath).catch(() => { });
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
await syncDir(receiptsDir);
|
|
1606
|
+
entry.durableOnDisk = true;
|
|
1607
|
+
undurableTerminalByOperation.delete(operationId);
|
|
1608
|
+
clearRecoveryFence(operationId);
|
|
1609
|
+
putBoundedTerminalCache(entry);
|
|
1610
|
+
}
|
|
1611
|
+
catch (persistErr) {
|
|
1612
|
+
recordRecoveryFence(operationId, 'receipt_persistence_failed');
|
|
1613
|
+
throw persistErr;
|
|
1614
|
+
}
|
|
1615
|
+
})().finally(() => {
|
|
1616
|
+
if (inFlightReceiptWrites.get(writeKey) === task) {
|
|
1617
|
+
inFlightReceiptWrites.delete(writeKey);
|
|
1618
|
+
}
|
|
1619
|
+
if (inFlightByOperation.get(operationId) === task) {
|
|
1620
|
+
inFlightByOperation.delete(operationId);
|
|
1621
|
+
}
|
|
1622
|
+
activeDurabilityTasks.delete(task);
|
|
1623
|
+
});
|
|
1624
|
+
inFlightReceiptWrites.set(writeKey, task);
|
|
1625
|
+
inFlightByOperation.set(operationId, task);
|
|
1626
|
+
activeDurabilityTasks.add(task);
|
|
1627
|
+
return task;
|
|
1628
|
+
};
|
|
1629
|
+
const persistOperationRequestRecord = async (request) => {
|
|
1630
|
+
const operationId = parseOperationId(request.operationId, '/operationId');
|
|
1631
|
+
await assertNoSymlinkAncestors(operationsDir, { checkLeaf: true, code: 'ARTIFACT_INVALID', diagPath: '/operations' });
|
|
1632
|
+
const finalOpPath = join(operationsDir, `${operationId}.json`);
|
|
1633
|
+
const reqCanonical = canonicalJson(request);
|
|
1634
|
+
const checkExistingOperationBytes = async (rawBytes) => {
|
|
1635
|
+
let existingReq;
|
|
1636
|
+
try {
|
|
1637
|
+
existingReq = parseAuthenticatedOperationBytes(rawBytes, operationId, config.controllerSigningSecret, config.maxBlobBytes);
|
|
1638
|
+
}
|
|
1639
|
+
catch (parseErr) {
|
|
1640
|
+
throw new Error('corrupted persisted operation descriptor', { cause: parseErr });
|
|
1641
|
+
}
|
|
1642
|
+
if (canonicalJson(existingReq) !== reqCanonical) {
|
|
1643
|
+
throw new HardwareRunnerError('QUEUE_JOB_CONFLICT', 'conflicting durable operation record exists');
|
|
1644
|
+
}
|
|
1645
|
+
await syncDir(operationsDir);
|
|
1646
|
+
};
|
|
1647
|
+
const existingBytes = await readRecordFileOrNull(finalOpPath, MAX_OPERATION_FILE_BYTES, 'runtime');
|
|
1648
|
+
if (existingBytes !== null) {
|
|
1649
|
+
await checkExistingOperationBytes(existingBytes);
|
|
1650
|
+
return;
|
|
1651
|
+
}
|
|
1652
|
+
const signature = signRelayPayload(config.controllerSigningSecret, `REQ\n${reqCanonical}`);
|
|
1653
|
+
const recordBytes = Buffer.from(canonicalJson({
|
|
1654
|
+
version: 1,
|
|
1655
|
+
kind: 'benchmark_operation_request',
|
|
1656
|
+
request,
|
|
1657
|
+
signature,
|
|
1658
|
+
}), 'utf8');
|
|
1659
|
+
const tmpOpPath = join(operationsDir, `.tmp-${operationId}-${randomBytes(8).toString('hex')}.json`);
|
|
1660
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
1661
|
+
const handle = await open(tmpOpPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | noFollow, 0o600);
|
|
1662
|
+
let closed = false;
|
|
1663
|
+
try {
|
|
1664
|
+
await writeAllToFileHandle(handle, recordBytes);
|
|
1665
|
+
await handle.sync();
|
|
1666
|
+
await handle.close();
|
|
1667
|
+
closed = true;
|
|
1668
|
+
try {
|
|
1669
|
+
linkSync(tmpOpPath, finalOpPath);
|
|
1670
|
+
}
|
|
1671
|
+
catch (linkErr) {
|
|
1672
|
+
await unlink(tmpOpPath).catch(() => { });
|
|
1673
|
+
if (linkErr?.code === 'EEXIST') {
|
|
1674
|
+
const racedBytes = await readRecordFileOrNull(finalOpPath, MAX_OPERATION_FILE_BYTES, 'runtime');
|
|
1675
|
+
if (racedBytes === null) {
|
|
1676
|
+
throw linkErr;
|
|
1677
|
+
}
|
|
1678
|
+
await checkExistingOperationBytes(racedBytes);
|
|
1679
|
+
return;
|
|
1680
|
+
}
|
|
1681
|
+
throw linkErr;
|
|
1682
|
+
}
|
|
1683
|
+
await unlink(tmpOpPath).catch(() => { });
|
|
1684
|
+
await syncDir(operationsDir);
|
|
1685
|
+
}
|
|
1686
|
+
catch (err) {
|
|
1687
|
+
if (!closed)
|
|
1688
|
+
await handle.close().catch(() => { });
|
|
1689
|
+
await unlink(tmpOpPath).catch(() => { });
|
|
1690
|
+
throw err;
|
|
1691
|
+
}
|
|
1692
|
+
};
|
|
1693
|
+
const resolveDiskOperationState = async (operationId) => {
|
|
1694
|
+
const memTerminal = undurableTerminalByOperation.get(operationId) ?? terminalCache.get(operationId);
|
|
1695
|
+
if (memTerminal !== undefined) {
|
|
1696
|
+
if (memTerminal.durableOnDisk) {
|
|
1697
|
+
putBoundedTerminalCache(memTerminal);
|
|
1698
|
+
}
|
|
1699
|
+
return { kind: 'terminal', entry: memTerminal };
|
|
1700
|
+
}
|
|
1701
|
+
const receiptPath = join(receiptsDir, `${operationId}.json`);
|
|
1702
|
+
const opPath = join(operationsDir, `${operationId}.json`);
|
|
1703
|
+
const receiptBytes = await readRecordFileOrNull(receiptPath, MAX_RECEIPT_FILE_BYTES, 'runtime');
|
|
1704
|
+
const opBytes = await readRecordFileOrNull(opPath, MAX_OPERATION_FILE_BYTES, 'runtime');
|
|
1705
|
+
let diskVerdict = null;
|
|
1706
|
+
if (receiptBytes !== null) {
|
|
1707
|
+
try {
|
|
1708
|
+
diskVerdict = parseAuthenticatedReceiptBytes(receiptBytes, operationId, config.controllerSigningSecret, config.maxBlobBytes, secretScrubber);
|
|
1709
|
+
}
|
|
1710
|
+
catch (err) {
|
|
1711
|
+
throw new Error('corrupted persisted receipt record', { cause: err });
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
let diskRequest = null;
|
|
1715
|
+
if (opBytes !== null) {
|
|
1716
|
+
try {
|
|
1717
|
+
diskRequest = parseAuthenticatedOperationBytes(opBytes, operationId, config.controllerSigningSecret, config.maxBlobBytes);
|
|
1718
|
+
}
|
|
1719
|
+
catch (err) {
|
|
1720
|
+
throw new Error('corrupted persisted operation descriptor', { cause: err });
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
if (diskVerdict !== null) {
|
|
1724
|
+
if (diskRequest !== null && !verdictMatchesRequestBinding(diskVerdict, diskRequest)) {
|
|
1725
|
+
throw new Error('persisted receipt and operation descriptor binding mismatch');
|
|
1726
|
+
}
|
|
1727
|
+
if (diskRequest !== null) {
|
|
1728
|
+
await syncDir(operationsDir);
|
|
1729
|
+
}
|
|
1730
|
+
await syncDir(receiptsDir);
|
|
1731
|
+
const entry = buildTerminalEntry(diskVerdict, diskRequest, {
|
|
1732
|
+
linkedOnDisk: true,
|
|
1733
|
+
durableOnDisk: true,
|
|
1734
|
+
});
|
|
1735
|
+
putBoundedTerminalCache(entry);
|
|
1736
|
+
return { kind: 'terminal', entry };
|
|
1737
|
+
}
|
|
1738
|
+
if (diskRequest !== null) {
|
|
1739
|
+
await syncDir(operationsDir);
|
|
1740
|
+
return {
|
|
1741
|
+
kind: 'descriptor_only',
|
|
1742
|
+
request: diskRequest,
|
|
1743
|
+
requestCanonical: canonicalJson(diskRequest),
|
|
1744
|
+
};
|
|
1745
|
+
}
|
|
1746
|
+
return { kind: 'absent' };
|
|
1747
|
+
};
|
|
1748
|
+
const hasCasBlobOnDisk = async (sha256) => {
|
|
1749
|
+
const st = await lstat(join(sha256Dir, sha256)).catch((err) => {
|
|
1750
|
+
if (err?.code === 'ENOENT')
|
|
1751
|
+
return null;
|
|
1752
|
+
throw err;
|
|
1753
|
+
});
|
|
1754
|
+
return st !== null;
|
|
1755
|
+
};
|
|
1756
|
+
const verifyExistingCasBlob = async (sha256, expectedLength, verifyOptions = {}) => {
|
|
1757
|
+
const blobPath = join(sha256Dir, sha256);
|
|
1758
|
+
await assertNoSymlinkAncestors(blobPath, { checkLeaf: true, code: 'ARTIFACT_INVALID', diagPath: '/blob' });
|
|
1759
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
1760
|
+
let handle;
|
|
1761
|
+
try {
|
|
1762
|
+
handle = await open(blobPath, constants.O_RDONLY | noFollow);
|
|
1763
|
+
}
|
|
1764
|
+
catch (err) {
|
|
1765
|
+
if (err?.code === 'ENOENT' && verifyOptions.missingCode !== undefined) {
|
|
1766
|
+
throw new HardwareRunnerError(verifyOptions.missingCode, `CAS blob ${sha256} is not staged`);
|
|
1767
|
+
}
|
|
1768
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'CAS blob could not be opened safely');
|
|
1769
|
+
}
|
|
1770
|
+
try {
|
|
1771
|
+
const st = await handle.stat();
|
|
1772
|
+
if (!st.isFile()
|
|
1773
|
+
|| st.isSymbolicLink()
|
|
1774
|
+
|| st.nlink !== 1
|
|
1775
|
+
|| (typeof process.getuid === 'function' && st.uid !== process.getuid())
|
|
1776
|
+
|| (st.mode & 0o777) !== 0o400
|
|
1777
|
+
|| st.size !== expectedLength) {
|
|
1778
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'existing CAS blob failed inode/0o400/size verification');
|
|
1779
|
+
}
|
|
1780
|
+
const hasher = createHash('sha256');
|
|
1781
|
+
let scanTail = Buffer.alloc(0);
|
|
1782
|
+
const buf = Buffer.allocUnsafe(Math.min(MAX_CAS_CHUNK_BYTES, Math.max(1, st.size)));
|
|
1783
|
+
let offset = 0;
|
|
1784
|
+
while (offset < st.size) {
|
|
1785
|
+
const maxStep = verifyOptions.scrubSecrets === true
|
|
1786
|
+
? MAX_CAS_CHUNK_BYTES - scanTail.byteLength
|
|
1787
|
+
: buf.byteLength;
|
|
1788
|
+
const toRead = Math.min(maxStep, buf.byteLength, st.size - offset);
|
|
1789
|
+
const { bytesRead } = await handle.read(buf, 0, toRead, offset);
|
|
1790
|
+
if (bytesRead <= 0)
|
|
1791
|
+
break;
|
|
1792
|
+
const slice = buf.subarray(0, bytesRead);
|
|
1793
|
+
if (verifyOptions.scrubSecrets === true) {
|
|
1794
|
+
const windowBuf = scanTail.byteLength === 0 ? slice : Buffer.concat([scanTail, slice]);
|
|
1795
|
+
if (secretScrubber.containsSecret(windowBuf.toString('latin1'))
|
|
1796
|
+
|| secretScrubber.containsSecret(windowBuf.toString('utf8'))) {
|
|
1797
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'output blob rejected by SecretScrubber');
|
|
1798
|
+
}
|
|
1799
|
+
scanTail = windowBuf.byteLength > secretOverlapBytes
|
|
1800
|
+
? Buffer.from(windowBuf.subarray(windowBuf.byteLength - secretOverlapBytes))
|
|
1801
|
+
: Buffer.from(windowBuf);
|
|
1802
|
+
}
|
|
1803
|
+
hasher.update(slice);
|
|
1804
|
+
offset += bytesRead;
|
|
1805
|
+
}
|
|
1806
|
+
const after = await handle.stat();
|
|
1807
|
+
if (offset !== st.size
|
|
1808
|
+
|| after.ino !== st.ino
|
|
1809
|
+
|| after.dev !== st.dev
|
|
1810
|
+
|| after.size !== st.size
|
|
1811
|
+
|| (after.mode & 0o777) !== 0o400
|
|
1812
|
+
|| after.nlink !== 1
|
|
1813
|
+
|| hasher.digest('hex') !== sha256) {
|
|
1814
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'existing CAS blob failed sha256 verification');
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
finally {
|
|
1818
|
+
await handle.close();
|
|
1819
|
+
}
|
|
1820
|
+
};
|
|
1821
|
+
const ingestStreamedCasBlob = async (req, sha256, expectedLength, optionsIngest) => {
|
|
1822
|
+
await assertNoSymlinkAncestors(sha256Dir, { checkLeaf: true, code: 'ARTIFACT_INVALID', diagPath: '/casDir' });
|
|
1823
|
+
await assertNoSymlinkAncestors(tmpDir, { checkLeaf: true, code: 'ARTIFACT_INVALID', diagPath: '/casDir' });
|
|
1824
|
+
const tmpPath = join(tmpDir, `.tmp-${randomBytes(16).toString('hex')}`);
|
|
1825
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
1826
|
+
const tmpHandle = await open(tmpPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | noFollow, 0o600);
|
|
1827
|
+
let tmpClosed = false;
|
|
1828
|
+
let tmpUnlinked = false;
|
|
1829
|
+
const hasher = createHash('sha256');
|
|
1830
|
+
let receivedBytes = 0;
|
|
1831
|
+
let scanTail = Buffer.alloc(0);
|
|
1832
|
+
try {
|
|
1833
|
+
for await (const rawChunk of req) {
|
|
1834
|
+
const buf = Buffer.isBuffer(rawChunk) ? rawChunk : Buffer.from(rawChunk);
|
|
1835
|
+
let offset = 0;
|
|
1836
|
+
while (offset < buf.byteLength) {
|
|
1837
|
+
const maxSliceBytes = optionsIngest.scrubSecrets
|
|
1838
|
+
? MAX_CAS_CHUNK_BYTES - scanTail.byteLength
|
|
1839
|
+
: MAX_CAS_CHUNK_BYTES;
|
|
1840
|
+
const slice = buf.subarray(offset, Math.min(buf.byteLength, offset + maxSliceBytes));
|
|
1841
|
+
if (slice.byteLength === 0)
|
|
1842
|
+
break;
|
|
1843
|
+
offset += slice.byteLength;
|
|
1844
|
+
receivedBytes += slice.byteLength;
|
|
1845
|
+
if (receivedBytes > config.maxBlobBytes) {
|
|
1846
|
+
throw new HardwareRunnerError('PAYLOAD_TOO_LARGE', `blob exceeds maxBlobBytes (${config.maxBlobBytes})`);
|
|
1847
|
+
}
|
|
1848
|
+
if (receivedBytes > expectedLength) {
|
|
1849
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'streamed blob exceeded declared x-loopwright-blob-length');
|
|
1850
|
+
}
|
|
1851
|
+
if (optionsIngest.scrubSecrets) {
|
|
1852
|
+
const windowBuf = scanTail.byteLength === 0 ? slice : Buffer.concat([scanTail, slice]);
|
|
1853
|
+
if (secretScrubber.containsSecret(windowBuf.toString('latin1'))
|
|
1854
|
+
|| secretScrubber.containsSecret(windowBuf.toString('utf8'))) {
|
|
1855
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'output blob rejected by SecretScrubber');
|
|
1856
|
+
}
|
|
1857
|
+
scanTail = windowBuf.byteLength > secretOverlapBytes
|
|
1858
|
+
? Buffer.from(windowBuf.subarray(windowBuf.byteLength - secretOverlapBytes))
|
|
1859
|
+
: Buffer.from(windowBuf);
|
|
1860
|
+
}
|
|
1861
|
+
hasher.update(slice);
|
|
1862
|
+
await writeAllToFileHandle(tmpHandle, slice);
|
|
1863
|
+
}
|
|
1864
|
+
}
|
|
1865
|
+
if (receivedBytes !== expectedLength) {
|
|
1866
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'streamed blob shorter than declared x-loopwright-blob-length');
|
|
1867
|
+
}
|
|
1868
|
+
const observedHex = hasher.digest('hex');
|
|
1869
|
+
if (observedHex !== sha256) {
|
|
1870
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'streamed blob sha256 mismatch');
|
|
1871
|
+
}
|
|
1872
|
+
await tmpHandle.chmod(0o400);
|
|
1873
|
+
await tmpHandle.sync();
|
|
1874
|
+
const tmpStat = await tmpHandle.stat();
|
|
1875
|
+
if (!tmpStat.isFile() || tmpStat.isSymbolicLink() || tmpStat.nlink !== 1 || (tmpStat.mode & 0o777) !== 0o400) {
|
|
1876
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'sealed temp blob failed stat verification');
|
|
1877
|
+
}
|
|
1878
|
+
const finalPath = join(sha256Dir, sha256);
|
|
1879
|
+
let linked = false;
|
|
1880
|
+
try {
|
|
1881
|
+
await link(tmpPath, finalPath);
|
|
1882
|
+
linked = true;
|
|
1883
|
+
}
|
|
1884
|
+
catch (err) {
|
|
1885
|
+
if (err?.code !== 'EEXIST')
|
|
1886
|
+
throw err;
|
|
1887
|
+
}
|
|
1888
|
+
if (linked) {
|
|
1889
|
+
await unlink(tmpPath);
|
|
1890
|
+
tmpUnlinked = true;
|
|
1891
|
+
await tmpHandle.close();
|
|
1892
|
+
tmpClosed = true;
|
|
1893
|
+
await syncDir(sha256Dir);
|
|
1894
|
+
await verifyExistingCasBlob(sha256, expectedLength);
|
|
1895
|
+
return { created: true };
|
|
1896
|
+
}
|
|
1897
|
+
await tmpHandle.close();
|
|
1898
|
+
tmpClosed = true;
|
|
1899
|
+
await unlink(tmpPath);
|
|
1900
|
+
tmpUnlinked = true;
|
|
1901
|
+
for (let attempt = 0; attempt < 20; attempt += 1) {
|
|
1902
|
+
const st = await lstat(finalPath).catch(() => null);
|
|
1903
|
+
if (!st || st.isSymbolicLink() || !st.isFile() || st.nlink <= 1)
|
|
1904
|
+
break;
|
|
1905
|
+
await new Promise(r => setTimeout(r, 5));
|
|
1906
|
+
}
|
|
1907
|
+
await verifyExistingCasBlob(sha256, expectedLength, { scrubSecrets: optionsIngest.scrubSecrets });
|
|
1908
|
+
await syncDir(sha256Dir);
|
|
1909
|
+
return { created: false };
|
|
1910
|
+
}
|
|
1911
|
+
finally {
|
|
1912
|
+
if (!tmpClosed)
|
|
1913
|
+
await tmpHandle.close().catch(() => { });
|
|
1914
|
+
if (!tmpUnlinked)
|
|
1915
|
+
await unlink(tmpPath).catch(() => { });
|
|
1916
|
+
}
|
|
1917
|
+
};
|
|
1918
|
+
const streamCasBlobResponse = async (res, sha256, expectedLength, extraHeaders) => {
|
|
1919
|
+
const blobPath = join(sha256Dir, sha256);
|
|
1920
|
+
await assertNoSymlinkAncestors(blobPath, { checkLeaf: true, code: 'ARTIFACT_INVALID', diagPath: '/blob' });
|
|
1921
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
1922
|
+
let handle;
|
|
1923
|
+
try {
|
|
1924
|
+
handle = await open(blobPath, constants.O_RDONLY | noFollow);
|
|
1925
|
+
}
|
|
1926
|
+
catch (err) {
|
|
1927
|
+
if (err?.code === 'ENOENT') {
|
|
1928
|
+
throw new HardwareRunnerError('NOT_FOUND', 'CAS blob file missing');
|
|
1929
|
+
}
|
|
1930
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'CAS blob failed O_NOFOLLOW open');
|
|
1931
|
+
}
|
|
1932
|
+
try {
|
|
1933
|
+
const before = await handle.stat();
|
|
1934
|
+
if (!before.isFile()
|
|
1935
|
+
|| before.isSymbolicLink()
|
|
1936
|
+
|| before.nlink !== 1
|
|
1937
|
+
|| (typeof process.getuid === 'function' && before.uid !== process.getuid())
|
|
1938
|
+
|| (before.mode & 0o777) !== 0o400
|
|
1939
|
+
|| before.size !== expectedLength) {
|
|
1940
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'CAS blob failed O_NOFOLLOW/nlink/0o400 check');
|
|
1941
|
+
}
|
|
1942
|
+
res.writeHead(200, {
|
|
1943
|
+
'content-type': 'application/octet-stream',
|
|
1944
|
+
'content-length': String(before.size),
|
|
1945
|
+
'x-loopwright-blob-sha256': sha256,
|
|
1946
|
+
'x-loopwright-blob-length': String(before.size),
|
|
1947
|
+
...extraHeaders,
|
|
1948
|
+
});
|
|
1949
|
+
const buf = Buffer.allocUnsafe(Math.min(MAX_CAS_CHUNK_BYTES, Math.max(1, before.size)));
|
|
1950
|
+
let offset = 0;
|
|
1951
|
+
while (offset < before.size) {
|
|
1952
|
+
if (res.destroyed || res.writableEnded || serverAbort.signal.aborted)
|
|
1953
|
+
return;
|
|
1954
|
+
const { bytesRead } = await handle.read(buf, 0, Math.min(buf.byteLength, before.size - offset), offset);
|
|
1955
|
+
if (bytesRead <= 0)
|
|
1956
|
+
break;
|
|
1957
|
+
offset += bytesRead;
|
|
1958
|
+
const canContinue = res.write(buf.subarray(0, bytesRead));
|
|
1959
|
+
if (!canContinue) {
|
|
1960
|
+
const ok = await waitForDrainOrClose(res, serverAbort.signal);
|
|
1961
|
+
if (!ok)
|
|
1962
|
+
return;
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
if (res.destroyed || res.writableEnded)
|
|
1966
|
+
return;
|
|
1967
|
+
const after = await handle.stat();
|
|
1968
|
+
if (offset !== before.size
|
|
1969
|
+
|| after.ino !== before.ino
|
|
1970
|
+
|| after.dev !== before.dev
|
|
1971
|
+
|| after.size !== before.size
|
|
1972
|
+
|| after.nlink !== 1
|
|
1973
|
+
|| (after.mode & 0o777) !== 0o400) {
|
|
1974
|
+
res.destroy();
|
|
1975
|
+
return;
|
|
1976
|
+
}
|
|
1977
|
+
res.end();
|
|
1978
|
+
}
|
|
1979
|
+
finally {
|
|
1980
|
+
await handle.close();
|
|
1981
|
+
}
|
|
1982
|
+
};
|
|
1983
|
+
const queue = new RelayPullQueue({
|
|
1984
|
+
leaseTtlMs: config.leaseTtlMs,
|
|
1985
|
+
sweepIntervalMs: config.sweepIntervalMs,
|
|
1986
|
+
verdictTtlMs: config.verdictTtlMs,
|
|
1987
|
+
maxJobs: config.maxJobs,
|
|
1988
|
+
...(config.maxRetainedTerminalOps !== undefined ? { maxRetainedTerminalOps: config.maxRetainedTerminalOps } : {}),
|
|
1989
|
+
...(options.clock !== undefined ? { clock: options.clock } : {}),
|
|
1990
|
+
onTerminalVerdict: verdict => {
|
|
1991
|
+
if (verdict.status === 'expired') {
|
|
1992
|
+
void ensureReceiptDurable(verdict).catch(() => { });
|
|
1993
|
+
}
|
|
1994
|
+
},
|
|
1995
|
+
});
|
|
1996
|
+
let server = null;
|
|
1997
|
+
let scheme = 'http';
|
|
1998
|
+
const releaseCasLock = async (strict) => {
|
|
1999
|
+
const db = casLockDb;
|
|
2000
|
+
const inodeKey = casLockInodeKey;
|
|
2001
|
+
casLockDb = null;
|
|
2002
|
+
casLockInodeKey = null;
|
|
2003
|
+
let hasCloseErr = false;
|
|
2004
|
+
let closeErr;
|
|
2005
|
+
if (db !== null) {
|
|
2006
|
+
try {
|
|
2007
|
+
db.close();
|
|
2008
|
+
}
|
|
2009
|
+
catch (err) {
|
|
2010
|
+
hasCloseErr = true;
|
|
2011
|
+
closeErr = err;
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
if (inodeKey !== null) {
|
|
2015
|
+
ACTIVE_CAS_DIR_LOCKS.delete(inodeKey);
|
|
2016
|
+
}
|
|
2017
|
+
if (strict && hasCloseErr) {
|
|
2018
|
+
throw closeErr;
|
|
2019
|
+
}
|
|
2020
|
+
};
|
|
2021
|
+
try {
|
|
2022
|
+
// 0. Establish process-lifetime exclusive CAS ownership (filesystem-identity dev:ino registry +
|
|
2023
|
+
// OS kernel SQLite EXCLUSIVE lock) BEFORE any subdir creation, temp cleanup, recovery scan, or listen().
|
|
2024
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
2025
|
+
const myUid = typeof process.getuid === 'function' ? process.getuid() : null;
|
|
2026
|
+
const casDirStat = statSync(config.casDir);
|
|
2027
|
+
const dirInodeKey = `${casDirStat.dev}:${casDirStat.ino}`;
|
|
2028
|
+
if (ACTIVE_CAS_DIR_LOCKS.has(dirInodeKey)) {
|
|
2029
|
+
throw new HardwareRunnerError('QUEUE_STATE_INVALID', `CAS directory "${config.casDir}" is already locked by an active Relay instance`, '/casDir');
|
|
2030
|
+
}
|
|
2031
|
+
ACTIVE_CAS_DIR_LOCKS.add(dirInodeKey);
|
|
2032
|
+
casLockInodeKey = dirInodeKey;
|
|
2033
|
+
// Inspect .relay.lock via lstat ONLY (never open/close an existing SQLite lockfile fd, which can cancel
|
|
2034
|
+
// POSIX fcntl locks on the same inode!). Only create with O_CREAT|O_EXCL when ENOENT, before DatabaseSync opens.
|
|
2035
|
+
let lockFileCreated = false;
|
|
2036
|
+
let existingLockStat = null;
|
|
2037
|
+
try {
|
|
2038
|
+
existingLockStat = await lstat(casLockPath);
|
|
2039
|
+
}
|
|
2040
|
+
catch (statErr) {
|
|
2041
|
+
if (statErr?.code !== 'ENOENT') {
|
|
2042
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'failed to inspect CAS lock file', '/casDir', { cause: statErr });
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
if (existingLockStat === null) {
|
|
2046
|
+
try {
|
|
2047
|
+
const fh = await open(casLockPath, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR | noFollow, 0o600);
|
|
2048
|
+
await fh.close();
|
|
2049
|
+
lockFileCreated = true;
|
|
2050
|
+
}
|
|
2051
|
+
catch (createErr) {
|
|
2052
|
+
if (createErr?.code !== 'EEXIST') {
|
|
2053
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'failed to initialize CAS lock file', '/casDir', { cause: createErr });
|
|
2054
|
+
}
|
|
2055
|
+
existingLockStat = await lstat(casLockPath).catch(() => null);
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
if (existingLockStat !== null) {
|
|
2059
|
+
if (!existingLockStat.isFile() || existingLockStat.isSymbolicLink() || (myUid !== null && existingLockStat.uid !== myUid)) {
|
|
2060
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'CAS lock file violates regular-file ownership invariants', '/casDir');
|
|
2061
|
+
}
|
|
2062
|
+
if ((existingLockStat.mode & 0o077) !== 0) {
|
|
2063
|
+
await chmod(casLockPath, 0o600);
|
|
2064
|
+
const tightenedStat = await lstat(casLockPath);
|
|
2065
|
+
if (!tightenedStat.isFile() || tightenedStat.isSymbolicLink() || (tightenedStat.mode & 0o077) !== 0) {
|
|
2066
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'failed to tighten CAS lock file permissions', '/casDir');
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
if (lockFileCreated) {
|
|
2071
|
+
await syncDir(config.casDir);
|
|
2072
|
+
}
|
|
2073
|
+
let db;
|
|
2074
|
+
try {
|
|
2075
|
+
db = new DatabaseSync(casLockPath);
|
|
2076
|
+
}
|
|
2077
|
+
catch (openErr) {
|
|
2078
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'failed to open exclusive CAS lock database', '/casDir', { cause: openErr });
|
|
2079
|
+
}
|
|
2080
|
+
casLockDb = db;
|
|
2081
|
+
try {
|
|
2082
|
+
db.exec('PRAGMA busy_timeout = 0;');
|
|
2083
|
+
db.exec('PRAGMA journal_mode = DELETE;');
|
|
2084
|
+
db.exec('PRAGMA locking_mode = EXCLUSIVE;');
|
|
2085
|
+
db.exec('BEGIN EXCLUSIVE;');
|
|
2086
|
+
db.exec('CREATE TABLE IF NOT EXISTS relay_lock (id INTEGER PRIMARY KEY CHECK (id = 1), pid INTEGER NOT NULL, relay_boot_id TEXT NOT NULL, acquired_at_ms INTEGER NOT NULL);');
|
|
2087
|
+
db.exec('CREATE TABLE IF NOT EXISTS recovery_fence (operation_id TEXT PRIMARY KEY, reason TEXT NOT NULL, created_at_ms INTEGER NOT NULL);');
|
|
2088
|
+
db.prepare('INSERT OR REPLACE INTO relay_lock (id, pid, relay_boot_id, acquired_at_ms) VALUES (1, ?, ?, ?)').run(process.pid, queue.relayBootId, Date.now());
|
|
2089
|
+
db.exec('COMMIT;');
|
|
2090
|
+
}
|
|
2091
|
+
catch (lockErr) {
|
|
2092
|
+
const msg = lockErr instanceof Error ? lockErr.message : String(lockErr);
|
|
2093
|
+
if (msg.includes('locked') || msg.includes('BUSY')) {
|
|
2094
|
+
throw new HardwareRunnerError('QUEUE_STATE_INVALID', `CAS directory "${config.casDir}" is already locked by an active Relay instance`, '/casDir', { cause: lockErr });
|
|
2095
|
+
}
|
|
2096
|
+
throw new HardwareRunnerError('QUEUE_STATE_INVALID', `failed to acquire exclusive CAS directory lock: ${msg}`, '/casDir', { cause: lockErr });
|
|
2097
|
+
}
|
|
2098
|
+
await syncDir(config.casDir);
|
|
2099
|
+
await ensurePrivateDir(blobsDir);
|
|
2100
|
+
await ensurePrivateDir(sha256Dir);
|
|
2101
|
+
await ensurePrivateDir(tmpDir);
|
|
2102
|
+
await ensurePrivateDir(receiptsDir);
|
|
2103
|
+
await ensurePrivateDir(operationsDir);
|
|
2104
|
+
await syncDir(config.casDir);
|
|
2105
|
+
await syncDir(blobsDir);
|
|
2106
|
+
await cleanStaleTempFiles(tmpDir);
|
|
2107
|
+
await cleanStaleTempFiles(receiptsDir);
|
|
2108
|
+
await cleanStaleTempFiles(operationsDir);
|
|
2109
|
+
await syncDir(tmpDir);
|
|
2110
|
+
await syncDir(sha256Dir);
|
|
2111
|
+
await syncDir(operationsDir);
|
|
2112
|
+
await syncDir(receiptsDir);
|
|
2113
|
+
// 0b. Fail closed with QUEUE_STATE_INVALID if a prior Relay left a fenced operation without a valid authenticated receipt.
|
|
2114
|
+
const fencedRows = db.prepare('SELECT operation_id FROM recovery_fence').all();
|
|
2115
|
+
for (const row of fencedRows) {
|
|
2116
|
+
const fencedOpId = typeof row.operation_id === 'string' ? row.operation_id : '';
|
|
2117
|
+
if (fencedOpId.length === 0) {
|
|
2118
|
+
throw new HardwareRunnerError('QUEUE_STATE_INVALID', 'corrupt recovery fence entry in CAS lock database', '/casDir');
|
|
2119
|
+
}
|
|
2120
|
+
let receiptBytes;
|
|
2121
|
+
try {
|
|
2122
|
+
receiptBytes = await readRecordFileOrNull(join(receiptsDir, `${fencedOpId}.json`), MAX_RECEIPT_FILE_BYTES, 'startup');
|
|
2123
|
+
}
|
|
2124
|
+
catch (readErr) {
|
|
2125
|
+
throw new HardwareRunnerError('QUEUE_STATE_INVALID', `CAS recovery fence active for operation "${fencedOpId}" with unreadable receipt; operator recovery required`, '/casDir', { cause: readErr });
|
|
2126
|
+
}
|
|
2127
|
+
if (receiptBytes === null) {
|
|
2128
|
+
throw new HardwareRunnerError('QUEUE_STATE_INVALID', `CAS recovery fence active for unflushed terminal operation "${fencedOpId}"; operator recovery required`, '/casDir');
|
|
2129
|
+
}
|
|
2130
|
+
try {
|
|
2131
|
+
parseAuthenticatedReceiptBytes(receiptBytes, fencedOpId, config.controllerSigningSecret, config.maxBlobBytes, secretScrubber);
|
|
2132
|
+
}
|
|
2133
|
+
catch (parseErr) {
|
|
2134
|
+
throw new HardwareRunnerError('QUEUE_STATE_INVALID', `CAS recovery fence active for operation "${fencedOpId}" with invalid or unauthenticated receipt; operator recovery required`, '/casDir', { cause: parseErr });
|
|
2135
|
+
}
|
|
2136
|
+
clearRecoveryFence(fencedOpId);
|
|
2137
|
+
}
|
|
2138
|
+
// 1. Stream-validate existing sealed 0o400 CAS blobs at startup without materializing directory listings.
|
|
2139
|
+
const blobDirStream = await opendir(sha256Dir);
|
|
2140
|
+
try {
|
|
2141
|
+
for await (const dirent of blobDirStream) {
|
|
2142
|
+
const name = dirent.name;
|
|
2143
|
+
if (name.startsWith('.tmp-'))
|
|
2144
|
+
continue;
|
|
2145
|
+
if (!SHA256_HEX_RE.test(name)) {
|
|
2146
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'unexpected filename in CAS blobs/sha256 directory');
|
|
2147
|
+
}
|
|
2148
|
+
const fh = await open(join(sha256Dir, name), constants.O_RDONLY | noFollow).catch(() => {
|
|
2149
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'untrusted symlink or unreadable CAS blob at startup');
|
|
2150
|
+
});
|
|
2151
|
+
try {
|
|
2152
|
+
const st = await fh.stat();
|
|
2153
|
+
if (!st.isFile()
|
|
2154
|
+
|| st.isSymbolicLink()
|
|
2155
|
+
|| st.nlink !== 1
|
|
2156
|
+
|| (myUid !== null && st.uid !== myUid)
|
|
2157
|
+
|| (st.mode & 0o777) !== 0o400) {
|
|
2158
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'existing CAS blob violates 0o400/nlink invariants');
|
|
2159
|
+
}
|
|
2160
|
+
}
|
|
2161
|
+
finally {
|
|
2162
|
+
await fh.close();
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
finally {
|
|
2167
|
+
await blobDirStream.close().catch(() => { });
|
|
2168
|
+
}
|
|
2169
|
+
// 2. Stream-authenticate terminal receipts (<casDir>/receipts/*.json) with on-demand operation pairing,
|
|
2170
|
+
// keeping retained in-memory caches strictly bounded by maxRetainedTerminalOps.
|
|
2171
|
+
const receiptDirStream = await opendir(receiptsDir);
|
|
2172
|
+
try {
|
|
2173
|
+
for await (const dirent of receiptDirStream) {
|
|
2174
|
+
const fileName = dirent.name;
|
|
2175
|
+
if (fileName.startsWith('.tmp-'))
|
|
2176
|
+
continue;
|
|
2177
|
+
if (!fileName.endsWith('.json')) {
|
|
2178
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'unexpected file in CAS receipts directory');
|
|
2179
|
+
}
|
|
2180
|
+
const opId = parseOperationId(fileName.slice(0, -5), '/receipts');
|
|
2181
|
+
const rawBytes = await readRequiredStartupRecord(join(receiptsDir, fileName), MAX_RECEIPT_FILE_BYTES);
|
|
2182
|
+
const verdict = parseAuthenticatedReceiptBytes(rawBytes, opId, config.controllerSigningSecret, config.maxBlobBytes, secretScrubber);
|
|
2183
|
+
let matchedReq = null;
|
|
2184
|
+
const opBytes = await readRecordFileOrNull(join(operationsDir, `${opId}.json`), MAX_OPERATION_FILE_BYTES, 'startup');
|
|
2185
|
+
if (opBytes !== null) {
|
|
2186
|
+
matchedReq = parseAuthenticatedOperationBytes(opBytes, opId, config.controllerSigningSecret, config.maxBlobBytes);
|
|
2187
|
+
if (!verdictMatchesRequestBinding(verdict, matchedReq)) {
|
|
2188
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `recovered request does not match receipt for "${verdict.operationId}"`);
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
const entry = buildTerminalEntry(verdict, matchedReq, {
|
|
2192
|
+
linkedOnDisk: true,
|
|
2193
|
+
durableOnDisk: true,
|
|
2194
|
+
});
|
|
2195
|
+
putBoundedTerminalCache(entry);
|
|
2196
|
+
queue.restoreTerminalOperation({
|
|
2197
|
+
verdict,
|
|
2198
|
+
...(matchedReq !== null ? { request: matchedReq } : {}),
|
|
2199
|
+
});
|
|
2200
|
+
}
|
|
2201
|
+
}
|
|
2202
|
+
finally {
|
|
2203
|
+
await receiptDirStream.close().catch(() => { });
|
|
2204
|
+
}
|
|
2205
|
+
// 3. Stream-authenticate remaining non-terminal operation descriptors (<casDir>/operations/*.json)
|
|
2206
|
+
// without materializing directory listings or retaining per-operation staging maps at startup;
|
|
2207
|
+
// descriptor_only input blob authority is verified on demand at POST time.
|
|
2208
|
+
const opDirStream = await opendir(operationsDir);
|
|
2209
|
+
try {
|
|
2210
|
+
for await (const dirent of opDirStream) {
|
|
2211
|
+
const fileName = dirent.name;
|
|
2212
|
+
if (fileName.startsWith('.tmp-'))
|
|
2213
|
+
continue;
|
|
2214
|
+
if (!fileName.endsWith('.json')) {
|
|
2215
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'unexpected file in CAS operations directory');
|
|
2216
|
+
}
|
|
2217
|
+
const opId = parseOperationId(fileName.slice(0, -5), '/operations');
|
|
2218
|
+
let receiptExists = false;
|
|
2219
|
+
try {
|
|
2220
|
+
await lstat(join(receiptsDir, `${opId}.json`));
|
|
2221
|
+
receiptExists = true;
|
|
2222
|
+
}
|
|
2223
|
+
catch (err) {
|
|
2224
|
+
if (err?.code !== 'ENOENT') {
|
|
2225
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'failed to inspect persisted receipt state at startup');
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
if (receiptExists)
|
|
2229
|
+
continue;
|
|
2230
|
+
const rawBytes = await readRequiredStartupRecord(join(operationsDir, fileName), MAX_OPERATION_FILE_BYTES);
|
|
2231
|
+
parseAuthenticatedOperationBytes(rawBytes, opId, config.controllerSigningSecret, config.maxBlobBytes);
|
|
2232
|
+
}
|
|
2233
|
+
}
|
|
2234
|
+
finally {
|
|
2235
|
+
await opDirStream.close().catch(() => { });
|
|
2236
|
+
}
|
|
2237
|
+
const checkControllerBearerIfConfigured = (req) => {
|
|
2238
|
+
if (config.controllerAuthToken === undefined)
|
|
2239
|
+
return true;
|
|
2240
|
+
const token = extractBearerToken(req);
|
|
2241
|
+
if (token === null)
|
|
2242
|
+
return false;
|
|
2243
|
+
return timingSafeEqualStrings(token, config.controllerAuthToken);
|
|
2244
|
+
};
|
|
2245
|
+
const parseBlobLengthHeaders = (req, sha256) => {
|
|
2246
|
+
const headerSha = singleHeader(req, 'x-loopwright-blob-sha256');
|
|
2247
|
+
const headerLenRaw = singleHeader(req, 'x-loopwright-blob-length');
|
|
2248
|
+
if (headerSha !== sha256 || headerLenRaw === null || !/^(?:0|[1-9][0-9]{0,14})$/.test(headerLenRaw)) {
|
|
2249
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'missing or mismatched x-loopwright-blob-sha256 / x-loopwright-blob-length');
|
|
2250
|
+
}
|
|
2251
|
+
const expectedLength = Number(headerLenRaw);
|
|
2252
|
+
if (!Number.isSafeInteger(expectedLength) || expectedLength < 0) {
|
|
2253
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid x-loopwright-blob-length');
|
|
2254
|
+
}
|
|
2255
|
+
if (expectedLength > config.maxBlobBytes) {
|
|
2256
|
+
throw new HardwareRunnerError('PAYLOAD_TOO_LARGE', `blob length exceeds maxBlobBytes (${config.maxBlobBytes})`);
|
|
2257
|
+
}
|
|
2258
|
+
if ((expectedLength === 0) !== (sha256 === EMPTY_SHA256_HEX)) {
|
|
2259
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'empty blob sha256/byteLength mismatch');
|
|
2260
|
+
}
|
|
2261
|
+
const contentLengthRaw = singleHeader(req, 'content-length');
|
|
2262
|
+
if (contentLengthRaw !== null) {
|
|
2263
|
+
if (!/^(?:0|[1-9][0-9]{0,14})$/.test(contentLengthRaw) || Number(contentLengthRaw) !== expectedLength) {
|
|
2264
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'content-length does not match x-loopwright-blob-length');
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
return expectedLength;
|
|
2268
|
+
};
|
|
2269
|
+
const parseControllerWaitMs = (req, parsedUrl) => {
|
|
2270
|
+
for (const key of parsedUrl.searchParams.keys()) {
|
|
2271
|
+
if (key !== 'waitMs') {
|
|
2272
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'unsupported query parameter on benchmark jobs endpoint');
|
|
2273
|
+
}
|
|
2274
|
+
}
|
|
2275
|
+
const queryValues = parsedUrl.searchParams.getAll('waitMs');
|
|
2276
|
+
if (queryValues.length > 1) {
|
|
2277
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'duplicate waitMs query parameter');
|
|
2278
|
+
}
|
|
2279
|
+
const rawWaitHeader = req.headers['x-loopwright-wait-ms'];
|
|
2280
|
+
if (Array.isArray(rawWaitHeader)) {
|
|
2281
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'duplicate x-loopwright-wait-ms header');
|
|
2282
|
+
}
|
|
2283
|
+
for (const candidate of [queryValues[0], rawWaitHeader]) {
|
|
2284
|
+
if (candidate !== undefined && !/^(?:0|[1-9][0-9]{0,7})$/.test(candidate)) {
|
|
2285
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid waitMs parameter');
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
const selected = queryValues[0] ?? rawWaitHeader;
|
|
2289
|
+
if (selected === undefined)
|
|
2290
|
+
return 0;
|
|
2291
|
+
return Math.min(MAX_ACQUIRE_WAIT_MS, Number(selected));
|
|
2292
|
+
};
|
|
2293
|
+
const handleRequest = async (req, res) => {
|
|
2294
|
+
const method = req.method ?? 'GET';
|
|
2295
|
+
const rawUrl = req.url ?? '/';
|
|
2296
|
+
let parsedUrl;
|
|
2297
|
+
try {
|
|
2298
|
+
parsedUrl = new URL(rawUrl, 'http://localhost');
|
|
2299
|
+
}
|
|
2300
|
+
catch {
|
|
2301
|
+
sendError(res, secretScrubber, 400, 'ARTIFACT_INVALID', 'malformed request URL');
|
|
2302
|
+
return;
|
|
2303
|
+
}
|
|
2304
|
+
const pathname = parsedUrl.pathname;
|
|
2305
|
+
// -----------------------------------------------------------------------
|
|
2306
|
+
// A.1 POST /v1/benchmark/jobs
|
|
2307
|
+
// -----------------------------------------------------------------------
|
|
2308
|
+
if (pathname === '/v1/benchmark/jobs') {
|
|
2309
|
+
if (method !== 'POST') {
|
|
2310
|
+
sendError(res, secretScrubber, 405, 'NOT_FOUND', 'method not allowed');
|
|
2311
|
+
return;
|
|
2312
|
+
}
|
|
2313
|
+
const rawBody = await readBoundedRequestBody(req, MAX_CONTROL_BODY_BYTES);
|
|
2314
|
+
const sigHeader = singleHeader(req, 'x-loopwright-signature') ?? '';
|
|
2315
|
+
const bearerOk = checkControllerBearerIfConfigured(req);
|
|
2316
|
+
const sigOk = verifyRelaySignature(config.controllerSigningSecret, rawBody, sigHeader);
|
|
2317
|
+
if (!bearerOk || !sigOk) {
|
|
2318
|
+
sendError(res, secretScrubber, 401, 'AUTH_UNAUTHORIZED', 'invalid controller signature or bearer token');
|
|
2319
|
+
return;
|
|
2320
|
+
}
|
|
2321
|
+
// Validate polling parameters BEFORE parsing/admitting the job so invalid requests leave queue untouched.
|
|
2322
|
+
const waitMs = parseControllerWaitMs(req, parsedUrl);
|
|
2323
|
+
const jsonBody = parseStrictJsonBytes(rawBody, MAX_CONTROL_BODY_BYTES, 'ARTIFACT_INVALID', '/');
|
|
2324
|
+
const benchmarkReq = parseBenchmarkRequest(jsonBody, config.maxBlobBytes);
|
|
2325
|
+
let verdict = await withAdmissionLock(async () => {
|
|
2326
|
+
const reqCanonical = canonicalJson(benchmarkReq);
|
|
2327
|
+
const existingLookup = queue.lookupExistingOperation(benchmarkReq);
|
|
2328
|
+
if (existingLookup.found) {
|
|
2329
|
+
return existingLookup.verdict;
|
|
2330
|
+
}
|
|
2331
|
+
const resolved = await resolveDiskOperationState(benchmarkReq.operationId);
|
|
2332
|
+
if (resolved.kind === 'terminal') {
|
|
2333
|
+
const term = resolved.entry;
|
|
2334
|
+
if (term.request === null || term.requestCanonical === null) {
|
|
2335
|
+
throw new HardwareRunnerError('QUEUE_JOB_CONFLICT', `operation "${benchmarkReq.operationId}" has a terminal receipt without an authenticated operation descriptor`);
|
|
2336
|
+
}
|
|
2337
|
+
if (term.request.dispatchId !== benchmarkReq.dispatchId
|
|
2338
|
+
|| term.request.requestDigest !== benchmarkReq.requestDigest
|
|
2339
|
+
|| term.requestCanonical !== reqCanonical) {
|
|
2340
|
+
throw new HardwareRunnerError('QUEUE_JOB_CONFLICT', `conflicting benchmark_request for settled operationId "${benchmarkReq.operationId}"`);
|
|
2341
|
+
}
|
|
2342
|
+
return term.verdict;
|
|
2343
|
+
}
|
|
2344
|
+
if (resolved.kind === 'descriptor_only') {
|
|
2345
|
+
if (resolved.request.dispatchId !== benchmarkReq.dispatchId
|
|
2346
|
+
|| resolved.request.requestDigest !== benchmarkReq.requestDigest
|
|
2347
|
+
|| resolved.requestCanonical !== reqCanonical) {
|
|
2348
|
+
throw new HardwareRunnerError('QUEUE_JOB_CONFLICT', `conflicting benchmark_request for persisted operationId "${benchmarkReq.operationId}"`);
|
|
2349
|
+
}
|
|
2350
|
+
}
|
|
2351
|
+
const stagedForOp = stagedInputBlobsByOperation.get(benchmarkReq.operationId);
|
|
2352
|
+
const frozenMap = new Map();
|
|
2353
|
+
for (const entry of collectDeclaredInputBlobs(benchmarkReq.candidateArtifacts)) {
|
|
2354
|
+
if (resolved.kind === 'absent') {
|
|
2355
|
+
const stagedLen = stagedForOp?.get(entry.digest.hex);
|
|
2356
|
+
if (stagedLen === undefined) {
|
|
2357
|
+
throw new HardwareRunnerError('ARTIFACT_MISSING', `declared candidate input blob ${entry.digest.hex} has not been staged for operation`);
|
|
2358
|
+
}
|
|
2359
|
+
if (stagedLen !== entry.byteLength) {
|
|
2360
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'staged candidate blob byteLength mismatch');
|
|
2361
|
+
}
|
|
2362
|
+
}
|
|
2363
|
+
await verifyExistingCasBlob(entry.digest.hex, entry.byteLength, { missingCode: 'ARTIFACT_MISSING' });
|
|
2364
|
+
frozenMap.set(entry.digest.hex, entry.byteLength);
|
|
2365
|
+
}
|
|
2366
|
+
const effectiveActiveCap = Math.min(config.maxJobs, maxRetainedTerminalOps);
|
|
2367
|
+
if (activeOperations.size + undurableTerminalByOperation.size >= effectiveActiveCap) {
|
|
2368
|
+
throw new HardwareRunnerError('QUEUE_CAPACITY_EXCEEDED', 'Relay queue capacity exceeded by active or pending-durability operations');
|
|
2369
|
+
}
|
|
2370
|
+
queue.assertCanAdmitNewJob();
|
|
2371
|
+
if (resolved.kind === 'absent') {
|
|
2372
|
+
if (options.onBeforeOperationPersist !== undefined) {
|
|
2373
|
+
await options.onBeforeOperationPersist(benchmarkReq.operationId);
|
|
2374
|
+
}
|
|
2375
|
+
await persistOperationRequestRecord(benchmarkReq);
|
|
2376
|
+
}
|
|
2377
|
+
// Re-verify shutdown and queue admission synchronously after the final await so a concurrent
|
|
2378
|
+
// clean close() during descriptor I/O can never leave a fence for a rejected job!
|
|
2379
|
+
if (serverAbort.signal.aborted) {
|
|
2380
|
+
throw new HardwareRunnerError('QUEUE_STATE_INVALID', 'Relay server is shutting down');
|
|
2381
|
+
}
|
|
2382
|
+
queue.assertCanAdmitNewJob();
|
|
2383
|
+
// Persist the recovery obligation BEFORE allowing the job to run so even simultaneous
|
|
2384
|
+
// receipt + lock-DB storage failures at expiry/shutdown can never lose the fence!
|
|
2385
|
+
recordRecoveryFenceStrict(benchmarkReq.operationId, 'operation_admitted');
|
|
2386
|
+
let sub;
|
|
2387
|
+
try {
|
|
2388
|
+
sub = queue.submitJob(benchmarkReq);
|
|
2389
|
+
}
|
|
2390
|
+
catch (submitErr) {
|
|
2391
|
+
clearRecoveryFence(benchmarkReq.operationId);
|
|
2392
|
+
throw submitErr;
|
|
2393
|
+
}
|
|
2394
|
+
activeOperations.set(benchmarkReq.operationId, {
|
|
2395
|
+
request: benchmarkReq,
|
|
2396
|
+
requestCanonical: reqCanonical,
|
|
2397
|
+
frozenInputs: frozenMap,
|
|
2398
|
+
});
|
|
2399
|
+
stagedInputBlobsByOperation.delete(benchmarkReq.operationId);
|
|
2400
|
+
return sub.verdict;
|
|
2401
|
+
});
|
|
2402
|
+
if (waitMs > 0 && verdict.status === 'pending' && !res.destroyed && !res.writableEnded) {
|
|
2403
|
+
const disconnectController = new AbortController();
|
|
2404
|
+
const onClose = () => disconnectController.abort();
|
|
2405
|
+
res.once('close', onClose);
|
|
2406
|
+
try {
|
|
2407
|
+
verdict = await queue.waitForVerdict(benchmarkReq.operationId, waitMs, AbortSignal.any([serverAbort.signal, disconnectController.signal]));
|
|
2408
|
+
}
|
|
2409
|
+
finally {
|
|
2410
|
+
res.removeListener('close', onClose);
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2413
|
+
if (res.destroyed || res.writableEnded)
|
|
2414
|
+
return;
|
|
2415
|
+
if (verdict.status !== 'pending') {
|
|
2416
|
+
await ensureReceiptDurable(verdict);
|
|
2417
|
+
}
|
|
2418
|
+
const verdictCanonical = assertVerdictPublishable(verdict);
|
|
2419
|
+
const responseBytes = Buffer.from(verdictCanonical, 'utf8');
|
|
2420
|
+
const responseSig = signRelayPayload(config.controllerSigningSecret, responseBytes);
|
|
2421
|
+
res.writeHead(200, {
|
|
2422
|
+
'content-type': 'application/json; charset=utf-8',
|
|
2423
|
+
'content-length': String(responseBytes.byteLength),
|
|
2424
|
+
'x-loopwright-signature': responseSig,
|
|
2425
|
+
});
|
|
2426
|
+
res.end(responseBytes);
|
|
2427
|
+
return;
|
|
2428
|
+
}
|
|
2429
|
+
// -----------------------------------------------------------------------
|
|
2430
|
+
// A.2 & A.3 PUT / GET /v1/benchmark/jobs/:operationId/blobs/:sha256
|
|
2431
|
+
// -----------------------------------------------------------------------
|
|
2432
|
+
const controllerBlobMatch = /^\/v1\/benchmark\/jobs\/([^/]+)\/blobs\/([^/]+)$/.exec(pathname);
|
|
2433
|
+
if (controllerBlobMatch !== null) {
|
|
2434
|
+
const operationId = parseOperationId(decodeSegment(controllerBlobMatch[1]), '/operationId');
|
|
2435
|
+
const sha256 = parseSha256Hex(decodeSegment(controllerBlobMatch[2]), '/sha256');
|
|
2436
|
+
const sigHeader = singleHeader(req, 'x-loopwright-signature') ?? '';
|
|
2437
|
+
const bearerOk = checkControllerBearerIfConfigured(req);
|
|
2438
|
+
if (method === 'PUT') {
|
|
2439
|
+
const expectedLength = parseBlobLengthHeaders(req, sha256);
|
|
2440
|
+
const canonicalSigningInput = `PUT\n${operationId}\n${sha256}\n${expectedLength}`;
|
|
2441
|
+
const sigOk = verifyRelaySignature(config.controllerSigningSecret, canonicalSigningInput, sigHeader);
|
|
2442
|
+
if (!bearerOk || !sigOk) {
|
|
2443
|
+
req.resume();
|
|
2444
|
+
sendError(res, secretScrubber, 401, 'AUTH_UNAUTHORIZED', 'invalid controller blob PUT signature or bearer token');
|
|
2445
|
+
return;
|
|
2446
|
+
}
|
|
2447
|
+
const assertCanStageInputBlob = async () => {
|
|
2448
|
+
const activeOp = activeOperations.get(operationId);
|
|
2449
|
+
if (activeOp !== undefined) {
|
|
2450
|
+
if (activeOp.frozenInputs.get(sha256) !== expectedLength) {
|
|
2451
|
+
throw new HardwareRunnerError('QUEUE_JOB_CONFLICT', 'cannot stage undeclared input blob after job submission');
|
|
2452
|
+
}
|
|
2453
|
+
return 'already_bound';
|
|
2454
|
+
}
|
|
2455
|
+
const resolved = await resolveDiskOperationState(operationId);
|
|
2456
|
+
if (resolved.kind === 'terminal') {
|
|
2457
|
+
if (resolved.entry.frozenInputs === null) {
|
|
2458
|
+
throw new HardwareRunnerError('QUEUE_JOB_CONFLICT', `operation "${operationId}" has a terminal receipt without an authenticated operation descriptor`);
|
|
2459
|
+
}
|
|
2460
|
+
if (resolved.entry.frozenInputs.get(sha256) !== expectedLength) {
|
|
2461
|
+
throw new HardwareRunnerError('QUEUE_JOB_CONFLICT', 'cannot stage undeclared input blob on settled operation');
|
|
2462
|
+
}
|
|
2463
|
+
return 'already_bound';
|
|
2464
|
+
}
|
|
2465
|
+
if (resolved.kind === 'descriptor_only') {
|
|
2466
|
+
const matchesDeclared = collectDeclaredInputBlobs(resolved.request.candidateArtifacts).some(e => e.digest.hex === sha256 && e.byteLength === expectedLength);
|
|
2467
|
+
if (!matchesDeclared) {
|
|
2468
|
+
throw new HardwareRunnerError('QUEUE_JOB_CONFLICT', 'cannot stage undeclared input blob on persisted operation descriptor');
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
return 'pre_submit';
|
|
2472
|
+
};
|
|
2473
|
+
await withAdmissionLock(() => assertCanStageInputBlob());
|
|
2474
|
+
const ingested = await ingestStreamedCasBlob(req, sha256, expectedLength, { scrubSecrets: false });
|
|
2475
|
+
await withAdmissionLock(async () => {
|
|
2476
|
+
const mode = await assertCanStageInputBlob();
|
|
2477
|
+
if (mode === 'pre_submit') {
|
|
2478
|
+
let opMap = stagedInputBlobsByOperation.get(operationId);
|
|
2479
|
+
if (!opMap) {
|
|
2480
|
+
opMap = new Map();
|
|
2481
|
+
stagedInputBlobsByOperation.set(operationId, opMap);
|
|
2482
|
+
}
|
|
2483
|
+
opMap.set(sha256, expectedLength);
|
|
2484
|
+
}
|
|
2485
|
+
});
|
|
2486
|
+
sendJson(res, ingested.created ? 201 : 200, { ok: true, sha256, byteLength: expectedLength });
|
|
2487
|
+
return;
|
|
2488
|
+
}
|
|
2489
|
+
if (method === 'GET') {
|
|
2490
|
+
const canonicalSigningInput = `GET\n${operationId}\n${sha256}`;
|
|
2491
|
+
const sigOk = verifyRelaySignature(config.controllerSigningSecret, canonicalSigningInput, sigHeader);
|
|
2492
|
+
if (!bearerOk || !sigOk) {
|
|
2493
|
+
sendError(res, secretScrubber, 401, 'AUTH_UNAUTHORIZED', 'invalid controller blob GET signature or bearer token');
|
|
2494
|
+
return;
|
|
2495
|
+
}
|
|
2496
|
+
const snap = queue.getJobByOperationId(operationId);
|
|
2497
|
+
if (snap && snap.verdict.status !== 'pending') {
|
|
2498
|
+
await ensureReceiptDurable(snap.verdict);
|
|
2499
|
+
}
|
|
2500
|
+
const resolved = await resolveDiskOperationState(operationId);
|
|
2501
|
+
if (resolved.kind === 'terminal' && !resolved.entry.durableOnDisk) {
|
|
2502
|
+
await ensureReceiptDurable(resolved.entry.verdict);
|
|
2503
|
+
}
|
|
2504
|
+
const committedLen = resolved.kind === 'terminal' ? resolved.entry.committedOutputs.get(sha256) : undefined;
|
|
2505
|
+
if (committedLen === undefined) {
|
|
2506
|
+
if (await hasCasBlobOnDisk(sha256)) {
|
|
2507
|
+
sendError(res, secretScrubber, 403, 'AUTH_FORBIDDEN', 'blob is not an authorized output of this operation');
|
|
2508
|
+
}
|
|
2509
|
+
else {
|
|
2510
|
+
sendError(res, secretScrubber, 404, 'NOT_FOUND', 'output blob not found');
|
|
2511
|
+
}
|
|
2512
|
+
return;
|
|
2513
|
+
}
|
|
2514
|
+
const blobSig = signRelayPayload(config.controllerSigningSecret, `BLOB\n${operationId}\n${sha256}\n${committedLen}`);
|
|
2515
|
+
await streamCasBlobResponse(res, sha256, committedLen, {
|
|
2516
|
+
'x-loopwright-signature': blobSig,
|
|
2517
|
+
});
|
|
2518
|
+
return;
|
|
2519
|
+
}
|
|
2520
|
+
sendError(res, secretScrubber, 405, 'NOT_FOUND', 'method not allowed');
|
|
2521
|
+
return;
|
|
2522
|
+
}
|
|
2523
|
+
// -----------------------------------------------------------------------
|
|
2524
|
+
// B. Worker routes (/v1/runner/leases*)
|
|
2525
|
+
// -----------------------------------------------------------------------
|
|
2526
|
+
if (pathname === '/v1/runner/leases:acquire' || pathname.startsWith('/v1/runner/leases/')) {
|
|
2527
|
+
if (!verifyBearerAgainstList(req, config.workerTokens)) {
|
|
2528
|
+
req.resume();
|
|
2529
|
+
sendError(res, secretScrubber, 401, 'AUTH_UNAUTHORIZED', 'invalid or missing worker bearer token');
|
|
2530
|
+
return;
|
|
2531
|
+
}
|
|
2532
|
+
// B.1 POST /v1/runner/leases:acquire
|
|
2533
|
+
if (pathname === '/v1/runner/leases:acquire') {
|
|
2534
|
+
if (method !== 'POST') {
|
|
2535
|
+
sendError(res, secretScrubber, 405, 'NOT_FOUND', 'method not allowed');
|
|
2536
|
+
return;
|
|
2537
|
+
}
|
|
2538
|
+
const rawBody = await readBoundedRequestBody(req, MAX_CONTROL_BODY_BYTES);
|
|
2539
|
+
const jsonBody = parseStrictJsonBytes(rawBody, MAX_CONTROL_BODY_BYTES, 'ARTIFACT_INVALID', '/');
|
|
2540
|
+
const acquireInput = parseAcquireInput(jsonBody);
|
|
2541
|
+
const disconnectController = new AbortController();
|
|
2542
|
+
const onClose = () => disconnectController.abort();
|
|
2543
|
+
res.once('close', onClose);
|
|
2544
|
+
let grant;
|
|
2545
|
+
try {
|
|
2546
|
+
grant = await queue.acquireLease(acquireInput, AbortSignal.any([serverAbort.signal, disconnectController.signal]));
|
|
2547
|
+
}
|
|
2548
|
+
finally {
|
|
2549
|
+
res.removeListener('close', onClose);
|
|
2550
|
+
}
|
|
2551
|
+
if (res.destroyed || res.writableEnded)
|
|
2552
|
+
return;
|
|
2553
|
+
if (grant === null) {
|
|
2554
|
+
res.writeHead(204);
|
|
2555
|
+
res.end();
|
|
2556
|
+
return;
|
|
2557
|
+
}
|
|
2558
|
+
sendJson(res, 200, grant);
|
|
2559
|
+
return;
|
|
2560
|
+
}
|
|
2561
|
+
// B.2 POST /v1/runner/leases/:jobId:heartbeat
|
|
2562
|
+
// B.4 POST /v1/runner/leases/:jobId:preempt
|
|
2563
|
+
// B.7 POST /v1/runner/leases/:jobId:complete
|
|
2564
|
+
const actionMatch = /^\/v1\/runner\/leases\/([^/:]+):(heartbeat|preempt|complete)$/.exec(pathname);
|
|
2565
|
+
if (actionMatch !== null) {
|
|
2566
|
+
if (method !== 'POST') {
|
|
2567
|
+
sendError(res, secretScrubber, 405, 'NOT_FOUND', 'method not allowed');
|
|
2568
|
+
return;
|
|
2569
|
+
}
|
|
2570
|
+
const jobId = parseSafeId(decodeSegment(actionMatch[1]), '/jobId');
|
|
2571
|
+
const action = actionMatch[2];
|
|
2572
|
+
const rawBody = await readBoundedRequestBody(req, MAX_CONTROL_BODY_BYTES);
|
|
2573
|
+
const jsonBody = parseStrictJsonBytes(rawBody, MAX_CONTROL_BODY_BYTES, 'ARTIFACT_INVALID', '/');
|
|
2574
|
+
if (action === 'heartbeat') {
|
|
2575
|
+
const hbInput = parseHeartbeatInput(jsonBody);
|
|
2576
|
+
const hbRes = queue.heartbeatLease(jobId, hbInput);
|
|
2577
|
+
sendJson(res, 200, hbRes);
|
|
2578
|
+
return;
|
|
2579
|
+
}
|
|
2580
|
+
if (action === 'preempt') {
|
|
2581
|
+
const preemptInput = parsePreemptInput(jsonBody);
|
|
2582
|
+
const preemptRes = queue.preemptLease(jobId, preemptInput);
|
|
2583
|
+
const snap = queue.getJob(jobId);
|
|
2584
|
+
if (snap && snap.verdict.status !== 'pending') {
|
|
2585
|
+
await ensureReceiptDurable(snap.verdict);
|
|
2586
|
+
}
|
|
2587
|
+
sendJson(res, 200, preemptRes);
|
|
2588
|
+
return;
|
|
2589
|
+
}
|
|
2590
|
+
if (action === 'complete') {
|
|
2591
|
+
const completeInput = parseCompleteInput(jsonBody, config.maxBlobBytes);
|
|
2592
|
+
await withSerialLock(jobCompletionChains, jobId, async () => {
|
|
2593
|
+
const prepared = queue.prepareCompleteLease(jobId, completeInput);
|
|
2594
|
+
let stagedReceipt = null;
|
|
2595
|
+
let linkedReceipt = false;
|
|
2596
|
+
let committedEntry = null;
|
|
2597
|
+
let dirSyncPromise = null;
|
|
2598
|
+
let resolveDirSync;
|
|
2599
|
+
let rejectDirSync;
|
|
2600
|
+
let writeKey = '';
|
|
2601
|
+
try {
|
|
2602
|
+
assertVerdictPublishable(prepared.verdict);
|
|
2603
|
+
for (const art of prepared.outputArtifacts) {
|
|
2604
|
+
queue.verifyActiveLease(jobId, completeInput);
|
|
2605
|
+
await verifyExistingCasBlob(art.digest.hex, art.byteLength, { scrubSecrets: true });
|
|
2606
|
+
}
|
|
2607
|
+
queue.verifyActiveLease(jobId, completeInput);
|
|
2608
|
+
const preExistingReceipt = await readRecordFileOrNull(join(receiptsDir, `${prepared.operationId}.json`), MAX_RECEIPT_FILE_BYTES, 'runtime');
|
|
2609
|
+
if (preExistingReceipt !== null) {
|
|
2610
|
+
throw new Error('durable receipt already exists before lease completion commit');
|
|
2611
|
+
}
|
|
2612
|
+
if (options.onBeforeReceiptPersist !== undefined) {
|
|
2613
|
+
await options.onBeforeReceiptPersist(prepared.operationId);
|
|
2614
|
+
}
|
|
2615
|
+
stagedReceipt = await stageSignedVerdictReceiptTemp(prepared.verdict);
|
|
2616
|
+
// Atomic synchronous publication boundary: validate live lease authority, link receipt without
|
|
2617
|
+
// overwriting any existing file, bind output authorization, and register durability state ONLY
|
|
2618
|
+
// after the completion wins in the queue.
|
|
2619
|
+
prepared.commit(() => {
|
|
2620
|
+
linkSync(stagedReceipt.tmpReceiptPath, stagedReceipt.finalReceiptPath);
|
|
2621
|
+
linkedReceipt = true;
|
|
2622
|
+
try {
|
|
2623
|
+
unlinkSync(stagedReceipt.tmpReceiptPath);
|
|
2624
|
+
}
|
|
2625
|
+
catch {
|
|
2626
|
+
// Best-effort cleanup of temp link after finalReceiptPath is linked.
|
|
2627
|
+
}
|
|
2628
|
+
dirSyncPromise = new Promise((resSync, rejSync) => {
|
|
2629
|
+
resolveDirSync = resSync;
|
|
2630
|
+
rejectDirSync = rejSync;
|
|
2631
|
+
});
|
|
2632
|
+
// Prevent unhandled rejection when no controller poll is concurrently awaiting dirSyncPromise.
|
|
2633
|
+
void dirSyncPromise.catch(() => { });
|
|
2634
|
+
committedEntry = recordCommittedTerminalTransition(prepared.verdict, {
|
|
2635
|
+
linkedOnDisk: true,
|
|
2636
|
+
durableOnDisk: false,
|
|
2637
|
+
});
|
|
2638
|
+
writeKey = `${prepared.operationId}\0${committedEntry.verdictCanonical}`;
|
|
2639
|
+
inFlightReceiptWrites.set(writeKey, dirSyncPromise);
|
|
2640
|
+
inFlightByOperation.set(prepared.operationId, dirSyncPromise);
|
|
2641
|
+
activeDurabilityTasks.add(dirSyncPromise);
|
|
2642
|
+
});
|
|
2643
|
+
try {
|
|
2644
|
+
await syncDir(receiptsDir);
|
|
2645
|
+
committedEntry.durableOnDisk = true;
|
|
2646
|
+
undurableTerminalByOperation.delete(prepared.operationId);
|
|
2647
|
+
clearRecoveryFence(prepared.operationId);
|
|
2648
|
+
putBoundedTerminalCache(committedEntry);
|
|
2649
|
+
resolveDirSync();
|
|
2650
|
+
}
|
|
2651
|
+
catch (syncErr) {
|
|
2652
|
+
// Receipt file was already linked into place; keep job committed (uncertain durability)
|
|
2653
|
+
// rather than rolling back a published receipt, and withhold 200 until dir-sync succeeds.
|
|
2654
|
+
rejectDirSync(syncErr);
|
|
2655
|
+
throw syncErr;
|
|
2656
|
+
}
|
|
2657
|
+
finally {
|
|
2658
|
+
if (dirSyncPromise !== null) {
|
|
2659
|
+
if (inFlightReceiptWrites.get(writeKey) === dirSyncPromise) {
|
|
2660
|
+
inFlightReceiptWrites.delete(writeKey);
|
|
2661
|
+
}
|
|
2662
|
+
if (inFlightByOperation.get(prepared.operationId) === dirSyncPromise) {
|
|
2663
|
+
inFlightByOperation.delete(prepared.operationId);
|
|
2664
|
+
}
|
|
2665
|
+
activeDurabilityTasks.delete(dirSyncPromise);
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
}
|
|
2669
|
+
catch (err) {
|
|
2670
|
+
if (!linkedReceipt) {
|
|
2671
|
+
prepared.abort();
|
|
2672
|
+
if (stagedReceipt !== null) {
|
|
2673
|
+
await unlink(stagedReceipt.tmpReceiptPath).catch(() => { });
|
|
2674
|
+
}
|
|
2675
|
+
const winningDurabilityTask = inFlightByOperation.get(prepared.operationId);
|
|
2676
|
+
if (winningDurabilityTask !== undefined) {
|
|
2677
|
+
await winningDurabilityTask.catch(() => { });
|
|
2678
|
+
}
|
|
2679
|
+
}
|
|
2680
|
+
throw err;
|
|
2681
|
+
}
|
|
2682
|
+
sendJson(res, 200, {
|
|
2683
|
+
ok: true,
|
|
2684
|
+
operationId: prepared.operationId,
|
|
2685
|
+
status: completeInput.status,
|
|
2686
|
+
});
|
|
2687
|
+
});
|
|
2688
|
+
return;
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
// B.3 GET /v1/runner/leases/:jobId/events (SSE cancel watch — headers only, never query tokens!)
|
|
2692
|
+
const eventsMatch = /^\/v1\/runner\/leases\/([^/]+)\/events$/.exec(pathname);
|
|
2693
|
+
if (eventsMatch !== null) {
|
|
2694
|
+
if (method !== 'GET') {
|
|
2695
|
+
sendError(res, secretScrubber, 405, 'NOT_FOUND', 'method not allowed');
|
|
2696
|
+
return;
|
|
2697
|
+
}
|
|
2698
|
+
if (parsedUrl.search !== '') {
|
|
2699
|
+
sendError(res, secretScrubber, 400, 'ARTIFACT_INVALID', 'lease credentials must be passed via headers, not URL query parameters');
|
|
2700
|
+
return;
|
|
2701
|
+
}
|
|
2702
|
+
const jobId = parseSafeId(decodeSegment(eventsMatch[1]), '/jobId');
|
|
2703
|
+
const creds = parseLeaseHeaders(req);
|
|
2704
|
+
queue.verifyActiveLease(jobId, creds);
|
|
2705
|
+
res.writeHead(200, {
|
|
2706
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
2707
|
+
'cache-control': 'no-cache, no-transform',
|
|
2708
|
+
connection: 'keep-alive',
|
|
2709
|
+
});
|
|
2710
|
+
res.write('event: state\ndata: {"desiredState":"running"}\n\n');
|
|
2711
|
+
let closed = false;
|
|
2712
|
+
const unsubscribe = queue.subscribeLeaseCancel(jobId, creds, reason => {
|
|
2713
|
+
if (closed)
|
|
2714
|
+
return;
|
|
2715
|
+
closed = true;
|
|
2716
|
+
if (reason === 'cancel' && !res.destroyed && !res.writableEnded) {
|
|
2717
|
+
res.write('event: cancel\ndata: {"desiredState":"cancel"}\n\n');
|
|
2718
|
+
}
|
|
2719
|
+
if (!res.destroyed && !res.writableEnded) {
|
|
2720
|
+
res.end();
|
|
2721
|
+
}
|
|
2722
|
+
});
|
|
2723
|
+
res.once('close', () => {
|
|
2724
|
+
closed = true;
|
|
2725
|
+
unsubscribe();
|
|
2726
|
+
});
|
|
2727
|
+
return;
|
|
2728
|
+
}
|
|
2729
|
+
// B.5 & B.6 GET / PUT /v1/runner/leases/:jobId/blobs/:sha256
|
|
2730
|
+
const workerBlobMatch = /^\/v1\/runner\/leases\/([^/]+)\/blobs\/([^/]+)$/.exec(pathname);
|
|
2731
|
+
if (workerBlobMatch !== null) {
|
|
2732
|
+
if (parsedUrl.search !== '') {
|
|
2733
|
+
req.resume();
|
|
2734
|
+
sendError(res, secretScrubber, 400, 'ARTIFACT_INVALID', 'lease credentials must not be passed in URL query parameters');
|
|
2735
|
+
return;
|
|
2736
|
+
}
|
|
2737
|
+
const jobId = parseSafeId(decodeSegment(workerBlobMatch[1]), '/jobId');
|
|
2738
|
+
const sha256 = parseSha256Hex(decodeSegment(workerBlobMatch[2]), '/sha256');
|
|
2739
|
+
const creds = parseLeaseHeaders(req);
|
|
2740
|
+
if (method === 'GET') {
|
|
2741
|
+
const active = queue.verifyActiveLease(jobId, creds);
|
|
2742
|
+
const frozenMap = activeOperations.get(active.operationId)?.frozenInputs;
|
|
2743
|
+
const expectedLen = frozenMap?.get(sha256);
|
|
2744
|
+
if (expectedLen === undefined) {
|
|
2745
|
+
if (await hasCasBlobOnDisk(sha256)) {
|
|
2746
|
+
sendError(res, secretScrubber, 403, 'AUTH_FORBIDDEN', 'blob is not an authorized input of this job');
|
|
2747
|
+
}
|
|
2748
|
+
else {
|
|
2749
|
+
sendError(res, secretScrubber, 404, 'NOT_FOUND', 'input blob not found');
|
|
2750
|
+
}
|
|
2751
|
+
return;
|
|
2752
|
+
}
|
|
2753
|
+
await streamCasBlobResponse(res, sha256, expectedLen, {});
|
|
2754
|
+
return;
|
|
2755
|
+
}
|
|
2756
|
+
if (method === 'PUT') {
|
|
2757
|
+
// Pre-flight active lease check, then stage/hash/scrub/seal/link/sync unbound CAS bytes first,
|
|
2758
|
+
// and finally execute the lease check + committed-output binding as ONE synchronous queue operation.
|
|
2759
|
+
queue.verifyActiveLease(jobId, creds);
|
|
2760
|
+
const expectedLen = parseBlobLengthHeaders(req, sha256);
|
|
2761
|
+
const ingested = await ingestStreamedCasBlob(req, sha256, expectedLen, {
|
|
2762
|
+
scrubSecrets: true,
|
|
2763
|
+
});
|
|
2764
|
+
queue.recordCommittedOutputBlob(jobId, creds, {
|
|
2765
|
+
sha256,
|
|
2766
|
+
byteLength: expectedLen,
|
|
2767
|
+
});
|
|
2768
|
+
sendJson(res, ingested.created ? 201 : 200, { ok: true, sha256, byteLength: expectedLen });
|
|
2769
|
+
return;
|
|
2770
|
+
}
|
|
2771
|
+
sendError(res, secretScrubber, 405, 'NOT_FOUND', 'method not allowed');
|
|
2772
|
+
return;
|
|
2773
|
+
}
|
|
2774
|
+
}
|
|
2775
|
+
req.resume();
|
|
2776
|
+
sendError(res, secretScrubber, 404, 'NOT_FOUND', 'route not found');
|
|
2777
|
+
};
|
|
2778
|
+
const requestListener = (req, res) => {
|
|
2779
|
+
const task = handleRequest(req, res)
|
|
2780
|
+
.catch((err) => {
|
|
2781
|
+
if (res.headersSent || res.destroyed || res.writableEnded) {
|
|
2782
|
+
if (!res.destroyed)
|
|
2783
|
+
res.destroy();
|
|
2784
|
+
return;
|
|
2785
|
+
}
|
|
2786
|
+
if (err instanceof HardwareRunnerError) {
|
|
2787
|
+
switch (err.code) {
|
|
2788
|
+
case 'PAYLOAD_TOO_LARGE':
|
|
2789
|
+
req.resume();
|
|
2790
|
+
sendError(res, secretScrubber, 413, err.code, err.message);
|
|
2791
|
+
return;
|
|
2792
|
+
case 'AUTH_UNAUTHORIZED':
|
|
2793
|
+
req.resume();
|
|
2794
|
+
sendError(res, secretScrubber, 401, err.code, err.message);
|
|
2795
|
+
return;
|
|
2796
|
+
case 'AUTH_FORBIDDEN':
|
|
2797
|
+
req.resume();
|
|
2798
|
+
sendError(res, secretScrubber, 403, err.code, err.message);
|
|
2799
|
+
return;
|
|
2800
|
+
case 'NOT_FOUND':
|
|
2801
|
+
req.resume();
|
|
2802
|
+
sendError(res, secretScrubber, 404, err.code, err.message);
|
|
2803
|
+
return;
|
|
2804
|
+
case 'ARTIFACT_MISSING':
|
|
2805
|
+
case 'QUEUE_LEASE_FENCED':
|
|
2806
|
+
case 'QUEUE_JOB_CONFLICT':
|
|
2807
|
+
req.resume();
|
|
2808
|
+
sendError(res, secretScrubber, 409, err.code, err.message);
|
|
2809
|
+
return;
|
|
2810
|
+
case 'QUEUE_CAPACITY_EXCEEDED':
|
|
2811
|
+
req.resume();
|
|
2812
|
+
sendError(res, secretScrubber, 429, err.code, err.message);
|
|
2813
|
+
return;
|
|
2814
|
+
case 'ARTIFACT_INVALID': {
|
|
2815
|
+
req.resume();
|
|
2816
|
+
const isUploadOrEvidenceValidation = (req.method === 'PUT' && (req.url ?? '').includes('/blobs/'))
|
|
2817
|
+
|| err.message.includes('SecretScrubber')
|
|
2818
|
+
|| err.message.includes('outputArtifact')
|
|
2819
|
+
|| err.message.includes('targetCellId')
|
|
2820
|
+
|| err.message.includes('CAS blob')
|
|
2821
|
+
|| err.message.includes('byteLength mismatch')
|
|
2822
|
+
|| err.message.includes('sha256 mismatch')
|
|
2823
|
+
|| err.message.includes('shorter than declared')
|
|
2824
|
+
|| err.message.includes('exceeded declared');
|
|
2825
|
+
sendError(res, secretScrubber, isUploadOrEvidenceValidation ? 422 : 400, err.code, err.message);
|
|
2826
|
+
return;
|
|
2827
|
+
}
|
|
2828
|
+
default:
|
|
2829
|
+
req.resume();
|
|
2830
|
+
sendError(res, secretScrubber, 400, err.code, err.message);
|
|
2831
|
+
return;
|
|
2832
|
+
}
|
|
2833
|
+
}
|
|
2834
|
+
req.resume();
|
|
2835
|
+
sendError(res, secretScrubber, 500, 'INTERNAL_ERROR', 'internal server error');
|
|
2836
|
+
})
|
|
2837
|
+
.finally(() => {
|
|
2838
|
+
activeRequestTasks.delete(task);
|
|
2839
|
+
});
|
|
2840
|
+
activeRequestTasks.add(task);
|
|
2841
|
+
};
|
|
2842
|
+
if (config.tls !== false) {
|
|
2843
|
+
scheme = 'https';
|
|
2844
|
+
const readTlsPem = async (pemPath, diagPath) => {
|
|
2845
|
+
await assertNoSymlinkAncestors(pemPath, { checkLeaf: true, code: 'CONFIG_INVALID', diagPath });
|
|
2846
|
+
const raw = await readBoundedRegularFile(pemPath, 262_144, msg => {
|
|
2847
|
+
throw new HardwareRunnerError('CONFIG_INVALID', msg, diagPath);
|
|
2848
|
+
});
|
|
2849
|
+
return Buffer.from(raw);
|
|
2850
|
+
};
|
|
2851
|
+
const cert = await readTlsPem(config.tls.certPath, '/tls/certPath');
|
|
2852
|
+
const key = await readTlsPem(config.tls.keyPath, '/tls/keyPath');
|
|
2853
|
+
const ca = config.tls.caPath !== undefined
|
|
2854
|
+
? await readTlsPem(config.tls.caPath, '/tls/caPath')
|
|
2855
|
+
: undefined;
|
|
2856
|
+
server = createHttpsServer({
|
|
2857
|
+
cert,
|
|
2858
|
+
key,
|
|
2859
|
+
...(ca !== undefined ? { ca } : {}),
|
|
2860
|
+
}, requestListener);
|
|
2861
|
+
}
|
|
2862
|
+
else {
|
|
2863
|
+
server = createHttpServer(requestListener);
|
|
2864
|
+
}
|
|
2865
|
+
const boundServer = server;
|
|
2866
|
+
boundServer.on('connection', (socket) => {
|
|
2867
|
+
openSockets.add(socket);
|
|
2868
|
+
socket.once('close', () => {
|
|
2869
|
+
openSockets.delete(socket);
|
|
2870
|
+
});
|
|
2871
|
+
});
|
|
2872
|
+
await new Promise((resolveListen, rejectListen) => {
|
|
2873
|
+
const onError = (err) => {
|
|
2874
|
+
boundServer.removeListener('listening', onListening);
|
|
2875
|
+
rejectListen(err);
|
|
2876
|
+
};
|
|
2877
|
+
const onListening = () => {
|
|
2878
|
+
boundServer.removeListener('error', onError);
|
|
2879
|
+
resolveListen();
|
|
2880
|
+
};
|
|
2881
|
+
boundServer.once('error', onError);
|
|
2882
|
+
boundServer.once('listening', onListening);
|
|
2883
|
+
boundServer.listen(config.port, config.host);
|
|
2884
|
+
});
|
|
2885
|
+
const addr = boundServer.address();
|
|
2886
|
+
if (!addr || typeof addr !== 'object') {
|
|
2887
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'failed to bind relay server socket');
|
|
2888
|
+
}
|
|
2889
|
+
const boundHost = addr.family === 'IPv6' && !config.host.startsWith('[') && config.host.includes(':')
|
|
2890
|
+
? `[${config.host}]`
|
|
2891
|
+
: config.host;
|
|
2892
|
+
const boundPort = addr.port;
|
|
2893
|
+
const baseUrl = `${scheme}://${boundHost}:${boundPort}`;
|
|
2894
|
+
let closePromise = null;
|
|
2895
|
+
return Object.freeze({
|
|
2896
|
+
url: baseUrl,
|
|
2897
|
+
host: config.host,
|
|
2898
|
+
port: boundPort,
|
|
2899
|
+
relayBootId: queue.relayBootId,
|
|
2900
|
+
casDir: config.casDir,
|
|
2901
|
+
retainedTerminalCount() {
|
|
2902
|
+
return Math.max(queue.retainedTerminalCount, countRetainedTerminalEntries());
|
|
2903
|
+
},
|
|
2904
|
+
close() {
|
|
2905
|
+
if (closePromise !== null)
|
|
2906
|
+
return closePromise;
|
|
2907
|
+
closePromise = (async () => {
|
|
2908
|
+
serverAbort.abort();
|
|
2909
|
+
const cleanPendingOpIds = [];
|
|
2910
|
+
for (const opId of activeOperations.keys()) {
|
|
2911
|
+
const snap = queue.getJobByOperationId(opId);
|
|
2912
|
+
if (snap !== null && snap.preemptionCount === 0 && snap.verdict.status === 'pending') {
|
|
2913
|
+
cleanPendingOpIds.push(opId);
|
|
2914
|
+
}
|
|
2915
|
+
}
|
|
2916
|
+
queue.close();
|
|
2917
|
+
if ('closeIdleConnections' in boundServer && typeof boundServer.closeIdleConnections === 'function') {
|
|
2918
|
+
boundServer.closeIdleConnections();
|
|
2919
|
+
}
|
|
2920
|
+
const serverClosePromise = new Promise(resolveClose => {
|
|
2921
|
+
boundServer.close(() => resolveClose());
|
|
2922
|
+
});
|
|
2923
|
+
const forceTimer = setTimeout(() => {
|
|
2924
|
+
for (const sock of openSockets) {
|
|
2925
|
+
sock.destroy();
|
|
2926
|
+
}
|
|
2927
|
+
}, 200);
|
|
2928
|
+
forceTimer.unref();
|
|
2929
|
+
await serverClosePromise;
|
|
2930
|
+
clearTimeout(forceTimer);
|
|
2931
|
+
while (activeRequestTasks.size > 0 || activeDurabilityTasks.size > 0) {
|
|
2932
|
+
await Promise.allSettled([...activeRequestTasks, ...activeDurabilityTasks]);
|
|
2933
|
+
}
|
|
2934
|
+
let hasFlushError = false;
|
|
2935
|
+
let flushError;
|
|
2936
|
+
for (const pendingEntry of [...undurableTerminalByOperation.values()]) {
|
|
2937
|
+
try {
|
|
2938
|
+
await ensureReceiptDurable(pendingEntry.verdict);
|
|
2939
|
+
}
|
|
2940
|
+
catch (err) {
|
|
2941
|
+
recordRecoveryFence(pendingEntry.operationId, 'shutdown_flush_failed');
|
|
2942
|
+
if (!hasFlushError) {
|
|
2943
|
+
hasFlushError = true;
|
|
2944
|
+
flushError = err;
|
|
2945
|
+
}
|
|
2946
|
+
}
|
|
2947
|
+
}
|
|
2948
|
+
while (activeDurabilityTasks.size > 0) {
|
|
2949
|
+
await Promise.allSettled([...activeDurabilityTasks]);
|
|
2950
|
+
}
|
|
2951
|
+
for (const remainingOpId of undurableTerminalByOperation.keys()) {
|
|
2952
|
+
recordRecoveryFence(remainingOpId, 'shutdown_flush_failed');
|
|
2953
|
+
}
|
|
2954
|
+
// Only release pre-allocated fences for operations that never consumed a preemption or settled terminally.
|
|
2955
|
+
for (const pendingOpId of cleanPendingOpIds) {
|
|
2956
|
+
if (!undurableTerminalByOperation.has(pendingOpId) && activeOperations.has(pendingOpId)) {
|
|
2957
|
+
clearRecoveryFence(pendingOpId);
|
|
2958
|
+
}
|
|
2959
|
+
}
|
|
2960
|
+
let hasLockReleaseError = false;
|
|
2961
|
+
let lockReleaseError;
|
|
2962
|
+
try {
|
|
2963
|
+
await releaseCasLock(true);
|
|
2964
|
+
}
|
|
2965
|
+
catch (err) {
|
|
2966
|
+
hasLockReleaseError = true;
|
|
2967
|
+
lockReleaseError = err;
|
|
2968
|
+
}
|
|
2969
|
+
if (hasFlushError) {
|
|
2970
|
+
throw flushError;
|
|
2971
|
+
}
|
|
2972
|
+
if (hasLockReleaseError) {
|
|
2973
|
+
throw lockReleaseError;
|
|
2974
|
+
}
|
|
2975
|
+
})();
|
|
2976
|
+
return closePromise;
|
|
2977
|
+
},
|
|
2978
|
+
});
|
|
2979
|
+
}
|
|
2980
|
+
catch (err) {
|
|
2981
|
+
serverAbort.abort();
|
|
2982
|
+
queue.close();
|
|
2983
|
+
while (activeRequestTasks.size > 0 || activeDurabilityTasks.size > 0) {
|
|
2984
|
+
await Promise.allSettled([...activeRequestTasks, ...activeDurabilityTasks]);
|
|
2985
|
+
}
|
|
2986
|
+
if (server !== null) {
|
|
2987
|
+
try {
|
|
2988
|
+
server.close();
|
|
2989
|
+
}
|
|
2990
|
+
catch {
|
|
2991
|
+
// Ignore close error on unbound server.
|
|
2992
|
+
}
|
|
2993
|
+
}
|
|
2994
|
+
await releaseCasLock(false);
|
|
2995
|
+
throw err;
|
|
2996
|
+
}
|
|
2997
|
+
}
|