@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,2642 @@
|
|
|
1
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, realpathSync, rmdirSync, statSync, unlinkSync, } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
6
|
+
import { assertManifestScopeInvariants, effectiveProtectedPaths, isControlRootProposalWritableAllowed, normalizeRelativePath, pathCoveredBy, resolveManifestControlRoot, tryNormalizeRelativePath, validateExecutionAuthority, } from './schema.js';
|
|
7
|
+
import { SecretScrubber } from './scrubber.js';
|
|
8
|
+
import { GITHUB_PROTECTED_AUTOMATION_PATHS, LOCAL_PROTECTED_AUTOMATION_PATHS, TaskpackError, } from './types.js';
|
|
9
|
+
export const TRUSTED_SEATBELT_PATHS = Object.freeze(['/usr/bin/sandbox-exec']);
|
|
10
|
+
export const TRUSTED_BWRAP_PATHS = Object.freeze(['/usr/bin/bwrap', '/bin/bwrap', '/usr/local/bin/bwrap']);
|
|
11
|
+
export const TRUSTED_PYTHON_PATHS = Object.freeze(['/usr/bin/python3', '/bin/python3', '/usr/local/bin/python3']);
|
|
12
|
+
export const TRUSTED_DOCKER_PATHS = Object.freeze(['/usr/local/bin/docker', '/usr/bin/docker', '/opt/homebrew/bin/docker']);
|
|
13
|
+
export const DEFAULT_DENIED_HOME_SUBPATHS = Object.freeze([
|
|
14
|
+
'.ssh', '.aws', '.gnupg', '.kube', '.docker', '.config/gh', '.npmrc', '.pypirc', '.netrc',
|
|
15
|
+
]);
|
|
16
|
+
/** Neutral built-in workspace subpaths protected under `'local'` mode (active controlRoot and manifest paths are added dynamically). */
|
|
17
|
+
export const ALWAYS_PROTECTED_WORKSPACE_SUBPATHS = Object.freeze(['.git']);
|
|
18
|
+
/** Built-in workspace subpaths protected under `'github'` mode (`.github/workflows/**` unlocked only via dual-key `allowWorkflowWrites`). */
|
|
19
|
+
export const GITHUB_PROTECTED_WORKSPACE_SUBPATHS = Object.freeze(['.git', '.github']);
|
|
20
|
+
export const DEFAULT_REQUIRED_SANDBOX_CAPABILITIES = Object.freeze([
|
|
21
|
+
'filesystemReadContainment',
|
|
22
|
+
'filesystemWriteContainment',
|
|
23
|
+
'protectedPathReadOnlyMask',
|
|
24
|
+
'networkIsolation',
|
|
25
|
+
'processTreeCleanup',
|
|
26
|
+
]);
|
|
27
|
+
export const SANDBOX_CAPABILITIES_BY_BACKEND = Object.freeze({
|
|
28
|
+
'macos-seatbelt': Object.freeze([
|
|
29
|
+
'filesystemReadContainment',
|
|
30
|
+
'filesystemWriteContainment',
|
|
31
|
+
'protectedPathReadOnlyMask',
|
|
32
|
+
'networkIsolation',
|
|
33
|
+
'processTreeCleanup',
|
|
34
|
+
]),
|
|
35
|
+
'linux-bwrap': Object.freeze([
|
|
36
|
+
'filesystemReadContainment',
|
|
37
|
+
'filesystemWriteContainment',
|
|
38
|
+
'protectedPathReadOnlyMask',
|
|
39
|
+
'networkIsolation',
|
|
40
|
+
'processTreeCleanup',
|
|
41
|
+
'syscallFiltering',
|
|
42
|
+
]),
|
|
43
|
+
'linux-landlock': Object.freeze([
|
|
44
|
+
'filesystemReadContainment',
|
|
45
|
+
'filesystemWriteContainment',
|
|
46
|
+
'protectedPathReadOnlyMask',
|
|
47
|
+
'networkIsolation',
|
|
48
|
+
'processTreeCleanup',
|
|
49
|
+
]),
|
|
50
|
+
'docker': Object.freeze([
|
|
51
|
+
'filesystemReadContainment',
|
|
52
|
+
'filesystemWriteContainment',
|
|
53
|
+
'protectedPathReadOnlyMask',
|
|
54
|
+
'networkIsolation',
|
|
55
|
+
'processTreeCleanup',
|
|
56
|
+
'syscallFiltering',
|
|
57
|
+
]),
|
|
58
|
+
'direct-dedicated': Object.freeze([
|
|
59
|
+
'processTreeCleanup',
|
|
60
|
+
]),
|
|
61
|
+
});
|
|
62
|
+
export const SECCOMP_BLOCKED_SYSCALLS = Object.freeze([
|
|
63
|
+
'ptrace', 'kexec_load', 'kexec_file_load', 'mount', 'umount2', 'pivot_root',
|
|
64
|
+
'bpf', 'perf_event_open', 'userfaultfd', 'keyctl', 'add_key', 'request_key',
|
|
65
|
+
'io_uring_setup', 'io_uring_enter', 'io_uring_register',
|
|
66
|
+
]);
|
|
67
|
+
const DEFAULT_SANDBOX_TIMEOUT_MS = 30_000;
|
|
68
|
+
const MAX_SANDBOX_TIMEOUT_MS = 300_000;
|
|
69
|
+
const DEFAULT_SANDBOX_OUTPUT_BYTES = 1_048_576;
|
|
70
|
+
export const MAX_LINUX_BWRAP_ARGS = 8_500;
|
|
71
|
+
/**
|
|
72
|
+
* Enumerate existing sibling entries along the `controlRoot -> dirname(proposalPath)` spine
|
|
73
|
+
* so carved-out control-root proposals preserve protected-sibling semantics.
|
|
74
|
+
*/
|
|
75
|
+
export function collectControlRootSiblingPaths(options) {
|
|
76
|
+
const empty = Object.freeze({
|
|
77
|
+
prioritySiblings: Object.freeze([]),
|
|
78
|
+
regularSiblings: Object.freeze([]),
|
|
79
|
+
});
|
|
80
|
+
if (options.repositoryRoot === undefined
|
|
81
|
+
|| options.repositoryRoot.trim().length === 0
|
|
82
|
+
|| options.proposalPath === options.controlRoot
|
|
83
|
+
|| !pathCoveredBy(options.proposalPath, options.controlRoot)) {
|
|
84
|
+
return empty;
|
|
85
|
+
}
|
|
86
|
+
const resolvedRoot = resolve(options.repositoryRoot);
|
|
87
|
+
if (!existsSync(resolvedRoot)) {
|
|
88
|
+
return empty;
|
|
89
|
+
}
|
|
90
|
+
const suffix = options.proposalPath.slice(options.controlRoot.length + 1);
|
|
91
|
+
const relSegments = suffix.split('/').filter(Boolean);
|
|
92
|
+
if (relSegments.length === 0)
|
|
93
|
+
return empty;
|
|
94
|
+
const spineLevels = [];
|
|
95
|
+
let cursorRel = options.controlRoot;
|
|
96
|
+
for (const seg of relSegments) {
|
|
97
|
+
spineLevels.push({ dirRel: cursorRel, spineChild: seg });
|
|
98
|
+
cursorRel = `${cursorRel}/${seg}`;
|
|
99
|
+
}
|
|
100
|
+
const priority = new Set();
|
|
101
|
+
const regular = new Set();
|
|
102
|
+
for (const { dirRel, spineChild } of spineLevels) {
|
|
103
|
+
const dirAbs = join(resolvedRoot, ...dirRel.split('/'));
|
|
104
|
+
let dirStat;
|
|
105
|
+
try {
|
|
106
|
+
dirStat = lstatSync(dirAbs);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
dirStat = null;
|
|
110
|
+
}
|
|
111
|
+
if (dirStat !== null && !dirStat.isSymbolicLink() && dirStat.isDirectory()) {
|
|
112
|
+
const dirents = readdirSync(dirAbs, { withFileTypes: true });
|
|
113
|
+
const lowerSpineChild = spineChild.normalize('NFC').toLowerCase();
|
|
114
|
+
for (const dirent of dirents) {
|
|
115
|
+
if (dirent.name === spineChild)
|
|
116
|
+
continue;
|
|
117
|
+
const childRel = `${dirRel}/${dirent.name}`;
|
|
118
|
+
if (tryNormalizeRelativePath(childRel) !== childRel)
|
|
119
|
+
continue;
|
|
120
|
+
const isCaseCollision = dirent.name.normalize('NFC').toLowerCase() === lowerSpineChild;
|
|
121
|
+
if (dirent.isSymbolicLink() || dirent.isDirectory() || !dirent.isFile() || isCaseCollision) {
|
|
122
|
+
priority.add(childRel);
|
|
123
|
+
regular.delete(childRel);
|
|
124
|
+
}
|
|
125
|
+
else if (!priority.has(childRel)) {
|
|
126
|
+
regular.add(childRel);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const revisions = [
|
|
132
|
+
...new Set((options.gitRevisions ?? []).filter(rev => typeof rev === 'string' && rev.trim().length > 0 && !rev.startsWith('-'))),
|
|
133
|
+
];
|
|
134
|
+
if (revisions.length > 0 && existsSync(join(resolvedRoot, '.git'))) {
|
|
135
|
+
const gitExecutable = existsSync('/usr/bin/git') ? '/usr/bin/git' : 'git';
|
|
136
|
+
for (const rev of revisions) {
|
|
137
|
+
for (const { dirRel, spineChild } of spineLevels) {
|
|
138
|
+
const res = spawnSync(gitExecutable, ['-c', 'core.hooksPath=/dev/null', 'ls-tree', '-z', `${rev}:${dirRel}`], {
|
|
139
|
+
cwd: resolvedRoot,
|
|
140
|
+
env: {
|
|
141
|
+
PATH: '/usr/bin:/bin:/usr/local/bin',
|
|
142
|
+
LANG: 'C',
|
|
143
|
+
LC_ALL: 'C',
|
|
144
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
145
|
+
GIT_CONFIG_NOSYSTEM: '1',
|
|
146
|
+
GIT_CONFIG_GLOBAL: '/dev/null',
|
|
147
|
+
HOME: '/nonexistent',
|
|
148
|
+
},
|
|
149
|
+
timeout: 5_000,
|
|
150
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
151
|
+
});
|
|
152
|
+
if (res.status !== 0 || !res.stdout || res.stdout.byteLength === 0)
|
|
153
|
+
continue;
|
|
154
|
+
const text = res.stdout.toString('utf8');
|
|
155
|
+
const rows = text.split('\0').filter(Boolean);
|
|
156
|
+
const lowerSpineChild = spineChild.normalize('NFC').toLowerCase();
|
|
157
|
+
for (const row of rows) {
|
|
158
|
+
const parsed = /^([0-9]{6}) ([a-z]+) [0-9a-f]+\t(.+)$/s.exec(row);
|
|
159
|
+
if (parsed === null)
|
|
160
|
+
continue;
|
|
161
|
+
const mode = parsed[1];
|
|
162
|
+
const objType = parsed[2];
|
|
163
|
+
const entryName = parsed[3];
|
|
164
|
+
if (entryName === spineChild)
|
|
165
|
+
continue;
|
|
166
|
+
const childRel = `${dirRel}/${entryName}`;
|
|
167
|
+
if (tryNormalizeRelativePath(childRel) !== childRel)
|
|
168
|
+
continue;
|
|
169
|
+
const isCaseCollision = entryName.normalize('NFC').toLowerCase() === lowerSpineChild;
|
|
170
|
+
if (mode === '120000'
|
|
171
|
+
|| mode === '160000'
|
|
172
|
+
|| mode === '040000'
|
|
173
|
+
|| objType === 'tree'
|
|
174
|
+
|| objType === 'commit'
|
|
175
|
+
|| isCaseCollision) {
|
|
176
|
+
priority.add(childRel);
|
|
177
|
+
regular.delete(childRel);
|
|
178
|
+
}
|
|
179
|
+
else if (!priority.has(childRel)) {
|
|
180
|
+
regular.add(childRel);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return Object.freeze({
|
|
187
|
+
prioritySiblings: Object.freeze([...priority].sort()),
|
|
188
|
+
regularSiblings: Object.freeze([...regular].sort()),
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Enumerate existing non-`workflows` sibling entries under `<repositoryRoot>/.github`
|
|
193
|
+
* so `'github'` mode with `allowWorkflowWrites: true` keeps `.github/CODEOWNERS`,
|
|
194
|
+
* templates, and custom actions protected while unlocking `.github/workflows/**`.
|
|
195
|
+
*/
|
|
196
|
+
export function collectGitHubSiblingPaths(options = {}) {
|
|
197
|
+
if (options.repositoryRoot === undefined || options.repositoryRoot.trim().length === 0) {
|
|
198
|
+
return Object.freeze([]);
|
|
199
|
+
}
|
|
200
|
+
const resolvedRoot = resolve(options.repositoryRoot);
|
|
201
|
+
if (!existsSync(resolvedRoot)) {
|
|
202
|
+
return Object.freeze([]);
|
|
203
|
+
}
|
|
204
|
+
const siblings = new Set();
|
|
205
|
+
const githubAbs = join(resolvedRoot, '.github');
|
|
206
|
+
let dirStat;
|
|
207
|
+
try {
|
|
208
|
+
dirStat = lstatSync(githubAbs);
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
dirStat = null;
|
|
212
|
+
}
|
|
213
|
+
if (dirStat !== null && !dirStat.isSymbolicLink() && dirStat.isDirectory()) {
|
|
214
|
+
for (const dirent of readdirSync(githubAbs, { withFileTypes: true })) {
|
|
215
|
+
if (dirent.name.normalize('NFC').toLowerCase() === 'workflows')
|
|
216
|
+
continue;
|
|
217
|
+
const childRel = `.github/${dirent.name}`;
|
|
218
|
+
if (tryNormalizeRelativePath(childRel) === childRel) {
|
|
219
|
+
siblings.add(childRel);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const revisions = [
|
|
224
|
+
...new Set((options.gitRevisions ?? []).filter(rev => typeof rev === 'string' && rev.trim().length > 0 && !rev.startsWith('-'))),
|
|
225
|
+
];
|
|
226
|
+
if (revisions.length > 0 && existsSync(join(resolvedRoot, '.git'))) {
|
|
227
|
+
const gitExecutable = existsSync('/usr/bin/git') ? '/usr/bin/git' : 'git';
|
|
228
|
+
for (const rev of revisions) {
|
|
229
|
+
const res = spawnSync(gitExecutable, ['-c', 'core.hooksPath=/dev/null', 'ls-tree', '-z', `${rev}:.github`], {
|
|
230
|
+
cwd: resolvedRoot,
|
|
231
|
+
env: {
|
|
232
|
+
PATH: '/usr/bin:/bin:/usr/local/bin',
|
|
233
|
+
LANG: 'C',
|
|
234
|
+
LC_ALL: 'C',
|
|
235
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
236
|
+
GIT_CONFIG_NOSYSTEM: '1',
|
|
237
|
+
GIT_CONFIG_GLOBAL: '/dev/null',
|
|
238
|
+
HOME: '/nonexistent',
|
|
239
|
+
},
|
|
240
|
+
timeout: 5_000,
|
|
241
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
242
|
+
});
|
|
243
|
+
if (res.status !== 0 || !res.stdout || res.stdout.byteLength === 0)
|
|
244
|
+
continue;
|
|
245
|
+
for (const row of res.stdout.toString('utf8').split('\0').filter(Boolean)) {
|
|
246
|
+
const parsed = /^[0-9]{6} [a-z]+ [0-9a-f]+\t(.+)$/s.exec(row);
|
|
247
|
+
if (parsed === null)
|
|
248
|
+
continue;
|
|
249
|
+
const entryName = parsed[1];
|
|
250
|
+
if (entryName.normalize('NFC').toLowerCase() === 'workflows')
|
|
251
|
+
continue;
|
|
252
|
+
const childRel = `.github/${entryName}`;
|
|
253
|
+
if (tryNormalizeRelativePath(childRel) === childRel) {
|
|
254
|
+
siblings.add(childRel);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return Object.freeze([...siblings].sort());
|
|
260
|
+
}
|
|
261
|
+
function policyInvalid(message, path = null) {
|
|
262
|
+
throw new TaskpackError('SANDBOX_POLICY_INVALID', message, path);
|
|
263
|
+
}
|
|
264
|
+
function sha256Digest(domain, payload) {
|
|
265
|
+
const hex = createHash('sha256').update(`${domain}\0${payload}`, 'utf8').digest('hex');
|
|
266
|
+
return Object.freeze({ algorithm: 'sha256', hex });
|
|
267
|
+
}
|
|
268
|
+
function assertCleanPathString(value, label) {
|
|
269
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > 1024) {
|
|
270
|
+
policyInvalid(`${label} must be a non-empty string of at most 1024 characters`, label);
|
|
271
|
+
}
|
|
272
|
+
if (/[\0\r\n"\\]/.test(value)) {
|
|
273
|
+
policyInvalid(`${label} contains forbidden characters`, label);
|
|
274
|
+
}
|
|
275
|
+
return value;
|
|
276
|
+
}
|
|
277
|
+
function canonicalizeAbsolutePath(rawPath, label) {
|
|
278
|
+
const cleaned = assertCleanPathString(rawPath, label);
|
|
279
|
+
if (!isAbsolute(cleaned)) {
|
|
280
|
+
policyInvalid(`${label} must be an absolute path`, label);
|
|
281
|
+
}
|
|
282
|
+
const resolved = resolve(cleaned);
|
|
283
|
+
const suffixSegments = [];
|
|
284
|
+
let cursor = resolved;
|
|
285
|
+
while (true) {
|
|
286
|
+
if (existsSync(cursor)) {
|
|
287
|
+
try {
|
|
288
|
+
const realBase = realpathSync(cursor);
|
|
289
|
+
const joined = suffixSegments.length === 0 ? realBase : join(realBase, ...suffixSegments.reverse());
|
|
290
|
+
if (/[\0\r\n"\\]/.test(joined))
|
|
291
|
+
policyInvalid(`${label} resolved to a path with forbidden characters`, label);
|
|
292
|
+
return joined;
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
// Fall through to parent if a broken symlink was encountered at cursor.
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
const parent = dirname(cursor);
|
|
299
|
+
if (parent === cursor) {
|
|
300
|
+
return resolved;
|
|
301
|
+
}
|
|
302
|
+
const base = cursor.slice(parent === '/' ? 1 : parent.length + 1);
|
|
303
|
+
suffixSegments.push(base);
|
|
304
|
+
cursor = parent;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
function normalizeRelativeSubpath(raw, label) {
|
|
308
|
+
const cleaned = assertCleanPathString(raw, label);
|
|
309
|
+
if (cleaned.startsWith('/')) {
|
|
310
|
+
policyInvalid(`${label} must be relative`, label);
|
|
311
|
+
}
|
|
312
|
+
const segments = cleaned.split('/');
|
|
313
|
+
for (const segment of segments) {
|
|
314
|
+
if (segment === '' || segment === '.' || segment === '..' || segment.includes('**')) {
|
|
315
|
+
policyInvalid(`${label} contains disallowed segment "${segment}"`, label);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return segments.join('/');
|
|
319
|
+
}
|
|
320
|
+
function normalizeRelativeScopeEntry(raw, label) {
|
|
321
|
+
const cleaned = assertCleanPathString(raw, label);
|
|
322
|
+
const subtree = cleaned.endsWith('/**');
|
|
323
|
+
const baseRaw = subtree ? cleaned.slice(0, -3) : cleaned;
|
|
324
|
+
const base = normalizeRelativeSubpath(baseRaw, label);
|
|
325
|
+
const hasGlob = base.includes('*') || base.includes('?');
|
|
326
|
+
return { base, subtree, hasGlob };
|
|
327
|
+
}
|
|
328
|
+
function segmentHasGlob(segment) {
|
|
329
|
+
return segment.includes('*') || segment.includes('?');
|
|
330
|
+
}
|
|
331
|
+
function segmentGlobToRegExp(segment) {
|
|
332
|
+
let expr = '^';
|
|
333
|
+
for (let i = 0; i < segment.length; i += 1) {
|
|
334
|
+
const ch = segment[i];
|
|
335
|
+
if (ch === '*')
|
|
336
|
+
expr += '[^/]*';
|
|
337
|
+
else if (ch === '?')
|
|
338
|
+
expr += '[^/]';
|
|
339
|
+
else if ('\\^$.|+()[]{}'.includes(ch))
|
|
340
|
+
expr += `\\${ch}`;
|
|
341
|
+
else
|
|
342
|
+
expr += ch;
|
|
343
|
+
}
|
|
344
|
+
expr += '$';
|
|
345
|
+
return new RegExp(expr);
|
|
346
|
+
}
|
|
347
|
+
function escapeSeatbeltRegexLiteral(text) {
|
|
348
|
+
if (/[\r\n]/.test(text)) {
|
|
349
|
+
policyInvalid('sandbox seatbelt regex literal must not contain line breaks');
|
|
350
|
+
}
|
|
351
|
+
return text.replace(/[\\^$.|+()*?[\]{}"]/g, '\\$&');
|
|
352
|
+
}
|
|
353
|
+
function segmentGlobToSeatbeltRegex(segment) {
|
|
354
|
+
if (/[\r\n]/.test(segment)) {
|
|
355
|
+
policyInvalid('sandbox seatbelt glob segment must not contain line breaks');
|
|
356
|
+
}
|
|
357
|
+
let expr = '';
|
|
358
|
+
for (let i = 0; i < segment.length; i += 1) {
|
|
359
|
+
const ch = segment[i];
|
|
360
|
+
if (ch === '*')
|
|
361
|
+
expr += '[^/]*';
|
|
362
|
+
else if (ch === '?')
|
|
363
|
+
expr += '[^/]';
|
|
364
|
+
else if ('\\^$.|+()[]{}"'.includes(ch))
|
|
365
|
+
expr += `\\${ch}`;
|
|
366
|
+
else
|
|
367
|
+
expr += ch;
|
|
368
|
+
}
|
|
369
|
+
return expr;
|
|
370
|
+
}
|
|
371
|
+
function buildSeatbeltRegexForRelativeGlob(canonicalWorkspaceRoot, base) {
|
|
372
|
+
const rootPrefix = canonicalWorkspaceRoot === '/'
|
|
373
|
+
? ''
|
|
374
|
+
: escapeSeatbeltRegexLiteral(canonicalWorkspaceRoot);
|
|
375
|
+
const segments = base.split('/');
|
|
376
|
+
let expr = `^${rootPrefix}/`;
|
|
377
|
+
for (let i = 0; i < segments.length; i += 1) {
|
|
378
|
+
const seg = segments[i];
|
|
379
|
+
const isLast = i === segments.length - 1;
|
|
380
|
+
if (!isLast) {
|
|
381
|
+
if (seg === '**') {
|
|
382
|
+
expr += '(?:[^/]+/)*';
|
|
383
|
+
}
|
|
384
|
+
else {
|
|
385
|
+
expr += `${segmentGlobToSeatbeltRegex(seg)}/`;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
else if (seg === '**') {
|
|
389
|
+
expr += '.+';
|
|
390
|
+
}
|
|
391
|
+
else {
|
|
392
|
+
expr += `${segmentGlobToSeatbeltRegex(seg)}(/.*)?`;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
expr += '$';
|
|
396
|
+
return expr;
|
|
397
|
+
}
|
|
398
|
+
const MAX_GLOB_VISITED_DIRS = 2_048;
|
|
399
|
+
const MAX_GLOB_EXPANDED_PATHS = 16_384;
|
|
400
|
+
const MAX_READ_ONLY_BIND_MOUNTS = 16;
|
|
401
|
+
function expandDirectorySegmentsSync(workspaceRoot, segments, label, budget) {
|
|
402
|
+
if (segments.length === 0)
|
|
403
|
+
return [workspaceRoot];
|
|
404
|
+
if (!segments.some(segmentHasGlob)) {
|
|
405
|
+
return [canonicalizeAbsolutePath(join(workspaceRoot, ...segments), label)];
|
|
406
|
+
}
|
|
407
|
+
if (!existsSync(workspaceRoot))
|
|
408
|
+
return [];
|
|
409
|
+
let currentDirs = [workspaceRoot];
|
|
410
|
+
for (const segment of segments) {
|
|
411
|
+
const nextDirs = [];
|
|
412
|
+
if (!segmentHasGlob(segment)) {
|
|
413
|
+
for (const dir of currentDirs) {
|
|
414
|
+
budget.visitedDirs += 1;
|
|
415
|
+
if (budget.visitedDirs > MAX_GLOB_VISITED_DIRS) {
|
|
416
|
+
policyInvalid(`sandbox glob expansion exceeded ${MAX_GLOB_VISITED_DIRS} visited directories`, label);
|
|
417
|
+
}
|
|
418
|
+
const candidate = join(dir, segment);
|
|
419
|
+
let st;
|
|
420
|
+
try {
|
|
421
|
+
st = lstatSync(candidate);
|
|
422
|
+
}
|
|
423
|
+
catch {
|
|
424
|
+
st = null;
|
|
425
|
+
}
|
|
426
|
+
if (st !== null && !st.isSymbolicLink() && st.isDirectory()) {
|
|
427
|
+
budget.expandedPaths += 1;
|
|
428
|
+
if (budget.expandedPaths > MAX_GLOB_EXPANDED_PATHS) {
|
|
429
|
+
policyInvalid(`sandbox glob expansion exceeded ${MAX_GLOB_EXPANDED_PATHS} expanded paths`, label);
|
|
430
|
+
}
|
|
431
|
+
nextDirs.push(canonicalizeAbsolutePath(candidate, label));
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
else {
|
|
436
|
+
const matcher = segmentGlobToRegExp(segment);
|
|
437
|
+
for (const dir of currentDirs) {
|
|
438
|
+
budget.visitedDirs += 1;
|
|
439
|
+
if (budget.visitedDirs > MAX_GLOB_VISITED_DIRS) {
|
|
440
|
+
policyInvalid(`sandbox glob expansion exceeded ${MAX_GLOB_VISITED_DIRS} visited directories`, label);
|
|
441
|
+
}
|
|
442
|
+
let entries;
|
|
443
|
+
try {
|
|
444
|
+
entries = readdirSync(dir, { encoding: 'utf8' }).sort();
|
|
445
|
+
}
|
|
446
|
+
catch {
|
|
447
|
+
entries = [];
|
|
448
|
+
}
|
|
449
|
+
for (const name of entries) {
|
|
450
|
+
if (name === '.' || name === '..' || !matcher.test(name))
|
|
451
|
+
continue;
|
|
452
|
+
const candidate = join(dir, name);
|
|
453
|
+
let st;
|
|
454
|
+
try {
|
|
455
|
+
st = lstatSync(candidate);
|
|
456
|
+
}
|
|
457
|
+
catch {
|
|
458
|
+
st = null;
|
|
459
|
+
}
|
|
460
|
+
if (st !== null && !st.isSymbolicLink() && st.isDirectory()) {
|
|
461
|
+
budget.expandedPaths += 1;
|
|
462
|
+
if (budget.expandedPaths > MAX_GLOB_EXPANDED_PATHS) {
|
|
463
|
+
policyInvalid(`sandbox glob expansion exceeded ${MAX_GLOB_EXPANDED_PATHS} expanded paths`, label);
|
|
464
|
+
}
|
|
465
|
+
nextDirs.push(canonicalizeAbsolutePath(candidate, label));
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
currentDirs = nextDirs;
|
|
471
|
+
if (currentDirs.length === 0)
|
|
472
|
+
break;
|
|
473
|
+
}
|
|
474
|
+
return currentDirs;
|
|
475
|
+
}
|
|
476
|
+
function isSameOrSubpath(candidate, root) {
|
|
477
|
+
if (root === '/')
|
|
478
|
+
return true;
|
|
479
|
+
return candidate === root || candidate.startsWith(`${root}${sep}`);
|
|
480
|
+
}
|
|
481
|
+
function isSameOrSubpathCaseInsensitive(candidate, root) {
|
|
482
|
+
return isSameOrSubpath(candidate.normalize('NFC').toLowerCase(), root.normalize('NFC').toLowerCase());
|
|
483
|
+
}
|
|
484
|
+
function resolveHostEnvironment(host) {
|
|
485
|
+
return {
|
|
486
|
+
platform: host?.platform ?? process.platform,
|
|
487
|
+
arch: host?.arch ?? process.arch,
|
|
488
|
+
homeDirectory: host?.homeDirectory ?? process.env.HOME ?? homedir(),
|
|
489
|
+
probeExecutables: host?.probeExecutables ?? true,
|
|
490
|
+
seatbeltExecutable: host?.seatbeltExecutable,
|
|
491
|
+
bwrapExecutable: host?.bwrapExecutable,
|
|
492
|
+
pythonExecutable: host?.pythonExecutable,
|
|
493
|
+
dockerExecutable: host?.dockerExecutable,
|
|
494
|
+
dockerSocket: host?.dockerSocket,
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
function findDynamicProtectedGlobOverlap(normalized) {
|
|
498
|
+
if (normalized.protectedGlobPrefixes.length === 0)
|
|
499
|
+
return null;
|
|
500
|
+
const writableDirs = normalized.canonicalWritablePaths.filter(wp => !normalized.canonicalExactWritableFiles.has(wp));
|
|
501
|
+
for (const g of normalized.protectedGlobPrefixes) {
|
|
502
|
+
if (writableDirs.some(wp => isSameOrSubpath(g.staticPrefixDir, wp) || isSameOrSubpath(wp, g.staticPrefixDir))) {
|
|
503
|
+
return g.raw;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
return null;
|
|
507
|
+
}
|
|
508
|
+
function findLandlockWritableOverlap(normalized) {
|
|
509
|
+
const globOverlap = findDynamicProtectedGlobOverlap(normalized);
|
|
510
|
+
if (globOverlap !== null) {
|
|
511
|
+
return `dynamic protected glob "${globOverlap}"`;
|
|
512
|
+
}
|
|
513
|
+
const writableDirs = normalized.canonicalWritablePaths.filter(wp => !normalized.canonicalExactWritableFiles.has(wp));
|
|
514
|
+
if (writableDirs.length === 0)
|
|
515
|
+
return null;
|
|
516
|
+
for (const protectedPath of normalized.canonicalProtectedPaths) {
|
|
517
|
+
if (writableDirs.some(wp => isSameOrSubpath(protectedPath, wp))) {
|
|
518
|
+
return `protectedPath "${protectedPath}"`;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
for (const deniedPath of normalized.canonicalDeniedReadPaths) {
|
|
522
|
+
if (writableDirs.some(wp => isSameOrSubpath(deniedPath, wp))) {
|
|
523
|
+
return `deniedReadPath "${deniedPath}"`;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
return null;
|
|
527
|
+
}
|
|
528
|
+
function provisionSandboxExactWritablePaths(normalized, options) {
|
|
529
|
+
if (normalized.canonicalExactWritableFiles.size === 0 || !existsSync(normalized.canonicalWorkspaceRoot)) {
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
const rootStat = lstatSync(normalized.canonicalWorkspaceRoot);
|
|
533
|
+
if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
|
|
534
|
+
policyInvalid('workspaceRoot must be an existing non-symlink directory', 'workspaceRoot');
|
|
535
|
+
}
|
|
536
|
+
for (const exactFile of normalized.canonicalExactWritableFiles) {
|
|
537
|
+
if (!isSameOrSubpath(exactFile, normalized.canonicalWorkspaceRoot) || exactFile === normalized.canonicalWorkspaceRoot) {
|
|
538
|
+
policyInvalid(`exact writable file "${exactFile}" escapes workspaceRoot`, 'proposalPath');
|
|
539
|
+
}
|
|
540
|
+
const rel = exactFile.slice(normalized.canonicalWorkspaceRoot.length + 1);
|
|
541
|
+
const segments = rel.split(sep).filter(Boolean);
|
|
542
|
+
let cursor = normalized.canonicalWorkspaceRoot;
|
|
543
|
+
for (let i = 0; i < segments.length - 1; i += 1) {
|
|
544
|
+
cursor = join(cursor, segments[i]);
|
|
545
|
+
let parentStat;
|
|
546
|
+
try {
|
|
547
|
+
parentStat = lstatSync(cursor);
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
parentStat = null;
|
|
551
|
+
}
|
|
552
|
+
if (parentStat === null) {
|
|
553
|
+
mkdirSync(cursor, { mode: 0o700 });
|
|
554
|
+
}
|
|
555
|
+
else if (parentStat.isSymbolicLink() || !parentStat.isDirectory()) {
|
|
556
|
+
policyInvalid(`parent segment of exact writable file "${exactFile}" must be a real directory`, 'proposalPath');
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
let targetStat;
|
|
560
|
+
try {
|
|
561
|
+
targetStat = lstatSync(exactFile);
|
|
562
|
+
}
|
|
563
|
+
catch {
|
|
564
|
+
targetStat = null;
|
|
565
|
+
}
|
|
566
|
+
if (targetStat === null) {
|
|
567
|
+
if (options.createTargetFile) {
|
|
568
|
+
const openFlags = fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY | (fsConstants.O_NOFOLLOW ?? 0);
|
|
569
|
+
const fd = openSync(exactFile, openFlags, 0o600);
|
|
570
|
+
closeSync(fd);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
else if (targetStat.isSymbolicLink() || !targetStat.isFile() || targetStat.nlink > 1) {
|
|
574
|
+
policyInvalid(`exact writable file "${exactFile}" must be a regular non-hardlinked file`, 'proposalPath');
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
function normalizeSandboxPolicy(policy, host) {
|
|
579
|
+
if (policy === null || typeof policy !== 'object') {
|
|
580
|
+
policyInvalid('policy must be an object', '/policy');
|
|
581
|
+
}
|
|
582
|
+
const env = resolveHostEnvironment(host);
|
|
583
|
+
const canonicalWorkspaceRoot = canonicalizeAbsolutePath(policy.workspaceRoot, 'workspaceRoot');
|
|
584
|
+
const canonicalScratchDirectory = policy.scratchDirectory === undefined
|
|
585
|
+
? null
|
|
586
|
+
: canonicalizeAbsolutePath(policy.scratchDirectory, 'scratchDirectory');
|
|
587
|
+
const protectGitHub = policy.policyProfile === 'github' || policy.protectGitHubDir === true;
|
|
588
|
+
const allowWorkflowWrites = protectGitHub && policy.allowWorkflowWrites === true;
|
|
589
|
+
const strictExactFiles = policy.strictExactFiles === true;
|
|
590
|
+
const networkMode = policy.networkMode ?? 'none';
|
|
591
|
+
if (networkMode !== 'none' && networkMode !== 'loopback-only' && networkMode !== 'allow-outbound') {
|
|
592
|
+
policyInvalid(`unsupported networkMode "${String(networkMode)}"`, 'networkMode');
|
|
593
|
+
}
|
|
594
|
+
if (!Array.isArray(policy.writablePaths) || policy.writablePaths.length === 0 || policy.writablePaths.length > 128) {
|
|
595
|
+
policyInvalid('writablePaths must be a non-empty array of at most 128 paths', 'writablePaths');
|
|
596
|
+
}
|
|
597
|
+
const protectedGlobBudget = { visitedDirs: 0, expandedPaths: 0 };
|
|
598
|
+
const callerProtectedRelPaths = [];
|
|
599
|
+
const seatbeltProtectedGlobRegexSet = new Set();
|
|
600
|
+
const protectedGlobPrefixesList = [];
|
|
601
|
+
if (policy.protectedPaths !== undefined) {
|
|
602
|
+
if (!Array.isArray(policy.protectedPaths) || policy.protectedPaths.length > 128) {
|
|
603
|
+
policyInvalid('protectedPaths must be an array of at most 128 paths', 'protectedPaths');
|
|
604
|
+
}
|
|
605
|
+
for (const [index, entry] of policy.protectedPaths.entries()) {
|
|
606
|
+
const cleaned = assertCleanPathString(entry, `protectedPaths/${index}`);
|
|
607
|
+
if (isAbsolute(cleaned)) {
|
|
608
|
+
const canonicalProtected = canonicalizeAbsolutePath(cleaned, `protectedPaths/${index}`);
|
|
609
|
+
if (!isSameOrSubpath(canonicalProtected, canonicalWorkspaceRoot)) {
|
|
610
|
+
policyInvalid(`protectedPath "${entry}" escapes workspaceRoot`, `protectedPaths/${index}`);
|
|
611
|
+
}
|
|
612
|
+
const rel = canonicalProtected.slice(canonicalWorkspaceRoot.length + 1);
|
|
613
|
+
if (rel.length === 0)
|
|
614
|
+
policyInvalid('protectedPath must not be workspaceRoot itself', `protectedPaths/${index}`);
|
|
615
|
+
callerProtectedRelPaths.push(normalizeRelativeSubpath(rel.split(sep).join('/'), `protectedPaths/${index}`));
|
|
616
|
+
}
|
|
617
|
+
else {
|
|
618
|
+
const parsedProtected = normalizeRelativeScopeEntry(cleaned, `protectedPaths/${index}`);
|
|
619
|
+
if (!parsedProtected.hasGlob) {
|
|
620
|
+
callerProtectedRelPaths.push(parsedProtected.base);
|
|
621
|
+
}
|
|
622
|
+
else {
|
|
623
|
+
const segments = parsedProtected.base.split('/');
|
|
624
|
+
const firstGlobIdx = segments.findIndex(segmentHasGlob);
|
|
625
|
+
const staticPrefixSegments = firstGlobIdx > 0 ? segments.slice(0, firstGlobIdx) : [];
|
|
626
|
+
const staticPrefixDir = staticPrefixSegments.length === 0
|
|
627
|
+
? canonicalWorkspaceRoot
|
|
628
|
+
: canonicalizeAbsolutePath(join(canonicalWorkspaceRoot, ...staticPrefixSegments), `protectedPaths/${index}`);
|
|
629
|
+
protectedGlobPrefixesList.push(Object.freeze({ raw: cleaned, staticPrefixDir }));
|
|
630
|
+
seatbeltProtectedGlobRegexSet.add(buildSeatbeltRegexForRelativeGlob(canonicalWorkspaceRoot, parsedProtected.base));
|
|
631
|
+
if (parsedProtected.subtree) {
|
|
632
|
+
for (const dir of expandDirectorySegmentsSync(canonicalWorkspaceRoot, segments, `protectedPaths/${index}`, protectedGlobBudget)) {
|
|
633
|
+
if (dir !== canonicalWorkspaceRoot && isSameOrSubpath(dir, canonicalWorkspaceRoot)) {
|
|
634
|
+
callerProtectedRelPaths.push(dir.slice(canonicalWorkspaceRoot.length + 1).split(sep).join('/'));
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
else {
|
|
639
|
+
const parentSegments = segments.slice(0, -1);
|
|
640
|
+
const leafSegment = segments[segments.length - 1];
|
|
641
|
+
const parentDirs = expandDirectorySegmentsSync(canonicalWorkspaceRoot, parentSegments, `protectedPaths/${index}`, protectedGlobBudget);
|
|
642
|
+
if (!segmentHasGlob(leafSegment)) {
|
|
643
|
+
for (const parentDir of parentDirs) {
|
|
644
|
+
protectedGlobBudget.expandedPaths += 1;
|
|
645
|
+
if (protectedGlobBudget.expandedPaths > MAX_GLOB_EXPANDED_PATHS) {
|
|
646
|
+
policyInvalid(`sandbox glob expansion exceeded ${MAX_GLOB_EXPANDED_PATHS} expanded paths`, `protectedPaths/${index}`);
|
|
647
|
+
}
|
|
648
|
+
const target = canonicalizeAbsolutePath(join(parentDir, leafSegment), `protectedPaths/${index}`);
|
|
649
|
+
if (target !== canonicalWorkspaceRoot && isSameOrSubpath(target, canonicalWorkspaceRoot)) {
|
|
650
|
+
callerProtectedRelPaths.push(target.slice(canonicalWorkspaceRoot.length + 1).split(sep).join('/'));
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
else {
|
|
655
|
+
const leafMatcher = segmentGlobToRegExp(leafSegment);
|
|
656
|
+
for (const parentDir of parentDirs) {
|
|
657
|
+
protectedGlobBudget.visitedDirs += 1;
|
|
658
|
+
if (protectedGlobBudget.visitedDirs > MAX_GLOB_VISITED_DIRS) {
|
|
659
|
+
policyInvalid(`sandbox glob expansion exceeded ${MAX_GLOB_VISITED_DIRS} visited directories`, `protectedPaths/${index}`);
|
|
660
|
+
}
|
|
661
|
+
let names;
|
|
662
|
+
try {
|
|
663
|
+
names = readdirSync(parentDir, { encoding: 'utf8' }).sort();
|
|
664
|
+
}
|
|
665
|
+
catch {
|
|
666
|
+
names = [];
|
|
667
|
+
}
|
|
668
|
+
for (const name of names) {
|
|
669
|
+
if (name === '.' || name === '..' || !leafMatcher.test(name))
|
|
670
|
+
continue;
|
|
671
|
+
protectedGlobBudget.expandedPaths += 1;
|
|
672
|
+
if (protectedGlobBudget.expandedPaths > MAX_GLOB_EXPANDED_PATHS) {
|
|
673
|
+
policyInvalid(`sandbox glob expansion exceeded ${MAX_GLOB_EXPANDED_PATHS} expanded paths`, `protectedPaths/${index}`);
|
|
674
|
+
}
|
|
675
|
+
const target = canonicalizeAbsolutePath(join(parentDir, name), `protectedPaths/${index}`);
|
|
676
|
+
if (target !== canonicalWorkspaceRoot && isSameOrSubpath(target, canonicalWorkspaceRoot)) {
|
|
677
|
+
callerProtectedRelPaths.push(target.slice(canonicalWorkspaceRoot.length + 1).split(sep).join('/'));
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
const effectiveControlRoot = policy.controlRoot !== undefined
|
|
688
|
+
? normalizeRelativeSubpath(policy.controlRoot, 'controlRoot')
|
|
689
|
+
: '.loopwright';
|
|
690
|
+
const canonicalControlRoot = canonicalizeAbsolutePath(join(canonicalWorkspaceRoot, effectiveControlRoot), 'controlRoot');
|
|
691
|
+
const normalizedProposalPath = policy.proposalPath !== undefined
|
|
692
|
+
? normalizeRelativeSubpath(policy.proposalPath, 'proposalPath')
|
|
693
|
+
: undefined;
|
|
694
|
+
const profileWorkspaceProtected = protectGitHub
|
|
695
|
+
? (allowWorkflowWrites
|
|
696
|
+
? GITHUB_PROTECTED_WORKSPACE_SUBPATHS.filter(sub => sub !== '.github')
|
|
697
|
+
: GITHUB_PROTECTED_WORKSPACE_SUBPATHS)
|
|
698
|
+
: ALWAYS_PROTECTED_WORKSPACE_SUBPATHS;
|
|
699
|
+
const profileAutomationProtected = protectGitHub
|
|
700
|
+
? (allowWorkflowWrites
|
|
701
|
+
? GITHUB_PROTECTED_AUTOMATION_PATHS.filter(sub => sub !== '.github')
|
|
702
|
+
: GITHUB_PROTECTED_AUTOMATION_PATHS)
|
|
703
|
+
: LOCAL_PROTECTED_AUTOMATION_PATHS;
|
|
704
|
+
const discoveredGitHubSiblings = allowWorkflowWrites
|
|
705
|
+
? collectGitHubSiblingPaths({ repositoryRoot: canonicalWorkspaceRoot })
|
|
706
|
+
: [];
|
|
707
|
+
let omitBareControlRootProtection = false;
|
|
708
|
+
let canonicalProposalFile = null;
|
|
709
|
+
let discoveredSiblings = {
|
|
710
|
+
prioritySiblings: [],
|
|
711
|
+
regularSiblings: [],
|
|
712
|
+
};
|
|
713
|
+
if (normalizedProposalPath !== undefined) {
|
|
714
|
+
discoveredSiblings = collectControlRootSiblingPaths({
|
|
715
|
+
repositoryRoot: canonicalWorkspaceRoot,
|
|
716
|
+
controlRoot: effectiveControlRoot,
|
|
717
|
+
proposalPath: normalizedProposalPath,
|
|
718
|
+
});
|
|
719
|
+
const workspaceRelativeWritables = [];
|
|
720
|
+
for (const [index, entry] of policy.writablePaths.entries()) {
|
|
721
|
+
const cleaned = assertCleanPathString(entry, `writablePaths/${index}`);
|
|
722
|
+
if (cleaned === '.' || cleaned === '**') {
|
|
723
|
+
workspaceRelativeWritables.push(cleaned);
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
if (isAbsolute(cleaned)) {
|
|
727
|
+
const canonicalEntry = canonicalizeAbsolutePath(cleaned, `writablePaths/${index}`);
|
|
728
|
+
if (isSameOrSubpath(canonicalEntry, canonicalWorkspaceRoot)) {
|
|
729
|
+
if (canonicalEntry === canonicalWorkspaceRoot) {
|
|
730
|
+
workspaceRelativeWritables.push('.');
|
|
731
|
+
}
|
|
732
|
+
else {
|
|
733
|
+
const rel = canonicalEntry.slice(canonicalWorkspaceRoot.length + 1).split(sep).join('/');
|
|
734
|
+
workspaceRelativeWritables.push(rel);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
else {
|
|
739
|
+
const parsedWritable = normalizeRelativeScopeEntry(cleaned, `writablePaths/${index}`);
|
|
740
|
+
workspaceRelativeWritables.push(parsedWritable.subtree ? `${parsedWritable.base}/**` : parsedWritable.base);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
const explicitControlProtected = [
|
|
744
|
+
...profileWorkspaceProtected,
|
|
745
|
+
...profileAutomationProtected,
|
|
746
|
+
...discoveredGitHubSiblings,
|
|
747
|
+
`${effectiveControlRoot}/policies`,
|
|
748
|
+
`${effectiveControlRoot}/checks`,
|
|
749
|
+
`${effectiveControlRoot}/scripts`,
|
|
750
|
+
`${effectiveControlRoot}/memory`,
|
|
751
|
+
`${effectiveControlRoot}/taskpack.yaml`,
|
|
752
|
+
`${effectiveControlRoot}/taskpack.yml`,
|
|
753
|
+
`${effectiveControlRoot}/taskpack.json`,
|
|
754
|
+
`${effectiveControlRoot}/digests.lock.json`,
|
|
755
|
+
...callerProtectedRelPaths,
|
|
756
|
+
...discoveredSiblings.prioritySiblings,
|
|
757
|
+
];
|
|
758
|
+
if (!isControlRootProposalWritableAllowed(normalizedProposalPath, workspaceRelativeWritables, effectiveControlRoot, explicitControlProtected)) {
|
|
759
|
+
policyInvalid(`proposalPath "${policy.proposalPath}" is not permitted as a carved-out control-root writable file`, 'proposalPath');
|
|
760
|
+
}
|
|
761
|
+
if (existsSync(canonicalWorkspaceRoot)) {
|
|
762
|
+
const segments = normalizedProposalPath.split('/');
|
|
763
|
+
let cursor = canonicalWorkspaceRoot;
|
|
764
|
+
for (let i = 0; i < segments.length; i += 1) {
|
|
765
|
+
cursor = join(cursor, segments[i]);
|
|
766
|
+
let st;
|
|
767
|
+
try {
|
|
768
|
+
st = lstatSync(cursor);
|
|
769
|
+
}
|
|
770
|
+
catch {
|
|
771
|
+
st = null;
|
|
772
|
+
}
|
|
773
|
+
if (st === null)
|
|
774
|
+
break;
|
|
775
|
+
if (st.isSymbolicLink()) {
|
|
776
|
+
policyInvalid(`proposalPath "${policy.proposalPath}" must not traverse or target symbolic links`, 'proposalPath');
|
|
777
|
+
}
|
|
778
|
+
if (i < segments.length - 1) {
|
|
779
|
+
if (!st.isDirectory()) {
|
|
780
|
+
policyInvalid(`parent segment of proposalPath "${policy.proposalPath}" is not a directory`, 'proposalPath');
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
else if (!st.isFile() || st.nlink > 1) {
|
|
784
|
+
policyInvalid(`proposalPath "${policy.proposalPath}" must be a regular non-hardlinked file when present`, 'proposalPath');
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
canonicalProposalFile = canonicalizeAbsolutePath(join(canonicalWorkspaceRoot, normalizedProposalPath), 'proposalPath');
|
|
789
|
+
if (!isSameOrSubpath(canonicalProposalFile, canonicalControlRoot) || canonicalProposalFile === canonicalControlRoot) {
|
|
790
|
+
policyInvalid(`proposalPath "${policy.proposalPath}" escapes controlRoot "${effectiveControlRoot}"`, 'proposalPath');
|
|
791
|
+
}
|
|
792
|
+
omitBareControlRootProtection = true;
|
|
793
|
+
}
|
|
794
|
+
const protectedSubpaths = new Set([
|
|
795
|
+
...profileWorkspaceProtected,
|
|
796
|
+
...profileAutomationProtected,
|
|
797
|
+
...(omitBareControlRootProtection
|
|
798
|
+
? [
|
|
799
|
+
`${effectiveControlRoot}/policies`,
|
|
800
|
+
`${effectiveControlRoot}/checks`,
|
|
801
|
+
`${effectiveControlRoot}/scripts`,
|
|
802
|
+
`${effectiveControlRoot}/memory`,
|
|
803
|
+
`${effectiveControlRoot}/taskpack.yaml`,
|
|
804
|
+
`${effectiveControlRoot}/taskpack.yml`,
|
|
805
|
+
`${effectiveControlRoot}/taskpack.json`,
|
|
806
|
+
`${effectiveControlRoot}/digests.lock.json`,
|
|
807
|
+
...discoveredSiblings.prioritySiblings,
|
|
808
|
+
]
|
|
809
|
+
: [effectiveControlRoot]),
|
|
810
|
+
...callerProtectedRelPaths,
|
|
811
|
+
]);
|
|
812
|
+
for (const githubSibling of discoveredGitHubSiblings) {
|
|
813
|
+
if (protectedSubpaths.size >= 128)
|
|
814
|
+
break;
|
|
815
|
+
protectedSubpaths.add(githubSibling);
|
|
816
|
+
}
|
|
817
|
+
if (omitBareControlRootProtection) {
|
|
818
|
+
for (const sibling of discoveredSiblings.regularSiblings) {
|
|
819
|
+
if (protectedSubpaths.size >= 128)
|
|
820
|
+
break;
|
|
821
|
+
protectedSubpaths.add(sibling);
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
const canonicalProtectedSet = new Set();
|
|
825
|
+
for (const rel of protectedSubpaths) {
|
|
826
|
+
canonicalProtectedSet.add(canonicalizeAbsolutePath(join(canonicalWorkspaceRoot, rel), `protectedPaths/${rel}`));
|
|
827
|
+
}
|
|
828
|
+
const canonicalProtectedPaths = Object.freeze([...canonicalProtectedSet].sort());
|
|
829
|
+
const canonicalGitHubDir = canonicalizeAbsolutePath(join(canonicalWorkspaceRoot, '.github'), 'protectedPaths/.github');
|
|
830
|
+
const canonicalWorkflowsDir = canonicalizeAbsolutePath(join(canonicalWorkspaceRoot, '.github', 'workflows'), 'protectedPaths/.github/workflows');
|
|
831
|
+
const assertCanonicalGrantAllowed = (canonicalGrant, label, checkEncompassedProtected) => {
|
|
832
|
+
for (const protectedPath of canonicalProtectedPaths) {
|
|
833
|
+
if (isSameOrSubpath(canonicalGrant, protectedPath)) {
|
|
834
|
+
policyInvalid(`${label} targets protected path "${protectedPath}"`, label);
|
|
835
|
+
}
|
|
836
|
+
if (checkEncompassedProtected && isSameOrSubpath(protectedPath, canonicalGrant)) {
|
|
837
|
+
policyInvalid(`${label} encompasses protected path "${protectedPath}"`, label);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
if (allowWorkflowWrites) {
|
|
841
|
+
if ((isSameOrSubpath(canonicalGrant, canonicalGitHubDir) || isSameOrSubpathCaseInsensitive(canonicalGrant, canonicalGitHubDir))
|
|
842
|
+
&& !(isSameOrSubpath(canonicalGrant, canonicalWorkflowsDir) || isSameOrSubpathCaseInsensitive(canonicalGrant, canonicalWorkflowsDir))) {
|
|
843
|
+
policyInvalid(`${label} targets protected .github path "${canonicalGrant}" outside .github/workflows`, label);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
if (canonicalProposalFile !== null) {
|
|
847
|
+
if (isSameOrSubpath(canonicalControlRoot, canonicalGrant)
|
|
848
|
+
|| isSameOrSubpathCaseInsensitive(canonicalControlRoot, canonicalGrant)) {
|
|
849
|
+
policyInvalid(`${label} canonicalizes to "${canonicalGrant}", encompassing protected control root "${canonicalControlRoot}"`, label);
|
|
850
|
+
}
|
|
851
|
+
if ((isSameOrSubpath(canonicalGrant, canonicalControlRoot)
|
|
852
|
+
|| isSameOrSubpathCaseInsensitive(canonicalGrant, canonicalControlRoot))
|
|
853
|
+
&& canonicalGrant !== canonicalProposalFile) {
|
|
854
|
+
policyInvalid(`${label} canonicalizes to "${canonicalGrant}" inside control root "${canonicalControlRoot}" outside "${canonicalProposalFile}"`, label);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
};
|
|
858
|
+
if (canonicalProposalFile !== null) {
|
|
859
|
+
for (const protectedPath of canonicalProtectedPaths) {
|
|
860
|
+
if (isSameOrSubpath(canonicalProposalFile, protectedPath)
|
|
861
|
+
|| isSameOrSubpath(protectedPath, canonicalProposalFile)
|
|
862
|
+
|| isSameOrSubpathCaseInsensitive(canonicalProposalFile, protectedPath)
|
|
863
|
+
|| isSameOrSubpathCaseInsensitive(protectedPath, canonicalProposalFile)) {
|
|
864
|
+
policyInvalid(`proposalPath "${policy.proposalPath}" overlaps protected path "${protectedPath}"`, 'proposalPath');
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
const assertRegularExactFileTarget = (exactTarget, label) => {
|
|
869
|
+
if (!existsSync(canonicalWorkspaceRoot))
|
|
870
|
+
return;
|
|
871
|
+
let st;
|
|
872
|
+
try {
|
|
873
|
+
st = lstatSync(exactTarget);
|
|
874
|
+
}
|
|
875
|
+
catch {
|
|
876
|
+
st = null;
|
|
877
|
+
}
|
|
878
|
+
if (st !== null && (st.isSymbolicLink() || !st.isFile() || st.nlink > 1)) {
|
|
879
|
+
policyInvalid(`${label} "${exactTarget}" must be a regular non-hardlinked file when present`, label);
|
|
880
|
+
}
|
|
881
|
+
};
|
|
882
|
+
const canonicalWritableSet = new Set();
|
|
883
|
+
const exactWritableFilesSet = new Set(canonicalProposalFile !== null ? [canonicalProposalFile] : []);
|
|
884
|
+
const seatbeltExactRegexSet = new Set();
|
|
885
|
+
const registerGrant = (canonicalWritable, rawEntry, label, exactFile) => {
|
|
886
|
+
const insideWorkspace = isSameOrSubpath(canonicalWritable, canonicalWorkspaceRoot);
|
|
887
|
+
const insideScratch = canonicalScratchDirectory !== null && isSameOrSubpath(canonicalWritable, canonicalScratchDirectory);
|
|
888
|
+
if (!insideWorkspace && !insideScratch) {
|
|
889
|
+
policyInvalid(`writablePath "${rawEntry}" escapes workspaceRoot`, label);
|
|
890
|
+
}
|
|
891
|
+
assertCanonicalGrantAllowed(canonicalWritable, label, false);
|
|
892
|
+
if (exactFile && canonicalWritable !== canonicalWorkspaceRoot) {
|
|
893
|
+
assertRegularExactFileTarget(canonicalWritable, label);
|
|
894
|
+
exactWritableFilesSet.add(canonicalWritable);
|
|
895
|
+
}
|
|
896
|
+
canonicalWritableSet.add(canonicalWritable);
|
|
897
|
+
};
|
|
898
|
+
for (const [index, entry] of policy.writablePaths.entries()) {
|
|
899
|
+
const label = `writablePaths/${index}`;
|
|
900
|
+
const cleaned = assertCleanPathString(entry, label);
|
|
901
|
+
if (cleaned === '.' || cleaned === '**') {
|
|
902
|
+
registerGrant(canonicalWorkspaceRoot, entry, label, false);
|
|
903
|
+
continue;
|
|
904
|
+
}
|
|
905
|
+
if (isAbsolute(cleaned)) {
|
|
906
|
+
const canonicalWritable = canonicalizeAbsolutePath(cleaned, label);
|
|
907
|
+
registerGrant(canonicalWritable, entry, label, strictExactFiles && canonicalWritable !== canonicalWorkspaceRoot);
|
|
908
|
+
continue;
|
|
909
|
+
}
|
|
910
|
+
const parsed = normalizeRelativeScopeEntry(cleaned, label);
|
|
911
|
+
if (!parsed.hasGlob) {
|
|
912
|
+
const canonicalWritable = canonicalizeAbsolutePath(join(canonicalWorkspaceRoot, parsed.base), label);
|
|
913
|
+
const isExact = (strictExactFiles && !parsed.subtree) || canonicalWritable === canonicalProposalFile;
|
|
914
|
+
registerGrant(canonicalWritable, entry, label, isExact);
|
|
915
|
+
continue;
|
|
916
|
+
}
|
|
917
|
+
const globBudget = { visitedDirs: 0, expandedPaths: 0 };
|
|
918
|
+
const segments = parsed.base.split('/');
|
|
919
|
+
if (parsed.subtree) {
|
|
920
|
+
for (const dir of expandDirectorySegmentsSync(canonicalWorkspaceRoot, segments, label, globBudget)) {
|
|
921
|
+
registerGrant(dir, entry, label, false);
|
|
922
|
+
}
|
|
923
|
+
continue;
|
|
924
|
+
}
|
|
925
|
+
const parentSegments = segments.slice(0, -1);
|
|
926
|
+
const leafSegment = segments[segments.length - 1];
|
|
927
|
+
const parentDirs = expandDirectorySegmentsSync(canonicalWorkspaceRoot, parentSegments, label, globBudget);
|
|
928
|
+
if (!segmentHasGlob(leafSegment)) {
|
|
929
|
+
for (const parentDir of parentDirs) {
|
|
930
|
+
globBudget.expandedPaths += 1;
|
|
931
|
+
if (globBudget.expandedPaths > MAX_GLOB_EXPANDED_PATHS) {
|
|
932
|
+
policyInvalid(`sandbox glob expansion exceeded ${MAX_GLOB_EXPANDED_PATHS} expanded paths`, label);
|
|
933
|
+
}
|
|
934
|
+
const target = canonicalizeAbsolutePath(join(parentDir, leafSegment), label);
|
|
935
|
+
registerGrant(target, entry, label, true);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
else {
|
|
939
|
+
const leafMatcher = segmentGlobToRegExp(leafSegment);
|
|
940
|
+
const leafRegex = segmentGlobToSeatbeltRegex(leafSegment);
|
|
941
|
+
for (const parentDir of parentDirs) {
|
|
942
|
+
globBudget.visitedDirs += 1;
|
|
943
|
+
if (globBudget.visitedDirs > MAX_GLOB_VISITED_DIRS) {
|
|
944
|
+
policyInvalid(`sandbox glob expansion exceeded ${MAX_GLOB_VISITED_DIRS} visited directories`, label);
|
|
945
|
+
}
|
|
946
|
+
assertCanonicalGrantAllowed(parentDir, label, false);
|
|
947
|
+
seatbeltExactRegexSet.add(`^${escapeSeatbeltRegexLiteral(parentDir)}/${leafRegex}$`);
|
|
948
|
+
let names;
|
|
949
|
+
try {
|
|
950
|
+
names = readdirSync(parentDir, { encoding: 'utf8' }).sort();
|
|
951
|
+
}
|
|
952
|
+
catch {
|
|
953
|
+
names = [];
|
|
954
|
+
}
|
|
955
|
+
for (const name of names) {
|
|
956
|
+
if (name === '.' || name === '..' || !leafMatcher.test(name))
|
|
957
|
+
continue;
|
|
958
|
+
const candidatePath = join(parentDir, name);
|
|
959
|
+
let st;
|
|
960
|
+
try {
|
|
961
|
+
st = lstatSync(candidatePath);
|
|
962
|
+
}
|
|
963
|
+
catch {
|
|
964
|
+
st = null;
|
|
965
|
+
}
|
|
966
|
+
if (st !== null && !st.isSymbolicLink() && st.isFile() && st.nlink === 1) {
|
|
967
|
+
globBudget.expandedPaths += 1;
|
|
968
|
+
if (globBudget.expandedPaths > MAX_GLOB_EXPANDED_PATHS) {
|
|
969
|
+
policyInvalid(`sandbox glob expansion exceeded ${MAX_GLOB_EXPANDED_PATHS} expanded paths`, label);
|
|
970
|
+
}
|
|
971
|
+
const target = canonicalizeAbsolutePath(candidatePath, label);
|
|
972
|
+
registerGrant(target, entry, label, true);
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
if (canonicalScratchDirectory !== null) {
|
|
979
|
+
assertCanonicalGrantAllowed(canonicalScratchDirectory, 'scratchDirectory', true);
|
|
980
|
+
canonicalWritableSet.add(canonicalScratchDirectory);
|
|
981
|
+
}
|
|
982
|
+
const canonicalWritablePaths = Object.freeze([...canonicalWritableSet].sort());
|
|
983
|
+
const canonicalExactWritableFiles = exactWritableFilesSet;
|
|
984
|
+
const seatbeltExactFileRegexes = Object.freeze([...seatbeltExactRegexSet].sort());
|
|
985
|
+
const defaultDeniedHomeSet = new Set();
|
|
986
|
+
const deniedSet = new Set();
|
|
987
|
+
if (typeof env.homeDirectory === 'string' && env.homeDirectory.length > 0 && isAbsolute(env.homeDirectory)) {
|
|
988
|
+
const canonicalHome = canonicalizeAbsolutePath(env.homeDirectory, 'homeDirectory');
|
|
989
|
+
for (const subpath of DEFAULT_DENIED_HOME_SUBPATHS) {
|
|
990
|
+
const canonicalDefaultDenied = canonicalizeAbsolutePath(join(canonicalHome, subpath), `homeDirectory/${subpath}`);
|
|
991
|
+
defaultDeniedHomeSet.add(canonicalDefaultDenied);
|
|
992
|
+
deniedSet.add(canonicalDefaultDenied);
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
if (policy.deniedReadPaths !== undefined) {
|
|
996
|
+
if (!Array.isArray(policy.deniedReadPaths) || policy.deniedReadPaths.length > 128) {
|
|
997
|
+
policyInvalid('deniedReadPaths must be an array of at most 128 paths', 'deniedReadPaths');
|
|
998
|
+
}
|
|
999
|
+
for (const [index, entry] of policy.deniedReadPaths.entries()) {
|
|
1000
|
+
const cleaned = assertCleanPathString(entry, `deniedReadPaths/${index}`);
|
|
1001
|
+
if (cleaned.startsWith('~/')) {
|
|
1002
|
+
const rel = normalizeRelativeSubpath(cleaned.slice(2), `deniedReadPaths/${index}`);
|
|
1003
|
+
const baseHome = isAbsolute(env.homeDirectory) ? canonicalizeAbsolutePath(env.homeDirectory, 'homeDirectory') : canonicalWorkspaceRoot;
|
|
1004
|
+
deniedSet.add(canonicalizeAbsolutePath(join(baseHome, rel), `deniedReadPaths/${index}`));
|
|
1005
|
+
}
|
|
1006
|
+
else if (isAbsolute(cleaned)) {
|
|
1007
|
+
if (cleaned.split('/').some(seg => seg === '..')) {
|
|
1008
|
+
policyInvalid(`deniedReadPath "${entry}" must not contain .. traversal`, `deniedReadPaths/${index}`);
|
|
1009
|
+
}
|
|
1010
|
+
deniedSet.add(canonicalizeAbsolutePath(cleaned, `deniedReadPaths/${index}`));
|
|
1011
|
+
}
|
|
1012
|
+
else {
|
|
1013
|
+
const rel = normalizeRelativeSubpath(cleaned, `deniedReadPaths/${index}`);
|
|
1014
|
+
deniedSet.add(canonicalizeAbsolutePath(join(canonicalWorkspaceRoot, rel), `deniedReadPaths/${index}`));
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
const allowedReadOnlySet = new Set();
|
|
1019
|
+
if (policy.allowedReadOnlyPaths !== undefined) {
|
|
1020
|
+
if (!Array.isArray(policy.allowedReadOnlyPaths) || policy.allowedReadOnlyPaths.length > 64) {
|
|
1021
|
+
policyInvalid('allowedReadOnlyPaths must be an array of at most 64 paths', 'allowedReadOnlyPaths');
|
|
1022
|
+
}
|
|
1023
|
+
for (const [index, entry] of policy.allowedReadOnlyPaths.entries()) {
|
|
1024
|
+
const label = `allowedReadOnlyPaths/${index}`;
|
|
1025
|
+
const cleaned = assertCleanPathString(entry, label);
|
|
1026
|
+
if (!isAbsolute(cleaned) || cleaned.split('/').some(seg => seg === '..')) {
|
|
1027
|
+
policyInvalid(`allowedReadOnlyPath "${entry}" must be an absolute path without .. traversal`, label);
|
|
1028
|
+
}
|
|
1029
|
+
const canonicalAllowed = canonicalizeAbsolutePath(cleaned, label);
|
|
1030
|
+
for (const homeDenied of defaultDeniedHomeSet) {
|
|
1031
|
+
if (isSameOrSubpath(canonicalAllowed, homeDenied) || isSameOrSubpathCaseInsensitive(canonicalAllowed, homeDenied)) {
|
|
1032
|
+
policyInvalid(`allowedReadOnlyPath "${entry}" targets default denied secret path "${homeDenied}"`, label);
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
allowedReadOnlySet.add(canonicalAllowed);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
const canonicalAllowedReadOnlyPaths = Object.freeze([...allowedReadOnlySet].sort());
|
|
1039
|
+
const readOnlyBindMountList = [];
|
|
1040
|
+
const seenBindTargets = new Set();
|
|
1041
|
+
if (policy.readOnlyBindMounts !== undefined) {
|
|
1042
|
+
if (!Array.isArray(policy.readOnlyBindMounts) || policy.readOnlyBindMounts.length > MAX_READ_ONLY_BIND_MOUNTS) {
|
|
1043
|
+
policyInvalid(`readOnlyBindMounts must be an array of at most ${MAX_READ_ONLY_BIND_MOUNTS} mounts`, 'readOnlyBindMounts');
|
|
1044
|
+
}
|
|
1045
|
+
for (const [index, rawMount] of policy.readOnlyBindMounts.entries()) {
|
|
1046
|
+
const mountLabel = `readOnlyBindMounts/${index}`;
|
|
1047
|
+
if (rawMount === null || typeof rawMount !== 'object' || Array.isArray(rawMount)) {
|
|
1048
|
+
policyInvalid('readOnlyBindMount entry must be an object', mountLabel);
|
|
1049
|
+
}
|
|
1050
|
+
const proto = Object.getPrototypeOf(rawMount);
|
|
1051
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
1052
|
+
policyInvalid('readOnlyBindMount entry must be a plain object', mountLabel);
|
|
1053
|
+
}
|
|
1054
|
+
const sourceLabel = `${mountLabel}/sourcePath`;
|
|
1055
|
+
const targetLabel = `${mountLabel}/targetPath`;
|
|
1056
|
+
const cleanedSource = assertCleanPathString(rawMount.sourcePath, sourceLabel);
|
|
1057
|
+
if (!isAbsolute(cleanedSource) || cleanedSource.split('/').some(seg => seg === '..')) {
|
|
1058
|
+
policyInvalid(`readOnlyBindMount sourcePath "${cleanedSource}" must be an absolute path without .. traversal`, sourceLabel);
|
|
1059
|
+
}
|
|
1060
|
+
const resolvedSource = resolve(cleanedSource);
|
|
1061
|
+
let sourceStat;
|
|
1062
|
+
try {
|
|
1063
|
+
sourceStat = lstatSync(resolvedSource);
|
|
1064
|
+
}
|
|
1065
|
+
catch {
|
|
1066
|
+
sourceStat = null;
|
|
1067
|
+
}
|
|
1068
|
+
if (sourceStat === null || sourceStat.isSymbolicLink() || !sourceStat.isDirectory()) {
|
|
1069
|
+
policyInvalid(`readOnlyBindMount sourcePath "${cleanedSource}" must be an existing non-symlink directory`, sourceLabel);
|
|
1070
|
+
}
|
|
1071
|
+
let canonicalSource;
|
|
1072
|
+
try {
|
|
1073
|
+
canonicalSource = realpathSync(resolvedSource);
|
|
1074
|
+
}
|
|
1075
|
+
catch {
|
|
1076
|
+
policyInvalid(`readOnlyBindMount sourcePath "${cleanedSource}" could not be canonicalized`, sourceLabel);
|
|
1077
|
+
}
|
|
1078
|
+
if (/[\0\r\n"\\]/.test(canonicalSource)) {
|
|
1079
|
+
policyInvalid(`readOnlyBindMount sourcePath "${cleanedSource}" resolved to a path with forbidden characters`, sourceLabel);
|
|
1080
|
+
}
|
|
1081
|
+
let realSourceStat;
|
|
1082
|
+
try {
|
|
1083
|
+
realSourceStat = lstatSync(canonicalSource);
|
|
1084
|
+
}
|
|
1085
|
+
catch {
|
|
1086
|
+
realSourceStat = null;
|
|
1087
|
+
}
|
|
1088
|
+
if (realSourceStat === null || realSourceStat.isSymbolicLink() || !realSourceStat.isDirectory()) {
|
|
1089
|
+
policyInvalid(`readOnlyBindMount sourcePath "${cleanedSource}" must resolve to a directory`, sourceLabel);
|
|
1090
|
+
}
|
|
1091
|
+
for (const homeDenied of defaultDeniedHomeSet) {
|
|
1092
|
+
if (isSameOrSubpath(canonicalSource, homeDenied)
|
|
1093
|
+
|| isSameOrSubpath(homeDenied, canonicalSource)
|
|
1094
|
+
|| isSameOrSubpathCaseInsensitive(canonicalSource, homeDenied)
|
|
1095
|
+
|| isSameOrSubpathCaseInsensitive(homeDenied, canonicalSource)) {
|
|
1096
|
+
policyInvalid(`readOnlyBindMount sourcePath "${cleanedSource}" overlaps default denied secret path "${homeDenied}"`, sourceLabel);
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
const cleanedTarget = assertCleanPathString(rawMount.targetPath, targetLabel);
|
|
1100
|
+
if (!isAbsolute(cleanedTarget) || cleanedTarget.split('/').some(seg => seg === '..')) {
|
|
1101
|
+
policyInvalid(`readOnlyBindMount targetPath "${cleanedTarget}" must be an absolute path without .. traversal`, targetLabel);
|
|
1102
|
+
}
|
|
1103
|
+
const canonicalTarget = canonicalizeAbsolutePath(cleanedTarget, targetLabel);
|
|
1104
|
+
if (!isSameOrSubpath(canonicalTarget, canonicalWorkspaceRoot) || canonicalTarget === canonicalWorkspaceRoot) {
|
|
1105
|
+
policyInvalid(`readOnlyBindMount targetPath "${cleanedTarget}" must be strictly inside workspaceRoot`, targetLabel);
|
|
1106
|
+
}
|
|
1107
|
+
if (existsSync(canonicalWorkspaceRoot)) {
|
|
1108
|
+
const relSegments = canonicalTarget.slice(canonicalWorkspaceRoot.length + 1).split(sep).filter(Boolean);
|
|
1109
|
+
let cursor = canonicalWorkspaceRoot;
|
|
1110
|
+
for (const seg of relSegments) {
|
|
1111
|
+
cursor = join(cursor, seg);
|
|
1112
|
+
let segStat;
|
|
1113
|
+
try {
|
|
1114
|
+
segStat = lstatSync(cursor);
|
|
1115
|
+
}
|
|
1116
|
+
catch {
|
|
1117
|
+
segStat = null;
|
|
1118
|
+
}
|
|
1119
|
+
if (segStat === null)
|
|
1120
|
+
break;
|
|
1121
|
+
if (segStat.isSymbolicLink()) {
|
|
1122
|
+
policyInvalid(`readOnlyBindMount targetPath "${cleanedTarget}" must not traverse or target symbolic links`, targetLabel);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
if (seenBindTargets.has(canonicalTarget)) {
|
|
1127
|
+
policyInvalid(`duplicate readOnlyBindMount targetPath "${canonicalTarget}"`, targetLabel);
|
|
1128
|
+
}
|
|
1129
|
+
seenBindTargets.add(canonicalTarget);
|
|
1130
|
+
readOnlyBindMountList.push(Object.freeze({ sourcePath: canonicalSource, targetPath: canonicalTarget }));
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
readOnlyBindMountList.sort((a, b) => (a.targetPath < b.targetPath ? -1 : a.targetPath > b.targetPath ? 1 : 0));
|
|
1134
|
+
const canonicalReadOnlyBindMounts = Object.freeze(readOnlyBindMountList);
|
|
1135
|
+
const filteredDenied = [...deniedSet].filter(deniedPath => {
|
|
1136
|
+
if (isSameOrSubpath(canonicalWorkspaceRoot, deniedPath) && deniedPath !== canonicalWorkspaceRoot) {
|
|
1137
|
+
return false;
|
|
1138
|
+
}
|
|
1139
|
+
if (deniedPath === canonicalWorkspaceRoot) {
|
|
1140
|
+
policyInvalid('deniedReadPaths must not deny workspaceRoot itself', 'deniedReadPaths');
|
|
1141
|
+
}
|
|
1142
|
+
if (canonicalScratchDirectory !== null && isSameOrSubpath(canonicalScratchDirectory, deniedPath)) {
|
|
1143
|
+
return false;
|
|
1144
|
+
}
|
|
1145
|
+
return true;
|
|
1146
|
+
}).sort();
|
|
1147
|
+
for (const wp of canonicalWritablePaths) {
|
|
1148
|
+
for (const dp of filteredDenied) {
|
|
1149
|
+
if (isSameOrSubpath(wp, dp)) {
|
|
1150
|
+
policyInvalid(`writablePath "${wp}" conflicts with deniedReadPath "${dp}"`, 'writablePaths');
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
return {
|
|
1155
|
+
canonicalWorkspaceRoot,
|
|
1156
|
+
canonicalScratchDirectory,
|
|
1157
|
+
canonicalWritablePaths,
|
|
1158
|
+
canonicalExactWritableFiles,
|
|
1159
|
+
seatbeltExactFileRegexes,
|
|
1160
|
+
seatbeltProtectedGlobRegexes: Object.freeze([...seatbeltProtectedGlobRegexSet].sort()),
|
|
1161
|
+
protectedGlobPrefixes: Object.freeze(protectedGlobPrefixesList),
|
|
1162
|
+
canonicalProtectedPaths,
|
|
1163
|
+
canonicalDeniedReadPaths: Object.freeze(filteredDenied),
|
|
1164
|
+
canonicalAllowedReadOnlyPaths,
|
|
1165
|
+
canonicalReadOnlyBindMounts,
|
|
1166
|
+
networkMode,
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
function isExecutableFile(candidate) {
|
|
1170
|
+
try {
|
|
1171
|
+
const real = realpathSync(candidate);
|
|
1172
|
+
const stats = statSync(real);
|
|
1173
|
+
return stats.isFile() && (stats.mode & 0o111) !== 0;
|
|
1174
|
+
}
|
|
1175
|
+
catch {
|
|
1176
|
+
return false;
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
function validateExecutableChoice(configured, trustedAllowlist, probeExecutables) {
|
|
1180
|
+
if (configured !== undefined) {
|
|
1181
|
+
if (!trustedAllowlist.includes(configured)) {
|
|
1182
|
+
return null;
|
|
1183
|
+
}
|
|
1184
|
+
if (probeExecutables && !isExecutableFile(configured)) {
|
|
1185
|
+
return null;
|
|
1186
|
+
}
|
|
1187
|
+
return configured;
|
|
1188
|
+
}
|
|
1189
|
+
if (!probeExecutables) {
|
|
1190
|
+
return trustedAllowlist[0] ?? null;
|
|
1191
|
+
}
|
|
1192
|
+
for (const candidate of trustedAllowlist) {
|
|
1193
|
+
if (isExecutableFile(candidate))
|
|
1194
|
+
return candidate;
|
|
1195
|
+
}
|
|
1196
|
+
return null;
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
1199
|
+
* Compile a canonical, deterministic macOS Seatbelt (`sandbox-exec`) SBPL profile.
|
|
1200
|
+
* Last-match-wins precedence ensures protected paths inside writable directories stay read-only.
|
|
1201
|
+
*/
|
|
1202
|
+
export function compileMacosSeatbeltProfile(policy, host) {
|
|
1203
|
+
const env = resolveHostEnvironment(host);
|
|
1204
|
+
const executablePath = env.seatbeltExecutable ?? TRUSTED_SEATBELT_PATHS[0];
|
|
1205
|
+
if (!TRUSTED_SEATBELT_PATHS.includes(executablePath)) {
|
|
1206
|
+
throw new TaskpackError('SANDBOX_BACKEND_UNAVAILABLE', `untrusted macOS seatbelt executable "${executablePath}"`, 'seatbeltExecutable');
|
|
1207
|
+
}
|
|
1208
|
+
const normalized = normalizeSandboxPolicy(policy, env);
|
|
1209
|
+
const lines = [
|
|
1210
|
+
'(version 1)',
|
|
1211
|
+
'(allow default)',
|
|
1212
|
+
];
|
|
1213
|
+
if (normalized.canonicalDeniedReadPaths.length > 0) {
|
|
1214
|
+
lines.push('(deny file-read*');
|
|
1215
|
+
for (const deniedPath of normalized.canonicalDeniedReadPaths) {
|
|
1216
|
+
lines.push(` (subpath "${deniedPath}")`);
|
|
1217
|
+
}
|
|
1218
|
+
lines.push(')');
|
|
1219
|
+
}
|
|
1220
|
+
if (normalized.canonicalAllowedReadOnlyPaths.length > 0) {
|
|
1221
|
+
lines.push('(allow file-read*');
|
|
1222
|
+
for (const roPath of normalized.canonicalAllowedReadOnlyPaths) {
|
|
1223
|
+
lines.push(` (subpath "${roPath}")`);
|
|
1224
|
+
}
|
|
1225
|
+
lines.push(')');
|
|
1226
|
+
}
|
|
1227
|
+
lines.push('(deny file-write*)');
|
|
1228
|
+
lines.push('(allow file-write*');
|
|
1229
|
+
lines.push(' (literal "/dev/null")');
|
|
1230
|
+
lines.push(' (literal "/dev/zero")');
|
|
1231
|
+
lines.push(' (literal "/dev/dtracehelper")');
|
|
1232
|
+
for (const writablePath of normalized.canonicalWritablePaths) {
|
|
1233
|
+
if (normalized.canonicalExactWritableFiles.has(writablePath)) {
|
|
1234
|
+
lines.push(` (require-all (literal "${writablePath}") (vnode-type REGULAR-FILE))`);
|
|
1235
|
+
}
|
|
1236
|
+
else {
|
|
1237
|
+
lines.push(` (subpath "${writablePath}")`);
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
for (const regexRule of normalized.seatbeltExactFileRegexes) {
|
|
1241
|
+
lines.push(` (require-all (regex #"${regexRule}") (vnode-type REGULAR-FILE))`);
|
|
1242
|
+
}
|
|
1243
|
+
lines.push(')');
|
|
1244
|
+
if (normalized.canonicalProtectedPaths.length > 0 || normalized.seatbeltProtectedGlobRegexes.length > 0) {
|
|
1245
|
+
lines.push('(deny file-write*');
|
|
1246
|
+
for (const protectedPath of normalized.canonicalProtectedPaths) {
|
|
1247
|
+
lines.push(` (subpath "${protectedPath}")`);
|
|
1248
|
+
}
|
|
1249
|
+
for (const rx of normalized.seatbeltProtectedGlobRegexes) {
|
|
1250
|
+
lines.push(` (regex #"${rx}")`);
|
|
1251
|
+
}
|
|
1252
|
+
lines.push(')');
|
|
1253
|
+
}
|
|
1254
|
+
if (normalized.networkMode === 'none') {
|
|
1255
|
+
lines.push('(deny network*)');
|
|
1256
|
+
}
|
|
1257
|
+
else if (normalized.networkMode === 'loopback-only') {
|
|
1258
|
+
lines.push('(deny network*)');
|
|
1259
|
+
lines.push('(allow network-outbound (remote ip "localhost:*"))');
|
|
1260
|
+
lines.push('(allow network-inbound (local ip "localhost:*"))');
|
|
1261
|
+
lines.push('(allow network-bind (local ip "localhost:*"))');
|
|
1262
|
+
}
|
|
1263
|
+
const profileText = `${lines.join('\n')}\n`;
|
|
1264
|
+
const profileDigest = sha256Digest('loopwright.dev/sandbox-seatbelt/v1', profileText);
|
|
1265
|
+
return Object.freeze({
|
|
1266
|
+
backendId: 'macos-seatbelt',
|
|
1267
|
+
executablePath,
|
|
1268
|
+
profileText,
|
|
1269
|
+
profileDigest,
|
|
1270
|
+
canonicalWorkspaceRoot: normalized.canonicalWorkspaceRoot,
|
|
1271
|
+
canonicalWritablePaths: normalized.canonicalWritablePaths,
|
|
1272
|
+
canonicalProtectedPaths: normalized.canonicalProtectedPaths,
|
|
1273
|
+
canonicalDeniedReadPaths: normalized.canonicalDeniedReadPaths,
|
|
1274
|
+
networkMode: normalized.networkMode,
|
|
1275
|
+
});
|
|
1276
|
+
}
|
|
1277
|
+
const SECCOMP_BLOCKED_SYSCALL_NRS_X64 = Object.freeze([
|
|
1278
|
+
101, 246, 320, 165, 166, 155, 321, 298, 323, 250, 248, 249, 425, 426, 427,
|
|
1279
|
+
]);
|
|
1280
|
+
const SECCOMP_BLOCKED_SYSCALL_NRS_ARM64 = Object.freeze([
|
|
1281
|
+
117, 104, 294, 40, 39, 41, 280, 241, 282, 219, 217, 218, 425, 426, 427,
|
|
1282
|
+
]);
|
|
1283
|
+
/**
|
|
1284
|
+
* Compile the deterministic classic BPF `struct sock_filter` binary (`bwrap --seccomp <fd>`)
|
|
1285
|
+
* enforcing `SECCOMP_BLOCKED_SYSCALLS` (and optional non-`AF_UNIX` `SYS_socket` blocking)
|
|
1286
|
+
* on `x64` (`AUDIT_ARCH_X86_64`) and `arm64` (`AUDIT_ARCH_AARCH64`).
|
|
1287
|
+
*/
|
|
1288
|
+
export function compileLinuxSeccompBpfBinary(arch, options) {
|
|
1289
|
+
let auditArch;
|
|
1290
|
+
let blockedNrs;
|
|
1291
|
+
let sysSocketNr;
|
|
1292
|
+
let blockX32Abi;
|
|
1293
|
+
if (arch === 'x64') {
|
|
1294
|
+
auditArch = 0xc000003e;
|
|
1295
|
+
blockedNrs = SECCOMP_BLOCKED_SYSCALL_NRS_X64;
|
|
1296
|
+
sysSocketNr = 41;
|
|
1297
|
+
blockX32Abi = true;
|
|
1298
|
+
}
|
|
1299
|
+
else if (arch === 'arm64') {
|
|
1300
|
+
auditArch = 0xc00000b7;
|
|
1301
|
+
blockedNrs = SECCOMP_BLOCKED_SYSCALL_NRS_ARM64;
|
|
1302
|
+
sysSocketNr = 198;
|
|
1303
|
+
blockX32Abi = false;
|
|
1304
|
+
}
|
|
1305
|
+
else {
|
|
1306
|
+
throw new TaskpackError('SANDBOX_CAPABILITY_INSUFFICIENT', `unsupported Linux seccomp architecture "${arch}"`, 'arch');
|
|
1307
|
+
}
|
|
1308
|
+
const blockIpSockets = options?.blockIpSockets === true;
|
|
1309
|
+
const extraSocketInsns = blockIpSockets ? 3 : 0;
|
|
1310
|
+
const instructions = [
|
|
1311
|
+
// 1. Load seccomp_data.arch (offset 4)
|
|
1312
|
+
[0x20, 0, 0, 4],
|
|
1313
|
+
// 2. If arch == auditArch, skip unexpected-arch deny
|
|
1314
|
+
[0x15, 1, 0, auditArch],
|
|
1315
|
+
// 3. Deny unexpected architecture with SECCOMP_RET_ERRNO | EPERM (1)
|
|
1316
|
+
[0x06, 0, 0, 0x00050001],
|
|
1317
|
+
// 4. Load seccomp_data.nr (offset 0)
|
|
1318
|
+
[0x20, 0, 0, 0],
|
|
1319
|
+
// On x64, also deny x32 ABI syscalls (nr >= 0x40000000), jumping straight to final SECCOMP_RET_ERRNO | 1
|
|
1320
|
+
...(blockX32Abi ? [[0x35, blockedNrs.length + extraSocketInsns + 1, 0, 0x40000000]] : []),
|
|
1321
|
+
// 5. Jump straight past remaining JEQs + optional socket check + RET_ALLOW to final SECCOMP_RET_ERRNO | 1
|
|
1322
|
+
...blockedNrs.map((nr, i) => [
|
|
1323
|
+
0x15,
|
|
1324
|
+
blockedNrs.length - i + extraSocketInsns,
|
|
1325
|
+
0,
|
|
1326
|
+
nr,
|
|
1327
|
+
]),
|
|
1328
|
+
// 6. When blockIpSockets is enabled, inspect SYS_socket domain (args[0] low 32 bits at offset 16) and allow only AF_UNIX (1)
|
|
1329
|
+
...(blockIpSockets
|
|
1330
|
+
? [
|
|
1331
|
+
[0x15, 0, 2, sysSocketNr],
|
|
1332
|
+
[0x20, 0, 0, 16],
|
|
1333
|
+
[0x15, 0, 1, 1],
|
|
1334
|
+
]
|
|
1335
|
+
: []),
|
|
1336
|
+
// 7. Default allow: SECCOMP_RET_ALLOW
|
|
1337
|
+
[0x06, 0, 0, 0x7fff0000],
|
|
1338
|
+
// 8. Deny matched syscall: SECCOMP_RET_ERRNO | EPERM (1)
|
|
1339
|
+
[0x06, 0, 0, 0x00050001],
|
|
1340
|
+
];
|
|
1341
|
+
const buf = Buffer.alloc(instructions.length * 8);
|
|
1342
|
+
for (let idx = 0; idx < instructions.length; idx += 1) {
|
|
1343
|
+
const [code, jt, jf, k] = instructions[idx];
|
|
1344
|
+
const offset = idx * 8;
|
|
1345
|
+
buf.writeUInt16LE(code, offset);
|
|
1346
|
+
buf.writeUInt8(jt, offset + 2);
|
|
1347
|
+
buf.writeUInt8(jf, offset + 3);
|
|
1348
|
+
buf.writeUInt32LE(k >>> 0, offset + 4);
|
|
1349
|
+
}
|
|
1350
|
+
return buf;
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1353
|
+
* Compute the canonical Linux seccomp BPF syscall filter profile for sandboxed tool execution.
|
|
1354
|
+
*/
|
|
1355
|
+
export function computeSandboxSeccompProfile(options) {
|
|
1356
|
+
const document = {
|
|
1357
|
+
defaultAction: 'SCMP_ACT_ALLOW',
|
|
1358
|
+
syscalls: [
|
|
1359
|
+
{
|
|
1360
|
+
names: [...SECCOMP_BLOCKED_SYSCALLS],
|
|
1361
|
+
action: 'SCMP_ACT_ERRNO',
|
|
1362
|
+
errnoRet: 1,
|
|
1363
|
+
},
|
|
1364
|
+
...(options?.blockIpSockets === true
|
|
1365
|
+
? [
|
|
1366
|
+
{
|
|
1367
|
+
names: ['socket'],
|
|
1368
|
+
action: 'SCMP_ACT_ERRNO',
|
|
1369
|
+
errnoRet: 1,
|
|
1370
|
+
args: [{ index: 0, value: 1, op: 'SCMP_CMP_NE' }],
|
|
1371
|
+
},
|
|
1372
|
+
]
|
|
1373
|
+
: []),
|
|
1374
|
+
],
|
|
1375
|
+
};
|
|
1376
|
+
const json = JSON.stringify(document);
|
|
1377
|
+
const digest = sha256Digest('loopwright.dev/sandbox-seccomp/v1', json);
|
|
1378
|
+
return Object.freeze({ json, digest });
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
* Compile deterministic Linux Bubblewrap (`bwrap`) command-line arguments and seccomp descriptor.
|
|
1382
|
+
*/
|
|
1383
|
+
export function compileLinuxBwrapCommand(policy, host, options) {
|
|
1384
|
+
const env = resolveHostEnvironment(host);
|
|
1385
|
+
const executablePath = env.bwrapExecutable ?? TRUSTED_BWRAP_PATHS[0];
|
|
1386
|
+
if (!TRUSTED_BWRAP_PATHS.includes(executablePath)) {
|
|
1387
|
+
throw new TaskpackError('SANDBOX_BACKEND_UNAVAILABLE', `untrusted Linux bwrap executable "${executablePath}"`, 'bwrapExecutable');
|
|
1388
|
+
}
|
|
1389
|
+
const normalized = normalizeSandboxPolicy(policy, env);
|
|
1390
|
+
const dynamicGlob = findDynamicProtectedGlobOverlap(normalized);
|
|
1391
|
+
if (dynamicGlob !== null) {
|
|
1392
|
+
throw new TaskpackError('SANDBOX_CAPABILITY_INSUFFICIENT', `linux-bwrap cannot enforce dynamic protected glob "${dynamicGlob}" inside writable directory`, 'protectedPaths');
|
|
1393
|
+
}
|
|
1394
|
+
if (options?.provisionExactFiles ?? env.probeExecutables) {
|
|
1395
|
+
provisionSandboxExactWritablePaths(normalized, { createTargetFile: true });
|
|
1396
|
+
}
|
|
1397
|
+
const targetCwd = options?.cwd === undefined
|
|
1398
|
+
? normalized.canonicalWorkspaceRoot
|
|
1399
|
+
: canonicalizeAbsolutePath(options.cwd, 'cwd');
|
|
1400
|
+
const usesDevShm = [
|
|
1401
|
+
normalized.canonicalWorkspaceRoot,
|
|
1402
|
+
...(normalized.canonicalScratchDirectory !== null ? [normalized.canonicalScratchDirectory] : []),
|
|
1403
|
+
targetCwd,
|
|
1404
|
+
...normalized.canonicalWritablePaths,
|
|
1405
|
+
...normalized.canonicalProtectedPaths,
|
|
1406
|
+
...normalized.canonicalAllowedReadOnlyPaths,
|
|
1407
|
+
...normalized.canonicalDeniedReadPaths,
|
|
1408
|
+
...normalized.canonicalReadOnlyBindMounts.flatMap(m => [m.sourcePath, m.targetPath]),
|
|
1409
|
+
].some(p => isSameOrSubpath(p, '/dev/shm'));
|
|
1410
|
+
const isolateDevShm = usesDevShm && !normalized.canonicalWritablePaths.includes('/dev/shm');
|
|
1411
|
+
const shmRoRoots = [];
|
|
1412
|
+
if (isolateDevShm) {
|
|
1413
|
+
if (isSameOrSubpath(normalized.canonicalWorkspaceRoot, '/dev/shm') && normalized.canonicalWorkspaceRoot !== '/dev/shm') {
|
|
1414
|
+
shmRoRoots.push(normalized.canonicalWorkspaceRoot);
|
|
1415
|
+
}
|
|
1416
|
+
if (isSameOrSubpath(targetCwd, '/dev/shm')
|
|
1417
|
+
&& targetCwd !== '/dev/shm'
|
|
1418
|
+
&& !shmRoRoots.some(r => isSameOrSubpath(targetCwd, r))
|
|
1419
|
+
&& !normalized.canonicalWritablePaths.some(w => isSameOrSubpath(targetCwd, w))) {
|
|
1420
|
+
shmRoRoots.push(targetCwd);
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
const args = ['--unshare-all'];
|
|
1424
|
+
if (normalized.networkMode === 'allow-outbound') {
|
|
1425
|
+
args.push('--share-net');
|
|
1426
|
+
}
|
|
1427
|
+
args.push('--die-with-parent', '--new-session', '--ro-bind', '/', '/', '--proc', '/proc', '--dev', '/dev');
|
|
1428
|
+
if (isolateDevShm) {
|
|
1429
|
+
// Isolate /dev/shm with an empty per-sandbox tmpfs instead of exposing host /dev/shm,
|
|
1430
|
+
// bind only the required workspace/policy subpaths, and remount /dev/shm read-only below.
|
|
1431
|
+
args.push('--tmpfs', '/dev/shm');
|
|
1432
|
+
}
|
|
1433
|
+
if (normalized.networkMode === 'none' && (!env.probeExecutables || existsSync('/etc/hosts'))) {
|
|
1434
|
+
args.push('--ro-bind-try', '/dev/null', '/etc/hosts');
|
|
1435
|
+
}
|
|
1436
|
+
const appendDeniedMask = (deniedPath) => {
|
|
1437
|
+
if (!env.probeExecutables) {
|
|
1438
|
+
args.push('--tmpfs', deniedPath, '--remount-ro', deniedPath);
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
1441
|
+
let st;
|
|
1442
|
+
try {
|
|
1443
|
+
st = existsSync(deniedPath) ? statSync(deniedPath) : null;
|
|
1444
|
+
}
|
|
1445
|
+
catch {
|
|
1446
|
+
st = null;
|
|
1447
|
+
}
|
|
1448
|
+
if (st === null) {
|
|
1449
|
+
return;
|
|
1450
|
+
}
|
|
1451
|
+
if (st.isDirectory()) {
|
|
1452
|
+
args.push('--tmpfs', deniedPath, '--remount-ro', deniedPath);
|
|
1453
|
+
}
|
|
1454
|
+
else {
|
|
1455
|
+
args.push('--ro-bind', '/dev/null', deniedPath);
|
|
1456
|
+
}
|
|
1457
|
+
};
|
|
1458
|
+
const allLaterMountTargets = [
|
|
1459
|
+
...shmRoRoots,
|
|
1460
|
+
...normalized.canonicalWritablePaths,
|
|
1461
|
+
...normalized.canonicalProtectedPaths,
|
|
1462
|
+
...normalized.canonicalAllowedReadOnlyPaths,
|
|
1463
|
+
...normalized.canonicalReadOnlyBindMounts.map(m => m.targetPath),
|
|
1464
|
+
];
|
|
1465
|
+
const postMountDeniedPaths = [];
|
|
1466
|
+
for (const deniedPath of normalized.canonicalDeniedReadPaths) {
|
|
1467
|
+
const reopenedByAllowedRo = normalized.canonicalAllowedReadOnlyPaths.some(ro => isSameOrSubpath(ro, deniedPath));
|
|
1468
|
+
if (!reopenedByAllowedRo && allLaterMountTargets.some(m => isSameOrSubpath(deniedPath, m))) {
|
|
1469
|
+
postMountDeniedPaths.push(deniedPath);
|
|
1470
|
+
continue;
|
|
1471
|
+
}
|
|
1472
|
+
appendDeniedMask(deniedPath);
|
|
1473
|
+
}
|
|
1474
|
+
for (const shmRoot of shmRoRoots) {
|
|
1475
|
+
if (!env.probeExecutables || existsSync(shmRoot)) {
|
|
1476
|
+
args.push('--ro-bind', shmRoot, shmRoot);
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
for (const writablePath of normalized.canonicalWritablePaths) {
|
|
1480
|
+
args.push('--bind', writablePath, writablePath);
|
|
1481
|
+
}
|
|
1482
|
+
for (const protectedPath of normalized.canonicalProtectedPaths) {
|
|
1483
|
+
args.push('--ro-bind-try', protectedPath, protectedPath);
|
|
1484
|
+
}
|
|
1485
|
+
for (const roPath of normalized.canonicalAllowedReadOnlyPaths) {
|
|
1486
|
+
args.push('--ro-bind-try', roPath, roPath);
|
|
1487
|
+
}
|
|
1488
|
+
for (const mount of normalized.canonicalReadOnlyBindMounts) {
|
|
1489
|
+
args.push('--ro-bind', mount.sourcePath, mount.targetPath);
|
|
1490
|
+
}
|
|
1491
|
+
for (const deniedPath of postMountDeniedPaths) {
|
|
1492
|
+
appendDeniedMask(deniedPath);
|
|
1493
|
+
}
|
|
1494
|
+
if (isolateDevShm) {
|
|
1495
|
+
args.push('--remount-ro', '/dev/shm');
|
|
1496
|
+
}
|
|
1497
|
+
if (options?.inheritSpawnEnv === true) {
|
|
1498
|
+
args.push('--chdir', targetCwd);
|
|
1499
|
+
const pinnedEnv = {
|
|
1500
|
+
GIT_CONFIG_GLOBAL: '/dev/null',
|
|
1501
|
+
GIT_CONFIG_NOSYSTEM: '1',
|
|
1502
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
1503
|
+
HOME: normalized.canonicalScratchDirectory ?? normalized.canonicalWorkspaceRoot,
|
|
1504
|
+
LANG: 'C.UTF-8',
|
|
1505
|
+
TERM: 'dumb',
|
|
1506
|
+
};
|
|
1507
|
+
for (const key of Object.keys(pinnedEnv).sort()) {
|
|
1508
|
+
args.push('--setenv', key, pinnedEnv[key]);
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
else {
|
|
1512
|
+
args.push('--chdir', targetCwd, '--clearenv');
|
|
1513
|
+
const safeEnv = {
|
|
1514
|
+
HOME: normalized.canonicalScratchDirectory ?? normalized.canonicalWorkspaceRoot,
|
|
1515
|
+
PATH: '/usr/local/bin:/usr/bin:/bin',
|
|
1516
|
+
LANG: 'C.UTF-8',
|
|
1517
|
+
TERM: 'dumb',
|
|
1518
|
+
...(options?.env ?? {}),
|
|
1519
|
+
GIT_CONFIG_NOSYSTEM: '1',
|
|
1520
|
+
GIT_CONFIG_GLOBAL: '/dev/null',
|
|
1521
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
1522
|
+
};
|
|
1523
|
+
for (const key of Object.keys(safeEnv).sort()) {
|
|
1524
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
|
|
1525
|
+
args.push('--setenv', key, safeEnv[key]);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
if (args.length > MAX_LINUX_BWRAP_ARGS) {
|
|
1530
|
+
throw new TaskpackError('SANDBOX_CAPABILITY_INSUFFICIENT', `compiled linux-bwrap policy requires ${args.length} arguments, exceeding max ${MAX_LINUX_BWRAP_ARGS}`, 'writablePaths');
|
|
1531
|
+
}
|
|
1532
|
+
const effectiveSeccomp = normalized.networkMode === 'none'
|
|
1533
|
+
? computeSandboxSeccompProfile({ blockIpSockets: true })
|
|
1534
|
+
: computeSandboxSeccompProfile();
|
|
1535
|
+
const profilePayload = JSON.stringify({
|
|
1536
|
+
executablePath,
|
|
1537
|
+
args,
|
|
1538
|
+
seccompDigest: effectiveSeccomp.digest.hex,
|
|
1539
|
+
networkMode: normalized.networkMode,
|
|
1540
|
+
});
|
|
1541
|
+
const profileDigest = sha256Digest('loopwright.dev/sandbox-bwrap/v1', profilePayload);
|
|
1542
|
+
return Object.freeze({
|
|
1543
|
+
backendId: 'linux-bwrap',
|
|
1544
|
+
executablePath,
|
|
1545
|
+
args: Object.freeze(args),
|
|
1546
|
+
seccompProfileJson: effectiveSeccomp.json,
|
|
1547
|
+
seccompDigest: effectiveSeccomp.digest,
|
|
1548
|
+
profileDigest,
|
|
1549
|
+
canonicalWorkspaceRoot: normalized.canonicalWorkspaceRoot,
|
|
1550
|
+
canonicalWritablePaths: normalized.canonicalWritablePaths,
|
|
1551
|
+
canonicalProtectedPaths: normalized.canonicalProtectedPaths,
|
|
1552
|
+
canonicalDeniedReadPaths: normalized.canonicalDeniedReadPaths,
|
|
1553
|
+
canonicalReadOnlyBindMounts: normalized.canonicalReadOnlyBindMounts,
|
|
1554
|
+
networkMode: normalized.networkMode,
|
|
1555
|
+
});
|
|
1556
|
+
}
|
|
1557
|
+
export const LANDLOCK_HOST_PROBE_SCRIPT = [
|
|
1558
|
+
'import ctypes, errno, os, socket, sys',
|
|
1559
|
+
'libc = ctypes.CDLL(None, use_errno=True)',
|
|
1560
|
+
'libc.prctl.restype = ctypes.c_int',
|
|
1561
|
+
'abi = libc.syscall(444, None, 0, 1)',
|
|
1562
|
+
'if abi < 3:',
|
|
1563
|
+
' sys.exit(1)',
|
|
1564
|
+
'seccomp_ok = 0',
|
|
1565
|
+
'machine = os.uname().machine',
|
|
1566
|
+
'if machine in ("x86_64", "amd64", "aarch64", "arm64") and libc.prctl(38, 1, 0, 0, 0) == 0:',
|
|
1567
|
+
' if machine in ("x86_64", "amd64"):',
|
|
1568
|
+
' audit_arch = 0xc000003e',
|
|
1569
|
+
' blocked_nrs = [90, 91, 92, 93, 94, 260, 268, 425, 426, 427, 452]',
|
|
1570
|
+
' sys_socket = 41',
|
|
1571
|
+
' block_x32 = True',
|
|
1572
|
+
' else:',
|
|
1573
|
+
' audit_arch = 0xc00000b7',
|
|
1574
|
+
' blocked_nrs = [52, 53, 54, 55, 425, 426, 427, 452]',
|
|
1575
|
+
' sys_socket = 198',
|
|
1576
|
+
' block_x32 = False',
|
|
1577
|
+
' class SockFilter(ctypes.Structure):',
|
|
1578
|
+
' _fields_ = [("code", ctypes.c_uint16), ("jt", ctypes.c_uint8), ("jf", ctypes.c_uint8), ("k", ctypes.c_uint32)]',
|
|
1579
|
+
' class SockFprog(ctypes.Structure):',
|
|
1580
|
+
' _fields_ = [("len", ctypes.c_uint16), ("filter", ctypes.POINTER(SockFilter))]',
|
|
1581
|
+
' n_blocked = len(blocked_nrs)',
|
|
1582
|
+
' raw_insns = [',
|
|
1583
|
+
' (0x20, 0, 0, 4), (0x15, 1, 0, audit_arch), (0x06, 0, 0, 0x00050001), (0x20, 0, 0, 0),',
|
|
1584
|
+
' ]',
|
|
1585
|
+
' if block_x32:',
|
|
1586
|
+
' raw_insns.append((0x35, n_blocked + 4, 0, 0x40000000))',
|
|
1587
|
+
' for idx_nr, nr in enumerate(blocked_nrs):',
|
|
1588
|
+
' raw_insns.append((0x15, (n_blocked - idx_nr) + 3, 0, nr))',
|
|
1589
|
+
' raw_insns.extend([',
|
|
1590
|
+
' (0x15, 0, 2, sys_socket), (0x20, 0, 0, 16), (0x15, 0, 1, 1),',
|
|
1591
|
+
' (0x06, 0, 0, 0x7fff0000), (0x06, 0, 0, 0x00050001),',
|
|
1592
|
+
' ])',
|
|
1593
|
+
' insns = (SockFilter * len(raw_insns))(*(SockFilter(*ins) for ins in raw_insns))',
|
|
1594
|
+
' prog = SockFprog(len(raw_insns), insns)',
|
|
1595
|
+
' if libc.prctl(22, 2, ctypes.byref(prog), 0, 0) == 0:',
|
|
1596
|
+
' try:',
|
|
1597
|
+
' us = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)',
|
|
1598
|
+
' us.close()',
|
|
1599
|
+
' chmod_blocked = False',
|
|
1600
|
+
' try:',
|
|
1601
|
+
' os.chmod("/", 0o755)',
|
|
1602
|
+
' except OSError as exc:',
|
|
1603
|
+
' chmod_blocked = (exc.errno == errno.EPERM)',
|
|
1604
|
+
' sock_blocked = False',
|
|
1605
|
+
' try:',
|
|
1606
|
+
' s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)',
|
|
1607
|
+
' s.close()',
|
|
1608
|
+
' except OSError as exc:',
|
|
1609
|
+
' sock_blocked = (exc.errno == errno.EPERM)',
|
|
1610
|
+
' ctypes.set_errno(0)',
|
|
1611
|
+
' uring_blocked = (libc.syscall(425, 1, 0) == -1 and ctypes.get_errno() == errno.EPERM)',
|
|
1612
|
+
' if chmod_blocked and sock_blocked and uring_blocked:',
|
|
1613
|
+
' seccomp_ok = 1',
|
|
1614
|
+
' except OSError:',
|
|
1615
|
+
' pass',
|
|
1616
|
+
'sys.stdout.write(f"{abi}:{seccomp_ok}")',
|
|
1617
|
+
].join('\n');
|
|
1618
|
+
const cachedLandlockProbesByExecutable = new Map();
|
|
1619
|
+
function probeLinuxLandlockExecutable(executable) {
|
|
1620
|
+
if (cachedLandlockProbesByExecutable.has(executable)) {
|
|
1621
|
+
return cachedLandlockProbesByExecutable.get(executable) ?? null;
|
|
1622
|
+
}
|
|
1623
|
+
const probe = spawnSync(executable, ['-I', '-S', '-B', '-c', LANDLOCK_HOST_PROBE_SCRIPT], { cwd: '/', encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 3_000 });
|
|
1624
|
+
if (probe.status === 0 && probe.error === undefined) {
|
|
1625
|
+
const parts = (probe.stdout ?? '').trim().split(':');
|
|
1626
|
+
const abi = Number.parseInt(parts[0] ?? '', 10);
|
|
1627
|
+
const seccompAvailable = parts[1] === '1';
|
|
1628
|
+
if (Number.isSafeInteger(abi) && abi >= 3 && seccompAvailable) {
|
|
1629
|
+
const info = Object.freeze({ abi, seccompAvailable });
|
|
1630
|
+
cachedLandlockProbesByExecutable.set(executable, info);
|
|
1631
|
+
return info;
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
cachedLandlockProbesByExecutable.set(executable, null);
|
|
1635
|
+
return null;
|
|
1636
|
+
}
|
|
1637
|
+
function defaultPreferredBackends(platform) {
|
|
1638
|
+
if (platform === 'darwin')
|
|
1639
|
+
return ['macos-seatbelt', 'docker'];
|
|
1640
|
+
if (platform === 'linux')
|
|
1641
|
+
return ['linux-bwrap', 'linux-landlock', 'docker'];
|
|
1642
|
+
return [];
|
|
1643
|
+
}
|
|
1644
|
+
/**
|
|
1645
|
+
* Fail-closed sandbox backend negotiation. Never silently downgrades to unsandboxed execution.
|
|
1646
|
+
*/
|
|
1647
|
+
export function negotiateSandboxBackend(policy, host) {
|
|
1648
|
+
const env = resolveHostEnvironment(host);
|
|
1649
|
+
const normalized = normalizeSandboxPolicy(policy, env);
|
|
1650
|
+
const requiredCapabilities = policy.requiredCapabilities !== undefined
|
|
1651
|
+
? policy.requiredCapabilities
|
|
1652
|
+
: DEFAULT_REQUIRED_SANDBOX_CAPABILITIES;
|
|
1653
|
+
for (const cap of requiredCapabilities) {
|
|
1654
|
+
if (cap !== 'filesystemReadContainment' &&
|
|
1655
|
+
cap !== 'filesystemWriteContainment' &&
|
|
1656
|
+
cap !== 'protectedPathReadOnlyMask' &&
|
|
1657
|
+
cap !== 'networkIsolation' &&
|
|
1658
|
+
cap !== 'processTreeCleanup' &&
|
|
1659
|
+
cap !== 'syscallFiltering') {
|
|
1660
|
+
policyInvalid(`unknown required capability "${String(cap)}"`, 'requiredCapabilities');
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
const preferredBackends = policy.preferredBackends !== undefined
|
|
1664
|
+
? policy.preferredBackends
|
|
1665
|
+
: defaultPreferredBackends(env.platform);
|
|
1666
|
+
if (!Array.isArray(preferredBackends) || preferredBackends.length === 0) {
|
|
1667
|
+
throw new TaskpackError('SANDBOX_BACKEND_UNAVAILABLE', `no sandbox backends are available for platform "${env.platform}"`, 'preferredBackends');
|
|
1668
|
+
}
|
|
1669
|
+
let capabilityFailure = null;
|
|
1670
|
+
let availabilityFailure = null;
|
|
1671
|
+
for (const backendId of preferredBackends) {
|
|
1672
|
+
if (!Object.hasOwn(SANDBOX_CAPABILITIES_BY_BACKEND, backendId)) {
|
|
1673
|
+
policyInvalid(`unknown sandbox backend "${String(backendId)}"`, 'preferredBackends');
|
|
1674
|
+
}
|
|
1675
|
+
if (backendId === 'macos-seatbelt') {
|
|
1676
|
+
if (env.platform !== 'darwin') {
|
|
1677
|
+
availabilityFailure ??= 'macos-seatbelt requires platform darwin';
|
|
1678
|
+
continue;
|
|
1679
|
+
}
|
|
1680
|
+
const executable = validateExecutableChoice(env.seatbeltExecutable, TRUSTED_SEATBELT_PATHS, env.probeExecutables);
|
|
1681
|
+
if (executable === null) {
|
|
1682
|
+
availabilityFailure ??= `macos-seatbelt binary is missing or untrusted (${env.seatbeltExecutable ?? TRUSTED_SEATBELT_PATHS[0]})`;
|
|
1683
|
+
continue;
|
|
1684
|
+
}
|
|
1685
|
+
const supported = SANDBOX_CAPABILITIES_BY_BACKEND['macos-seatbelt'];
|
|
1686
|
+
const missing = requiredCapabilities.filter(req => !supported.includes(req));
|
|
1687
|
+
if (missing.length > 0) {
|
|
1688
|
+
capabilityFailure ??= `macos-seatbelt lacks required capabilities: ${missing.join(', ')}`;
|
|
1689
|
+
continue;
|
|
1690
|
+
}
|
|
1691
|
+
const compiled = compileMacosSeatbeltProfile(policy, { ...env, seatbeltExecutable: executable });
|
|
1692
|
+
return Object.freeze({
|
|
1693
|
+
backendId: 'macos-seatbelt',
|
|
1694
|
+
executablePath: executable,
|
|
1695
|
+
capabilities: supported,
|
|
1696
|
+
networkMode: normalized.networkMode,
|
|
1697
|
+
profileDigest: compiled.profileDigest,
|
|
1698
|
+
});
|
|
1699
|
+
}
|
|
1700
|
+
if (backendId === 'linux-bwrap') {
|
|
1701
|
+
if (env.platform !== 'linux') {
|
|
1702
|
+
availabilityFailure ??= 'linux-bwrap requires platform linux';
|
|
1703
|
+
continue;
|
|
1704
|
+
}
|
|
1705
|
+
if (env.arch !== 'x64' && env.arch !== 'arm64') {
|
|
1706
|
+
if (requiredCapabilities.includes('syscallFiltering')) {
|
|
1707
|
+
capabilityFailure ??= `linux-bwrap syscallFiltering is unsupported on architecture "${env.arch}"`;
|
|
1708
|
+
}
|
|
1709
|
+
else {
|
|
1710
|
+
availabilityFailure ??= `linux-bwrap seccomp filter compiler does not support architecture "${env.arch}"`;
|
|
1711
|
+
}
|
|
1712
|
+
continue;
|
|
1713
|
+
}
|
|
1714
|
+
const executable = validateExecutableChoice(env.bwrapExecutable, TRUSTED_BWRAP_PATHS, env.probeExecutables);
|
|
1715
|
+
if (executable === null) {
|
|
1716
|
+
availabilityFailure ??= `linux-bwrap binary is missing or untrusted (${env.bwrapExecutable ?? TRUSTED_BWRAP_PATHS[0]})`;
|
|
1717
|
+
continue;
|
|
1718
|
+
}
|
|
1719
|
+
if (env.probeExecutables && process.platform === 'linux') {
|
|
1720
|
+
const probe = spawnSync(executable, ['--unshare-all', '--ro-bind', '/', '/', '/bin/true'], {
|
|
1721
|
+
timeout: 2000,
|
|
1722
|
+
stdio: 'ignore',
|
|
1723
|
+
});
|
|
1724
|
+
if (probe.status !== 0) {
|
|
1725
|
+
availabilityFailure ??= 'linux-bwrap runtime namespace creation is blocked on this host';
|
|
1726
|
+
continue;
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
const supported = SANDBOX_CAPABILITIES_BY_BACKEND['linux-bwrap'];
|
|
1730
|
+
const missing = requiredCapabilities.filter(req => !supported.includes(req));
|
|
1731
|
+
if (missing.length > 0) {
|
|
1732
|
+
capabilityFailure ??= `linux-bwrap lacks required capabilities: ${missing.join(', ')}`;
|
|
1733
|
+
continue;
|
|
1734
|
+
}
|
|
1735
|
+
if (requiredCapabilities.includes('protectedPathReadOnlyMask') || (policy.protectedPaths?.length ?? 0) > 0) {
|
|
1736
|
+
const dynamicGlob = findDynamicProtectedGlobOverlap(normalized);
|
|
1737
|
+
if (dynamicGlob !== null) {
|
|
1738
|
+
capabilityFailure ??= `linux-bwrap cannot enforce dynamic protected glob "${dynamicGlob}" inside writable directory`;
|
|
1739
|
+
continue;
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
let compiled;
|
|
1743
|
+
try {
|
|
1744
|
+
compiled = compileLinuxBwrapCommand(policy, { ...env, bwrapExecutable: executable }, { provisionExactFiles: false });
|
|
1745
|
+
}
|
|
1746
|
+
catch (err) {
|
|
1747
|
+
if (err instanceof TaskpackError && err.code === 'SANDBOX_CAPABILITY_INSUFFICIENT') {
|
|
1748
|
+
capabilityFailure ??= err.message;
|
|
1749
|
+
continue;
|
|
1750
|
+
}
|
|
1751
|
+
throw err;
|
|
1752
|
+
}
|
|
1753
|
+
return Object.freeze({
|
|
1754
|
+
backendId: 'linux-bwrap',
|
|
1755
|
+
executablePath: executable,
|
|
1756
|
+
capabilities: supported,
|
|
1757
|
+
networkMode: normalized.networkMode,
|
|
1758
|
+
profileDigest: compiled.profileDigest,
|
|
1759
|
+
});
|
|
1760
|
+
}
|
|
1761
|
+
if (backendId === 'linux-landlock') {
|
|
1762
|
+
if (env.platform !== 'linux') {
|
|
1763
|
+
availabilityFailure ??= 'linux-landlock requires platform linux';
|
|
1764
|
+
continue;
|
|
1765
|
+
}
|
|
1766
|
+
if (env.arch !== 'x64' && env.arch !== 'arm64') {
|
|
1767
|
+
availabilityFailure ??= `linux-landlock seccomp filter does not support architecture "${env.arch}"`;
|
|
1768
|
+
continue;
|
|
1769
|
+
}
|
|
1770
|
+
const supported = SANDBOX_CAPABILITIES_BY_BACKEND['linux-landlock'];
|
|
1771
|
+
const missing = requiredCapabilities.filter(req => !supported.includes(req));
|
|
1772
|
+
if (missing.length > 0) {
|
|
1773
|
+
capabilityFailure ??= `linux-landlock lacks required capabilities: ${missing.join(', ')}`;
|
|
1774
|
+
continue;
|
|
1775
|
+
}
|
|
1776
|
+
if (normalized.networkMode === 'loopback-only'
|
|
1777
|
+
&& (requiredCapabilities.includes('networkIsolation') || policy.networkMode === 'loopback-only')) {
|
|
1778
|
+
capabilityFailure ??= 'linux-landlock cannot enforce loopback-only network isolation without network namespaces';
|
|
1779
|
+
continue;
|
|
1780
|
+
}
|
|
1781
|
+
if (requiredCapabilities.includes('protectedPathReadOnlyMask')
|
|
1782
|
+
|| requiredCapabilities.includes('filesystemReadContainment')
|
|
1783
|
+
|| (policy.protectedPaths?.length ?? 0) > 0
|
|
1784
|
+
|| (policy.deniedReadPaths?.length ?? 0) > 0) {
|
|
1785
|
+
const overlap = findLandlockWritableOverlap(normalized);
|
|
1786
|
+
if (overlap !== null) {
|
|
1787
|
+
capabilityFailure ??= `linux-landlock cannot enforce nested exclusion inside writable directory (${overlap})`;
|
|
1788
|
+
continue;
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
const executable = validateExecutableChoice(env.pythonExecutable, TRUSTED_PYTHON_PATHS, env.probeExecutables);
|
|
1792
|
+
if (executable === null) {
|
|
1793
|
+
availabilityFailure ??= `linux-landlock helper binary is missing or untrusted (${env.pythonExecutable ?? TRUSTED_PYTHON_PATHS[0]})`;
|
|
1794
|
+
continue;
|
|
1795
|
+
}
|
|
1796
|
+
if (env.probeExecutables && process.platform === 'linux') {
|
|
1797
|
+
const probed = probeLinuxLandlockExecutable(executable);
|
|
1798
|
+
if (probed === null || probed.abi < 3 || !probed.seccompAvailable) {
|
|
1799
|
+
availabilityFailure ??= 'linux-landlock requires Linux kernel Landlock ABI >= 3 and seccomp filter support';
|
|
1800
|
+
continue;
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
const profileDigest = sha256Digest('loopwright.dev/sandbox-landlock/v1', JSON.stringify({
|
|
1804
|
+
executable,
|
|
1805
|
+
workspaceRoot: normalized.canonicalWorkspaceRoot,
|
|
1806
|
+
writablePaths: normalized.canonicalWritablePaths,
|
|
1807
|
+
protectedPaths: normalized.canonicalProtectedPaths,
|
|
1808
|
+
deniedReadPaths: normalized.canonicalDeniedReadPaths,
|
|
1809
|
+
...(normalized.canonicalAllowedReadOnlyPaths.length > 0
|
|
1810
|
+
? { allowedReadOnlyPaths: normalized.canonicalAllowedReadOnlyPaths }
|
|
1811
|
+
: {}),
|
|
1812
|
+
networkMode: normalized.networkMode,
|
|
1813
|
+
}));
|
|
1814
|
+
return Object.freeze({
|
|
1815
|
+
backendId: 'linux-landlock',
|
|
1816
|
+
executablePath: executable,
|
|
1817
|
+
capabilities: supported,
|
|
1818
|
+
networkMode: normalized.networkMode,
|
|
1819
|
+
profileDigest,
|
|
1820
|
+
});
|
|
1821
|
+
}
|
|
1822
|
+
if (backendId === 'docker') {
|
|
1823
|
+
const executable = validateExecutableChoice(env.dockerExecutable, TRUSTED_DOCKER_PATHS, env.probeExecutables);
|
|
1824
|
+
const socketPath = env.dockerSocket ?? '/var/run/docker.sock';
|
|
1825
|
+
const socketAvailable = !env.probeExecutables || existsSync(socketPath);
|
|
1826
|
+
if (executable === null || !socketAvailable) {
|
|
1827
|
+
availabilityFailure ??= 'docker executable or socket is unavailable on this host';
|
|
1828
|
+
continue;
|
|
1829
|
+
}
|
|
1830
|
+
const supported = SANDBOX_CAPABILITIES_BY_BACKEND['docker'];
|
|
1831
|
+
const missing = requiredCapabilities.filter(req => !supported.includes(req));
|
|
1832
|
+
if (missing.length > 0) {
|
|
1833
|
+
capabilityFailure ??= `docker lacks required capabilities: ${missing.join(', ')}`;
|
|
1834
|
+
continue;
|
|
1835
|
+
}
|
|
1836
|
+
const profileDigest = sha256Digest('loopwright.dev/sandbox-docker/v1', JSON.stringify({
|
|
1837
|
+
executable,
|
|
1838
|
+
socketPath,
|
|
1839
|
+
workspaceRoot: normalized.canonicalWorkspaceRoot,
|
|
1840
|
+
writablePaths: normalized.canonicalWritablePaths,
|
|
1841
|
+
protectedPaths: normalized.canonicalProtectedPaths,
|
|
1842
|
+
...(normalized.canonicalReadOnlyBindMounts.length > 0
|
|
1843
|
+
? { readOnlyBindMounts: normalized.canonicalReadOnlyBindMounts }
|
|
1844
|
+
: {}),
|
|
1845
|
+
networkMode: normalized.networkMode,
|
|
1846
|
+
}));
|
|
1847
|
+
return Object.freeze({
|
|
1848
|
+
backendId: 'docker',
|
|
1849
|
+
executablePath: executable,
|
|
1850
|
+
capabilities: supported,
|
|
1851
|
+
networkMode: normalized.networkMode,
|
|
1852
|
+
profileDigest,
|
|
1853
|
+
});
|
|
1854
|
+
}
|
|
1855
|
+
if (backendId === 'direct-dedicated') {
|
|
1856
|
+
const supported = SANDBOX_CAPABILITIES_BY_BACKEND['direct-dedicated'];
|
|
1857
|
+
const missing = requiredCapabilities.filter(req => !supported.includes(req));
|
|
1858
|
+
if (missing.length > 0 && policy.allowDedicatedDirectOverride !== true) {
|
|
1859
|
+
capabilityFailure ??= `direct-dedicated backend lacks required isolation capabilities (${missing.join(', ')}) and allowDedicatedDirectOverride is not enabled`;
|
|
1860
|
+
continue;
|
|
1861
|
+
}
|
|
1862
|
+
const profileDigest = sha256Digest('loopwright.dev/sandbox-direct/v1', JSON.stringify({ workspaceRoot: normalized.canonicalWorkspaceRoot, networkMode: normalized.networkMode }));
|
|
1863
|
+
return Object.freeze({
|
|
1864
|
+
backendId: 'direct-dedicated',
|
|
1865
|
+
executablePath: null,
|
|
1866
|
+
capabilities: supported,
|
|
1867
|
+
networkMode: normalized.networkMode,
|
|
1868
|
+
profileDigest,
|
|
1869
|
+
});
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
if (capabilityFailure !== null) {
|
|
1873
|
+
throw new TaskpackError('SANDBOX_CAPABILITY_INSUFFICIENT', capabilityFailure, 'requiredCapabilities');
|
|
1874
|
+
}
|
|
1875
|
+
throw new TaskpackError('SANDBOX_BACKEND_UNAVAILABLE', availabilityFailure ?? `no compatible sandbox backend available for platform "${env.platform}"`, 'preferredBackends');
|
|
1876
|
+
}
|
|
1877
|
+
export const LANDLOCK_BOOTSTRAP_SCRIPT = `import ctypes, errno, json, os, signal, stat, sys
|
|
1878
|
+
|
|
1879
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
1880
|
+
libc.prctl.restype = ctypes.c_int
|
|
1881
|
+
PR_SET_PDEATHSIG = 1
|
|
1882
|
+
PR_SET_SECCOMP = 22
|
|
1883
|
+
PR_SET_NO_NEW_PRIVS = 38
|
|
1884
|
+
SECCOMP_MODE_FILTER = 2
|
|
1885
|
+
SYS_landlock_create_ruleset = 444
|
|
1886
|
+
SYS_landlock_add_rule = 445
|
|
1887
|
+
SYS_landlock_restrict_self = 446
|
|
1888
|
+
LANDLOCK_CREATE_RULESET_VERSION = 1 << 0
|
|
1889
|
+
LANDLOCK_RULE_PATH_BENEATH = 1
|
|
1890
|
+
|
|
1891
|
+
class RulesetAttr(ctypes.Structure):
|
|
1892
|
+
_fields_ = [("handled_access_fs", ctypes.c_uint64), ("handled_access_net", ctypes.c_uint64)]
|
|
1893
|
+
|
|
1894
|
+
class PathBeneathAttr(ctypes.Structure):
|
|
1895
|
+
_pack_ = 1
|
|
1896
|
+
_fields_ = [("allowed_access", ctypes.c_uint64), ("parent_fd", ctypes.c_int32)]
|
|
1897
|
+
|
|
1898
|
+
class SockFilter(ctypes.Structure):
|
|
1899
|
+
_fields_ = [
|
|
1900
|
+
("code", ctypes.c_uint16),
|
|
1901
|
+
("jt", ctypes.c_uint8),
|
|
1902
|
+
("jf", ctypes.c_uint8),
|
|
1903
|
+
("k", ctypes.c_uint32),
|
|
1904
|
+
]
|
|
1905
|
+
|
|
1906
|
+
class SockFprog(ctypes.Structure):
|
|
1907
|
+
_fields_ = [
|
|
1908
|
+
("len", ctypes.c_uint16),
|
|
1909
|
+
("filter", ctypes.POINTER(SockFilter)),
|
|
1910
|
+
]
|
|
1911
|
+
|
|
1912
|
+
cfg = json.loads(sys.argv[1])
|
|
1913
|
+
cmd = sys.argv[2]
|
|
1914
|
+
args = sys.argv[3:]
|
|
1915
|
+
|
|
1916
|
+
libc.prctl(PR_SET_PDEATHSIG, signal.SIGKILL, 0, 0, 0)
|
|
1917
|
+
if libc.prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
|
|
1918
|
+
sys.exit(126)
|
|
1919
|
+
|
|
1920
|
+
abi = libc.syscall(SYS_landlock_create_ruleset, None, 0, LANDLOCK_CREATE_RULESET_VERSION)
|
|
1921
|
+
if abi < 3:
|
|
1922
|
+
sys.exit(126)
|
|
1923
|
+
|
|
1924
|
+
FS_EXECUTE = 1 << 0
|
|
1925
|
+
FS_WRITE_FILE = 1 << 1
|
|
1926
|
+
FS_READ_FILE = 1 << 2
|
|
1927
|
+
FS_READ_DIR = 1 << 3
|
|
1928
|
+
FS_REMOVE_DIR = 1 << 4
|
|
1929
|
+
FS_REMOVE_FILE = 1 << 5
|
|
1930
|
+
FS_MAKE_CHAR = 1 << 6
|
|
1931
|
+
FS_MAKE_DIR = 1 << 7
|
|
1932
|
+
FS_MAKE_REG = 1 << 8
|
|
1933
|
+
FS_MAKE_SOCK = 1 << 9
|
|
1934
|
+
FS_MAKE_FIFO = 1 << 10
|
|
1935
|
+
FS_MAKE_BLOCK = 1 << 11
|
|
1936
|
+
FS_MAKE_SYM = 1 << 12
|
|
1937
|
+
FS_REFER = 1 << 13 if abi >= 2 else 0
|
|
1938
|
+
FS_TRUNCATE = 1 << 14 if abi >= 3 else 0
|
|
1939
|
+
|
|
1940
|
+
READ_ACCESS = FS_EXECUTE | FS_READ_FILE | FS_READ_DIR
|
|
1941
|
+
WRITE_FILE_ACCESS = FS_WRITE_FILE | FS_TRUNCATE
|
|
1942
|
+
WRITE_DIR_ACCESS = (
|
|
1943
|
+
FS_WRITE_FILE | FS_REMOVE_DIR | FS_REMOVE_FILE | FS_MAKE_CHAR |
|
|
1944
|
+
FS_MAKE_DIR | FS_MAKE_REG | FS_MAKE_SOCK | FS_MAKE_FIFO |
|
|
1945
|
+
FS_MAKE_BLOCK | FS_MAKE_SYM | FS_REFER | FS_TRUNCATE
|
|
1946
|
+
)
|
|
1947
|
+
HANDLED_FS = READ_ACCESS | WRITE_DIR_ACCESS
|
|
1948
|
+
HANDLED_NET = ((1 << 0) | (1 << 1)) if (abi >= 4 and cfg.get("networkMode") == "none") else 0
|
|
1949
|
+
|
|
1950
|
+
attr = RulesetAttr(HANDLED_FS, HANDLED_NET)
|
|
1951
|
+
ruleset_fd = libc.syscall(SYS_landlock_create_ruleset, ctypes.byref(attr), ctypes.sizeof(attr), 0)
|
|
1952
|
+
if ruleset_fd < 0:
|
|
1953
|
+
sys.exit(126)
|
|
1954
|
+
|
|
1955
|
+
O_PATH = getattr(os, "O_PATH", 0o10000000)
|
|
1956
|
+
O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0o400000)
|
|
1957
|
+
O_DIRECTORY = getattr(os, "O_DIRECTORY", 0o200000)
|
|
1958
|
+
|
|
1959
|
+
def open_nofollow_abs(abs_path, leaf_flags, fail_on_symlink_ancestor=False):
|
|
1960
|
+
if not isinstance(abs_path, str) or not abs_path.startswith("/"):
|
|
1961
|
+
if fail_on_symlink_ancestor:
|
|
1962
|
+
sys.exit(126)
|
|
1963
|
+
raise OSError(errno.EINVAL, "invalid path")
|
|
1964
|
+
if abs_path == "/":
|
|
1965
|
+
return os.open("/", leaf_flags | O_NOFOLLOW | os.O_CLOEXEC)
|
|
1966
|
+
parts = [p for p in abs_path.split("/") if p]
|
|
1967
|
+
cur_fd = os.open("/", os.O_RDONLY | O_NOFOLLOW | O_DIRECTORY | os.O_CLOEXEC)
|
|
1968
|
+
try:
|
|
1969
|
+
for part in parts[:-1]:
|
|
1970
|
+
try:
|
|
1971
|
+
nxt_fd = os.open(part, os.O_RDONLY | O_NOFOLLOW | O_DIRECTORY | os.O_CLOEXEC, dir_fd=cur_fd)
|
|
1972
|
+
except OSError as exc:
|
|
1973
|
+
if fail_on_symlink_ancestor and exc.errno != errno.ENOENT:
|
|
1974
|
+
sys.exit(126)
|
|
1975
|
+
raise
|
|
1976
|
+
os.close(cur_fd)
|
|
1977
|
+
cur_fd = nxt_fd
|
|
1978
|
+
try:
|
|
1979
|
+
return os.open(parts[-1], leaf_flags | O_NOFOLLOW | os.O_CLOEXEC, dir_fd=cur_fd)
|
|
1980
|
+
except OSError as exc:
|
|
1981
|
+
if fail_on_symlink_ancestor and exc.errno != errno.ENOENT:
|
|
1982
|
+
sys.exit(126)
|
|
1983
|
+
raise
|
|
1984
|
+
finally:
|
|
1985
|
+
os.close(cur_fd)
|
|
1986
|
+
|
|
1987
|
+
def add_fd_rule(fd, is_dir, access):
|
|
1988
|
+
actual = access if is_dir else (access & (FS_EXECUTE | FS_READ_FILE | WRITE_FILE_ACCESS))
|
|
1989
|
+
if actual == 0:
|
|
1990
|
+
return True
|
|
1991
|
+
rule = PathBeneathAttr(actual, fd)
|
|
1992
|
+
return libc.syscall(SYS_landlock_add_rule, ruleset_fd, LANDLOCK_RULE_PATH_BENEATH, ctypes.byref(rule), 0) == 0
|
|
1993
|
+
|
|
1994
|
+
def add_path_rule(path, access, dir_fd=None):
|
|
1995
|
+
try:
|
|
1996
|
+
if dir_fd is not None:
|
|
1997
|
+
fd = os.open(path, O_PATH | O_NOFOLLOW | os.O_CLOEXEC, dir_fd=dir_fd)
|
|
1998
|
+
else:
|
|
1999
|
+
fd = open_nofollow_abs(path, O_PATH, False)
|
|
2000
|
+
except OSError:
|
|
2001
|
+
return
|
|
2002
|
+
try:
|
|
2003
|
+
st = os.fstat(fd)
|
|
2004
|
+
if stat.S_ISLNK(st.st_mode):
|
|
2005
|
+
return
|
|
2006
|
+
add_fd_rule(fd, stat.S_ISDIR(st.st_mode), access)
|
|
2007
|
+
finally:
|
|
2008
|
+
os.close(fd)
|
|
2009
|
+
|
|
2010
|
+
def is_same_or_child(candidate, parent):
|
|
2011
|
+
if parent == "/":
|
|
2012
|
+
return True
|
|
2013
|
+
return candidate == parent or candidate.startswith(parent + "/")
|
|
2014
|
+
|
|
2015
|
+
def grant_tree(current, excluded_set, access, parent_dir_fd=None, rel_name=None):
|
|
2016
|
+
if current in excluded_set:
|
|
2017
|
+
return
|
|
2018
|
+
target = rel_name if parent_dir_fd is not None else current
|
|
2019
|
+
needs_split = any(ex != current and is_same_or_child(ex, current) for ex in excluded_set)
|
|
2020
|
+
if not needs_split:
|
|
2021
|
+
add_path_rule(target, access, dir_fd=parent_dir_fd)
|
|
2022
|
+
return
|
|
2023
|
+
try:
|
|
2024
|
+
if parent_dir_fd is not None:
|
|
2025
|
+
dir_fd = os.open(target, os.O_RDONLY | O_NOFOLLOW | O_DIRECTORY | os.O_CLOEXEC, dir_fd=parent_dir_fd)
|
|
2026
|
+
else:
|
|
2027
|
+
dir_fd = open_nofollow_abs(current, os.O_RDONLY | O_DIRECTORY, False)
|
|
2028
|
+
except OSError as exc:
|
|
2029
|
+
if exc.errno == errno.ENOTDIR:
|
|
2030
|
+
add_path_rule(target, access, dir_fd=parent_dir_fd)
|
|
2031
|
+
return
|
|
2032
|
+
try:
|
|
2033
|
+
st = os.fstat(dir_fd)
|
|
2034
|
+
if not stat.S_ISDIR(st.st_mode):
|
|
2035
|
+
return
|
|
2036
|
+
entries = sorted(os.listdir(dir_fd))
|
|
2037
|
+
for name in entries:
|
|
2038
|
+
if name in (".", ".."):
|
|
2039
|
+
continue
|
|
2040
|
+
child = "/" + name if current == "/" else current + "/" + name
|
|
2041
|
+
grant_tree(child, excluded_set, access, parent_dir_fd=dir_fd, rel_name=name)
|
|
2042
|
+
finally:
|
|
2043
|
+
os.close(dir_fd)
|
|
2044
|
+
|
|
2045
|
+
raw_denied_reads = set(cfg.get("deniedReadPaths", []))
|
|
2046
|
+
denied_reads = {p for p in raw_denied_reads if os.path.lexists(p)}
|
|
2047
|
+
protected_writes = set(cfg.get("protectedPaths", [])) | raw_denied_reads
|
|
2048
|
+
writable_paths = cfg.get("writablePaths", [])
|
|
2049
|
+
exact_writable_files = set(cfg.get("exactWritableFiles", []))
|
|
2050
|
+
positive_read_roots = cfg.get("positiveReadRoots")
|
|
2051
|
+
allowed_ro_paths = cfg.get("allowedReadOnlyPaths", [])
|
|
2052
|
+
|
|
2053
|
+
if isinstance(positive_read_roots, list):
|
|
2054
|
+
ro_excluded = denied_reads - set(allowed_ro_paths)
|
|
2055
|
+
for root_path in positive_read_roots:
|
|
2056
|
+
grant_tree(root_path, ro_excluded, READ_ACCESS)
|
|
2057
|
+
for ro_path in allowed_ro_paths:
|
|
2058
|
+
grant_tree(ro_path, ro_excluded, READ_ACCESS)
|
|
2059
|
+
else:
|
|
2060
|
+
grant_tree("/", denied_reads, READ_ACCESS)
|
|
2061
|
+
for ro_path in allowed_ro_paths:
|
|
2062
|
+
add_path_rule(ro_path, READ_ACCESS)
|
|
2063
|
+
for dev in ("/dev/null", "/dev/zero"):
|
|
2064
|
+
add_path_rule(dev, READ_ACCESS | WRITE_FILE_ACCESS)
|
|
2065
|
+
for wp in writable_paths:
|
|
2066
|
+
if any(is_same_or_child(ex, wp) for ex in protected_writes):
|
|
2067
|
+
sys.exit(126)
|
|
2068
|
+
if wp in exact_writable_files:
|
|
2069
|
+
try:
|
|
2070
|
+
wp_fd = open_nofollow_abs(wp, O_PATH, True)
|
|
2071
|
+
except OSError:
|
|
2072
|
+
sys.exit(126)
|
|
2073
|
+
try:
|
|
2074
|
+
wp_st = os.fstat(wp_fd)
|
|
2075
|
+
if stat.S_ISLNK(wp_st.st_mode) or not stat.S_ISREG(wp_st.st_mode) or wp_st.st_nlink != 1:
|
|
2076
|
+
sys.exit(126)
|
|
2077
|
+
if not add_fd_rule(wp_fd, False, READ_ACCESS | WRITE_FILE_ACCESS):
|
|
2078
|
+
sys.exit(126)
|
|
2079
|
+
finally:
|
|
2080
|
+
os.close(wp_fd)
|
|
2081
|
+
else:
|
|
2082
|
+
try:
|
|
2083
|
+
wp_fd = open_nofollow_abs(wp, O_PATH, True)
|
|
2084
|
+
except OSError as exc:
|
|
2085
|
+
if exc.errno == errno.ENOENT:
|
|
2086
|
+
continue
|
|
2087
|
+
sys.exit(126)
|
|
2088
|
+
try:
|
|
2089
|
+
wp_st = os.fstat(wp_fd)
|
|
2090
|
+
if stat.S_ISLNK(wp_st.st_mode):
|
|
2091
|
+
sys.exit(126)
|
|
2092
|
+
if stat.S_ISDIR(wp_st.st_mode):
|
|
2093
|
+
if not add_fd_rule(wp_fd, True, READ_ACCESS | WRITE_DIR_ACCESS):
|
|
2094
|
+
sys.exit(126)
|
|
2095
|
+
elif stat.S_ISREG(wp_st.st_mode) and wp_st.st_nlink == 1:
|
|
2096
|
+
if not add_fd_rule(wp_fd, False, READ_ACCESS | WRITE_FILE_ACCESS):
|
|
2097
|
+
sys.exit(126)
|
|
2098
|
+
else:
|
|
2099
|
+
sys.exit(126)
|
|
2100
|
+
finally:
|
|
2101
|
+
os.close(wp_fd)
|
|
2102
|
+
|
|
2103
|
+
if libc.syscall(SYS_landlock_restrict_self, ruleset_fd, 0) != 0:
|
|
2104
|
+
os.close(ruleset_fd)
|
|
2105
|
+
sys.exit(126)
|
|
2106
|
+
os.close(ruleset_fd)
|
|
2107
|
+
|
|
2108
|
+
machine = os.uname().machine
|
|
2109
|
+
if machine in ("x86_64", "amd64"):
|
|
2110
|
+
audit_arch = 0xc000003e
|
|
2111
|
+
blocked_nrs = [90, 91, 92, 93, 94, 260, 268, 425, 426, 427, 452]
|
|
2112
|
+
all_socket_nrs = [41, 42, 43, 49, 50, 53, 288]
|
|
2113
|
+
sys_socket = 41
|
|
2114
|
+
block_x32 = True
|
|
2115
|
+
elif machine in ("aarch64", "arm64"):
|
|
2116
|
+
audit_arch = 0xc00000b7
|
|
2117
|
+
blocked_nrs = [52, 53, 54, 55, 425, 426, 427, 452]
|
|
2118
|
+
all_socket_nrs = [198, 199, 200, 201, 202, 203, 242]
|
|
2119
|
+
sys_socket = 198
|
|
2120
|
+
block_x32 = False
|
|
2121
|
+
else:
|
|
2122
|
+
sys.exit(126)
|
|
2123
|
+
block_all_sockets = cfg.get("blockAllSockets") is True
|
|
2124
|
+
if block_all_sockets:
|
|
2125
|
+
blocked_nrs = blocked_nrs + all_socket_nrs
|
|
2126
|
+
block_ip = (not block_all_sockets) and (cfg.get("blockIpSockets") is True)
|
|
2127
|
+
extra_sock = 3 if block_ip else 0
|
|
2128
|
+
n_blocked = len(blocked_nrs)
|
|
2129
|
+
raw_insns = [
|
|
2130
|
+
(0x20, 0, 0, 4),
|
|
2131
|
+
(0x15, 1, 0, audit_arch),
|
|
2132
|
+
(0x06, 0, 0, 0x00050001),
|
|
2133
|
+
(0x20, 0, 0, 0),
|
|
2134
|
+
]
|
|
2135
|
+
if block_x32:
|
|
2136
|
+
raw_insns.append((0x35, n_blocked + extra_sock + 1, 0, 0x40000000))
|
|
2137
|
+
for idx_nr, nr in enumerate(blocked_nrs):
|
|
2138
|
+
raw_insns.append((0x15, (n_blocked - idx_nr) + extra_sock, 0, nr))
|
|
2139
|
+
if block_ip:
|
|
2140
|
+
raw_insns.extend([
|
|
2141
|
+
(0x15, 0, 2, sys_socket),
|
|
2142
|
+
(0x20, 0, 0, 16),
|
|
2143
|
+
(0x15, 0, 1, 1),
|
|
2144
|
+
])
|
|
2145
|
+
raw_insns.append((0x06, 0, 0, 0x7fff0000))
|
|
2146
|
+
raw_insns.append((0x06, 0, 0, 0x00050001))
|
|
2147
|
+
insns = (SockFilter * len(raw_insns))(*(SockFilter(*ins) for ins in raw_insns))
|
|
2148
|
+
prog = SockFprog(len(raw_insns), insns)
|
|
2149
|
+
if libc.prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, ctypes.byref(prog), 0, 0) != 0:
|
|
2150
|
+
sys.exit(126)
|
|
2151
|
+
cwd = cfg.get("cwd")
|
|
2152
|
+
if cwd:
|
|
2153
|
+
os.chdir(cwd)
|
|
2154
|
+
env = cfg.get("env")
|
|
2155
|
+
if env is not None:
|
|
2156
|
+
os.environ.clear()
|
|
2157
|
+
os.environ.update(env)
|
|
2158
|
+
os.execvp(cmd, [cmd] + args)
|
|
2159
|
+
`;
|
|
2160
|
+
export function provisionAbsentProtectedPlaceholders(normalized) {
|
|
2161
|
+
const createdFiles = [];
|
|
2162
|
+
const createdDirs = [];
|
|
2163
|
+
const writableDirs = normalized.canonicalWritablePaths.filter(wp => !normalized.canonicalExactWritableFiles.has(wp));
|
|
2164
|
+
const cleanupCreated = () => {
|
|
2165
|
+
for (let i = createdFiles.length - 1; i >= 0; i -= 1) {
|
|
2166
|
+
const item = createdFiles[i];
|
|
2167
|
+
try {
|
|
2168
|
+
const st = lstatSync(item.path);
|
|
2169
|
+
if (!st.isSymbolicLink() && st.isFile() && st.dev === item.dev && st.ino === item.ino && st.size === 0) {
|
|
2170
|
+
unlinkSync(item.path);
|
|
2171
|
+
}
|
|
2172
|
+
}
|
|
2173
|
+
catch {
|
|
2174
|
+
// Ignore if already absent.
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
2177
|
+
for (let i = createdDirs.length - 1; i >= 0; i -= 1) {
|
|
2178
|
+
const item = createdDirs[i];
|
|
2179
|
+
try {
|
|
2180
|
+
const st = lstatSync(item.path);
|
|
2181
|
+
if (!st.isSymbolicLink() && st.isDirectory() && st.dev === item.dev && st.ino === item.ino) {
|
|
2182
|
+
rmdirSync(item.path);
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
catch {
|
|
2186
|
+
// Keep directory if non-empty (e.g., sibling allowed file created inside it).
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
};
|
|
2190
|
+
try {
|
|
2191
|
+
if (writableDirs.length > 0 && existsSync(normalized.canonicalWorkspaceRoot)) {
|
|
2192
|
+
const sortedProtected = [...normalized.canonicalProtectedPaths].sort((a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0));
|
|
2193
|
+
const coveredRoots = [];
|
|
2194
|
+
for (const protectedPath of sortedProtected) {
|
|
2195
|
+
const coveringWritable = writableDirs
|
|
2196
|
+
.filter(wp => protectedPath !== wp && isSameOrSubpath(protectedPath, wp))
|
|
2197
|
+
.sort((a, b) => b.length - a.length)[0];
|
|
2198
|
+
if (coveringWritable === undefined)
|
|
2199
|
+
continue;
|
|
2200
|
+
if (coveredRoots.some(r => isSameOrSubpath(protectedPath, r)))
|
|
2201
|
+
continue;
|
|
2202
|
+
let cwStat = null;
|
|
2203
|
+
try {
|
|
2204
|
+
cwStat = lstatSync(coveringWritable);
|
|
2205
|
+
}
|
|
2206
|
+
catch (err) {
|
|
2207
|
+
if (err?.code === 'ENOENT') {
|
|
2208
|
+
continue;
|
|
2209
|
+
}
|
|
2210
|
+
throw err;
|
|
2211
|
+
}
|
|
2212
|
+
if (cwStat.isSymbolicLink()) {
|
|
2213
|
+
policyInvalid(`writable directory "${coveringWritable}" must not be a symbolic link`, 'writablePaths');
|
|
2214
|
+
}
|
|
2215
|
+
const rel = protectedPath.slice(coveringWritable === '/' ? 1 : coveringWritable.length + 1);
|
|
2216
|
+
const segments = rel.split(sep).filter(Boolean);
|
|
2217
|
+
let cursor = coveringWritable;
|
|
2218
|
+
let parentsValid = true;
|
|
2219
|
+
let parentCreated = false;
|
|
2220
|
+
for (let i = 0; i < segments.length - 1; i += 1) {
|
|
2221
|
+
cursor = join(cursor, segments[i]);
|
|
2222
|
+
let pStat = null;
|
|
2223
|
+
let pMissing = false;
|
|
2224
|
+
try {
|
|
2225
|
+
pStat = lstatSync(cursor);
|
|
2226
|
+
}
|
|
2227
|
+
catch (err) {
|
|
2228
|
+
if (err?.code === 'ENOENT') {
|
|
2229
|
+
pMissing = true;
|
|
2230
|
+
}
|
|
2231
|
+
else {
|
|
2232
|
+
parentsValid = false;
|
|
2233
|
+
break;
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
if (pMissing) {
|
|
2237
|
+
try {
|
|
2238
|
+
mkdirSync(cursor, { mode: 0o755 });
|
|
2239
|
+
const createdDirStat = lstatSync(cursor);
|
|
2240
|
+
if (createdDirStat.isSymbolicLink()) {
|
|
2241
|
+
policyInvalid(`protectedPath "${protectedPath}" traverses symbolic link "${cursor}" inside writable directory`, 'protectedPaths');
|
|
2242
|
+
}
|
|
2243
|
+
if (createdDirStat.isDirectory()) {
|
|
2244
|
+
createdDirs.push({ path: cursor, dev: createdDirStat.dev, ino: createdDirStat.ino });
|
|
2245
|
+
parentCreated = true;
|
|
2246
|
+
}
|
|
2247
|
+
else {
|
|
2248
|
+
parentsValid = false;
|
|
2249
|
+
break;
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
catch (err) {
|
|
2253
|
+
if (err instanceof TaskpackError)
|
|
2254
|
+
throw err;
|
|
2255
|
+
parentsValid = false;
|
|
2256
|
+
break;
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
2259
|
+
else if (pStat !== null && pStat.isSymbolicLink()) {
|
|
2260
|
+
policyInvalid(`protectedPath "${protectedPath}" traverses symbolic link "${cursor}" inside writable directory`, 'protectedPaths');
|
|
2261
|
+
}
|
|
2262
|
+
else if (pStat === null || !pStat.isDirectory()) {
|
|
2263
|
+
parentsValid = false;
|
|
2264
|
+
break;
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
if (!parentsValid)
|
|
2268
|
+
continue;
|
|
2269
|
+
let existingStat = null;
|
|
2270
|
+
let missing = parentCreated;
|
|
2271
|
+
if (!missing) {
|
|
2272
|
+
try {
|
|
2273
|
+
existingStat = lstatSync(protectedPath);
|
|
2274
|
+
}
|
|
2275
|
+
catch (err) {
|
|
2276
|
+
if (err?.code === 'ENOENT') {
|
|
2277
|
+
missing = true;
|
|
2278
|
+
}
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
if (missing) {
|
|
2282
|
+
const openFlags = fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY | (fsConstants.O_NOFOLLOW ?? 0);
|
|
2283
|
+
try {
|
|
2284
|
+
const fd = openSync(protectedPath, openFlags, 0o000);
|
|
2285
|
+
try {
|
|
2286
|
+
const st = fstatSync(fd);
|
|
2287
|
+
createdFiles.push({ path: protectedPath, dev: st.dev, ino: st.ino });
|
|
2288
|
+
coveredRoots.push(protectedPath);
|
|
2289
|
+
}
|
|
2290
|
+
finally {
|
|
2291
|
+
closeSync(fd);
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
catch (err) {
|
|
2295
|
+
if (err?.code === 'ELOOP') {
|
|
2296
|
+
policyInvalid(`protectedPath "${protectedPath}" targets a symbolic link`, 'protectedPaths');
|
|
2297
|
+
}
|
|
2298
|
+
// Skip if concurrently created or parent is non-writable.
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
else if (existingStat !== null) {
|
|
2302
|
+
coveredRoots.push(protectedPath);
|
|
2303
|
+
}
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2307
|
+
catch (err) {
|
|
2308
|
+
cleanupCreated();
|
|
2309
|
+
throw err;
|
|
2310
|
+
}
|
|
2311
|
+
return {
|
|
2312
|
+
placeholderPaths: Object.freeze(createdFiles.map(f => f.path)),
|
|
2313
|
+
cleanup: cleanupCreated,
|
|
2314
|
+
};
|
|
2315
|
+
}
|
|
2316
|
+
/**
|
|
2317
|
+
* Execute a command inside the negotiated OS sandbox with sanitized environment, bounded streams,
|
|
2318
|
+
* timeout enforcement, process-group cleanup, and secret scrubbing.
|
|
2319
|
+
*/
|
|
2320
|
+
export async function executeSandboxedCommand(input) {
|
|
2321
|
+
if (typeof input.command !== 'string' || input.command.trim().length === 0 || /[\0\r\n]/.test(input.command)) {
|
|
2322
|
+
policyInvalid('command must be a non-empty string without control characters', 'command');
|
|
2323
|
+
}
|
|
2324
|
+
const env = resolveHostEnvironment(input.host);
|
|
2325
|
+
const normalized = normalizeSandboxPolicy(input.policy, env);
|
|
2326
|
+
const negotiated = negotiateSandboxBackend(input.policy, env);
|
|
2327
|
+
const timeoutMs = input.timeoutMs ?? DEFAULT_SANDBOX_TIMEOUT_MS;
|
|
2328
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 50 || timeoutMs > MAX_SANDBOX_TIMEOUT_MS) {
|
|
2329
|
+
policyInvalid(`timeoutMs must be an integer in 50..${MAX_SANDBOX_TIMEOUT_MS}`, 'timeoutMs');
|
|
2330
|
+
}
|
|
2331
|
+
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_SANDBOX_OUTPUT_BYTES;
|
|
2332
|
+
if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1024 || maxOutputBytes > 16_777_216) {
|
|
2333
|
+
policyInvalid('maxOutputBytes must be an integer in 1024..16777216', 'maxOutputBytes');
|
|
2334
|
+
}
|
|
2335
|
+
const scrubber = new SecretScrubber();
|
|
2336
|
+
for (const secret of input.secretsToScrub ?? []) {
|
|
2337
|
+
scrubber.register(secret);
|
|
2338
|
+
}
|
|
2339
|
+
const sanitizedEnv = {
|
|
2340
|
+
HOME: normalized.canonicalScratchDirectory ?? normalized.canonicalWorkspaceRoot,
|
|
2341
|
+
PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin',
|
|
2342
|
+
LANG: 'C.UTF-8',
|
|
2343
|
+
TERM: 'dumb',
|
|
2344
|
+
...(input.env ?? {}),
|
|
2345
|
+
GIT_CONFIG_NOSYSTEM: '1',
|
|
2346
|
+
GIT_CONFIG_GLOBAL: '/dev/null',
|
|
2347
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
2348
|
+
};
|
|
2349
|
+
const targetCwd = input.cwd === undefined
|
|
2350
|
+
? normalized.canonicalWorkspaceRoot
|
|
2351
|
+
: canonicalizeAbsolutePath(input.cwd, 'cwd');
|
|
2352
|
+
let placeholderGuard = null;
|
|
2353
|
+
try {
|
|
2354
|
+
let spawnExecutable;
|
|
2355
|
+
let spawnArgs;
|
|
2356
|
+
let spawnCwd = targetCwd;
|
|
2357
|
+
let seccompBpf = null;
|
|
2358
|
+
if (negotiated.backendId === 'macos-seatbelt') {
|
|
2359
|
+
provisionSandboxExactWritablePaths(normalized, { createTargetFile: false });
|
|
2360
|
+
const compiled = compileMacosSeatbeltProfile(input.policy, env);
|
|
2361
|
+
spawnExecutable = compiled.executablePath;
|
|
2362
|
+
spawnArgs = ['-p', compiled.profileText, '--', input.command, ...(input.args ?? [])];
|
|
2363
|
+
}
|
|
2364
|
+
else if (negotiated.backendId === 'linux-bwrap') {
|
|
2365
|
+
const dynamicGlob = findDynamicProtectedGlobOverlap(normalized);
|
|
2366
|
+
if (dynamicGlob !== null) {
|
|
2367
|
+
throw new TaskpackError('SANDBOX_CAPABILITY_INSUFFICIENT', `linux-bwrap cannot enforce dynamic protected glob "${dynamicGlob}" inside writable directory`, 'protectedPaths');
|
|
2368
|
+
}
|
|
2369
|
+
placeholderGuard = provisionAbsentProtectedPlaceholders(normalized);
|
|
2370
|
+
const compiled = compileLinuxBwrapCommand(input.policy, env, {
|
|
2371
|
+
cwd: targetCwd,
|
|
2372
|
+
env: sanitizedEnv,
|
|
2373
|
+
provisionExactFiles: true,
|
|
2374
|
+
inheritSpawnEnv: true,
|
|
2375
|
+
});
|
|
2376
|
+
seccompBpf = compileLinuxSeccompBpfBinary(env.arch, {
|
|
2377
|
+
blockIpSockets: normalized.networkMode === 'none',
|
|
2378
|
+
});
|
|
2379
|
+
spawnExecutable = compiled.executablePath;
|
|
2380
|
+
spawnArgs = [...compiled.args, '--seccomp', '3', '--', input.command, ...(input.args ?? [])];
|
|
2381
|
+
if (spawnArgs.length > 8_999) {
|
|
2382
|
+
throw new TaskpackError('SANDBOX_CAPABILITY_INSUFFICIENT', `linux-bwrap invocation requires ${spawnArgs.length} arguments, exceeding max 8999`, 'args');
|
|
2383
|
+
}
|
|
2384
|
+
}
|
|
2385
|
+
else if (negotiated.backendId === 'linux-landlock') {
|
|
2386
|
+
if (normalized.networkMode === 'loopback-only') {
|
|
2387
|
+
throw new TaskpackError('SANDBOX_CAPABILITY_INSUFFICIENT', 'linux-landlock cannot enforce loopback-only network isolation without network namespaces', 'networkMode');
|
|
2388
|
+
}
|
|
2389
|
+
const overlap = findLandlockWritableOverlap(normalized);
|
|
2390
|
+
if (overlap !== null) {
|
|
2391
|
+
throw new TaskpackError('SANDBOX_CAPABILITY_INSUFFICIENT', `linux-landlock cannot enforce nested exclusion inside writable directory (${overlap})`, 'protectedPaths');
|
|
2392
|
+
}
|
|
2393
|
+
provisionSandboxExactWritablePaths(normalized, { createTargetFile: true });
|
|
2394
|
+
spawnExecutable = negotiated.executablePath;
|
|
2395
|
+
spawnCwd = '/';
|
|
2396
|
+
const landlockConfig = JSON.stringify({
|
|
2397
|
+
workspaceRoot: normalized.canonicalWorkspaceRoot,
|
|
2398
|
+
writablePaths: normalized.canonicalWritablePaths,
|
|
2399
|
+
exactWritableFiles: [...normalized.canonicalExactWritableFiles],
|
|
2400
|
+
protectedPaths: normalized.canonicalProtectedPaths,
|
|
2401
|
+
deniedReadPaths: normalized.canonicalDeniedReadPaths,
|
|
2402
|
+
allowedReadOnlyPaths: normalized.canonicalAllowedReadOnlyPaths,
|
|
2403
|
+
networkMode: normalized.networkMode,
|
|
2404
|
+
blockIpSockets: normalized.networkMode === 'none',
|
|
2405
|
+
cwd: targetCwd,
|
|
2406
|
+
});
|
|
2407
|
+
spawnArgs = ['-I', '-S', '-B', '-c', LANDLOCK_BOOTSTRAP_SCRIPT, landlockConfig, input.command, ...(input.args ?? [])];
|
|
2408
|
+
}
|
|
2409
|
+
else if (negotiated.backendId === 'direct-dedicated') {
|
|
2410
|
+
spawnExecutable = input.command;
|
|
2411
|
+
spawnArgs = [...(input.args ?? [])];
|
|
2412
|
+
}
|
|
2413
|
+
else {
|
|
2414
|
+
throw new TaskpackError('SANDBOX_BACKEND_UNAVAILABLE', `backend "${negotiated.backendId}" direct command spawn is not supported without container runtime adapter`, 'backendId');
|
|
2415
|
+
}
|
|
2416
|
+
const started = performance.now();
|
|
2417
|
+
return await new Promise((resolvePromise, rejectPromise) => {
|
|
2418
|
+
const child = spawn(spawnExecutable, [...spawnArgs], {
|
|
2419
|
+
cwd: spawnCwd,
|
|
2420
|
+
env: sanitizedEnv,
|
|
2421
|
+
stdio: seccompBpf !== null ? ['pipe', 'pipe', 'pipe', 'pipe'] : ['pipe', 'pipe', 'pipe'],
|
|
2422
|
+
detached: true,
|
|
2423
|
+
});
|
|
2424
|
+
if (seccompBpf !== null) {
|
|
2425
|
+
const seccompStream = child.stdio[3];
|
|
2426
|
+
if (seccompStream !== null && seccompStream !== undefined) {
|
|
2427
|
+
seccompStream.on('error', () => undefined);
|
|
2428
|
+
seccompStream.end(seccompBpf);
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
const killGroup = (signal) => {
|
|
2432
|
+
try {
|
|
2433
|
+
if (child.pid !== undefined)
|
|
2434
|
+
process.kill(-child.pid, signal);
|
|
2435
|
+
}
|
|
2436
|
+
catch {
|
|
2437
|
+
child.kill(signal);
|
|
2438
|
+
}
|
|
2439
|
+
};
|
|
2440
|
+
const stdoutChunks = [];
|
|
2441
|
+
const stderrChunks = [];
|
|
2442
|
+
let stdoutBytes = 0;
|
|
2443
|
+
let stderrBytes = 0;
|
|
2444
|
+
let timedOut = false;
|
|
2445
|
+
let settled = false;
|
|
2446
|
+
const timer = setTimeout(() => {
|
|
2447
|
+
timedOut = true;
|
|
2448
|
+
killGroup('SIGTERM');
|
|
2449
|
+
setTimeout(() => {
|
|
2450
|
+
if (!settled)
|
|
2451
|
+
killGroup('SIGKILL');
|
|
2452
|
+
}, 200);
|
|
2453
|
+
}, timeoutMs);
|
|
2454
|
+
const finish = (exitCode, signal, error) => {
|
|
2455
|
+
if (settled)
|
|
2456
|
+
return;
|
|
2457
|
+
settled = true;
|
|
2458
|
+
clearTimeout(timer);
|
|
2459
|
+
if (error !== undefined) {
|
|
2460
|
+
rejectPromise(error);
|
|
2461
|
+
return;
|
|
2462
|
+
}
|
|
2463
|
+
const rawStdout = Buffer.concat(stdoutChunks).toString('utf8');
|
|
2464
|
+
const rawStderr = Buffer.concat(stderrChunks).toString('utf8');
|
|
2465
|
+
resolvePromise(Object.freeze({
|
|
2466
|
+
backendId: negotiated.backendId,
|
|
2467
|
+
profileDigest: negotiated.profileDigest,
|
|
2468
|
+
exitCode,
|
|
2469
|
+
signal,
|
|
2470
|
+
stdout: scrubber.scrub(rawStdout),
|
|
2471
|
+
stderr: scrubber.scrub(rawStderr),
|
|
2472
|
+
timedOut,
|
|
2473
|
+
durationMs: Math.max(1, Math.round(performance.now() - started)),
|
|
2474
|
+
}));
|
|
2475
|
+
};
|
|
2476
|
+
child.on('error', err => {
|
|
2477
|
+
finish(null, null, new TaskpackError('SANDBOX_EXECUTION_FAILED', `sandboxed command failed to spawn: ${err.message}`));
|
|
2478
|
+
});
|
|
2479
|
+
child.stdout.on('data', (chunk) => {
|
|
2480
|
+
stdoutBytes += chunk.byteLength;
|
|
2481
|
+
if (stdoutBytes > maxOutputBytes) {
|
|
2482
|
+
killGroup('SIGKILL');
|
|
2483
|
+
finish(null, null, new TaskpackError('SANDBOX_EXECUTION_FAILED', `sandboxed command stdout exceeded ${maxOutputBytes} bytes`));
|
|
2484
|
+
return;
|
|
2485
|
+
}
|
|
2486
|
+
stdoutChunks.push(chunk);
|
|
2487
|
+
});
|
|
2488
|
+
child.stderr.on('data', (chunk) => {
|
|
2489
|
+
stderrBytes += chunk.byteLength;
|
|
2490
|
+
if (stderrBytes > maxOutputBytes) {
|
|
2491
|
+
killGroup('SIGKILL');
|
|
2492
|
+
finish(null, null, new TaskpackError('SANDBOX_EXECUTION_FAILED', `sandboxed command stderr exceeded ${maxOutputBytes} bytes`));
|
|
2493
|
+
return;
|
|
2494
|
+
}
|
|
2495
|
+
stderrChunks.push(chunk);
|
|
2496
|
+
});
|
|
2497
|
+
if (input.stdin !== undefined) {
|
|
2498
|
+
child.stdin.end(input.stdin);
|
|
2499
|
+
}
|
|
2500
|
+
else {
|
|
2501
|
+
child.stdin.end();
|
|
2502
|
+
}
|
|
2503
|
+
child.on('close', (code, signal) => {
|
|
2504
|
+
killGroup('SIGKILL');
|
|
2505
|
+
finish(code, signal);
|
|
2506
|
+
});
|
|
2507
|
+
});
|
|
2508
|
+
}
|
|
2509
|
+
finally {
|
|
2510
|
+
placeholderGuard?.cleanup();
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
/**
|
|
2514
|
+
* Resolve the effective sandbox policy for a declarative Taskpack manifest.
|
|
2515
|
+
* Under GitHub Actions (`GITHUB_ACTIONS === 'true'`), omitted `spec.sandbox`
|
|
2516
|
+
* defaults to `direct-dedicated` because GitHub-hosted runners already isolate the job.
|
|
2517
|
+
*/
|
|
2518
|
+
export function resolveEffectiveTaskpackSandboxPolicy(manifest, options) {
|
|
2519
|
+
if (options.policyProfile !== undefined
|
|
2520
|
+
&& options.hostPolicy?.policyProfile !== undefined
|
|
2521
|
+
&& options.policyProfile !== options.hostPolicy.policyProfile) {
|
|
2522
|
+
throw new TaskpackError('TASKPACK_HOST_BINDING_INVALID', `conflicting policyProfile "${options.policyProfile}" and hostPolicy.policyProfile "${options.hostPolicy.policyProfile}"`, '/policyProfile');
|
|
2523
|
+
}
|
|
2524
|
+
const policyProfile = options.policyProfile ?? options.hostPolicy?.policyProfile ?? 'local';
|
|
2525
|
+
validateExecutionAuthority(manifest.spec.execution, options.hostPolicy);
|
|
2526
|
+
const allowWorkflowWrites = policyProfile === 'github'
|
|
2527
|
+
&& manifest.spec.execution?.capabilities.allowWorkflowWrites === true
|
|
2528
|
+
&& options.hostPolicy?.allowWorkflowWrites === true;
|
|
2529
|
+
const allowAgentNetwork = manifest.spec.execution?.capabilities.allowAgentNetwork === true
|
|
2530
|
+
&& options.hostPolicy?.allowPrivileged === true;
|
|
2531
|
+
const resolvedControl = options.controlRoot !== undefined
|
|
2532
|
+
? {
|
|
2533
|
+
controlRoot: normalizeRelativePath(options.controlRoot, '/controlRoot'),
|
|
2534
|
+
...(options.relativeTaskpackPath !== undefined
|
|
2535
|
+
? { manifestPath: normalizeRelativePath(options.relativeTaskpackPath, '/relativeTaskpackPath') }
|
|
2536
|
+
: manifest.manifestPath !== undefined
|
|
2537
|
+
? { manifestPath: manifest.manifestPath }
|
|
2538
|
+
: {}),
|
|
2539
|
+
}
|
|
2540
|
+
: resolveManifestControlRoot(manifest, options.relativeTaskpackPath);
|
|
2541
|
+
const commandScripts = manifest.spec.verification.localChecks
|
|
2542
|
+
.flatMap(check => (check.implementation === 'command.v1' && typeof check.parameters?.['script'] === 'string' && check.parameters['script'].length > 0
|
|
2543
|
+
? [check.parameters['script']]
|
|
2544
|
+
: []));
|
|
2545
|
+
const toolchainPaths = manifest.spec.verification.localChecks
|
|
2546
|
+
.flatMap(check => (check.implementation === 'command.v1' && Array.isArray(check.parameters?.['toolchainPaths'])
|
|
2547
|
+
? check.parameters['toolchainPaths'].filter((entry) => typeof entry === 'string' && entry.length > 0)
|
|
2548
|
+
: []));
|
|
2549
|
+
const allInstructions = [
|
|
2550
|
+
...(manifest.spec.instructions ?? []),
|
|
2551
|
+
...(manifest.spec.roles ?? []).flatMap(role => role.instructions ?? []),
|
|
2552
|
+
];
|
|
2553
|
+
const allSkills = [
|
|
2554
|
+
...(manifest.spec.skills ?? []),
|
|
2555
|
+
...(manifest.spec.roles ?? []).flatMap(role => role.skills ?? []),
|
|
2556
|
+
];
|
|
2557
|
+
const proposalPath = manifest.spec.proposal?.path;
|
|
2558
|
+
const controlRootSiblingSet = proposalPath !== undefined
|
|
2559
|
+
? collectControlRootSiblingPaths({
|
|
2560
|
+
repositoryRoot: options.workspaceRoot,
|
|
2561
|
+
controlRoot: resolvedControl.controlRoot,
|
|
2562
|
+
proposalPath,
|
|
2563
|
+
})
|
|
2564
|
+
: Object.freeze({ prioritySiblings: Object.freeze([]), regularSiblings: Object.freeze([]) });
|
|
2565
|
+
const githubSiblings = allowWorkflowWrites
|
|
2566
|
+
? collectGitHubSiblingPaths({ repositoryRoot: options.workspaceRoot })
|
|
2567
|
+
: [];
|
|
2568
|
+
assertManifestScopeInvariants(manifest, {
|
|
2569
|
+
policyProfile,
|
|
2570
|
+
controlRoot: resolvedControl.controlRoot,
|
|
2571
|
+
manifestPath: resolvedControl.manifestPath,
|
|
2572
|
+
commandScripts,
|
|
2573
|
+
priorityControlRootSiblings: controlRootSiblingSet.prioritySiblings,
|
|
2574
|
+
controlRootSiblings: controlRootSiblingSet.regularSiblings,
|
|
2575
|
+
githubSiblings,
|
|
2576
|
+
hostPolicy: options.hostPolicy,
|
|
2577
|
+
allowWildcardWritableWhenControlRootProtected: true,
|
|
2578
|
+
});
|
|
2579
|
+
const writablePaths = manifest.spec.scope.writable.length === 0 ||
|
|
2580
|
+
(manifest.spec.scope.writable.length === 1 && manifest.spec.scope.writable[0] === '**')
|
|
2581
|
+
? ['.']
|
|
2582
|
+
: [...manifest.spec.scope.writable];
|
|
2583
|
+
const protectedPaths = effectiveProtectedPaths(manifest.spec.scope.protected, {
|
|
2584
|
+
policyProfile,
|
|
2585
|
+
controlRoot: resolvedControl.controlRoot,
|
|
2586
|
+
manifestPath: resolvedControl.manifestPath,
|
|
2587
|
+
digestsLockfile: manifest.spec.execution?.digests?.lockfile,
|
|
2588
|
+
instructions: allInstructions.length > 0 ? allInstructions : undefined,
|
|
2589
|
+
skills: allSkills.length > 0 ? allSkills : undefined,
|
|
2590
|
+
preflightScript: manifest.spec.preflight?.script,
|
|
2591
|
+
commandScripts,
|
|
2592
|
+
toolchainPaths: toolchainPaths.length > 0 ? toolchainPaths : undefined,
|
|
2593
|
+
proposalPath,
|
|
2594
|
+
priorityControlRootSiblings: controlRootSiblingSet.prioritySiblings,
|
|
2595
|
+
controlRootSiblings: controlRootSiblingSet.regularSiblings,
|
|
2596
|
+
allowWorkflowWrites,
|
|
2597
|
+
githubSiblings,
|
|
2598
|
+
});
|
|
2599
|
+
const proposalInControlRoot = proposalPath !== undefined && pathCoveredBy(proposalPath, resolvedControl.controlRoot);
|
|
2600
|
+
const basePolicy = {
|
|
2601
|
+
workspaceRoot: options.workspaceRoot,
|
|
2602
|
+
...(options.scratchDirectory !== undefined ? { scratchDirectory: options.scratchDirectory } : {}),
|
|
2603
|
+
writablePaths,
|
|
2604
|
+
protectedPaths,
|
|
2605
|
+
policyProfile,
|
|
2606
|
+
allowWorkflowWrites,
|
|
2607
|
+
strictExactFiles: true,
|
|
2608
|
+
...(options.allowedReadOnlyPaths !== undefined && options.allowedReadOnlyPaths.length > 0
|
|
2609
|
+
? { allowedReadOnlyPaths: options.allowedReadOnlyPaths }
|
|
2610
|
+
: {}),
|
|
2611
|
+
...(allowAgentNetwork ? { networkMode: 'allow-outbound' } : {}),
|
|
2612
|
+
...(proposalInControlRoot && proposalPath !== undefined
|
|
2613
|
+
? {
|
|
2614
|
+
controlRoot: resolvedControl.controlRoot,
|
|
2615
|
+
proposalPath,
|
|
2616
|
+
}
|
|
2617
|
+
: {}),
|
|
2618
|
+
};
|
|
2619
|
+
if (manifest.spec.sandbox !== undefined) {
|
|
2620
|
+
const sandbox = manifest.spec.sandbox;
|
|
2621
|
+
return {
|
|
2622
|
+
...basePolicy,
|
|
2623
|
+
...(sandbox.preferredBackends?.includes('direct-dedicated') === true ? { allowDedicatedDirectOverride: true } : {}),
|
|
2624
|
+
...(sandbox.preferredBackends !== undefined ? { preferredBackends: sandbox.preferredBackends } : {}),
|
|
2625
|
+
...(sandbox.networkMode !== undefined ? { networkMode: sandbox.networkMode } : {}),
|
|
2626
|
+
...(sandbox.requiredCapabilities !== undefined ? { requiredCapabilities: sandbox.requiredCapabilities } : {}),
|
|
2627
|
+
...(sandbox.deniedReadPaths !== undefined ? { deniedReadPaths: sandbox.deniedReadPaths } : {}),
|
|
2628
|
+
};
|
|
2629
|
+
}
|
|
2630
|
+
const runtimeEnv = options.env ?? process.env;
|
|
2631
|
+
const runnerEnv = (runtimeEnv['RUNNER_ENVIRONMENT'] ?? '').trim();
|
|
2632
|
+
if (runtimeEnv['GITHUB_ACTIONS'] === 'true' && runnerEnv === 'github-hosted') {
|
|
2633
|
+
return {
|
|
2634
|
+
...basePolicy,
|
|
2635
|
+
preferredBackends: ['direct-dedicated'],
|
|
2636
|
+
networkMode: 'allow-outbound',
|
|
2637
|
+
requiredCapabilities: ['processTreeCleanup'],
|
|
2638
|
+
allowDedicatedDirectOverride: true,
|
|
2639
|
+
};
|
|
2640
|
+
}
|
|
2641
|
+
return basePolicy;
|
|
2642
|
+
}
|