@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,3178 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
3
|
+
import { constants, existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync, } from 'node:fs';
|
|
4
|
+
import { chmod, lstat, mkdir, open, readdir, realpath, rmdir, unlink } from 'node:fs/promises';
|
|
5
|
+
import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
6
|
+
import { types } from 'node:util';
|
|
7
|
+
import { isVerifierNamespacePath, LIMITS, SecretScrubber, validateRelativePath, VERIFIER_ARTIFACT_LIMITS, } from '@loopwright/core';
|
|
8
|
+
import { LANDLOCK_BOOTSTRAP_SCRIPT, negotiateSandboxBackend, SECCOMP_BLOCKED_SYSCALLS, TaskpackError, TRUSTED_DOCKER_PATHS, } from '@loopwright/taskpack';
|
|
9
|
+
import { assertNoSymlinkAncestors, canonicalJson, expectNullProtoRecord, hasLoneSurrogate, parseStrictJsonBytes, } from './config.js';
|
|
10
|
+
import { collectHardwareProvenance, snapshotHeldOutWorkload, verifyTrustedSystemExecutableSync, } from './provenance.js';
|
|
11
|
+
import { computeSecretScanOverlapBytes, EMPTY_SHA256_HEX, MAX_CAS_CHUNK_BYTES, } from './relay-server.js';
|
|
12
|
+
import { HardwareRunnerError, } from './types.js';
|
|
13
|
+
export const LWTREE01_MAGIC = 'LWTREE01';
|
|
14
|
+
const BASE_TREE_BUNDLE_MAGIC = Buffer.from(LWTREE01_MAGIC, 'ascii');
|
|
15
|
+
// Cap Stage B stdout JSON envelope at 48 KiB so the worker's `:complete` control body
|
|
16
|
+
// (envelope + hardwareProvenance + outputArtifacts + lease credentials) stays within 64 KiB.
|
|
17
|
+
export const MAX_STAGE_B_RESULT_BYTES = 49_152;
|
|
18
|
+
export const MAX_STAGE_STDIO_BYTES = 1_048_576;
|
|
19
|
+
export const STAGE_B_RESULT_MARKER_PREFIX = 'LOOPWRIGHT_STAGE_B_RESULT:';
|
|
20
|
+
export class RunnerTeardownError extends HardwareRunnerError {
|
|
21
|
+
teardownFailed = true;
|
|
22
|
+
reasonCode = 'RUNNER_TEARDOWN_FAILED';
|
|
23
|
+
constructor(message, options) {
|
|
24
|
+
super('RUNNER_SANDBOX_FAILED', message, undefined, options);
|
|
25
|
+
this.name = 'RunnerTeardownError';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function isRunnerTeardownError(err) {
|
|
29
|
+
return (err instanceof RunnerTeardownError
|
|
30
|
+
|| (err instanceof Error && err.teardownFailed === true));
|
|
31
|
+
}
|
|
32
|
+
export const STAGE_A_CANDIDATE_ENTRYPOINTS = Object.freeze([
|
|
33
|
+
'benchmark/stage-a.sh',
|
|
34
|
+
'scripts/stage-a.sh',
|
|
35
|
+
'scripts/build.sh',
|
|
36
|
+
'packages/build.sh',
|
|
37
|
+
'build.sh',
|
|
38
|
+
]);
|
|
39
|
+
export const STAGE_B_WORKLOAD_ENTRYPOINTS = Object.freeze([
|
|
40
|
+
'stage-b.sh',
|
|
41
|
+
'evaluate.sh',
|
|
42
|
+
'benchmark.sh',
|
|
43
|
+
'run.sh',
|
|
44
|
+
]);
|
|
45
|
+
const PRINTABLE_ASCII_RE = /^[\x20-\x7E]+$/;
|
|
46
|
+
const METRIC_KEY_RE = /^[A-Za-z_][A-Za-z0-9._-]*$/;
|
|
47
|
+
const FORBIDDEN_METRIC_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
48
|
+
const STAGE_B_ENVELOPE_KEYS = new Set([
|
|
49
|
+
'status',
|
|
50
|
+
'reason',
|
|
51
|
+
'detail',
|
|
52
|
+
'metrics',
|
|
53
|
+
'findings',
|
|
54
|
+
]);
|
|
55
|
+
const FINDING_KEYS = new Set(['title', 'severity', 'path', 'line', 'evidence']);
|
|
56
|
+
const MAX_TOOLCHAIN_SCAN_ENTRIES = 262_144;
|
|
57
|
+
const MAX_TOOLCHAIN_SCAN_DEPTH = 32;
|
|
58
|
+
const FORBIDDEN_MOUNT_ROOTS = Object.freeze([
|
|
59
|
+
'/',
|
|
60
|
+
'/run',
|
|
61
|
+
'/var/run',
|
|
62
|
+
'/private/var/run',
|
|
63
|
+
'/dev',
|
|
64
|
+
'/proc',
|
|
65
|
+
'/sys',
|
|
66
|
+
'/tmp',
|
|
67
|
+
'/private/tmp',
|
|
68
|
+
]);
|
|
69
|
+
// Linux x64 and arm64 syscall numbers for strict kernel-boundary socket + dangerous syscall denial.
|
|
70
|
+
const STRICT_SECCOMP_BLOCKED_X64 = Object.freeze([
|
|
71
|
+
101, 246, 320, 165, 166, 155, 321, 298, 323, 250, 248, 249, 425, 426, 427,
|
|
72
|
+
41, // socket
|
|
73
|
+
53, // socketpair
|
|
74
|
+
42, // connect
|
|
75
|
+
49, // bind
|
|
76
|
+
50, // listen
|
|
77
|
+
43, // accept
|
|
78
|
+
288, // accept4
|
|
79
|
+
]);
|
|
80
|
+
const STRICT_SECCOMP_BLOCKED_ARM64 = Object.freeze([
|
|
81
|
+
117, 104, 294, 40, 39, 41, 280, 241, 282, 219, 217, 218, 425, 426, 427,
|
|
82
|
+
198, // socket
|
|
83
|
+
199, // socketpair
|
|
84
|
+
203, // connect
|
|
85
|
+
200, // bind
|
|
86
|
+
201, // listen
|
|
87
|
+
202, // accept
|
|
88
|
+
242, // accept4
|
|
89
|
+
]);
|
|
90
|
+
function compareUtf16(a, b) {
|
|
91
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
92
|
+
}
|
|
93
|
+
function pathsOverlap(pathA, pathB) {
|
|
94
|
+
if (pathA === pathB)
|
|
95
|
+
return true;
|
|
96
|
+
const prefixA = pathA === '/' ? '/' : `${pathA}${sep}`;
|
|
97
|
+
const prefixB = pathB === '/' ? '/' : `${pathB}${sep}`;
|
|
98
|
+
return pathA.startsWith(prefixB) || pathB.startsWith(prefixA);
|
|
99
|
+
}
|
|
100
|
+
function canonicalOrResolvedSync(rawPath) {
|
|
101
|
+
const resolved = resolve(rawPath);
|
|
102
|
+
const out = new Set([resolved]);
|
|
103
|
+
try {
|
|
104
|
+
out.add(realpathSync(resolved));
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
// Also canonicalize closest existing ancestor so non-existent leaf paths under /var -> /private/var match.
|
|
108
|
+
let cur = dirname(resolved);
|
|
109
|
+
const tail = [resolved.slice(cur.length).replace(/^[/\\]+/, '')];
|
|
110
|
+
while (cur !== dirname(cur)) {
|
|
111
|
+
try {
|
|
112
|
+
const realParent = realpathSync(cur);
|
|
113
|
+
out.add(join(realParent, ...tail.reverse()));
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
const prev = cur;
|
|
118
|
+
cur = dirname(cur);
|
|
119
|
+
tail.push(prev.slice(cur.length).replace(/^[/\\]+/, ''));
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return [...out];
|
|
124
|
+
}
|
|
125
|
+
function validateSafeRelativeArtifactPath(rawName, diagPath) {
|
|
126
|
+
if (typeof rawName !== 'string' || rawName.length < 1 || rawName.length > LIMITS.path || hasLoneSurrogate(rawName)) {
|
|
127
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid artifact relative path', diagPath);
|
|
128
|
+
}
|
|
129
|
+
const validated = validateRelativePath(rawName);
|
|
130
|
+
if (!validated.ok
|
|
131
|
+
|| validated.value !== rawName
|
|
132
|
+
|| isVerifierNamespacePath(rawName)
|
|
133
|
+
|| rawName.split('/').some(seg => seg.toLowerCase() === '.git' || Buffer.byteLength(seg, 'utf8') > 255)) {
|
|
134
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `disallowed artifact relative path "${rawName}"`, diagPath);
|
|
135
|
+
}
|
|
136
|
+
return rawName;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Deterministic `LWTREE01` binary base-tree bundle encoder.
|
|
140
|
+
*/
|
|
141
|
+
export function encodeLwtree01Bundle(entries) {
|
|
142
|
+
if (entries.length > LIMITS.baselineEntries) {
|
|
143
|
+
throw new HardwareRunnerError('PAYLOAD_TOO_LARGE', 'LWTREE01 entry count exceeds baselineEntries limit');
|
|
144
|
+
}
|
|
145
|
+
const sorted = [...entries].sort((a, b) => compareUtf16(a.name, b.name));
|
|
146
|
+
const seenFolded = new Set();
|
|
147
|
+
const parts = [];
|
|
148
|
+
const header = Buffer.allocUnsafe(12);
|
|
149
|
+
BASE_TREE_BUNDLE_MAGIC.copy(header, 0);
|
|
150
|
+
header.writeUInt32BE(sorted.length, 8);
|
|
151
|
+
parts.push(header);
|
|
152
|
+
let prevName = null;
|
|
153
|
+
for (const item of sorted) {
|
|
154
|
+
validateSafeRelativeArtifactPath(item.name, '/baseTreeBundle');
|
|
155
|
+
if (prevName !== null && compareUtf16(prevName, item.name) >= 0) {
|
|
156
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'duplicate LWTREE01 entry name');
|
|
157
|
+
}
|
|
158
|
+
prevName = item.name;
|
|
159
|
+
const folded = item.name.normalize('NFC').toLowerCase();
|
|
160
|
+
if (seenFolded.has(folded)) {
|
|
161
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'case-colliding LWTREE01 entry path');
|
|
162
|
+
}
|
|
163
|
+
seenFolded.add(folded);
|
|
164
|
+
const pathBuf = Buffer.from(item.name, 'utf8');
|
|
165
|
+
const prefix = Buffer.allocUnsafe(4 + pathBuf.byteLength + 1 + 4);
|
|
166
|
+
prefix.writeUInt32BE(pathBuf.byteLength, 0);
|
|
167
|
+
pathBuf.copy(prefix, 4);
|
|
168
|
+
prefix[4 + pathBuf.byteLength] = item.mode === '100755' ? 1 : 0;
|
|
169
|
+
prefix.writeUInt32BE(item.bytes.byteLength, 4 + pathBuf.byteLength + 1);
|
|
170
|
+
parts.push(prefix, Buffer.from(item.bytes));
|
|
171
|
+
}
|
|
172
|
+
for (const folded of seenFolded) {
|
|
173
|
+
let slash = folded.indexOf('/');
|
|
174
|
+
while (slash !== -1) {
|
|
175
|
+
if (seenFolded.has(folded.slice(0, slash))) {
|
|
176
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'file/directory prefix collision in LWTREE01 bundle');
|
|
177
|
+
}
|
|
178
|
+
slash = folded.indexOf('/', slash + 1);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return Buffer.concat(parts);
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Bounded deterministic `LWTREE01` binary base-tree bundle decoder matching `@loopwright/controller`.
|
|
185
|
+
*/
|
|
186
|
+
export function decodeLwtree01Bundle(bytes, maxBytes = VERIFIER_ARTIFACT_LIMITS.maxFileBytes) {
|
|
187
|
+
if (!(bytes instanceof Uint8Array)
|
|
188
|
+
|| types.isProxy(bytes)
|
|
189
|
+
|| types.isSharedArrayBuffer(bytes.buffer)
|
|
190
|
+
|| bytes.byteLength < 12
|
|
191
|
+
|| bytes.byteLength > maxBytes) {
|
|
192
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid LWTREE01 bundle buffer bounds', '/baseTreeBundle');
|
|
193
|
+
}
|
|
194
|
+
if (!Buffer.from(bytes.buffer, bytes.byteOffset, 8).equals(BASE_TREE_BUNDLE_MAGIC)) {
|
|
195
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid LWTREE01 bundle magic header', '/baseTreeBundle');
|
|
196
|
+
}
|
|
197
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
198
|
+
const count = view.getUint32(8, false);
|
|
199
|
+
if (count > LIMITS.baselineEntries) {
|
|
200
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'LWTREE01 entry count exceeds maximum', '/baseTreeBundle');
|
|
201
|
+
}
|
|
202
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
203
|
+
const entries = [];
|
|
204
|
+
const seenFolded = new Set();
|
|
205
|
+
let prevName = null;
|
|
206
|
+
let offset = 12;
|
|
207
|
+
for (let idx = 0; idx < count; idx += 1) {
|
|
208
|
+
if (offset + 4 > bytes.byteLength) {
|
|
209
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'truncated LWTREE01 path length', '/baseTreeBundle');
|
|
210
|
+
}
|
|
211
|
+
const pathLen = view.getUint32(offset, false);
|
|
212
|
+
offset += 4;
|
|
213
|
+
if (pathLen < 1 || pathLen > 4096 || offset + pathLen + 5 > bytes.byteLength) {
|
|
214
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid LWTREE01 entry framing', '/baseTreeBundle');
|
|
215
|
+
}
|
|
216
|
+
let name;
|
|
217
|
+
try {
|
|
218
|
+
name = decoder.decode(bytes.subarray(offset, offset + pathLen));
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'non-UTF8 path in LWTREE01 bundle', '/baseTreeBundle');
|
|
222
|
+
}
|
|
223
|
+
offset += pathLen;
|
|
224
|
+
validateSafeRelativeArtifactPath(name, `/baseTreeBundle/${idx}`);
|
|
225
|
+
if (prevName !== null && compareUtf16(prevName, name) >= 0) {
|
|
226
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'unsorted or duplicate LWTREE01 entry path', `/baseTreeBundle/${idx}`);
|
|
227
|
+
}
|
|
228
|
+
prevName = name;
|
|
229
|
+
const folded = name.normalize('NFC').toLowerCase();
|
|
230
|
+
if (seenFolded.has(folded)) {
|
|
231
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'case-colliding LWTREE01 entry path', `/baseTreeBundle/${idx}`);
|
|
232
|
+
}
|
|
233
|
+
seenFolded.add(folded);
|
|
234
|
+
const modeFlag = bytes[offset];
|
|
235
|
+
offset += 1;
|
|
236
|
+
if (modeFlag !== 0 && modeFlag !== 1) {
|
|
237
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid LWTREE01 modeFlag byte', `/baseTreeBundle/${idx}`);
|
|
238
|
+
}
|
|
239
|
+
const contentLen = view.getUint32(offset, false);
|
|
240
|
+
offset += 4;
|
|
241
|
+
if (contentLen > bytes.byteLength - offset) {
|
|
242
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'truncated LWTREE01 entry payload', `/baseTreeBundle/${idx}`);
|
|
243
|
+
}
|
|
244
|
+
const content = bytes.slice(offset, offset + contentLen);
|
|
245
|
+
offset += contentLen;
|
|
246
|
+
entries.push(Object.freeze({
|
|
247
|
+
name,
|
|
248
|
+
mode: modeFlag === 1 ? '100755' : '100644',
|
|
249
|
+
bytes: content,
|
|
250
|
+
}));
|
|
251
|
+
}
|
|
252
|
+
if (offset !== bytes.byteLength) {
|
|
253
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'trailing bytes in LWTREE01 bundle', '/baseTreeBundle');
|
|
254
|
+
}
|
|
255
|
+
for (const folded of seenFolded) {
|
|
256
|
+
let slash = folded.indexOf('/');
|
|
257
|
+
while (slash !== -1) {
|
|
258
|
+
if (seenFolded.has(folded.slice(0, slash))) {
|
|
259
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'file/directory prefix collision in LWTREE01 bundle', '/baseTreeBundle');
|
|
260
|
+
}
|
|
261
|
+
slash = folded.indexOf('/', slash + 1);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
return Object.freeze(entries);
|
|
265
|
+
}
|
|
266
|
+
async function readExactFromHandle(handle, target, length, fileOffset) {
|
|
267
|
+
let filled = 0;
|
|
268
|
+
while (filled < length) {
|
|
269
|
+
const { bytesRead } = await handle.read(target, filled, length - filled, fileOffset + filled);
|
|
270
|
+
if (bytesRead <= 0) {
|
|
271
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'unexpected EOF while decoding LWTREE01 bundle', '/baseTreeBundle');
|
|
272
|
+
}
|
|
273
|
+
filled += bytesRead;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
async function writeAllToHandle(handle, bytes) {
|
|
277
|
+
let offset = 0;
|
|
278
|
+
while (offset < bytes.byteLength) {
|
|
279
|
+
const slice = bytes.subarray(offset, Math.min(bytes.byteLength, offset + MAX_CAS_CHUNK_BYTES));
|
|
280
|
+
let sliceOffset = 0;
|
|
281
|
+
while (sliceOffset < slice.byteLength) {
|
|
282
|
+
const { bytesWritten } = await handle.write(slice, sliceOffset, slice.byteLength - sliceOffset);
|
|
283
|
+
if (bytesWritten <= 0) {
|
|
284
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'short write while materializing candidate file');
|
|
285
|
+
}
|
|
286
|
+
sliceOffset += bytesWritten;
|
|
287
|
+
}
|
|
288
|
+
offset += slice.byteLength;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
async function ensureSafeSubdirectories(rootDir, relFilePath) {
|
|
292
|
+
const segments = relFilePath.split('/');
|
|
293
|
+
let cursor = rootDir;
|
|
294
|
+
for (let i = 0; i < segments.length - 1; i += 1) {
|
|
295
|
+
cursor = join(cursor, segments[i]);
|
|
296
|
+
const st = await lstat(cursor).catch((err) => {
|
|
297
|
+
if (err?.code === 'ENOENT')
|
|
298
|
+
return null;
|
|
299
|
+
throw err;
|
|
300
|
+
});
|
|
301
|
+
if (st === null) {
|
|
302
|
+
await mkdir(cursor, { mode: 0o755 });
|
|
303
|
+
const created = await lstat(cursor);
|
|
304
|
+
if (created.isSymbolicLink() || !created.isDirectory()) {
|
|
305
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'symlink encountered while creating candidate directory');
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
else if (st.isSymbolicLink() || !st.isDirectory()) {
|
|
309
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `file/directory collision or symlink at "${segments.slice(0, i + 1).join('/')}"`);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return join(cursor, segments[segments.length - 1]);
|
|
313
|
+
}
|
|
314
|
+
async function writeVerifiedFileNoFollow(rootDir, relPath, mode, writer) {
|
|
315
|
+
const targetAbs = await ensureSafeSubdirectories(rootDir, relPath);
|
|
316
|
+
const existing = await lstat(targetAbs).catch((err) => {
|
|
317
|
+
if (err?.code === 'ENOENT')
|
|
318
|
+
return null;
|
|
319
|
+
throw err;
|
|
320
|
+
});
|
|
321
|
+
if (existing !== null) {
|
|
322
|
+
if (existing.isSymbolicLink() || !existing.isFile()) {
|
|
323
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `cannot overwrite symlink or directory at "${relPath}"`);
|
|
324
|
+
}
|
|
325
|
+
await unlink(targetAbs);
|
|
326
|
+
}
|
|
327
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
328
|
+
const targetMode = mode === '100755' ? 0o755 : 0o644;
|
|
329
|
+
const handle = await open(targetAbs, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | noFollow, 0o600);
|
|
330
|
+
try {
|
|
331
|
+
await writer(handle);
|
|
332
|
+
await handle.chmod(targetMode);
|
|
333
|
+
const after = await handle.stat();
|
|
334
|
+
if (!after.isFile() || after.isSymbolicLink() || after.nlink !== 1 || (after.mode & 0o777) !== targetMode) {
|
|
335
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `materialized candidate file "${relPath}" failed mode/nlink verification`);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
catch (err) {
|
|
339
|
+
await handle.close().catch(() => { });
|
|
340
|
+
await unlink(targetAbs).catch(() => { });
|
|
341
|
+
throw err;
|
|
342
|
+
}
|
|
343
|
+
await handle.close();
|
|
344
|
+
}
|
|
345
|
+
async function decodeAndMaterializeLwtree01FromHandle(options) {
|
|
346
|
+
const { bundleHandle, totalBytes, maxBytes, candidateDir, signal } = options;
|
|
347
|
+
if (totalBytes < 12 || totalBytes > maxBytes) {
|
|
348
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid LWTREE01 bundle buffer bounds', '/baseTreeBundle');
|
|
349
|
+
}
|
|
350
|
+
const headerBuf = Buffer.allocUnsafe(4105);
|
|
351
|
+
await readExactFromHandle(bundleHandle, headerBuf, 12, 0);
|
|
352
|
+
if (!headerBuf.subarray(0, 8).equals(BASE_TREE_BUNDLE_MAGIC)) {
|
|
353
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid LWTREE01 bundle magic header', '/baseTreeBundle');
|
|
354
|
+
}
|
|
355
|
+
const count = headerBuf.readUInt32BE(8);
|
|
356
|
+
if (count > LIMITS.baselineEntries) {
|
|
357
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'LWTREE01 entry count exceeds maximum', '/baseTreeBundle');
|
|
358
|
+
}
|
|
359
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
360
|
+
const entryMeta = [];
|
|
361
|
+
const seenFolded = new Set();
|
|
362
|
+
let prevName = null;
|
|
363
|
+
let offset = 12;
|
|
364
|
+
// Pass 1: Validate all headers, ordering, collisions, and exact EOF without buffering file contents in RAM.
|
|
365
|
+
for (let idx = 0; idx < count; idx += 1) {
|
|
366
|
+
if (signal?.aborted) {
|
|
367
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'workspace reconstruction aborted');
|
|
368
|
+
}
|
|
369
|
+
if (offset + 4 > totalBytes) {
|
|
370
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'truncated LWTREE01 path length', '/baseTreeBundle');
|
|
371
|
+
}
|
|
372
|
+
await readExactFromHandle(bundleHandle, headerBuf, 4, offset);
|
|
373
|
+
const pathLen = headerBuf.readUInt32BE(0);
|
|
374
|
+
offset += 4;
|
|
375
|
+
if (pathLen < 1 || pathLen > 4096 || offset + pathLen + 5 > totalBytes) {
|
|
376
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid LWTREE01 entry framing', '/baseTreeBundle');
|
|
377
|
+
}
|
|
378
|
+
await readExactFromHandle(bundleHandle, headerBuf, pathLen + 5, offset);
|
|
379
|
+
let name;
|
|
380
|
+
try {
|
|
381
|
+
name = decoder.decode(headerBuf.subarray(0, pathLen));
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'non-UTF8 path in LWTREE01 bundle', '/baseTreeBundle');
|
|
385
|
+
}
|
|
386
|
+
validateSafeRelativeArtifactPath(name, `/baseTreeBundle/${idx}`);
|
|
387
|
+
if (prevName !== null && compareUtf16(prevName, name) >= 0) {
|
|
388
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'unsorted or duplicate LWTREE01 entry path', `/baseTreeBundle/${idx}`);
|
|
389
|
+
}
|
|
390
|
+
prevName = name;
|
|
391
|
+
const folded = name.normalize('NFC').toLowerCase();
|
|
392
|
+
if (seenFolded.has(folded)) {
|
|
393
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'case-colliding LWTREE01 entry path', `/baseTreeBundle/${idx}`);
|
|
394
|
+
}
|
|
395
|
+
seenFolded.add(folded);
|
|
396
|
+
const modeFlag = headerBuf[pathLen];
|
|
397
|
+
if (modeFlag !== 0 && modeFlag !== 1) {
|
|
398
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid LWTREE01 modeFlag byte', `/baseTreeBundle/${idx}`);
|
|
399
|
+
}
|
|
400
|
+
const contentLen = headerBuf.readUInt32BE(pathLen + 1);
|
|
401
|
+
const payloadOffset = offset + pathLen + 5;
|
|
402
|
+
if (contentLen > totalBytes - payloadOffset) {
|
|
403
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'truncated LWTREE01 entry payload', `/baseTreeBundle/${idx}`);
|
|
404
|
+
}
|
|
405
|
+
offset = payloadOffset + contentLen;
|
|
406
|
+
entryMeta.push({
|
|
407
|
+
name,
|
|
408
|
+
mode: modeFlag === 1 ? '100755' : '100644',
|
|
409
|
+
payloadOffset,
|
|
410
|
+
contentLen,
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
if (offset !== totalBytes) {
|
|
414
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'trailing bytes in LWTREE01 bundle', '/baseTreeBundle');
|
|
415
|
+
}
|
|
416
|
+
for (const folded of seenFolded) {
|
|
417
|
+
let slash = folded.indexOf('/');
|
|
418
|
+
while (slash !== -1) {
|
|
419
|
+
if (seenFolded.has(folded.slice(0, slash))) {
|
|
420
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'file/directory prefix collision in LWTREE01 bundle', '/baseTreeBundle');
|
|
421
|
+
}
|
|
422
|
+
slash = folded.indexOf('/', slash + 1);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
// Pass 2: Materialize each entry using a single reusable <= 1 MiB copy buffer.
|
|
426
|
+
const copyBuf = Buffer.allocUnsafe(MAX_CAS_CHUNK_BYTES);
|
|
427
|
+
for (const item of entryMeta) {
|
|
428
|
+
if (signal?.aborted) {
|
|
429
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'workspace reconstruction aborted');
|
|
430
|
+
}
|
|
431
|
+
await writeVerifiedFileNoFollow(candidateDir, item.name, item.mode, async (dstHandle) => {
|
|
432
|
+
let remaining = item.contentLen;
|
|
433
|
+
let readPos = item.payloadOffset;
|
|
434
|
+
while (remaining > 0) {
|
|
435
|
+
if (signal?.aborted) {
|
|
436
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'workspace reconstruction aborted');
|
|
437
|
+
}
|
|
438
|
+
const step = Math.min(copyBuf.byteLength, remaining);
|
|
439
|
+
await readExactFromHandle(bundleHandle, copyBuf, step, readPos);
|
|
440
|
+
await writeAllToHandle(dstHandle, copyBuf.subarray(0, step));
|
|
441
|
+
readPos += step;
|
|
442
|
+
remaining -= step;
|
|
443
|
+
}
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Reconstruct the frozen candidate workspace inside `candidateDir` (`O_NOFOLLOW` verified) from
|
|
449
|
+
* optional `LWTREE01` `baseTreeBundle` (streamed into a verified private file without full-buffer
|
|
450
|
+
* RAM retention), `entries[]` CAS blobs, and `deleted[]` tombstones.
|
|
451
|
+
*/
|
|
452
|
+
export async function reconstructCandidateWorkspace(options) {
|
|
453
|
+
const { candidateDir, candidateArtifacts, downloadInputBlob } = options;
|
|
454
|
+
const maxBlobBytes = options.maxBlobBytes ?? VERIFIER_ARTIFACT_LIMITS.maxFileBytes;
|
|
455
|
+
const resolvedCandDir = resolve(candidateDir);
|
|
456
|
+
await assertNoSymlinkAncestors(resolvedCandDir, {
|
|
457
|
+
checkLeaf: true,
|
|
458
|
+
code: 'RUNNER_SANDBOX_FAILED',
|
|
459
|
+
diagPath: '/candidateDir',
|
|
460
|
+
});
|
|
461
|
+
await mkdir(resolvedCandDir, { recursive: true, mode: 0o755 });
|
|
462
|
+
const dirStat = await lstat(resolvedCandDir);
|
|
463
|
+
if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) {
|
|
464
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'candidateDir must be a non-symlink directory');
|
|
465
|
+
}
|
|
466
|
+
if (candidateArtifacts.baseTreeBundle !== undefined) {
|
|
467
|
+
const bundleMeta = candidateArtifacts.baseTreeBundle;
|
|
468
|
+
if (bundleMeta.byteLength > maxBlobBytes) {
|
|
469
|
+
throw new HardwareRunnerError('PAYLOAD_TOO_LARGE', 'baseTreeBundle exceeds maxBlobBytes');
|
|
470
|
+
}
|
|
471
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
472
|
+
const tmpBundlePath = join(resolvedCandDir, `.lwtree-bundle-${randomBytes(12).toString('hex')}.tmp`);
|
|
473
|
+
const bundleHandle = await open(tmpBundlePath, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR | noFollow, 0o600);
|
|
474
|
+
let primaryBundleErr = null;
|
|
475
|
+
try {
|
|
476
|
+
const createdSt = await bundleHandle.stat();
|
|
477
|
+
if (!createdSt.isFile() || createdSt.isSymbolicLink() || createdSt.nlink !== 1) {
|
|
478
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'temporary baseTreeBundle file failed identity check');
|
|
479
|
+
}
|
|
480
|
+
let received = 0;
|
|
481
|
+
const bundleHasher = createHash('sha256');
|
|
482
|
+
await downloadInputBlob(bundleMeta.digest.hex, bundleMeta.byteLength, async (slice) => {
|
|
483
|
+
if (options.signal?.aborted) {
|
|
484
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'workspace reconstruction aborted');
|
|
485
|
+
}
|
|
486
|
+
received += slice.byteLength;
|
|
487
|
+
if (received > bundleMeta.byteLength || received > maxBlobBytes) {
|
|
488
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'baseTreeBundle stream exceeded declared byteLength');
|
|
489
|
+
}
|
|
490
|
+
for (let off = 0; off < slice.byteLength; off += MAX_CAS_CHUNK_BYTES) {
|
|
491
|
+
const sub = slice.subarray(off, Math.min(slice.byteLength, off + MAX_CAS_CHUNK_BYTES));
|
|
492
|
+
bundleHasher.update(sub);
|
|
493
|
+
await writeAllToHandle(bundleHandle, sub);
|
|
494
|
+
}
|
|
495
|
+
});
|
|
496
|
+
if (received !== bundleMeta.byteLength || bundleHasher.digest('hex') !== bundleMeta.digest.hex) {
|
|
497
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'baseTreeBundle failed sha256 or byteLength verification');
|
|
498
|
+
}
|
|
499
|
+
const verifiedSt = await bundleHandle.stat();
|
|
500
|
+
if (verifiedSt.dev !== createdSt.dev || verifiedSt.ino !== createdSt.ino || verifiedSt.size !== received || verifiedSt.nlink !== 1) {
|
|
501
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'temporary baseTreeBundle file mutated before decoding');
|
|
502
|
+
}
|
|
503
|
+
await decodeAndMaterializeLwtree01FromHandle({
|
|
504
|
+
bundleHandle,
|
|
505
|
+
totalBytes: received,
|
|
506
|
+
maxBytes: maxBlobBytes,
|
|
507
|
+
candidateDir: resolvedCandDir,
|
|
508
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
catch (err) {
|
|
512
|
+
primaryBundleErr = err;
|
|
513
|
+
}
|
|
514
|
+
finally {
|
|
515
|
+
await bundleHandle.close().catch(() => { });
|
|
516
|
+
}
|
|
517
|
+
let bundleCleanupErr = null;
|
|
518
|
+
try {
|
|
519
|
+
await unlink(tmpBundlePath).catch((err) => {
|
|
520
|
+
if (err?.code !== 'ENOENT')
|
|
521
|
+
throw err;
|
|
522
|
+
});
|
|
523
|
+
const lingering = await lstat(tmpBundlePath).catch((err) => {
|
|
524
|
+
if (err?.code === 'ENOENT')
|
|
525
|
+
return null;
|
|
526
|
+
throw err;
|
|
527
|
+
});
|
|
528
|
+
if (lingering !== null) {
|
|
529
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'failed to remove temporary baseTreeBundle file');
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
catch (err) {
|
|
533
|
+
bundleCleanupErr = err;
|
|
534
|
+
}
|
|
535
|
+
if (primaryBundleErr !== null)
|
|
536
|
+
throw primaryBundleErr;
|
|
537
|
+
if (bundleCleanupErr !== null)
|
|
538
|
+
throw bundleCleanupErr;
|
|
539
|
+
}
|
|
540
|
+
for (const entry of candidateArtifacts.entries) {
|
|
541
|
+
if (options.signal?.aborted) {
|
|
542
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'workspace reconstruction aborted');
|
|
543
|
+
}
|
|
544
|
+
const relName = validateSafeRelativeArtifactPath(entry.name, '/candidateArtifacts/entries');
|
|
545
|
+
if (entry.byteLength > maxBlobBytes) {
|
|
546
|
+
throw new HardwareRunnerError('PAYLOAD_TOO_LARGE', `candidate entry "${relName}" exceeds maxBlobBytes`);
|
|
547
|
+
}
|
|
548
|
+
if ((entry.byteLength === 0) !== (entry.digest.hex === EMPTY_SHA256_HEX)) {
|
|
549
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `candidate entry "${relName}" empty digest mismatch`);
|
|
550
|
+
}
|
|
551
|
+
const mode = entry.mode === '100755' ? '100755' : '100644';
|
|
552
|
+
await writeVerifiedFileNoFollow(resolvedCandDir, relName, mode, async (handle) => {
|
|
553
|
+
const hasher = createHash('sha256');
|
|
554
|
+
let written = 0;
|
|
555
|
+
await downloadInputBlob(entry.digest.hex, entry.byteLength, async (slice) => {
|
|
556
|
+
if (options.signal?.aborted) {
|
|
557
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'workspace reconstruction aborted');
|
|
558
|
+
}
|
|
559
|
+
written += slice.byteLength;
|
|
560
|
+
if (written > entry.byteLength || written > maxBlobBytes) {
|
|
561
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `candidate entry "${relName}" exceeded declared byteLength`);
|
|
562
|
+
}
|
|
563
|
+
hasher.update(slice);
|
|
564
|
+
await writeAllToHandle(handle, slice);
|
|
565
|
+
});
|
|
566
|
+
if (written !== entry.byteLength || hasher.digest('hex') !== entry.digest.hex) {
|
|
567
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `candidate entry "${relName}" failed sha256 or byteLength check`);
|
|
568
|
+
}
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
for (const rawDel of candidateArtifacts.deleted) {
|
|
572
|
+
const relDel = validateSafeRelativeArtifactPath(rawDel, '/candidateArtifacts/deleted');
|
|
573
|
+
const segments = relDel.split('/');
|
|
574
|
+
let cursor = resolvedCandDir;
|
|
575
|
+
let missingParent = false;
|
|
576
|
+
for (let i = 0; i < segments.length - 1; i += 1) {
|
|
577
|
+
cursor = join(cursor, segments[i]);
|
|
578
|
+
const st = await lstat(cursor).catch((err) => {
|
|
579
|
+
if (err?.code === 'ENOENT')
|
|
580
|
+
return null;
|
|
581
|
+
throw err;
|
|
582
|
+
});
|
|
583
|
+
if (st === null) {
|
|
584
|
+
missingParent = true;
|
|
585
|
+
break;
|
|
586
|
+
}
|
|
587
|
+
if (st.isSymbolicLink() || !st.isDirectory()) {
|
|
588
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `deleted path "${relDel}" traverses symlink or non-directory`);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
if (missingParent)
|
|
592
|
+
continue;
|
|
593
|
+
const leafPath = join(cursor, segments[segments.length - 1]);
|
|
594
|
+
const leafStat = await lstat(leafPath).catch((err) => {
|
|
595
|
+
if (err?.code === 'ENOENT')
|
|
596
|
+
return null;
|
|
597
|
+
throw err;
|
|
598
|
+
});
|
|
599
|
+
if (leafStat === null)
|
|
600
|
+
continue;
|
|
601
|
+
if (leafStat.isSymbolicLink() || !leafStat.isFile()) {
|
|
602
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `deleted path "${relDel}" targets symlink or directory`);
|
|
603
|
+
}
|
|
604
|
+
await unlink(leafPath);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
function resolveMonotonicDeadlineChecker(options) {
|
|
608
|
+
if (options.getLeaseDeadlineMonoMs === undefined && options.leaseDeadlineMonoMs === undefined) {
|
|
609
|
+
return undefined;
|
|
610
|
+
}
|
|
611
|
+
const fixedDeadline = options.leaseDeadlineMonoMs;
|
|
612
|
+
const getDeadlineMonoMs = options.getLeaseDeadlineMonoMs ?? (() => fixedDeadline);
|
|
613
|
+
const nowMonotonicMs = options.nowMonotonicMs ?? (() => performance.now());
|
|
614
|
+
return { getDeadlineMonoMs, nowMonotonicMs };
|
|
615
|
+
}
|
|
616
|
+
function assertLeaseDeadlineNotExpired(checker, contextLabel, signal) {
|
|
617
|
+
if (checker !== undefined && checker.nowMonotonicMs() >= checker.getDeadlineMonoMs()) {
|
|
618
|
+
throw new HardwareRunnerError('QUEUE_LEASE_FENCED', `local lease authority expired (${contextLabel})`);
|
|
619
|
+
}
|
|
620
|
+
if (signal?.aborted) {
|
|
621
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `${contextLabel} aborted`);
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
function isDockerSocketPath(p) {
|
|
625
|
+
const lower = p.toLowerCase();
|
|
626
|
+
return lower.includes('docker.sock') || lower.includes('podman.sock') || lower.includes('containerd.sock');
|
|
627
|
+
}
|
|
628
|
+
function scanMountTreeForSocketsAndEscapesSync(canonicalMountRoot, forbiddenCanonicalRoots, deadlineChecker, signal) {
|
|
629
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, 'toolchain mount scan', signal);
|
|
630
|
+
let scannedEntries = 0;
|
|
631
|
+
const rootStat = lstatSync(canonicalMountRoot);
|
|
632
|
+
if (rootStat.isSocket() || isDockerSocketPath(canonicalMountRoot)) {
|
|
633
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `toolchain mount "${canonicalMountRoot}" must not be a socket`);
|
|
634
|
+
}
|
|
635
|
+
if (!rootStat.isDirectory() && !rootStat.isFile()) {
|
|
636
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `toolchain mount "${canonicalMountRoot}" must be a directory or regular file`);
|
|
637
|
+
}
|
|
638
|
+
if (rootStat.isFile()) {
|
|
639
|
+
return;
|
|
640
|
+
}
|
|
641
|
+
const walk = (dirPath, depth) => {
|
|
642
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, 'toolchain mount scan', signal);
|
|
643
|
+
if (depth > MAX_TOOLCHAIN_SCAN_DEPTH) {
|
|
644
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `toolchain mount "${canonicalMountRoot}" exceeds scan depth limit`);
|
|
645
|
+
}
|
|
646
|
+
let dirents;
|
|
647
|
+
try {
|
|
648
|
+
dirents = readdirSync(dirPath, { withFileTypes: true });
|
|
649
|
+
}
|
|
650
|
+
catch {
|
|
651
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `unable to inspect toolchain mount directory "${dirPath}"`);
|
|
652
|
+
}
|
|
653
|
+
for (const dirent of dirents) {
|
|
654
|
+
scannedEntries += 1;
|
|
655
|
+
if ((scannedEntries & 0xff) === 0) {
|
|
656
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, 'toolchain mount scan', signal);
|
|
657
|
+
}
|
|
658
|
+
if (scannedEntries > MAX_TOOLCHAIN_SCAN_ENTRIES) {
|
|
659
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `toolchain mount "${canonicalMountRoot}" exceeds ${MAX_TOOLCHAIN_SCAN_ENTRIES} scanned entries`);
|
|
660
|
+
}
|
|
661
|
+
const entryPath = join(dirPath, dirent.name);
|
|
662
|
+
if (isDockerSocketPath(entryPath) || dirent.isSocket()) {
|
|
663
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `toolchain mount "${canonicalMountRoot}" contains forbidden Unix socket "${entryPath}"`);
|
|
664
|
+
}
|
|
665
|
+
if (dirent.isSymbolicLink()) {
|
|
666
|
+
let resolvedLinkTarget;
|
|
667
|
+
try {
|
|
668
|
+
resolvedLinkTarget = realpathSync(entryPath);
|
|
669
|
+
}
|
|
670
|
+
catch {
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
if (isDockerSocketPath(resolvedLinkTarget)) {
|
|
674
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `toolchain mount "${canonicalMountRoot}" contains symlink to container socket`);
|
|
675
|
+
}
|
|
676
|
+
const targetStat = statSync(resolvedLinkTarget, { throwIfNoEntry: false });
|
|
677
|
+
if (targetStat?.isSocket()) {
|
|
678
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `toolchain mount "${canonicalMountRoot}" contains symlink to Unix socket "${resolvedLinkTarget}"`);
|
|
679
|
+
}
|
|
680
|
+
for (const forbidden of forbiddenCanonicalRoots) {
|
|
681
|
+
if (pathsOverlap(resolvedLinkTarget, forbidden)) {
|
|
682
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `toolchain mount "${canonicalMountRoot}" contains symlink overlapping protected path "${forbidden}"`);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
continue;
|
|
686
|
+
}
|
|
687
|
+
if (dirent.isDirectory()) {
|
|
688
|
+
walk(entryPath, depth + 1);
|
|
689
|
+
continue;
|
|
690
|
+
}
|
|
691
|
+
if (!dirent.isFile()) {
|
|
692
|
+
const st = lstatSync(entryPath);
|
|
693
|
+
if (st.isSocket()) {
|
|
694
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `toolchain mount "${canonicalMountRoot}" contains forbidden Unix socket "${entryPath}"`);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
};
|
|
699
|
+
walk(canonicalMountRoot, 0);
|
|
700
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, 'toolchain mount scan', signal);
|
|
701
|
+
}
|
|
702
|
+
function validateAndCanonicalizeToolchainMountsSync(options) {
|
|
703
|
+
assertLeaseDeadlineNotExpired(options.deadlineChecker, 'toolchain mount validation', options.signal);
|
|
704
|
+
const forbiddenExpanded = new Set(FORBIDDEN_MOUNT_ROOTS);
|
|
705
|
+
for (const fp of options.forbiddenPaths) {
|
|
706
|
+
for (const v of canonicalOrResolvedSync(fp)) {
|
|
707
|
+
forbiddenExpanded.add(v);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
const nonRootForbidden = [...forbiddenExpanded].filter(p => p !== '/');
|
|
711
|
+
const canonicalToolchains = [];
|
|
712
|
+
for (const rawTc of options.toolchainPaths) {
|
|
713
|
+
assertLeaseDeadlineNotExpired(options.deadlineChecker, 'toolchain mount validation', options.signal);
|
|
714
|
+
if (typeof rawTc !== 'string' || !isAbsolute(rawTc) || /[\0\r\n,"]/.test(rawTc) || hasLoneSurrogate(rawTc)) {
|
|
715
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `invalid toolchain mount path "${String(rawTc)}"`);
|
|
716
|
+
}
|
|
717
|
+
if (isDockerSocketPath(rawTc)) {
|
|
718
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'mounting container runtime sockets is forbidden');
|
|
719
|
+
}
|
|
720
|
+
const resolvedTc = resolve(rawTc);
|
|
721
|
+
if (FORBIDDEN_MOUNT_ROOTS.includes(resolvedTc)) {
|
|
722
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `forbidden system root toolchain mount "${resolvedTc}"`);
|
|
723
|
+
}
|
|
724
|
+
const existsOnDisk = existsSync(resolvedTc);
|
|
725
|
+
if (options.requireExistingOnDisk && !existsOnDisk) {
|
|
726
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `configured toolchain path "${resolvedTc}" does not exist`);
|
|
727
|
+
}
|
|
728
|
+
const candidateVariants = canonicalOrResolvedSync(resolvedTc);
|
|
729
|
+
const canonicalTc = existsOnDisk ? realpathSync(resolvedTc) : resolvedTc;
|
|
730
|
+
if (FORBIDDEN_MOUNT_ROOTS.includes(canonicalTc)) {
|
|
731
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `forbidden canonical toolchain mount "${canonicalTc}"`);
|
|
732
|
+
}
|
|
733
|
+
for (const variant of candidateVariants) {
|
|
734
|
+
for (const forbidden of nonRootForbidden) {
|
|
735
|
+
if (pathsOverlap(variant, forbidden)) {
|
|
736
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `toolchain mount "${rawTc}" overlaps protected or job-private path "${forbidden}"`);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
for (const prior of canonicalToolchains) {
|
|
741
|
+
if (pathsOverlap(canonicalTc, prior)) {
|
|
742
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `overlapping toolchain mount paths "${canonicalTc}" and "${prior}" are forbidden`);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (existsOnDisk) {
|
|
746
|
+
scanMountTreeForSocketsAndEscapesSync(canonicalTc, nonRootForbidden, options.deadlineChecker, options.signal);
|
|
747
|
+
}
|
|
748
|
+
canonicalToolchains.push(canonicalTc);
|
|
749
|
+
}
|
|
750
|
+
return Object.freeze(canonicalToolchains);
|
|
751
|
+
}
|
|
752
|
+
export function resolveTrustedDockerExecutable(host, testOnlyTrustedRoot) {
|
|
753
|
+
const probe = host?.probeExecutables ?? true;
|
|
754
|
+
const verifyOpts = testOnlyTrustedRoot !== undefined ? { _testOnlyTrustedRoot: testOnlyTrustedRoot } : {};
|
|
755
|
+
if (host?.dockerExecutable !== undefined) {
|
|
756
|
+
const resolvedExplicit = resolve(host.dockerExecutable);
|
|
757
|
+
const effectiveAllowlist = testOnlyTrustedRoot !== undefined
|
|
758
|
+
? [...TRUSTED_DOCKER_PATHS, resolvedExplicit]
|
|
759
|
+
: TRUSTED_DOCKER_PATHS;
|
|
760
|
+
if (!effectiveAllowlist.includes(resolvedExplicit)) {
|
|
761
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `untrusted docker executable "${host.dockerExecutable}"`);
|
|
762
|
+
}
|
|
763
|
+
if (!probe && testOnlyTrustedRoot === undefined) {
|
|
764
|
+
return resolvedExplicit;
|
|
765
|
+
}
|
|
766
|
+
return verifyTrustedSystemExecutableSync(resolvedExplicit, effectiveAllowlist, verifyOpts, 'docker');
|
|
767
|
+
}
|
|
768
|
+
if (!probe) {
|
|
769
|
+
return TRUSTED_DOCKER_PATHS[0];
|
|
770
|
+
}
|
|
771
|
+
let lastErr = null;
|
|
772
|
+
for (const candidate of TRUSTED_DOCKER_PATHS) {
|
|
773
|
+
try {
|
|
774
|
+
return verifyTrustedSystemExecutableSync(candidate, TRUSTED_DOCKER_PATHS, verifyOpts, 'docker');
|
|
775
|
+
}
|
|
776
|
+
catch (err) {
|
|
777
|
+
lastErr = err;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
if (lastErr instanceof HardwareRunnerError) {
|
|
781
|
+
throw lastErr;
|
|
782
|
+
}
|
|
783
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'no trusted root-owned docker executable found on worker host');
|
|
784
|
+
}
|
|
785
|
+
function buildVisibleDevicesCsv(deviceCount) {
|
|
786
|
+
return Array.from({ length: deviceCount }, (_, idx) => String(idx)).join(',');
|
|
787
|
+
}
|
|
788
|
+
function validateExplicitDeviceIndices(explicitIndices, expectedCount, maxUpperExclusive = 64) {
|
|
789
|
+
if (explicitIndices.length !== expectedCount) {
|
|
790
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `allocatedDeviceIndices count (${explicitIndices.length}) must equal deviceCount (${expectedCount})`);
|
|
791
|
+
}
|
|
792
|
+
const seen = new Set();
|
|
793
|
+
const out = [];
|
|
794
|
+
for (const idx of explicitIndices) {
|
|
795
|
+
if (!Number.isSafeInteger(idx) || Object.is(idx, -0) || idx < 0 || idx >= maxUpperExclusive) {
|
|
796
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `invalid allocated device index ${String(idx)}`);
|
|
797
|
+
}
|
|
798
|
+
if (seen.has(idx)) {
|
|
799
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `duplicate allocated device index ${idx}`);
|
|
800
|
+
}
|
|
801
|
+
seen.add(idx);
|
|
802
|
+
out.push(idx);
|
|
803
|
+
}
|
|
804
|
+
return Object.freeze(out);
|
|
805
|
+
}
|
|
806
|
+
function discoverHostRocmRenderMinorsSync(sysfsRoot) {
|
|
807
|
+
const renderNodeRe = /^renderD([0-9]{1,6})$/;
|
|
808
|
+
const discoveredMinors = [];
|
|
809
|
+
// 1. Prefer KFD topology GPU nodes (drm_render_minor > 0), ordered by KFD node ID.
|
|
810
|
+
const kfdNodesDir = join(sysfsRoot, 'class', 'kfd', 'kfd', 'topology', 'nodes');
|
|
811
|
+
if (existsSync(kfdNodesDir)) {
|
|
812
|
+
const nodeIds = readdirSync(kfdNodesDir)
|
|
813
|
+
.filter(n => /^[0-9]+$/.test(n))
|
|
814
|
+
.map(n => Number.parseInt(n, 10))
|
|
815
|
+
.sort((a, b) => a - b);
|
|
816
|
+
for (const id of nodeIds) {
|
|
817
|
+
try {
|
|
818
|
+
const props = readFileSync(join(kfdNodesDir, String(id), 'properties'), 'utf8');
|
|
819
|
+
const m = /^drm_render_minor\s+([1-9][0-9]*)\s*$/m.exec(props);
|
|
820
|
+
if (m !== null) {
|
|
821
|
+
discoveredMinors.push(Number.parseInt(m[1], 10));
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
catch {
|
|
825
|
+
// Ignore unreadable topology node entry.
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
// 2. Fallback to /sys/class/drm/renderD* filtered to AMD vendor 0x1002.
|
|
830
|
+
if (discoveredMinors.length === 0) {
|
|
831
|
+
const sysDrmDir = join(sysfsRoot, 'class', 'drm');
|
|
832
|
+
if (existsSync(sysDrmDir)) {
|
|
833
|
+
const candidates = readdirSync(sysDrmDir)
|
|
834
|
+
.map(name => renderNodeRe.exec(name))
|
|
835
|
+
.filter((m) => m !== null)
|
|
836
|
+
.map(m => Number.parseInt(m[1], 10))
|
|
837
|
+
.sort((a, b) => a - b);
|
|
838
|
+
for (const minor of candidates) {
|
|
839
|
+
try {
|
|
840
|
+
const vendor = readFileSync(join(sysDrmDir, `renderD${minor}`, 'device', 'vendor'), 'utf8').trim().toLowerCase();
|
|
841
|
+
if (vendor === '0x1002') {
|
|
842
|
+
discoveredMinors.push(minor);
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
catch {
|
|
846
|
+
// Ignore non-PCIe or unreadable DRM entry.
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
return [...new Set(discoveredMinors)];
|
|
852
|
+
}
|
|
853
|
+
function resolveAllocatedRocmDevicesSync(options) {
|
|
854
|
+
const devRoot = resolve(options.devRoot ?? '/dev');
|
|
855
|
+
const sysfsRoot = resolve(options.sysfsRoot ?? '/sys');
|
|
856
|
+
const kfdPath = join(devRoot, 'kfd');
|
|
857
|
+
const renderNodeRe = /^renderD([0-9]{1,6})$/;
|
|
858
|
+
const groupSet = new Set();
|
|
859
|
+
const assertCharDevice = (p) => {
|
|
860
|
+
let st;
|
|
861
|
+
try {
|
|
862
|
+
st = lstatSync(p);
|
|
863
|
+
}
|
|
864
|
+
catch {
|
|
865
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `required ROCm device node "${p}" does not exist`);
|
|
866
|
+
}
|
|
867
|
+
if (st.isSymbolicLink() || !st.isCharacterDevice()) {
|
|
868
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `ROCm device node "${p}" must be a non-symlink character device`);
|
|
869
|
+
}
|
|
870
|
+
if (st.gid > 0) {
|
|
871
|
+
groupSet.add(String(st.gid));
|
|
872
|
+
}
|
|
873
|
+
};
|
|
874
|
+
const uniqueMinors = discoverHostRocmRenderMinorsSync(sysfsRoot);
|
|
875
|
+
if (options.explicitNodes !== undefined) {
|
|
876
|
+
if (options.explicitNodes.length !== options.deviceCount) {
|
|
877
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `allocatedDeviceNodes count (${options.explicitNodes.length}) must equal deviceCount (${options.deviceCount})`);
|
|
878
|
+
}
|
|
879
|
+
const seen = new Set();
|
|
880
|
+
const validated = [];
|
|
881
|
+
const parsedMinors = [];
|
|
882
|
+
for (const rawNode of options.explicitNodes) {
|
|
883
|
+
if (typeof rawNode !== 'string' || !isAbsolute(rawNode) || /[\0\r\n,"]/.test(rawNode)) {
|
|
884
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `invalid ROCm device node "${String(rawNode)}"`);
|
|
885
|
+
}
|
|
886
|
+
const resolvedNode = resolve(rawNode);
|
|
887
|
+
const expectedDriDir = join(devRoot, 'dri');
|
|
888
|
+
const leafName = resolvedNode.slice(expectedDriDir.length + 1);
|
|
889
|
+
const minorMatch = renderNodeRe.exec(leafName);
|
|
890
|
+
if (dirname(resolvedNode) !== expectedDriDir || minorMatch === null) {
|
|
891
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `ROCm device node "${rawNode}" must be an individual ${expectedDriDir}/renderD<N> node (never /dev/dri directory)`);
|
|
892
|
+
}
|
|
893
|
+
if (seen.has(resolvedNode)) {
|
|
894
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `duplicate ROCm device node "${resolvedNode}"`);
|
|
895
|
+
}
|
|
896
|
+
seen.add(resolvedNode);
|
|
897
|
+
if (options.verifyCharDevices) {
|
|
898
|
+
assertCharDevice(resolvedNode);
|
|
899
|
+
}
|
|
900
|
+
validated.push(resolvedNode);
|
|
901
|
+
parsedMinors.push(Number.parseInt(minorMatch[1], 10));
|
|
902
|
+
}
|
|
903
|
+
let resolvedIndices;
|
|
904
|
+
if (uniqueMinors.length > 0) {
|
|
905
|
+
const mapped = parsedMinors.map((minor, pos) => {
|
|
906
|
+
const gpuIdx = uniqueMinors.indexOf(minor);
|
|
907
|
+
if (gpuIdx < 0) {
|
|
908
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `allocated ROCm device node "${validated[pos]}" could not be mapped to an AMD GPU in sysfs/KFD`);
|
|
909
|
+
}
|
|
910
|
+
return gpuIdx;
|
|
911
|
+
});
|
|
912
|
+
if (options.explicitIndices !== undefined) {
|
|
913
|
+
const checkedExplicit = validateExplicitDeviceIndices(options.explicitIndices, options.deviceCount, uniqueMinors.length);
|
|
914
|
+
for (let i = 0; i < mapped.length; i += 1) {
|
|
915
|
+
if (mapped[i] !== checkedExplicit[i]) {
|
|
916
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `allocatedDeviceNodes "${validated[i]}" (GPU ${mapped[i]}) conflicts with allocatedDeviceIndices (${checkedExplicit[i]})`);
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
resolvedIndices = Object.freeze(mapped);
|
|
921
|
+
}
|
|
922
|
+
else if (options.explicitIndices !== undefined) {
|
|
923
|
+
resolvedIndices = validateExplicitDeviceIndices(options.explicitIndices, options.deviceCount, 64);
|
|
924
|
+
}
|
|
925
|
+
else if (options.requireIndexMapping === true) {
|
|
926
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'unable to map allocatedDeviceNodes to physical ROCm GPU indices via sysfs/KFD');
|
|
927
|
+
}
|
|
928
|
+
if (options.verifyCharDevices) {
|
|
929
|
+
assertCharDevice(kfdPath);
|
|
930
|
+
}
|
|
931
|
+
else {
|
|
932
|
+
groupSet.add('video');
|
|
933
|
+
groupSet.add('render');
|
|
934
|
+
}
|
|
935
|
+
const groupArgs = [];
|
|
936
|
+
for (const grp of groupSet) {
|
|
937
|
+
groupArgs.push('--group-add', grp);
|
|
938
|
+
}
|
|
939
|
+
return {
|
|
940
|
+
kfdPath,
|
|
941
|
+
renderNodes: validated,
|
|
942
|
+
groupArgs,
|
|
943
|
+
...(resolvedIndices !== undefined ? { deviceIndices: resolvedIndices } : {}),
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
if (options.verifyCharDevices) {
|
|
947
|
+
assertCharDevice(kfdPath);
|
|
948
|
+
}
|
|
949
|
+
if (uniqueMinors.length < options.deviceCount) {
|
|
950
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `unable to isolate ${options.deviceCount} allocated ROCm renderD device node(s) on host (found ${uniqueMinors.length})`);
|
|
951
|
+
}
|
|
952
|
+
const chosenIndices = options.explicitIndices !== undefined
|
|
953
|
+
? validateExplicitDeviceIndices(options.explicitIndices, options.deviceCount, uniqueMinors.length)
|
|
954
|
+
: Object.freeze(Array.from({ length: options.deviceCount }, (_, idx) => idx));
|
|
955
|
+
const renderNodes = chosenIndices.map(gpuIdx => {
|
|
956
|
+
const minor = uniqueMinors[gpuIdx];
|
|
957
|
+
const nodePath = join(devRoot, 'dri', `renderD${minor}`);
|
|
958
|
+
if (options.verifyCharDevices) {
|
|
959
|
+
assertCharDevice(nodePath);
|
|
960
|
+
}
|
|
961
|
+
return nodePath;
|
|
962
|
+
});
|
|
963
|
+
if (groupSet.size === 0) {
|
|
964
|
+
groupSet.add('video');
|
|
965
|
+
groupSet.add('render');
|
|
966
|
+
}
|
|
967
|
+
const groupArgs = [];
|
|
968
|
+
for (const grp of groupSet) {
|
|
969
|
+
groupArgs.push('--group-add', grp);
|
|
970
|
+
}
|
|
971
|
+
return { kfdPath, renderNodes, groupArgs, deviceIndices: chosenIndices };
|
|
972
|
+
}
|
|
973
|
+
/**
|
|
974
|
+
* Deterministic Docker Stage B seccomp JSON profile denying `socket`, `socketpair`, `connect`,
|
|
975
|
+
* `bind`, `listen`, `accept`, `accept4`, and privileged kernel syscalls with `EPERM` (`errnoRet: 1`).
|
|
976
|
+
*/
|
|
977
|
+
export function buildDockerStageBSeccompProfileJson() {
|
|
978
|
+
const blockedNames = [
|
|
979
|
+
...SECCOMP_BLOCKED_SYSCALLS,
|
|
980
|
+
'acct',
|
|
981
|
+
'add_key',
|
|
982
|
+
'clock_adjtime',
|
|
983
|
+
'clock_settime',
|
|
984
|
+
'delete_module',
|
|
985
|
+
'finit_module',
|
|
986
|
+
'init_module',
|
|
987
|
+
'ioperm',
|
|
988
|
+
'iopl',
|
|
989
|
+
'kcmp',
|
|
990
|
+
'lookup_dcookie',
|
|
991
|
+
'move_pages',
|
|
992
|
+
'name_to_handle_at',
|
|
993
|
+
'open_by_handle_at',
|
|
994
|
+
'personality',
|
|
995
|
+
'process_vm_readv',
|
|
996
|
+
'process_vm_writev',
|
|
997
|
+
'quotactl',
|
|
998
|
+
'reboot',
|
|
999
|
+
'request_key',
|
|
1000
|
+
'setns',
|
|
1001
|
+
'settimeofday',
|
|
1002
|
+
'swapon',
|
|
1003
|
+
'swapoff',
|
|
1004
|
+
'syslog',
|
|
1005
|
+
'unshare',
|
|
1006
|
+
'uselib',
|
|
1007
|
+
'socket',
|
|
1008
|
+
'socketpair',
|
|
1009
|
+
'connect',
|
|
1010
|
+
'bind',
|
|
1011
|
+
'listen',
|
|
1012
|
+
'accept',
|
|
1013
|
+
'accept4',
|
|
1014
|
+
];
|
|
1015
|
+
const uniqueNames = [...new Set(blockedNames)].sort(compareUtf16);
|
|
1016
|
+
return JSON.stringify({
|
|
1017
|
+
defaultAction: 'SCMP_ACT_ALLOW',
|
|
1018
|
+
syscalls: [
|
|
1019
|
+
{
|
|
1020
|
+
names: uniqueNames,
|
|
1021
|
+
action: 'SCMP_ACT_ERRNO',
|
|
1022
|
+
errnoRet: 1,
|
|
1023
|
+
},
|
|
1024
|
+
],
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Compile deterministic classic BPF `struct sock_filter` binary (`bwrap --seccomp <fd>`)
|
|
1029
|
+
* denying `socket`, `socketpair`, `connect`, `bind`, `listen`, `accept`, `accept4`, x32 ABI,
|
|
1030
|
+
* and all `SECCOMP_BLOCKED_SYSCALLS` at the Linux kernel boundary (`EPERM`).
|
|
1031
|
+
*/
|
|
1032
|
+
export function compileStrictSocketDenySeccompBpf(arch) {
|
|
1033
|
+
let auditArch;
|
|
1034
|
+
let blockedNrs;
|
|
1035
|
+
let blockX32Abi;
|
|
1036
|
+
if (arch === 'x64') {
|
|
1037
|
+
auditArch = 0xc000003e;
|
|
1038
|
+
blockedNrs = STRICT_SECCOMP_BLOCKED_X64;
|
|
1039
|
+
blockX32Abi = true;
|
|
1040
|
+
}
|
|
1041
|
+
else if (arch === 'arm64') {
|
|
1042
|
+
auditArch = 0xc00000b7;
|
|
1043
|
+
blockedNrs = STRICT_SECCOMP_BLOCKED_ARM64;
|
|
1044
|
+
blockX32Abi = false;
|
|
1045
|
+
}
|
|
1046
|
+
else {
|
|
1047
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `unsupported Linux seccomp architecture "${arch}"`);
|
|
1048
|
+
}
|
|
1049
|
+
const instructions = [
|
|
1050
|
+
[0x20, 0, 0, 4],
|
|
1051
|
+
[0x15, 1, 0, auditArch],
|
|
1052
|
+
[0x06, 0, 0, 0x00050001],
|
|
1053
|
+
[0x20, 0, 0, 0],
|
|
1054
|
+
...(blockX32Abi ? [[0x35, blockedNrs.length + 1, 0, 0x40000000]] : []),
|
|
1055
|
+
...blockedNrs.map((nr, i) => [
|
|
1056
|
+
0x15,
|
|
1057
|
+
blockedNrs.length - i,
|
|
1058
|
+
0,
|
|
1059
|
+
nr,
|
|
1060
|
+
]),
|
|
1061
|
+
[0x06, 0, 0, 0x7fff0000],
|
|
1062
|
+
[0x06, 0, 0, 0x00050001],
|
|
1063
|
+
];
|
|
1064
|
+
const buf = Buffer.alloc(instructions.length * 8);
|
|
1065
|
+
for (let idx = 0; idx < instructions.length; idx += 1) {
|
|
1066
|
+
const [code, jt, jf, k] = instructions[idx];
|
|
1067
|
+
const off = idx * 8;
|
|
1068
|
+
buf.writeUInt16LE(code, off);
|
|
1069
|
+
buf.writeUInt8(jt, off + 2);
|
|
1070
|
+
buf.writeUInt8(jf, off + 3);
|
|
1071
|
+
buf.writeUInt32LE(k >>> 0, off + 4);
|
|
1072
|
+
}
|
|
1073
|
+
return buf;
|
|
1074
|
+
}
|
|
1075
|
+
/**
|
|
1076
|
+
* Compile hardened `docker run` arguments with `--network none`, `--read-only`, `--user <uid>:<gid>`,
|
|
1077
|
+
* disjoint socket-free mount trees, Stage B socket-denial seccomp, and exact allocated GPU/NPU devices.
|
|
1078
|
+
*/
|
|
1079
|
+
export function compileDockerSandboxCommand(input) {
|
|
1080
|
+
const executablePath = resolveTrustedDockerExecutable(input.host, input._testOnlyTrustedDockerRoot);
|
|
1081
|
+
const probeHost = input.host?.probeExecutables ?? true;
|
|
1082
|
+
if (typeof input.dockerImage !== 'string'
|
|
1083
|
+
|| input.dockerImage.length < 1
|
|
1084
|
+
|| input.dockerImage.length > 256
|
|
1085
|
+
|| input.dockerImage.startsWith('-')
|
|
1086
|
+
|| /\s/.test(input.dockerImage)
|
|
1087
|
+
|| !PRINTABLE_ASCII_RE.test(input.dockerImage)) {
|
|
1088
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'invalid dockerImage for hardware sandbox');
|
|
1089
|
+
}
|
|
1090
|
+
if (typeof input.containerName !== 'string'
|
|
1091
|
+
|| !/^[A-Za-z0-9][A-Za-z0-9_.-]{1,120}$/.test(input.containerName)) {
|
|
1092
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'invalid docker containerName');
|
|
1093
|
+
}
|
|
1094
|
+
const stagePaths = [
|
|
1095
|
+
input.stageAOutDir,
|
|
1096
|
+
...(input.candidateDir !== undefined ? [input.candidateDir] : []),
|
|
1097
|
+
...(input.workloadDir !== undefined ? [input.workloadDir] : []),
|
|
1098
|
+
];
|
|
1099
|
+
for (const p of stagePaths) {
|
|
1100
|
+
if (typeof p !== 'string' || !isAbsolute(p) || /[\0\r\n,"]/.test(p)) {
|
|
1101
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `invalid host mount path "${String(p)}" for docker sandbox`);
|
|
1102
|
+
}
|
|
1103
|
+
if (isDockerSocketPath(p)) {
|
|
1104
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'mounting docker/container runtime sockets into candidate sandboxes is forbidden');
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
const deadlineChecker = resolveMonotonicDeadlineChecker(input);
|
|
1108
|
+
const canonicalToolchains = validateAndCanonicalizeToolchainMountsSync({
|
|
1109
|
+
toolchainPaths: input.toolchainPaths ?? [],
|
|
1110
|
+
forbiddenPaths: [...stagePaths, ...(input.forbiddenHostPaths ?? [])],
|
|
1111
|
+
requireExistingOnDisk: probeHost,
|
|
1112
|
+
...(deadlineChecker !== undefined ? { deadlineChecker } : {}),
|
|
1113
|
+
...(input.signal !== undefined ? { signal: input.signal } : {}),
|
|
1114
|
+
});
|
|
1115
|
+
for (const arg of [input.command, ...(input.args ?? [])]) {
|
|
1116
|
+
if (typeof arg !== 'string' || /[\0\r\n]/.test(arg)) {
|
|
1117
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'invalid command argument for docker sandbox');
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
const uid = input.containerUser?.uid ?? (typeof process.getuid === 'function' ? process.getuid() : 0);
|
|
1121
|
+
const gid = input.containerUser?.gid ?? (typeof process.getgid === 'function' ? process.getgid() : 0);
|
|
1122
|
+
if (!Number.isSafeInteger(uid) || uid < 0 || uid > 4_294_967_294
|
|
1123
|
+
|| !Number.isSafeInteger(gid) || gid < 0 || gid > 4_294_967_294) {
|
|
1124
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'invalid container UID/GID for docker sandbox');
|
|
1125
|
+
}
|
|
1126
|
+
const deviceCount = input.targetHardware.deviceCount ?? 1;
|
|
1127
|
+
if (!Number.isSafeInteger(deviceCount) || deviceCount < 1 || deviceCount > 64) {
|
|
1128
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'invalid targetHardware.deviceCount for docker sandbox');
|
|
1129
|
+
}
|
|
1130
|
+
const visibleCsv = buildVisibleDevicesCsv(deviceCount);
|
|
1131
|
+
const accel = input.targetHardware.accelerator.toLowerCase();
|
|
1132
|
+
const gpuArgs = [];
|
|
1133
|
+
if (accel.startsWith('sm_')) {
|
|
1134
|
+
const selectedCuda = input.allocatedDeviceIndices !== undefined
|
|
1135
|
+
? validateExplicitDeviceIndices(input.allocatedDeviceIndices, deviceCount, 64)
|
|
1136
|
+
: Array.from({ length: deviceCount }, (_, idx) => idx);
|
|
1137
|
+
const selectedCsv = selectedCuda.map(String).join(',');
|
|
1138
|
+
const gpuSpec = selectedCuda.length === 1 ? `device=${selectedCuda[0]}` : `"device=${selectedCsv}"`;
|
|
1139
|
+
gpuArgs.push('--gpus', gpuSpec);
|
|
1140
|
+
gpuArgs.push('-e', `CUDA_VISIBLE_DEVICES=${visibleCsv}`);
|
|
1141
|
+
}
|
|
1142
|
+
else if (accel.startsWith('gfx')) {
|
|
1143
|
+
const rocmDevices = resolveAllocatedRocmDevicesSync({
|
|
1144
|
+
deviceCount,
|
|
1145
|
+
...(input.allocatedDeviceNodes !== undefined ? { explicitNodes: input.allocatedDeviceNodes } : {}),
|
|
1146
|
+
...(input.allocatedDeviceIndices !== undefined ? { explicitIndices: input.allocatedDeviceIndices } : {}),
|
|
1147
|
+
...(input.sysfsRoot !== undefined ? { sysfsRoot: input.sysfsRoot } : {}),
|
|
1148
|
+
...(input.devRoot !== undefined ? { devRoot: input.devRoot } : {}),
|
|
1149
|
+
verifyCharDevices: probeHost,
|
|
1150
|
+
});
|
|
1151
|
+
gpuArgs.push('--device', rocmDevices.kfdPath);
|
|
1152
|
+
for (const renderNode of rocmDevices.renderNodes) {
|
|
1153
|
+
gpuArgs.push('--device', renderNode);
|
|
1154
|
+
}
|
|
1155
|
+
gpuArgs.push(...rocmDevices.groupArgs);
|
|
1156
|
+
gpuArgs.push('-e', `ROCR_VISIBLE_DEVICES=${visibleCsv}`, '-e', `HIP_VISIBLE_DEVICES=${visibleCsv}`);
|
|
1157
|
+
}
|
|
1158
|
+
else if (accel.startsWith('ascend')) {
|
|
1159
|
+
const devRoot = resolve(input.devRoot ?? '/dev');
|
|
1160
|
+
const selectedAscend = input.allocatedDeviceIndices !== undefined
|
|
1161
|
+
? validateExplicitDeviceIndices(input.allocatedDeviceIndices, deviceCount, 64)
|
|
1162
|
+
: Array.from({ length: deviceCount }, (_, idx) => idx);
|
|
1163
|
+
const ascendNodes = [
|
|
1164
|
+
...selectedAscend.map(idx => join(devRoot, `davinci${idx}`)),
|
|
1165
|
+
join(devRoot, 'davinci_manager'),
|
|
1166
|
+
join(devRoot, 'devmm_svm'),
|
|
1167
|
+
join(devRoot, 'hisi_hdc'),
|
|
1168
|
+
];
|
|
1169
|
+
if (probeHost) {
|
|
1170
|
+
for (const devNode of ascendNodes) {
|
|
1171
|
+
let st;
|
|
1172
|
+
try {
|
|
1173
|
+
st = lstatSync(devNode);
|
|
1174
|
+
}
|
|
1175
|
+
catch {
|
|
1176
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `required Ascend device node "${devNode}" does not exist`);
|
|
1177
|
+
}
|
|
1178
|
+
if (st.isSymbolicLink() || !st.isCharacterDevice()) {
|
|
1179
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `Ascend device node "${devNode}" is not a character device`);
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
for (const devNode of ascendNodes) {
|
|
1184
|
+
gpuArgs.push('--device', devNode);
|
|
1185
|
+
}
|
|
1186
|
+
gpuArgs.push('-e', `ASCEND_RT_VISIBLE_DEVICES=${visibleCsv}`);
|
|
1187
|
+
}
|
|
1188
|
+
else {
|
|
1189
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `unsupported accelerator "${input.targetHardware.accelerator}" for docker GPU isolation`);
|
|
1190
|
+
}
|
|
1191
|
+
const securityArgs = ['--security-opt', 'no-new-privileges:true'];
|
|
1192
|
+
if (typeof input.seccompProfilePath !== 'string'
|
|
1193
|
+
|| !isAbsolute(input.seccompProfilePath)
|
|
1194
|
+
|| /[\0\r\n,"]/.test(input.seccompProfilePath)) {
|
|
1195
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `Stage ${input.stage} docker sandbox requires an explicit socket-denial seccompProfilePath`);
|
|
1196
|
+
}
|
|
1197
|
+
const resolvedSeccomp = resolve(input.seccompProfilePath);
|
|
1198
|
+
if (probeHost) {
|
|
1199
|
+
const st = lstatSync(resolvedSeccomp, { throwIfNoEntry: false });
|
|
1200
|
+
if (!st || st.isSymbolicLink() || !st.isFile()) {
|
|
1201
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `Stage ${input.stage} seccomp profile must be an existing regular file`);
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
securityArgs.push('--security-opt', `seccomp=${resolvedSeccomp}`);
|
|
1205
|
+
const mountArgs = [];
|
|
1206
|
+
if (input.stage === 'A') {
|
|
1207
|
+
if (input.candidateDir === undefined) {
|
|
1208
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'Stage A docker sandbox requires candidateDir');
|
|
1209
|
+
}
|
|
1210
|
+
if (input.workloadDir !== undefined) {
|
|
1211
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'Stage A docker sandbox must NEVER mount held_out_workloads');
|
|
1212
|
+
}
|
|
1213
|
+
mountArgs.push('--mount', `type=bind,src=${resolve(input.candidateDir)},dst=/workspace/candidate,readonly`);
|
|
1214
|
+
mountArgs.push('--mount', `type=bind,src=${resolve(input.stageAOutDir)},dst=/workspace/stage-a-out`);
|
|
1215
|
+
}
|
|
1216
|
+
else {
|
|
1217
|
+
if (input.workloadDir === undefined) {
|
|
1218
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'Stage B docker sandbox requires workloadDir');
|
|
1219
|
+
}
|
|
1220
|
+
if (input.candidateDir !== undefined) {
|
|
1221
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'Stage B docker sandbox must not mount raw Stage A candidateDir');
|
|
1222
|
+
}
|
|
1223
|
+
mountArgs.push('--mount', `type=bind,src=${resolve(input.stageAOutDir)},dst=/workspace/stage-a-out,readonly`);
|
|
1224
|
+
mountArgs.push('--mount', `type=bind,src=${resolve(input.workloadDir)},dst=/workspace/workload,readonly`);
|
|
1225
|
+
}
|
|
1226
|
+
for (const resolvedTc of canonicalToolchains) {
|
|
1227
|
+
mountArgs.push('--mount', `type=bind,src=${resolvedTc},dst=${resolvedTc},readonly`);
|
|
1228
|
+
}
|
|
1229
|
+
const workdir = input.cwd ?? (input.stage === 'A' ? '/workspace/candidate' : '/workspace/workload');
|
|
1230
|
+
const envArgs = [];
|
|
1231
|
+
const mergedEnv = {
|
|
1232
|
+
HOME: '/scratch',
|
|
1233
|
+
TMPDIR: '/scratch',
|
|
1234
|
+
LANG: 'C.UTF-8',
|
|
1235
|
+
TERM: 'dumb',
|
|
1236
|
+
...(input.env ?? {}),
|
|
1237
|
+
};
|
|
1238
|
+
for (const key of Object.keys(mergedEnv).sort()) {
|
|
1239
|
+
const val = mergedEnv[key];
|
|
1240
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || /[\0\r\n]/.test(val)) {
|
|
1241
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `invalid environment variable "${key}" for docker sandbox`);
|
|
1242
|
+
}
|
|
1243
|
+
envArgs.push('-e', `${key}=${val}`);
|
|
1244
|
+
}
|
|
1245
|
+
const args = [
|
|
1246
|
+
'run',
|
|
1247
|
+
'--rm',
|
|
1248
|
+
'--name', input.containerName,
|
|
1249
|
+
'--init',
|
|
1250
|
+
'--user', `${uid}:${gid}`,
|
|
1251
|
+
'--network', 'none',
|
|
1252
|
+
'--read-only',
|
|
1253
|
+
...securityArgs,
|
|
1254
|
+
'--cap-drop', 'ALL',
|
|
1255
|
+
'--pids-limit', '512',
|
|
1256
|
+
'--ipc', 'private',
|
|
1257
|
+
'--tmpfs', '/scratch:rw,exec,nosuid,nodev,mode=1777,size=268435456',
|
|
1258
|
+
'--tmpfs', '/tmp:rw,nosuid,nodev,size=268435456',
|
|
1259
|
+
...gpuArgs,
|
|
1260
|
+
...mountArgs,
|
|
1261
|
+
...envArgs,
|
|
1262
|
+
'--workdir', workdir,
|
|
1263
|
+
input.dockerImage,
|
|
1264
|
+
input.command,
|
|
1265
|
+
...(input.args ?? []),
|
|
1266
|
+
];
|
|
1267
|
+
return Object.freeze({
|
|
1268
|
+
executablePath,
|
|
1269
|
+
containerName: input.containerName,
|
|
1270
|
+
args: Object.freeze(args),
|
|
1271
|
+
});
|
|
1272
|
+
}
|
|
1273
|
+
function escapeSbplLiteral(p) {
|
|
1274
|
+
if (/[\0\r\n"\\]/.test(p)) {
|
|
1275
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `unsafe path character for seatbelt profile "${p}"`);
|
|
1276
|
+
}
|
|
1277
|
+
return p;
|
|
1278
|
+
}
|
|
1279
|
+
function canonicalizeExistingOrParentSync(rawPath) {
|
|
1280
|
+
const resolved = resolve(rawPath);
|
|
1281
|
+
try {
|
|
1282
|
+
return realpathSync(resolved);
|
|
1283
|
+
}
|
|
1284
|
+
catch {
|
|
1285
|
+
const parent = dirname(resolved);
|
|
1286
|
+
if (parent !== resolved) {
|
|
1287
|
+
try {
|
|
1288
|
+
return join(realpathSync(parent), resolved.slice(parent.length).replace(/^[/\\]+/, ''));
|
|
1289
|
+
}
|
|
1290
|
+
catch {
|
|
1291
|
+
return resolved;
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
return resolved;
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
function buildStrictSeatbeltStageProfile(spec) {
|
|
1298
|
+
const stageAOutReal = canonicalizeExistingOrParentSync(spec.stageAOutDir);
|
|
1299
|
+
const scratchReal = canonicalizeExistingOrParentSync(spec.scratchDir);
|
|
1300
|
+
const candidateReal = spec.candidateDir !== undefined ? canonicalizeExistingOrParentSync(spec.candidateDir) : null;
|
|
1301
|
+
const workloadSnapReal = spec.workloadSnapshotDir !== undefined ? canonicalizeExistingOrParentSync(spec.workloadSnapshotDir) : null;
|
|
1302
|
+
if (spec.stage === 'A' && (candidateReal === null || workloadSnapReal !== null)) {
|
|
1303
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'invalid Stage A native sandbox directory specification');
|
|
1304
|
+
}
|
|
1305
|
+
if (spec.stage === 'B' && (workloadSnapReal === null || candidateReal !== null)) {
|
|
1306
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'invalid Stage B native sandbox directory specification');
|
|
1307
|
+
}
|
|
1308
|
+
const readSubpaths = new Set([
|
|
1309
|
+
'/usr/bin',
|
|
1310
|
+
'/bin',
|
|
1311
|
+
'/sbin',
|
|
1312
|
+
'/usr/sbin',
|
|
1313
|
+
'/private/var/db/dyld',
|
|
1314
|
+
'/private/var/select',
|
|
1315
|
+
stageAOutReal,
|
|
1316
|
+
scratchReal,
|
|
1317
|
+
]);
|
|
1318
|
+
const execMapSubpaths = new Set([
|
|
1319
|
+
'/usr/bin',
|
|
1320
|
+
'/bin',
|
|
1321
|
+
'/sbin',
|
|
1322
|
+
'/usr/sbin',
|
|
1323
|
+
stageAOutReal,
|
|
1324
|
+
scratchReal,
|
|
1325
|
+
]);
|
|
1326
|
+
if (candidateReal !== null) {
|
|
1327
|
+
readSubpaths.add(candidateReal);
|
|
1328
|
+
execMapSubpaths.add(candidateReal);
|
|
1329
|
+
}
|
|
1330
|
+
if (workloadSnapReal !== null) {
|
|
1331
|
+
readSubpaths.add(workloadSnapReal);
|
|
1332
|
+
execMapSubpaths.add(workloadSnapReal);
|
|
1333
|
+
}
|
|
1334
|
+
let allowHomebrewRuntime = false;
|
|
1335
|
+
for (const tc of spec.toolchainPaths) {
|
|
1336
|
+
const realTc = canonicalizeExistingOrParentSync(tc);
|
|
1337
|
+
readSubpaths.add(realTc);
|
|
1338
|
+
execMapSubpaths.add(realTc);
|
|
1339
|
+
if (realTc === '/opt/homebrew' || realTc.startsWith('/opt/homebrew/')) {
|
|
1340
|
+
allowHomebrewRuntime = true;
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
if (allowHomebrewRuntime) {
|
|
1344
|
+
for (const hb of ['/opt/homebrew/Cellar', '/opt/homebrew/opt', '/opt/homebrew/lib', '/opt/homebrew/bin']) {
|
|
1345
|
+
readSubpaths.add(hb);
|
|
1346
|
+
execMapSubpaths.add(hb);
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
const metadataLiterals = new Set(['/', '/private', '/private/var', '/private/var/select', '/private/var/select/sh']);
|
|
1350
|
+
for (const p of readSubpaths) {
|
|
1351
|
+
let cur = dirname(p);
|
|
1352
|
+
while (cur && cur !== '/') {
|
|
1353
|
+
metadataLiterals.add(cur);
|
|
1354
|
+
const next = dirname(cur);
|
|
1355
|
+
if (next === cur)
|
|
1356
|
+
break;
|
|
1357
|
+
cur = next;
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
const deniedExpanded = new Set();
|
|
1361
|
+
for (const dp of spec.explicitDeniedReadPaths) {
|
|
1362
|
+
for (const v of canonicalOrResolvedSync(dp)) {
|
|
1363
|
+
deniedExpanded.add(v);
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
const writableSubpaths = spec.stage === 'A'
|
|
1367
|
+
? [stageAOutReal, scratchReal]
|
|
1368
|
+
: [scratchReal];
|
|
1369
|
+
const lines = [
|
|
1370
|
+
'(version 1)',
|
|
1371
|
+
'(deny default)',
|
|
1372
|
+
'(import "system.sb")',
|
|
1373
|
+
'(allow process-exec)',
|
|
1374
|
+
'(deny process-fork)',
|
|
1375
|
+
'(allow dynamic-code-generation)',
|
|
1376
|
+
'(allow process-info* (target same-sandbox))',
|
|
1377
|
+
'(allow signal (target same-sandbox))',
|
|
1378
|
+
'(allow file-map-executable',
|
|
1379
|
+
...[...execMapSubpaths].sort(compareUtf16).map(p => ` (subpath "${escapeSbplLiteral(p)}")`),
|
|
1380
|
+
')',
|
|
1381
|
+
'(allow file-read-metadata',
|
|
1382
|
+
...[...metadataLiterals].sort(compareUtf16).map(p => ` (literal "${escapeSbplLiteral(p)}")`),
|
|
1383
|
+
...(allowHomebrewRuntime ? [' (subpath "/opt/homebrew")'] : []),
|
|
1384
|
+
')',
|
|
1385
|
+
'(allow file-read*',
|
|
1386
|
+
...[...readSubpaths].sort(compareUtf16).map(p => ` (subpath "${escapeSbplLiteral(p)}")`),
|
|
1387
|
+
...(allowHomebrewRuntime ? [' (regex #"^/opt/homebrew/etc/openssl")'] : []),
|
|
1388
|
+
')',
|
|
1389
|
+
'(deny file-write*)',
|
|
1390
|
+
'(allow file-write*',
|
|
1391
|
+
' (literal "/dev/null")',
|
|
1392
|
+
' (literal "/dev/zero")',
|
|
1393
|
+
' (literal "/dev/dtracehelper")',
|
|
1394
|
+
...writableSubpaths.sort(compareUtf16).map(p => ` (subpath "${escapeSbplLiteral(p)}")`),
|
|
1395
|
+
')',
|
|
1396
|
+
];
|
|
1397
|
+
if (deniedExpanded.size > 0) {
|
|
1398
|
+
lines.push('(deny file-read*');
|
|
1399
|
+
for (const dp of [...deniedExpanded].sort(compareUtf16)) {
|
|
1400
|
+
lines.push(` (subpath "${escapeSbplLiteral(dp)}")`);
|
|
1401
|
+
}
|
|
1402
|
+
lines.push(')');
|
|
1403
|
+
}
|
|
1404
|
+
lines.push('(deny network*)');
|
|
1405
|
+
return `${lines.join('\n')}\n`;
|
|
1406
|
+
}
|
|
1407
|
+
export const LINUX_BWRAP_IMPLICIT_RUNTIME_ROOTS = Object.freeze([
|
|
1408
|
+
'/usr',
|
|
1409
|
+
'/bin',
|
|
1410
|
+
'/sbin',
|
|
1411
|
+
'/lib',
|
|
1412
|
+
'/lib32',
|
|
1413
|
+
'/lib64',
|
|
1414
|
+
'/etc/ld.so.cache',
|
|
1415
|
+
'/etc/ld.so.conf',
|
|
1416
|
+
'/etc/ld.so.conf.d',
|
|
1417
|
+
'/etc/alternatives',
|
|
1418
|
+
]);
|
|
1419
|
+
const LINUX_BWRAP_NARROW_USR_SUBPATHS = Object.freeze([
|
|
1420
|
+
'/usr/bin',
|
|
1421
|
+
'/usr/sbin',
|
|
1422
|
+
'/usr/lib',
|
|
1423
|
+
'/usr/lib32',
|
|
1424
|
+
'/usr/lib64',
|
|
1425
|
+
'/usr/libexec',
|
|
1426
|
+
'/usr/include',
|
|
1427
|
+
'/usr/share',
|
|
1428
|
+
'/usr/x86_64-linux-gnu',
|
|
1429
|
+
'/usr/aarch64-linux-gnu',
|
|
1430
|
+
'/usr/local/bin',
|
|
1431
|
+
'/usr/local/lib',
|
|
1432
|
+
'/usr/local/lib64',
|
|
1433
|
+
'/usr/local/include',
|
|
1434
|
+
]);
|
|
1435
|
+
export function buildStrictLinuxBwrapArgs(spec, cwd, env, probeExecutables) {
|
|
1436
|
+
const stageAOutReal = canonicalizeExistingOrParentSync(spec.stageAOutDir);
|
|
1437
|
+
const scratchReal = canonicalizeExistingOrParentSync(spec.scratchDir);
|
|
1438
|
+
const candidateReal = spec.candidateDir !== undefined ? canonicalizeExistingOrParentSync(spec.candidateDir) : null;
|
|
1439
|
+
const workloadSnapReal = spec.workloadSnapshotDir !== undefined ? canonicalizeExistingOrParentSync(spec.workloadSnapshotDir) : null;
|
|
1440
|
+
if (spec.stage === 'A' && (candidateReal === null || workloadSnapReal !== null)) {
|
|
1441
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'invalid Stage A linux-bwrap directory specification');
|
|
1442
|
+
}
|
|
1443
|
+
if (spec.stage === 'B' && (workloadSnapReal === null || candidateReal !== null)) {
|
|
1444
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'invalid Stage B linux-bwrap directory specification');
|
|
1445
|
+
}
|
|
1446
|
+
// Reject ANY overlap (equal, ancestor, or descendant) between implicit runtime bind trees
|
|
1447
|
+
// (including /usr such as /usr/local/share/held-out) and protected or stage-private paths!
|
|
1448
|
+
const implicitVariants = new Set();
|
|
1449
|
+
for (const rtRoot of LINUX_BWRAP_IMPLICIT_RUNTIME_ROOTS) {
|
|
1450
|
+
for (const v of canonicalOrResolvedSync(rtRoot)) {
|
|
1451
|
+
if (v !== '/')
|
|
1452
|
+
implicitVariants.add(v);
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
const nonOverlappingPaths = [
|
|
1456
|
+
...spec.explicitDeniedReadPaths,
|
|
1457
|
+
spec.stageAOutDir,
|
|
1458
|
+
spec.scratchDir,
|
|
1459
|
+
...(spec.candidateDir !== undefined ? [spec.candidateDir] : []),
|
|
1460
|
+
...(spec.workloadSnapshotDir !== undefined ? [spec.workloadSnapshotDir] : []),
|
|
1461
|
+
];
|
|
1462
|
+
for (const rawProtected of nonOverlappingPaths) {
|
|
1463
|
+
for (const pv of canonicalOrResolvedSync(rawProtected)) {
|
|
1464
|
+
for (const iv of implicitVariants) {
|
|
1465
|
+
if (pathsOverlap(iv, pv)) {
|
|
1466
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `linux-bwrap implicit runtime bind "${iv}" overlaps protected or job path "${pv}"`);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
const args = [
|
|
1472
|
+
'--unshare-all',
|
|
1473
|
+
'--unshare-pid',
|
|
1474
|
+
'--die-with-parent',
|
|
1475
|
+
'--new-session',
|
|
1476
|
+
'--tmpfs', '/',
|
|
1477
|
+
'--proc', '/proc',
|
|
1478
|
+
'--dev', '/dev',
|
|
1479
|
+
'--tmpfs', '/tmp',
|
|
1480
|
+
];
|
|
1481
|
+
// Bind only narrow system runtime subpaths (never wholesale /usr or /usr/local/share).
|
|
1482
|
+
for (const usrSub of LINUX_BWRAP_NARROW_USR_SUBPATHS) {
|
|
1483
|
+
if (!probeExecutables || existsSync(usrSub)) {
|
|
1484
|
+
args.push('--ro-bind-try', usrSub, usrSub);
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
const optionalSystemRo = [
|
|
1488
|
+
'/bin',
|
|
1489
|
+
'/sbin',
|
|
1490
|
+
'/lib',
|
|
1491
|
+
'/lib32',
|
|
1492
|
+
'/lib64',
|
|
1493
|
+
'/etc/ld.so.cache',
|
|
1494
|
+
'/etc/ld.so.conf',
|
|
1495
|
+
'/etc/ld.so.conf.d',
|
|
1496
|
+
'/etc/alternatives',
|
|
1497
|
+
'/etc/ssl/openssl.cnf',
|
|
1498
|
+
'/etc/ssl/certs',
|
|
1499
|
+
'/etc/ca-certificates',
|
|
1500
|
+
'/etc/pki/ca-trust',
|
|
1501
|
+
'/etc/pki/tls/certs',
|
|
1502
|
+
'/etc/pki/tls/cacerts',
|
|
1503
|
+
'/etc/pki/tls/openssl.cnf',
|
|
1504
|
+
];
|
|
1505
|
+
for (const sysPath of optionalSystemRo) {
|
|
1506
|
+
if (!probeExecutables || existsSync(sysPath)) {
|
|
1507
|
+
args.push('--ro-bind-try', sysPath, sysPath);
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
for (const tc of spec.toolchainPaths) {
|
|
1511
|
+
const realTc = canonicalizeExistingOrParentSync(tc);
|
|
1512
|
+
args.push('--ro-bind', realTc, realTc);
|
|
1513
|
+
}
|
|
1514
|
+
if (spec.stage === 'A') {
|
|
1515
|
+
args.push('--ro-bind', candidateReal, candidateReal);
|
|
1516
|
+
args.push('--bind', stageAOutReal, stageAOutReal);
|
|
1517
|
+
args.push('--bind', scratchReal, scratchReal);
|
|
1518
|
+
}
|
|
1519
|
+
else {
|
|
1520
|
+
args.push('--ro-bind', stageAOutReal, stageAOutReal);
|
|
1521
|
+
args.push('--ro-bind', workloadSnapReal, workloadSnapReal);
|
|
1522
|
+
args.push('--bind', scratchReal, scratchReal);
|
|
1523
|
+
}
|
|
1524
|
+
const canonicalCwd = canonicalizeExistingOrParentSync(cwd);
|
|
1525
|
+
args.push('--chdir', canonicalCwd, '--clearenv');
|
|
1526
|
+
const safeEnv = {
|
|
1527
|
+
HOME: scratchReal,
|
|
1528
|
+
TMPDIR: scratchReal,
|
|
1529
|
+
PATH: '/usr/local/bin:/usr/bin:/bin',
|
|
1530
|
+
LANG: 'C.UTF-8',
|
|
1531
|
+
TERM: 'dumb',
|
|
1532
|
+
...env,
|
|
1533
|
+
GIT_CONFIG_NOSYSTEM: '1',
|
|
1534
|
+
GIT_CONFIG_GLOBAL: '/dev/null',
|
|
1535
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
1536
|
+
};
|
|
1537
|
+
for (const key of Object.keys(safeEnv).sort(compareUtf16)) {
|
|
1538
|
+
const val = safeEnv[key];
|
|
1539
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || /[\0\r\n]/.test(val)) {
|
|
1540
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `invalid environment variable "${key}" for linux-bwrap`);
|
|
1541
|
+
}
|
|
1542
|
+
args.push('--setenv', key, val);
|
|
1543
|
+
}
|
|
1544
|
+
return Object.freeze(args);
|
|
1545
|
+
}
|
|
1546
|
+
const LINUX_LANDLOCK_POSITIVE_READ_ROOTS = Object.freeze([
|
|
1547
|
+
...LINUX_BWRAP_NARROW_USR_SUBPATHS,
|
|
1548
|
+
'/bin',
|
|
1549
|
+
'/sbin',
|
|
1550
|
+
'/lib',
|
|
1551
|
+
'/lib32',
|
|
1552
|
+
'/lib64',
|
|
1553
|
+
'/etc/ld.so.cache',
|
|
1554
|
+
'/etc/ld.so.conf',
|
|
1555
|
+
'/etc/ld.so.conf.d',
|
|
1556
|
+
'/etc/alternatives',
|
|
1557
|
+
'/etc/ssl/openssl.cnf',
|
|
1558
|
+
'/etc/ssl/certs',
|
|
1559
|
+
'/etc/ca-certificates',
|
|
1560
|
+
'/etc/pki/ca-trust',
|
|
1561
|
+
'/etc/pki/tls/certs',
|
|
1562
|
+
'/etc/pki/tls/cacerts',
|
|
1563
|
+
'/etc/pki/tls/openssl.cnf',
|
|
1564
|
+
'/etc/localtime',
|
|
1565
|
+
'/proc/cpuinfo',
|
|
1566
|
+
'/proc/meminfo',
|
|
1567
|
+
'/proc/stat',
|
|
1568
|
+
'/proc/version',
|
|
1569
|
+
'/proc/sys/kernel/random',
|
|
1570
|
+
'/dev/urandom',
|
|
1571
|
+
'/sys/devices/system/cpu',
|
|
1572
|
+
]);
|
|
1573
|
+
export function buildStrictLinuxLandlockConfig(spec, cwd, env) {
|
|
1574
|
+
const stageAOutReal = canonicalizeExistingOrParentSync(spec.stageAOutDir);
|
|
1575
|
+
const scratchReal = canonicalizeExistingOrParentSync(spec.scratchDir);
|
|
1576
|
+
const candidateReal = spec.candidateDir !== undefined ? canonicalizeExistingOrParentSync(spec.candidateDir) : null;
|
|
1577
|
+
const workloadSnapReal = spec.workloadSnapshotDir !== undefined ? canonicalizeExistingOrParentSync(spec.workloadSnapshotDir) : null;
|
|
1578
|
+
if (spec.stage === 'A' && (candidateReal === null || workloadSnapReal !== null)) {
|
|
1579
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'invalid Stage A linux-landlock directory specification');
|
|
1580
|
+
}
|
|
1581
|
+
if (spec.stage === 'B' && (workloadSnapReal === null || candidateReal !== null)) {
|
|
1582
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'invalid Stage B linux-landlock directory specification');
|
|
1583
|
+
}
|
|
1584
|
+
const implicitVariants = new Set();
|
|
1585
|
+
for (const rtRoot of LINUX_BWRAP_IMPLICIT_RUNTIME_ROOTS) {
|
|
1586
|
+
for (const v of canonicalOrResolvedSync(rtRoot)) {
|
|
1587
|
+
if (v !== '/')
|
|
1588
|
+
implicitVariants.add(v);
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
const nonOverlappingPaths = [
|
|
1592
|
+
...spec.explicitDeniedReadPaths,
|
|
1593
|
+
spec.stageAOutDir,
|
|
1594
|
+
spec.scratchDir,
|
|
1595
|
+
...(spec.candidateDir !== undefined ? [spec.candidateDir] : []),
|
|
1596
|
+
...(spec.workloadSnapshotDir !== undefined ? [spec.workloadSnapshotDir] : []),
|
|
1597
|
+
];
|
|
1598
|
+
for (const rawProtected of nonOverlappingPaths) {
|
|
1599
|
+
for (const pv of canonicalOrResolvedSync(rawProtected)) {
|
|
1600
|
+
for (const iv of implicitVariants) {
|
|
1601
|
+
if (pathsOverlap(iv, pv)) {
|
|
1602
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `linux-landlock implicit runtime bind "${iv}" overlaps protected or job path "${pv}"`);
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
const allowedReadOnlyPaths = [];
|
|
1608
|
+
for (const tc of spec.toolchainPaths) {
|
|
1609
|
+
allowedReadOnlyPaths.push(canonicalizeExistingOrParentSync(tc));
|
|
1610
|
+
}
|
|
1611
|
+
const writablePaths = [];
|
|
1612
|
+
if (spec.stage === 'A') {
|
|
1613
|
+
allowedReadOnlyPaths.push(candidateReal);
|
|
1614
|
+
writablePaths.push(stageAOutReal, scratchReal);
|
|
1615
|
+
}
|
|
1616
|
+
else {
|
|
1617
|
+
allowedReadOnlyPaths.push(stageAOutReal, workloadSnapReal);
|
|
1618
|
+
writablePaths.push(scratchReal);
|
|
1619
|
+
}
|
|
1620
|
+
const deniedReadPaths = new Set();
|
|
1621
|
+
for (const dp of spec.explicitDeniedReadPaths) {
|
|
1622
|
+
for (const v of canonicalOrResolvedSync(dp)) {
|
|
1623
|
+
deniedReadPaths.add(v);
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
const safeEnv = {
|
|
1627
|
+
HOME: scratchReal,
|
|
1628
|
+
TMPDIR: scratchReal,
|
|
1629
|
+
PATH: '/usr/local/bin:/usr/bin:/bin',
|
|
1630
|
+
LANG: 'C.UTF-8',
|
|
1631
|
+
TERM: 'dumb',
|
|
1632
|
+
...env,
|
|
1633
|
+
GIT_CONFIG_NOSYSTEM: '1',
|
|
1634
|
+
GIT_CONFIG_GLOBAL: '/dev/null',
|
|
1635
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
1636
|
+
};
|
|
1637
|
+
for (const key of Object.keys(safeEnv).sort(compareUtf16)) {
|
|
1638
|
+
const val = safeEnv[key];
|
|
1639
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || /[\0\r\n]/.test(val)) {
|
|
1640
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `invalid environment variable "${key}" for linux-landlock`);
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
const canonicalCwd = canonicalizeExistingOrParentSync(cwd);
|
|
1644
|
+
return JSON.stringify({
|
|
1645
|
+
workspaceRoot: canonicalCwd,
|
|
1646
|
+
positiveReadRoots: [...LINUX_LANDLOCK_POSITIVE_READ_ROOTS],
|
|
1647
|
+
writablePaths,
|
|
1648
|
+
exactWritableFiles: [],
|
|
1649
|
+
protectedPaths: [],
|
|
1650
|
+
deniedReadPaths: [...deniedReadPaths].sort(compareUtf16),
|
|
1651
|
+
allowedReadOnlyPaths: [...new Set(allowedReadOnlyPaths)].sort(compareUtf16),
|
|
1652
|
+
networkMode: 'none',
|
|
1653
|
+
blockAllSockets: true,
|
|
1654
|
+
cwd: canonicalCwd,
|
|
1655
|
+
env: safeEnv,
|
|
1656
|
+
});
|
|
1657
|
+
}
|
|
1658
|
+
export function prepareStageSandboxInvocation(input) {
|
|
1659
|
+
if (input.backend === 'docker') {
|
|
1660
|
+
if (input.dockerCompiled === undefined) {
|
|
1661
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'missing compiled docker command');
|
|
1662
|
+
}
|
|
1663
|
+
return Object.freeze({
|
|
1664
|
+
executablePath: input.dockerCompiled.executablePath,
|
|
1665
|
+
args: input.dockerCompiled.args,
|
|
1666
|
+
cwd: '/',
|
|
1667
|
+
seccompBpf: null,
|
|
1668
|
+
dockerCleanupInfo: Object.freeze({
|
|
1669
|
+
executablePath: input.dockerCompiled.executablePath,
|
|
1670
|
+
containerName: input.dockerCompiled.containerName,
|
|
1671
|
+
}),
|
|
1672
|
+
cleanup: () => undefined,
|
|
1673
|
+
});
|
|
1674
|
+
}
|
|
1675
|
+
const effectiveProbeMode = input.probeMode ?? input.nativeStageSpec?.probeMode;
|
|
1676
|
+
if (effectiveProbeMode === 'physical') {
|
|
1677
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'native_os sandbox backend cannot enforce isolated physical accelerator device allocation; docker backend is required');
|
|
1678
|
+
}
|
|
1679
|
+
const stageSpec = input.nativeStageSpec;
|
|
1680
|
+
if (stageSpec === undefined) {
|
|
1681
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'missing native OS stage sandbox specification');
|
|
1682
|
+
}
|
|
1683
|
+
const platform = input.host?.platform ?? process.platform;
|
|
1684
|
+
const arch = input.host?.arch ?? process.arch;
|
|
1685
|
+
const preferredBackends = platform === 'darwin'
|
|
1686
|
+
? ['macos-seatbelt']
|
|
1687
|
+
: platform === 'linux'
|
|
1688
|
+
? ['linux-bwrap', 'linux-landlock']
|
|
1689
|
+
: [];
|
|
1690
|
+
if (preferredBackends.length === 0) {
|
|
1691
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `native_os sandbox backend is unsupported on platform "${platform}"`);
|
|
1692
|
+
}
|
|
1693
|
+
const probePolicy = {
|
|
1694
|
+
workspaceRoot: resolve(stageSpec.scratchDir),
|
|
1695
|
+
writablePaths: ['work'],
|
|
1696
|
+
networkMode: 'none',
|
|
1697
|
+
preferredBackends,
|
|
1698
|
+
};
|
|
1699
|
+
let negotiated;
|
|
1700
|
+
try {
|
|
1701
|
+
negotiated = negotiateSandboxBackend(probePolicy, input.host);
|
|
1702
|
+
}
|
|
1703
|
+
catch (err) {
|
|
1704
|
+
const msg = err instanceof Error ? err.message : 'sandbox negotiation failed';
|
|
1705
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', msg);
|
|
1706
|
+
}
|
|
1707
|
+
const deadlineChecker = resolveMonotonicDeadlineChecker(input);
|
|
1708
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, `Stage ${input.stage} sandbox preparation`, input.signal);
|
|
1709
|
+
const probeExecutables = input.host?.probeExecutables ?? true;
|
|
1710
|
+
const canonicalToolchains = validateAndCanonicalizeToolchainMountsSync({
|
|
1711
|
+
toolchainPaths: stageSpec.toolchainPaths,
|
|
1712
|
+
forbiddenPaths: [
|
|
1713
|
+
stageSpec.stageAOutDir,
|
|
1714
|
+
stageSpec.scratchDir,
|
|
1715
|
+
...(stageSpec.candidateDir !== undefined ? [stageSpec.candidateDir] : []),
|
|
1716
|
+
...(stageSpec.workloadSnapshotDir !== undefined ? [stageSpec.workloadSnapshotDir] : []),
|
|
1717
|
+
...stageSpec.explicitDeniedReadPaths,
|
|
1718
|
+
],
|
|
1719
|
+
requireExistingOnDisk: probeExecutables,
|
|
1720
|
+
...(deadlineChecker !== undefined ? { deadlineChecker } : {}),
|
|
1721
|
+
...(input.signal !== undefined ? { signal: input.signal } : {}),
|
|
1722
|
+
});
|
|
1723
|
+
const normalizedSpec = {
|
|
1724
|
+
...stageSpec,
|
|
1725
|
+
toolchainPaths: canonicalToolchains,
|
|
1726
|
+
};
|
|
1727
|
+
if (negotiated.backendId === 'macos-seatbelt') {
|
|
1728
|
+
const profileText = buildStrictSeatbeltStageProfile(normalizedSpec);
|
|
1729
|
+
const canonicalCwd = canonicalizeExistingOrParentSync(input.cwd);
|
|
1730
|
+
return Object.freeze({
|
|
1731
|
+
executablePath: negotiated.executablePath,
|
|
1732
|
+
args: Object.freeze(['-p', profileText, '--', input.command, ...input.args]),
|
|
1733
|
+
cwd: canonicalCwd,
|
|
1734
|
+
seccompBpf: null,
|
|
1735
|
+
dockerCleanupInfo: null,
|
|
1736
|
+
cleanup: () => undefined,
|
|
1737
|
+
});
|
|
1738
|
+
}
|
|
1739
|
+
if (negotiated.backendId === 'linux-bwrap') {
|
|
1740
|
+
const bwrapArgs = buildStrictLinuxBwrapArgs(normalizedSpec, input.cwd, input.env, probeExecutables);
|
|
1741
|
+
const seccompBpf = compileStrictSocketDenySeccompBpf(arch);
|
|
1742
|
+
return Object.freeze({
|
|
1743
|
+
executablePath: negotiated.executablePath,
|
|
1744
|
+
args: Object.freeze([...bwrapArgs, '--seccomp', '3', '--', input.command, ...input.args]),
|
|
1745
|
+
cwd: '/',
|
|
1746
|
+
seccompBpf,
|
|
1747
|
+
dockerCleanupInfo: null,
|
|
1748
|
+
cleanup: () => undefined,
|
|
1749
|
+
});
|
|
1750
|
+
}
|
|
1751
|
+
if (negotiated.backendId === 'linux-landlock') {
|
|
1752
|
+
const landlockConfig = buildStrictLinuxLandlockConfig(normalizedSpec, input.cwd, input.env);
|
|
1753
|
+
return Object.freeze({
|
|
1754
|
+
executablePath: negotiated.executablePath,
|
|
1755
|
+
args: Object.freeze(['-I', '-S', '-B', '-c', LANDLOCK_BOOTSTRAP_SCRIPT, landlockConfig, input.command, ...input.args]),
|
|
1756
|
+
cwd: '/',
|
|
1757
|
+
seccompBpf: null,
|
|
1758
|
+
dockerCleanupInfo: null,
|
|
1759
|
+
cleanup: () => undefined,
|
|
1760
|
+
});
|
|
1761
|
+
}
|
|
1762
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `unexpected negotiated native sandbox backend "${negotiated.backendId}"`);
|
|
1763
|
+
}
|
|
1764
|
+
const SANITIZED_DOCKER_CLEANUP_ENV = Object.freeze({
|
|
1765
|
+
PATH: '/usr/local/bin:/usr/bin:/bin',
|
|
1766
|
+
LANG: 'C',
|
|
1767
|
+
LC_ALL: 'C',
|
|
1768
|
+
});
|
|
1769
|
+
export function runSanitizedDockerRmForce(executablePath, containerName, options = {}) {
|
|
1770
|
+
const timeoutMs = options.timeoutMs ?? 10_000;
|
|
1771
|
+
return new Promise((resolveRm, rejectRm) => {
|
|
1772
|
+
execFile(executablePath, ['rm', '-f', containerName], {
|
|
1773
|
+
shell: false,
|
|
1774
|
+
cwd: '/',
|
|
1775
|
+
env: { ...SANITIZED_DOCKER_CLEANUP_ENV },
|
|
1776
|
+
timeout: timeoutMs,
|
|
1777
|
+
maxBuffer: 65_536,
|
|
1778
|
+
killSignal: 'SIGKILL',
|
|
1779
|
+
windowsHide: true,
|
|
1780
|
+
}, (error, stdout, stderr) => {
|
|
1781
|
+
if (error !== null) {
|
|
1782
|
+
const errno = error;
|
|
1783
|
+
const combined = `${String(stderr ?? '')}\n${String(stdout ?? '')}`;
|
|
1784
|
+
if (!errno.killed
|
|
1785
|
+
&& errno.code !== 'ETIMEDOUT'
|
|
1786
|
+
&& errno.signal == null
|
|
1787
|
+
&& typeof errno.code === 'number'
|
|
1788
|
+
&& /no such container/i.test(combined)) {
|
|
1789
|
+
resolveRm();
|
|
1790
|
+
return;
|
|
1791
|
+
}
|
|
1792
|
+
rejectRm(new RunnerTeardownError(`docker rm -f "${containerName}" failed to confirm container teardown: ${error.message}`));
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
resolveRm();
|
|
1796
|
+
});
|
|
1797
|
+
});
|
|
1798
|
+
}
|
|
1799
|
+
function isProcessGroupAlive(pgid) {
|
|
1800
|
+
if (pgid <= 0)
|
|
1801
|
+
return false;
|
|
1802
|
+
try {
|
|
1803
|
+
process.kill(-pgid, 0);
|
|
1804
|
+
return true;
|
|
1805
|
+
}
|
|
1806
|
+
catch (err) {
|
|
1807
|
+
return err?.code === 'EPERM';
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
export async function waitForProcessGroupExit(pgid, maxWaitMs = 2_000, probeGroupAlive = isProcessGroupAlive) {
|
|
1811
|
+
if (pgid <= 0)
|
|
1812
|
+
return;
|
|
1813
|
+
const deadline = performance.now() + maxWaitMs;
|
|
1814
|
+
while (probeGroupAlive(pgid) && performance.now() < deadline) {
|
|
1815
|
+
try {
|
|
1816
|
+
process.kill(-pgid, 'SIGKILL');
|
|
1817
|
+
}
|
|
1818
|
+
catch (err) {
|
|
1819
|
+
if (err?.code === 'ESRCH' && !probeGroupAlive(pgid)) {
|
|
1820
|
+
break;
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
await new Promise(r => {
|
|
1824
|
+
const t = setTimeout(r, 15);
|
|
1825
|
+
t.unref();
|
|
1826
|
+
});
|
|
1827
|
+
}
|
|
1828
|
+
if (probeGroupAlive(pgid)) {
|
|
1829
|
+
throw new RunnerTeardownError(`process group ${pgid} remained alive after ${maxWaitMs}ms SIGKILL teardown`);
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
async function defaultStageProcessRunner(input) {
|
|
1833
|
+
const deadlineChecker = resolveMonotonicDeadlineChecker(input);
|
|
1834
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, `Stage ${input.stage} pre-prepare`, input.signal);
|
|
1835
|
+
if (!Number.isSafeInteger(input.timeoutMs) || input.timeoutMs < 50 || input.timeoutMs > 3_600_000) {
|
|
1836
|
+
throw new HardwareRunnerError('CONFIG_INVALID', `Stage ${input.stage} timeoutMs out of bounds`);
|
|
1837
|
+
}
|
|
1838
|
+
const prepared = prepareStageSandboxInvocation(input);
|
|
1839
|
+
try {
|
|
1840
|
+
// Recheck monotonic lease deadline and abort signal IMMEDIATELY BEFORE spawn(...) so
|
|
1841
|
+
// synchronous mount-tree scanning or sandbox compilation can NEVER launch a stage past expiry!
|
|
1842
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, `Stage ${input.stage} pre-spawn`, input.signal);
|
|
1843
|
+
const { executablePath: spawnExecutable, args: spawnArgs, cwd: spawnCwd, seccompBpf, dockerCleanupInfo } = prepared;
|
|
1844
|
+
return await new Promise((resolveRun, rejectRun) => {
|
|
1845
|
+
const child = spawn(spawnExecutable, [...spawnArgs], {
|
|
1846
|
+
cwd: spawnCwd,
|
|
1847
|
+
env: { ...input.env },
|
|
1848
|
+
stdio: seccompBpf !== null ? ['pipe', 'pipe', 'pipe', 'pipe'] : ['pipe', 'pipe', 'pipe'],
|
|
1849
|
+
detached: true,
|
|
1850
|
+
});
|
|
1851
|
+
const childPgid = child.pid ?? 0;
|
|
1852
|
+
if (seccompBpf !== null) {
|
|
1853
|
+
const seccompPipe = child.stdio[3];
|
|
1854
|
+
if (seccompPipe !== null && seccompPipe !== undefined) {
|
|
1855
|
+
seccompPipe.on('error', () => undefined);
|
|
1856
|
+
seccompPipe.end(seccompBpf);
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
child.stdin.on('error', () => undefined);
|
|
1860
|
+
child.stdin.end();
|
|
1861
|
+
child.stdout.on('error', () => undefined);
|
|
1862
|
+
child.stderr.on('error', () => undefined);
|
|
1863
|
+
let forceKillTimer = null;
|
|
1864
|
+
let leaseDeadlineTimer = null;
|
|
1865
|
+
let activeDockerRm = null;
|
|
1866
|
+
let terminationRequested = false;
|
|
1867
|
+
let leaseExpired = false;
|
|
1868
|
+
let overflowError = null;
|
|
1869
|
+
let stdoutClosed = false;
|
|
1870
|
+
let stderrClosed = false;
|
|
1871
|
+
let onStdioStreamClosed = null;
|
|
1872
|
+
const markStdoutClosed = () => {
|
|
1873
|
+
if (!stdoutClosed) {
|
|
1874
|
+
stdoutClosed = true;
|
|
1875
|
+
onStdioStreamClosed?.();
|
|
1876
|
+
}
|
|
1877
|
+
};
|
|
1878
|
+
const markStderrClosed = () => {
|
|
1879
|
+
if (!stderrClosed) {
|
|
1880
|
+
stderrClosed = true;
|
|
1881
|
+
onStdioStreamClosed?.();
|
|
1882
|
+
}
|
|
1883
|
+
};
|
|
1884
|
+
child.stdout.once('end', markStdoutClosed);
|
|
1885
|
+
child.stdout.once('close', markStdoutClosed);
|
|
1886
|
+
child.stderr.once('end', markStderrClosed);
|
|
1887
|
+
child.stderr.once('close', markStderrClosed);
|
|
1888
|
+
const triggerDockerRm = () => {
|
|
1889
|
+
if (dockerCleanupInfo === null)
|
|
1890
|
+
return Promise.resolve();
|
|
1891
|
+
if (activeDockerRm === null) {
|
|
1892
|
+
activeDockerRm = runSanitizedDockerRmForce(dockerCleanupInfo.executablePath, dockerCleanupInfo.containerName).finally(() => {
|
|
1893
|
+
activeDockerRm = null;
|
|
1894
|
+
});
|
|
1895
|
+
}
|
|
1896
|
+
return activeDockerRm;
|
|
1897
|
+
};
|
|
1898
|
+
const signalProcessGroup = (sig) => {
|
|
1899
|
+
try {
|
|
1900
|
+
if (childPgid > 0) {
|
|
1901
|
+
process.kill(-childPgid, sig);
|
|
1902
|
+
}
|
|
1903
|
+
else {
|
|
1904
|
+
child.kill(sig);
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
catch {
|
|
1908
|
+
try {
|
|
1909
|
+
child.kill(sig);
|
|
1910
|
+
}
|
|
1911
|
+
catch {
|
|
1912
|
+
// Child already exited.
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
};
|
|
1916
|
+
const terminateNow = (immediateKill = false) => {
|
|
1917
|
+
terminationRequested = true;
|
|
1918
|
+
child.stdout.destroy();
|
|
1919
|
+
child.stderr.destroy();
|
|
1920
|
+
onStdioStreamClosed?.();
|
|
1921
|
+
signalProcessGroup(immediateKill ? 'SIGKILL' : 'SIGTERM');
|
|
1922
|
+
void triggerDockerRm().catch(() => { });
|
|
1923
|
+
if (!immediateKill && forceKillTimer === null) {
|
|
1924
|
+
forceKillTimer = setTimeout(() => {
|
|
1925
|
+
if (!settled) {
|
|
1926
|
+
signalProcessGroup('SIGKILL');
|
|
1927
|
+
void triggerDockerRm().catch(() => { });
|
|
1928
|
+
}
|
|
1929
|
+
}, 150);
|
|
1930
|
+
forceKillTimer.unref();
|
|
1931
|
+
}
|
|
1932
|
+
};
|
|
1933
|
+
const stdoutChunks = [];
|
|
1934
|
+
const stderrChunks = [];
|
|
1935
|
+
let stdoutBytes = 0;
|
|
1936
|
+
let stderrBytes = 0;
|
|
1937
|
+
let timedOut = false;
|
|
1938
|
+
let settled = false;
|
|
1939
|
+
const armLeaseDeadlineTimer = () => {
|
|
1940
|
+
if (deadlineChecker === undefined || settled || terminationRequested)
|
|
1941
|
+
return;
|
|
1942
|
+
if (leaseDeadlineTimer !== null) {
|
|
1943
|
+
clearTimeout(leaseDeadlineTimer);
|
|
1944
|
+
leaseDeadlineTimer = null;
|
|
1945
|
+
}
|
|
1946
|
+
const remMs = deadlineChecker.getDeadlineMonoMs() - deadlineChecker.nowMonotonicMs();
|
|
1947
|
+
if (remMs <= 0) {
|
|
1948
|
+
leaseExpired = true;
|
|
1949
|
+
terminateNow(false);
|
|
1950
|
+
return;
|
|
1951
|
+
}
|
|
1952
|
+
const waitMs = Math.min(input.timeoutMs, Math.max(1, Math.ceil(remMs)));
|
|
1953
|
+
leaseDeadlineTimer = setTimeout(() => {
|
|
1954
|
+
leaseDeadlineTimer = null;
|
|
1955
|
+
if (settled || terminationRequested)
|
|
1956
|
+
return;
|
|
1957
|
+
if (deadlineChecker.nowMonotonicMs() >= deadlineChecker.getDeadlineMonoMs()) {
|
|
1958
|
+
leaseExpired = true;
|
|
1959
|
+
terminateNow(false);
|
|
1960
|
+
}
|
|
1961
|
+
else {
|
|
1962
|
+
armLeaseDeadlineTimer();
|
|
1963
|
+
}
|
|
1964
|
+
}, waitMs);
|
|
1965
|
+
leaseDeadlineTimer.unref();
|
|
1966
|
+
};
|
|
1967
|
+
const finishAfterTeardown = async (exitCode, exitSignal, err) => {
|
|
1968
|
+
if (settled)
|
|
1969
|
+
return;
|
|
1970
|
+
settled = true;
|
|
1971
|
+
clearTimeout(timeoutTimer);
|
|
1972
|
+
if (leaseDeadlineTimer !== null)
|
|
1973
|
+
clearTimeout(leaseDeadlineTimer);
|
|
1974
|
+
if (forceKillTimer !== null)
|
|
1975
|
+
clearTimeout(forceKillTimer);
|
|
1976
|
+
input.signal?.removeEventListener('abort', onExternalAbort);
|
|
1977
|
+
child.stdout.destroy();
|
|
1978
|
+
child.stderr.destroy();
|
|
1979
|
+
let teardownErr = null;
|
|
1980
|
+
try {
|
|
1981
|
+
signalProcessGroup('SIGKILL');
|
|
1982
|
+
await waitForProcessGroupExit(childPgid);
|
|
1983
|
+
if (activeDockerRm !== null) {
|
|
1984
|
+
await activeDockerRm.catch(() => { });
|
|
1985
|
+
}
|
|
1986
|
+
if (dockerCleanupInfo !== null
|
|
1987
|
+
&& (terminationRequested || timedOut || leaseExpired || err !== undefined || exitCode !== 0 || exitSignal !== null)) {
|
|
1988
|
+
await runSanitizedDockerRmForce(dockerCleanupInfo.executablePath, dockerCleanupInfo.containerName);
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
catch (tdErr) {
|
|
1992
|
+
teardownErr = tdErr instanceof RunnerTeardownError
|
|
1993
|
+
? tdErr
|
|
1994
|
+
: new RunnerTeardownError(tdErr instanceof Error ? tdErr.message : String(tdErr));
|
|
1995
|
+
}
|
|
1996
|
+
const leaseFenceErr = leaseExpired || (deadlineChecker !== undefined && deadlineChecker.nowMonotonicMs() >= deadlineChecker.getDeadlineMonoMs())
|
|
1997
|
+
? new HardwareRunnerError('QUEUE_LEASE_FENCED', `Stage ${input.stage} lease authority expired`)
|
|
1998
|
+
: undefined;
|
|
1999
|
+
const effectiveErr = teardownErr ?? err ?? overflowError ?? leaseFenceErr ?? (input.signal?.aborted
|
|
2000
|
+
? new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `Stage ${input.stage} aborted`)
|
|
2001
|
+
: undefined);
|
|
2002
|
+
if (effectiveErr !== undefined) {
|
|
2003
|
+
rejectRun(effectiveErr);
|
|
2004
|
+
return;
|
|
2005
|
+
}
|
|
2006
|
+
resolveRun({
|
|
2007
|
+
exitCode,
|
|
2008
|
+
signal: exitSignal,
|
|
2009
|
+
stdout: Buffer.concat(stdoutChunks, stdoutBytes).toString('utf8'),
|
|
2010
|
+
stderr: Buffer.concat(stderrChunks, stderrBytes).toString('utf8'),
|
|
2011
|
+
timedOut,
|
|
2012
|
+
});
|
|
2013
|
+
};
|
|
2014
|
+
const onExternalAbort = () => {
|
|
2015
|
+
terminateNow(false);
|
|
2016
|
+
};
|
|
2017
|
+
if (input.signal?.aborted) {
|
|
2018
|
+
terminateNow(false);
|
|
2019
|
+
}
|
|
2020
|
+
else {
|
|
2021
|
+
input.signal?.addEventListener('abort', onExternalAbort, { once: true });
|
|
2022
|
+
}
|
|
2023
|
+
armLeaseDeadlineTimer();
|
|
2024
|
+
const timeoutTimer = setTimeout(() => {
|
|
2025
|
+
timedOut = true;
|
|
2026
|
+
terminateNow(false);
|
|
2027
|
+
}, input.timeoutMs);
|
|
2028
|
+
timeoutTimer.unref();
|
|
2029
|
+
child.on('error', err => {
|
|
2030
|
+
const mapped = err instanceof TaskpackError
|
|
2031
|
+
? new HardwareRunnerError('RUNNER_SANDBOX_FAILED', err.message)
|
|
2032
|
+
: new HardwareRunnerError('RUNNER_SANDBOX_FAILED', `failed to spawn sandboxed process: ${err.message}`);
|
|
2033
|
+
void finishAfterTeardown(null, null, mapped);
|
|
2034
|
+
});
|
|
2035
|
+
child.stdout.on('data', (chunk) => {
|
|
2036
|
+
if (overflowError !== null)
|
|
2037
|
+
return;
|
|
2038
|
+
if (stdoutBytes + chunk.byteLength > MAX_STAGE_STDIO_BYTES) {
|
|
2039
|
+
overflowError = new HardwareRunnerError('ARTIFACT_INVALID', `Stage ${input.stage} stdout exceeded ${MAX_STAGE_STDIO_BYTES} bytes`);
|
|
2040
|
+
terminateNow(true);
|
|
2041
|
+
return;
|
|
2042
|
+
}
|
|
2043
|
+
stdoutChunks.push(chunk);
|
|
2044
|
+
stdoutBytes += chunk.byteLength;
|
|
2045
|
+
});
|
|
2046
|
+
child.stderr.on('data', (chunk) => {
|
|
2047
|
+
if (overflowError !== null)
|
|
2048
|
+
return;
|
|
2049
|
+
if (stderrBytes + chunk.byteLength > MAX_STAGE_STDIO_BYTES) {
|
|
2050
|
+
overflowError = new HardwareRunnerError('ARTIFACT_INVALID', `Stage ${input.stage} stderr exceeded ${MAX_STAGE_STDIO_BYTES} bytes`);
|
|
2051
|
+
terminateNow(true);
|
|
2052
|
+
return;
|
|
2053
|
+
}
|
|
2054
|
+
stderrChunks.push(chunk);
|
|
2055
|
+
stderrBytes += chunk.byteLength;
|
|
2056
|
+
});
|
|
2057
|
+
// Listen on 'exit' (NEVER 'close'!) so a leaked stdio descriptor cannot delay teardown!
|
|
2058
|
+
child.once('exit', (code, exitSignal) => {
|
|
2059
|
+
void (async () => {
|
|
2060
|
+
if (!terminationRequested
|
|
2061
|
+
&& !timedOut
|
|
2062
|
+
&& !leaseExpired
|
|
2063
|
+
&& overflowError === null
|
|
2064
|
+
&& (!stdoutClosed || !stderrClosed)) {
|
|
2065
|
+
await new Promise(resolveDrain => {
|
|
2066
|
+
const checkDone = () => {
|
|
2067
|
+
if ((stdoutClosed && stderrClosed) || terminationRequested || overflowError !== null) {
|
|
2068
|
+
clearTimeout(drainCap);
|
|
2069
|
+
onStdioStreamClosed = null;
|
|
2070
|
+
resolveDrain();
|
|
2071
|
+
}
|
|
2072
|
+
};
|
|
2073
|
+
const drainCap = setTimeout(() => {
|
|
2074
|
+
onStdioStreamClosed = null;
|
|
2075
|
+
resolveDrain();
|
|
2076
|
+
}, 150);
|
|
2077
|
+
drainCap.unref();
|
|
2078
|
+
onStdioStreamClosed = checkDone;
|
|
2079
|
+
checkDone();
|
|
2080
|
+
});
|
|
2081
|
+
}
|
|
2082
|
+
await finishAfterTeardown(code, exitSignal);
|
|
2083
|
+
})();
|
|
2084
|
+
});
|
|
2085
|
+
});
|
|
2086
|
+
}
|
|
2087
|
+
finally {
|
|
2088
|
+
prepared.cleanup();
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
/**
|
|
2092
|
+
* Walk `stageAOutDir` with `O_NOFOLLOW`, reject symlinks/hardlinks/secrets/budget violations without
|
|
2093
|
+
* mutating bytes, seal every output file `0o400` + `fsync`, and lock directories `0o500`.
|
|
2094
|
+
*/
|
|
2095
|
+
export async function sealStageAOutputs(options) {
|
|
2096
|
+
const { stageAOutDir, scrubber, secretOverlapBytes } = options;
|
|
2097
|
+
const perFileMax = Math.min(options.maxBlobBytes ?? VERIFIER_ARTIFACT_LIMITS.maxFileBytes, VERIFIER_ARTIFACT_LIMITS.maxFileBytes);
|
|
2098
|
+
await assertNoSymlinkAncestors(stageAOutDir, {
|
|
2099
|
+
checkLeaf: true,
|
|
2100
|
+
code: 'ARTIFACT_INVALID',
|
|
2101
|
+
diagPath: '/stageAOutDir',
|
|
2102
|
+
});
|
|
2103
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
2104
|
+
const oDirectory = 'O_DIRECTORY' in constants ? constants.O_DIRECTORY : 0;
|
|
2105
|
+
const realRoot = await realpath(stageAOutDir);
|
|
2106
|
+
const dirsToSeal = [];
|
|
2107
|
+
const seenFolded = new Set();
|
|
2108
|
+
const sealed = [];
|
|
2109
|
+
let totalBytes = 0;
|
|
2110
|
+
const isInsideOutRoot = (candidateReal) => candidateReal === realRoot
|
|
2111
|
+
|| candidateReal.startsWith(realRoot.endsWith(sep) ? realRoot : `${realRoot}${sep}`);
|
|
2112
|
+
const walk = async (absDir, relPrefix, depth) => {
|
|
2113
|
+
if (depth > 32) {
|
|
2114
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'Stage A output directory exceeds maximum nesting depth');
|
|
2115
|
+
}
|
|
2116
|
+
const dirHandle = await open(absDir, constants.O_RDONLY | noFollow | oDirectory).catch(() => {
|
|
2117
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'symlink or invalid directory in Stage A output');
|
|
2118
|
+
});
|
|
2119
|
+
await dirHandle.close();
|
|
2120
|
+
const dirents = await readdir(absDir, { withFileTypes: true });
|
|
2121
|
+
dirents.sort((a, b) => compareUtf16(a.name, b.name));
|
|
2122
|
+
for (const dirent of dirents) {
|
|
2123
|
+
if (options.signal?.aborted) {
|
|
2124
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'Stage A output sealing aborted');
|
|
2125
|
+
}
|
|
2126
|
+
const childAbs = join(absDir, dirent.name);
|
|
2127
|
+
const childRel = relPrefix.length === 0 ? dirent.name : `${relPrefix}/${dirent.name}`;
|
|
2128
|
+
if (dirent.isSymbolicLink()) {
|
|
2129
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `symlink "${childRel}" is forbidden in Stage A outputs`);
|
|
2130
|
+
}
|
|
2131
|
+
const st = await lstat(childAbs).catch(() => null);
|
|
2132
|
+
if (st === null || st.isSymbolicLink()) {
|
|
2133
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `symlink or vanished entry "${childRel}" in Stage A outputs`);
|
|
2134
|
+
}
|
|
2135
|
+
const realChild = await realpath(childAbs).catch(() => {
|
|
2136
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `unable to resolve Stage A output "${childRel}"`);
|
|
2137
|
+
});
|
|
2138
|
+
if (!isInsideOutRoot(realChild)) {
|
|
2139
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `Stage A output "${childRel}" escapes stage-a-out`);
|
|
2140
|
+
}
|
|
2141
|
+
if (st.isDirectory()) {
|
|
2142
|
+
if (dirent.name.toLowerCase() === '.git' || dirent.name.toLowerCase() === '.loopwright-verifier') {
|
|
2143
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `forbidden directory "${childRel}" in Stage A outputs`);
|
|
2144
|
+
}
|
|
2145
|
+
await walk(childAbs, childRel, depth + 1);
|
|
2146
|
+
dirsToSeal.push(childAbs);
|
|
2147
|
+
}
|
|
2148
|
+
else if (st.isFile()) {
|
|
2149
|
+
validateSafeRelativeArtifactPath(childRel, '/outputArtifacts');
|
|
2150
|
+
const folded = childRel.normalize('NFC').toLowerCase();
|
|
2151
|
+
if (seenFolded.has(folded)) {
|
|
2152
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `case-colliding Stage A output "${childRel}"`);
|
|
2153
|
+
}
|
|
2154
|
+
seenFolded.add(folded);
|
|
2155
|
+
if (sealed.length >= VERIFIER_ARTIFACT_LIMITS.maxFilesPerSlot) {
|
|
2156
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `Stage A outputs exceed maximum of ${VERIFIER_ARTIFACT_LIMITS.maxFilesPerSlot} files`);
|
|
2157
|
+
}
|
|
2158
|
+
if (st.nlink !== 1) {
|
|
2159
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `hardlinked file "${childRel}" is forbidden in Stage A outputs`);
|
|
2160
|
+
}
|
|
2161
|
+
if (st.size > perFileMax) {
|
|
2162
|
+
throw new HardwareRunnerError('PAYLOAD_TOO_LARGE', `Stage A output "${childRel}" exceeds per-file byte limit`);
|
|
2163
|
+
}
|
|
2164
|
+
if (st.size > VERIFIER_ARTIFACT_LIMITS.maxTotalBytes - totalBytes) {
|
|
2165
|
+
throw new HardwareRunnerError('PAYLOAD_TOO_LARGE', 'Stage A outputs exceed aggregate verifier byte budget');
|
|
2166
|
+
}
|
|
2167
|
+
const fh = await open(childAbs, constants.O_RDONLY | noFollow);
|
|
2168
|
+
let hexDigest;
|
|
2169
|
+
let byteLength;
|
|
2170
|
+
try {
|
|
2171
|
+
const opened = await fh.stat();
|
|
2172
|
+
if (!opened.isFile()
|
|
2173
|
+
|| opened.isSymbolicLink()
|
|
2174
|
+
|| opened.nlink !== 1
|
|
2175
|
+
|| opened.dev !== st.dev
|
|
2176
|
+
|| opened.ino !== st.ino
|
|
2177
|
+
|| opened.size !== st.size) {
|
|
2178
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `Stage A output "${childRel}" mutated while opening`);
|
|
2179
|
+
}
|
|
2180
|
+
const hasher = createHash('sha256');
|
|
2181
|
+
let scanTail = Buffer.alloc(0);
|
|
2182
|
+
const buf = Buffer.allocUnsafe(Math.min(MAX_CAS_CHUNK_BYTES, Math.max(1, opened.size)));
|
|
2183
|
+
let offset = 0;
|
|
2184
|
+
while (offset < opened.size) {
|
|
2185
|
+
if (options.signal?.aborted) {
|
|
2186
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'Stage A output sealing aborted');
|
|
2187
|
+
}
|
|
2188
|
+
const maxStep = Math.max(1, MAX_CAS_CHUNK_BYTES - scanTail.byteLength);
|
|
2189
|
+
const toRead = Math.min(maxStep, buf.byteLength, opened.size - offset);
|
|
2190
|
+
const { bytesRead } = await fh.read(buf, 0, toRead, offset);
|
|
2191
|
+
if (bytesRead <= 0)
|
|
2192
|
+
break;
|
|
2193
|
+
const slice = buf.subarray(0, bytesRead);
|
|
2194
|
+
const windowBuf = scanTail.byteLength === 0 ? slice : Buffer.concat([scanTail, slice]);
|
|
2195
|
+
if (scrubber.containsSecret(windowBuf.toString('latin1'))
|
|
2196
|
+
|| scrubber.containsSecret(windowBuf.toString('utf8'))) {
|
|
2197
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `Stage A output "${childRel}" rejected by SecretScrubber`);
|
|
2198
|
+
}
|
|
2199
|
+
scanTail = windowBuf.byteLength > secretOverlapBytes
|
|
2200
|
+
? Buffer.from(windowBuf.subarray(windowBuf.byteLength - secretOverlapBytes))
|
|
2201
|
+
: Buffer.from(windowBuf);
|
|
2202
|
+
hasher.update(slice);
|
|
2203
|
+
offset += bytesRead;
|
|
2204
|
+
}
|
|
2205
|
+
const extra = await fh.read(buf, 0, 1, offset);
|
|
2206
|
+
if (extra.bytesRead !== 0 || offset !== opened.size) {
|
|
2207
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `Stage A output "${childRel}" changed size during hashing`);
|
|
2208
|
+
}
|
|
2209
|
+
await fh.chmod(0o400);
|
|
2210
|
+
await fh.sync();
|
|
2211
|
+
const sealedStat = await fh.stat();
|
|
2212
|
+
if (sealedStat.dev !== opened.dev
|
|
2213
|
+
|| sealedStat.ino !== opened.ino
|
|
2214
|
+
|| sealedStat.size !== opened.size
|
|
2215
|
+
|| sealedStat.nlink !== 1
|
|
2216
|
+
|| (sealedStat.mode & 0o7777) !== 0o400) {
|
|
2217
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `failed to seal Stage A output "${childRel}" to 0o400`);
|
|
2218
|
+
}
|
|
2219
|
+
hexDigest = hasher.digest('hex');
|
|
2220
|
+
byteLength = offset;
|
|
2221
|
+
}
|
|
2222
|
+
finally {
|
|
2223
|
+
await fh.close();
|
|
2224
|
+
}
|
|
2225
|
+
totalBytes += byteLength;
|
|
2226
|
+
sealed.push(Object.freeze({
|
|
2227
|
+
artifact: Object.freeze({
|
|
2228
|
+
name: childRel,
|
|
2229
|
+
digest: Object.freeze({ algorithm: 'sha256', hex: hexDigest }),
|
|
2230
|
+
byteLength,
|
|
2231
|
+
}),
|
|
2232
|
+
sealedFilePath: childAbs,
|
|
2233
|
+
}));
|
|
2234
|
+
}
|
|
2235
|
+
else {
|
|
2236
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `unsupported non-regular file "${childRel}" in Stage A outputs`);
|
|
2237
|
+
}
|
|
2238
|
+
}
|
|
2239
|
+
};
|
|
2240
|
+
await walk(stageAOutDir, '', 0);
|
|
2241
|
+
for (const subDir of dirsToSeal) {
|
|
2242
|
+
await chmod(subDir, 0o500);
|
|
2243
|
+
}
|
|
2244
|
+
await chmod(stageAOutDir, 0o500);
|
|
2245
|
+
sealed.sort((a, b) => compareUtf16(a.artifact.name, b.artifact.name));
|
|
2246
|
+
return Object.freeze(sealed);
|
|
2247
|
+
}
|
|
2248
|
+
function assertNoDecodedSecret(value, scrubber) {
|
|
2249
|
+
if (scrubber.containsSecret(value)) {
|
|
2250
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'Stage B result envelope rejected by SecretScrubber');
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
function parseEnvelopeMetrics(raw, scrubber) {
|
|
2254
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
2255
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'Stage B metrics must be an object', '/metrics');
|
|
2256
|
+
}
|
|
2257
|
+
const rec = raw;
|
|
2258
|
+
const keys = Object.keys(rec).sort();
|
|
2259
|
+
if (keys.length > LIMITS.metricEntries) {
|
|
2260
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'Stage B metrics exceeds maximum entries', '/metrics');
|
|
2261
|
+
}
|
|
2262
|
+
const out = Object.create(null);
|
|
2263
|
+
for (let idx = 0; idx < keys.length; idx += 1) {
|
|
2264
|
+
const key = keys[idx];
|
|
2265
|
+
if (!Object.hasOwn(rec, key))
|
|
2266
|
+
continue;
|
|
2267
|
+
assertNoDecodedSecret(key, scrubber);
|
|
2268
|
+
if (key.length < 1 || key.length > LIMITS.metricKey || FORBIDDEN_METRIC_KEYS.has(key) || !METRIC_KEY_RE.test(key)) {
|
|
2269
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `invalid Stage B metric key at index ${idx}`, '/metrics');
|
|
2270
|
+
}
|
|
2271
|
+
const val = rec[key];
|
|
2272
|
+
if (typeof val !== 'number' || !Number.isFinite(val) || Object.is(val, -0)) {
|
|
2273
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', `Stage B metric "${key}" must be a finite numeric value`, `/metrics/${key}`);
|
|
2274
|
+
}
|
|
2275
|
+
out[key] = val;
|
|
2276
|
+
}
|
|
2277
|
+
return Object.freeze(out);
|
|
2278
|
+
}
|
|
2279
|
+
function parseEnvelopeFindings(raw, scrubber) {
|
|
2280
|
+
if (!Array.isArray(raw) || raw.length > LIMITS.findings) {
|
|
2281
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'Stage B findings must be a bounded array', '/findings');
|
|
2282
|
+
}
|
|
2283
|
+
const out = raw.map((item, idx) => {
|
|
2284
|
+
const fPath = `/findings/${idx}`;
|
|
2285
|
+
const obj = expectNullProtoRecord(item, FINDING_KEYS, ['title', 'severity', 'evidence'], 'ARTIFACT_INVALID', fPath);
|
|
2286
|
+
if (typeof obj.title !== 'string' || obj.title.length < 1 || obj.title.length > LIMITS.findingTitle || hasLoneSurrogate(obj.title)) {
|
|
2287
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid Stage B finding title', `${fPath}/title`);
|
|
2288
|
+
}
|
|
2289
|
+
assertNoDecodedSecret(obj.title, scrubber);
|
|
2290
|
+
if (obj.severity !== 'critical' && obj.severity !== 'high' && obj.severity !== 'medium' && obj.severity !== 'low') {
|
|
2291
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid Stage B finding severity', `${fPath}/severity`);
|
|
2292
|
+
}
|
|
2293
|
+
const severity = obj.severity;
|
|
2294
|
+
if (typeof obj.evidence !== 'string' || obj.evidence.length < 1 || obj.evidence.length > LIMITS.findingEvidence || hasLoneSurrogate(obj.evidence)) {
|
|
2295
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid Stage B finding evidence', `${fPath}/evidence`);
|
|
2296
|
+
}
|
|
2297
|
+
assertNoDecodedSecret(obj.evidence, scrubber);
|
|
2298
|
+
let relPath;
|
|
2299
|
+
if (Object.hasOwn(obj, 'path')) {
|
|
2300
|
+
if (obj.path === null) {
|
|
2301
|
+
relPath = null;
|
|
2302
|
+
}
|
|
2303
|
+
else if (typeof obj.path === 'string') {
|
|
2304
|
+
assertNoDecodedSecret(obj.path, scrubber);
|
|
2305
|
+
const v = validateRelativePath(obj.path);
|
|
2306
|
+
if (!v.ok) {
|
|
2307
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid Stage B finding path', `${fPath}/path`);
|
|
2308
|
+
}
|
|
2309
|
+
relPath = v.value;
|
|
2310
|
+
}
|
|
2311
|
+
else {
|
|
2312
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid Stage B finding path type', `${fPath}/path`);
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
let line;
|
|
2316
|
+
if (Object.hasOwn(obj, 'line')) {
|
|
2317
|
+
if (obj.line === null) {
|
|
2318
|
+
line = null;
|
|
2319
|
+
}
|
|
2320
|
+
else if (typeof obj.line === 'number' && Number.isSafeInteger(obj.line) && !Object.is(obj.line, -0) && obj.line >= 1) {
|
|
2321
|
+
line = obj.line;
|
|
2322
|
+
}
|
|
2323
|
+
else {
|
|
2324
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid Stage B finding line', `${fPath}/line`);
|
|
2325
|
+
}
|
|
2326
|
+
}
|
|
2327
|
+
const built = Object.create(null);
|
|
2328
|
+
built.title = obj.title;
|
|
2329
|
+
built.severity = severity;
|
|
2330
|
+
if (relPath !== undefined)
|
|
2331
|
+
built.path = relPath;
|
|
2332
|
+
if (line !== undefined)
|
|
2333
|
+
built.line = line;
|
|
2334
|
+
built.evidence = obj.evidence;
|
|
2335
|
+
return Object.freeze(built);
|
|
2336
|
+
});
|
|
2337
|
+
return Object.freeze(out);
|
|
2338
|
+
}
|
|
2339
|
+
/**
|
|
2340
|
+
* Parse and validate the bounded (`<= 64 KiB`) Stage B JSON result envelope into null-prototype
|
|
2341
|
+
* structures, accepting ONLY finite numeric metrics and scanning all decoded strings/keys with
|
|
2342
|
+
* `SecretScrubber`.
|
|
2343
|
+
*/
|
|
2344
|
+
export function parseStageBResultEnvelope(rawStdout, scrubber) {
|
|
2345
|
+
if (typeof rawStdout !== 'string') {
|
|
2346
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'Stage B stdout must be a string');
|
|
2347
|
+
}
|
|
2348
|
+
const lines = rawStdout.split(/\r?\n/);
|
|
2349
|
+
const markerLines = lines.filter(line => line.startsWith(STAGE_B_RESULT_MARKER_PREFIX));
|
|
2350
|
+
let jsonCandidate;
|
|
2351
|
+
if (markerLines.length > 1) {
|
|
2352
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'multiple LOOPWRIGHT_STAGE_B_RESULT markers in Stage B stdout');
|
|
2353
|
+
}
|
|
2354
|
+
if (markerLines.length === 1) {
|
|
2355
|
+
jsonCandidate = markerLines[0].slice(STAGE_B_RESULT_MARKER_PREFIX.length).trim();
|
|
2356
|
+
}
|
|
2357
|
+
else {
|
|
2358
|
+
jsonCandidate = rawStdout.trim();
|
|
2359
|
+
}
|
|
2360
|
+
const rawBytes = Buffer.from(jsonCandidate, 'utf8');
|
|
2361
|
+
if (rawBytes.byteLength === 0) {
|
|
2362
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'empty Stage B JSON result envelope');
|
|
2363
|
+
}
|
|
2364
|
+
if (rawBytes.byteLength > MAX_STAGE_B_RESULT_BYTES) {
|
|
2365
|
+
throw new HardwareRunnerError('PAYLOAD_TOO_LARGE', `Stage B result envelope exceeds ${MAX_STAGE_B_RESULT_BYTES} bytes`);
|
|
2366
|
+
}
|
|
2367
|
+
assertNoDecodedSecret(jsonCandidate, scrubber);
|
|
2368
|
+
const parsed = parseStrictJsonBytes(rawBytes, MAX_STAGE_B_RESULT_BYTES, 'ARTIFACT_INVALID', '/stageB');
|
|
2369
|
+
const obj = expectNullProtoRecord(parsed, STAGE_B_ENVELOPE_KEYS, ['status'], 'ARTIFACT_INVALID', '/stageB');
|
|
2370
|
+
if (obj.status !== 'approved' && obj.status !== 'denied') {
|
|
2371
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'Stage B status must be "approved" or "denied"', '/stageB/status');
|
|
2372
|
+
}
|
|
2373
|
+
let reason;
|
|
2374
|
+
if (Object.hasOwn(obj, 'reason')) {
|
|
2375
|
+
if (obj.reason === null) {
|
|
2376
|
+
reason = obj.status === 'approved' ? null : 'BENCHMARK_DENIED';
|
|
2377
|
+
}
|
|
2378
|
+
else if (typeof obj.reason === 'string' && obj.reason.length >= 1 && obj.reason.length <= 256 && !hasLoneSurrogate(obj.reason)) {
|
|
2379
|
+
assertNoDecodedSecret(obj.reason, scrubber);
|
|
2380
|
+
if (obj.status === 'approved') {
|
|
2381
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'Stage B approved envelope must not specify non-null reason', '/stageB/reason');
|
|
2382
|
+
}
|
|
2383
|
+
reason = obj.reason;
|
|
2384
|
+
}
|
|
2385
|
+
else {
|
|
2386
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid Stage B reason string', '/stageB/reason');
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
else {
|
|
2390
|
+
reason = obj.status === 'approved' ? null : 'BENCHMARK_DENIED';
|
|
2391
|
+
}
|
|
2392
|
+
let detail;
|
|
2393
|
+
if (Object.hasOwn(obj, 'detail')) {
|
|
2394
|
+
if (obj.detail === null) {
|
|
2395
|
+
detail = null;
|
|
2396
|
+
}
|
|
2397
|
+
else if (typeof obj.detail === 'string' && obj.detail.length >= 1 && obj.detail.length <= LIMITS.string && !hasLoneSurrogate(obj.detail)) {
|
|
2398
|
+
assertNoDecodedSecret(obj.detail, scrubber);
|
|
2399
|
+
detail = obj.detail;
|
|
2400
|
+
}
|
|
2401
|
+
else {
|
|
2402
|
+
throw new HardwareRunnerError('ARTIFACT_INVALID', 'invalid Stage B detail field', '/stageB/detail');
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
const metrics = Object.hasOwn(obj, 'metrics') ? parseEnvelopeMetrics(obj.metrics, scrubber) : undefined;
|
|
2406
|
+
const findings = Object.hasOwn(obj, 'findings') ? parseEnvelopeFindings(obj.findings, scrubber) : undefined;
|
|
2407
|
+
const out = Object.create(null);
|
|
2408
|
+
out.status = obj.status;
|
|
2409
|
+
out.reason = reason;
|
|
2410
|
+
if (detail !== undefined)
|
|
2411
|
+
out.detail = detail;
|
|
2412
|
+
if (metrics !== undefined)
|
|
2413
|
+
out.metrics = metrics;
|
|
2414
|
+
if (findings !== undefined)
|
|
2415
|
+
out.findings = findings;
|
|
2416
|
+
assertNoDecodedSecret(canonicalJson(out), scrubber);
|
|
2417
|
+
return Object.freeze(out);
|
|
2418
|
+
}
|
|
2419
|
+
function readFiniteMetricValue(metrics, key) {
|
|
2420
|
+
if (!Object.hasOwn(metrics, key))
|
|
2421
|
+
return undefined;
|
|
2422
|
+
const val = metrics[key];
|
|
2423
|
+
if (typeof val !== 'number' || !Number.isFinite(val))
|
|
2424
|
+
return undefined;
|
|
2425
|
+
return Object.is(val, -0) ? 0 : val;
|
|
2426
|
+
}
|
|
2427
|
+
function checkMetricThresholds(rules, metrics) {
|
|
2428
|
+
if (rules.length === 0)
|
|
2429
|
+
return null;
|
|
2430
|
+
if (metrics === undefined) {
|
|
2431
|
+
return 'required quantitative metrics map is missing from Stage B output';
|
|
2432
|
+
}
|
|
2433
|
+
for (const rule of rules) {
|
|
2434
|
+
const observed = readFiniteMetricValue(metrics, rule.metric);
|
|
2435
|
+
if (observed === undefined) {
|
|
2436
|
+
return `missing numeric metric "${rule.metric}"`;
|
|
2437
|
+
}
|
|
2438
|
+
if (rule.kind === 'bounds') {
|
|
2439
|
+
if (rule.min !== undefined && observed < rule.min) {
|
|
2440
|
+
return `metric "${rule.metric}" (${observed}) is below min ${rule.min}`;
|
|
2441
|
+
}
|
|
2442
|
+
if (rule.max !== undefined && observed > rule.max) {
|
|
2443
|
+
return `metric "${rule.metric}" (${observed}) exceeds max ${rule.max}`;
|
|
2444
|
+
}
|
|
2445
|
+
continue;
|
|
2446
|
+
}
|
|
2447
|
+
const baseline = readFiniteMetricValue(metrics, rule.baselineMetric);
|
|
2448
|
+
if (baseline === undefined) {
|
|
2449
|
+
return `missing numeric baseline metric "${rule.baselineMetric}"`;
|
|
2450
|
+
}
|
|
2451
|
+
if (rule.operator === 'min_ratio') {
|
|
2452
|
+
if (!(baseline > 0) || observed / baseline < rule.threshold) {
|
|
2453
|
+
return `comparative ratio ${rule.metric}/${rule.baselineMetric} failed min_ratio ${rule.threshold}`;
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
else if (rule.operator === 'max_ratio') {
|
|
2457
|
+
if (!(baseline > 0) || observed / baseline > rule.threshold) {
|
|
2458
|
+
return `comparative ratio ${rule.metric}/${rule.baselineMetric} failed max_ratio ${rule.threshold}`;
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
2461
|
+
else if (observed - baseline > rule.threshold) {
|
|
2462
|
+
return `comparative delta ${rule.metric}-${rule.baselineMetric} failed max_delta ${rule.threshold}`;
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
return null;
|
|
2466
|
+
}
|
|
2467
|
+
/**
|
|
2468
|
+
* Recursively remove a directory or file tree fail-closed without ever calling `chmod` on regular
|
|
2469
|
+
* files (preserving multiply linked inode permissions), restoring `0o700` on directories only so
|
|
2470
|
+
* sealed entries can be unlinked, propagating removal errors, and verifying `ENOENT` on completion.
|
|
2471
|
+
*/
|
|
2472
|
+
export async function removeTreeFailClosed(targetPath) {
|
|
2473
|
+
const resolved = resolve(targetPath);
|
|
2474
|
+
const removeNode = async (current, depth) => {
|
|
2475
|
+
if (depth > 64) {
|
|
2476
|
+
throw new RunnerTeardownError(`cleanup path "${resolved}" exceeds maximum nesting depth`);
|
|
2477
|
+
}
|
|
2478
|
+
let st;
|
|
2479
|
+
try {
|
|
2480
|
+
st = await lstat(current);
|
|
2481
|
+
}
|
|
2482
|
+
catch (err) {
|
|
2483
|
+
if (err?.code === 'ENOENT')
|
|
2484
|
+
return;
|
|
2485
|
+
throw new RunnerTeardownError(`failed to inspect path "${current}" during cleanup: ${err instanceof Error ? err.message : String(err)}`);
|
|
2486
|
+
}
|
|
2487
|
+
if (st.isSymbolicLink() || !st.isDirectory()) {
|
|
2488
|
+
// NEVER chmod regular files (which could mutate a multiply linked inode); unlink directory entry directly.
|
|
2489
|
+
try {
|
|
2490
|
+
await unlink(current);
|
|
2491
|
+
}
|
|
2492
|
+
catch (err) {
|
|
2493
|
+
if (err?.code !== 'ENOENT') {
|
|
2494
|
+
throw new RunnerTeardownError(`failed to unlink "${current}" during cleanup: ${err instanceof Error ? err.message : String(err)}`);
|
|
2495
|
+
}
|
|
2496
|
+
}
|
|
2497
|
+
return;
|
|
2498
|
+
}
|
|
2499
|
+
if ((st.mode & 0o700) !== 0o700) {
|
|
2500
|
+
try {
|
|
2501
|
+
await chmod(current, 0o700);
|
|
2502
|
+
}
|
|
2503
|
+
catch (err) {
|
|
2504
|
+
throw new RunnerTeardownError(`failed to restore directory permissions on "${current}" during cleanup: ${err instanceof Error ? err.message : String(err)}`);
|
|
2505
|
+
}
|
|
2506
|
+
}
|
|
2507
|
+
let entries;
|
|
2508
|
+
try {
|
|
2509
|
+
entries = await readdir(current);
|
|
2510
|
+
}
|
|
2511
|
+
catch (err) {
|
|
2512
|
+
throw new RunnerTeardownError(`failed to list directory "${current}" during cleanup: ${err instanceof Error ? err.message : String(err)}`);
|
|
2513
|
+
}
|
|
2514
|
+
for (const name of entries) {
|
|
2515
|
+
await removeNode(join(current, name), depth + 1);
|
|
2516
|
+
}
|
|
2517
|
+
try {
|
|
2518
|
+
await rmdir(current);
|
|
2519
|
+
}
|
|
2520
|
+
catch (err) {
|
|
2521
|
+
if (err?.code !== 'ENOENT') {
|
|
2522
|
+
throw new RunnerTeardownError(`failed to remove directory "${current}" during cleanup: ${err instanceof Error ? err.message : String(err)}`);
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2525
|
+
};
|
|
2526
|
+
await removeNode(resolved, 0);
|
|
2527
|
+
const postStat = await lstat(resolved).catch((err) => {
|
|
2528
|
+
if (err?.code === 'ENOENT')
|
|
2529
|
+
return null;
|
|
2530
|
+
throw new RunnerTeardownError(`failed to verify removal of "${resolved}": ${err instanceof Error ? err.message : String(err)}`);
|
|
2531
|
+
});
|
|
2532
|
+
if (postStat !== null) {
|
|
2533
|
+
throw new RunnerTeardownError(`cleanup verification failed: "${resolved}" still exists`);
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
async function discoverStageACandidateScript(candidateDir) {
|
|
2537
|
+
for (const rel of STAGE_A_CANDIDATE_ENTRYPOINTS) {
|
|
2538
|
+
const abs = join(candidateDir, ...rel.split('/'));
|
|
2539
|
+
const st = await lstat(abs).catch(() => null);
|
|
2540
|
+
if (st !== null && !st.isSymbolicLink() && st.isFile() && (st.mode & 0o111) !== 0) {
|
|
2541
|
+
return rel;
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2544
|
+
return null;
|
|
2545
|
+
}
|
|
2546
|
+
async function discoverStageBWorkloadScript(workloadDir) {
|
|
2547
|
+
for (const rel of STAGE_B_WORKLOAD_ENTRYPOINTS) {
|
|
2548
|
+
const abs = join(workloadDir, ...rel.split('/'));
|
|
2549
|
+
const st = await lstat(abs).catch(() => null);
|
|
2550
|
+
if (st !== null && !st.isSymbolicLink() && st.isFile()) {
|
|
2551
|
+
return { relPath: rel, directExec: (st.mode & 0o111) !== 0 };
|
|
2552
|
+
}
|
|
2553
|
+
}
|
|
2554
|
+
throw new HardwareRunnerError('CONFIG_INVALID', `worker held-out workload is missing a trusted Stage B entrypoint (${STAGE_B_WORKLOAD_ENTRYPOINTS.join(', ')})`, '/heldOutWorkloadsDir');
|
|
2555
|
+
}
|
|
2556
|
+
function buildSanitizedPathEnv(toolchainPaths, isDocker) {
|
|
2557
|
+
const defaults = isDocker
|
|
2558
|
+
? ['/usr/local/nvidia/bin', '/usr/local/cuda/bin', '/opt/rocm/bin', '/usr/local/bin', '/usr/bin', '/bin']
|
|
2559
|
+
: ['/usr/local/cuda/bin', '/opt/rocm/bin', '/usr/local/bin', '/usr/bin', '/bin'];
|
|
2560
|
+
return [...toolchainPaths, ...defaults].join(':');
|
|
2561
|
+
}
|
|
2562
|
+
function buildDeviceVisibilityEnv(targetHardware) {
|
|
2563
|
+
const count = targetHardware.deviceCount ?? 1;
|
|
2564
|
+
const csv = buildVisibleDevicesCsv(count);
|
|
2565
|
+
const accel = targetHardware.accelerator.toLowerCase();
|
|
2566
|
+
if (accel.startsWith('sm_'))
|
|
2567
|
+
return { CUDA_VISIBLE_DEVICES: csv };
|
|
2568
|
+
if (accel.startsWith('gfx'))
|
|
2569
|
+
return { ROCR_VISIBLE_DEVICES: csv, HIP_VISIBLE_DEVICES: csv };
|
|
2570
|
+
if (accel.startsWith('ascend'))
|
|
2571
|
+
return { ASCEND_RT_VISIBLE_DEVICES: csv };
|
|
2572
|
+
return {};
|
|
2573
|
+
}
|
|
2574
|
+
function boundDiagnosticSnippet(text, scrubber, maxChars = LIMITS.findingEvidence) {
|
|
2575
|
+
const scrubbed = scrubber.scrub(text).trim();
|
|
2576
|
+
if (!scrubbed)
|
|
2577
|
+
return '';
|
|
2578
|
+
if (scrubbed.length <= maxChars)
|
|
2579
|
+
return scrubbed;
|
|
2580
|
+
const suffix = '...(truncated)';
|
|
2581
|
+
if (maxChars <= suffix.length) {
|
|
2582
|
+
let end = Math.max(0, maxChars);
|
|
2583
|
+
if (end > 0) {
|
|
2584
|
+
const lastCode = scrubbed.charCodeAt(end - 1);
|
|
2585
|
+
if (lastCode >= 0xd800 && lastCode <= 0xdbff)
|
|
2586
|
+
end -= 1;
|
|
2587
|
+
}
|
|
2588
|
+
return scrubbed.slice(0, end);
|
|
2589
|
+
}
|
|
2590
|
+
let end = maxChars - suffix.length;
|
|
2591
|
+
if (end > 0) {
|
|
2592
|
+
const lastCode = scrubbed.charCodeAt(end - 1);
|
|
2593
|
+
if (lastCode >= 0xd800 && lastCode <= 0xdbff)
|
|
2594
|
+
end -= 1;
|
|
2595
|
+
}
|
|
2596
|
+
return `${scrubbed.slice(0, end)}${suffix}`;
|
|
2597
|
+
}
|
|
2598
|
+
function buildSupervisorStageBFailureDiag(result) {
|
|
2599
|
+
if (result.exitCode !== null) {
|
|
2600
|
+
return `Stage B exited with code ${String(result.exitCode)}`;
|
|
2601
|
+
}
|
|
2602
|
+
if (result.signal !== null) {
|
|
2603
|
+
return `Stage B terminated by signal ${result.signal}`;
|
|
2604
|
+
}
|
|
2605
|
+
return 'Stage B execution failed';
|
|
2606
|
+
}
|
|
2607
|
+
async function writePrivateSeccompProfileFile(filePath) {
|
|
2608
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
2609
|
+
const fh = await open(filePath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | noFollow, 0o600);
|
|
2610
|
+
try {
|
|
2611
|
+
const jsonBytes = Buffer.from(buildDockerStageBSeccompProfileJson(), 'utf8');
|
|
2612
|
+
await writeAllToHandle(fh, jsonBytes);
|
|
2613
|
+
await fh.chmod(0o400);
|
|
2614
|
+
await fh.sync();
|
|
2615
|
+
}
|
|
2616
|
+
finally {
|
|
2617
|
+
await fh.close();
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
/**
|
|
2621
|
+
* Execute the full two-stage zero-trust blind evaluation for a leased hardware benchmark job:
|
|
2622
|
+
* - Snapshots `held_out_workloads/<id>` into an immutable `0o500`/`0o400` private job snapshot before Stage A.
|
|
2623
|
+
* - Stage A: isolated compile on frozen candidate tree WITHOUT `held_out_workloads`, sealing `.cubin`/`.o`/`.sass` outputs `0o400`.
|
|
2624
|
+
* - Stage B: isolated blind correctness + benchmark with ONLY the single immutable workload snapshot and sealed `stage-a-out/` read-only, kernel socket denial, and ZERO exported files or raw stderr disclosure.
|
|
2625
|
+
*/
|
|
2626
|
+
export async function evaluateBenchmarkJob(options) {
|
|
2627
|
+
const { config, grant } = options;
|
|
2628
|
+
const { job } = grant;
|
|
2629
|
+
const processRunner = options.processRunner ?? defaultStageProcessRunner;
|
|
2630
|
+
const probeCollector = options.probe ?? collectHardwareProvenance;
|
|
2631
|
+
if (config.sandboxBackend === 'native_os' && config.probeMode === 'physical') {
|
|
2632
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'native_os sandbox backend cannot enforce isolated physical accelerator device allocation; docker backend is required');
|
|
2633
|
+
}
|
|
2634
|
+
const resolvedWorkDir = resolve(config.workDir);
|
|
2635
|
+
const resolvedWorkloadsDir = resolve(config.heldOutWorkloadsDir);
|
|
2636
|
+
const resolvedTlsCa = config.tlsCaPath !== undefined ? resolve(config.tlsCaPath) : undefined;
|
|
2637
|
+
if (pathsOverlap(resolvedWorkDir, resolvedWorkloadsDir)) {
|
|
2638
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'workDir and heldOutWorkloadsDir must be disjoint directories', '/heldOutWorkloadsDir');
|
|
2639
|
+
}
|
|
2640
|
+
if (resolvedTlsCa !== undefined && (pathsOverlap(resolvedWorkDir, resolvedTlsCa) || pathsOverlap(resolvedWorkloadsDir, resolvedTlsCa))) {
|
|
2641
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'tlsCaPath must be disjoint from workDir and heldOutWorkloadsDir', '/tlsCaPath');
|
|
2642
|
+
}
|
|
2643
|
+
await assertNoSymlinkAncestors(resolvedWorkDir, {
|
|
2644
|
+
checkLeaf: true,
|
|
2645
|
+
code: 'CONFIG_INVALID',
|
|
2646
|
+
diagPath: '/workDir',
|
|
2647
|
+
});
|
|
2648
|
+
await mkdir(resolvedWorkDir, { recursive: true, mode: 0o700 });
|
|
2649
|
+
const workDirStat = await lstat(resolvedWorkDir);
|
|
2650
|
+
if (workDirStat.isSymbolicLink() || !workDirStat.isDirectory()) {
|
|
2651
|
+
throw new HardwareRunnerError('CONFIG_INVALID', 'workDir must be a non-symlink directory', '/workDir');
|
|
2652
|
+
}
|
|
2653
|
+
await chmod(resolvedWorkDir, 0o700);
|
|
2654
|
+
for (const tcPath of config.toolchainPaths) {
|
|
2655
|
+
if (isDockerSocketPath(tcPath)) {
|
|
2656
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'toolchainPaths must not reference container sockets');
|
|
2657
|
+
}
|
|
2658
|
+
await assertNoSymlinkAncestors(tcPath, {
|
|
2659
|
+
checkLeaf: true,
|
|
2660
|
+
code: 'CONFIG_INVALID',
|
|
2661
|
+
diagPath: '/toolchainPaths',
|
|
2662
|
+
});
|
|
2663
|
+
}
|
|
2664
|
+
const deadlineChecker = resolveMonotonicDeadlineChecker(options);
|
|
2665
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, 'evaluator entry', options.signal);
|
|
2666
|
+
const baseForbiddenHostPaths = [
|
|
2667
|
+
resolvedWorkDir,
|
|
2668
|
+
resolvedWorkloadsDir,
|
|
2669
|
+
...(resolvedTlsCa !== undefined ? [resolvedTlsCa] : []),
|
|
2670
|
+
];
|
|
2671
|
+
const probeHostExecutables = options.host?.probeExecutables ?? true;
|
|
2672
|
+
const canonicalToolchainPaths = validateAndCanonicalizeToolchainMountsSync({
|
|
2673
|
+
toolchainPaths: config.toolchainPaths,
|
|
2674
|
+
forbiddenPaths: baseForbiddenHostPaths,
|
|
2675
|
+
requireExistingOnDisk: probeHostExecutables,
|
|
2676
|
+
...(deadlineChecker !== undefined ? { deadlineChecker } : {}),
|
|
2677
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
2678
|
+
});
|
|
2679
|
+
// Register worker secrets and lease tokens into SecretScrubber; NEVER pass secrets into sandbox env!
|
|
2680
|
+
const scrubber = new SecretScrubber();
|
|
2681
|
+
const registeredSecrets = [config.workerToken, grant.leaseToken, ...(options.extraSecrets ?? [])];
|
|
2682
|
+
for (const sec of registeredSecrets) {
|
|
2683
|
+
if (typeof sec === 'string' && sec.length > 0) {
|
|
2684
|
+
scrubber.register(sec);
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
const secretOverlapBytes = computeSecretScanOverlapBytes(registeredSecrets);
|
|
2688
|
+
const supervisorDir = join(resolvedWorkDir, `job-${grant.jobId.replace(/[^A-Za-z0-9_.-]/g, '_')}-ep${grant.leaseEpoch}-${randomBytes(6).toString('hex')}`);
|
|
2689
|
+
const jobRoot = supervisorDir;
|
|
2690
|
+
const internalSupervisorDir = join(jobRoot, 'supervisor');
|
|
2691
|
+
const workloadSnapshotDir = join(internalSupervisorDir, 'workload-snapshot');
|
|
2692
|
+
const stageARoot = join(jobRoot, 'stage-a');
|
|
2693
|
+
const candidateDir = join(stageARoot, 'candidate');
|
|
2694
|
+
const stageAOutDir = join(stageARoot, 'stage-a-out');
|
|
2695
|
+
const stageAScratchDir = join(stageARoot, 'scratch');
|
|
2696
|
+
const stageBRoot = join(jobRoot, 'stage-b');
|
|
2697
|
+
const stageBScratchDir = join(stageBRoot, 'scratch');
|
|
2698
|
+
await mkdir(jobRoot, { mode: 0o700 });
|
|
2699
|
+
let keepJobRootForUpload = false;
|
|
2700
|
+
let cleanedUpJobRoot = false;
|
|
2701
|
+
let sealedOutputs = Object.freeze([]);
|
|
2702
|
+
const cleanupJobRoot = async (cleanupOpts) => {
|
|
2703
|
+
if (cleanedUpJobRoot)
|
|
2704
|
+
return;
|
|
2705
|
+
if (cleanupOpts?.preserveSealedOutputs === true && sealedOutputs.length > 0) {
|
|
2706
|
+
await removeTreeFailClosed(internalSupervisorDir);
|
|
2707
|
+
await removeTreeFailClosed(stageBRoot);
|
|
2708
|
+
await removeTreeFailClosed(candidateDir);
|
|
2709
|
+
await removeTreeFailClosed(stageAScratchDir);
|
|
2710
|
+
return;
|
|
2711
|
+
}
|
|
2712
|
+
await removeTreeFailClosed(jobRoot);
|
|
2713
|
+
cleanedUpJobRoot = true;
|
|
2714
|
+
};
|
|
2715
|
+
let primaryEvalErr;
|
|
2716
|
+
let finalCleanupErr = null;
|
|
2717
|
+
try {
|
|
2718
|
+
// Cleanup ownership is active immediately after mkdir(jobRoot) — BEFORE subdirectory creation!
|
|
2719
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, 'jobRoot setup', options.signal);
|
|
2720
|
+
await assertNoSymlinkAncestors(jobRoot, { checkLeaf: true, code: 'RUNNER_SANDBOX_FAILED', diagPath: '/workDir' });
|
|
2721
|
+
await mkdir(internalSupervisorDir, { mode: 0o700 });
|
|
2722
|
+
await mkdir(stageARoot, { mode: 0o700 });
|
|
2723
|
+
await mkdir(candidateDir, { mode: 0o755 });
|
|
2724
|
+
await mkdir(stageAOutDir, { mode: 0o700 });
|
|
2725
|
+
await mkdir(stageAScratchDir, { mode: 0o700 });
|
|
2726
|
+
// Snapshot worker-owned held_out_workloads/<id> BEFORE Stage A starts.
|
|
2727
|
+
// Classify any worker-owned workload missing/corrupt error as worker infrastructure (NEVER candidate denial!).
|
|
2728
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, 'held-out workload snapshot', options.signal);
|
|
2729
|
+
let workloadSnapshot;
|
|
2730
|
+
try {
|
|
2731
|
+
workloadSnapshot = await snapshotHeldOutWorkload(resolvedWorkloadsDir, job.heldOutWorkloadId, workloadSnapshotDir, options.signal !== undefined ? { signal: options.signal } : {});
|
|
2732
|
+
}
|
|
2733
|
+
catch (wlErr) {
|
|
2734
|
+
if (isRunnerTeardownError(wlErr))
|
|
2735
|
+
throw wlErr;
|
|
2736
|
+
if (wlErr instanceof HardwareRunnerError && wlErr.code === 'QUEUE_LEASE_FENCED')
|
|
2737
|
+
throw wlErr;
|
|
2738
|
+
if (options.signal?.aborted) {
|
|
2739
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'held-out workload snapshot aborted');
|
|
2740
|
+
}
|
|
2741
|
+
if (wlErr instanceof HardwareRunnerError && (wlErr.code === 'CONFIG_INVALID' || wlErr.code === 'RUNNER_SANDBOX_FAILED')) {
|
|
2742
|
+
throw wlErr;
|
|
2743
|
+
}
|
|
2744
|
+
throw new HardwareRunnerError('CONFIG_INVALID', wlErr instanceof Error ? wlErr.message : 'failed to snapshot worker held-out workload', '/heldOutWorkloadsDir', { cause: wlErr });
|
|
2745
|
+
}
|
|
2746
|
+
const isDocker = config.sandboxBackend === 'docker';
|
|
2747
|
+
const targetDeviceCount = job.targetHardware.deviceCount ?? 1;
|
|
2748
|
+
const isRocmTarget = job.targetHardware.accelerator.toLowerCase().startsWith('gfx');
|
|
2749
|
+
// Resolve allocated device identity ONCE so both physical provenance and Docker stages bind identical GPU(s)!
|
|
2750
|
+
let resolvedRocmNodes = options.allocatedDeviceNodes;
|
|
2751
|
+
let resolvedDeviceIndices = options.allocatedDeviceIndices;
|
|
2752
|
+
if (isRocmTarget && (isDocker || options.allocatedDeviceNodes !== undefined || options.allocatedDeviceIndices !== undefined)) {
|
|
2753
|
+
const requireRocmIndexMapping = config.probeMode === 'physical'
|
|
2754
|
+
&& (probeHostExecutables || options.sysfsRoot !== undefined || options.probe === undefined);
|
|
2755
|
+
const rocmAllocation = resolveAllocatedRocmDevicesSync({
|
|
2756
|
+
deviceCount: targetDeviceCount,
|
|
2757
|
+
...(options.allocatedDeviceNodes !== undefined ? { explicitNodes: options.allocatedDeviceNodes } : {}),
|
|
2758
|
+
...(options.allocatedDeviceIndices !== undefined ? { explicitIndices: options.allocatedDeviceIndices } : {}),
|
|
2759
|
+
...(options.sysfsRoot !== undefined ? { sysfsRoot: options.sysfsRoot } : {}),
|
|
2760
|
+
...(options.devRoot !== undefined ? { devRoot: options.devRoot } : {}),
|
|
2761
|
+
verifyCharDevices: isDocker && probeHostExecutables,
|
|
2762
|
+
requireIndexMapping: requireRocmIndexMapping,
|
|
2763
|
+
});
|
|
2764
|
+
resolvedRocmNodes = rocmAllocation.renderNodes;
|
|
2765
|
+
if (rocmAllocation.deviceIndices !== undefined) {
|
|
2766
|
+
resolvedDeviceIndices = rocmAllocation.deviceIndices;
|
|
2767
|
+
}
|
|
2768
|
+
}
|
|
2769
|
+
else if (resolvedDeviceIndices !== undefined) {
|
|
2770
|
+
resolvedDeviceIndices = validateExplicitDeviceIndices(resolvedDeviceIndices, targetDeviceCount, 64);
|
|
2771
|
+
}
|
|
2772
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, 'hardware provenance probe', options.signal);
|
|
2773
|
+
const hardwareProvenance = await probeCollector({
|
|
2774
|
+
probeMode: config.probeMode,
|
|
2775
|
+
targetCellId: job.targetCellId,
|
|
2776
|
+
targetHardware: job.targetHardware,
|
|
2777
|
+
capabilities: config.capabilities,
|
|
2778
|
+
workloadDigest: workloadSnapshot.digest,
|
|
2779
|
+
sandboxBackend: config.sandboxBackend,
|
|
2780
|
+
...(resolvedDeviceIndices !== undefined ? { allocatedDeviceIndices: resolvedDeviceIndices } : {}),
|
|
2781
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
2782
|
+
});
|
|
2783
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, 'candidate workspace reconstruction', options.signal);
|
|
2784
|
+
await reconstructCandidateWorkspace({
|
|
2785
|
+
candidateDir,
|
|
2786
|
+
candidateArtifacts: job.candidateArtifacts,
|
|
2787
|
+
downloadInputBlob: options.downloadInputBlob,
|
|
2788
|
+
...(options.maxBlobBytes !== undefined ? { maxBlobBytes: options.maxBlobBytes } : {}),
|
|
2789
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
2790
|
+
});
|
|
2791
|
+
const pathEnv = buildSanitizedPathEnv(canonicalToolchainPaths, isDocker);
|
|
2792
|
+
const deviceVisEnv = buildDeviceVisibilityEnv(job.targetHardware);
|
|
2793
|
+
const dockerSeccompPath = join(internalSupervisorDir, 'docker-seccomp.json');
|
|
2794
|
+
if (isDocker) {
|
|
2795
|
+
await writePrivateSeccompProfileFile(dockerSeccompPath);
|
|
2796
|
+
}
|
|
2797
|
+
const deadlineInputFields = {
|
|
2798
|
+
...(options.leaseDeadlineMonoMs !== undefined ? { leaseDeadlineMonoMs: options.leaseDeadlineMonoMs } : {}),
|
|
2799
|
+
...(options.getLeaseDeadlineMonoMs !== undefined ? { getLeaseDeadlineMonoMs: options.getLeaseDeadlineMonoMs } : {}),
|
|
2800
|
+
...(options.nowMonotonicMs !== undefined ? { nowMonotonicMs: options.nowMonotonicMs } : {}),
|
|
2801
|
+
};
|
|
2802
|
+
// -------------------------------------------------------------------------
|
|
2803
|
+
// Stage A: Candidate Compile (NO held_out_workloads or snapshot access!)
|
|
2804
|
+
// -------------------------------------------------------------------------
|
|
2805
|
+
let stageACmd;
|
|
2806
|
+
let stageAArgs;
|
|
2807
|
+
if (options.stageACommand !== undefined) {
|
|
2808
|
+
stageACmd = options.stageACommand.command;
|
|
2809
|
+
stageAArgs = options.stageACommand.args ?? [];
|
|
2810
|
+
}
|
|
2811
|
+
else {
|
|
2812
|
+
const discoveredRel = await discoverStageACandidateScript(candidateDir);
|
|
2813
|
+
if (discoveredRel === null) {
|
|
2814
|
+
await removeTreeFailClosed(internalSupervisorDir);
|
|
2815
|
+
await removeTreeFailClosed(stageARoot);
|
|
2816
|
+
const deniedNoEntry = {
|
|
2817
|
+
status: 'denied',
|
|
2818
|
+
reason: 'STAGE_A_ENTRYPOINT_MISSING',
|
|
2819
|
+
detail: `No executable Stage A build script found (${STAGE_A_CANDIDATE_ENTRYPOINTS.join(', ')})`,
|
|
2820
|
+
findings: Object.freeze([
|
|
2821
|
+
Object.freeze({
|
|
2822
|
+
title: 'Missing executable Stage A build script',
|
|
2823
|
+
severity: 'high',
|
|
2824
|
+
evidence: `Expected an executable build script at one of: ${STAGE_A_CANDIDATE_ENTRYPOINTS.join(', ')}`,
|
|
2825
|
+
}),
|
|
2826
|
+
]),
|
|
2827
|
+
hardwareProvenance,
|
|
2828
|
+
sealedOutputs: Object.freeze([]),
|
|
2829
|
+
cleanup: cleanupJobRoot,
|
|
2830
|
+
};
|
|
2831
|
+
keepJobRootForUpload = true;
|
|
2832
|
+
return deniedNoEntry;
|
|
2833
|
+
}
|
|
2834
|
+
stageACmd = isDocker ? `/workspace/candidate/${discoveredRel}` : join(candidateDir, ...discoveredRel.split('/'));
|
|
2835
|
+
stageAArgs = [];
|
|
2836
|
+
}
|
|
2837
|
+
const stageAEnv = {
|
|
2838
|
+
PATH: pathEnv,
|
|
2839
|
+
HOME: isDocker ? '/scratch' : stageAScratchDir,
|
|
2840
|
+
TMPDIR: isDocker ? '/scratch' : stageAScratchDir,
|
|
2841
|
+
LANG: 'C.UTF-8',
|
|
2842
|
+
TERM: 'dumb',
|
|
2843
|
+
LOOPWRIGHT_STAGE: 'A',
|
|
2844
|
+
LOOPWRIGHT_CANDIDATE_DIR: isDocker ? '/workspace/candidate' : candidateDir,
|
|
2845
|
+
LOOPWRIGHT_STAGE_A_OUT: isDocker ? '/workspace/stage-a-out' : stageAOutDir,
|
|
2846
|
+
LOOPWRIGHT_TARGET_CELL_ID: job.targetCellId,
|
|
2847
|
+
LOOPWRIGHT_TARGET_ACCELERATOR: job.targetHardware.accelerator,
|
|
2848
|
+
...deviceVisEnv,
|
|
2849
|
+
};
|
|
2850
|
+
const stageADeniedReadPaths = [
|
|
2851
|
+
resolvedWorkloadsDir,
|
|
2852
|
+
internalSupervisorDir,
|
|
2853
|
+
...(resolvedTlsCa !== undefined ? [resolvedTlsCa] : []),
|
|
2854
|
+
];
|
|
2855
|
+
const stageANativeSpec = isDocker
|
|
2856
|
+
? undefined
|
|
2857
|
+
: {
|
|
2858
|
+
stage: 'A',
|
|
2859
|
+
candidateDir,
|
|
2860
|
+
stageAOutDir,
|
|
2861
|
+
scratchDir: stageAScratchDir,
|
|
2862
|
+
toolchainPaths: canonicalToolchainPaths,
|
|
2863
|
+
explicitDeniedReadPaths: stageADeniedReadPaths,
|
|
2864
|
+
probeMode: config.probeMode,
|
|
2865
|
+
};
|
|
2866
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, 'Stage A launch preparation', options.signal);
|
|
2867
|
+
const stageADockerCompiled = isDocker
|
|
2868
|
+
? compileDockerSandboxCommand({
|
|
2869
|
+
stage: 'A',
|
|
2870
|
+
dockerImage: config.dockerImage,
|
|
2871
|
+
containerName: `lw-stage-a-${randomBytes(6).toString('hex')}`,
|
|
2872
|
+
targetHardware: job.targetHardware,
|
|
2873
|
+
candidateDir,
|
|
2874
|
+
stageAOutDir,
|
|
2875
|
+
toolchainPaths: canonicalToolchainPaths,
|
|
2876
|
+
forbiddenHostPaths: baseForbiddenHostPaths,
|
|
2877
|
+
seccompProfilePath: dockerSeccompPath,
|
|
2878
|
+
...(resolvedRocmNodes !== undefined ? { allocatedDeviceNodes: resolvedRocmNodes } : {}),
|
|
2879
|
+
...(resolvedDeviceIndices !== undefined ? { allocatedDeviceIndices: resolvedDeviceIndices } : {}),
|
|
2880
|
+
...(options.sysfsRoot !== undefined ? { sysfsRoot: options.sysfsRoot } : {}),
|
|
2881
|
+
...(options.devRoot !== undefined ? { devRoot: options.devRoot } : {}),
|
|
2882
|
+
command: stageACmd,
|
|
2883
|
+
args: stageAArgs,
|
|
2884
|
+
cwd: '/workspace/candidate',
|
|
2885
|
+
env: stageAEnv,
|
|
2886
|
+
...(options.host !== undefined ? { host: options.host } : {}),
|
|
2887
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
2888
|
+
...deadlineInputFields,
|
|
2889
|
+
...(options._testOnlyTrustedDockerRoot !== undefined
|
|
2890
|
+
? { _testOnlyTrustedDockerRoot: options._testOnlyTrustedDockerRoot }
|
|
2891
|
+
: {}),
|
|
2892
|
+
})
|
|
2893
|
+
: undefined;
|
|
2894
|
+
const stageAResult = await processRunner({
|
|
2895
|
+
stage: 'A',
|
|
2896
|
+
backend: config.sandboxBackend,
|
|
2897
|
+
command: stageACmd,
|
|
2898
|
+
args: stageAArgs,
|
|
2899
|
+
cwd: isDocker ? '/workspace/candidate' : candidateDir,
|
|
2900
|
+
env: stageAEnv,
|
|
2901
|
+
timeoutMs: config.stageATimeoutMs,
|
|
2902
|
+
probeMode: config.probeMode,
|
|
2903
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
2904
|
+
...deadlineInputFields,
|
|
2905
|
+
...(stageANativeSpec !== undefined ? { nativeStageSpec: stageANativeSpec } : {}),
|
|
2906
|
+
...(stageADockerCompiled !== undefined ? { dockerCompiled: stageADockerCompiled } : {}),
|
|
2907
|
+
...(options.host !== undefined ? { host: options.host } : {}),
|
|
2908
|
+
});
|
|
2909
|
+
if (stageAResult.timedOut || stageAResult.exitCode !== 0 || stageAResult.signal !== null) {
|
|
2910
|
+
await removeTreeFailClosed(internalSupervisorDir);
|
|
2911
|
+
await removeTreeFailClosed(stageARoot);
|
|
2912
|
+
const reason = stageAResult.timedOut ? 'STAGE_A_TIMEOUT' : 'STAGE_A_COMPILE_FAILED';
|
|
2913
|
+
const diag = boundDiagnosticSnippet(stageAResult.stderr || stageAResult.stdout || `Stage A exited with code ${String(stageAResult.exitCode)}`, scrubber);
|
|
2914
|
+
keepJobRootForUpload = true;
|
|
2915
|
+
return Object.freeze({
|
|
2916
|
+
status: 'denied',
|
|
2917
|
+
reason,
|
|
2918
|
+
detail: diag || reason,
|
|
2919
|
+
findings: Object.freeze([
|
|
2920
|
+
Object.freeze({
|
|
2921
|
+
title: stageAResult.timedOut ? 'Stage A compilation timed out' : 'Stage A compilation failed',
|
|
2922
|
+
severity: 'high',
|
|
2923
|
+
evidence: diag || reason,
|
|
2924
|
+
}),
|
|
2925
|
+
]),
|
|
2926
|
+
hardwareProvenance,
|
|
2927
|
+
sealedOutputs: Object.freeze([]),
|
|
2928
|
+
cleanup: cleanupJobRoot,
|
|
2929
|
+
});
|
|
2930
|
+
}
|
|
2931
|
+
// Seal Stage A outputs (O_NOFOLLOW, nlink === 1, <= 64 files, SecretScrubber, 0o400) BEFORE Stage B starts!
|
|
2932
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, 'Stage A output sealing', options.signal);
|
|
2933
|
+
sealedOutputs = await sealStageAOutputs({
|
|
2934
|
+
stageAOutDir,
|
|
2935
|
+
scrubber,
|
|
2936
|
+
secretOverlapBytes,
|
|
2937
|
+
...(options.maxBlobBytes !== undefined ? { maxBlobBytes: options.maxBlobBytes } : {}),
|
|
2938
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
2939
|
+
});
|
|
2940
|
+
// Fail-closed removal + ENOENT verification of Stage A candidate source & scratch before Stage B begins!
|
|
2941
|
+
await removeTreeFailClosed(candidateDir);
|
|
2942
|
+
await removeTreeFailClosed(stageAScratchDir);
|
|
2943
|
+
// -------------------------------------------------------------------------
|
|
2944
|
+
// Stage B: Blind Correctness & Benchmark (immutable workload snapshot
|
|
2945
|
+
// read-only, kernel socket denial, ZERO exported files!)
|
|
2946
|
+
// -------------------------------------------------------------------------
|
|
2947
|
+
await mkdir(stageBRoot, { mode: 0o700 });
|
|
2948
|
+
await mkdir(stageBScratchDir, { mode: 0o700 });
|
|
2949
|
+
let stageBResult = null;
|
|
2950
|
+
let stageBExecErr = null;
|
|
2951
|
+
try {
|
|
2952
|
+
let stageBCmd;
|
|
2953
|
+
let stageBArgs;
|
|
2954
|
+
if (options.stageBCommand !== undefined) {
|
|
2955
|
+
stageBCmd = options.stageBCommand.command;
|
|
2956
|
+
stageBArgs = options.stageBCommand.args ?? [];
|
|
2957
|
+
}
|
|
2958
|
+
else {
|
|
2959
|
+
const discoveredB = await discoverStageBWorkloadScript(workloadSnapshot.snapshotDir);
|
|
2960
|
+
const scriptInSandbox = isDocker
|
|
2961
|
+
? `/workspace/workload/${discoveredB.relPath}`
|
|
2962
|
+
: join(workloadSnapshot.snapshotDir, ...discoveredB.relPath.split('/'));
|
|
2963
|
+
if (discoveredB.directExec) {
|
|
2964
|
+
stageBCmd = scriptInSandbox;
|
|
2965
|
+
stageBArgs = [];
|
|
2966
|
+
}
|
|
2967
|
+
else {
|
|
2968
|
+
stageBCmd = '/bin/sh';
|
|
2969
|
+
stageBArgs = [scriptInSandbox];
|
|
2970
|
+
}
|
|
2971
|
+
}
|
|
2972
|
+
const stageBEnv = {
|
|
2973
|
+
PATH: pathEnv,
|
|
2974
|
+
HOME: isDocker ? '/scratch' : stageBScratchDir,
|
|
2975
|
+
TMPDIR: isDocker ? '/scratch' : stageBScratchDir,
|
|
2976
|
+
LANG: 'C.UTF-8',
|
|
2977
|
+
TERM: 'dumb',
|
|
2978
|
+
LOOPWRIGHT_STAGE: 'B',
|
|
2979
|
+
LOOPWRIGHT_STAGE_A_OUT: isDocker ? '/workspace/stage-a-out' : stageAOutDir,
|
|
2980
|
+
LOOPWRIGHT_HELD_OUT_WORKLOAD_DIR: isDocker ? '/workspace/workload' : workloadSnapshot.snapshotDir,
|
|
2981
|
+
LOOPWRIGHT_HELD_OUT_WORKLOAD_ID: job.heldOutWorkloadId,
|
|
2982
|
+
LOOPWRIGHT_TARGET_CELL_ID: job.targetCellId,
|
|
2983
|
+
LOOPWRIGHT_TARGET_ACCELERATOR: job.targetHardware.accelerator,
|
|
2984
|
+
...deviceVisEnv,
|
|
2985
|
+
};
|
|
2986
|
+
// Deny the entire live heldOutWorkloadsDir (including sibling workloads!) in Stage B;
|
|
2987
|
+
// Stage B may ONLY read its private immutable workloadSnapshotDir!
|
|
2988
|
+
const stageBDeniedPaths = [
|
|
2989
|
+
resolvedWorkloadsDir,
|
|
2990
|
+
...(resolvedTlsCa !== undefined ? [resolvedTlsCa] : []),
|
|
2991
|
+
];
|
|
2992
|
+
const stageBNativeSpec = isDocker
|
|
2993
|
+
? undefined
|
|
2994
|
+
: {
|
|
2995
|
+
stage: 'B',
|
|
2996
|
+
stageAOutDir,
|
|
2997
|
+
workloadSnapshotDir: workloadSnapshot.snapshotDir,
|
|
2998
|
+
scratchDir: stageBScratchDir,
|
|
2999
|
+
toolchainPaths: canonicalToolchainPaths,
|
|
3000
|
+
explicitDeniedReadPaths: stageBDeniedPaths,
|
|
3001
|
+
probeMode: config.probeMode,
|
|
3002
|
+
};
|
|
3003
|
+
assertLeaseDeadlineNotExpired(deadlineChecker, 'Stage B launch preparation', options.signal);
|
|
3004
|
+
const stageBDockerCompiled = isDocker
|
|
3005
|
+
? compileDockerSandboxCommand({
|
|
3006
|
+
stage: 'B',
|
|
3007
|
+
dockerImage: config.dockerImage,
|
|
3008
|
+
containerName: `lw-stage-b-${randomBytes(6).toString('hex')}`,
|
|
3009
|
+
targetHardware: job.targetHardware,
|
|
3010
|
+
stageAOutDir,
|
|
3011
|
+
workloadDir: workloadSnapshot.snapshotDir,
|
|
3012
|
+
toolchainPaths: canonicalToolchainPaths,
|
|
3013
|
+
forbiddenHostPaths: baseForbiddenHostPaths,
|
|
3014
|
+
seccompProfilePath: dockerSeccompPath,
|
|
3015
|
+
...(resolvedRocmNodes !== undefined ? { allocatedDeviceNodes: resolvedRocmNodes } : {}),
|
|
3016
|
+
...(resolvedDeviceIndices !== undefined ? { allocatedDeviceIndices: resolvedDeviceIndices } : {}),
|
|
3017
|
+
...(options.sysfsRoot !== undefined ? { sysfsRoot: options.sysfsRoot } : {}),
|
|
3018
|
+
...(options.devRoot !== undefined ? { devRoot: options.devRoot } : {}),
|
|
3019
|
+
command: stageBCmd,
|
|
3020
|
+
args: stageBArgs,
|
|
3021
|
+
cwd: '/workspace/workload',
|
|
3022
|
+
env: stageBEnv,
|
|
3023
|
+
...(options.host !== undefined ? { host: options.host } : {}),
|
|
3024
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
3025
|
+
...deadlineInputFields,
|
|
3026
|
+
...(options._testOnlyTrustedDockerRoot !== undefined
|
|
3027
|
+
? { _testOnlyTrustedDockerRoot: options._testOnlyTrustedDockerRoot }
|
|
3028
|
+
: {}),
|
|
3029
|
+
})
|
|
3030
|
+
: undefined;
|
|
3031
|
+
stageBResult = await processRunner({
|
|
3032
|
+
stage: 'B',
|
|
3033
|
+
backend: config.sandboxBackend,
|
|
3034
|
+
command: stageBCmd,
|
|
3035
|
+
args: stageBArgs,
|
|
3036
|
+
cwd: isDocker ? '/workspace/workload' : workloadSnapshot.snapshotDir,
|
|
3037
|
+
env: stageBEnv,
|
|
3038
|
+
timeoutMs: config.stageBTimeoutMs,
|
|
3039
|
+
probeMode: config.probeMode,
|
|
3040
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
3041
|
+
...deadlineInputFields,
|
|
3042
|
+
...(stageBNativeSpec !== undefined ? { nativeStageSpec: stageBNativeSpec } : {}),
|
|
3043
|
+
...(stageBDockerCompiled !== undefined ? { dockerCompiled: stageBDockerCompiled } : {}),
|
|
3044
|
+
...(options.host !== undefined ? { host: options.host } : {}),
|
|
3045
|
+
});
|
|
3046
|
+
}
|
|
3047
|
+
catch (err) {
|
|
3048
|
+
stageBExecErr = err;
|
|
3049
|
+
}
|
|
3050
|
+
// Export ZERO files from Stage B! Fail-closed removal + ENOENT verification of Stage B scratch and workload snapshot!
|
|
3051
|
+
let stageBCleanupErr = null;
|
|
3052
|
+
try {
|
|
3053
|
+
await removeTreeFailClosed(stageBRoot);
|
|
3054
|
+
}
|
|
3055
|
+
catch (err) {
|
|
3056
|
+
stageBCleanupErr = err;
|
|
3057
|
+
}
|
|
3058
|
+
try {
|
|
3059
|
+
await removeTreeFailClosed(internalSupervisorDir);
|
|
3060
|
+
}
|
|
3061
|
+
catch (err) {
|
|
3062
|
+
stageBCleanupErr ??= err;
|
|
3063
|
+
}
|
|
3064
|
+
if (isRunnerTeardownError(stageBExecErr)) {
|
|
3065
|
+
throw stageBExecErr;
|
|
3066
|
+
}
|
|
3067
|
+
if (stageBCleanupErr !== null) {
|
|
3068
|
+
throw stageBCleanupErr;
|
|
3069
|
+
}
|
|
3070
|
+
if (stageBExecErr !== null) {
|
|
3071
|
+
throw stageBExecErr;
|
|
3072
|
+
}
|
|
3073
|
+
if (stageBResult === null) {
|
|
3074
|
+
throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'Stage B produced no execution result');
|
|
3075
|
+
}
|
|
3076
|
+
if (stageBResult.timedOut) {
|
|
3077
|
+
keepJobRootForUpload = true;
|
|
3078
|
+
return Object.freeze({
|
|
3079
|
+
status: 'denied',
|
|
3080
|
+
reason: 'STAGE_B_TIMEOUT',
|
|
3081
|
+
detail: `Stage B benchmark timed out after ${config.stageBTimeoutMs}ms`,
|
|
3082
|
+
findings: Object.freeze([
|
|
3083
|
+
Object.freeze({
|
|
3084
|
+
title: 'Stage B blind benchmark timed out',
|
|
3085
|
+
severity: 'high',
|
|
3086
|
+
evidence: `Stage B exceeded ${config.stageBTimeoutMs}ms`,
|
|
3087
|
+
}),
|
|
3088
|
+
]),
|
|
3089
|
+
hardwareProvenance,
|
|
3090
|
+
sealedOutputs,
|
|
3091
|
+
cleanup: cleanupJobRoot,
|
|
3092
|
+
});
|
|
3093
|
+
}
|
|
3094
|
+
// Check nonzero exit or signal STRICTLY BEFORE parsing Stage B stdout so a failing or crashed
|
|
3095
|
+
// Stage B process can NEVER exfiltrate private held-out workload text via a denied JSON envelope!
|
|
3096
|
+
if (stageBResult.exitCode !== 0 || stageBResult.signal !== null) {
|
|
3097
|
+
const supervisorDiag = buildSupervisorStageBFailureDiag(stageBResult);
|
|
3098
|
+
keepJobRootForUpload = true;
|
|
3099
|
+
return Object.freeze({
|
|
3100
|
+
status: 'denied',
|
|
3101
|
+
reason: 'STAGE_B_EXECUTION_FAILED',
|
|
3102
|
+
detail: supervisorDiag,
|
|
3103
|
+
findings: Object.freeze([
|
|
3104
|
+
Object.freeze({
|
|
3105
|
+
title: 'Stage B blind evaluation failed',
|
|
3106
|
+
severity: 'high',
|
|
3107
|
+
evidence: supervisorDiag,
|
|
3108
|
+
}),
|
|
3109
|
+
]),
|
|
3110
|
+
hardwareProvenance,
|
|
3111
|
+
sealedOutputs,
|
|
3112
|
+
cleanup: cleanupJobRoot,
|
|
3113
|
+
});
|
|
3114
|
+
}
|
|
3115
|
+
const envelope = parseStageBResultEnvelope(stageBResult.stdout, scrubber);
|
|
3116
|
+
let finalStatus = envelope.status;
|
|
3117
|
+
let finalReason = envelope.reason;
|
|
3118
|
+
let finalDetail = envelope.detail;
|
|
3119
|
+
let finalFindings = envelope.findings;
|
|
3120
|
+
if (finalStatus === 'approved') {
|
|
3121
|
+
const thresholdViolation = checkMetricThresholds(job.metricThresholds, envelope.metrics);
|
|
3122
|
+
if (thresholdViolation !== null) {
|
|
3123
|
+
finalStatus = 'denied';
|
|
3124
|
+
finalReason = 'METRIC_THRESHOLD_FAILED';
|
|
3125
|
+
finalDetail = finalDetail ?? thresholdViolation;
|
|
3126
|
+
const thresholdFinding = Object.freeze({
|
|
3127
|
+
title: 'Quantitative metric threshold not met',
|
|
3128
|
+
severity: 'high',
|
|
3129
|
+
evidence: thresholdViolation,
|
|
3130
|
+
});
|
|
3131
|
+
const existing = finalFindings ?? [];
|
|
3132
|
+
finalFindings = Object.freeze([
|
|
3133
|
+
...existing.slice(0, Math.max(0, LIMITS.findings - 1)),
|
|
3134
|
+
thresholdFinding,
|
|
3135
|
+
]);
|
|
3136
|
+
}
|
|
3137
|
+
}
|
|
3138
|
+
keepJobRootForUpload = true;
|
|
3139
|
+
return Object.freeze({
|
|
3140
|
+
status: finalStatus,
|
|
3141
|
+
reason: finalReason,
|
|
3142
|
+
...(finalDetail !== undefined ? { detail: finalDetail } : {}),
|
|
3143
|
+
...(envelope.metrics !== undefined ? { metrics: envelope.metrics } : {}),
|
|
3144
|
+
...(finalFindings !== undefined ? { findings: finalFindings } : {}),
|
|
3145
|
+
hardwareProvenance,
|
|
3146
|
+
sealedOutputs,
|
|
3147
|
+
cleanup: cleanupJobRoot,
|
|
3148
|
+
});
|
|
3149
|
+
}
|
|
3150
|
+
catch (err) {
|
|
3151
|
+
primaryEvalErr = err;
|
|
3152
|
+
}
|
|
3153
|
+
finally {
|
|
3154
|
+
if (!keepJobRootForUpload) {
|
|
3155
|
+
try {
|
|
3156
|
+
await cleanupJobRoot();
|
|
3157
|
+
}
|
|
3158
|
+
catch (cleanErr) {
|
|
3159
|
+
finalCleanupErr = cleanErr instanceof RunnerTeardownError
|
|
3160
|
+
? cleanErr
|
|
3161
|
+
: new RunnerTeardownError(cleanErr instanceof Error ? cleanErr.message : 'failed to roll back jobRoot during cleanup', { cause: cleanErr });
|
|
3162
|
+
}
|
|
3163
|
+
}
|
|
3164
|
+
}
|
|
3165
|
+
if (isRunnerTeardownError(primaryEvalErr)) {
|
|
3166
|
+
throw primaryEvalErr;
|
|
3167
|
+
}
|
|
3168
|
+
if (finalCleanupErr !== null) {
|
|
3169
|
+
throw finalCleanupErr;
|
|
3170
|
+
}
|
|
3171
|
+
throw primaryEvalErr;
|
|
3172
|
+
}
|
|
3173
|
+
export function createTwoStageEvaluator(defaults = {}) {
|
|
3174
|
+
return options => evaluateBenchmarkJob({
|
|
3175
|
+
...defaults,
|
|
3176
|
+
...options,
|
|
3177
|
+
});
|
|
3178
|
+
}
|