From cc8ea482c32d6cc8f9491383ecc14c333ed3046f Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Wed, 25 Nov 2026 23:44:31 +0100 Subject: [PATCH] Add the SendBox and SendBox Fleet website and documentation A dependency-free static site for sendbox.synctune.it: a landing page that showcases SendBox and SendBox Fleet, user and contributor documentation for both projects, and a contributor guide. Documentation is synced unchanged from sendbox-dev/sendbox@fe05a0d and sendbox-dev/sendbox-fleet@962a6cf into vendor/, recorded with SHA-256 hashes in SOURCE.json, and rendered to static pages by Node scripts that use only built-in modules. CI checks vendored files, generated pages, links, anchors, accessibility basics, the sitemap and theme contrast, then deploys to GitHub Pages from main. --- .github/workflows/pages.yml | 71 ++ .gitignore | 4 + .node-version | 1 + .nojekyll | 0 404.html | 20 + CNAME | 1 + README.md | 28 +- assets/favicon.svg | 8 + assets/logos/sendbox-fleet.svg | 15 + assets/logos/sendbox.svg | 8 + assets/styles.css | 284 +++++++ contribute/index.html | 90 +++ docs/deployment.md | 80 ++ docs/maintenance.md | 109 +++ fleet/architecture/index.html | 356 +++++++++ fleet/contract/index.html | 181 +++++ fleet/contributing/index.html | 103 +++ fleet/deployment/index.html | 318 ++++++++ fleet/development/index.html | 253 ++++++ fleet/index.html | 81 ++ fleet/overview/index.html | 124 +++ fleet/roadmap/index.html | 175 +++++ fleet/security-policy/index.html | 94 +++ fleet/threat-model/index.html | 165 ++++ index.html | 184 +++++ robots.txt | 3 + scripts/build.mjs | 144 ++++ scripts/catalogue.mjs | 145 ++++ scripts/check.mjs | 283 +++++++ scripts/layout.mjs | 202 +++++ scripts/markdown.mjs | 571 ++++++++++++++ scripts/package.mjs | 32 + scripts/sync.mjs | 80 ++ scripts/vendor.mjs | 29 + sendbox/apple-runtime/index.html | 385 ++++++++++ .../agent-orchestration/index.html | 198 +++++ .../authenticated-guest-protocol/index.html | 373 +++++++++ .../egress-enforcement/index.html | 577 ++++++++++++++ .../architecture/execution-broker/index.html | 282 +++++++ .../architecture/git-branch-guard/index.html | 202 +++++ .../architecture/governed-sessions/index.html | 552 +++++++++++++ .../guest-artifact-bundles/index.html | 341 ++++++++ .../architecture/guest-supervisor/index.html | 334 ++++++++ .../interactive-terminal/index.html | 352 +++++++++ sendbox/architecture/kata-runtime/index.html | 203 +++++ sendbox/architecture/mcp-broker/index.html | 264 +++++++ .../native-project-analysis/index.html | 241 ++++++ .../package-registry-proxy/index.html | 252 ++++++ sendbox/architecture/runtime-core/index.html | 290 +++++++ .../architecture/rust-cli-parity/index.html | 180 +++++ sendbox/architecture/safe-outputs/index.html | 304 ++++++++ .../secrets-and-credential-broker/index.html | 322 ++++++++ .../architecture/security-records/index.html | 197 +++++ .../session-security-lifecycle/index.html | 225 ++++++ sendbox/cli-agents/index.html | 373 +++++++++ sendbox/cli-reference/index.html | 251 ++++++ sendbox/configuration/index.html | 478 ++++++++++++ sendbox/contributing/index.html | 241 ++++++ sendbox/dns-cold-start/index.html | 424 ++++++++++ sendbox/egress-trust-boundary/index.html | 318 ++++++++ sendbox/hyperlight/index.html | 252 ++++++ sendbox/index.html | 123 +++ sendbox/installation/index.html | 448 +++++++++++ sendbox/integrations/index.html | 260 +++++++ sendbox/interactive-sessions/index.html | 209 +++++ sendbox/kata-containers/index.html | 267 +++++++ sendbox/mcp-inspection/index.html | 338 ++++++++ sendbox/overview/index.html | 433 +++++++++++ sendbox/package-supply-chain/index.html | 372 +++++++++ sendbox/qualification/index.html | 266 +++++++ sendbox/roadmap/index.html | 436 +++++++++++ sendbox/secrets-migration/index.html | 175 +++++ sendbox/security-model/index.html | 725 ++++++++++++++++++ sendbox/security-policy/index.html | 157 ++++ sendbox/security-records-migration/index.html | 149 ++++ sendbox/similar-tools/index.html | 252 ++++++ sitemap.xml | 57 ++ tests/check.test.mjs | 56 ++ tests/markdown.test.mjs | 65 ++ vendor/sendbox-fleet/CONTRIBUTING.md | 16 + vendor/sendbox-fleet/LICENSE | 201 +++++ vendor/sendbox-fleet/README.md | 44 ++ vendor/sendbox-fleet/SECURITY.md | 10 + vendor/sendbox-fleet/SOURCE.json | 19 + vendor/sendbox-fleet/docs/architecture.md | 269 +++++++ vendor/sendbox-fleet/docs/assets/logo.svg | 15 + vendor/sendbox-fleet/docs/contract.md | 96 +++ vendor/sendbox-fleet/docs/deployment.md | 254 ++++++ vendor/sendbox-fleet/docs/development.md | 191 +++++ vendor/sendbox-fleet/docs/roadmap.md | 89 +++ vendor/sendbox-fleet/docs/threat-model.md | 68 ++ vendor/sendbox/LICENSE | 201 +++++ vendor/sendbox/README.md | 360 +++++++++ vendor/sendbox/ROADMAP.md | 317 ++++++++ vendor/sendbox/SECURITY.md | 33 + vendor/sendbox/SOURCE.json | 51 ++ vendor/sendbox/docs/alternatives.md | 126 +++ vendor/sendbox/docs/apple-runtime.md | 293 +++++++ .../docs/architecture/agent-orchestration.md | 72 ++ .../authenticated-guest-protocol.md | 268 +++++++ .../docs/architecture/egress-enforcement.md | 482 ++++++++++++ .../docs/architecture/execution-broker.md | 170 ++++ .../docs/architecture/git-branch-guard.md | 86 +++ .../docs/architecture/governed-sessions.md | 451 +++++++++++ .../architecture/guest-artifact-bundles.md | 241 ++++++ .../docs/architecture/guest-supervisor.md | 225 ++++++ .../docs/architecture/interactive-terminal.md | 245 ++++++ .../sendbox/docs/architecture/kata-runtime.md | 82 ++ .../sendbox/docs/architecture/mcp-broker.md | 154 ++++ .../architecture/native-project-analysis.md | 119 +++ .../architecture/package-registry-proxy.md | 139 ++++ .../sendbox/docs/architecture/runtime-core.md | 179 +++++ .../docs/architecture/rust-cli-parity.md | 54 ++ .../sendbox/docs/architecture/safe-outputs.md | 199 +++++ .../secrets-and-credential-broker.md | 225 ++++++ .../docs/architecture/security-records.md | 78 ++ .../session-security-lifecycle.md | 105 +++ vendor/sendbox/docs/assets/logo.svg | 8 + vendor/sendbox/docs/cli-agents.md | 300 ++++++++ vendor/sendbox/docs/cli-reference.md | 129 ++++ vendor/sendbox/docs/configuration.md | 374 +++++++++ vendor/sendbox/docs/contributing.md | 145 ++++ vendor/sendbox/docs/dns-cold-start.md | 328 ++++++++ vendor/sendbox/docs/hyperlight.md | 150 ++++ vendor/sendbox/docs/installation.md | 401 ++++++++++ vendor/sendbox/docs/integrations.md | 173 +++++ vendor/sendbox/docs/interactive-sessions.md | 88 +++ vendor/sendbox/docs/kata-containers.md | 182 +++++ vendor/sendbox/docs/mcp-inspection.md | 270 +++++++ vendor/sendbox/docs/migration/secrets.md | 53 ++ .../docs/migration/security-records.md | 25 + vendor/sendbox/docs/package-supply-chain.md | 273 +++++++ vendor/sendbox/docs/qualification.md | 166 ++++ vendor/sendbox/docs/security-model.md | 643 ++++++++++++++++ .../egress-enforcement-trust-boundary.md | 188 +++++ 135 files changed, 27562 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/pages.yml create mode 100644 .gitignore create mode 100644 .node-version create mode 100644 .nojekyll create mode 100644 404.html create mode 100644 CNAME create mode 100644 assets/favicon.svg create mode 100644 assets/logos/sendbox-fleet.svg create mode 100644 assets/logos/sendbox.svg create mode 100644 assets/styles.css create mode 100644 contribute/index.html create mode 100644 docs/deployment.md create mode 100644 docs/maintenance.md create mode 100644 fleet/architecture/index.html create mode 100644 fleet/contract/index.html create mode 100644 fleet/contributing/index.html create mode 100644 fleet/deployment/index.html create mode 100644 fleet/development/index.html create mode 100644 fleet/index.html create mode 100644 fleet/overview/index.html create mode 100644 fleet/roadmap/index.html create mode 100644 fleet/security-policy/index.html create mode 100644 fleet/threat-model/index.html create mode 100644 index.html create mode 100644 robots.txt create mode 100644 scripts/build.mjs create mode 100644 scripts/catalogue.mjs create mode 100644 scripts/check.mjs create mode 100644 scripts/layout.mjs create mode 100644 scripts/markdown.mjs create mode 100644 scripts/package.mjs create mode 100644 scripts/sync.mjs create mode 100644 scripts/vendor.mjs create mode 100644 sendbox/apple-runtime/index.html create mode 100644 sendbox/architecture/agent-orchestration/index.html create mode 100644 sendbox/architecture/authenticated-guest-protocol/index.html create mode 100644 sendbox/architecture/egress-enforcement/index.html create mode 100644 sendbox/architecture/execution-broker/index.html create mode 100644 sendbox/architecture/git-branch-guard/index.html create mode 100644 sendbox/architecture/governed-sessions/index.html create mode 100644 sendbox/architecture/guest-artifact-bundles/index.html create mode 100644 sendbox/architecture/guest-supervisor/index.html create mode 100644 sendbox/architecture/interactive-terminal/index.html create mode 100644 sendbox/architecture/kata-runtime/index.html create mode 100644 sendbox/architecture/mcp-broker/index.html create mode 100644 sendbox/architecture/native-project-analysis/index.html create mode 100644 sendbox/architecture/package-registry-proxy/index.html create mode 100644 sendbox/architecture/runtime-core/index.html create mode 100644 sendbox/architecture/rust-cli-parity/index.html create mode 100644 sendbox/architecture/safe-outputs/index.html create mode 100644 sendbox/architecture/secrets-and-credential-broker/index.html create mode 100644 sendbox/architecture/security-records/index.html create mode 100644 sendbox/architecture/session-security-lifecycle/index.html create mode 100644 sendbox/cli-agents/index.html create mode 100644 sendbox/cli-reference/index.html create mode 100644 sendbox/configuration/index.html create mode 100644 sendbox/contributing/index.html create mode 100644 sendbox/dns-cold-start/index.html create mode 100644 sendbox/egress-trust-boundary/index.html create mode 100644 sendbox/hyperlight/index.html create mode 100644 sendbox/index.html create mode 100644 sendbox/installation/index.html create mode 100644 sendbox/integrations/index.html create mode 100644 sendbox/interactive-sessions/index.html create mode 100644 sendbox/kata-containers/index.html create mode 100644 sendbox/mcp-inspection/index.html create mode 100644 sendbox/overview/index.html create mode 100644 sendbox/package-supply-chain/index.html create mode 100644 sendbox/qualification/index.html create mode 100644 sendbox/roadmap/index.html create mode 100644 sendbox/secrets-migration/index.html create mode 100644 sendbox/security-model/index.html create mode 100644 sendbox/security-policy/index.html create mode 100644 sendbox/security-records-migration/index.html create mode 100644 sendbox/similar-tools/index.html create mode 100644 sitemap.xml create mode 100644 tests/check.test.mjs create mode 100644 tests/markdown.test.mjs create mode 100644 vendor/sendbox-fleet/CONTRIBUTING.md create mode 100644 vendor/sendbox-fleet/LICENSE create mode 100644 vendor/sendbox-fleet/README.md create mode 100644 vendor/sendbox-fleet/SECURITY.md create mode 100644 vendor/sendbox-fleet/SOURCE.json create mode 100644 vendor/sendbox-fleet/docs/architecture.md create mode 100644 vendor/sendbox-fleet/docs/assets/logo.svg create mode 100644 vendor/sendbox-fleet/docs/contract.md create mode 100644 vendor/sendbox-fleet/docs/deployment.md create mode 100644 vendor/sendbox-fleet/docs/development.md create mode 100644 vendor/sendbox-fleet/docs/roadmap.md create mode 100644 vendor/sendbox-fleet/docs/threat-model.md create mode 100644 vendor/sendbox/LICENSE create mode 100644 vendor/sendbox/README.md create mode 100644 vendor/sendbox/ROADMAP.md create mode 100644 vendor/sendbox/SECURITY.md create mode 100644 vendor/sendbox/SOURCE.json create mode 100644 vendor/sendbox/docs/alternatives.md create mode 100644 vendor/sendbox/docs/apple-runtime.md create mode 100644 vendor/sendbox/docs/architecture/agent-orchestration.md create mode 100644 vendor/sendbox/docs/architecture/authenticated-guest-protocol.md create mode 100644 vendor/sendbox/docs/architecture/egress-enforcement.md create mode 100644 vendor/sendbox/docs/architecture/execution-broker.md create mode 100644 vendor/sendbox/docs/architecture/git-branch-guard.md create mode 100644 vendor/sendbox/docs/architecture/governed-sessions.md create mode 100644 vendor/sendbox/docs/architecture/guest-artifact-bundles.md create mode 100644 vendor/sendbox/docs/architecture/guest-supervisor.md create mode 100644 vendor/sendbox/docs/architecture/interactive-terminal.md create mode 100644 vendor/sendbox/docs/architecture/kata-runtime.md create mode 100644 vendor/sendbox/docs/architecture/mcp-broker.md create mode 100644 vendor/sendbox/docs/architecture/native-project-analysis.md create mode 100644 vendor/sendbox/docs/architecture/package-registry-proxy.md create mode 100644 vendor/sendbox/docs/architecture/runtime-core.md create mode 100644 vendor/sendbox/docs/architecture/rust-cli-parity.md create mode 100644 vendor/sendbox/docs/architecture/safe-outputs.md create mode 100644 vendor/sendbox/docs/architecture/secrets-and-credential-broker.md create mode 100644 vendor/sendbox/docs/architecture/security-records.md create mode 100644 vendor/sendbox/docs/architecture/session-security-lifecycle.md create mode 100644 vendor/sendbox/docs/assets/logo.svg create mode 100644 vendor/sendbox/docs/cli-agents.md create mode 100644 vendor/sendbox/docs/cli-reference.md create mode 100644 vendor/sendbox/docs/configuration.md create mode 100644 vendor/sendbox/docs/contributing.md create mode 100644 vendor/sendbox/docs/dns-cold-start.md create mode 100644 vendor/sendbox/docs/hyperlight.md create mode 100644 vendor/sendbox/docs/installation.md create mode 100644 vendor/sendbox/docs/integrations.md create mode 100644 vendor/sendbox/docs/interactive-sessions.md create mode 100644 vendor/sendbox/docs/kata-containers.md create mode 100644 vendor/sendbox/docs/mcp-inspection.md create mode 100644 vendor/sendbox/docs/migration/secrets.md create mode 100644 vendor/sendbox/docs/migration/security-records.md create mode 100644 vendor/sendbox/docs/package-supply-chain.md create mode 100644 vendor/sendbox/docs/qualification.md create mode 100644 vendor/sendbox/docs/security-model.md create mode 100644 vendor/sendbox/docs/security/egress-enforcement-trust-boundary.md diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..9342139 --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,71 @@ +name: Website + +on: + pull_request: + branches: [main] + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: website-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + check: + name: Check and package + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Check out site + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Node + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version-file: .node-version + + - name: Unit tests + run: node --test tests/*.test.mjs + + - name: Package public files + run: node scripts/package.mjs "$RUNNER_TEMP/pages" + + - name: Check vendored docs, generated pages, links and accessibility + run: node scripts/check.mjs --site "$RUNNER_TEMP/pages" + + - name: Upload Pages artifact + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 + with: + path: ${{ runner.temp }}/pages + retention-days: 1 + include-hidden-files: true + + deploy: + name: Deploy GitHub Pages + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + needs: check + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + concurrency: + group: pages-production + cancel-in-progress: false + steps: + - name: Configure GitHub Pages + uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0 + + - name: Deploy site + id: deployment + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f60edb --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +.vendor-sync-*/ +.site-check-*/ +.DS_Store diff --git a/.node-version b/.node-version new file mode 100644 index 0000000..6f4247a --- /dev/null +++ b/.node-version @@ -0,0 +1 @@ +26 diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 0000000..e69de29 diff --git a/404.html b/404.html new file mode 100644 index 0000000..a4957b6 --- /dev/null +++ b/404.html @@ -0,0 +1,20 @@ + + + + + + + + Page not found | SendBox + + + +

404 / SendBox

This page is not here.

The address may have changed when the documentation was reorganized.

Go to the SendBox home page or browse the SendBox docs and Fleet docs.

+ + diff --git a/CNAME b/CNAME new file mode 100644 index 0000000..4aa05d9 --- /dev/null +++ b/CNAME @@ -0,0 +1 @@ +sendbox.synctune.it diff --git a/README.md b/README.md index 9552675..e5b5b78 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,28 @@ # sendbox.synctune.it -The website and documentation for [SendBox](https://github.com/sendbox-dev/sendbox) -and [SendBox Fleet](https://github.com/sendbox-dev/sendbox-fleet). +The website for [SendBox](https://github.com/sendbox-dev/sendbox) and +[SendBox Fleet](https://github.com/sendbox-dev/sendbox-fleet), published at +[sendbox.synctune.it](https://sendbox.synctune.it): a landing page, user and +contributor documentation for both projects, and a contributor guide. + +Plain HTML and CSS. No JavaScript, dependencies, install command, cookies or +third-party resources. The documentation pages are generated from the projects' +own Markdown, synced unchanged at a recorded commit, by small Node scripts that +use only Node's built-in modules. + +```sh +node scripts/sync.mjs # update vendor/ from the projects' main branches +node scripts/build.mjs # regenerate the documentation pages and sitemap +node --test tests/*.test.mjs # unit tests +node scripts/check.mjs # vendored docs, generated files, links, accessibility +``` + +- [Preview and Pages deployment](docs/deployment.md) +- [Content, synced documentation and checks](docs/maintenance.md) +- [Synced project documents](vendor/) (don't edit, see the maintenance guide) + +## License + +[MIT](LICENSE.md) for the website. The synced SendBox and SendBox Fleet documents +and logos in `vendor/`, `sendbox/`, `fleet/` and `assets/logos/` stay under the +projects' [Apache License 2.0](vendor/sendbox/LICENSE). diff --git a/assets/favicon.svg b/assets/favicon.svg new file mode 100644 index 0000000..e9d1950 --- /dev/null +++ b/assets/favicon.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/logos/sendbox-fleet.svg b/assets/logos/sendbox-fleet.svg new file mode 100644 index 0000000..eee6f49 --- /dev/null +++ b/assets/logos/sendbox-fleet.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/assets/logos/sendbox.svg b/assets/logos/sendbox.svg new file mode 100644 index 0000000..e9d1950 --- /dev/null +++ b/assets/logos/sendbox.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/styles.css b/assets/styles.css new file mode 100644 index 0000000..f14d4ca --- /dev/null +++ b/assets/styles.css @@ -0,0 +1,284 @@ +/* SendBox website. System fonts only; no external resources. */ +:root { + color-scheme: light dark; + --ink: #14161B; + --paper: #F5F7F8; + --green: #34D399; + --bg: #F5F7F8; + --surface: #FFFFFF; + --text: #14161B; + --muted: #4A545E; + --border: #CED6DC; + --link: #0A6B4B; + --code-bg: #E7ECEF; + --code-text: #14161B; + --focus: #0A6B4B; + --hero-bg: #14161B; + --hero-text: #F5F7F8; + --hero-muted: #B9C3CB; + --hero-accent: #34D399; + --button-bg: #34D399; + --button-text: #14161B; + --terminal-bg: #1F2A2E; + --terminal-text: #E6ECEF; + --terminal-muted: #B9C3CB; + --radius: 12px; + --font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #14161B; + --surface: #1B1F25; + --text: #EEF2F4; + --muted: #A9B4BD; + --border: #2E363E; + --link: #34D399; + --code-bg: #1F2A2E; + --code-text: #E6ECEF; + --focus: #34D399; + --hero-bg: #0F1115; + } +} + +*, *::before, *::after { box-sizing: border-box; } + +html { -webkit-text-size-adjust: 100%; text-size-adjust: 100%; } + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font: 1.0625rem/1.65 var(--font); +} + +img, svg { max-width: 100%; height: auto; } + +a { color: var(--link); text-underline-offset: 0.2em; text-decoration-thickness: 1px; } +a:hover { text-decoration-thickness: 2px; } + +:focus-visible { outline: 3px solid var(--focus); outline-offset: 3px; border-radius: 4px; } + +code, pre { font-family: var(--mono); font-size: 0.9em; } + +.wrap { width: min(74rem, 100% - 2.5rem); margin-inline: auto; } + +.skip-link { + position: absolute; + left: 1rem; + top: -4rem; + z-index: 10; + padding: 0.75rem 1rem; + background: var(--button-bg); + color: var(--button-text); + font-weight: 700; + border-radius: 8px; +} +.skip-link:focus { top: 1rem; } + +/* Header and footer */ +.site-header { background: var(--hero-bg); color: var(--hero-text); border-bottom: 1px solid #2E363E; } +.header-inner { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 0.5rem 1.5rem; padding-block: 0.75rem; } +.brand { display: inline-flex; align-items: center; gap: 0.6rem; color: var(--hero-text); font-weight: 700; font-size: 1.15rem; text-decoration: none; padding-block: 0.25rem; } +.brand img { width: 32px; height: 32px; } +.site-header :focus-visible { outline-color: var(--hero-accent); } +.site-nav ul { display: flex; flex-wrap: wrap; gap: 0.25rem 1.25rem; margin: 0; padding: 0; list-style: none; } +.site-nav a { display: inline-block; padding-block: 0.5rem; color: var(--hero-text); text-decoration: none; border-bottom: 2px solid transparent; } +.site-nav a:hover, .site-nav a[aria-current="page"], .site-nav a.is-active { border-bottom-color: var(--hero-accent); } + +.site-footer { margin-top: 4rem; padding-block: 2rem; border-top: 1px solid var(--border); color: var(--muted); font-size: 0.95rem; } +.footer-inner p { margin: 0.25rem 0; } + +/* Shared pieces */ +.eyebrow { margin: 0 0 0.5rem; color: var(--muted); font: 600 0.8rem/1.4 var(--mono); letter-spacing: 0.06em; text-transform: uppercase; } +.lede { font-size: 1.3rem; line-height: 1.45; } +.button { + display: inline-block; + padding: 0.7rem 1.15rem; + border: 2px solid var(--button-bg); + border-radius: 999px; + background: var(--button-bg); + color: var(--button-text); + font-weight: 700; + text-decoration: none; +} +.button.secondary { background: transparent; color: inherit; } +.button:hover { text-decoration: underline; } +.actions { display: flex; flex-wrap: wrap; gap: 0.75rem; margin-top: 1.5rem; } +.badge { display: inline-block; margin-left: 0.5rem; padding: 0.1rem 0.6rem; border: 1px solid var(--border); border-radius: 999px; color: var(--muted); font: 600 0.75rem/1.6 var(--mono); vertical-align: middle; } + +/* Home page */ +.hero { background: var(--hero-bg); color: var(--hero-text); padding-block: 3rem 3.5rem; } +.hero a:not(.button) { color: var(--hero-accent); } +.hero .eyebrow { color: var(--hero-muted); } +.hero-inner { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3rem; align-items: center; } +.hero-figure { margin: 0; min-width: 0; } +.hero-figure figcaption { margin-top: 0.75rem; font-size: 0.95rem; } +.hero h1 { margin: 0; font-size: clamp(2.3rem, 6vw, 3.8rem); line-height: 1.08; letter-spacing: -0.02em; } +.hero h1 span { color: var(--hero-accent); } +.hero p { max-width: 42rem; } +.hero .muted { color: var(--hero-muted); } +.hero .button.secondary { border-color: var(--hero-text); } +.hero :focus-visible { outline-color: var(--hero-accent); } +.terminal { + margin: 0; + padding: 1.25rem 1.4rem; + border: 1px solid #2E363E; + border-radius: var(--radius); + background: var(--terminal-bg); + color: var(--terminal-text); + font-size: 0.9rem; + line-height: 1.7; + overflow-x: auto; + white-space: pre; +} +.terminal .prompt { color: var(--hero-accent); } +.terminal .comment { color: var(--terminal-muted); } + +.section { padding-block: 4rem 0; } +.section > h2, .section-heading h2 { margin: 0 0 0.75rem; font-size: clamp(1.7rem, 3.5vw, 2.3rem); line-height: 1.2; } +.section-heading { max-width: 46rem; margin-bottom: 2rem; } +.section-heading p { margin: 0; color: var(--muted); } + +.products { display: grid; gap: 1.5rem; } +.product { + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 1.75rem; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); +} +.product-title { display: flex; align-items: center; gap: 1rem; } +.product-title img { width: 64px; height: 64px; } +.product h3 { margin: 0; font-size: 1.5rem; } +.product p { margin: 0; } +.product ul { margin: 0; padding-left: 1.2rem; } +.product .links { display: flex; flex-wrap: wrap; gap: 0.5rem 1.25rem; margin-top: auto; padding-top: 0.75rem; } +.product .links a { padding-block: 0.25rem; font-weight: 600; } + +.features { display: grid; gap: 1rem; margin: 0; padding: 0; list-style: none; } +.features li { padding: 1.25rem; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); } +.features h3 { margin: 0 0 0.35rem; font-size: 1.05rem; } +.features p { margin: 0; color: var(--muted); } + +.steps { display: grid; gap: 1.25rem; margin: 0; padding: 0; list-style: none; counter-reset: step; } +.steps > li { counter-increment: step; display: grid; grid-template-columns: minmax(0, 1fr); gap: 0.5rem; } +.steps h3 { margin: 0; font-size: 1.1rem; } +.steps h3::before { content: counter(step) ". "; color: var(--muted); } +.steps p { margin: 0; } + +.agents { display: flex; flex-wrap: wrap; gap: 0.5rem; margin: 0; padding: 0; list-style: none; } +.agents li { padding: 0.35rem 0.85rem; border: 1px solid var(--border); border-radius: 999px; background: var(--surface); } + +.callout { margin-top: 1.5rem; padding: 1rem 1.25rem; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); } +.callout p { margin: 0; } + +.fit { display: grid; gap: 1.5rem; } +.fit-card { padding: 1.5rem; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); } +.fit-card h3 { margin-top: 0; } +.fit-card p:last-child, .fit-card ul:last-child { margin-bottom: 0; } + +/* Documentation index */ +.project-hero { background: var(--hero-bg); color: var(--hero-text); padding-block: 3rem; } +.project-hero a:not(.button) { color: var(--hero-accent); } +.project-hero .eyebrow { color: var(--hero-muted); } +.project-hero .button.secondary { border-color: var(--hero-text); } +.project-hero :focus-visible { outline-color: var(--hero-accent); } +.project-hero-inner { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1.5rem; align-items: start; } +.project-hero h1 { margin: 0; font-size: clamp(2.2rem, 5vw, 3.2rem); line-height: 1.1; } +.project-hero p { max-width: 46rem; } +.docs-index { padding-top: 2.5rem; } +.doc-group { margin-bottom: 2.5rem; } +.doc-group h2 { margin: 0 0 1rem; font-size: 1.5rem; } +.doc-list { display: grid; gap: 0.75rem; margin: 0; padding: 0; list-style: none; } +.doc-list a { display: flex; flex-direction: column; gap: 0.2rem; height: 100%; padding: 1rem 1.15rem; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); text-decoration: none; } +.doc-list a:hover { border-color: var(--link); } +.doc-title { color: var(--link); font-weight: 700; text-decoration: underline; text-underline-offset: 0.2em; } +.doc-summary { color: var(--muted); font-size: 0.95rem; } +.doc-list.compact a { padding: 0.75rem 1rem; } + +/* Documentation pages */ +.docs-layout { display: grid; grid-template-columns: minmax(0, 1fr); gap: 2.5rem; padding-top: 1.5rem; } +.docs-main { min-width: 0; } +.breadcrumb ol { display: flex; flex-wrap: wrap; gap: 0.25rem 0.5rem; margin: 0; padding: 0; list-style: none; color: var(--muted); font-size: 0.9rem; } +.breadcrumb li + li::before { content: "/"; margin-right: 0.5rem; color: var(--muted); } +.breadcrumb a, .breadcrumb span { display: inline-block; padding-block: 0.25rem; } +.docs-menu-link { display: inline-block; margin-top: 0.5rem; padding-block: 0.25rem; font-size: 0.95rem; font-weight: 600; } +.docs-nav { padding: 1.25rem; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); font-size: 0.95rem; } +.nav-project { margin: 0 0 0.5rem; font-weight: 700; } +.nav-heading { margin: 1.25rem 0 0.35rem; color: var(--muted); font: 600 0.75rem/1.4 var(--mono); letter-spacing: 0.06em; text-transform: uppercase; } +.docs-nav ul { margin: 0; padding: 0; list-style: none; } +.docs-nav li a { display: block; padding: 0.3rem 0.5rem; border-radius: 6px; text-decoration: none; } +.docs-nav li a:hover { text-decoration: underline; } +.docs-nav a[aria-current="page"] { background: var(--code-bg); color: var(--text); font-weight: 700; } + +.prose { max-width: 50rem; } +.doc-header { margin: 1.25rem 0 1.5rem; } +.prose h1 { margin: 0; font-size: clamp(1.9rem, 4vw, 2.6rem); line-height: 1.15; letter-spacing: -0.01em; } +.prose h2 { margin: 2.5rem 0 0.75rem; padding-top: 0.5rem; font-size: 1.6rem; line-height: 1.25; border-top: 1px solid var(--border); } +.prose h3 { margin: 2rem 0 0.5rem; font-size: 1.25rem; line-height: 1.3; } +.prose h4, .prose h5, .prose h6 { margin: 1.5rem 0 0.5rem; font-size: 1.05rem; } +.prose h2, .prose h3, .prose h4, .prose span[id] { scroll-margin-top: 1rem; } +.prose p, .prose ul, .prose ol, .prose blockquote, .prose pre, .prose .table-scroll, .prose figure { margin: 0 0 1.1rem; } +.prose ul, .prose ol { padding-left: 1.5rem; } +.prose li > ul, .prose li > ol { margin: 0.35rem 0; } +.prose li + li { margin-top: 0.3rem; } +.prose li > p { margin-bottom: 0.5rem; } +.prose :not(pre) > code { padding: 0.1em 0.35em; border-radius: 5px; background: var(--code-bg); color: var(--code-text); overflow-wrap: anywhere; } +.prose pre { padding: 1rem 1.15rem; border: 1px solid var(--border); border-radius: var(--radius); background: var(--code-bg); color: var(--code-text); line-height: 1.55; overflow-x: auto; } +.prose pre code { font-size: 0.88rem; } +.prose blockquote { padding: 0.25rem 1.25rem; border-left: 0.25em solid var(--border); color: var(--muted); } +.prose hr { margin: 2.5rem 0; border: 0; border-top: 1px solid var(--border); } +.prose img { vertical-align: middle; } +.table-scroll { overflow-x: auto; border: 1px solid var(--border); border-radius: var(--radius); } +.prose table { width: 100%; border-collapse: collapse; font-size: 0.95rem; } +.prose th, .prose td { padding: 0.6rem 0.8rem; border-bottom: 1px solid var(--border); text-align: left; vertical-align: top; } +.prose thead th { background: var(--code-bg); } +.prose tbody tr:last-child td { border-bottom: 0; } +.prose .align-center { text-align: center; } +.prose .align-right { text-align: right; } +.diagram figcaption { margin-top: 0.4rem; color: var(--muted); font-size: 0.9rem; } + +.toc { margin: 0 0 2rem; padding: 1rem 1.25rem; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); } +.toc-title { margin: 0 0 0.35rem; font-weight: 700; } +.toc ol { margin: 0; padding-left: 1.25rem; columns: 2 16rem; column-gap: 2rem; } +.toc li { break-inside: avoid; } +.toc a { display: inline-block; padding-block: 0.15rem; } + +.source-note { margin-top: 2.5rem; padding: 1rem 1.25rem; border: 1px dashed var(--border); border-radius: var(--radius); color: var(--muted); font-size: 0.95rem; } +.source-note p { margin: 0; } +.pager { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 1rem; margin-top: 2rem; } +.pager a { display: flex; flex-direction: column; padding: 0.75rem 1rem; border: 1px solid var(--border); border-radius: var(--radius); font-weight: 600; text-decoration: none; } +.pager a:hover { border-color: var(--link); } +.pager-next { margin-left: auto; text-align: right; } +.pager-label { color: var(--muted); font-size: 0.8rem; font-weight: 400; } + +@media (min-width: 48rem) { + .products, .fit { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .features { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .doc-list { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .project-hero-inner { grid-template-columns: auto minmax(0, 1fr); } +} + +@media (min-width: 64rem) { + .hero { padding-block: 4.5rem 5rem; } + .hero-inner { grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr); } + .features { grid-template-columns: repeat(4, minmax(0, 1fr)); } + .doc-list { grid-template-columns: repeat(3, minmax(0, 1fr)); } + .docs-layout { grid-template-columns: 16rem minmax(0, 1fr); } + .docs-main { grid-column: 2; grid-row: 1; } + .docs-nav { grid-column: 1; grid-row: 1; position: sticky; top: 1rem; align-self: start; max-height: calc(100vh - 2rem); overflow-y: auto; } + .docs-menu-link { display: none; } +} + +@media (prefers-reduced-motion: no-preference) { + html { scroll-behavior: smooth; } +} + +@media print { + .site-header, .site-footer, .docs-nav, .pager, .skip-link, .docs-menu-link { display: none; } + .docs-layout { display: block; } +} diff --git a/contribute/index.html b/contribute/index.html new file mode 100644 index 0000000..515b78f --- /dev/null +++ b/contribute/index.html @@ -0,0 +1,90 @@ + + + + + + Contribute | SendBox + + + + + + + + + + + + + + + + +
+
+
+

Contributor guide

+

Contribute to SendBox

+

Both projects are Apache-2.0 and developed in the open on GitHub.

+

For larger changes, open an issue first to discuss the approach. Use synthetic data in tests and examples, and never commit real credentials, tokens or personal data. Report vulnerabilities privately, not in issues or pull requests.

+
+
+ +
+
+

SendBox

+

The CLI, runtimes and guest services live in sendbox-dev/sendbox. The Rust toolchain is pinned in the repository.

+ +

SendBox issues SendBox pull requests

+
+ +
+

SendBox Fleet

+

The governance service lives in sendbox-dev/sendbox-fleet. Its contract types come from sendbox-governance: change them in the SendBox repository first, then update the pin.

+ +

Fleet issues Fleet pull requests

+
+ +
+

Documentation and this website

+

The documentation pages on this site are published unchanged from each project's repository at a recorded commit. To fix or extend a page, change the document in its project repository; each page links to its source and has an edit link. The site is updated by syncing to a newer commit.

+

The website itself is plain HTML and CSS with no dependencies. Its source, sync and check scripts are in sendbox-dev/sendbox.synctune.it; see its maintenance guide.

+
+
+
+ + + + + diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..3c61129 --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,80 @@ +# Preview and deployment + +## No installation + +The repository contains the finished website. `index.html`, `404.html`, +`contribute/`, `assets/` and the generated `sendbox/` and `fleet/` directories +are served as they are. There is no package manager, framework or runtime +service, and no `package.json`. Do not run `npm install`. + +Node (the version in `.node-version`) is only needed to sync documentation, +regenerate pages and run checks. The scripts use Node's built-in modules only. + +## Preview + +Serve the published files with any static web server. With Node: + +```sh +node scripts/package.mjs /tmp/sendbox-site +``` + +Then, if Python 3 is already available: + +```sh +python3 -m http.server 8080 --bind 127.0.0.1 --directory /tmp/sendbox-site +``` + +Visit `http://127.0.0.1:8080`. Stop the server with Ctrl+C. Python is an +optional preview tool, not a website dependency. Serving the repository root +also works, but it exposes unpublished files such as `vendor/`. + +## GitHub Pages setup + +Complete this once. The workflow doesn't enable Pages, set the custom domain or +configure DNS. + +1. Enable Pages with **GitHub Actions** as the source (**Settings > Pages**, or + `gh api -X POST repos/sendbox-dev/sendbox.synctune.it/pages -f build_type=workflow`). +2. Set the custom domain to the hostname in `CNAME`, `sendbox.synctune.it` + (**Settings > Pages > Custom domain**). The `CNAME` file records the intended + hostname; for Actions deployments it doesn't configure the setting. +3. In the `synctune.it` DNS zone (Vercel DNS), add a `CNAME` record from + `sendbox` to `sendbox-dev.github.io`, the organization's Pages host without + a repository path. +4. When GitHub has issued the certificate, enable **Enforce HTTPS**. + +`synctune.it` has a wildcard record. Until the new `CNAME` replaces the cached +wildcard answer (TTL 1800 seconds), GitHub's DNS check and certificate request +can still see the old answer, so HTTPS can lag behind HTTP. Wait for that TTL +before removing and re-adding the custom domain; each failed certificate attempt +counts toward Let's Encrypt's rate limits. + +## Deployment workflow + +`.github/workflows/pages.yml` has two jobs. + +- **Check and package** runs the unit tests, copies the public files into a + temporary directory with `scripts/package.mjs`, and runs `scripts/check.mjs` + on exactly that directory: vendored documents against `SOURCE.json`, generated + files against the build, every local link and anchor, page structure and + accessibility basics, the sitemap and theme contrast. It runs on pull requests + to `main`, including drafts, with read-only permissions. +- **Deploy GitHub Pages** runs only on `main`. It deploys the artifact uploaded + by the checked job; only this job gets Pages write and OIDC permissions. + +Only the files listed in `scripts/package.mjs` are published. `vendor/`, +`scripts/`, `tests/`, `docs/`, the README and workflow files are not. + +Redeploy manually with **Actions > Website > Run workflow** on `main`. Newer +pushes to a pull request cancel its older runs; production deployments are +serialized without canceling one in progress. + +The workflow uses official GitHub actions pinned to full commit SHAs. It needs +no secrets beyond the standard `GITHUB_TOKEN` and GitHub's OIDC token. + +## Other static hosts + +Publish the output of `node scripts/package.mjs ` as static files. +Leave install and build commands empty. The site needs no environment +variables, rewrites or server functions. Directory URLs such as `/sendbox/` +must serve their `index.html`, and `404.html` should be the not-found page. diff --git a/docs/maintenance.md b/docs/maintenance.md new file mode 100644 index 0000000..9ca3502 --- /dev/null +++ b/docs/maintenance.md @@ -0,0 +1,109 @@ +# Content, synced documentation and checks + +## Layout + +| Path | What it is | +| --- | --- | +| `index.html` | The landing page, written by hand | +| `contribute/index.html` | The contributor guide for both projects, written by hand | +| `404.html` | A standalone not-found page with inline styles and absolute links | +| `assets/styles.css` | The only stylesheet, with light and dark themes. System fonts only | +| `sendbox/`, `fleet/` | Generated documentation pages. Don't edit | +| `assets/logos/`, `assets/favicon.svg`, `sitemap.xml` | Generated from `vendor/` and the catalogue. Don't edit | +| `vendor//` | The projects' documents, logo and license, synced unchanged | +| `vendor//SOURCE.json` | Source repository, branch, commit, commit date and SHA-256 of each synced file | +| `scripts/catalogue.mjs` | The single list of published documents, their routes, labels and groups | +| `scripts/markdown.mjs` | The Markdown renderer (the GitHub-flavored subset the documents use) | +| `scripts/layout.mjs` | Shared header and footer, documentation page and index templates | + +`index.html` and `contribute/index.html` contain `` and +`` regions. The build fills them with the shared header and +footer, so navigation stays identical on every page. Edit everything outside +those regions by hand. + +## Update the documentation + +The documentation is never edited here. Fix or extend a document in its +project repository, then sync: + +```sh +node scripts/sync.mjs # both projects, from main +node scripts/sync.mjs sendbox --ref +node scripts/build.mjs +node scripts/check.mjs +``` + +`sync.mjs` resolves the ref to one commit, downloads every catalogued file at +that commit and rewrites `vendor//` with a new `SOURCE.json`. It needs +network access to GitHub; set `GITHUB_TOKEN` to raise the API rate limit. It +also lists Markdown files upstream that the catalogue doesn't publish, such as +historical spikes. Review the rendered pages, then commit `vendor/` and the +generated files together in a pull request. + +To publish another document, add it to `scripts/catalogue.mjs` with a slug, +upstream path, label and, for the main groups, a one-line summary. Then sync and +build. Removing an entry removes its page on the next build. + +## How documents are rendered + +- The first level-1 heading becomes the page title. A README logo before it is + replaced by the page header. +- Heading anchors match GitHub's, so links such as + `installation.md#dependency-security-status` keep working. +- Relative links to published documents point to their pages. Links to anything + else (source files, unpublished docs) open on GitHub at the synced commit. +- Links to the projects' former `mbianchidev/...` repository URLs are rewritten + to `sendbox-dev`; GitHub links to published documents on `main` point to their + pages instead. +- Raw HTML is escaped, except `` anchors, images and `kbd`, `sub` and `sup`. + Images must be bundled; the build fails on an image that would load from + another site. +- Mermaid diagrams are shown as source with a link to GitHub's rendering, since + the site runs no JavaScript. + +Every documentation page names its source file and commit, and links to the +upstream edit page. + +## Checks + +```sh +node --test tests/*.test.mjs +node scripts/check.mjs +node scripts/check.mjs --external +``` + +`check.mjs` fails when a vendored file no longer matches `SOURCE.json`, when the +generated files are out of date, or when a published page has a broken local +link or anchor, a missing or duplicate title, more than one `h1`, skipped +heading levels, an image without `alt`, a link without text, duplicate ids, +unlabelled navigation landmarks, a missing skip link, a positive `tabindex`, +a script, a third-party resource or a wrong canonical URL. It also compares the +sitemap with the pages and checks theme colors against WCAG contrast (4.5:1 for +text, 3:1 for focus outlines) in both color schemes. + +`--external` also requests every external link. It needs network access, so CI +doesn't run it; run it before releases or when a sync adds links. + +Static checks don't replace a browser review. After layout changes, check +narrow (320px) and wide screens, keyboard focus, both color schemes and +reduced motion. + +## Content rules + +Describe what the tools do today; take facts from the synced documents and keep +status notes (such as pending releases) accurate. Don't invent release dates, +testimonials or screenshots. + +The site loads no scripts, analytics, cookies, web fonts or third-party +resources. Update the footer's privacy note if that ever changes. + +## Brand and rights + +The SendBox and SendBox Fleet logos come unchanged from each repository's +`docs/assets/logo.svg`, synced with the documents. Theme colors follow the +logos: ink `#14161B`, paper `#F5F7F8` and green `#34D399`. Use the bright green +on dark backgrounds only; links on light backgrounds use `#0A6B4B`. + +The website's own code and copy are MIT licensed. Synced documents and logos +remain under the projects' Apache License 2.0, a copy of which is synced into +each `vendor//LICENSE`. diff --git a/fleet/architecture/index.html b/fleet/architecture/index.html new file mode 100644 index 0000000..293c047 --- /dev/null +++ b/fleet/architecture/index.html @@ -0,0 +1,356 @@ + + + + + + Architecture | SendBox Fleet docs + + + + + + + + + + + + + + +
+
+ +All SendBox Fleet docs +
+
+

SendBox Fleet · Get started

+

Architecture

+
+ +

sendbox-fleet is the shared governance service for SendBox governed sessions +(mbianchidev/sendbox#87). +It is increment 2 of that issue: the authenticated, multi-user management API +and central authority that increment 1 deliberately left out.

+

It authenticates every /v1 caller (service tokens or OpenID Connect), +enforces project-scoped roles, verifies and publishes operator-signed +profiles, admits governed sessions, issues and checks credential grants, +records bounded and expiring exceptions and host-reported request outcomes, +and keeps a hash-chained central audit log whose signed heads can be anchored +outside the database. See roadmap.md for what remains and +deployment.md for running it.

+

Relationship to SendBox increment 1

+

Increment 1 lives in the sendbox +repository and works on a single host:

+
    +
  • An operator signs a governance profile (the maximum a session may do). The +host verifies it and binds its digest and revision into the session plan.
  • +
  • LocalGrantAuthority (in sendbox-governance) issues, authorizes, renews, +and revokes credential grants in process.
  • +
  • The host credential broker holds provider credentials and injects them into +approved upstream requests. Agents only ever see a placeholder.
  • +
+

Increment 2 moves the authority off the host, so several hosts and users +share one set of profiles, roles, grants, exceptions, and audit evidence. The +fleet implements the same GrantAuthority semantics over HTTP (both use +sendbox_governance::evaluate_request); a SendBox host whose operator +configuration has a fleet section uses its remote authority client instead +of the local one. See SendBox's +shared governance service +for the host side.

+
+
flowchart LR
+    subgraph host["SendBox host (worker)"]
+        vm["Agent VM<br/>(untrusted workload)"]
+        broker["Credential broker<br/>(holds provider credentials)"]
+    end
+    fleet["sendbox-fleet<br/>(authenticates, authorizes, audits)"]
+    db[("PostgreSQL")]
+    people["Operators and project members"]
+    provider["Model provider API"]
+
+    vm -- "request with placeholder credential" --> broker
+    broker -- "admit / grant / authorize / revoke" --> fleet
+    broker -- "request with injected credential" --> provider
+    people -- "profiles, roles, exceptions, audit" --> fleet
+    fleet --> db
+
Diagram source (Mermaid). View it rendered on GitHub.
+
+

Trust boundaries

+
    +
  1. Workload to host broker. The agent VM is untrusted. It never receives +provider credentials, and it cannot choose the principal, project, session, +policy revision, or upstream that a request is attributed to. The broker +builds every RequestContext from trusted host state.
  2. +
  3. Host to fleet. A SendBox host is an authenticated worker principal. +The fleet never holds provider credentials: credential injection stays in +the host broker, and the fleet only decides (admission, grants, +per-request authorization) and records evidence. A +compromised fleet can therefore authorize misuse but cannot leak provider +keys; a compromised host is limited to the sessions and grants the fleet +issued to it.
  4. +
  5. People to fleet. Operators and project members are authenticated user +principals. What they may do is decided by project-scoped roles.
  6. +
  7. Fleet to database. The database stores identifiers, digests, signed +profile bytes, and audit evidence. It stores no credentials, tokens, +authorization headers, or request bodies; there are no columns for them.
  8. +
+

Authentication is separate from authorization

+
    +
  • Authentication answers "who is calling". Every /v1 request passes +through auth::require_bearer before routing, so an unauthenticated +request is rejected with 401 before its body is read. Only +Authorization: Bearer <token> is accepted. Identity headers such as +X-Forwarded-User, X-Remote-User, or X-Sendbox-Principal are ignored. +Two kinds of bearer token are accepted:

    +
      +
    • Service tokens (sbf_…), issued with sendbox-fleet admin token issue or exchanged at POST /v1/tokens. Only their SHA-256 is stored, +and a token works while it is unexpired (at most 90 days), unrevoked, and +its principal is not disabled.
    • +
    • Identity-provider JWTs from an issuer in FLEET_OIDC_CONFIG. The +signature must verify with the issuer's published keys, and iss, aud, +exp, nbf, iat, required claims, and email_verified (for email +principals) must pass. The principal is <prefix>:<claim>; it must exist, +be active, and have the issuer's kind, unless the issuer may auto-provision +it (with no roles). See deployment.
    • +
    +

    A failed token lookup or unreachable key set is 503, never an implicit +allow. Repeated failures from one peer address, and too many requests from +one principal, get 429 with Retry-After.

  • +
  • Token exchange. POST /v1/tokens turns an identity-provider sign-in +into a service token for hosts (sendbox governance login). Only JWT +callers may exchange, so a service token cannot mint another. Lifetime +defaults to FLEET_TOKEN_TTL_SECONDS and is capped by +FLEET_TOKEN_MAX_TTL_SECONDS; a principal holds at most 20 live tokens.

  • +
  • Authorization answers "may this caller do this". It combines the caller +kind (user or worker), the fleet-wide operator flag, project roles, +the current profile revision, admitted sessions, grants, and exceptions, +all read from the database.

  • +
  • Workload identity fields are never authoritative. A binding or grant +principal must equal the authenticated caller; a host cannot claim another +identity. local-user: principals belong to single-host increment 1 and are +rejected by both the API and the schema.

  • +
+

Roles

+
+ + + + + + + + + +
WhoMay
Operator (fleet-wide, users only)Publish profiles, raise minimum revisions, create projects with a first owner, manage any project's roles, revoke grants and exceptions, read and verify all audit
ownerAssign and remove roles (never leaving the project without an owner), approve or reject exceptions, run sessions
adminApprove or reject exceptions, revoke grants (operator_revoked, policy_changed), run sessions
memberRun governed sessions, request exceptions
viewerRead roles, exceptions, and the project's audit events
+
+

Workers never manage roles, profiles, or exceptions. A principal runs +sessions as itself: it needs member or higher in the project.

+

Request flow

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
StepEndpointChecks
IdentifyGET /v1/whoamiReturns the authenticated principal, kind, and operator flag
Admit a sessionPOST /v1/sessions:admitBinding principal is the caller; binding names this authority (FLEET_AUTHORITY_ID); caller holds member or higher; profile reference is the current revision (at or above the minimum, unexpired, digest matches); brokered services exist in the profile; every bound exception is approved, unrevoked, unexpired, for this project and principal (or project-wide), bound to this exact revision, and permitted by it. Records the canonical binding
End a sessionPOST /v1/sessions/{session}:endSession principal only; revokes every live grant with the matching session reason
Issue a grantPOST /v1/grantsCaller and request match the admitted session's binding exactly; session not ended; service admitted; methods and path prefixes inside the profile service; profile current; bound exceptions still valid. Lease from the profile; hard expiry capped by the profile TTL, profile expiry, the earliest bound exception expiry, and 7 days
Authorize a requestPOST /v1/authorizeevaluate_request against shared state, plus: the caller is the grant principal, the session is not ended, bound exceptions are still valid. Every decision is audited with a redacted target
Renew a leasePOST /v1/grants/{grant}:renewGrant principal; not revoked or expired; lease not lapsed; session admitted; profile current; exceptions valid. Lease never exceeds the hard expiry or the earliest exception expiry
Revoke a grantPOST /v1/grants/{grant}:revokeSession reasons by the grant principal; operator_revoked and policy_changed by an admin, owner, or operator. New requests deny at once; the grace window is the profile's revocation_grace_seconds (at most 60)
Publish a profilePUT /v1/profiles/{profile}Operator; body is the exact YAML plus the sendbox.governance-signatures bundle that sendbox governance sign writes; signatures must satisfy FLEET_PROFILE_TRUST; revisions only increase
Read a profileGET /v1/profiles/{profile}[?revision=N]Any caller; the current revision is the newest whose not_before_unix has passed
Raise the minimumPUT /v1/profiles/{profile}/minimum-revisionOperator; minimums only rise; older revisions, and everything bound to them, become stale
Create a projectPOST /v1/projectsOperator; the owner must be an active principal
List or change rolesGET / POST /v1/projects/{project}/roles, DELETE …/roles/{principal}Listing needs any role (or operator); changes need owner (or operator); the last owner cannot be removed or demoted
Request an exceptionPOST /v1/exceptionsUser with member or higher; scope is a denial the current revision lists under exceptions; optional principal must be a member; expiry in the future, within the profile's exceptions.max_ttl_seconds (at most 7 days) and before the profile expires
Decide an exceptionPOST /v1/exceptions/{id}:approve / :rejectUser with owner or admin, not the requester; approval only while unexpired and its revision is still current
Revoke an exceptionPOST /v1/exceptions/{id}:revokeRequester, owner, admin, or operator. Sessions admitted with it are denied on their next request or renewal
List exceptionsGET /v1/exceptions?project=…&state=active|pending|all, GET /v1/exceptions/{id}Any role in the project (or operator)
Query audit eventsGET /v1/audit/eventsOperators read everything; others must pass a project in which they hold a role. Cursor pagination
Verify the chainGET /v1/audit/verifyOperator; recomputes every hash and link
Signed chain headGET /v1/audit/headOperator; the current sequence and hash signed with FLEET_AUDIT_SIGNING_KEY (503 without it)
Exchange a sign-inPOST /v1/tokensIdentity-provider caller only; ttl_seconds in 60 to the maximum; returns the token once with Cache-Control: no-store
List or revoke tokensGET /v1/tokens, DELETE /v1/tokens/{id}Callers see and revoke their own tokens (never the secret); operators may revoke any
Report an outcomePOST /v1/grants/{grant}:outcomeGrant principal; service must match the grant. Records the redacted method, path, outcome, reason, status, sizes, and duration as request.outcome. Outcomes are evidence only and never change a grant or a decision
+
+

Project identifiers contain a slash (github:owner/repo), so clients +percent-encode it in paths: /v1/projects/github:owner%2Frepo/roles.

+

HTTP responses

+

Errors use RFC 9457 application/problem+json with type: about:blank, the +standard reason phrase as title, and a specific detail.

+
+ + + + + + + + + + + + + +
StatusWhen
400Body, path, or query does not match the contract
401Missing, malformed, or unaccepted bearer token (with WWW-Authenticate: Bearer)
403Authenticated, but the role, kind, operator flag, profile, or signer check refuses it
404 / 405Unknown resource or path, or unsupported method
409Stale profile revision, stale or inactive exception, already-decided exception, ended session, duplicate admission, last owner
413 / 415Body too large (64 KiB, 1 MiB for profile publication) or not JSON
429Rate limit; Retry-After gives the seconds to wait
500Internal failure; the cause is logged, never returned
503Authentication or /readyz cannot reach the database or identity-provider keys, profile publication without FLEET_PROFILE_TRUST, or GET /v1/audit/head without a signing key
+
+

A per-request authorization denial is a 200 with {"decision": "deny", "reason": …}; hosts deny on any other answer.

+

GET /healthz (liveness) and GET /readyz (database round trip) are +unauthenticated and reveal nothing beyond availability.

+

Persistence

+

migrations/postgres and migrations/sqlite define the same schema; the +server applies the matching set at startup, or with FLEET_MIGRATE=false +only checks that every migration was applied (by sendbox-fleet admin migrate under a schema-owner role). PostgreSQL is the shared deployment +target; SQLite is for local development and tests.

+
+ + + + + + + + + + + + + + + + +
TableHolds
principalsAuthenticated users and workers (never local-user:), with the operator flag
api_tokensSHA-256 of each service token (admin-issued or exchanged), description, expiry (at most 90 days), revocation
projectsgithub:owner/repo or path-sha256: projects
role_bindingsOne project-scoped role per principal per project
profilesExact signed bytes, digest, signatures, validity window per revision
profile_minimum_revisionsOldest revision still accepted per profile
sessionsAdmitted sessions with their canonical binding and digest
credential_grantsGrant scope, lease, hard expiry, generation; no credential material
revocationsReason, actor, bounded grace window
exceptionsOne liftable denial (command, domain, network), reason, requester, approver, expiry, revocation, exact profile revision
session_exceptionsExceptions each session was admitted with
audit_eventsAppend-only, hash-chained evidence with a redacted target, the exception concerned, and a short non-secret detail
+
+

Constraints carry the invariants the database can check: identifier grammar, +7-day grant and exception lifetimes, 90-day tokens, a 60-second revocation +grace, approvers who differ from requesters, grants whose principal, project, +binding, and profile must equal their session's (composite foreign key), and +audit rows that must extend the chain and can never be updated or deleted +(triggers).

+

Writers are serialized (SQLite BEGIN IMMEDIATE, PostgreSQL transaction +advisory lock), so check-then-write decisions cannot race. Every state change +and the audit event that records it commit in one transaction; a refused, +security-relevant request commits only its audit event.

+

Audit

+

Each event records the actor (the authenticated caller, or cli:admin), the +principal, project, session, grant, exception, and profile revision it +concerns, the decision and deny reason, an outcome, a redacted target +(METHOD service/path, never a query string), and a short detail such as +role=admin or scope=domain:gist.github.com. Credentials, tokens, headers, +request or response bodies, and exception reasons are never recorded.

+

event_hash is the SHA-256 of the RFC 8785 canonical JSON of the event as +returned by GET /v1/audit/events without event_hash (so it includes +previous_hash). The first event links to 64 zeros. GET /v1/audit/verify +recomputes the chain.

+

The chain alone cannot stop someone who can rewrite the table and recompute +every hash, such as a database owner. With FLEET_AUDIT_SIGNING_KEY, the +service signs chain heads (sendbox-fleet-audit-head v1: authority, +sequence, event hash, time) with an Ed25519 key in SendBox's provenance +envelope. With FLEET_AUDIT_ANCHOR_DIR, it writes one to that directory at +startup and on every interval in which the chain advanced, never overwriting +an anchor. sendbox-fleet admin audit verify --identity … --anchor … +recomputes the chain and checks each anchor's signature and that the database +still holds its hash at its sequence.

+

Other audit events added for authentication: principal.provisioned, +token.issued, and token.revoked (token ids, never tokens).

+

Logging

+

Structured JSON lines go to stdout and to sendbox-fleet.YYYY-MM-DD.log in +FLEET_LOG_DIR, rotated at each UTC day and at FLEET_LOG_MAX_BYTES, and +pruned after 30 days. Request +bodies, headers, and query strings are never logged. Details in +development.md.

+

Code layout

+
crates/fleet-server/src/
+  main.rs          process entry: serve (default) or `admin` subcommands
+  admin.rs         bootstrap: principals, tokens, projects, audit keys, migrate
+  server.rs        app assembly, startup, graceful shutdown, background tasks
+  config.rs        environment configuration and profile trust loading
+  state.rs         shared state: database, clock, random ids, authority id, trust, limits
+  oidc.rs          identity-provider configuration and JWT/JWKS verification
+  anchor.rs        signed audit heads, anchoring, anchor verification
+  ratelimit.rs     per-principal and per-peer token buckets
+  metrics.rs       Prometheus counters and the metrics listener
+  logging.rs       subscriber setup and request logging middleware
+  logging/rotation.rs, logging/retention.rs
+  db.rs            pools, migrations, readiness, backend-neutral transactions and rows
+  governance.rs    stored roles, profiles, sessions, grants, and exceptions
+  audit.rs         hash-chained append, queries, chain verification
+  problem.rs       RFC 9457 problem responses
+  auth.rs          bearer middleware, service-token and identity-provider authenticators
+  routes/          health probes and the /v1 API
+migrations/{postgres,sqlite}/
+deploy/postgres/roles.sql   least-privilege owner and runtime roles
+
+ + +
+ +
+
+ +
+ + diff --git a/fleet/contract/index.html b/fleet/contract/index.html new file mode 100644 index 0000000..85e92a7 --- /dev/null +++ b/fleet/contract/index.html @@ -0,0 +1,181 @@ + + + + + + Shared contract | SendBox Fleet docs + + + + + + + + + + + + + + +
+
+ +All SendBox Fleet docs +
+
+

SendBox Fleet · Get started

+

Shared contract

+
+ +

SendBox hosts and this service must agree byte-for-byte on identities, +profile references, session bindings, grants, request contexts, and +decisions. That agreement lives in one crate, sendbox-governance, in the +sendbox repository +(crates/sendbox-governance). This service depends on it instead of +redefining any of those types.

+

How it is pinned

+
# Cargo.toml (workspace)
+sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", branch = "main" }
+sendbox-security = { git = "https://github.com/mbianchidev/sendbox", branch = "main" }
+

sendbox-security supplies the signing envelope and trust store used for +profile signatures and audit heads.

+
    +
  • The dependency tracks sendbox main, and Cargo.lock records the exact +commit. CI builds with --locked, so every build sees the same contract +until the lockfile moves.
  • +
  • Dependabot checks sendbox main daily and opens +one pull request (group sendbox-contract) that moves Cargo.lock to the +latest commit. The +auto-merge workflow enables +auto-merge when that pull request updates nothing but sendbox-governance +and sendbox-security, and branch protection merges it only after every CI +job passes. A contract change that breaks this service leaves the pull +request open with failing checks for a maintainer to fix.
  • +
  • Both crates inherit versions from the sendbox workspace and depend on +sendbox-core by path; Cargo resolves all three from the same git checkout, +so they always share one commit.
  • +
  • Only main is tracked, so the recorded commit cannot disappear when sendbox +feature branches are rewritten or deleted. A pull request that needs an +unmerged contract change may track the sendbox pull request branch while +both are in review. CI's last step, +scripts/check-contract-pin.sh, fails +until every SendBox crate is locked to a sendbox main commit again (it also +rejects rev/tag pins and local path patches), so such a pull request +cannot merge. After the sendbox pull request merges, set branch = "main" +and run cargo update -p sendbox-governance -p sendbox-security.
  • +
+

To move the lockfile by hand, to the latest main commit or to a specific one:

+
cargo update -p sendbox-governance -p sendbox-security
+cargo update -p sendbox-governance --precise <commit-sha>   # moves all three crates
+scripts/check-contract-pin.sh
+cargo test --locked --workspace
+

What the API reuses

+
+ + + + + + + + + + + + + + + + + +
Contract typeUsed by
api::CallerIdentityGET /v1/whoami response
api::SessionAdmissionRequest, api::SessionAdmission, GovernanceBindingPOST /v1/sessions:admit body and response
api::SessionEndPOST /v1/sessions/{session}:end body
GrantRequest, CredentialGrantPOST /v1/grants body and response
GrantId:renew and :revoke path parameter; renew response is a CredentialGrant
api::RevokeGrantRequest, RevocationReason:revoke body
RequestContext, Decision, DenyReason, evaluate_requestPOST /v1/authorize body, response, and decision rules
ProfileId, ProfileRef, GovernanceProfile, check_current/v1/profiles/{profile_id}; publication bodies are parsed with GovernanceProfile::parse
PolicyException, ExceptionScope, ExceptionId, api::ExceptionList/v1/exceptions responses; scopes are checked with GovernanceProfile::permits_exception
ProjectId, PrincipalIdRole, exception, and audit endpoints
Sha256Digest, canonical_digestDigests in responses, binding storage, and audit event hashes
api::TokenRequest, api::IssuedTokenPOST /v1/tokens body and response
api::RequestOutcomeReport, api::ReportedOutcomePOST /v1/grants/{grant}:outcome body, checked with RequestOutcomeReport::validate
+
+

Validation is the contract's own: identifier grammars, deny_unknown_fields, +GovernanceBinding::validate, validate_method, validate_path_prefix, and +GovernanceProfile::parse. Invalid input is a 400 problem.

+

Wire types a SendBox host also uses live in sendbox_governance::api. Types +only people use live here, in the route module that uses them: +CreateProject, ProjectRole and RoleBinding, ExceptionRequest, +ProfilePublication and MinimumRevision, TokenSummary and TokenList, +and the audit query, page, event, and signed-head types. Profile signatures use SendBox's signing envelope +(sendbox_security::provenance::DetachedSignature in a +sendbox.governance-signatures bundle), verified with the same trust store +code as hosts.

+

Versioning

+
    +
  • sendbox_governance::CONTRACT_VERSION (currently 2, which added +exceptions to the session binding) is the wire and digest version. GovernanceBinding and CredentialGrant carry it, and validation +rejects any other value. The server logs it at startup.
  • +
  • Contract structs use deny_unknown_fields, so adding a field is a breaking +change for older peers. Any change to a contract type or to how digests are +computed requires bumping CONTRACT_VERSION in the sendbox repository and +then updating this pin; hosts and the fleet must be upgraded together or +support both versions during the transition.
  • +
  • The /v1 path prefix versions the HTTP API surface (routes, fleet-only +types, problem format). It changes independently of CONTRACT_VERSION.
  • +
+
+ + +
+ +
+
+ +
+ + diff --git a/fleet/contributing/index.html b/fleet/contributing/index.html new file mode 100644 index 0000000..28679f8 --- /dev/null +++ b/fleet/contributing/index.html @@ -0,0 +1,103 @@ + + + + + + Contributing | SendBox Fleet docs + + + + + + + + + + + + + + +
+
+ +All SendBox Fleet docs +
+
+

SendBox Fleet · Contribute

+

Contributing

+
+ +
    +
  1. Read docs/architecture.md and the +threat model; changes must keep the trust boundaries +(no provider credentials in this service, bearer-only authentication, +workload-supplied identity never authoritative).
  2. +
  3. Contract types come from sendbox-governance. Change them in the sendbox +repository first, then update the pin (docs/contract.md). +A pull request may track a sendbox branch during review, but CI blocks the +merge until it tracks sendbox main again.
  4. +
  5. Schema changes need matching PostgreSQL and SQLite migrations and a test.
  6. +
  7. Before opening a pull request, run the checks in +docs/development.md. CI runs the same +commands plus PostgreSQL and cargo audit jobs.
  8. +
  9. Use synthetic data in tests and examples; never commit real credentials, +tokens, or personal data.
  10. +
+
+ + +
+ +
+
+ +
+ + diff --git a/fleet/deployment/index.html b/fleet/deployment/index.html new file mode 100644 index 0000000..2bec9d8 --- /dev/null +++ b/fleet/deployment/index.html @@ -0,0 +1,318 @@ + + + + + + Deployment | SendBox Fleet docs + + + + + + + + + + + + + + +
+
+ +All SendBox Fleet docs +
+
+

SendBox Fleet · Get started

+

Deployment

+
+ +

How to run sendbox-fleet for a team. Development covers +local runs; this page covers a shared, production-like setup. Every setting +here is an environment variable listed in +development.md.

+
+
flowchart LR
+    hosts["SendBox hosts and people"] -- "HTTPS" --> proxy["Reverse proxy<br/>(TLS, request limits)"]
+    proxy -- "HTTP on a private network" --> fleet["sendbox-fleet<br/>FLEET_MIGRATE=false"]
+    fleet -- "sendbox_fleet_app role" --> pg[("PostgreSQL")]
+    fleet -. "JWKS over HTTPS" .-> idp["Identity providers"]
+    fleet -- "signed audit heads" --> anchors[("Write-once storage")]
+    prom["Prometheus"] -- "FLEET_METRICS_BIND" --> fleet
+
Diagram source (Mermaid). View it rendered on GitHub.
+
+

Checklist

+
    +
  1. PostgreSQL with the least-privilege roles below. SQLite is for development +only.
  2. +
  3. A reverse proxy that terminates TLS. The service itself speaks plain HTTP.
  4. +
  5. FLEET_AUTHORITY_ID set to the value every host puts under authority:.
  6. +
  7. FLEET_PROFILE_TRUST naming the operators who sign profiles.
  8. +
  9. FLEET_OIDC_CONFIG for people and CI, or admin-issued tokens only.
  10. +
  11. An audit signing key and an anchor directory on storage the database +administrators cannot rewrite.
  12. +
  13. Metrics on a private address, log shipping from stdout or FLEET_LOG_DIR, +and database backups.
  14. +
+

TLS and the reverse proxy

+

Bearer tokens must only travel over TLS. Run the service on a private address +(FLEET_BIND=10.0.0.5:8080, or the Compose network) behind a proxy such as +nginx, Caddy, Envoy, or a cloud load balancer that:

+
    +
  • terminates TLS 1.2 or later with a certificate hosts trust;
  • +
  • forwards the Authorization header unchanged and adds no identity headers +(the service ignores X-Forwarded-User and similar anyway);
  • +
  • does not cache responses (token exchange already sends +Cache-Control: no-store);
  • +
  • limits request rates per client address.
  • +
+

The service rate limits per process: FLEET_RATE_LIMIT_PER_MINUTE requests +per authenticated principal, and FLEET_AUTH_FAILURES_PER_MINUTE failed +authentications per peer address. Behind a proxy every client shares the +proxy's address, so the failure limit throttles all clients together when one +of them sends bad tokens. Either set FLEET_AUTH_FAILURES_PER_MINUTE=0 and +rely on the proxy's per-client limit, or raise it well above normal traffic. +X-Forwarded-For is not trusted.

+

Limits are per instance. With several instances, the effective limit is the +per-instance value times the instance count.

+

PostgreSQL roles and migrations

+

deploy/postgres/roles.sql creates two +roles:

+
+ + + + + + +
RoleCan
sendbox_fleet_ownerOwns the schema; runs sendbox-fleet admin migrate
sendbox_fleet_appReads and writes operational tables; only SELECT and INSERT on audit_events; only SELECT on _sqlx_migrations; cannot create, alter, or drop anything
+
+
psql -v ON_ERROR_STOP=1 -d sendbox_fleet -f deploy/postgres/roles.sql   # as a superuser
+psql -d sendbox_fleet -c "ALTER ROLE sendbox_fleet_owner PASSWORD '…'"
+psql -d sendbox_fleet -c "ALTER ROLE sendbox_fleet_app PASSWORD '…'"
+FLEET_DATABASE_URL=postgres://sendbox_fleet_owner:…@db/sendbox_fleet sendbox-fleet admin migrate
+psql -v ON_ERROR_STOP=1 -d sendbox_fleet -f deploy/postgres/roles.sql   # grants on the new tables
+

Then run the service as sendbox_fleet_app with FLEET_MIGRATE=false. It +refuses to start while a migration is missing and names the fix. Admin +commands run with FLEET_MIGRATE=false also check instead of migrating, so +they work with the app role. On upgrade: stop the old version, run +admin migrate as the owner, rerun roles.sql, then start the new version.

+

The audit triggers stop the app role and anyone without ALTER on the table. +The owner and superusers can still disable them, which is what audit +anchoring is for.

+

Identity providers

+

FLEET_OIDC_CONFIG points at a YAML file of trusted issuers. Without it, only +service tokens from sendbox-fleet admin token issue authenticate.

+
issuers:
+  # People: the principal is `oidc:<verified email>`.
+  - issuer: https://accounts.google.com
+    audiences: ["123456789-example.apps.googleusercontent.com"]
+    kind: user
+    principal_claim: email
+    principal_prefix: oidc
+  # CI: GitHub Actions jobs from one organization, as `github-actions:<repository_id>`.
+  - issuer: https://token.actions.githubusercontent.com
+    audiences: [sendbox-fleet]
+    kind: worker
+    principal_claim: repository_id
+    principal_prefix: github-actions
+    required_claims:
+      repository_owner: example
+    auto_provision: true
+
+ + + + + + + + + + + + + + + + +
FieldDefaultMeaning
issuerrequiredExact iss; https:// (or http:// on loopback for tests)
audiencesrequiredAt least one must appear in aud
kindrequireduser or worker; an existing principal of the other kind is refused
principal_claimrequiredClaim that names the principal; string or number
principal_prefixrequiredUnique per issuer, lowercase letters or -, not local-user
require_email_verifiedtrue when the claim is emailRequire email_verified: true
auto_provisionfalseCreate unknown principals on first sign-in, with no roles and no operator flag, audited as principal.provisioned
jwks_urifrom discoverySkip /.well-known/openid-configuration
algorithmsRS256, ES256, EdDSAAccepted signature algorithms
required_claimsnoneClaims that must equal these strings
jwks_cache_seconds600Key cache lifetime (60 to 86400)
leeway_seconds60Clock skew for exp, nbf, and iat (at most 300)
+
+

Keys are fetched over HTTPS with the system CA bundle, without proxies or +redirects, and cached. An unknown key id refreshes the key set at most every +30 seconds. If keys cannot be fetched and none are cached, callers get 503; +cached keys keep working through an outage.

+

Keep auto_provision off for people unless anyone who can sign in to the +provider may hold a principal; roles still have to be granted per project. +For CI, required_claims is what limits which repositories can sign in.

+

Signing in from a SendBox host

+

A JWT from a configured issuer authenticates any /v1 call directly, but +provider tokens are short-lived. Hosts exchange one for a fleet service token:

+
my-idp print-id-token | sendbox governance login
+

POST /v1/tokens accepts only identity-provider callers, so a leaked service +token cannot mint more. Exchanged tokens last FLEET_TOKEN_TTL_SECONDS +(12 hours) unless the request asks for less or up to +FLEET_TOKEN_MAX_TTL_SECONDS (7 days); a principal holds at most 20 live +tokens. GET /v1/tokens lists the caller's tokens and +DELETE /v1/tokens/{id} revokes one; operators can revoke any token.

+

In GitHub Actions, request an ID token with the fleet's audience (the job +needs permissions: id-token: write), then pass it to sendbox governance login --identity-token-file.

+

Audit anchoring

+

The audit chain detects edits by anyone who cannot recompute every later hash. +A database owner can. Anchors fix that: a signed copy of the chain head, kept +where the database administrators cannot rewrite it.

+
sendbox-fleet admin audit keygen --output /etc/sendbox-fleet/audit.key > audit-identity.json
+

The key file is created with mode 0600; the service refuses to load a key +that group or others can access. Keep it off the database host and out of database backups; publish +audit-identity.json to whoever verifies the log.

+
+ + + + + + +
SettingEffect
FLEET_AUDIT_SIGNING_KEYEnables GET /v1/audit/head (operators): the current head, signed
FLEET_AUDIT_ANCHOR_DIRWrites audit-head-<sequence>.json there at startup and every FLEET_AUDIT_ANCHOR_INTERVAL_SECONDS (default 3600) when the chain has advanced
+
+

Point FLEET_AUDIT_ANCHOR_DIR at write-once storage, such as an object-store +bucket with object lock mounted into the container, or a directory another +system collects. Anchors are never overwritten. Without a mounted directory, +an external job can call GET /v1/audit/head or run +sendbox-fleet admin audit anchor --output DIR.

+

To check the log:

+
sendbox-fleet admin audit verify --identity audit-identity.json \
+  --anchor anchors/audit-head-00000000000000001234.json …
+

It recomputes the chain and checks that each anchor's signature verifies and +that the database still holds the anchored hash at that sequence. It prints +one JSON line per result and exits non-zero on any failure.

+

Metrics

+

Set FLEET_METRICS_BIND (for example 10.0.0.5:9090) to serve Prometheus +text at /metrics on a second listener. It has no authentication, so keep it +on a private network; it is never served on FLEET_BIND.

+
+ + + + + + + + + + + +
MetricTypeMeaning
fleet_http_requests_total{class}counterRequests by status class (2xx, 4xx, …)
fleet_http_request_duration_seconds_sum / _countsummaryRequest time
fleet_auth_failures_totalcounterRejected bearer tokens
fleet_rate_limited_totalcounter429 answers
fleet_authorization_decisions_total{decision,reason}counter/v1/authorize results by deny reason
fleet_audit_events_totalcounterEvents appended by this process
fleet_audit_sequencegaugeHighest audit sequence
+
+

Labels never contain principals, projects, sessions, or tokens. Useful alerts: +a rising 5xx rate, fleet_auth_failures_total spikes, and +fleet_authorization_decisions_total{reason="authority_unavailable"}.

+

Logs

+

Logs go to stdout and FLEET_LOG_DIR. Files rotate at UTC midnight and when +they reach FLEET_LOG_MAX_BYTES (100 MiB), and are pruned after +FLEET_LOG_RETENTION_DAYS. In containers, ship stdout and keep the volume +small. See development.md.

+

Backups and restore

+
    +
  • PostgreSQL: pg_dump --format=custom sendbox_fleet on a schedule, or +continuous archiving for point-in-time recovery. Store dumps encrypted and +away from the database host.
  • +
  • SQLite (development only): sqlite3 sendbox-fleet.db ".backup copy.db" +while the service runs.
  • +
  • Back up FLEET_PROFILE_TRUST, FLEET_OIDC_CONFIG, and the audit identity +with the deployment configuration. Back up the audit signing key separately.
  • +
+

The database holds token digests, not tokens, so a restored backup cannot be +used to sign in. Tokens revoked after the backup become valid again after a +restore, as do principals disabled after it: revoke and disable them again.

+

After a restore, run sendbox-fleet admin audit verify with the newest +anchors. Anchors newer than the backup fail with "the database no longer +holds this sequence", which documents exactly what the restore lost.

+

Compose

+

docker-compose.yml passes every setting through +from .env and mounts a fleet-anchors volume at +/var/lib/sendbox-fleet/anchors. Mount the trust file, OIDC file, and audit +key with an override file:

+
# docker-compose.override.yml
+services:
+  fleet:
+    environment:
+      FLEET_PROFILE_TRUST: /etc/sendbox-fleet/profile-trust.yaml
+      FLEET_OIDC_CONFIG: /etc/sendbox-fleet/oidc.yaml
+      FLEET_AUDIT_SIGNING_KEY: /run/sendbox-fleet/audit.key
+      FLEET_AUDIT_ANCHOR_DIR: /var/lib/sendbox-fleet/anchors
+    volumes:
+      - ./config:/etc/sendbox-fleet:ro
+      - ./audit-key:/run/sendbox-fleet:ro
+

The service runs as uid 10001, so ./audit-key/audit.key must be owned by +that uid with mode 0600 or 0400.

+
+ + +
+ +
+
+ +
+ + diff --git a/fleet/development/index.html b/fleet/development/index.html new file mode 100644 index 0000000..a953313 --- /dev/null +++ b/fleet/development/index.html @@ -0,0 +1,253 @@ + + + + + + Development | SendBox Fleet docs + + + + + + + + + + + + + + +
+
+ +All SendBox Fleet docs +
+
+

SendBox Fleet · Contribute

+

Development

+
+ +

Prerequisites

+
    +
  • rustup. The pinned toolchain (Rust 1.100.0 with +clippy and rustfmt) installs automatically from rust-toolchain.toml.
  • +
  • A Docker-compatible engine with Compose, only for the PostgreSQL stack.
  • +
+

Configuration

+

The server reads its configuration from the environment at startup and exits +with status 2 and a message naming the variable when a value is invalid.

+
+ + + + + + + + + + + + + + + + + + + + + + +
VariableDefaultMeaning
FLEET_DATABASE_URLrequiredsqlite://path.db?mode=rwc, sqlite::memory:, or postgres://user:password@host:5432/db
FLEET_BIND127.0.0.1:8080Listen address
FLEET_LOG_DIR./logsLog directory; relative paths resolve against the working directory at startup
FLEET_LOG_LEVELinfo,sqlx=warnEnvFilter directives
FLEET_LOG_RETENTION_DAYS30Days to keep rotated log files (1 to 3650)
FLEET_AUTHORITY_IDsendbox-fleetAuthority id hosts put in authority: of their operator configuration and bind into every session; not local
FLEET_PROFILE_TRUSTunsetYAML or JSON file with threshold and signers (the same shape as a host operator configuration's trust section). Profile publication is refused until it is set
FLEET_OIDC_CONFIGunsetYAML file of trusted identity providers (format). Unset: only service tokens authenticate
FLEET_TOKEN_TTL_SECONDS43200 (12 h)Default lifetime of tokens from POST /v1/tokens
FLEET_TOKEN_MAX_TTL_SECONDS604800 (7 d)Longest lifetime a caller may request (at most 90 days)
FLEET_AUDIT_SIGNING_KEYunsetKey from admin audit keygen (no group or other access). Enables GET /v1/audit/head
FLEET_AUDIT_ANCHOR_DIRunsetDirectory for periodic signed heads; needs the signing key
FLEET_AUDIT_ANCHOR_INTERVAL_SECONDS3600Anchoring interval (60 to 86400)
FLEET_RATE_LIMIT_PER_MINUTE1200/v1 requests per principal per minute; 0 disables
FLEET_AUTH_FAILURES_PER_MINUTE60Failed authentications per peer address per minute; 0 disables
FLEET_METRICS_BINDunsetSeparate listener for Prometheus /metrics; must differ from FLEET_BIND
FLEET_MIGRATEtruefalse: never change the schema; refuse to start until admin migrate has run
FLEET_LOG_MAX_BYTES104857600 (100 MiB)Rotate the log file at this size (1 MiB to 10 GiB)
+
+

Database credentials in FLEET_DATABASE_URL are never logged.

+

Run locally with SQLite

+
export FLEET_DATABASE_URL='sqlite://sendbox-fleet.db?mode=rwc'
+cargo run --bin sendbox-fleet
+
+curl -i http://127.0.0.1:8080/healthz
+curl -i http://127.0.0.1:8080/readyz
+curl -i -X POST http://127.0.0.1:8080/v1/authorize   # 401: authentication required
+

Migrations run at startup. Stop the server with Ctrl-C (or SIGTERM); it +stops accepting connections, gives in-flight requests up to 30 seconds, +closes the database pool, and flushes logs.

+

Bootstrap principals, tokens, and projects

+

sendbox-fleet admin acts on the database directly and needs only +FLEET_DATABASE_URL (and honors FLEET_MIGRATE). Every change is audited +with the actor cli:admin.

+
sendbox-fleet admin principal add oidc:olivia@example.com --kind user --operator
+sendbox-fleet admin principal add oidc:owen@example.com --kind user
+sendbox-fleet admin principal add worker:ci-1 --kind worker
+sendbox-fleet admin project create github:example/service --owner oidc:owen@example.com
+sendbox-fleet admin token issue oidc:owen@example.com --ttl-days 30 > owen.token
+sendbox-fleet admin token list oidc:owen@example.com
+sendbox-fleet admin token revoke <token-id>
+sendbox-fleet admin principal disable oidc:owen@example.com
+

token issue prints the token once on stdout; only its SHA-256 is stored. +People then use the API with Authorization: Bearer <token>, for example:

+
T=$(cat owen.token); U=http://127.0.0.1:8080
+curl -H "Authorization: Bearer $T" $U/v1/whoami
+curl -H "Authorization: Bearer $T" -H 'Content-Type: application/json' \
+  -d '{"principal":"oidc:alice@example.com","role":"member"}' \
+  "$U/v1/projects/github:example%2Fservice/roles"
+

An operator publishes the exact profile and the signature bundle produced by +sendbox governance sign:

+
jq -n --rawfile document acme.yaml --slurpfile signatures acme.yaml.sig.json \
+  '{document: $document, signatures: $signatures[0]}' |
+  curl -X PUT -H "Authorization: Bearer $OPERATOR_TOKEN" \
+    -H 'Content-Type: application/json' --data @- $U/v1/profiles/acme
+

On each SendBox host, the operator configuration names this service and the +caller stores their own token: sendbox secrets add SENDBOX_FLEET_TOKEN.

+

With FLEET_OIDC_CONFIG, people and CI sign in with their identity provider +instead, and hosts exchange that sign-in for a service token with +sendbox governance login. See deployment.

+

Other admin commands:

+
sendbox-fleet admin migrate                                  # apply migrations only
+sendbox-fleet admin audit keygen --output audit.key > audit-identity.json
+FLEET_AUDIT_SIGNING_KEY=audit.key sendbox-fleet admin audit anchor --output anchors/
+sendbox-fleet admin audit verify --identity audit-identity.json --anchor anchors/audit-head-*.json
+

Run with PostgreSQL (Compose)

+
cp .env.example .env        # set POSTGRES_PASSWORD (URL-safe characters)
+docker compose build --no-cache && docker compose up
+

The server listens on 127.0.0.1:${FLEET_PORT:-8080}. The container runs as +an unprivileged user with a read-only root filesystem; logs go to the +fleet-logs volume. docker compose down stops the stack and keeps data; +docker compose down --volumes also deletes the database and logs.

+

Checks

+
cargo fmt --all -- --check
+cargo clippy --locked --workspace --all-targets -- -D warnings
+cargo test --locked --workspace
+cargo audit --deny warnings          # needs cargo-audit; see .cargo/audit.toml
+scripts/check-contract-pin.sh        # SendBox crates locked to sendbox main
+

Tests use in-memory SQLite and synthetic data. To run the migration and API +tests against PostgreSQL, point FLEET_TEST_DATABASE_URL at a disposable +database whose name ends in _test (the tests drop and recreate its public +schema):

+

The PostgreSQL run also checks deploy/postgres/roles.sql by connecting as +its roles, which the trust authentication below allows.

+
docker run -d --name sendbox-fleet-pg-test -p 127.0.0.1:55432:5432 \
+  -e POSTGRES_DB=sendbox_fleet_test -e POSTGRES_USER=sendbox_fleet \
+  -e POSTGRES_HOST_AUTH_METHOD=trust postgres:18.7-alpine3.24
+FLEET_TEST_DATABASE_URL=postgres://sendbox_fleet@127.0.0.1:55432/sendbox_fleet_test \
+  cargo test --locked --workspace --test migrations --test http -- --test-threads=1
+docker rm -f sendbox-fleet-pg-test
+

CI runs formatting, Clippy, and tests on SQLite; the migration and API tests +plus a start, probe, and graceful-stop run of the server on PostgreSQL; and +cargo audit.

+

Logs

+
    +
  • Every event is a JSON line written to stdout and to +FLEET_LOG_DIR/sendbox-fleet.YYYY-MM-DD.log. A new file starts at each UTC +midnight, and whenever the live file reaches FLEET_LOG_MAX_BYTES the next +part continues in sendbox-fleet.YYYY-MM-DD.1.log, .2.log, and so on. +Files are created with mode 0600.
  • +
  • Retention runs at startup and then hourly. It deletes only regular files +named sendbox-fleet.YYYY-MM-DD.log or sendbox-fleet.YYYY-MM-DD.N.log +whose UTC day ended at least FLEET_LOG_RETENTION_DAYS days ago, judged by +the date in the name rather than the modification time. Other files, directories, and symlinks are left +alone; deletion failures are logged and retried at the next run.
  • +
  • The log directory is created with mode 0700.
  • +
  • File writes go through a bounded queue of 16,384 events. When it is full, +logging callers wait instead of dropping events.
  • +
  • Never logged: request bodies, headers (including Authorization), query +strings, and database credentials.
  • +
+

Migrations

+

Schema changes need a new, numbered file in both migrations/postgres and +migrations/sqlite with equivalent constraints. Never edit a migration that +has been applied anywhere: sqlx records checksums and refuses to start on a +mismatch. Add a test in crates/fleet-server/tests/migrations.rs for any new +invariant.

+

Troubleshooting

+
+ + + + + + + + + + + + + + + + + +
SymptomCause
configuration error: FLEET_DATABASE_URL is required (exit 2)Export a database URL
cannot connect to postgres://***@...Database not reachable or wrong credentials
cannot listen on ...Port already in use; set FLEET_BIND or FLEET_PORT
cannot create log directoryFLEET_LOG_DIR not writable by the server user
Every /v1 call returns 401 bearer token was not acceptedThe token is unknown, expired, revoked, or its principal is disabled; issue a new one with sendbox-fleet admin token issue
503 profile signers are not configured on profile publicationSet FLEET_PROFILE_TRUST
409 ... is not the current revision on session admissionThe host's local profile differs from the newest published revision; install the same signed bytes on the host
migrations … are not applied; run sendbox-fleet admin migrateFLEET_MIGRATE=false and the schema is behind; run admin migrate as the schema owner
permission denied for schema public at startupThe runtime role cannot migrate; set FLEET_MIGRATE=false and migrate as the owner
401 for an identity-provider tokenIssuer, audience, expiry, key, required claim, or email_verified did not match, or the principal is unknown, disabled, or of the other kind. The server log names the reason (for example expired, audience_mismatch, not_registered); callers only see 401
503 identity provider keys are unavailableThe issuer's discovery or JWKS endpoint is unreachable and no keys are cached
429 rate limit exceededWait Retry-After seconds; behind a proxy, see deployment
… must not be accessible by group or otherschmod 600 the audit signing key
+
+
+ + +
+ +
+
+ +
+ + diff --git a/fleet/index.html b/fleet/index.html new file mode 100644 index 0000000..d915189 --- /dev/null +++ b/fleet/index.html @@ -0,0 +1,81 @@ + + + + + + SendBox Fleet documentation + + + + + + + + + + + + + + +
+
+
+ +
+

Documentation

+

SendBox Fleet

+

Shared governance for SendBox teams.

+

SendBox Fleet is the shared governance service for SendBox governed sessions: operator-signed policy profiles shared across users and hosts, project roles, session admission, credential grants and a hash-chained central audit log. Provider credentials never reach it; they stay in the SendBox host broker.

+

Overview and quick start Source on GitHub

+
+
+
+ +
+
+ +
+ + diff --git a/fleet/overview/index.html b/fleet/overview/index.html new file mode 100644 index 0000000..f2ea106 --- /dev/null +++ b/fleet/overview/index.html @@ -0,0 +1,124 @@ + + + + + + Overview and quick start | SendBox Fleet docs + + + + + + + + + + + + + + +
+
+ +All SendBox Fleet docs +
+
+

SendBox Fleet · Get started

+

sendbox-fleet

+
+ +

Shared governance service for SendBox governed sessions: operator-signed policy profiles shared across users and hosts, project-scoped roles, session admission, credential grant authorization and revocation, approved expiring exceptions, and a hash-chained central audit log. It is increment 2 of mbianchidev/sendbox#87.

+

Provider credentials never reach this service; they stay in the SendBox host broker.

+

Status

+

Feature-complete for increment 2 and usable for team deployments:

+
    +
  • Signed profiles, project roles, session admission, grants, per-request authorization, revocation, and exceptions with a different approver.
  • +
  • Sign-in with any OpenID Connect provider (people and CI such as GitHub Actions), exchanged for short-lived service tokens; admin-issued tokens for bootstrap.
  • +
  • Hash-chained audit with host-reported request outcomes, signed chain heads, and anchoring outside the database.
  • +
  • Operations: PostgreSQL least-privilege roles, rate limits, Prometheus metrics, size and daily log rotation, deployment and backup guidance.
  • +
+

Not yet done: a governed session on Apple or Kata against real model providers through a deployed fleet. That run is host-side work tracked in mbianchidev/sendbox#96. See the roadmap.

+

Quick start

+
export FLEET_DATABASE_URL='sqlite://sendbox-fleet.db?mode=rwc'
+cargo run --bin sendbox-fleet -- admin principal add oidc:you@example.com --kind user --operator
+cargo run --bin sendbox-fleet -- admin token issue oidc:you@example.com > you.token
+cargo run --bin sendbox-fleet
+curl -H "Authorization: Bearer $(cat you.token)" http://127.0.0.1:8080/v1/whoami
+

Set FLEET_PROFILE_TRUST to publish signed profiles; see development. With PostgreSQL: cp .env.example .env, set POSTGRES_PASSWORD, then docker compose build --no-cache && docker compose up. For a shared setup, follow deployment.

+

Documentation

+
    +
  • Architecture: relationship to SendBox, trust boundaries, authentication, roles, API surface, schema, audit
  • +
  • Deployment: TLS, database roles, identity providers, audit anchoring, metrics, backups
  • +
  • Shared contract: how sendbox-governance is pinned and versioned
  • +
  • Threat model
  • +
  • Roadmap: delivered and remaining work mapped to the issue's acceptance criteria
  • +
  • Development: configuration, bootstrap, local runs, tests, logs
  • +
  • Contributing and security
  • +
+

License

+

Apache-2.0

+
+ + +
+ +
+
+ +
+ + diff --git a/fleet/roadmap/index.html b/fleet/roadmap/index.html new file mode 100644 index 0000000..1b85841 --- /dev/null +++ b/fleet/roadmap/index.html @@ -0,0 +1,175 @@ + + + + + + Roadmap | SendBox Fleet docs + + + + + + + + + + + + + + +
+
+ +All SendBox Fleet docs +
+
+

SendBox Fleet · Contribute

+

Roadmap

+
+ +

Increment-2 work for +mbianchidev/sendbox#87. +Each item names the issue's acceptance criteria (AC) it serves:

+
    +
  • AC1 A trusted shared profile is enforced at actual session admission and +execution; project configuration and CLI flags cannot broaden or bypass it.
  • +
  • AC4 Cross-principal, project, or session requests, changed policy +bindings, and forbidden destinations, methods, or paths are rejected at the +enforcement boundary.
  • +
  • AC5 Expired or revoked grants, stale policy, and unavailable +authorization produce explicit denial without credential export or fallback.
  • +
  • AC6 Session cancellation and teardown end grants while preserving +redacted audit evidence and reporting uncertain external outcomes honestly.
  • +
  • AC7 The shared-service increment enforces project-scoped roles and +authorized, expiring exceptions with attributable audit records.
  • +
  • AC8 Standalone workflows stay unchanged unless governance is selected; +compatibility and trust boundaries are documented.
  • +
+

Done

+

The scaffold delivered the service skeleton, the schema with its database +invariants, CI, and these documents. Increment 2 then delivered:

+
    +
  • Caller authentication (AC7). Opaque bearer tokens issued by +sendbox-fleet admin token issue, stored only as SHA-256 digests, expiring +within 90 days, revocable, and void when the principal is disabled. The +bearer-only rule and "authenticate before validating" ordering are kept.
  • +
  • Persistence (all). Backend-neutral transactions over PostgreSQL and +SQLite with serialized writers, an injectable clock, random identifiers, +and every change committed with its audit event.
  • +
  • Profiles (AC1, AC5). Publication verified against FLEET_PROFILE_TRUST +using the sendbox.governance-signatures bundle from sendbox governance sign; monotonic revisions; current-revision lookup; rising minimums.
  • +
  • Project-scoped roles (AC7). Operator project bootstrap, owner-managed +assignment and removal, last-owner guard, audited refusals. Roles gate +admission, exceptions, and audit visibility.
  • +
  • Session admission (AC1, AC4). Caller-bound principal, this authority, +member role, current revision, offered services, and valid exceptions.
  • +
  • Grants and revocation (AC4, AC5, AC6). Issue, renew, revoke, and end +sessions with bounded leases, exception-capped expiry, and the profile grace +window. The SendBox host's remote authority client lives in the sendbox +repository.
  • +
  • Per-request authorization (AC4, AC5). Same rules as the local authority +through the shared evaluate_request, plus session and exception state.
  • +
  • Exceptions (AC7). Request, approve, reject, revoke; a different +owner or admin approves; scope limited to denials the signed revision +lists as liftable; expiry at most 7 days; stale approvals rejected after a +new revision or minimum.
  • +
  • Central audit (AC6, AC7). Hash-chained events for every decision with +actor, principal, project, session, grant, exception, revision, decision, +redacted target, and detail; role-scoped queries; chain verification.
  • +
  • Identity providers (AC7). Any OpenID Connect issuer for people and +machine identities such as GitHub Actions: JWKS verification with ring +(RS256, ES256, EdDSA), exact issuer and audience, required claims, +verified email, optional auto-provisioning without roles. POST /v1/tokens exchanges a sign-in for a short-lived service token, which +sendbox governance login stores on the host; tokens can be listed and +revoked.
  • +
  • Outcomes and anchoring (AC6, AC7). Hosts report each brokered stream's +outcome (succeeded, failed, unknown) to POST /v1/grants/{grant}:outcome, recorded as request.outcome. Chain heads are +signed (GET /v1/audit/head), written periodically to an anchor directory, +and checked with sendbox-fleet admin audit verify.
  • +
  • Operations (AC8). Least-privilege PostgreSQL roles +(deploy/postgres/roles.sql, no UPDATE/DELETE on audit for the +runtime role), FLEET_MIGRATE=false with admin migrate, per-principal and +per-peer rate limits, Prometheus metrics on a separate listener, size and +daily log rotation, and deployment guidance for TLS, +identity providers, anchoring, metrics, and backups.
  • +
  • Dependencies. Rust 1.100.0 and sqlx 0.9, which removed the unused +rsa advisory exception.
  • +
+

Remaining

+
    +
  1. Live end-to-end runs. Run Apple and Kata governed sessions against a +deployed fleet and real model providers. The provider path (broker, +relay, credential injection) is host-side, so this is tracked in SendBox: +mbianchidev/sendbox#96.
  2. +
  3. RUSTSEC-2026-0459. Drop the exception in .cargo/audit.toml once an +sqlx release allows libsqlite3-sys 0.39. It affects only SQLite, which +production does not use.
  4. +
+

Non-goals

+

Kubernetes or fleet scheduling, universal TLS interception, formal policy +verification, and replacing SendBox isolation providers (as in the issue). +The service never stores or forwards provider credentials.

+
+ + +
+ +
+
+ +
+ + diff --git a/fleet/security-policy/index.html b/fleet/security-policy/index.html new file mode 100644 index 0000000..9a60cff --- /dev/null +++ b/fleet/security-policy/index.html @@ -0,0 +1,94 @@ + + + + + + Reporting vulnerabilities | SendBox Fleet docs + + + + + + + + + + + + + + +
+
+ +All SendBox Fleet docs +
+
+

SendBox Fleet · Security

+

Security

+
+ +

Please report suspected vulnerabilities privately through +GitHub private vulnerability reporting +(the repository's Security tab, then Report a vulnerability). Do not +open public issues or pull requests for vulnerabilities.

+

The security design is described in docs/threat-model.md. +This service is a scaffold: it authorizes nothing yet and must not be deployed +as a governance authority.

+
+ + +
+ +
+
+ +
+ + diff --git a/fleet/threat-model/index.html b/fleet/threat-model/index.html new file mode 100644 index 0000000..de45eb1 --- /dev/null +++ b/fleet/threat-model/index.html @@ -0,0 +1,165 @@ + + + + + + Threat model | SendBox Fleet docs + + + + + + + + + + + + + + +
+
+ +All SendBox Fleet docs +
+
+

SendBox Fleet · Security

+

Threat model

+
+ +

Scope: the shared governance service in this repository and its interfaces to +SendBox hosts, people, and its database. The SendBox VM boundary, host broker, +and increment-1 local authority are covered in the sendbox repository.

+

Status column: implemented means implemented and tested here; +documented means the mitigation is deployment guidance in +deployment.md. Remaining work is in roadmap.md.

+

Assets

+
    +
  • Authorization decisions: session admission, grants, per-request decisions.
  • +
  • Policy state: signed profile revisions, minimum revisions, project roles, +exceptions.
  • +
  • Audit evidence and its integrity.
  • +
  • Availability of authorization for running sessions.
  • +
+

Provider credentials are not an asset of this service: they stay in the +SendBox host broker and never reach the fleet.

+

Actors

+
+ + + + + + + + + + + + +
ActorTrust
OperatorTrusted to sign and publish profiles, create projects, and recover ownership
Project owner, admin, member, viewerTrusted within their project role
SendBox host (user or worker token)Trusted to report sessions of the principal whose token it holds; untrusted for anything else
Service host administrator (sendbox-fleet admin)Issues tokens and creates principals; equivalent to database access
Workload (agent inside a VM)Untrusted; never talks to the fleet directly
Network attackerUntrusted
Database administratorCan bypass application controls; mitigated by evidence anchoring
Identity provider in FLEET_OIDC_CONFIGTrusted to name principals under its own prefix, within its audience and required claims; nothing else
+
+

Threats and mitigations

+
+ + + + + + + + + + + + + + + + + + + + +
#ThreatMitigationStatus
T1Caller spoofs identity with headers such as X-Forwarded-UserOnly bearer tokens authenticate; identity headers are ignored; auth runs before routingImplemented (tested)
T2Workload-supplied identity in a body is trustedBinding and grant principals must equal the authenticated caller; projects and sessions are checked against stored state; local-user: principals rejected by API and schemaImplemented (tested)
T3Stolen or replayed bearer tokenService tokens stored only as SHA-256, expiring within 90 days (exchanged ones within FLEET_TOKEN_MAX_TTL_SECONDS, 7 days by default), listable and revocable by their owner, void when the principal is disabled; a service token cannot mint another; identity-provider JWTs need this service's audience and expire in minutes; TLS in front of the service (deployment)Implemented (tested)
T4Compromised worker acts for sessions it does not runA caller can only admit, use, renew, or end sessions bound to its own principal; grants bound to session, principal, project, binding digest, and profile revision (composite foreign key)Implemented (tested)
T5Stale policy or approval authorizes changed workSessions, grants, and exceptions reference an exact profile revision and digest; a new revision or raised minimum makes them stale; approvals of stale requests are refused; sessions bound to a revoked or expired exception are deniedImplemented (tested)
T6Grant wider than the profile allowsMethods and path prefixes must be inside the profile service; lifetime capped by the profile TTL, profile expiry, exception expiry, and 7 daysImplemented (tested)
T7Audit evidence altered or deletedAppend-only triggers, contiguous hash chain computed by the service and enforced on insert, GET /v1/audit/verify; runtime role without UPDATE, DELETE, TRUNCATE, or ALTER on audit (deploy/postgres/roles.sql); Ed25519-signed chain heads anchored outside the database and checked by admin audit verifyImplemented (tested)
T8Secrets leak into logs or auditNo request bodies, headers, or query strings logged; database URL credentials redacted; tokens stored only as digests; no credential columns; audit keeps a redacted target without query strings (schema check) and omits exception reasonsImplemented (tested)
T9Authority outage silently allows requestsHosts deny with authority_unavailable on any non-200 answer, timeout, or redirect; a token lookup failure is 503Implemented (host client tested in sendbox)
T10Exception abuse or self-approvalOnly denials the signed revision lists as liftable; reason; expiry at most the profile's exceptions.max_ttl_seconds and 7 days; approver is a different owner or admin (also a schema check); lifting never widens the ceiling; every request, decision, refusal, use, and revocation auditedImplemented (tested)
T11Revocation does not stop in-flight trafficNew requests denied at once; open streams bounded by the profile grace window (at most 60 seconds) on the host; uncertain outcomes audited on the host as aborted_uncertain and centrally as request.outcome with outcome unknownImplemented (tested)
T12Resource exhaustionBody limits (64 KiB, 1 MiB for profile publication), bounded connection pool and acquire timeout, bounded list sizes, non-lossy bounded log queue, per-principal request and per-peer authentication-failure rate limits, at most 20 live exchanged tokens per principal, bounded and throttled JWKS fetches, size-capped log filesImplemented (tested); limits are per instance
T13Supply-chain compromiseActions pinned by commit SHA, images pinned by digest, Cargo.lock committed, contract pinned by git revision, cargo audit in CI with documented exceptionsImplemented
T14Forged or misdirected identity-provider tokenExact issuer match against an operator-written list (HTTPS, or HTTP to loopback for tests), audience required, keys only from that issuer's JWKS (no jku, x5u, or embedded keys, no none or HMAC algorithms, crit refused), per-issuer algorithm allowlist, required claims (for example repository_owner), verified email, unique principal prefixes, kind bound to the issuer; auto-provisioned principals get no rolesImplemented (tested)
T15Rate-limit bypass or lockout behind a proxyThe failure limit keys on the TCP peer and ignores X-Forwarded-For; deployment guidance to limit per client at the proxyDocumented
T16Metrics leak identitiesMetrics on a separate listener, labels limited to status classes and decision codesImplemented (tested)
+
+

Known accepted risks

+
    +
  • RUSTSEC-2026-0459 (bundled SQLite older than the fix): SQLite is used +only for local development and tests on files the service creates. The fix +is libsqlite3-sys 0.39, which sqlx 0.9.0 does not allow yet. Tracked in +roadmap.md.
  • +
  • Database triggers do not stop a database owner or superuser. Run the +service with sendbox_fleet_app and anchor chain heads on storage those +administrators cannot rewrite; then a rewrite is detected, though not +prevented.
  • +
  • An identity-provider compromise can sign in as any principal that provider +names. Limit each issuer's prefix, audience, and required claims, and keep +auto_provision off where it is not needed.
  • +
+
+ + +
+ +
+
+ +
+ + diff --git a/index.html b/index.html new file mode 100644 index 0000000..9affa50 --- /dev/null +++ b/index.html @@ -0,0 +1,184 @@ + + + + + + SendBox | Run coding agents in dedicated VMs + + + + + + + + + + + + + + + + +
+
+
+
+

Open-source sandboxing for coding agents

+

Give your coding agent a workspace, not your whole machine.

+

SendBox runs coding agents in dedicated Linux VMs on macOS and Linux. Keep your terminal workflow while explicitly choosing the files, network destinations, credentials and MCP tools a session can use.

+

SendBox Fleet adds shared governance for teams: signed policy profiles, credential grants and a central audit log.

+

Get started Read the docs

+
+
+
# From your project directory
+$ sendbox init --project . --agent claude
+$ sendbox policy validate --config .sendbox.yaml
+$ sendbox run --interactive \
+    --config .sendbox.yaml \
+    --image "$WORKLOAD_IMAGE" \
+    --bundle "$GUEST_DIR/bundle" \
+    --trust-root "$GUEST_DIR/release-public.key" \
+    -- /usr/local/bin/claude
+
Create a policy, validate it, then start the agent in its own VM.
+
+
+
+ +
+
+

Two projects, one boundary

+

Use SendBox on its own for a single developer or runner. Add SendBox Fleet when several people and hosts need to share policy, grants and audit evidence.

+
+
+
+

SendBox

+

An open-source Rust CLI for running coding agents in dedicated Linux VMs, through Apple Containerization on macOS and Kata Containers on Linux.

+
    +
  • One reviewable YAML policy for commands, network destinations, credentials and MCP tools.
  • +
  • Workspace snapshots, diffs, failure rollback and tamper-evident lifecycle records.
  • +
  • Interactive terminal sessions, or headless runs with JSON events for scripts and CI.
  • +
+ +
+
+

SendBox Fleet

+

The shared governance service for SendBox governed sessions. Provider credentials never reach it; they stay in the SendBox host broker.

+
    +
  • Operator-signed policy profiles shared across users and hosts, with project-scoped roles.
  • +
  • Session admission, credential grants, revocation and approved, expiring exceptions.
  • +
  • OpenID Connect sign-in and a hash-chained audit log with signed, anchored chain heads.
  • +
+ +
+
+
+ +
+
+

What a session gets, and what it doesn't

+

An agent needs to edit code, run commands and reach its model provider. It doesn't need everything else on your laptop or runner.

+
+
    +
  • VM-backed isolation

    A dedicated guest kernel, not a workload sharing the host kernel.

  • +
  • Explicit workspace scope

    Share one project, or opt into a multi-repository workspace. Your home directory isn't mounted automatically.

  • +
  • Deny-first networking

    Allowed domains only. Direct external agent traffic and UDP/QUIC are blocked.

  • +
  • Scoped credentials

    Vault-backed secrets with separate GitHub, Copilot, MCP and registry paths, masked in output.

  • +
  • MCP tool policies

    Admit exact local or remote servers and allow or deny tools per server.

  • +
  • Package checks

    An optional npm proxy verifies and inspects packages before releasing their bytes.

  • +
  • Snapshots and audit

    Before and after snapshots, diffs and tamper-evident lifecycle records.

  • +
  • GitHub write controls

    Branch guards, or Safe Outputs for bounded writes without an agent write token.

  • +
+

An unavailable runtime or unsupported capability is an error, never a fallback to running on the host. Read the security model and the limitations for what isolation does and doesn't cover.

+
+ +
+
+

How they fit together

+

Both projects share the sendbox-governance contract. A host can govern sessions locally or through a shared Fleet service.

+
+
+
+

Standalone and local governance

+

Install the SendBox CLI and a runtime, generate .sendbox.yaml for a project and start sessions. Operators can require signed policy profiles and keep model provider keys on the host with governed sessions, using a grant authority that runs in process.

+
+
+

Shared governance with Fleet

+

Point the host's governance configuration at a Fleet service. Fleet authenticates people and CI, enforces project roles, admits sessions, issues and checks grants, and keeps the central audit log. Follow the deployment guide to run it with PostgreSQL and your identity provider.

+
+
+
+ +
+
+

Bring the agent you already use

+

Init profiles set the agent's entry command and initial inference hosts. They don't install the agent or log you in; your digest-pinned workload image provides the Linux agent and its tools.

+
+
    +
  • Moguri
  • +
  • Claude Code
  • +
  • OpenAI Codex CLI
  • +
  • GitHub Copilot CLI
  • +
  • Gemini CLI
  • +
  • OpenCode
  • +
  • Custom CLI agents and programs
  • +
+

Agent profiles, credentials and networking

+
+ +
+
+

Get started

+

SendBox supports macOS 26+ on Apple silicon and Linux on x86_64 or aarch64 with hardware or nested virtualization.

+
+
    +
  1. +

    Install SendBox and a runtime

    +

    Install the CLI from the Homebrew tap, or download and verify a release. Then set up Apple Containerization on macOS or Kata Containers on Linux, and stage the signed guest bundle.

    +
    $ brew install mbianchidev/tap/sendbox
    +
  2. +
  3. +

    Configure your project and agent

    +

    Generate a private .sendbox.yaml, store credentials outside shell history and validate the policy before starting a VM.

    +
    $ sendbox init --project . --agent claude
    +$ sendbox secrets add ANTHROPIC_API_KEY
    +$ sendbox policy validate --config .sendbox.yaml
    +
  4. +
  5. +

    Start a session

    +

    Run the agent interactively with your workload image, or drop --interactive for headless automation. See the full quick start and the CLI reference.

    +
  6. +
+

Before installing a release, check the dependency security status and Homebrew update notes in the installation guide.

+
+ +
+
+

Build it with us

+

Both projects are Apache-2.0 and developed in the open. Start with the contribution guides, and report vulnerabilities privately.

+
+

Contribute sendbox-dev on GitHub

+
+
+ +
+ +
+ + + diff --git a/robots.txt b/robots.txt new file mode 100644 index 0000000..ce3b458 --- /dev/null +++ b/robots.txt @@ -0,0 +1,3 @@ +User-agent: * +Allow: / +Sitemap: https://sendbox.synctune.it/sitemap.xml diff --git a/scripts/build.mjs b/scripts/build.mjs new file mode 100644 index 0000000..6573ec8 --- /dev/null +++ b/scripts/build.mjs @@ -0,0 +1,144 @@ +// Generates the documentation pages, logos, sitemap and the shared header and footer of the +// hand-written pages from vendor/ and the catalogue. Node built-ins only. +// Usage: node scripts/build.mjs write the generated files +// node scripts/build.mjs --check fail if any generated file is missing or out of date +import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { dirname, join, posix } from "node:path"; +import { fileURLToPath } from "node:url"; +import { formerOwners, pagesOf, projects } from "./catalogue.mjs"; +import { docPage, footer, header, pagePath, projectIndex, relative, sitemap } from "./layout.mjs"; +import { renderMarkdown } from "./markdown.mjs"; +import { readVendor } from "./vendor.mjs"; + +// Hand-written pages whose and regions the build refreshes. +export const handwritten = [ + { file: "index.html", directory: "" }, + { file: "contribute/index.html", directory: "contribute/" }, +]; + +// Directories and files the build owns completely. Anything else in them is removed. +const generatedDirectories = ["sendbox", "fleet", "assets/logos"]; + +const findPage = (project, upstream) => pagesOf(project).find((page) => page.upstream === upstream); + +// Maps a link in an upstream document to its published page, or to GitHub at the synced commit. +export function resolveDocLink(href, { project, upstream, commit, directory }) { + if (href.startsWith("#")) return href; + if (/^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("//")) { + const github = /^https:\/\/github\.com\/([^/]+)\/([^/#?]+)(.*)$/.exec(href); + const target = github && [...formerOwners, "sendbox-dev"].includes(github[1]) + ? projects.find((candidate) => candidate.repo.split("/")[1] === github[2].replace(/\.git$/, "")) + : null; + if (!target) return href; + const blob = /^\/(?:blob|tree)\/main\/([^#?]*)(#.*)?$/.exec(github[3]); + const page = blob && findPage(target, blob[1]); + if (page) return relative(directory, pagePath(target, page)) + (blob[2] ?? ""); + return `https://github.com/${target.repo}${github[3]}`; + } + const [, path, suffix = ""] = /^([^#?]*)([#?].*)?$/.exec(href); + if (!path) return suffix; + const resolved = posix.normalize(posix.join(posix.dirname(upstream), decodeURI(path))); + if (resolved.startsWith("../")) throw new Error(`${project.repo}/${upstream} links outside the repository: ${href}`); + const page = findPage(project, resolved.replace(/\/$/, "")); + if (page) return relative(directory, pagePath(project, page)) + suffix; + if (resolved === project.logo.upstream) return relative(directory, project.logo.file); + const kind = path.endsWith("/") ? "tree" : "blob"; + return `https://github.com/${project.repo}/${kind}/${commit}/${resolved.replace(/\/$/, "")}${suffix}`; +} + +function resolveImage(src, context) { + const resolved = resolveDocLink(src, context); + if (/^[a-z][a-z0-9+.-]*:/i.test(resolved)) { + throw new Error(`${context.project.repo}/${context.upstream} shows an image that isn't bundled: ${src}. Add it to the catalogue so the site loads no third-party resources.`); + } + return resolved; +} + +function refreshRegions(html, directory, file) { + let output = html; + for (const [name, content] of [["header", header(directory)], ["footer", footer(directory)]]) { + const pattern = new RegExp(`()[\\s\\S]*?()`); + if (!pattern.test(output)) throw new Error(`${file} is missing its region.`); + output = output.replace(pattern, `$1\n${content}\n$2`); + } + return output; +} + +// Returns every generated file as a Map of repository path to contents. +export async function buildSite(root) { + const files = new Map(); + const paths = [""]; + for (const project of projects) { + const record = await readVendor(root, project); + const pages = pagesOf(project); + paths.push(`${project.route}/`); + pages.forEach((page, position) => { + const directory = pagePath(project, page); + const context = { project, upstream: page.upstream, commit: record.commit, directory }; + const rendered = renderMarkdown(record.contents.get(page.upstream).toString("utf8"), { + resolveLink: (href) => resolveDocLink(href, context), + resolveImage: (src) => resolveImage(src, context), + sourceUrl: `https://github.com/${project.repo}/blob/${record.commit}/${page.upstream}`, + }); + files.set(`${directory}index.html`, docPage({ project, page, record, rendered, previous: pages[position - 1], next: pages[position + 1] })); + paths.push(directory); + }); + files.set(`${project.route}/index.html`, projectIndex({ project, record })); + files.set(project.logo.file, record.contents.get(project.logo.upstream)); + } + files.set("assets/favicon.svg", files.get(projects[0].logo.file)); + for (const { file, directory } of handwritten) { + files.set(file, refreshRegions(await readFile(join(root, file), "utf8"), directory, file)); + } + paths.push("contribute/"); + files.set("sitemap.xml", sitemap(paths)); + return files; +} + +async function listFiles(root, directory) { + const entries = await readdir(join(root, directory), { withFileTypes: true, recursive: true }).catch(() => []); + return entries.filter((entry) => entry.isFile()).map((entry) => posix.join(posix.relative(root, entry.parentPath).split("\\").join("/"), entry.name)); +} + +// Compares the generated files with the working tree. Returns the out-of-date paths. +export async function compareBuild(root, files) { + const differences = []; + for (const [path, content] of files) { + const existing = await readFile(join(root, path)).catch(() => null); + if (!existing || !existing.equals(Buffer.from(content))) differences.push(path); + } + for (const directory of generatedDirectories) { + for (const path of await listFiles(root, directory)) { + if (!files.has(path)) differences.push(`${path} (not generated, remove it)`); + } + } + return differences; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const root = fileURLToPath(new URL("../", import.meta.url)); + try { + const files = await buildSite(root); + const differences = await compareBuild(root, files); + if (process.argv.includes("--check")) { + if (differences.length) { + console.error(`Generated files are out of date. Run node scripts/build.mjs and commit the result:\n ${differences.join("\n ")}`); + process.exitCode = 1; + } else { + console.log(`All ${files.size} generated files are up to date.`); + } + } else { + for (const directory of generatedDirectories) { + for (const path of await listFiles(root, directory)) if (!files.has(path)) await rm(join(root, path)); + } + for (const [path, content] of files) { + await mkdir(dirname(join(root, path)), { recursive: true }); + await writeFile(join(root, path), content); + } + console.log(`Built ${files.size} files (${differences.length} changed).`); + } + } catch (error) { + console.error(`Build failed: ${error.message}`); + process.exitCode = 1; + } +} diff --git a/scripts/catalogue.mjs b/scripts/catalogue.mjs new file mode 100644 index 0000000..cd3c42a --- /dev/null +++ b/scripts/catalogue.mjs @@ -0,0 +1,145 @@ +// The single list of projects, published documents and their site routes. +// Every upstream path here is synced into vendor// and recorded in SOURCE.json. + +export const site = { + origin: "https://sendbox.synctune.it", + name: "SendBox", + org: "https://github.com/sendbox-dev", + repository: "https://github.com/sendbox-dev/sendbox.synctune.it", +}; + +// Previous repository owners. Links to them are rewritten to the current owner. +export const formerOwners = ["mbianchidev"]; + +const sendboxGroups = [ + { + title: "Get started", + pages: [ + { slug: "overview", upstream: "README.md", label: "Overview and quick start", summary: "What SendBox is, supported agents and the shortest path to a first run." }, + { slug: "installation", upstream: "docs/installation.md", label: "Installation", summary: "Host and runtime requirements, workload images, release verification, source builds and macOS package notes." }, + { slug: "configuration", upstream: "docs/configuration.md", label: "Configuration", summary: "YAML examples, policy settings and credential configuration." }, + { slug: "cli-reference", upstream: "docs/cli-reference.md", label: "CLI reference", summary: "Commands, run flags and common examples." }, + { slug: "interactive-sessions", upstream: "docs/interactive-sessions.md", label: "Interactive sessions", summary: "Terminal requirements, behavior and troubleshooting." }, + { slug: "cli-agents", upstream: "docs/cli-agents.md", label: "CLI agents", summary: "Agent profiles, native MCP formats, multi-repo scope, HTTP proxies and syscall tracing." }, + { slug: "integrations", upstream: "docs/integrations.md", label: "Integrations", summary: "MCP, GitHub, model providers, private registries, devcontainers and CI workflows." }, + { slug: "similar-tools", upstream: "docs/alternatives.md", label: "Similar tools", summary: "SendBox compared with other agent sandboxes and dev containers." }, + ], + }, + { + title: "Runtimes and operations", + pages: [ + { slug: "apple-runtime", upstream: "docs/apple-runtime.md", label: "Apple runtime", summary: "Apple Containerization on macOS, supported container CLI versions and qualification status." }, + { slug: "kata-containers", upstream: "docs/kata-containers.md", label: "Kata Containers", summary: "The Linux runtime: Kata, containerd, nerdctl and KVM setup." }, + { slug: "hyperlight", upstream: "docs/hyperlight.md", label: "Hyperlight", summary: "The explicit one-shot Linux/KVM provider and what it rejects." }, + { slug: "dns-cold-start", upstream: "docs/dns-cold-start.md", label: "Cold-start DNS diagnostics", summary: "A credential-free diagnostic for first-request networking failures." }, + { slug: "package-supply-chain", upstream: "docs/package-supply-chain.md", label: "Package supply-chain proxy", summary: "Verify and inspect npm packages before their bytes reach the workload." }, + { slug: "mcp-inspection", upstream: "docs/mcp-inspection.md", label: "MCP inspection", summary: "The MCP boundary, tool policies and inspection records." }, + ], + }, + { + title: "Security", + pages: [ + { slug: "security-model", upstream: "docs/security-model.md", label: "Security model", summary: "Guarantees, assumptions and defense-in-depth analysis." }, + { slug: "security-policy", upstream: "SECURITY.md", label: "Reporting vulnerabilities", summary: "How to report a vulnerability privately and which versions receive fixes." }, + { slug: "egress-trust-boundary", upstream: "docs/security/egress-enforcement-trust-boundary.md", label: "Egress trust boundary", summary: "The egress enforcement trust boundary and runtime integration contract." }, + { slug: "secrets-migration", upstream: "docs/migration/secrets.md", label: "Secrets migration", summary: "Moving existing secrets to the current secret store." }, + { slug: "security-records-migration", upstream: "docs/migration/security-records.md", label: "Security-record migration", summary: "Migrating stored security records." }, + ], + }, + { + title: "Contribute", + contributor: true, + pages: [ + { slug: "contributing", upstream: "docs/contributing.md", label: "Contributing", summary: "Source setup, checks, documentation conventions and release procedures." }, + { slug: "qualification", upstream: "docs/qualification.md", label: "Qualification", summary: "The qualification inventory, conformance checks and benchmarks." }, + { slug: "roadmap", upstream: "ROADMAP.md", label: "Roadmap", summary: "Future proposals and historical designs." }, + ], + }, + { + title: "Architecture", + contributor: true, + pages: [ + { slug: "architecture/runtime-core", upstream: "docs/architecture/runtime-core.md", label: "Runtime core" }, + { slug: "architecture/execution-broker", upstream: "docs/architecture/execution-broker.md", label: "Execution broker" }, + { slug: "architecture/guest-supervisor", upstream: "docs/architecture/guest-supervisor.md", label: "Guest supervisor" }, + { slug: "architecture/guest-artifact-bundles", upstream: "docs/architecture/guest-artifact-bundles.md", label: "Guest artifact bundles" }, + { slug: "architecture/interactive-terminal", upstream: "docs/architecture/interactive-terminal.md", label: "Interactive terminal" }, + { slug: "architecture/kata-runtime", upstream: "docs/architecture/kata-runtime.md", label: "Kata runtime" }, + { slug: "architecture/authenticated-guest-protocol", upstream: "docs/architecture/authenticated-guest-protocol.md", label: "Authenticated guest protocol" }, + { slug: "architecture/session-security-lifecycle", upstream: "docs/architecture/session-security-lifecycle.md", label: "Session security lifecycle" }, + { slug: "architecture/egress-enforcement", upstream: "docs/architecture/egress-enforcement.md", label: "Egress enforcement" }, + { slug: "architecture/mcp-broker", upstream: "docs/architecture/mcp-broker.md", label: "MCP broker" }, + { slug: "architecture/package-registry-proxy", upstream: "docs/architecture/package-registry-proxy.md", label: "Package registry proxy" }, + { slug: "architecture/secrets-and-credential-broker", upstream: "docs/architecture/secrets-and-credential-broker.md", label: "Secrets and credential broker" }, + { slug: "architecture/governed-sessions", upstream: "docs/architecture/governed-sessions.md", label: "Governed sessions" }, + { slug: "architecture/git-branch-guard", upstream: "docs/architecture/git-branch-guard.md", label: "Git branch guard" }, + { slug: "architecture/safe-outputs", upstream: "docs/architecture/safe-outputs.md", label: "Safe Outputs" }, + { slug: "architecture/security-records", upstream: "docs/architecture/security-records.md", label: "Security records" }, + { slug: "architecture/agent-orchestration", upstream: "docs/architecture/agent-orchestration.md", label: "Agent orchestration" }, + { slug: "architecture/native-project-analysis", upstream: "docs/architecture/native-project-analysis.md", label: "Native project analysis" }, + { slug: "architecture/rust-cli-parity", upstream: "docs/architecture/rust-cli-parity.md", label: "Rust CLI" }, + ], + }, +]; + +const fleetGroups = [ + { + title: "Get started", + pages: [ + { slug: "overview", upstream: "README.md", label: "Overview and quick start", summary: "What SendBox Fleet does, its status and a local quick start." }, + { slug: "deployment", upstream: "docs/deployment.md", label: "Deployment", summary: "TLS, database roles, identity providers, audit anchoring, metrics and backups." }, + { slug: "architecture", upstream: "docs/architecture.md", label: "Architecture", summary: "Relationship to SendBox, trust boundaries, authentication, roles, API surface, schema and audit." }, + { slug: "contract", upstream: "docs/contract.md", label: "Shared contract", summary: "How the sendbox-governance contract is pinned and versioned." }, + ], + }, + { + title: "Security", + pages: [ + { slug: "threat-model", upstream: "docs/threat-model.md", label: "Threat model", summary: "Assets, adversaries and mitigations for the governance service." }, + { slug: "security-policy", upstream: "SECURITY.md", label: "Reporting vulnerabilities", summary: "How to report a vulnerability privately." }, + ], + }, + { + title: "Contribute", + contributor: true, + pages: [ + { slug: "contributing", upstream: "CONTRIBUTING.md", label: "Contributing", summary: "Trust boundaries to keep, contract changes, migrations and pre-PR checks." }, + { slug: "development", upstream: "docs/development.md", label: "Development", summary: "Configuration, bootstrap, local runs, tests and logs." }, + { slug: "roadmap", upstream: "docs/roadmap.md", label: "Roadmap", summary: "Delivered and remaining work." }, + ], + }, +]; + +export const projects = [ + { + id: "sendbox", + name: "SendBox", + repo: "sendbox-dev/sendbox", + route: "sendbox", + logo: { upstream: "docs/assets/logo.svg", file: "assets/logos/sendbox.svg" }, + license: "LICENSE", + tagline: "Give your coding agent a workspace, not your whole machine.", + intro: "SendBox is an open-source Rust CLI for running coding agents in dedicated Linux VMs on macOS and Linux. Keep your terminal workflow while explicitly choosing the files, network destinations, credentials and MCP tools a session can use.", + groups: sendboxGroups, + }, + { + id: "sendbox-fleet", + name: "SendBox Fleet", + repo: "sendbox-dev/sendbox-fleet", + route: "fleet", + logo: { upstream: "docs/assets/logo.svg", file: "assets/logos/sendbox-fleet.svg" }, + license: "LICENSE", + tagline: "Shared governance for SendBox teams.", + intro: "SendBox Fleet is the shared governance service for SendBox governed sessions: operator-signed policy profiles shared across users and hosts, project roles, session admission, credential grants and a hash-chained central audit log. Provider credentials never reach it; they stay in the SendBox host broker.", + groups: fleetGroups, + }, +]; + +export function pagesOf(project) { + return project.groups.flatMap((group) => group.pages.map((page) => ({ ...page, group: group.title }))); +} + +// Every file synced from upstream for a project: published documents, the logo and the license. +export function upstreamFiles(project) { + return [...pagesOf(project).map((page) => page.upstream), project.logo.upstream, project.license]; +} diff --git a/scripts/check.mjs b/scripts/check.mjs new file mode 100644 index 0000000..f250675 --- /dev/null +++ b/scripts/check.mjs @@ -0,0 +1,283 @@ +// Checks the website with Node built-ins only: +// - vendored documents match SOURCE.json and the generated pages are up to date; +// - every local link, image and anchor resolves, and the sitemap matches the pages; +// - each page has the expected structure and accessibility basics (language, title, one h1, +// heading order, alt text, link names, unique ids, labelled landmarks, skip link); +// - no scripts or third-party resources load, and the theme colors meet WCAG contrast. +// Usage: node scripts/check.mjs [--site ] [--external] +// --site check an already packaged site (default: package into a temporary directory) +// --external also request every external URL (needs network access) +import { mkdtemp, readFile, readdir, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, posix, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { site } from "./catalogue.mjs"; +import { buildSite, compareBuild } from "./build.mjs"; +import { decodeEntities, plainText } from "./markdown.mjs"; +import { packageSite } from "./package.mjs"; + +const local = "https://local.invalid/"; + +function parseAttributes(source = "") { + const values = {}; + for (const match of source.matchAll(/([a-zA-Z][\w:-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g)) { + values[match[1].toLowerCase()] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? ""); + } + return values; +} + +function tags(html, name) { + const pattern = new RegExp(`<${name}\\b([^<>]*)>`, "gi"); + return [...html.matchAll(pattern)].map((match) => parseAttributes(match[1])); +} + +// Checks one page's structure and accessibility basics. Returns its ids, references and problems. +export function inspectPage(html, path) { + const problems = []; + const report = (message) => problems.push(`${path}: ${message}`); + const ids = new Set(); + for (const { id } of tags(html, "[a-z][a-z0-9]*").filter((attributes) => "id" in attributes)) { + if (ids.has(id)) report(`duplicate id "${id}"`); + ids.add(id); + } + if (!tags(html, "html")[0]?.lang) report(" has no lang attribute"); + if (!/[^<]*\S[^<]*<\/title>/.test(html)) report("missing or empty <title>"); + const viewport = tags(html, "meta").find((meta) => meta.name === "viewport"); + if (!viewport) report("missing viewport meta tag"); + else if (/user-scalable\s*=\s*no|maximum-scale\s*=\s*1(?:\.0)?(?!\d)/.test(viewport.content)) report("viewport blocks zooming"); + if (/<script\b/i.test(html)) report("loads a script; the site promises no JavaScript"); + if ((html.match(/<main\b/g) ?? []).length !== 1) report("needs exactly one <main>"); + if ((html.match(/<h1\b/g) ?? []).length !== 1) report("needs exactly one <h1>"); + let previous = 0; + for (const match of html.matchAll(/<h([1-6])\b/g)) { + const level = Number(match[1]); + if (level > previous + 1) report(`heading jumps from h${previous || "(none)"} to h${level}`); + previous = level; + } + for (const image of tags(html, "img")) if (!("alt" in image)) report(`image ${image.src} has no alt attribute`); + for (const match of html.matchAll(/<a\b([^<>]*)>([\s\S]*?)<\/a>/g)) { + const attributes = parseAttributes(match[1]); + if (!("href" in attributes)) continue; + const name = attributes["aria-label"] ?? plainText(match[2].replace(/<img\b[^>]*\balt="([^"]*)"[^>]*>/g, " $1 ")); + if (!name.trim()) report(`link to ${attributes.href} has no accessible name`); + } + for (const element of tags(html, "[a-z][a-z0-9]*")) { + if (Number(element.tabindex) > 0) report(`positive tabindex ${element.tabindex}`); + } + for (const landmark of ["nav", "aside"]) { + const labels = tags(html, landmark).map((attributes) => attributes["aria-label"] ?? attributes["aria-labelledby"]); + if (labels.length > 1 || landmark === "aside") { + for (const label of labels) if (!label) report(`<${landmark}> needs an aria-label`); + const unique = new Set(labels); + if (unique.size !== labels.length) report(`<${landmark}> labels must be unique`); + } + } + if (/<nav\b/.test(html)) { + const first = /<body\b[^>]*>\s*(?:<!--[\s\S]*?-->\s*)*<a\b([^<>]*)>/.exec(html); + if (!first || parseAttributes(first[1]).href !== "#main") report("the first link must skip to #main"); + if (!/<main\b[^>]*\bid="main"/.test(html)) report('<main> needs id="main" for the skip link'); + } + for (const table of html.matchAll(/<table\b[\s\S]*?<\/table>/g)) { + if (!/<th\b/.test(table[0])) report("a table has no header cells"); + } + const references = []; + for (const [name, attribute] of [["a", "href"], ["link", "href"], ["img", "src"], ["source", "srcset"]]) { + for (const attributes of tags(html, name)) { + if (attribute in attributes) references.push({ tag: name, rel: attributes.rel ?? "", url: attributes[attribute] }); + } + } + return { ids, references, problems }; +} + +async function publishedFiles(directory) { + const entries = await readdir(directory, { withFileTypes: true, recursive: true }); + return entries.filter((entry) => entry.isFile()).map((entry) => posix.join(posix.relative(directory, entry.parentPath).split("\\").join("/"), entry.name)); +} + +const pageUrl = (file) => file.replace(/(^|\/)index\.html$/, "$1"); + +// Checks every published page, link and anchor in a packaged site directory. +export async function checkSite(directory) { + const problems = []; + const files = new Set(await publishedFiles(directory)); + const pages = new Map(); + for (const file of [...files].filter((path) => path.endsWith(".html")).sort()) { + const html = await readFile(join(directory, file), "utf8"); + const inspected = inspectPage(html, file); + problems.push(...inspected.problems); + pages.set(file, { html, ...inspected }); + } + const titles = new Map(); + for (const [file, { html }] of pages) { + const title = /<title>([^<]*)<\/title>/.exec(html)?.[1]; + if (title && titles.has(title)) problems.push(`${file}: title "${title}" is also used by ${titles.get(title)}`); + titles.set(title, file); + if (file === "404.html") continue; + const canonical = tags(html, "link").find((link) => link.rel === "canonical")?.href; + if (canonical !== `${site.origin}/${pageUrl(file)}`) problems.push(`${file}: canonical URL should be ${site.origin}/${pageUrl(file)}`); + } + + const externals = new Map(); + for (const [file, { references }] of pages) { + for (const { tag, rel, url: raw } of references) { + if (rel === "canonical" || /^(?:mailto|tel):/i.test(raw)) continue; + const url = raw.startsWith(`${site.origin}/`) ? `/${raw.slice(site.origin.length + 1)}` : raw; + if (/^https?:/i.test(url)) { + if (tag !== "a") problems.push(`${file}: loads a third-party resource ${url}`); + if (!externals.has(url)) externals.set(url, []); + externals.get(url).push(file); + continue; + } + if (/^[a-z][a-z0-9+.-]*:|^\/\//i.test(url)) { + problems.push(`${file}: unsupported link ${url}`); + continue; + } + const resolved = new URL(url, url.startsWith("/") ? local : `${local}${file}`); + let target = decodeURIComponent(resolved.pathname.slice(1)); + if (target === "" || target.endsWith("/")) target += "index.html"; + if (!files.has(target)) { + const hint = files.has(`${target}/index.html`) ? " (add a trailing slash)" : /\.md$/.test(target) ? " (a Markdown source link)" : ""; + problems.push(`${file}: broken link ${raw}${hint}`); + continue; + } + if (resolved.hash) { + const id = decodeURIComponent(resolved.hash.slice(1)); + if (!pages.get(target)?.ids.has(id)) problems.push(`${file}: missing anchor ${raw}`); + } + } + } + + const sitemap = await readFile(join(directory, "sitemap.xml"), "utf8").catch(() => ""); + const listed = new Set([...sitemap.matchAll(/<loc>([^<]+)<\/loc>/g)].map((match) => match[1])); + for (const file of pages.keys()) { + if (file !== "404.html" && !listed.has(`${site.origin}/${pageUrl(file)}`)) problems.push(`sitemap.xml: missing ${pageUrl(file) || "/"}`); + } + for (const loc of listed) { + const path = loc.slice(site.origin.length + 1); + if (!loc.startsWith(`${site.origin}/`) || !pages.has(`${path}index.html`)) problems.push(`sitemap.xml: ${loc} is not a page`); + } + const robots = await readFile(join(directory, "robots.txt"), "utf8").catch(() => ""); + if (!robots.includes(`Sitemap: ${site.origin}/sitemap.xml`)) problems.push("robots.txt: missing the sitemap URL"); + const cname = (await readFile(join(directory, "CNAME"), "utf8").catch(() => "")).trim(); + if (cname !== new URL(site.origin).hostname) problems.push(`CNAME: expected ${new URL(site.origin).hostname}, found "${cname}"`); + if (!files.has(".nojekyll")) problems.push(".nojekyll is missing"); + return { problems, externals, pages: pages.size }; +} + +function luminance(hex) { + const value = hex.replace("#", ""); + const full = value.length === 3 ? [...value].map((digit) => digit + digit).join("") : value; + const [red, green, blue] = [0, 2, 4].map((offset) => { + const channel = parseInt(full.slice(offset, offset + 2), 16) / 255; + return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4; + }); + return 0.2126 * red + 0.7152 * green + 0.0722 * blue; +} + +export function contrast(foreground, background) { + const [light, dark] = [luminance(foreground), luminance(background)].sort((a, b) => b - a); + return (light + 0.05) / (dark + 0.05); +} + +// Foreground and background custom properties used together in the stylesheet. +const textPairs = [ + ["--text", "--bg"], ["--text", "--surface"], ["--text", "--code-bg"], + ["--muted", "--bg"], ["--muted", "--surface"], + ["--link", "--bg"], ["--link", "--surface"], + ["--code-text", "--code-bg"], + ["--hero-text", "--hero-bg"], ["--hero-muted", "--hero-bg"], ["--hero-accent", "--hero-bg"], + ["--button-text", "--button-bg"], + ["--terminal-text", "--terminal-bg"], ["--terminal-muted", "--terminal-bg"], ["--hero-accent", "--terminal-bg"], +]; +const focusPairs = [["--focus", "--bg"], ["--focus", "--surface"], ["--hero-accent", "--hero-bg"]]; + +function variables(block) { + return Object.fromEntries([...block.matchAll(/(--[\w-]+)\s*:\s*(#[0-9a-fA-F]{3,6})\s*;/g)].map((match) => [match[1], match[2]])); +} + +export function checkContrast(css) { + const light = variables(/:root\s*\{([^}]*)\}/.exec(css)?.[1] ?? ""); + const darkBlock = /@media\s*\(prefers-color-scheme:\s*dark\)\s*\{\s*:root\s*\{([^}]*)\}/.exec(css)?.[1]; + const themes = { light, dark: { ...light, ...variables(darkBlock ?? "") } }; + const problems = []; + for (const [theme, colors] of Object.entries(themes)) { + for (const [pairs, minimum] of [[textPairs, 4.5], [focusPairs, 3]]) { + for (const [foreground, background] of pairs) { + if (!colors[foreground] || !colors[background]) { + problems.push(`styles.css (${theme}): ${foreground} or ${background} is not a hex color variable`); + continue; + } + const ratio = contrast(colors[foreground], colors[background]); + if (ratio < minimum) problems.push(`styles.css (${theme}): ${foreground} on ${background} is ${ratio.toFixed(2)}:1, below ${minimum}:1`); + } + } + } + return problems; +} + +async function status(url) { + for (const method of ["HEAD", "GET"]) { + const response = await fetch(url, { method, redirect: "follow", signal: AbortSignal.timeout(20_000), headers: { "User-Agent": "sendbox-website-link-check" } }); + await response.body?.cancel(); + if (method === "HEAD" && [403, 404, 405, 501].includes(response.status)) continue; + return response.status; + } +} + +async function checkExternal(externals) { + const problems = []; + const warnings = []; + const urls = [...externals.keys()]; + for (let index = 0; index < urls.length; index += 8) { + await Promise.all(urls.slice(index, index + 8).map(async (url) => { + const from = externals.get(url).slice(0, 3).join(", "); + try { + const code = await status(url); + if (code === 429) warnings.push(`${url} was rate limited (linked from ${from})`); + else if (code < 200 || code >= 400) problems.push(`${url} returned ${code} (linked from ${from})`); + } catch (error) { + problems.push(`${url} failed: ${error.cause?.code ?? error.name} (linked from ${from})`); + } + })); + } + for (const warning of warnings) console.warn(`Warning: ${warning}`); + console.log(`Requested ${urls.length} external URLs.`); + return problems; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const root = fileURLToPath(new URL("../", import.meta.url)); + const args = process.argv.slice(2); + const siteIndex = args.indexOf("--site"); + let directory = siteIndex >= 0 ? resolve(args[siteIndex + 1] ?? "") : null; + let temporary = null; + const problems = []; + try { + try { + const differences = await compareBuild(root, await buildSite(root)); + if (differences.length) problems.push(`Generated files are out of date. Run node scripts/build.mjs and commit the result:\n ${differences.join("\n ")}`); + } catch (error) { + problems.push(error.message); + } + if (!directory) { + temporary = await mkdtemp(join(tmpdir(), "sendbox-site-")); + await packageSite(root, temporary); + directory = temporary; + } + const result = await checkSite(directory); + problems.push(...result.problems); + problems.push(...checkContrast(await readFile(join(directory, "assets/styles.css"), "utf8"))); + if (args.includes("--external")) problems.push(...await checkExternal(result.externals)); + console.log(`Checked ${result.pages} pages and ${result.externals.size} distinct external links.`); + } catch (error) { + problems.push(`Check failed: ${error.message}`); + } finally { + if (temporary) await rm(temporary, { recursive: true, force: true }); + } + if (problems.length) { + console.error(`${problems.length} problem(s):\n${problems.map((problem) => `- ${problem}`).join("\n")}`); + process.exitCode = 1; + } else { + console.log("All checks passed."); + } +} diff --git a/scripts/layout.mjs b/scripts/layout.mjs new file mode 100644 index 0000000..b0ec5a2 --- /dev/null +++ b/scripts/layout.mjs @@ -0,0 +1,202 @@ +// Shared page chrome and the generated documentation pages. +import { posix } from "node:path"; +import { escapeHtml } from "./markdown.mjs"; +import { pagesOf, site } from "./catalogue.mjs"; + +// Site paths are relative to the root: "" for the home page, "sendbox/" for a directory page, +// "assets/styles.css" for a file. Every link is relative so the site also works under a path prefix. +export function relative(fromDirectory, to) { + const isDirectory = to === "" || to.endsWith("/"); + const path = posix.relative(fromDirectory.replace(/\/$/, "") || ".", to.replace(/\/$/, "") || "."); + if (!path) return "./"; + return isDirectory ? `${path}/` : path; +} + +export const pagePath = (project, page) => `${project.route}/${page.slug}/`; + +const navigation = [ + { path: "sendbox/", label: "SendBox docs", section: "sendbox" }, + { path: "fleet/", label: "Fleet docs", section: "fleet" }, + { path: "contribute/", label: "Contribute", section: "contribute" }, +]; + +export function header(directory) { + const section = directory.split("/")[0]; + const links = navigation.map((item) => { + const current = item.path === directory ? ' aria-current="page"' : item.section === section ? ' class="is-active"' : ""; + return `<li><a href="${relative(directory, item.path)}"${current}>${item.label}</a></li>`; + }); + links.push(`<li><a href="${site.org}">GitHub</a></li>`); + return `<a class="skip-link" href="#main">Skip to content</a> +<header class="site-header"> + <div class="wrap header-inner"> + <a class="brand" href="${relative(directory, "")}"${directory === "" ? ' aria-current="page"' : ""}><img src="${relative(directory, "assets/logos/sendbox.svg")}" alt="" width="32" height="32"><span>SendBox</span></a> + <nav class="site-nav" aria-label="Main"> + <ul> + ${links.join("\n ")} + </ul> + </nav> + </div> +</header>`; +} + +export function footer(directory) { + return `<footer class="site-footer"> + <div class="wrap footer-inner"> + <p>SendBox and SendBox Fleet are open source under the Apache License 2.0, built in the open by <a href="https://open.synctune.it">Synctune Open</a>.</p> + <p>This site sets no cookies and loads no scripts, analytics or third-party resources. <a href="${site.repository}">Website source</a> · <a href="${relative(directory, "contribute/")}">Contribute</a></p> + </div> +</footer>`; +} + +function head({ directory, title, description }) { + const canonical = `${site.origin}/${directory}`; + return `<!doctype html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <title>${escapeHtml(title)} + + + + + + + + + + +`; +} + +function truncate(text, length = 158) { + if (text.length <= length) return text; + return `${text.slice(0, text.lastIndexOf(" ", length - 1)).replace(/[,.;:]$/, "")}…`; +} + +function docsNav(project, directory) { + const groups = project.groups.map((group) => { + const items = group.pages.map((page) => { + const path = pagePath(project, page); + const current = path === directory ? ' aria-current="page"' : ""; + return `
  • ${escapeHtml(page.label)}
  • `; + }); + return `\n
      \n${items.join("\n")}\n
    `; + }); + const index = `${project.route}/`; + const current = index === directory ? ' aria-current="page"' : ""; + return ``; +} + +function sourceLinks(project, record, upstream) { + const repo = `https://github.com/${project.repo}`; + const short = record.commit.slice(0, 7); + return { repo, short, blob: `${repo}/blob/${record.commit}/${upstream}`, commit: `${repo}/commit/${record.commit}`, edit: `${repo}/edit/main/${upstream}` }; +} + +export function docPage({ project, page, record, rendered, previous, next }) { + const directory = pagePath(project, page); + const links = sourceLinks(project, record, page.upstream); + const title = rendered.title ?? { html: escapeHtml(page.label), text: page.label, id: "top" }; + const toc = rendered.headings.filter((heading) => heading.level === 2); + const tocHtml = toc.length >= 2 + ? `` + : ""; + const pager = [ + previous ? `Previous ${escapeHtml(previous.label)}` : "", + next ? `Next ${escapeHtml(next.label)}` : "", + ].filter(Boolean); + const description = truncate(page.summary ?? rendered.summary ?? `${page.label} for ${project.name}.`); + return `${head({ directory, title: `${page.label} | ${project.name} docs`, description })} + +${header(directory)} +
    +
    + +All ${escapeHtml(project.name)} docs +
    +
    +

    ${escapeHtml(project.name)} · ${escapeHtml(page.group)}

    +

    ${title.html}

    +
    +${tocHtml} +${rendered.html} +
    + +${pager.length ? `` : ""} +
    +${docsNav(project, directory)} +
    +${footer(directory)} + + +`; +} + +export function projectIndex({ project, record }) { + const directory = `${project.route}/`; + const links = sourceLinks(project, record, ""); + const groups = project.groups.map((group, position) => { + const id = `group-${position + 1}`; + const items = group.pages.map((page) => { + const summary = page.summary ? `${escapeHtml(page.summary)}` : ""; + return `
  • ${escapeHtml(page.label)}${summary}
  • `; + }); + const compact = group.pages.every((page) => !page.summary) ? " compact" : ""; + return `
    +

    ${escapeHtml(group.title)}${group.contributor ? ' For contributors' : ""}

    +
      +${items.join("\n")} +
    +
    `; + }); + const overview = pagesOf(project)[0]; + return `${head({ directory, title: `${project.name} documentation`, description: truncate(`${project.tagline} ${project.intro}`) })} + +${header(directory)} +
    +
    +
    + +
    +

    Documentation

    +

    ${escapeHtml(project.name)}

    +

    ${escapeHtml(project.tagline)}

    +

    ${escapeHtml(project.intro)}

    +

    ${escapeHtml(overview.label)} Source on GitHub

    +
    +
    +
    +
    +${groups.join("\n")} +

    These pages are published unchanged from ${project.repo} at commit ${links.short} (${record.committed.slice(0, 10)}). Links to files that aren't published here open on GitHub at that commit.

    +
    +
    +${footer(directory)} + + +`; +} + +export function sitemap(paths) { + const urls = paths.map((path) => ` ${site.origin}/${path}`); + return `\n\n${urls.join("\n")}\n\n`; +} + diff --git a/scripts/markdown.mjs b/scripts/markdown.mjs new file mode 100644 index 0000000..2aa8764 --- /dev/null +++ b/scripts/markdown.mjs @@ -0,0 +1,571 @@ +// A small GitHub-flavored Markdown renderer for the synced project documents. +// It covers the syntax those documents use: ATX and setext headings, paragraphs, +// emphasis, code spans and fences, links, lists, block quotes, tables and rules. +// Raw HTML is escaped, except anchors (), images and a few inline tags. + +const asciiPunctuation = /[!-/:-@[-`{-~]/; +const fenceOpen = /^( {0,3})(`{3,}|~{3,})[ \t]*(.*?)[ \t]*$/; +const fenceClose = /^ {0,3}(`{3,}|~{3,})[ \t]*$/; +const atxHeading = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*$/; +const thematicBreak = /^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})$/; +const quoteLine = /^ {0,3}> ?(.*)$/; +const setextUnderline = /^ {0,3}(=+|-+)[ \t]*$/; +const tableDelimiter = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/; +const htmlBlockStart = /^ {0,3}(?:<(?:a|img|br|p|div|details|summary|picture)\b| broker + broker -- "admit / grant / authorize / revoke" --> fleet + broker -- "request with injected credential" --> provider + people -- "profiles, roles, exceptions, audit" --> fleet + fleet --> db +``` + +## Trust boundaries + +1. **Workload to host broker.** The agent VM is untrusted. It never receives + provider credentials, and it cannot choose the principal, project, session, + policy revision, or upstream that a request is attributed to. The broker + builds every `RequestContext` from trusted host state. +2. **Host to fleet.** A SendBox host is an authenticated *worker* principal. + The fleet never holds provider credentials: credential injection stays in + the host broker, and the fleet only decides (admission, grants, + per-request authorization) and records evidence. A + compromised fleet can therefore authorize misuse but cannot leak provider + keys; a compromised host is limited to the sessions and grants the fleet + issued to it. +3. **People to fleet.** Operators and project members are authenticated *user* + principals. What they may do is decided by project-scoped roles. +4. **Fleet to database.** The database stores identifiers, digests, signed + profile bytes, and audit evidence. It stores no credentials, tokens, + authorization headers, or request bodies; there are no columns for them. + +## Authentication is separate from authorization + +- **Authentication** answers "who is calling". Every `/v1` request passes + through `auth::require_bearer` *before* routing, so an unauthenticated + request is rejected with `401` before its body is read. Only + `Authorization: Bearer ` is accepted. Identity headers such as + `X-Forwarded-User`, `X-Remote-User`, or `X-Sendbox-Principal` are ignored. + Two kinds of bearer token are accepted: + - **Service tokens** (`sbf_…`), issued with `sendbox-fleet admin token + issue` or exchanged at `POST /v1/tokens`. Only their SHA-256 is stored, + and a token works while it is unexpired (at most 90 days), unrevoked, and + its principal is not disabled. + - **Identity-provider JWTs** from an issuer in `FLEET_OIDC_CONFIG`. The + signature must verify with the issuer's published keys, and `iss`, `aud`, + `exp`, `nbf`, `iat`, required claims, and `email_verified` (for email + principals) must pass. The principal is `:`; it must exist, + be active, and have the issuer's kind, unless the issuer may auto-provision + it (with no roles). See [deployment](deployment.md#identity-providers). + + A failed token lookup or unreachable key set is `503`, never an implicit + allow. Repeated failures from one peer address, and too many requests from + one principal, get `429` with `Retry-After`. +- **Token exchange.** `POST /v1/tokens` turns an identity-provider sign-in + into a service token for hosts (`sendbox governance login`). Only JWT + callers may exchange, so a service token cannot mint another. Lifetime + defaults to `FLEET_TOKEN_TTL_SECONDS` and is capped by + `FLEET_TOKEN_MAX_TTL_SECONDS`; a principal holds at most 20 live tokens. +- **Authorization** answers "may this caller do this". It combines the caller + kind (`user` or `worker`), the fleet-wide `operator` flag, project roles, + the current profile revision, admitted sessions, grants, and exceptions, + all read from the database. +- **Workload identity fields are never authoritative.** A binding or grant + principal must equal the authenticated caller; a host cannot claim another + identity. `local-user:` principals belong to single-host increment 1 and are + rejected by both the API and the schema. + +## Roles + +| Who | May | +| --- | --- | +| Operator (fleet-wide, users only) | Publish profiles, raise minimum revisions, create projects with a first owner, manage any project's roles, revoke grants and exceptions, read and verify all audit | +| `owner` | Assign and remove roles (never leaving the project without an owner), approve or reject exceptions, run sessions | +| `admin` | Approve or reject exceptions, revoke grants (`operator_revoked`, `policy_changed`), run sessions | +| `member` | Run governed sessions, request exceptions | +| `viewer` | Read roles, exceptions, and the project's audit events | + +Workers never manage roles, profiles, or exceptions. A principal runs +sessions as itself: it needs `member` or higher in the project. + +## Request flow + +| Step | Endpoint | Checks | +| --- | --- | --- | +| Identify | `GET /v1/whoami` | Returns the authenticated principal, kind, and operator flag | +| Admit a session | `POST /v1/sessions:admit` | Binding principal is the caller; binding names this authority (`FLEET_AUTHORITY_ID`); caller holds `member` or higher; profile reference is the current revision (at or above the minimum, unexpired, digest matches); brokered services exist in the profile; every bound exception is approved, unrevoked, unexpired, for this project and principal (or project-wide), bound to this exact revision, and permitted by it. Records the canonical binding | +| End a session | `POST /v1/sessions/{session}:end` | Session principal only; revokes every live grant with the matching session reason | +| Issue a grant | `POST /v1/grants` | Caller and request match the admitted session's binding exactly; session not ended; service admitted; methods and path prefixes inside the profile service; profile current; bound exceptions still valid. Lease from the profile; hard expiry capped by the profile TTL, profile expiry, the earliest bound exception expiry, and 7 days | +| Authorize a request | `POST /v1/authorize` | `evaluate_request` against shared state, plus: the caller is the grant principal, the session is not ended, bound exceptions are still valid. Every decision is audited with a redacted target | +| Renew a lease | `POST /v1/grants/{grant}:renew` | Grant principal; not revoked or expired; lease not lapsed; session admitted; profile current; exceptions valid. Lease never exceeds the hard expiry or the earliest exception expiry | +| Revoke a grant | `POST /v1/grants/{grant}:revoke` | Session reasons by the grant principal; `operator_revoked` and `policy_changed` by an `admin`, `owner`, or operator. New requests deny at once; the grace window is the profile's `revocation_grace_seconds` (at most 60) | +| Publish a profile | `PUT /v1/profiles/{profile}` | Operator; body is the exact YAML plus the `sendbox.governance-signatures` bundle that `sendbox governance sign` writes; signatures must satisfy `FLEET_PROFILE_TRUST`; revisions only increase | +| Read a profile | `GET /v1/profiles/{profile}[?revision=N]` | Any caller; the current revision is the newest whose `not_before_unix` has passed | +| Raise the minimum | `PUT /v1/profiles/{profile}/minimum-revision` | Operator; minimums only rise; older revisions, and everything bound to them, become stale | +| Create a project | `POST /v1/projects` | Operator; the owner must be an active principal | +| List or change roles | `GET` / `POST /v1/projects/{project}/roles`, `DELETE …/roles/{principal}` | Listing needs any role (or operator); changes need `owner` (or operator); the last owner cannot be removed or demoted | +| Request an exception | `POST /v1/exceptions` | User with `member` or higher; scope is a denial the current revision lists under `exceptions`; optional principal must be a member; expiry in the future, within the profile's `exceptions.max_ttl_seconds` (at most 7 days) and before the profile expires | +| Decide an exception | `POST /v1/exceptions/{id}:approve` / `:reject` | User with `owner` or `admin`, not the requester; approval only while unexpired and its revision is still current | +| Revoke an exception | `POST /v1/exceptions/{id}:revoke` | Requester, `owner`, `admin`, or operator. Sessions admitted with it are denied on their next request or renewal | +| List exceptions | `GET /v1/exceptions?project=…&state=active\|pending\|all`, `GET /v1/exceptions/{id}` | Any role in the project (or operator) | +| Query audit events | `GET /v1/audit/events` | Operators read everything; others must pass a `project` in which they hold a role. Cursor pagination | +| Verify the chain | `GET /v1/audit/verify` | Operator; recomputes every hash and link | +| Signed chain head | `GET /v1/audit/head` | Operator; the current sequence and hash signed with `FLEET_AUDIT_SIGNING_KEY` (`503` without it) | +| Exchange a sign-in | `POST /v1/tokens` | Identity-provider caller only; `ttl_seconds` in 60 to the maximum; returns the token once with `Cache-Control: no-store` | +| List or revoke tokens | `GET /v1/tokens`, `DELETE /v1/tokens/{id}` | Callers see and revoke their own tokens (never the secret); operators may revoke any | +| Report an outcome | `POST /v1/grants/{grant}:outcome` | Grant principal; service must match the grant. Records the redacted method, path, outcome, reason, status, sizes, and duration as `request.outcome`. Outcomes are evidence only and never change a grant or a decision | + +Project identifiers contain a slash (`github:owner/repo`), so clients +percent-encode it in paths: `/v1/projects/github:owner%2Frepo/roles`. + +## HTTP responses + +Errors use RFC 9457 `application/problem+json` with `type: about:blank`, the +standard reason phrase as `title`, and a specific `detail`. + +| Status | When | +| --- | --- | +| `400` | Body, path, or query does not match the contract | +| `401` | Missing, malformed, or unaccepted bearer token (with `WWW-Authenticate: Bearer`) | +| `403` | Authenticated, but the role, kind, operator flag, profile, or signer check refuses it | +| `404` / `405` | Unknown resource or path, or unsupported method | +| `409` | Stale profile revision, stale or inactive exception, already-decided exception, ended session, duplicate admission, last owner | +| `413` / `415` | Body too large (64 KiB, 1 MiB for profile publication) or not JSON | +| `429` | Rate limit; `Retry-After` gives the seconds to wait | +| `500` | Internal failure; the cause is logged, never returned | +| `503` | Authentication or `/readyz` cannot reach the database or identity-provider keys, profile publication without `FLEET_PROFILE_TRUST`, or `GET /v1/audit/head` without a signing key | + +A per-request authorization denial is a `200` with `{"decision": "deny", +"reason": …}`; hosts deny on any other answer. + +`GET /healthz` (liveness) and `GET /readyz` (database round trip) are +unauthenticated and reveal nothing beyond availability. + +## Persistence + +`migrations/postgres` and `migrations/sqlite` define the same schema; the +server applies the matching set at startup, or with `FLEET_MIGRATE=false` +only checks that every migration was applied (by `sendbox-fleet admin +migrate` under a schema-owner role). PostgreSQL is the shared deployment +target; SQLite is for local development and tests. + +| Table | Holds | +| --- | --- | +| `principals` | Authenticated users and workers (never `local-user:`), with the operator flag | +| `api_tokens` | SHA-256 of each service token (admin-issued or exchanged), description, expiry (at most 90 days), revocation | +| `projects` | `github:owner/repo` or `path-sha256:` projects | +| `role_bindings` | One project-scoped role per principal per project | +| `profiles` | Exact signed bytes, digest, signatures, validity window per revision | +| `profile_minimum_revisions` | Oldest revision still accepted per profile | +| `sessions` | Admitted sessions with their canonical binding and digest | +| `credential_grants` | Grant scope, lease, hard expiry, generation; no credential material | +| `revocations` | Reason, actor, bounded grace window | +| `exceptions` | One liftable denial (`command`, `domain`, `network`), reason, requester, approver, expiry, revocation, exact profile revision | +| `session_exceptions` | Exceptions each session was admitted with | +| `audit_events` | Append-only, hash-chained evidence with a redacted target, the exception concerned, and a short non-secret detail | + +Constraints carry the invariants the database can check: identifier grammar, +7-day grant and exception lifetimes, 90-day tokens, a 60-second revocation +grace, approvers who differ from requesters, grants whose principal, project, +binding, and profile must equal their session's (composite foreign key), and +audit rows that must extend the chain and can never be updated or deleted +(triggers). + +Writers are serialized (SQLite `BEGIN IMMEDIATE`, PostgreSQL transaction +advisory lock), so check-then-write decisions cannot race. Every state change +and the audit event that records it commit in one transaction; a refused, +security-relevant request commits only its audit event. + +## Audit + +Each event records the actor (the authenticated caller, or `cli:admin`), the +principal, project, session, grant, exception, and profile revision it +concerns, the decision and deny reason, an outcome, a redacted target +(`METHOD service/path`, never a query string), and a short detail such as +`role=admin` or `scope=domain:gist.github.com`. Credentials, tokens, headers, +request or response bodies, and exception reasons are never recorded. + +`event_hash` is the SHA-256 of the RFC 8785 canonical JSON of the event as +returned by `GET /v1/audit/events` without `event_hash` (so it includes +`previous_hash`). The first event links to 64 zeros. `GET /v1/audit/verify` +recomputes the chain. + +The chain alone cannot stop someone who can rewrite the table and recompute +every hash, such as a database owner. With `FLEET_AUDIT_SIGNING_KEY`, the +service signs chain heads (`sendbox-fleet-audit-head` v1: authority, +sequence, event hash, time) with an Ed25519 key in SendBox's provenance +envelope. With `FLEET_AUDIT_ANCHOR_DIR`, it writes one to that directory at +startup and on every interval in which the chain advanced, never overwriting +an anchor. `sendbox-fleet admin audit verify --identity … --anchor …` +recomputes the chain and checks each anchor's signature and that the database +still holds its hash at its sequence. + +Other audit events added for authentication: `principal.provisioned`, +`token.issued`, and `token.revoked` (token ids, never tokens). + +## Logging + +Structured JSON lines go to stdout and to `sendbox-fleet.YYYY-MM-DD.log` in +`FLEET_LOG_DIR`, rotated at each UTC day and at `FLEET_LOG_MAX_BYTES`, and +pruned after 30 days. Request +bodies, headers, and query strings are never logged. Details in +[development.md](development.md#logs). + +## Code layout + +```text +crates/fleet-server/src/ + main.rs process entry: serve (default) or `admin` subcommands + admin.rs bootstrap: principals, tokens, projects, audit keys, migrate + server.rs app assembly, startup, graceful shutdown, background tasks + config.rs environment configuration and profile trust loading + state.rs shared state: database, clock, random ids, authority id, trust, limits + oidc.rs identity-provider configuration and JWT/JWKS verification + anchor.rs signed audit heads, anchoring, anchor verification + ratelimit.rs per-principal and per-peer token buckets + metrics.rs Prometheus counters and the metrics listener + logging.rs subscriber setup and request logging middleware + logging/rotation.rs, logging/retention.rs + db.rs pools, migrations, readiness, backend-neutral transactions and rows + governance.rs stored roles, profiles, sessions, grants, and exceptions + audit.rs hash-chained append, queries, chain verification + problem.rs RFC 9457 problem responses + auth.rs bearer middleware, service-token and identity-provider authenticators + routes/ health probes and the /v1 API +migrations/{postgres,sqlite}/ +deploy/postgres/roles.sql least-privilege owner and runtime roles +``` diff --git a/vendor/sendbox-fleet/docs/assets/logo.svg b/vendor/sendbox-fleet/docs/assets/logo.svg new file mode 100644 index 0000000..eee6f49 --- /dev/null +++ b/vendor/sendbox-fleet/docs/assets/logo.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/vendor/sendbox-fleet/docs/contract.md b/vendor/sendbox-fleet/docs/contract.md new file mode 100644 index 0000000..1ecbc5e --- /dev/null +++ b/vendor/sendbox-fleet/docs/contract.md @@ -0,0 +1,96 @@ +# Shared contract + +SendBox hosts and this service must agree byte-for-byte on identities, +profile references, session bindings, grants, request contexts, and +decisions. That agreement lives in one crate, `sendbox-governance`, in the +[sendbox](https://github.com/mbianchidev/sendbox) repository +(`crates/sendbox-governance`). This service depends on it instead of +redefining any of those types. + +## How it is pinned + +```toml +# Cargo.toml (workspace) +sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", branch = "main" } +sendbox-security = { git = "https://github.com/mbianchidev/sendbox", branch = "main" } +``` + +`sendbox-security` supplies the signing envelope and trust store used for +profile signatures and audit heads. + +- The dependency tracks sendbox `main`, and `Cargo.lock` records the exact + commit. CI builds with `--locked`, so every build sees the same contract + until the lockfile moves. +- [Dependabot](../.github/dependabot.yml) checks sendbox `main` daily and opens + one pull request (group `sendbox-contract`) that moves `Cargo.lock` to the + latest commit. The + [auto-merge workflow](../.github/workflows/dependabot-auto-merge.yml) enables + auto-merge when that pull request updates nothing but `sendbox-governance` + and `sendbox-security`, and branch protection merges it only after every CI + job passes. A contract change that breaks this service leaves the pull + request open with failing checks for a maintainer to fix. +- Both crates inherit versions from the sendbox workspace and depend on + `sendbox-core` by path; Cargo resolves all three from the same git checkout, + so they always share one commit. +- Only `main` is tracked, so the recorded commit cannot disappear when sendbox + feature branches are rewritten or deleted. A pull request that needs an + unmerged contract change may track the sendbox pull request branch while + both are in review. CI's last step, + [`scripts/check-contract-pin.sh`](../scripts/check-contract-pin.sh), fails + until every SendBox crate is locked to a sendbox `main` commit again (it also + rejects `rev`/`tag` pins and local path patches), so such a pull request + cannot merge. After the sendbox pull request merges, set `branch = "main"` + and run `cargo update -p sendbox-governance -p sendbox-security`. + +To move the lockfile by hand, to the latest `main` commit or to a specific one: + +```sh +cargo update -p sendbox-governance -p sendbox-security +cargo update -p sendbox-governance --precise # moves all three crates +scripts/check-contract-pin.sh +cargo test --locked --workspace +``` + +## What the API reuses + +| Contract type | Used by | +| --- | --- | +| `api::CallerIdentity` | `GET /v1/whoami` response | +| `api::SessionAdmissionRequest`, `api::SessionAdmission`, `GovernanceBinding` | `POST /v1/sessions:admit` body and response | +| `api::SessionEnd` | `POST /v1/sessions/{session}:end` body | +| `GrantRequest`, `CredentialGrant` | `POST /v1/grants` body and response | +| `GrantId` | `:renew` and `:revoke` path parameter; renew response is a `CredentialGrant` | +| `api::RevokeGrantRequest`, `RevocationReason` | `:revoke` body | +| `RequestContext`, `Decision`, `DenyReason`, `evaluate_request` | `POST /v1/authorize` body, response, and decision rules | +| `ProfileId`, `ProfileRef`, `GovernanceProfile`, `check_current` | `/v1/profiles/{profile_id}`; publication bodies are parsed with `GovernanceProfile::parse` | +| `PolicyException`, `ExceptionScope`, `ExceptionId`, `api::ExceptionList` | `/v1/exceptions` responses; scopes are checked with `GovernanceProfile::permits_exception` | +| `ProjectId`, `PrincipalId` | Role, exception, and audit endpoints | +| `Sha256Digest`, `canonical_digest` | Digests in responses, binding storage, and audit event hashes | +| `api::TokenRequest`, `api::IssuedToken` | `POST /v1/tokens` body and response | +| `api::RequestOutcomeReport`, `api::ReportedOutcome` | `POST /v1/grants/{grant}:outcome` body, checked with `RequestOutcomeReport::validate` | + +Validation is the contract's own: identifier grammars, `deny_unknown_fields`, +`GovernanceBinding::validate`, `validate_method`, `validate_path_prefix`, and +`GovernanceProfile::parse`. Invalid input is a `400` problem. + +Wire types a SendBox host also uses live in `sendbox_governance::api`. Types +only people use live here, in the route module that uses them: +`CreateProject`, `ProjectRole` and `RoleBinding`, `ExceptionRequest`, +`ProfilePublication` and `MinimumRevision`, `TokenSummary` and `TokenList`, +and the audit query, page, event, and signed-head types. Profile signatures use SendBox's signing envelope +(`sendbox_security::provenance::DetachedSignature` in a +`sendbox.governance-signatures` bundle), verified with the same trust store +code as hosts. + +## Versioning + +- `sendbox_governance::CONTRACT_VERSION` (currently `2`, which added + exceptions to the session binding) is the wire and digest version. `GovernanceBinding` and `CredentialGrant` carry it, and validation + rejects any other value. The server logs it at startup. +- Contract structs use `deny_unknown_fields`, so adding a field is a breaking + change for older peers. Any change to a contract type or to how digests are + computed requires bumping `CONTRACT_VERSION` in the sendbox repository and + then updating this pin; hosts and the fleet must be upgraded together or + support both versions during the transition. +- The `/v1` path prefix versions the HTTP API surface (routes, fleet-only + types, problem format). It changes independently of `CONTRACT_VERSION`. diff --git a/vendor/sendbox-fleet/docs/deployment.md b/vendor/sendbox-fleet/docs/deployment.md new file mode 100644 index 0000000..fa4c31c --- /dev/null +++ b/vendor/sendbox-fleet/docs/deployment.md @@ -0,0 +1,254 @@ +# Deployment + +How to run `sendbox-fleet` for a team. [Development](development.md) covers +local runs; this page covers a shared, production-like setup. Every setting +here is an environment variable listed in +[development.md](development.md#configuration). + +```mermaid +flowchart LR + hosts["SendBox hosts and people"] -- "HTTPS" --> proxy["Reverse proxy
    (TLS, request limits)"] + proxy -- "HTTP on a private network" --> fleet["sendbox-fleet
    FLEET_MIGRATE=false"] + fleet -- "sendbox_fleet_app role" --> pg[("PostgreSQL")] + fleet -. "JWKS over HTTPS" .-> idp["Identity providers"] + fleet -- "signed audit heads" --> anchors[("Write-once storage")] + prom["Prometheus"] -- "FLEET_METRICS_BIND" --> fleet +``` + +## Checklist + +1. PostgreSQL with the least-privilege roles below. SQLite is for development + only. +2. A reverse proxy that terminates TLS. The service itself speaks plain HTTP. +3. `FLEET_AUTHORITY_ID` set to the value every host puts under `authority:`. +4. `FLEET_PROFILE_TRUST` naming the operators who sign profiles. +5. `FLEET_OIDC_CONFIG` for people and CI, or admin-issued tokens only. +6. An audit signing key and an anchor directory on storage the database + administrators cannot rewrite. +7. Metrics on a private address, log shipping from stdout or `FLEET_LOG_DIR`, + and database backups. + +## TLS and the reverse proxy + +Bearer tokens must only travel over TLS. Run the service on a private address +(`FLEET_BIND=10.0.0.5:8080`, or the Compose network) behind a proxy such as +nginx, Caddy, Envoy, or a cloud load balancer that: + +- terminates TLS 1.2 or later with a certificate hosts trust; +- forwards the `Authorization` header unchanged and adds no identity headers + (the service ignores `X-Forwarded-User` and similar anyway); +- does not cache responses (token exchange already sends + `Cache-Control: no-store`); +- limits request rates per client address. + +The service rate limits per process: `FLEET_RATE_LIMIT_PER_MINUTE` requests +per authenticated principal, and `FLEET_AUTH_FAILURES_PER_MINUTE` failed +authentications per peer address. Behind a proxy every client shares the +proxy's address, so the failure limit throttles all clients together when one +of them sends bad tokens. Either set `FLEET_AUTH_FAILURES_PER_MINUTE=0` and +rely on the proxy's per-client limit, or raise it well above normal traffic. +`X-Forwarded-For` is not trusted. + +Limits are per instance. With several instances, the effective limit is the +per-instance value times the instance count. + +## PostgreSQL roles and migrations + +[`deploy/postgres/roles.sql`](../deploy/postgres/roles.sql) creates two +roles: + +| Role | Can | +| --- | --- | +| `sendbox_fleet_owner` | Owns the schema; runs `sendbox-fleet admin migrate` | +| `sendbox_fleet_app` | Reads and writes operational tables; only `SELECT` and `INSERT` on `audit_events`; only `SELECT` on `_sqlx_migrations`; cannot create, alter, or drop anything | + +```sh +psql -v ON_ERROR_STOP=1 -d sendbox_fleet -f deploy/postgres/roles.sql # as a superuser +psql -d sendbox_fleet -c "ALTER ROLE sendbox_fleet_owner PASSWORD '…'" +psql -d sendbox_fleet -c "ALTER ROLE sendbox_fleet_app PASSWORD '…'" +FLEET_DATABASE_URL=postgres://sendbox_fleet_owner:…@db/sendbox_fleet sendbox-fleet admin migrate +psql -v ON_ERROR_STOP=1 -d sendbox_fleet -f deploy/postgres/roles.sql # grants on the new tables +``` + +Then run the service as `sendbox_fleet_app` with `FLEET_MIGRATE=false`. It +refuses to start while a migration is missing and names the fix. Admin +commands run with `FLEET_MIGRATE=false` also check instead of migrating, so +they work with the app role. On upgrade: stop the old version, run +`admin migrate` as the owner, rerun `roles.sql`, then start the new version. + +The audit triggers stop the app role and anyone without `ALTER` on the table. +The owner and superusers can still disable them, which is what audit +anchoring is for. + +## Identity providers + +`FLEET_OIDC_CONFIG` points at a YAML file of trusted issuers. Without it, only +service tokens from `sendbox-fleet admin token issue` authenticate. + +```yaml +issuers: + # People: the principal is `oidc:`. + - issuer: https://accounts.google.com + audiences: ["123456789-example.apps.googleusercontent.com"] + kind: user + principal_claim: email + principal_prefix: oidc + # CI: GitHub Actions jobs from one organization, as `github-actions:`. + - issuer: https://token.actions.githubusercontent.com + audiences: [sendbox-fleet] + kind: worker + principal_claim: repository_id + principal_prefix: github-actions + required_claims: + repository_owner: example + auto_provision: true +``` + +| Field | Default | Meaning | +| --- | --- | --- | +| `issuer` | required | Exact `iss`; `https://` (or `http://` on loopback for tests) | +| `audiences` | required | At least one must appear in `aud` | +| `kind` | required | `user` or `worker`; an existing principal of the other kind is refused | +| `principal_claim` | required | Claim that names the principal; string or number | +| `principal_prefix` | required | Unique per issuer, lowercase letters or `-`, not `local-user` | +| `require_email_verified` | true when the claim is `email` | Require `email_verified: true` | +| `auto_provision` | `false` | Create unknown principals on first sign-in, with no roles and no operator flag, audited as `principal.provisioned` | +| `jwks_uri` | from discovery | Skip `/.well-known/openid-configuration` | +| `algorithms` | `RS256`, `ES256`, `EdDSA` | Accepted signature algorithms | +| `required_claims` | none | Claims that must equal these strings | +| `jwks_cache_seconds` | `600` | Key cache lifetime (60 to 86400) | +| `leeway_seconds` | `60` | Clock skew for `exp`, `nbf`, and `iat` (at most 300) | + +Keys are fetched over HTTPS with the system CA bundle, without proxies or +redirects, and cached. An unknown key id refreshes the key set at most every +30 seconds. If keys cannot be fetched and none are cached, callers get `503`; +cached keys keep working through an outage. + +Keep `auto_provision` off for people unless anyone who can sign in to the +provider may hold a principal; roles still have to be granted per project. +For CI, `required_claims` is what limits which repositories can sign in. + +### Signing in from a SendBox host + +A JWT from a configured issuer authenticates any `/v1` call directly, but +provider tokens are short-lived. Hosts exchange one for a fleet service token: + +```sh +my-idp print-id-token | sendbox governance login +``` + +`POST /v1/tokens` accepts only identity-provider callers, so a leaked service +token cannot mint more. Exchanged tokens last `FLEET_TOKEN_TTL_SECONDS` +(12 hours) unless the request asks for less or up to +`FLEET_TOKEN_MAX_TTL_SECONDS` (7 days); a principal holds at most 20 live +tokens. `GET /v1/tokens` lists the caller's tokens and +`DELETE /v1/tokens/{id}` revokes one; operators can revoke any token. + +In GitHub Actions, request an ID token with the fleet's audience (the job +needs `permissions: id-token: write`), then pass it to `sendbox governance +login --identity-token-file`. + +## Audit anchoring + +The audit chain detects edits by anyone who cannot recompute every later hash. +A database owner can. Anchors fix that: a signed copy of the chain head, kept +where the database administrators cannot rewrite it. + +```sh +sendbox-fleet admin audit keygen --output /etc/sendbox-fleet/audit.key > audit-identity.json +``` + +The key file is created with mode `0600`; the service refuses to load a key +that group or others can access. Keep it off the database host and out of database backups; publish +`audit-identity.json` to whoever verifies the log. + +| Setting | Effect | +| --- | --- | +| `FLEET_AUDIT_SIGNING_KEY` | Enables `GET /v1/audit/head` (operators): the current head, signed | +| `FLEET_AUDIT_ANCHOR_DIR` | Writes `audit-head-.json` there at startup and every `FLEET_AUDIT_ANCHOR_INTERVAL_SECONDS` (default 3600) when the chain has advanced | + +Point `FLEET_AUDIT_ANCHOR_DIR` at write-once storage, such as an object-store +bucket with object lock mounted into the container, or a directory another +system collects. Anchors are never overwritten. Without a mounted directory, +an external job can call `GET /v1/audit/head` or run +`sendbox-fleet admin audit anchor --output DIR`. + +To check the log: + +```sh +sendbox-fleet admin audit verify --identity audit-identity.json \ + --anchor anchors/audit-head-00000000000000001234.json … +``` + +It recomputes the chain and checks that each anchor's signature verifies and +that the database still holds the anchored hash at that sequence. It prints +one JSON line per result and exits non-zero on any failure. + +## Metrics + +Set `FLEET_METRICS_BIND` (for example `10.0.0.5:9090`) to serve Prometheus +text at `/metrics` on a second listener. It has no authentication, so keep it +on a private network; it is never served on `FLEET_BIND`. + +| Metric | Type | Meaning | +| --- | --- | --- | +| `fleet_http_requests_total{class}` | counter | Requests by status class (`2xx`, `4xx`, …) | +| `fleet_http_request_duration_seconds_sum` / `_count` | summary | Request time | +| `fleet_auth_failures_total` | counter | Rejected bearer tokens | +| `fleet_rate_limited_total` | counter | `429` answers | +| `fleet_authorization_decisions_total{decision,reason}` | counter | `/v1/authorize` results by deny reason | +| `fleet_audit_events_total` | counter | Events appended by this process | +| `fleet_audit_sequence` | gauge | Highest audit sequence | + +Labels never contain principals, projects, sessions, or tokens. Useful alerts: +a rising `5xx` rate, `fleet_auth_failures_total` spikes, and +`fleet_authorization_decisions_total{reason="authority_unavailable"}`. + +## Logs + +Logs go to stdout and `FLEET_LOG_DIR`. Files rotate at UTC midnight and when +they reach `FLEET_LOG_MAX_BYTES` (100 MiB), and are pruned after +`FLEET_LOG_RETENTION_DAYS`. In containers, ship stdout and keep the volume +small. See [development.md](development.md#logs). + +## Backups and restore + +- **PostgreSQL**: `pg_dump --format=custom sendbox_fleet` on a schedule, or + continuous archiving for point-in-time recovery. Store dumps encrypted and + away from the database host. +- **SQLite** (development only): `sqlite3 sendbox-fleet.db ".backup copy.db"` + while the service runs. +- Back up `FLEET_PROFILE_TRUST`, `FLEET_OIDC_CONFIG`, and the audit identity + with the deployment configuration. Back up the audit signing key separately. + +The database holds token digests, not tokens, so a restored backup cannot be +used to sign in. Tokens revoked after the backup become valid again after a +restore, as do principals disabled after it: revoke and disable them again. + +After a restore, run `sendbox-fleet admin audit verify` with the newest +anchors. Anchors newer than the backup fail with "the database no longer +holds this sequence", which documents exactly what the restore lost. + +## Compose + +[`docker-compose.yml`](../docker-compose.yml) passes every setting through +from `.env` and mounts a `fleet-anchors` volume at +`/var/lib/sendbox-fleet/anchors`. Mount the trust file, OIDC file, and audit +key with an override file: + +```yaml +# docker-compose.override.yml +services: + fleet: + environment: + FLEET_PROFILE_TRUST: /etc/sendbox-fleet/profile-trust.yaml + FLEET_OIDC_CONFIG: /etc/sendbox-fleet/oidc.yaml + FLEET_AUDIT_SIGNING_KEY: /run/sendbox-fleet/audit.key + FLEET_AUDIT_ANCHOR_DIR: /var/lib/sendbox-fleet/anchors + volumes: + - ./config:/etc/sendbox-fleet:ro + - ./audit-key:/run/sendbox-fleet:ro +``` + +The service runs as uid 10001, so `./audit-key/audit.key` must be owned by +that uid with mode `0600` or `0400`. diff --git a/vendor/sendbox-fleet/docs/development.md b/vendor/sendbox-fleet/docs/development.md new file mode 100644 index 0000000..ce9c189 --- /dev/null +++ b/vendor/sendbox-fleet/docs/development.md @@ -0,0 +1,191 @@ +# Development + +## Prerequisites + +- [rustup](https://rustup.rs). The pinned toolchain (Rust 1.100.0 with + clippy and rustfmt) installs automatically from `rust-toolchain.toml`. +- A Docker-compatible engine with Compose, only for the PostgreSQL stack. + +## Configuration + +The server reads its configuration from the environment at startup and exits +with status `2` and a message naming the variable when a value is invalid. + +| Variable | Default | Meaning | +| --- | --- | --- | +| `FLEET_DATABASE_URL` | required | `sqlite://path.db?mode=rwc`, `sqlite::memory:`, or `postgres://user:password@host:5432/db` | +| `FLEET_BIND` | `127.0.0.1:8080` | Listen address | +| `FLEET_LOG_DIR` | `./logs` | Log directory; relative paths resolve against the working directory at startup | +| `FLEET_LOG_LEVEL` | `info,sqlx=warn` | [`EnvFilter`](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html) directives | +| `FLEET_LOG_RETENTION_DAYS` | `30` | Days to keep rotated log files (1 to 3650) | +| `FLEET_AUTHORITY_ID` | `sendbox-fleet` | Authority id hosts put in `authority:` of their operator configuration and bind into every session; not `local` | +| `FLEET_PROFILE_TRUST` | unset | YAML or JSON file with `threshold` and `signers` (the same shape as a host operator configuration's `trust` section). Profile publication is refused until it is set | +| `FLEET_OIDC_CONFIG` | unset | YAML file of trusted identity providers ([format](deployment.md#identity-providers)). Unset: only service tokens authenticate | +| `FLEET_TOKEN_TTL_SECONDS` | `43200` (12 h) | Default lifetime of tokens from `POST /v1/tokens` | +| `FLEET_TOKEN_MAX_TTL_SECONDS` | `604800` (7 d) | Longest lifetime a caller may request (at most 90 days) | +| `FLEET_AUDIT_SIGNING_KEY` | unset | Key from `admin audit keygen` (no group or other access). Enables `GET /v1/audit/head` | +| `FLEET_AUDIT_ANCHOR_DIR` | unset | Directory for periodic signed heads; needs the signing key | +| `FLEET_AUDIT_ANCHOR_INTERVAL_SECONDS` | `3600` | Anchoring interval (60 to 86400) | +| `FLEET_RATE_LIMIT_PER_MINUTE` | `1200` | `/v1` requests per principal per minute; `0` disables | +| `FLEET_AUTH_FAILURES_PER_MINUTE` | `60` | Failed authentications per peer address per minute; `0` disables | +| `FLEET_METRICS_BIND` | unset | Separate listener for Prometheus `/metrics`; must differ from `FLEET_BIND` | +| `FLEET_MIGRATE` | `true` | `false`: never change the schema; refuse to start until `admin migrate` has run | +| `FLEET_LOG_MAX_BYTES` | `104857600` (100 MiB) | Rotate the log file at this size (1 MiB to 10 GiB) | + +Database credentials in `FLEET_DATABASE_URL` are never logged. + +## Run locally with SQLite + +```sh +export FLEET_DATABASE_URL='sqlite://sendbox-fleet.db?mode=rwc' +cargo run --bin sendbox-fleet + +curl -i http://127.0.0.1:8080/healthz +curl -i http://127.0.0.1:8080/readyz +curl -i -X POST http://127.0.0.1:8080/v1/authorize # 401: authentication required +``` + +Migrations run at startup. Stop the server with Ctrl-C (or `SIGTERM`); it +stops accepting connections, gives in-flight requests up to 30 seconds, +closes the database pool, and flushes logs. + +## Bootstrap principals, tokens, and projects + +`sendbox-fleet admin` acts on the database directly and needs only +`FLEET_DATABASE_URL` (and honors `FLEET_MIGRATE`). Every change is audited +with the actor `cli:admin`. + +```sh +sendbox-fleet admin principal add oidc:olivia@example.com --kind user --operator +sendbox-fleet admin principal add oidc:owen@example.com --kind user +sendbox-fleet admin principal add worker:ci-1 --kind worker +sendbox-fleet admin project create github:example/service --owner oidc:owen@example.com +sendbox-fleet admin token issue oidc:owen@example.com --ttl-days 30 > owen.token +sendbox-fleet admin token list oidc:owen@example.com +sendbox-fleet admin token revoke +sendbox-fleet admin principal disable oidc:owen@example.com +``` + +`token issue` prints the token once on stdout; only its SHA-256 is stored. +People then use the API with `Authorization: Bearer `, for example: + +```sh +T=$(cat owen.token); U=http://127.0.0.1:8080 +curl -H "Authorization: Bearer $T" $U/v1/whoami +curl -H "Authorization: Bearer $T" -H 'Content-Type: application/json' \ + -d '{"principal":"oidc:alice@example.com","role":"member"}' \ + "$U/v1/projects/github:example%2Fservice/roles" +``` + +An operator publishes the exact profile and the signature bundle produced by +`sendbox governance sign`: + +```sh +jq -n --rawfile document acme.yaml --slurpfile signatures acme.yaml.sig.json \ + '{document: $document, signatures: $signatures[0]}' | + curl -X PUT -H "Authorization: Bearer $OPERATOR_TOKEN" \ + -H 'Content-Type: application/json' --data @- $U/v1/profiles/acme +``` + +On each SendBox host, the operator configuration names this service and the +caller stores their own token: `sendbox secrets add SENDBOX_FLEET_TOKEN`. + +With `FLEET_OIDC_CONFIG`, people and CI sign in with their identity provider +instead, and hosts exchange that sign-in for a service token with +`sendbox governance login`. See [deployment](deployment.md#identity-providers). + +Other admin commands: + +```sh +sendbox-fleet admin migrate # apply migrations only +sendbox-fleet admin audit keygen --output audit.key > audit-identity.json +FLEET_AUDIT_SIGNING_KEY=audit.key sendbox-fleet admin audit anchor --output anchors/ +sendbox-fleet admin audit verify --identity audit-identity.json --anchor anchors/audit-head-*.json +``` + +## Run with PostgreSQL (Compose) + +```sh +cp .env.example .env # set POSTGRES_PASSWORD (URL-safe characters) +docker compose build --no-cache && docker compose up +``` + +The server listens on `127.0.0.1:${FLEET_PORT:-8080}`. The container runs as +an unprivileged user with a read-only root filesystem; logs go to the +`fleet-logs` volume. `docker compose down` stops the stack and keeps data; +`docker compose down --volumes` also deletes the database and logs. + +## Checks + +```sh +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets -- -D warnings +cargo test --locked --workspace +cargo audit --deny warnings # needs cargo-audit; see .cargo/audit.toml +scripts/check-contract-pin.sh # SendBox crates locked to sendbox main +``` + +Tests use in-memory SQLite and synthetic data. To run the migration and API +tests against PostgreSQL, point `FLEET_TEST_DATABASE_URL` at a disposable +database whose name ends in `_test` (the tests drop and recreate its `public` +schema): + +The PostgreSQL run also checks `deploy/postgres/roles.sql` by connecting as +its roles, which the trust authentication below allows. + +```sh +docker run -d --name sendbox-fleet-pg-test -p 127.0.0.1:55432:5432 \ + -e POSTGRES_DB=sendbox_fleet_test -e POSTGRES_USER=sendbox_fleet \ + -e POSTGRES_HOST_AUTH_METHOD=trust postgres:18.7-alpine3.24 +FLEET_TEST_DATABASE_URL=postgres://sendbox_fleet@127.0.0.1:55432/sendbox_fleet_test \ + cargo test --locked --workspace --test migrations --test http -- --test-threads=1 +docker rm -f sendbox-fleet-pg-test +``` + +CI runs formatting, Clippy, and tests on SQLite; the migration and API tests +plus a start, probe, and graceful-stop run of the server on PostgreSQL; and +`cargo audit`. + +## Logs + +- Every event is a JSON line written to stdout and to + `FLEET_LOG_DIR/sendbox-fleet.YYYY-MM-DD.log`. A new file starts at each UTC + midnight, and whenever the live file reaches `FLEET_LOG_MAX_BYTES` the next + part continues in `sendbox-fleet.YYYY-MM-DD.1.log`, `.2.log`, and so on. + Files are created with mode `0600`. +- Retention runs at startup and then hourly. It deletes only regular files + named `sendbox-fleet.YYYY-MM-DD.log` or `sendbox-fleet.YYYY-MM-DD.N.log` + whose UTC day ended at least `FLEET_LOG_RETENTION_DAYS` days ago, judged by + the date in the name rather than the modification time. Other files, directories, and symlinks are left + alone; deletion failures are logged and retried at the next run. +- The log directory is created with mode `0700`. +- File writes go through a bounded queue of 16,384 events. When it is full, + logging callers wait instead of dropping events. +- Never logged: request bodies, headers (including `Authorization`), query + strings, and database credentials. + +## Migrations + +Schema changes need a new, numbered file in **both** `migrations/postgres` and +`migrations/sqlite` with equivalent constraints. Never edit a migration that +has been applied anywhere: sqlx records checksums and refuses to start on a +mismatch. Add a test in `crates/fleet-server/tests/migrations.rs` for any new +invariant. + +## Troubleshooting + +| Symptom | Cause | +| --- | --- | +| `configuration error: FLEET_DATABASE_URL is required` (exit 2) | Export a database URL | +| `cannot connect to postgres://***@...` | Database not reachable or wrong credentials | +| `cannot listen on ...` | Port already in use; set `FLEET_BIND` or `FLEET_PORT` | +| `cannot create log directory` | `FLEET_LOG_DIR` not writable by the server user | +| Every `/v1` call returns `401 bearer token was not accepted` | The token is unknown, expired, revoked, or its principal is disabled; issue a new one with `sendbox-fleet admin token issue` | +| `503 profile signers are not configured` on profile publication | Set `FLEET_PROFILE_TRUST` | +| `409 ... is not the current revision` on session admission | The host's local profile differs from the newest published revision; install the same signed bytes on the host | +| `migrations … are not applied; run sendbox-fleet admin migrate` | `FLEET_MIGRATE=false` and the schema is behind; run `admin migrate` as the schema owner | +| `permission denied for schema public` at startup | The runtime role cannot migrate; set `FLEET_MIGRATE=false` and migrate as the owner | +| `401` for an identity-provider token | Issuer, audience, expiry, key, required claim, or `email_verified` did not match, or the principal is unknown, disabled, or of the other kind. The server log names the reason (for example `expired`, `audience_mismatch`, `not_registered`); callers only see `401` | +| `503 identity provider keys are unavailable` | The issuer's discovery or JWKS endpoint is unreachable and no keys are cached | +| `429 rate limit exceeded` | Wait `Retry-After` seconds; behind a proxy, see [deployment](deployment.md#tls-and-the-reverse-proxy) | +| `… must not be accessible by group or others` | `chmod 600` the audit signing key | diff --git a/vendor/sendbox-fleet/docs/roadmap.md b/vendor/sendbox-fleet/docs/roadmap.md new file mode 100644 index 0000000..eae98c2 --- /dev/null +++ b/vendor/sendbox-fleet/docs/roadmap.md @@ -0,0 +1,89 @@ +# Roadmap + +Increment-2 work for +[mbianchidev/sendbox#87](https://github.com/mbianchidev/sendbox/issues/87). +Each item names the issue's acceptance criteria (AC) it serves: + +- **AC1** A trusted shared profile is enforced at actual session admission and + execution; project configuration and CLI flags cannot broaden or bypass it. +- **AC4** Cross-principal, project, or session requests, changed policy + bindings, and forbidden destinations, methods, or paths are rejected at the + enforcement boundary. +- **AC5** Expired or revoked grants, stale policy, and unavailable + authorization produce explicit denial without credential export or fallback. +- **AC6** Session cancellation and teardown end grants while preserving + redacted audit evidence and reporting uncertain external outcomes honestly. +- **AC7** The shared-service increment enforces project-scoped roles and + authorized, expiring exceptions with attributable audit records. +- **AC8** Standalone workflows stay unchanged unless governance is selected; + compatibility and trust boundaries are documented. + +## Done + +The scaffold delivered the service skeleton, the schema with its database +invariants, CI, and these documents. Increment 2 then delivered: + +- **Caller authentication** (AC7). Opaque bearer tokens issued by + `sendbox-fleet admin token issue`, stored only as SHA-256 digests, expiring + within 90 days, revocable, and void when the principal is disabled. The + bearer-only rule and "authenticate before validating" ordering are kept. +- **Persistence** (all). Backend-neutral transactions over PostgreSQL and + SQLite with serialized writers, an injectable clock, random identifiers, + and every change committed with its audit event. +- **Profiles** (AC1, AC5). Publication verified against `FLEET_PROFILE_TRUST` + using the `sendbox.governance-signatures` bundle from `sendbox governance + sign`; monotonic revisions; current-revision lookup; rising minimums. +- **Project-scoped roles** (AC7). Operator project bootstrap, owner-managed + assignment and removal, last-owner guard, audited refusals. Roles gate + admission, exceptions, and audit visibility. +- **Session admission** (AC1, AC4). Caller-bound principal, this authority, + `member` role, current revision, offered services, and valid exceptions. +- **Grants and revocation** (AC4, AC5, AC6). Issue, renew, revoke, and end + sessions with bounded leases, exception-capped expiry, and the profile grace + window. The SendBox host's remote authority client lives in the sendbox + repository. +- **Per-request authorization** (AC4, AC5). Same rules as the local authority + through the shared `evaluate_request`, plus session and exception state. +- **Exceptions** (AC7). Request, approve, reject, revoke; a different + `owner` or `admin` approves; scope limited to denials the signed revision + lists as liftable; expiry at most 7 days; stale approvals rejected after a + new revision or minimum. +- **Central audit** (AC6, AC7). Hash-chained events for every decision with + actor, principal, project, session, grant, exception, revision, decision, + redacted target, and detail; role-scoped queries; chain verification. +- **Identity providers** (AC7). Any OpenID Connect issuer for people and + machine identities such as GitHub Actions: JWKS verification with `ring` + (`RS256`, `ES256`, `EdDSA`), exact issuer and audience, required claims, + verified email, optional auto-provisioning without roles. `POST + /v1/tokens` exchanges a sign-in for a short-lived service token, which + `sendbox governance login` stores on the host; tokens can be listed and + revoked. +- **Outcomes and anchoring** (AC6, AC7). Hosts report each brokered stream's + outcome (`succeeded`, `failed`, `unknown`) to `POST + /v1/grants/{grant}:outcome`, recorded as `request.outcome`. Chain heads are + signed (`GET /v1/audit/head`), written periodically to an anchor directory, + and checked with `sendbox-fleet admin audit verify`. +- **Operations** (AC8). Least-privilege PostgreSQL roles + (`deploy/postgres/roles.sql`, no `UPDATE`/`DELETE` on audit for the + runtime role), `FLEET_MIGRATE=false` with `admin migrate`, per-principal and + per-peer rate limits, Prometheus metrics on a separate listener, size and + daily log rotation, and [deployment](deployment.md) guidance for TLS, + identity providers, anchoring, metrics, and backups. +- **Dependencies.** Rust 1.100.0 and sqlx 0.9, which removed the unused + `rsa` advisory exception. + +## Remaining + +1. **Live end-to-end runs.** Run Apple and Kata governed sessions against a + deployed fleet and real model providers. The provider path (broker, + relay, credential injection) is host-side, so this is tracked in SendBox: + [mbianchidev/sendbox#96](https://github.com/mbianchidev/sendbox/issues/96). +2. **`RUSTSEC-2026-0459`.** Drop the exception in `.cargo/audit.toml` once an + sqlx release allows libsqlite3-sys 0.39. It affects only SQLite, which + production does not use. + +## Non-goals + +Kubernetes or fleet scheduling, universal TLS interception, formal policy +verification, and replacing SendBox isolation providers (as in the issue). +The service never stores or forwards provider credentials. diff --git a/vendor/sendbox-fleet/docs/threat-model.md b/vendor/sendbox-fleet/docs/threat-model.md new file mode 100644 index 0000000..de1057b --- /dev/null +++ b/vendor/sendbox-fleet/docs/threat-model.md @@ -0,0 +1,68 @@ +# Threat model + +Scope: the shared governance service in this repository and its interfaces to +SendBox hosts, people, and its database. The SendBox VM boundary, host broker, +and increment-1 local authority are covered in the sendbox repository. + +Status column: **implemented** means implemented and tested here; +**documented** means the mitigation is deployment guidance in +[deployment.md](deployment.md). Remaining work is in [roadmap.md](roadmap.md). + +## Assets + +- Authorization decisions: session admission, grants, per-request decisions. +- Policy state: signed profile revisions, minimum revisions, project roles, + exceptions. +- Audit evidence and its integrity. +- Availability of authorization for running sessions. + +Provider credentials are **not** an asset of this service: they stay in the +SendBox host broker and never reach the fleet. + +## Actors + +| Actor | Trust | +| --- | --- | +| Operator | Trusted to sign and publish profiles, create projects, and recover ownership | +| Project owner, admin, member, viewer | Trusted within their project role | +| SendBox host (user or worker token) | Trusted to report sessions of the principal whose token it holds; untrusted for anything else | +| Service host administrator (`sendbox-fleet admin`) | Issues tokens and creates principals; equivalent to database access | +| Workload (agent inside a VM) | Untrusted; never talks to the fleet directly | +| Network attacker | Untrusted | +| Database administrator | Can bypass application controls; mitigated by evidence anchoring | +| Identity provider in `FLEET_OIDC_CONFIG` | Trusted to name principals under its own prefix, within its audience and required claims; nothing else | + +## Threats and mitigations + +| # | Threat | Mitigation | Status | +| --- | --- | --- | --- | +| T1 | Caller spoofs identity with headers such as `X-Forwarded-User` | Only bearer tokens authenticate; identity headers are ignored; auth runs before routing | Implemented (tested) | +| T2 | Workload-supplied identity in a body is trusted | Binding and grant principals must equal the authenticated caller; projects and sessions are checked against stored state; `local-user:` principals rejected by API and schema | Implemented (tested) | +| T3 | Stolen or replayed bearer token | Service tokens stored only as SHA-256, expiring within 90 days (exchanged ones within `FLEET_TOKEN_MAX_TTL_SECONDS`, 7 days by default), listable and revocable by their owner, void when the principal is disabled; a service token cannot mint another; identity-provider JWTs need this service's audience and expire in minutes; TLS in front of the service ([deployment](deployment.md#tls-and-the-reverse-proxy)) | Implemented (tested) | +| T4 | Compromised worker acts for sessions it does not run | A caller can only admit, use, renew, or end sessions bound to its own principal; grants bound to session, principal, project, binding digest, and profile revision (composite foreign key) | Implemented (tested) | +| T5 | Stale policy or approval authorizes changed work | Sessions, grants, and exceptions reference an exact profile revision and digest; a new revision or raised minimum makes them stale; approvals of stale requests are refused; sessions bound to a revoked or expired exception are denied | Implemented (tested) | +| T6 | Grant wider than the profile allows | Methods and path prefixes must be inside the profile service; lifetime capped by the profile TTL, profile expiry, exception expiry, and 7 days | Implemented (tested) | +| T7 | Audit evidence altered or deleted | Append-only triggers, contiguous hash chain computed by the service and enforced on insert, `GET /v1/audit/verify`; runtime role without `UPDATE`, `DELETE`, `TRUNCATE`, or `ALTER` on audit (`deploy/postgres/roles.sql`); Ed25519-signed chain heads anchored outside the database and checked by `admin audit verify` | Implemented (tested) | +| T8 | Secrets leak into logs or audit | No request bodies, headers, or query strings logged; database URL credentials redacted; tokens stored only as digests; no credential columns; audit keeps a redacted target without query strings (schema check) and omits exception reasons | Implemented (tested) | +| T9 | Authority outage silently allows requests | Hosts deny with `authority_unavailable` on any non-200 answer, timeout, or redirect; a token lookup failure is `503` | Implemented (host client tested in sendbox) | +| T10 | Exception abuse or self-approval | Only denials the signed revision lists as liftable; reason; expiry at most the profile's `exceptions.max_ttl_seconds` and 7 days; approver is a different `owner` or `admin` (also a schema check); lifting never widens the ceiling; every request, decision, refusal, use, and revocation audited | Implemented (tested) | +| T11 | Revocation does not stop in-flight traffic | New requests denied at once; open streams bounded by the profile grace window (at most 60 seconds) on the host; uncertain outcomes audited on the host as `aborted_uncertain` and centrally as `request.outcome` with outcome `unknown` | Implemented (tested) | +| T12 | Resource exhaustion | Body limits (64 KiB, 1 MiB for profile publication), bounded connection pool and acquire timeout, bounded list sizes, non-lossy bounded log queue, per-principal request and per-peer authentication-failure rate limits, at most 20 live exchanged tokens per principal, bounded and throttled JWKS fetches, size-capped log files | Implemented (tested); limits are per instance | +| T13 | Supply-chain compromise | Actions pinned by commit SHA, images pinned by digest, `Cargo.lock` committed, contract pinned by git revision, `cargo audit` in CI with documented exceptions | Implemented | +| T14 | Forged or misdirected identity-provider token | Exact issuer match against an operator-written list (HTTPS, or HTTP to loopback for tests), audience required, keys only from that issuer's JWKS (no `jku`, `x5u`, or embedded keys, no `none` or HMAC algorithms, `crit` refused), per-issuer algorithm allowlist, required claims (for example `repository_owner`), verified email, unique principal prefixes, kind bound to the issuer; auto-provisioned principals get no roles | Implemented (tested) | +| T15 | Rate-limit bypass or lockout behind a proxy | The failure limit keys on the TCP peer and ignores `X-Forwarded-For`; deployment guidance to limit per client at the proxy | Documented | +| T16 | Metrics leak identities | Metrics on a separate listener, labels limited to status classes and decision codes | Implemented (tested) | + +## Known accepted risks + +- `RUSTSEC-2026-0459` (bundled SQLite older than the fix): SQLite is used + only for local development and tests on files the service creates. The fix + is libsqlite3-sys 0.39, which sqlx 0.9.0 does not allow yet. Tracked in + [roadmap.md](roadmap.md). +- Database triggers do not stop a database owner or superuser. Run the + service with `sendbox_fleet_app` and anchor chain heads on storage those + administrators cannot rewrite; then a rewrite is detected, though not + prevented. +- An identity-provider compromise can sign in as any principal that provider + names. Limit each issuer's prefix, audience, and required claims, and keep + `auto_provision` off where it is not needed. diff --git a/vendor/sendbox/LICENSE b/vendor/sendbox/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/vendor/sendbox/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/sendbox/README.md b/vendor/sendbox/README.md new file mode 100644 index 0000000..7bf8e17 --- /dev/null +++ b/vendor/sendbox/README.md @@ -0,0 +1,360 @@ +SendBox logo + +# SendBox + +**Give your coding agent a workspace, not your whole machine.** + +SendBox is an open-source Rust CLI for running coding agents in dedicated Linux +VMs on **macOS and Linux**. Keep your terminal workflow while explicitly choosing +the files, network destinations, credentials, and MCP tools a session can use. + +Use it to try an unfamiliar agent, work on a sensitive repository, or run +headless coding tasks without handing the agent your home directory and host +environment. + +[Quick start](#quick-start) | +[Supported agents](#supported-coding-agents) | +[Configuration and commands](#configuration-and-commands) | +[Integrations](#integrations) | +[Similar tools](#similar-tools) | +[Documentation](docs/README.md) + +## Why SendBox? + +An agent needs to edit code, run commands, and reach its model provider. It does +not need unrestricted access to everything else on your laptop or runner. +SendBox puts that distinction in a reviewable YAML policy, with the same guest +controls across supported CLI agents. + +| Feature | What it gives you | +|---|---| +| **VM-backed isolation** | A dedicated guest kernel through Apple Containerization or Kata Containers, rather than a workload sharing the host kernel. | +| **Explicit workspace scope** | Share one project, or deliberately opt into a multi-repository workspace. Your host home and runtime sockets are not mounted automatically. | +| **Controlled execution and networking** | Deny-first rules for the brokered entry command and allowed domains. Guest containment also covers descendants; direct external agent traffic and UDP/QUIC are blocked. | +| **Scoped credentials** | Vault-backed secrets and separate GitHub, Copilot, MCP, and registry credential paths. Known credentials are masked in terminal output and diagnostics. | +| **MCP tool policies** | Admit exact local servers or remote Streamable HTTP endpoints, filter tool discovery, and allow or deny tools per server. | +| **Package checks before delivery** | An optional npm proxy verifies and inspects packages before releasing their bytes, with private registry credentials kept out of the workload. | +| **Snapshots and audit evidence** | Before/after workspace snapshots, diffs, failure rollback, and tamper-evident lifecycle records help you understand what changed. | +| **GitHub write controls** | Guard selected-repository Git branches, or use optional Safe Outputs to declare bounded writes without giving the agent a GitHub write token. | +| **Interactive or automated sessions** | Run terminal agents with `--interactive`, or use headless execution and JSON events from scripts and job runners. | +| **Reproducible tooling** | Bring a digest-pinned Linux tooling image and generate devcontainer configuration from project analysis. | + +The host verifies and signs the runtime plan before launch; required guest +controls must be ready before the agent starts. An unavailable provider or +unsupported capability is an error, **not a fallback to running on the host**. + +Network grants support explicit subdomain wildcards. On Apple and Kata, an exact +`github.com` grant also includes official GitHub Meta domains and IPv4/IPv6 +CIDRs, including shared-cloud ranges. The host caches them for all sessions and +revalidates at most hourly, keeping within GitHub's anonymous rate limit. See +[network scope, outages, and provenance](docs/configuration.md#network-grants). + +## Supported coding agents + +| Agent | Init profile | Example guest executable | +|---|---|---| +| **Moguri** | `--agent moguri` | `/usr/local/bin/moguri` | +| **Claude Code** | `--agent claude` | `/usr/local/bin/claude` | +| **OpenAI Codex CLI** | `--agent codex` | `/usr/local/bin/codex` | +| **GitHub Copilot CLI** | `--agent copilot` | `/usr/local/bin/copilot` | +| **Gemini CLI** | `--agent gemini` | `/usr/local/bin/gemini` | +| **OpenCode** | `--agent opencode` | `/usr/local/bin/opencode` | +| **Custom CLI agents and programs** | `--agent custom` | Your explicitly allowed absolute path | + +Profiles configure the agent's entry command and initial inference hosts; they +**do not install the agent or log you in**. Your workload image must contain the +Linux agent, its dependencies, certificates, development tools, and `nftables` +for mandatory guest egress enforcement. Use the agent's actual installed +executable path when launching; entrypoint and working-directory paths must not +traverse symlinks. + +Only the Copilot profile enables SendBox's Copilot credential forwarding. +Other agents, including Moguri, manage their own authentication. Add any extra +model provider, authentication, package, or plugin endpoints you need explicitly. +The [agent guide](docs/cli-agents.md) covers credentials, native MCP formats, +multi-repo workspaces, and nested agent sandbox settings. + +## Quick start + +### 1. Install SendBox and a runtime + +**Central Homebrew automation is pending review and activation in the tap.** +The v0.2.3 TLS-fix floor alone is no longer sufficient: v0.2.5 also predates +the dependency fixes identified by the November 11, 2026 audit. New reviewed +host/guest release artifacts are still required. See the +[dependency security status](docs/installation.md#dependency-security-status) and +[stable Homebrew updates](docs/installation.md#stable-homebrew-updates). + +Install the CLI from the existing Homebrew tap: + +```bash +brew install mbianchidev/tap/sendbox +``` + +The formula supports macOS on Apple silicon and Linux on x86_64/aarch64. Follow +the [Homebrew setup](docs/installation.md#homebrew) to stage its signed guest +bundle in a root-owned location before running a VM session. Homebrew does not +provision or start a runtime. + +Alternatively, download a matching +[release](https://github.com/mbianchidev/sendbox/releases), verify its attestation +and checksum, and follow the [installation guide](docs/installation.md). +Host release artifacts include the matching signed guest bundle; source builds +need that bundle separately. + +| Your host | Session runtime and prerequisites | Setup | +|---|---|---| +| macOS 26+ on Apple silicon | Apple Containerization, Xcode 26, and an exact matching official `container` CLI/service pair: **0.10.0** or **1.7.1**, with the service registered and running | [Apple runtime and qualification status](docs/apple-runtime.md) | +| Linux x86_64 or aarch64 with hardware or nested virtualization | Kata Containers **3.28+**, containerd **1.7+**, nerdctl, CNI plugins, and user access to `/dev/kvm` and containerd | [Kata runtime](docs/kata-containers.md) | + +Linux host binaries also need libseccomp, libelf, zlib, and zstd runtime libraries +(on Debian/Ubuntu: `libseccomp2 libelf1 zlib1g libzstd1`). Rust is only required +when building from source. + +Apple 1.7.1 compatibility is currently source-only, not part of released +SendBox v0.2.5. See the [release and physical qualification gates](docs/apple-runtime.md#qualification). + +Run the installed `setup.sh` as your normal user for runtime preflight and +configuration assistance, not `sudo sendbox`. For macOS package/DMG installs, +the helper is `/usr/local/share/sendbox/setup.sh`; for tarballs it is in the +extracted release directory. See [full requirements](docs/installation.md#requirements). +macOS installers are **unsigned and unnotarized**; follow the +[package instructions](docs/installation.md#unsigned-macos-packages). + +Confirm the binary is on your `PATH`: + +```bash +sendbox --version +sendbox help run +``` + +#### Build from source instead + +Install the pinned Rust **1.93.1** toolchain and the +[native build dependencies](docs/installation.md#requirements), then: + +```bash +git clone https://github.com/mbianchidev/sendbox.git +cd sendbox +make install PREFIX="$HOME/.local" +export PATH="$HOME/.local/bin:$PATH" +sendbox --version +``` + +This builds and installs the host CLI, not a VM runtime, an agent image, or the +signed guest bundle. Obtain the matching verified bundle and trust root +separately before `sendbox run`. + +### 2. Configure your project and agent + +From your project directory, select a profile. For example, with Claude Code: + +```bash +sendbox init --project . --agent claude +sendbox secrets add ANTHROPIC_API_KEY +``` + +`init` creates a private `.sendbox.yaml` in the project root and refuses to +overwrite an existing one. `secrets add` prompts for the value without putting +it in shell history. Edit the generated file to reference the stored credential, +preserving its other settings: + +```yaml +secrets: [ANTHROPIC_API_KEY] +``` + +Review the generated command and network policy before running. The Claude +profile adds `claude` and `api.anthropic.com`; it is not a minimal network +allowlist, so remove any default development endpoints you do not need. + +Generated configurations enable GitHub repository forwarding and branch guards. +For a `github.com` checkout, authenticate the host's `gh` CLI, for example with +`gh auth login`. Private repository access additionally requires +`github.allow_private_repository_access: true`. If no GitHub credential is +needed, set `github.forward_auth: false`; for a non-Git project also set +`github.branch_protection.enabled: false`. Non-Copilot profiles already disable +Copilot token forwarding. See the +[credential guide](docs/cli-agents.md#credentials-and-agent-state); host login +files are not copied into the VM. + +Validate and inspect the policy before starting a VM: + +```bash +sendbox policy validate --config .sendbox.yaml +sendbox policy show --config .sendbox.yaml --json +``` + +Validation should exit successfully. It checks configuration and policy, not +runtime readiness, image contents, or whether credentials can be retrieved. + +### 3. Start a terminal session + +Set `WORKLOAD_IMAGE` to your **digest-pinned image containing Claude Code**. +The image below is a placeholder, not a published agent image. +`GUEST_DIR` below matches a macOS package/DMG installation: + +```bash +WORKLOAD_IMAGE='your-registry/agent-tools@sha256:REPLACE_WITH_DIGEST' +GUEST_DIR='/usr/local/share/sendbox/guest/aarch64' + +sendbox run --interactive \ + --config .sendbox.yaml \ + --image "$WORKLOAD_IMAGE" \ + --bundle "$GUEST_DIR/bundle" \ + --trust-root "$GUEST_DIR/release-public.key" \ + -- /usr/local/bin/claude +``` + +For Homebrew installs, use the versioned root-owned `GUEST_DIR` from the +[guest staging guide](docs/installation.md#stage-the-guest-bundle), not the +macOS package path above. + +For tarball installs, use `guest/aarch64/` or `guest/x86_64/` under the root-owned +extracted release directory. The workload image and bundle architectures must +match; **ARM guest directories are named `aarch64`, not `arm64`**. Bundle files, +the trust root, and their ancestors must meet the runtime's ownership and +permission checks. Moving only the public key into a trusted location is not +sufficient. + +`auto` selects Apple on macOS arm64 and Kata on Linux; you can select a provider +explicitly with `--runtime`. Once authenticated guest services are ready, the +agent starts in the shared project at `/workspace`. A successful zero exit +preserves workspace edits; the session's guest home and login state are discarded. + +Drop `--interactive` and supply your agent's headless arguments for automation. +`--json` emits machine-readable events in headless mode and cannot be combined +with `--interactive`; workload output bytes are hex encoded. +See [terminal troubleshooting](docs/interactive-sessions.md) and the +[CLI reference](docs/cli-reference.md) for more options. +For first-request networking failures, use the credential-free +[cold-start DNS diagnostic](docs/dns-cold-start.md), not a warmed retry. + +## Configuration and commands + +The generated `.sendbox.yaml` is the starting point, not a requirement to use +every integration. Review `project_path` and optional `workspace_path`, CPU and +memory resources, `policy.commands`, `policy.network`, `secrets`, and `github` +for each project. Sharing a parent workspace exposes its sibling repositories +too. Package inspection, Safe Outputs, and syscall tracing are opt-in. + +Use the [configuration guide](docs/configuration.md) and +[annotated YAML reference](config/example-sandbox.yaml) for individual settings. +Operators can require signed policy profiles and keep model provider keys on +the host with [governed sessions](docs/architecture/governed-sessions.md). +These commands do not launch a VM or require an agent login: + +```bash +# Inspect the configured boundary declaration, not a live session +sendbox boundary inspect --config .sendbox.yaml --json + +# Analyze a project without writing generated files +sendbox analyze --project . --json + +# Write .devcontainer/devcontainer.json from native project analysis +sendbox devcontainer generate --project . + +# Install completions for your shell (bash, zsh, or fish) +sendbox completions install --shell zsh +``` + +Devcontainer generation merges an existing configuration and rewrites it as +JSON; JSONC comments are not preserved. Review the resulting diff. A generated +devcontainer is development-environment configuration, not a replacement for +`sendbox run` or its security services. Use `sendbox help ` for +options supported by your installed version. + +## Integrations + +| Connect it to | How it fits | +|---|---| +| **Local and remote MCP servers** | Broker local stdio tools and remote Streamable HTTP services with separate tool policies and scoped authentication. | +| **GitHub workflows** | Use repository-scoped credentials and branch guards, or stage Safe Outputs for host-side writes after the VM is gone. | +| **Model providers and private registries** | Allow only the inference endpoints you use; optionally route npm traffic through the package inspection proxy. | +| **VS Code and devcontainer tooling** | Generate a standard devcontainer spec for reproducible development setup. The spec alone does not reproduce SendBox's security controls. | +| **CI and custom orchestrators** | Invoke the CLI on a prepared virtualization-capable runner; use headless commands and JSON events. Runner provisioning and scheduling remain yours. | + +See [integration recipes and boundaries](docs/integrations.md) for configuration +examples and the distinction between built-in support and workflows you compose. + +
    + +## Similar tools + +**Choose SendBox when you want to run CLI agents on infrastructure you control, +with VM isolation and explicit policies across agents.** It is not a hosted +sandbox service or a turnkey fleet scheduler. + +| Tool | Deployment and isolation | Strengths and tradeoffs | +|---|---|---| +| [Agent Substrate](https://github.com/agent-substrate/substrate) | Kubernetes; gVisor or Cloud Hypervisor microVMs | Stateful agent fleets, suspend/resume, and credentials injected outside actors. Requires operating a cluster; gVisor and microVMs are different boundaries. | +| [Chainguard Workspaces](https://edu.chainguard.dev/chainguard/workspaces/overview/) | Chainguard-hosted Linux microVMs | Terminal sessions, external credentials, and full-state resume. Currently beta; default sessions reach the public internet unless opened with an egress allowlist. | +| [Docker Sandboxes](https://docs.docker.com/ai/sandboxes/) | Local microVMs or a separate managed cloud offering | Local sandboxes include their own Docker Engine and optional private-clone workflow. Local and cloud policies and lifecycles differ. | +| [E2B](https://docs.e2b.dev/) | API/SDK-driven cloud Linux VMs; self-hosting also documented | Code execution, templates, and pause/resume for applications. A platform to integrate, rather than a local CLI session policy wrapper. | +| [Daytona](https://www.daytona.io/docs/en/sandboxes/) | API-first remote platform with container and VM sandbox classes | Programmatic environments, snapshots, and multiple OS options. Select the sandbox class explicitly; do not assume every sandbox is a VM. | +| [microsandbox](https://github.com/superradcompany/microsandbox) | Local microVMs on macOS, Linux, and Windows | Embeddable SDKs, OCI images, and fork/snapshot workflows. Beta, general-purpose execution infrastructure rather than SendBox's integrated session controls. | +| [Dev containers](https://containers.dev/overview) | Environment specification; boundary depends on its runtime and mounts | Reproducible tooling and editor setup. The specification itself is not an agent security boundary. | +| **SendBox** | Self-managed macOS/Apple and Linux/Kata VMs | One policy across CLI agents, with the optional controls below. You prepare the runtime, tooling image, and verified guest bundle; no Windows runtime or fleet scheduler. | + +Two distinctive SendBox built-ins, rather than claims of exclusive invention: + +| Workflow | SendBox implementation | Comparison | +|---|---|---| +| **Gate npm bytes before delivery** | An opt-in [registry proxy](docs/package-supply-chain.md) quarantines tarballs, verifies integrity and configured signature/provenance requirements, and statically inspects content before allowing delivery. | An equivalent built-in pipeline was not established in the reviewed sources. Chainguard advertises lockfile verification, which is not the same guarantee. | +| **Bound GitHub writes after VM teardown** | A native, partial-conformance [Safe Outputs gateway](docs/architecture/safe-outputs.md) validates bounded requests and stages them or applies them on the host without giving the agent a write token. | Docker Sandboxes can also run under GitHub Agentic Workflows, which supplies Safe Outputs through the external workflow. SendBox integrates this subset into local sessions. | + +Both SendBox controls are opt-in and supported on Apple/Kata, not Hyperlight. +VMs, credential mediation, and snapshots are **not unique to SendBox**. +This comparison uses official sources reviewed on October 29, 2026; missing +documentation means unknown, not unsupported. See the +[comparison guide and sources](docs/alternatives.md) for scope and limitations. + +## Limitations and security expectations + +VM isolation does not make agent-generated changes trustworthy. The shared +workspace is writable, and credentials deliberately delivered to an agent are +available to that agent. Review changes before executing them on your host. + +Workspace mounts are live, not an isolated copy waiting to be merged. +Nonzero exits, runtime failures, and normal session cancellation trigger +snapshot rollback of the shared workspace. Avoid concurrent host edits during +a session: they can be included in a rollback. A failed run is not a way to +retain partial agent changes. + +Command policy covers the brokered top-level argv, not recursive semantic +inspection of every descendant command. Credential masking is not comprehensive +data-loss prevention, and local Git guards do not replace server-side branch +protection. Optional syscall tracing observes activity; it does not enforce policy. + +Agents must honor the configured HTTP/SOCKS proxies to reach allowed external +services. Direct connections and UDP/QUIC remain blocked; a client that ignores +the proxies will fail even if its destination is allowed. See +[agent networking](docs/cli-agents.md#agent-compatible-network-proxy). + +Apple and Kata support the full persistent guest-service path. +[Hyperlight](docs/hyperlight.md) is an explicit Linux/KVM **one-shot** provider, +not an interactive agent runtime; it rejects MCP, credential delivery, and +restrictive-egress composition rather than silently downgrading them. + +There is no Windows or Intel macOS runtime, Kubernetes backend, or graphical +dashboard. CI sessions require a prepared runner with the selected runtime and +virtualization access; ordinary container-only runners are not enough. + +Read the [security model](docs/security-model.md) for guarantees and assumptions, +and the [documentation index](docs/README.md) for configuration, architecture, +and operational guides. + +## Contributing + +Contributions are welcome. See the [contribution guide](docs/contributing.md) +for source setup, checks, and release procedures. The [roadmap](ROADMAP.md) +includes future proposals and historical designs; use the CLI and runtime +guides above for current behavior. + +## Security + +Report vulnerabilities privately as described in the +[security policy](SECURITY.md). Only the latest release receives security fixes. + +## License + +[Apache License 2.0](LICENSE). diff --git a/vendor/sendbox/ROADMAP.md b/vendor/sendbox/ROADMAP.md new file mode 100644 index 0000000..cc2234e --- /dev/null +++ b/vendor/sendbox/ROADMAP.md @@ -0,0 +1,317 @@ +# SendBox Roadmap + +> Living document tracking planned features, platform expansion, and ecosystem integrations. + +--- + +## Phase 1 — Foundation and Direct VM Runtimes ✅ (Current) + +SendBox supports direct hardware-isolated runtimes on macOS and Linux: Apple's [Containerization](https://github.com/apple/containerization) framework on Apple silicon, and [Kata Containers](https://katacontainers.io/) through nerdctl/containerd on Linux. + +| Feature | Status | +|---------|--------| +| Lightweight Linux VMs via Virtualization.framework | ✅ Done | +| Kata Containers runtime via nerdctl/containerd | ✅ Done | +| RuntimeProvider abstraction and `--runtime` selection | ✅ Done | +| Command allowlist / denylist engine | ✅ Done | +| Domain-level network firewall (iptables) | ✅ Done | +| macOS Keychain and Linux file-backed secrets management | ✅ Done | +| DevContainer generation via Copilot SDK | ✅ Done | +| YAML-based configuration with presets | ✅ Done | +| CLI (`run`, `init`, `analyze`, `secrets`, `policy`) | ✅ Done | +| Interactive setup script | ✅ Done | +| Fail-closed seccomp syscall and stdio MCP tool boundaries | ✅ Done | + +--- + +## Phase 2 — Kubernetes Orchestration (KinD) + +### Goal + +Add **Kubernetes in Docker (KinD)** as an orchestrated runtime for Windows, Intel macOS, remote clusters, and multi-sandbox deployments. Linux already has direct Kata Containers support. + +### Architecture + +``` +┌─────────────────────────────────────────────────────┐ +│ sendbox CLI │ +├──────────────────┬──────────────────────────────────┤ +│ RuntimeProvider │ (protocol / trait / interface) │ +├──────────────────┼──────────────────────────────────┤ +│ AppleVMRuntime │ KataRuntime │ Kubernetes │ +│ (macOS arm64) │ (Linux) │ Runtime │ +│ Virtualization │ nerdctl + │ KinD + │ +│ .framework │ containerd │ containerd │ +└──────────────────┴──────────────────────────────────┘ +``` + +### Approach + +1. **Extend the existing `RuntimeProvider` abstraction** with a Kubernetes implementation while keeping sandbox logic runtime-agnostic. + +2. **KinD backend** (`KubernetesRuntime`): + - Requires Docker and [KinD](https://kind.sigs.k8s.io/) installed on the host. + - Creates a dedicated KinD cluster per sandbox (or reuses one with namespace isolation). + - Maps SendBox concepts to Kubernetes primitives: + + | SendBox Concept | Kubernetes Primitive | + |-----------------|---------------------| + | Container / VM | Pod (single-container) | + | Command policy | Admission webhook / OPA Gatekeeper policy | + | Network firewall | NetworkPolicy (Calico/Cilium) | + | Secrets | Kubernetes Secrets (encrypted at rest) | + | Filesystem isolation | EmptyDir + InitContainer for workspace copy | + | DevContainer | Pod spec with devcontainer image + volume mounts | + + - NetworkPolicy replaces iptables — egress rules map allowed/blocked domains to CIDR blocks via DNS resolution at policy-apply time, or use Cilium's FQDN-aware policies. + - Secrets injected as Kubernetes Secrets mounted at `/run/secrets/` or as environment variables. + - Command filtering enforced via a sidecar admission proxy or an init script that wraps the shell. + +3. **Runtime selection** — auto-detected or user-specified: + ```yaml + # .sendbox.yaml + runtime: + provider: auto # auto | apple | kata | kubernetes + kubernetes: + provider: kind # kind | minikube | k3d | remote + cluster_name: sendbox-cluster + namespace: sandbox-default + network_plugin: cilium # calico | cilium (for FQDN policies) + ``` + +4. **CLI changes**: + ```bash + sendbox run --runtime kubernetes --project ./my-app + sendbox cluster create # Create/manage KinD cluster + sendbox cluster delete + sendbox cluster status + ``` + +### Tasks + +- [x] Define `RuntimeProvider` protocol with create/start/stop/exec/cleanup +- [ ] Implement `KubernetesRuntime` using client-go or kubectl subprocess +- [ ] Generate Kubernetes manifests (Pod, NetworkPolicy, Secret) from SendBox config +- [ ] Implement FQDN-aware NetworkPolicy (Cilium CiliumNetworkPolicy or DNS-to-CIDR resolver) +- [ ] Map command policy to OPA/Gatekeeper constraints or shell wrapper +- [ ] KinD cluster lifecycle management (create, reuse, destroy) +- [x] Add `--runtime` flag to CLI +- [ ] Cross-platform CI (macOS and Linux complete; Windows pending) +- [x] Runtime unit tests on Linux (live Kata tests require nested virtualization) +- [ ] Helm chart for remote Kubernetes clusters (EKS, GKE, AKS) + +### Platform Support Matrix + +| Platform | Runtime | Status | +|----------|---------|--------| +| macOS arm64 | Apple Virtualization | ✅ Supported | +| Linux x86_64 | Kata Containers | ✅ Supported | +| Linux arm64 | Kata Containers | ✅ Supported | +| macOS arm64 | KinD | 🔲 Planned | +| macOS x86_64 | KinD | 🔲 Planned | +| Linux x86_64 | KinD | 🔲 Planned | +| Linux arm64 | KinD | 🔲 Planned | +| Windows (WSL2) | KinD | 🔲 Planned | +| Remote K8s | kubectl | 🔲 Planned | + +--- + +## Phase 3 — Multi-Agent Tool Compatibility + +### Goal + +Support **any AI coding agent**, not just GitHub Copilot CLI. The sandbox should be agent-agnostic — the security guarantees (isolation, command filtering, network firewall, secrets) apply regardless of which tool runs inside. + +### Supported Agents + +| Agent | Integration Approach | Status | +|-------|---------------------|--------| +| **GitHub Copilot CLI** | Native via `@github/copilot-sdk` | ✅ Supported | +| **Claude Code** (Anthropic) | CLI binary + API key injection | 🔲 Planned | +| **Codex CLI** (OpenAI) | CLI binary + API key injection | 🔲 Planned | +| **Gemini CLI** (Google) | CLI binary + API key injection | 🔲 Planned | +| **Aider** | pip install + config | 🔲 Planned | +| **Cline / Roo Code** | VS Code extension (devcontainer) | 🔲 Planned | +| **Cursor Agent** | Not CLI-based (limited support) | 🔲 Investigating | +| **Amazon Q Developer CLI** | CLI binary + AWS credentials | 🔲 Planned | +| **Custom agents** | User-defined command + env | 🔲 Planned | + +### Architecture + +``` +┌─────────────────────────────────────────────────────┐ +│ sendbox CLI │ +├─────────────────────────────────────────────────────┤ +│ AgentProvider │ +│ (protocol / interface) │ +├────────┬─────────┬─────────┬──────────┬─────────────┤ +│Copilot │ Claude │ Codex │ Gemini │ Custom │ +│CLI │ Code │ CLI │ CLI │ (user cmd) │ +├────────┴─────────┴─────────┴──────────┴─────────────┤ +│ Agent-Agnostic Sandbox │ +│ ┌──────────┬───────────┬──────────┬──────────────┐ │ +│ │ Command │ Network │ Secrets │ Filesystem │ │ +│ │ Policy │ Firewall │ Vault │ Isolation │ │ +│ └──────────┴───────────┴──────────┴──────────────┘ │ +└─────────────────────────────────────────────────────┘ +``` + +### AgentProvider Protocol + +Each agent adapter implements: + +``` +AgentProvider: + name() → String # "claude-code", "codex", etc. + installCommand() → [String] # How to install inside container + runCommand() → [String] # How to launch the agent + requiredSecrets() → [String] # e.g., ["ANTHROPIC_API_KEY"] + requiredDomains() → [String] # e.g., ["api.anthropic.com"] + healthCheck() → Bool # Verify agent is working + configFiles() → [FilePath] # Agent-specific config to mount +``` + +### Agent-Specific Details + +#### Claude Code (Anthropic) +- **Install**: `npm install -g @anthropic-ai/claude-code` +- **Run**: `claude` (interactive) or `claude -p "prompt"` (headless) +- **Secrets**: `ANTHROPIC_API_KEY` +- **Domains**: `api.anthropic.com`, `*.anthropic.com` +- **Notes**: Supports `--allowedTools` flag for built-in tool restriction. SendBox command policy provides an additional layer. + +#### Codex CLI (OpenAI) +- **Install**: `npm install -g @openai/codex` +- **Run**: `codex` (interactive) or `codex -q "prompt"` +- **Secrets**: `OPENAI_API_KEY` +- **Domains**: `api.openai.com`, `*.openai.com` +- **Notes**: Has its own sandbox mode (`--full-auto`). SendBox wraps this for network/filesystem guarantees the built-in sandbox doesn't provide. + +#### Gemini CLI (Google) +- **Install**: `npm install -g @anthropic-ai/claude-code` → TBD (check actual package name on release) +- **Run**: `gemini` or via API +- **Secrets**: `GEMINI_API_KEY` or Google Cloud credentials +- **Domains**: `generativelanguage.googleapis.com`, `*.googleapis.com` +- **Notes**: May require Google Cloud auth flow. + +#### Aider +- **Install**: `pip install aider-chat` +- **Run**: `aider --model ` +- **Secrets**: Model-specific API key (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, etc.) +- **Domains**: Depends on model provider +- **Notes**: Highly configurable. SendBox mounts `.aider.conf.yml` if present. + +#### Custom Agent +- **Config**: User provides install/run commands directly + ```yaml + agent: + type: custom + install: "pip install my-agent" + command: ["my-agent", "--workspace", "/workspace"] + secrets: + - MY_API_KEY + extra_domains: + - "api.my-service.com" + ``` + +### Configuration Changes + +```yaml +# .sendbox.yaml — Phase 3 additions +agent: + type: claude-code # copilot | claude-code | codex | gemini | aider | custom + + # Auto-resolved per agent type, but overridable: + # install_command: "npm install -g @anthropic-ai/claude-code" + # run_command: ["claude", "-p", "Fix all failing tests"] + + # Agent-specific options + options: + model: claude-sonnet-4-20250514 # For agents that support model selection + headless: true # Non-interactive mode + prompt: "Fix the CI" # Initial prompt for headless mode + + # Custom agent (when type: custom) + # custom: + # install: "pip install my-agent" + # command: ["my-agent", "--auto"] + # secrets: [MY_API_KEY] + # domains: ["api.example.com"] +``` + +### Tasks + +- [ ] Define `AgentProvider` protocol +- [ ] Implement `CopilotAgent` (refactor existing Copilot SDK integration) +- [ ] Implement `ClaudeCodeAgent` +- [ ] Implement `CodexAgent` +- [ ] Implement `GeminiAgent` +- [ ] Implement `AiderAgent` +- [ ] Implement `CustomAgent` (user-defined) +- [ ] Auto-detect agent type from project files (`.claude`, `.codex`, etc.) +- [ ] Agent-specific domain allowlists (merged with user policy) +- [ ] Agent-specific secret requirements (validated before launch) +- [ ] `sendbox run --agent claude-code --project ./my-app` +- [ ] Documentation and examples for each agent + +--- + +## Phase 4 — Advanced Features + +Features planned after core platform and agent support is solid. + +### Observability & Audit +- [ ] Full audit log of all commands executed, network connections made, files modified +- [x] eBPF inspection of MCP (Model Context Protocol) calls the agent performs +- [ ] Real-time dashboard (TUI) showing agent activity +- [ ] Export audit logs as JSON/CSV for compliance +- [ ] Cost tracking (API calls made by agent, token usage if available) + +### Multi-Agent Orchestration +- [ ] Run multiple agents in isolated sandboxes that share a workspace +- [ ] Agent-to-agent communication through controlled channels +- [ ] Supervisor agent that reviews changes from worker agents + +### Snapshot & Rollback +- [ ] Filesystem snapshots before/after agent runs +- [ ] Diff view of all changes made by the agent +- [ ] One-click rollback to pre-agent state +- [ ] Git-based change tracking within the sandbox + +### CI/CD Integration +- [ ] GitHub Actions action: `sendbox-action` +- [ ] GitLab CI template +- [ ] Pre-commit hook for validating sandbox configs +- [ ] PR review mode: agent runs in sandbox, posts diff as PR comment + +### Policy as Code +- [ ] OPA/Rego policy language support for complex rules +- [x] Operator-signed governance profiles that projects can only narrow ([governed sessions](docs/architecture/governed-sessions.md), single host) +- [x] Host-side brokered model provider credentials with leased, revocable grants (Anthropic, OpenAI) +- [x] Shared multi-user governance service with project-scoped roles, approved expiring exceptions, and central audit ([`sendbox-fleet`](https://github.com/mbianchidev/sendbox-fleet), [shared governance service](docs/architecture/governed-sessions.md#shared-governance-service)) +- [ ] Policy inheritance (org → team → project) +- [ ] Policy testing framework +- [ ] Community policy library + +--- + +## Timeline + +| Phase | Target | Key Milestone | +|-------|--------|---------------| +| Phase 1 | ✅ Complete | Core sandbox on macOS with Copilot SDK | +| Phase 2 | Next | KinD runtime → Linux/Windows support | +| Phase 3 | After Phase 2 | Claude Code, Codex, Gemini CLI support | +| Phase 4 | Ongoing | Audit logs, multi-agent, CI/CD | + +--- + +## Contributing + +We welcome contributions, especially for: +- New `AgentProvider` implementations +- New `RuntimeProvider` backends (Podman, Firecracker, gVisor) +- Platform testing on Linux and Windows +- Policy templates for common use cases + +See [CONTRIBUTING.md](https://github.com/apple/containerization/blob/main/CONTRIBUTING.md) for guidelines. diff --git a/vendor/sendbox/SECURITY.md b/vendor/sendbox/SECURITY.md new file mode 100644 index 0000000..c4cc678 --- /dev/null +++ b/vendor/sendbox/SECURITY.md @@ -0,0 +1,33 @@ +# Security policy + +## Reporting a vulnerability + +Report suspected vulnerabilities privately through +[GitHub private vulnerability reporting](https://github.com/mbianchidev/sendbox/security/advisories/new) +(the repository's **Security** tab, then **Report a vulnerability**). Do not +open public issues, pull requests, or discussions for vulnerabilities. + +Include what you can of the following: + +- the SendBox version (`sendbox --version`), runtime (Apple, Kata, or + Hyperlight), and host platform; +- the configuration and command needed to reproduce, with secrets removed; +- the boundary you were able to cross and its impact, such as a guest reaching + the host, egress outside the allowlist, or a credential reaching the guest. + +The report stays private while it is investigated, fixed, and disclosed +through a GitHub security advisory. + +## Supported versions + +Only the [latest release](https://github.com/mbianchidev/sendbox/releases/latest) +receives security fixes. Upgrade to it before reporting, and confirm the issue +still reproduces there. + +## Scope + +The [security model](docs/security-model.md) describes the boundaries SendBox +enforces and the assumptions it makes. The README's +[limitations and security expectations](README.md#limitations-and-security-expectations) +lists behavior that is known and intended, such as the writable shared +workspace and credentials deliberately delivered to an agent. diff --git a/vendor/sendbox/SOURCE.json b/vendor/sendbox/SOURCE.json new file mode 100644 index 0000000..610b764 --- /dev/null +++ b/vendor/sendbox/SOURCE.json @@ -0,0 +1,51 @@ +{ + "repository": "sendbox-dev/sendbox", + "ref": "main", + "commit": "fe05a0d84ca36fbffa3892d7705ee4ba8ed08eb9", + "committed": "2026-11-22T01:51:33Z", + "files": { + "README.md": "e9c8aa9a5533cacad260d2dc0c928a2c876c2696b7cda4ef24d145b9b5bab180", + "docs/installation.md": "4aa9667cb4fb5f0e267ea05585b2d26e4b877074631a32ffb439dd90a6674272", + "docs/configuration.md": "5af57844d7be905cf940787050d716746a68349289502c811ae4d5225fd61614", + "docs/cli-reference.md": "35fb9ba36e4786071885ca0a32665c4d793ddd628030102132d9a4813dc3bf21", + "docs/interactive-sessions.md": "c2d061d0d6f90a2c33bdaf2c5a1389dc0fc7e1f069e1f518bd3ff33c11e3858b", + "docs/cli-agents.md": "f02ece93c572d93ddcf79c36f3e699246466d0f8e09630e3597db684acc3a264", + "docs/integrations.md": "bc4809ca398ff2ce65a4e39ce4d00b532498740368a9e88613c95c7bc59a43e4", + "docs/alternatives.md": "6a3d8612d7807ebbf05e0f584e0ebe788438ae59ab6039aa67666a8a61834a5e", + "docs/apple-runtime.md": "5f47cd68abd0b0f4c6060275b54d429e6b6023ebff5cfd0fcb66e07a8ea5f8f4", + "docs/kata-containers.md": "0a2ed758aaeee266eeff6269776644978cbc666249c229ec84954bf2cfab315e", + "docs/hyperlight.md": "ac43ea6f3d6b1198cbe790285d7502df8b7acefd9adcc93ca9e12536adcddbfe", + "docs/dns-cold-start.md": "444d249889f07bccf20dd03cab01940a75f1f91cb0e100e0cd18e741b8463b02", + "docs/package-supply-chain.md": "6b921548dffd25c0110377e0b232b9a3eafb20526f0a1f953e9761e041599768", + "docs/mcp-inspection.md": "6bdeda801ca0d32d7234425888aa6bf8bb366fa6674168b85d9271ae6e51f323", + "docs/security-model.md": "8212c39d81805f40005721f6dcebd9dd001658c32f596bb02f5d1a5789cce2be", + "SECURITY.md": "d0cef7b6b78b7abcfaf082640b179ce2cebe81bb3a690507cd414502b752afbb", + "docs/security/egress-enforcement-trust-boundary.md": "bf7062b26dba51d6a4f6d229a19696d121424f5180010b5c8ee975e9ef05aa44", + "docs/migration/secrets.md": "9490e21e570a65a3a743e45badf6f1d1e55aac997215be0a3c452ddc2707cf03", + "docs/migration/security-records.md": "e8d0d80c560d9fdbaa88ccfd3b81526cb6bbc1701b941ceef4ac73e2887543fd", + "docs/contributing.md": "ebde5ea0ca9af8ed94662299707a02b3bf139016999adb942156bccfefa4c5d5", + "docs/qualification.md": "08bd2e61e30d947578576e91b2205079bfab00ba853268d0cd6d540b941a8751", + "ROADMAP.md": "44aaef5fe4beefe8800c7d2788b897242a0ed130a1c347fdfb251cefea1d0f07", + "docs/architecture/runtime-core.md": "74a638f4569a85838226137fe0bdab383070f63c1e5f71cb59cba1ffde110fe8", + "docs/architecture/execution-broker.md": "60de7de30604f6133b3b0fe914b8cc189f4f433f328e8a2f26001b97d2b5af84", + "docs/architecture/guest-supervisor.md": "2ad01116070336b51cc7d7d5e71ff49e1b72d82e0ce46c077a6d6357ec343e69", + "docs/architecture/guest-artifact-bundles.md": "af14702a85f904bc51726d8d433749ef22839b28cd356ad222897e6cf5557e98", + "docs/architecture/interactive-terminal.md": "cd039e98b5664872aff3244a7f685a4e555f170e440c4218feafc961944ab828", + "docs/architecture/kata-runtime.md": "0ca9054b62ac0f6f8206c08199b1b499ea59e9aacdc4d7d94c16b2f908835a44", + "docs/architecture/authenticated-guest-protocol.md": "f8fb9961ad81c1e3cdd5976ecd2c8323becb4592d403ac7af06a894c3c6af4a6", + "docs/architecture/session-security-lifecycle.md": "86ccff479925a222900f7263674ca3bdf51a9ebf44af5047218c95b8a9f86d7a", + "docs/architecture/egress-enforcement.md": "3d73cd588310f54c8525ea6d14549ca811b2781c25c4f250c882ae189626a9f5", + "docs/architecture/mcp-broker.md": "e60c0a415dcb8d3df9574b600a1244733e5ce43af578bd089e3dce6edfd7d6d9", + "docs/architecture/package-registry-proxy.md": "a6abb43c440308de07a4ec559ef6ec029178265348480d65c26155e42c2c90be", + "docs/architecture/secrets-and-credential-broker.md": "27206faaa3a21fce0cc3485c44ec410cc17642d6cb4e9e1fb12a78aece977b3c", + "docs/architecture/governed-sessions.md": "7953bc4fa5f5687a6e109496d0e10edf46b51e3d7fa440a0ba86f764f30fb4d0", + "docs/architecture/git-branch-guard.md": "b291d45a0fb2abe0fd0252f12d0df6ef95bfb7927da675ca976059a632add766", + "docs/architecture/safe-outputs.md": "49cc33150e5049b333c9e3ca1e53307ee7286d9be0037ed88514ada735cb7411", + "docs/architecture/security-records.md": "6a39dd8124bee6f07e652981e98a1f1d7956745ec8a1bd7a50d7c98002829fad", + "docs/architecture/agent-orchestration.md": "db199c18d21b13c7333b1879b1f43a303f7910081dd543ade31725fb77f59960", + "docs/architecture/native-project-analysis.md": "4c44afe5bb249070af471d4eaff7a9c86c06a464789cc9c72a866a3802df8c8e", + "docs/architecture/rust-cli-parity.md": "a99b42b21404fd2dc4a0c171b0096fabbcf7ae745809538dbaf49e5f391db1c5", + "docs/assets/logo.svg": "2c28d4dc333797682f8b526f494e7ac29ac286f6b876d4b150b1ba30ccee0d41", + "LICENSE": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4" + } +} diff --git a/vendor/sendbox/docs/alternatives.md b/vendor/sendbox/docs/alternatives.md new file mode 100644 index 0000000..0152dfb --- /dev/null +++ b/vendor/sendbox/docs/alternatives.md @@ -0,0 +1,126 @@ +# Choosing an agent sandbox + +The right sandbox depends on what you need to isolate and who should operate +it. A reproducible development environment, an interactive agent session, and +an API that executes code for many users solve related but different problems. + +SendBox focuses on **CLI agent sessions on a Mac or Linux host you control**, +with a VM boundary and a reviewable policy for workspace access, entry commands, +network destinations, credentials, and MCP tools. + +## Options and tradeoffs + +| Option | Deployment and isolation model | Good fit | What to evaluate | +|---|---|---|---| +| **[Agent Substrate](https://github.com/agent-substrate/substrate)** | Kubernetes runtime with gVisor or Cloud Hypervisor microVM backends. Actors are stateful workloads multiplexed across worker pools. | Stateful agent fleets, full-state suspend/resume, per-actor identity, and credential injection outside the actor. | You operate Kubernetes and its control plane. gVisor's userspace kernel and a microVM's dedicated guest kernel are different isolation mechanisms. The project is pre-1.0. | +| **[Chainguard Workspaces](https://edu.chainguard.dev/chainguard/workspaces/overview/)** | Remote Linux microVM sessions in Chainguard's cloud, accessed with `chainctl develop`. A local directory is synced, not mounted from the host. | Keeping a terminal workflow while offloading compute, keeping long-lived credentials outside the VM, and parking/resuming the full session. | Currently beta/Technology Preview. Default sessions have public internet access; an egress allowlist requires opening on an appropriately configured check. Service limits and data-use terms apply. | +| **[Docker Sandboxes](https://docs.docker.com/ai/sandboxes/)** | Local sandboxes use a microVM with a dedicated Linux kernel. Docker also offers cloud sandboxes with separate behavior and lifecycle controls. | An agent-focused sandbox product, including workflows that need a Docker Engine inside the local sandbox. | Compare local versus cloud support, workspace modes, credential handling, network defaults, and where MCP servers execute. | +| **[E2B](https://docs.e2b.dev/)** | API/SDK-driven cloud Linux VMs, with a separately documented self-hosting path. | Building applications that provision environments, execute agent-generated code, and pause/resume full sandbox state programmatically. | Hosted versus self-hosted operations, environment lifecycle and limits, data placement, network controls, and how to connect your agent tooling. | +| **[Daytona](https://www.daytona.io/docs/en/sandboxes/)** | An API-first remote sandbox platform. Current documentation distinguishes default Linux container sandboxes from Linux/Windows VM sandboxes and other classes. | Programmatically managing environments with SDKs, process/filesystem APIs, snapshots, and remote-access tooling. | Select the actual sandbox class and deployment before comparing isolation or lifecycle guarantees. VM-specific capabilities are not universal container-sandbox capabilities. | +| **[microsandbox](https://github.com/superradcompany/microsandbox)** | Local hardware-isolated microVMs on Apple-silicon macOS, KVM-enabled Linux, and WHP-enabled Windows. Supports OCI images and CLI/SDK use. | Embedding sandbox execution into an application, local shell workflows, and forking or snapshotting running sandboxes. | Beta software with changing APIs. Compare the controls provided by the runtime with the agent policies and integrations your application would need to supply. | +| **[Dev containers](https://containers.dev/overview)** | A development-environment specification used by local and remote tools. Isolation depends on the backing container/VM runtime and configured mounts. | Sharing reproducible dependencies, editor settings, and development setup across a team. | The specification alone does not provide a per-agent VM or enforce SendBox-style command, network, credential, or MCP policy. | +| **SendBox** | Self-managed macOS/Linux hosts. Apple and Kata sessions have a dedicated Linux guest kernel; Hyperlight is a separate one-shot path. | Switching between CLI agents while retaining explicit session controls, scoped integrations, snapshots, and audit records. | You supply virtualization-capable hosts, a tooling image, verified guest artifacts, and operational setup. No hosted service, Windows runtime, or fleet scheduler. | + +These are workflow comparisons, **not a security ranking or a feature-parity +claim**. Local and hosted variants can have different boundaries. Product +capabilities change; verify the current documentation for your chosen +deployment rather than relying on a product name alone. + +## Distinctive SendBox built-ins + +These two workflows distinguish SendBox's integrated CLI stack in the reviewed +sources. This is a comparison of documented built-ins, not proof that another +project cannot provide equivalent behavior. An undocumented capability is +**unknown**, not unsupported. + +| Workflow | What SendBox implements | Related capabilities and limits | +|---|---|---| +| **Pre-delivery npm package gate** | A trusted registry proxy quarantines tarballs, verifies package identity and integrity, enforces configured signature/provenance requirements, and inspects archive content without executing package code. Only an `allow` verdict releases bytes to the workload. Exceptions bind to an exact artifact digest. | The reviewed alternative sources do not establish an equivalent built-in tarball pipeline. Chainguard's product page advertises lockfile verification; that should not be equated with SendBox's static archive inspection. Generic registry access controls or installing a scanner inside a sandbox are also different boundaries. | +| **Post-session GitHub Safe Outputs** | A native partial-conformance gateway records bounded GitHub requests with session/policy provenance. After guest teardown, the host verifies the batch and either persists a preview or applies permitted writes with a host-only token. | This is an integration of the GitHub Agentic Workflows design, not an invention of SendBox. Docker Sandboxes is also a supported runtime for GitHub Agentic Workflows, where a separate Safe Outputs job performs writes. That is a documented alternative when CI orchestration, rather than a local CLI integration, fits your workflow. | + +Both controls are disabled by default and supported on Apple/Kata persistent +sessions only. Package inspection is npm-only; other package adapters are not +implemented. Signature/provenance checks default to verifying evidence when +present; use `required` to reject its absence. Static inspection is not proof +that a package is safe. See the [package guide](package-supply-chain.md). + +Safe Outputs defaults to staged mode when enabled and supports only a subset +of GitHub.com operations. Apply mode prevalidates the batch but performs remote +writes sequentially, so a later API failure can leave earlier writes applied. +See the [gateway architecture and limitations](architecture/safe-outputs.md). + +VM isolation, network policies, external credential injection, MCP support, +snapshots, and audit records are not claimed as SendBox-only features. Agent +Substrate, Chainguard, Docker, and other tools provide overlapping controls. +Some alternatives also offer capabilities SendBox does not: cluster scheduling, +managed compute, durable full-VM resume, Windows environments, or an embedded +sandbox SDK. + +## When SendBox is a good fit + +Choose SendBox when you want to keep using terminal agents on infrastructure +you manage, avoid granting them broad access to your host environment, and +review their permissions in one configuration. + +It is especially relevant when you need the combination of a VM boundary, +explicit model-provider egress, per-server MCP tool rules, registry inspection, +and GitHub workflows without tying the session to one coding agent. + +Choose a different approach when your primary need is a managed execution API, +large-scale environment scheduling, or simply a shared development setup. A +cloud sandbox platform can own more infrastructure for you; a devcontainer may +be sufficient when reproducibility, rather than containing untrusted code, is +the main goal. + +## Questions to ask before choosing + +1. **What is outside the boundary?** Does the workload share a kernel with the + host or other workloads? Which host files, runtime sockets, and MCP servers + remain reachable? +2. **What can leave the environment?** Are outbound destinations restricted, + and what happens when an agent or plugin ignores proxy settings? +3. **Where do credentials live?** Can the agent read them, or does a trusted + service inject them only for approved upstream requests? +4. **How do changes reach your repository?** Is the workspace shared read/write, + copied, or synchronized? What must you review before running changed files? +5. **What does failure look like?** Do missing controls stop execution? What + evidence, cleanup, and rollback are available? +6. **Who operates it?** Who patches the runtime, verifies artifacts, provisions + compute, and handles concurrency and tenant separation? + +For SendBox, the shared workspace is writable, workload secrets are accessible +to the workload, and command policy does not recursively authorize descendant +argv. See [security expectations](../README.md#limitations-and-security-expectations) and the +[security model](security-model.md) before treating any control as a guarantee. + +## Sources + +The comparison was reviewed against these official sources on October 29, 2026. +It is a documentation review, not a head-to-head benchmark or an exhaustive +audit of every deployment and integration: + +- [Agent Substrate README at the reviewed revision](https://github.com/agent-substrate/substrate/blob/eaf0e85c7622d021d833c13e8f8911e2854f9794/README.md), + including its backends, credential model, actor snapshots, and pre-1.0 status. +- [Chainguard Workspaces overview](https://edu.chainguard.dev/chainguard/workspaces/overview/), + [session environment and network defaults](https://edu.chainguard.dev/chainguard/workspaces/session-environment/), + and [Checks/Workspaces security model](https://edu.chainguard.dev/get-started/checks-and-workspaces/how-it-works/). + Prefer these operational docs over assuming that every feature advertised on + the [product page](https://www.chainguard.dev/products/workspaces) applies to + every session configuration. +- [Docker Sandboxes overview](https://docs.docker.com/ai/sandboxes/) and + [local isolation layers](https://docs.docker.com/ai/sandboxes/security/isolation/), + including direct-mount and clone workspaces. Docker's + [GitHub Actions integration walkthrough](https://www.docker.com/blog/running-ai-agents-in-github-actions-with-docker-sandboxes/) + demonstrates Safe Outputs supplied by GitHub Agentic Workflows. +- [E2B overview](https://docs.e2b.dev/), + [sandbox lifecycle](https://docs.e2b.dev/sandbox), and + [project self-hosting section](https://github.com/e2b-dev/E2B#self-hosting). +- [Daytona sandbox classes and lifecycle](https://www.daytona.io/docs/en/sandboxes/). +- [microsandbox README at the reviewed revision](https://github.com/superradcompany/microsandbox/blob/8ff916f38a628390fff21e26339495272f20d782/README.md), + including CLI/SDK use, platform requirements, snapshots, and beta status. +- [Dev Container Specification overview](https://containers.dev/overview). +- SendBox's [runtime security model](security-model.md), + [package delivery pipeline](package-supply-chain.md), and + [Safe Outputs implementation](architecture/safe-outputs.md). The gateway + documents its partial conformance to the upstream + [Safe Outputs specification](https://github.github.com/gh-aw/specs/safe-outputs-specification/). diff --git a/vendor/sendbox/docs/apple-runtime.md b/vendor/sendbox/docs/apple-runtime.md new file mode 100644 index 0000000..bd189a4 --- /dev/null +++ b/vendor/sendbox/docs/apple-runtime.md @@ -0,0 +1,293 @@ +# Apple runtime adapter + +`sendbox-runtime-apple` is the production Rust `RuntimeProvider` for the +official Apple `container` CLI and service. It invokes the executable directly +with exact argv, clears the inherited environment, supplies `PATH`, `LANG`, +`LC_ALL`, the host `HOME`/`USER`/`TMPDIR` needed by the registered service, and +explicitly marked secret variables, and never invokes a shell or language +bridge. Supplying the host service environment does not mount the host home +inside the VM. + +## Requirements + +- macOS on arm64 +- official `container` CLI and API server with exactly matching versions: + **0.10.0 / 0.10.0** or **1.7.1 / 1.7.1** +- a root-owned executable, root-owned/non-writable bundle and optional kernel, + and a root-owned mode `0444` Ed25519 public key +- the `container` service already registered and running +- a signed arm64 guest bundle whose signature, trust-root ID, host/guest + versions, artifact digests, modes, owners, architecture, and release sequence + pass `sendbox-bundle` verification +- an explicit Linux arm64 image and any configured kernel, mounts, network, + DNS, CPU, memory, and ulimit values + +The workload image must include `nft` and its runtime libraries, and the guest +kernel must support the mandatory +[egress enforcement prerequisites](installation.md#workload-image-versus-guest-bundle). +A plain Alpine base image does not include `nftables`. +Entrypoint and working-directory paths must also be symlink-free; see the +[workload image requirements](installation.md#workload-image-versus-guest-bundle). + +The 1.7.1 adapter changes are source compatibility, not a new SendBox release +or completed consumer qualification. Released SendBox v0.2.5 does not contain +them. Keep using independently verified, compatible released host/guest bytes +for production; a source build or portable fixture pass is not equivalent. + +`setup.sh` still installs only the pinned 0.10.0 signed package and verifies its +SHA-256 digest plus package signature. This compatibility change does not +update the installer, install 1.7.1, or change the registered service. All +other versions, prereleases, and mixed CLI/server pairs fail closed. + +Preflight is non-mutating. It queries version, complete command help, and +`container system status --format json`. It checks the API server's version and +`container-apiserver` identity, not just `status: running`. The 1.7.1 payload +must also identify the client as `container` at the selected CLI version. +Creation repeats preflight before inspecting/pulling an image or creating a +container, including when a library caller omitted a separate preflight. +It never runs `container system start`, `stop`, or registration commands. + +### Executable and service selection + +The production host resolves `container` in this fixed order, independently of +the caller's `PATH`: `/usr/local/bin`, `/opt/homebrew/bin`, `/usr/bin`, `/bin`. +It does not skip an older installed executable to find a newer one. Diagnostics +identify the selected absolute path and observed CLI/server versions. A +user-owned Homebrew CLI or writable ancestor is still rejected. + +`AppleRuntimeConfiguration.executable` is an explicit library API override. +`SENDBOX_APPLE_CONTAINER_EXECUTABLE` configures only the live test below; it is +not an override for `sendbox run`. The production CLI currently has no Apple +executable override. Do not copy an unsigned Homebrew binary into a trusted +location or relax ownership checks to make preflight pass. + +Apple 1.7.1 discovers plugins from the **running server's** `installRoot`: +`libexec/container-plugins` first, then `libexec/container/plugins` beneath that +root. The official signed package installs `bin/container`, +`bin/container-apiserver`, and `libexec/container/plugins//` under +`/usr/local`; each plugin has its own `bin/` executable and `config.toml`. +Apple's `--install-root` option belongs to `container system start`, not a +per-container command. SendBox clears inherited `CONTAINER_*` variables and +does not offer a plugin-root override or restart services. + +In the compatibility investigation, `/usr/local/bin/container` was 0.10.0 +while the API server and Homebrew CLI were 1.7.1. The old CLI returned an empty +network list and failed creation with `builtin network is not present`; the +matching 1.7.1 CLI could see the existing built-in `default` NAT network. That +error was not evidence that a network should be created or reconfigured. +An operator must review and provision a matching trusted CLI explicitly. + +### Reviewed JSON contracts + +The 1.7.1 contracts were reviewed against upstream +[`a15b46097aa4c2325da13c1fb5192b9274aab083`](https://github.com/apple/container/tree/a15b46097aa4c2325da13c1fb5192b9274aab083): + +- Image inspection accepts the 0.10.0 top-level `name`/`index.digest` layout + and the 1.7.1 `configuration.name`/`configuration.descriptor.digest` layout. + Exactly one image is required. The 1.7.1 raw-hex `id` must agree with the + canonical SHA-256 descriptor. A requested digest must match that descriptor, + never a tag, display name, annotation, or platform-variant digest. Inspection + is repeated after a pull; malformed or truncated output fails. +- Container inspection requires exactly one record bound to the owned + `configuration.id`. It reads the 0.10.0 top-level status string or the + 1.7.1 `status.state` plus matching top-level `id`. Missing, unknown, or + ambiguous state is an error, never cached `running` health or a recursively + discovered label. +- With the default network on 1.7.1, non-mutating + `network inspect default` must identify `id` and `configuration.name` as + `default`, mode `nat`, plugin `container-network-vmnet`, and label + `com.apple.container.resource.role=builtin`. This is a prerequisite check, + not network creation, migration, or an egress-policy exception. + +Apple 1.7.1 also restricts the default Linux capability set. A root UID alone +cannot program nftables: the reviewed default mask lacks `CAP_NET_ADMIN`. +The adapter explicitly grants that capability to the signed trusted guest +containment services. Only when syscall tracing is explicitly enabled does it +also grant guest-only `CAP_SYS_ADMIN`, needed by the reviewed guest to mount +tracefs and attach BPF programs. That broader trusted-service capability is +absent when tracing is disabled. It never requests `ALL` or a privileged +container. The non-root workload still runs through the signed +launcher with empty capability sets, seccomp and deny-first command/network +policy; these supervisor grants are not workload grants. The 0.10.0 argv is +unchanged because that CLI does not offer `--cap-add`. + +## Lifecycle and control transport + +The adapter checks or pulls the image according to policy, creates a named +container with the verified bundle mounted read-only, starts it, parses inspect +status, supports bounded log following, maps signals, stops with a grace +period, and deletes only the owned container. Workload exec is rejected; +`container exec` is reserved for bootstrap/control operations because workload +commands must pass through the authenticated guest broker. + +Provider-neutral create requests are applied at container creation: dynamic +environment, mounts, DNS servers, CPU, memory, working directory, and labels +override or extend adapter defaults. Memory must be expressed in whole MiB, and +conflicting no-DNS/DNS settings fail before the CLI is invoked. + +Both reviewed versions advertise `--publish-socket`, but no live VM evidence +establishes its replacement, ownership, cancellation, or bidirectional semantics. +The production adapter therefore **does not advertise published Unix sockets**. +It uses another official CLI surface: + +1. The provider combines the per-session secret with the signed trust metadata, + hardening requirements, and broker policy in the shared typed guest-bootstrap + schema, then `container exec --interactive` installs it as a root-created, + mode `0400` guest file. Before completing injection, the signed helper moves + init into the trusted runtime cgroup without enabling any controllers. +2. A detached bootstrap/control exec starts the verified guest supervisor. +3. A second interactive exec runs the signed `stdio-bridge`, which connects to + the session-unique guest Unix socket and relays raw stdin/stdout. +4. The merged SendBox handshake authenticates the byte stream before readiness + or requests are accepted. + +The bridge process and stream are owned by the provisioned channel and are +terminated during channel/runtime cleanup. There is no host-global socket, +daemon, port, or side channel. A real local Unix-stream fixture proves that the +relay preserves authenticated protocol bytes. The configured live gate proves +the same path across the Apple VM. + +## Qualification + +Unit and conformance tests: + +```bash +cargo test -p sendbox-runtime-apple --all-targets +``` + +Live qualification requires a prepared host. The test never mutates service +registration or service lifecycle: + +```bash +export SENDBOX_APPLE_CONTAINER_LIVE=1 +export SENDBOX_APPLE_CONTAINER_BUNDLE=/absolute/path/to/verified/bundle +export SENDBOX_APPLE_CONTAINER_PUBLIC_KEY=/absolute/path/to/root.pub +export SENDBOX_APPLE_CONTAINER_TRUST_ROOT_ID=release-root-v1 +export SENDBOX_APPLE_CONTAINER_MIN_RELEASE_SEQUENCE=1 +export SENDBOX_APPLE_CONTAINER_LIVE_IMAGE=ghcr.io/example/sendbox-base@sha256:... +# Optional explicit trusted CLI path, for this test only: +export SENDBOX_APPLE_CONTAINER_EXECUTABLE=/usr/local/bin/container +cargo test -p sendbox-runtime-apple --test live -- --nocapture +``` + +When `SENDBOX_APPLE_CONTAINER_LIVE=1`, missing configuration, a stopped service, +transport failure, authentication failure, or cleanup failure fails the test; +it is not converted to a skip. The image must already exist locally at its exact +index digest; the test never pulls it. It mounts only generated fixture data, +separate from host runtime state, uses unique container and session/socket +identities, and checks running and stopped inspect states. The primary live +operation has a 90-second deadline, followed by channel cleanup, stop, and +targeted delete even after failure. An ordinary test run without the live flag +does not provide physical qualification evidence. + +The November 11, 2026 investigation first verified mixed-version and +user-owned-CLI rejection before VM creation. After the operator provisioned the +official root-owned Apple 1.7.1 CLI, the live gate passed with the already-running +1.7.1 service and existing default network. A generated production-host Node +workload also exited successfully with non-root UID, empty workload capability +sets and `NoNewPrivs=1`. A separate generated cancellation returned exit 130, +rolled back its transient write, preserved prior successful output, and removed +the exact owned VM. No model credentials or live checkout were used. + +These runs used the source-built, dependency-patched host with the unchanged +reviewed v0.2.5 guest bundle, release sequence 10. They are backend evidence, +not patched guest or release qualification. New independently reviewed +compatible host/guest release artifacts and each consumer's exact-image +execution, cancellation, recovery, accounting, and checkpoint qualification +remain separate gates. + +Optional syscall tracing remains **unqualified on the inspected default guest +environment**: guest kernel 6.18.5 exposed neither +`/sys/kernel/tracing` nor `/sys/kernel/btf/vmlinux`. The reviewed tracer failed +with `mounting guest tracefs: No such file or directory`, even with the +explicitly opted-in guest-only `CAP_SYS_ADMIN`. Prepare a trusted guest/kernel +exposing tracefs, BTF and the required tracepoints before qualifying this mode. +Do not silently skip tracing or claim readiness when it was requested. SendBox +does not install a kernel or restart/reconfigure shared services to fix it. + +## Limitations + +- Only exact matching 0.10.0 and 1.7.1 CLI/server pairs are supported by this + source. No other version is accepted based on ordering or help similarity. +- The adapter does not start/register/stop the Apple service. +- `--publish-socket`, Rosetta, virtualization passthrough, SSH forwarding, TTY + mode, and arbitrary workload exec are not advertised. +- Neither reviewed CLI has a hostname option. Container identity remains the + session-unique container name rather than claiming a separately configured + kernel hostname. +- Runtime `Network` capability covers Apple network/DNS provisioning. + Restrictive policy is a separate signed guest admission: the provider binds + the authenticated egress policy and delegated execution cgroup parent into + bootstrap, and Exec cannot start until the guest DNS/SOCKS5 gateway reports + readiness. +- Bundle and trust-root mounts depend on official CLI bind-mount semantics and + are fail-closed by guest-side mode, owner, digest, version, and rollback + checks. + +## Guest readiness troubleshooting + +Bootstrap injection moves guest init from `/` to `/sendbox-runtime` before +controller delegation, without changing the cgroup namespace root. +Guest admission checks the full writable +cgroup2 mount independently of this membership change. It still rejects +subtree mounts, read-only mounts, and unrelated init cgroups. + +The v0.2.0 guest incorrectly required init to remain at `/` after moving it, +causing the mandatory egress service to exit before authenticated readiness. +Its execution broker also treated the supervisor's connect/disconnect socket +health probe as its sole execution connection and exited on the empty request. +The broker must survive that empty probe without accepting malformed requests +or weakening peer/session authentication. +The concurrent stdio relay can also repopulate the root cgroup during controller +delegation. Startup refreshes and migrates those processes when the kernel returns +`EBUSY`, retrying for at most five seconds rather than disabling the controllers. +Native exec also snapshots init's cgroup before attaching the new process. +Moving init only during concurrent supervisor startup leaves a window where +Apple targets the old root after controllers make it a non-leaf. The bootstrap +injection helpers now establish `/sendbox-runtime` before returning, so later +supervisor/control execs use a stable leaf. Controllers are still enabled and +verified by the supervisor, not by the injection helper. + +In one retained failed run, Apple reported `vmexec ... read ack pipe` while +starting the control relay; the guest was locally ready but the relay never +reached the handshake. Apple 0.10.0 can also wait indefinitely after such a start +failure. The upstream [waiter fix](https://github.com/apple/container/pull/1289) +is included in 0.11.0. That does not qualify 0.11.0 or every later version; +this adapter separately reviews exact supported pairs. Do not infer that a +later successful retry repaired an earlier failed run or upgrade the host +service as an implicit workaround. + +Replacing only the host CLI cannot correct that guest defect: rebuild and sign +the guest bundle as well. Host/guest manifest versions must match the binaries, +and trust-root identity, architecture, release sequence, digests, and ownership +must still verify. Never edit an installed signed bundle in place. + +A Node `fetch` error saying `Request was cancelled` can wrap a proxy failure +rather than application cancellation. Inspect its nested cause or Undici +diagnostics: HTTP CONNECT 502 indicates upstream resolution/connection failure; +403 is a policy denial. Domain policy validates the complete CNAME chain, so +allowing a public API hostname does not implicitly authorize its canonical +backend names. Keep those denials intact and require explicit policy approval +for any additional names. + +For first-request DNS failures, use the credential-free +[cold-start diagnostic](dns-cold-start.md). It measures a new VM's first +SOCKS/HTTP request without a lookup, warm-up or application retry, retains +sanitized resolver failure details, checks deny-first containment, and records +per-request latency and owned-VM cleanup. A successful later request is not +proof that the cold request worked. + +If readiness succeeds but launch reports `openat2`/`Symbolic link loop`, fix the +workload image or select its actual regular executable path. For a minimal +qualification image, the original Alpine base can be extended without relaxing +the broker: + +```dockerfile +FROM alpine@sha256:5291449c3df73caf6ed85e649dec1b9e818b39a5d8c871e97afc13e9cd5e8fa8 +RUN apk add --no-cache nftables \ + && cp /bin/busybox /bin/sh.sendbox \ + && mv -f /bin/sh.sendbox /bin/sh +``` + +Build without cache and pin the resulting image digest. This image is only a +minimal shell qualification image; it does not install a coding agent. diff --git a/vendor/sendbox/docs/architecture/agent-orchestration.md b/vendor/sendbox/docs/architecture/agent-orchestration.md new file mode 100644 index 0000000..f5005e0 --- /dev/null +++ b/vendor/sendbox/docs/architecture/agent-orchestration.md @@ -0,0 +1,72 @@ +# Host Agent Orchestration + +Status: **production transport-neutral orchestration**. `sendbox-agent` owns an +immutable run plan and the pure host-side state machine. `sendbox-host` composes +it with CLI `run`, concrete Apple/Kata/Hyperlight adapters, guest platform +controls, MCP, and security persistence without adding those dependencies to the +orchestration crate. + +## Run sequence + +1. Validate `SandboxConfiguration` and compile workspace, mount, environment, + command, workload-secret, package-policy, capability, and transport intents + into `RunPlan`. + An optional enclosing workspace becomes the signed mount root while the + initial cwd and Git guard stay bound to the selected project. +2. Reject missing runtime, brokered-exec, or transport capabilities before + resource creation. Package-enabled plans additionally require authenticated + audit/report capability. +3. Preflight, initialize, create, and start the selected runtime. +4. Resolve redacted bootstrap material, including registry-only credentials + that cannot overlap workload secrets, provision a lifecycle-owned channel, + and accept exactly one stream before the readiness deadline. +5. Authenticate the expected session with `sendbox-protocol` and verify guest + exec, streamed-I/O, and health capabilities. +6. Resolve named secret envelopes through an injected trait and send references + plus envelopes to the guest. Debug output never exposes envelope bytes. +7. Launch and monitor the workload through the guest channel. Runtime `exec` + remains bootstrap/control-only. +8. After a terminal response, fetch the bounded package report exactly once + when package analysis is enabled, fetch a single bounded syscall report + when tracing is requested, then gracefully close the authenticated + session. The guest report is returned to `sendbox-host` for independent + digest/schema validation and owner-only atomic persistence. +9. On success, signal, cancellation, transport loss, service death, report + failure, or backpressure, clean up guest execution, guest session, channel, + runtime stop, and runtime resources in order. + +Native CLI profiles do not change this state machine or add a host execution +path. Requested syscall tracing additionally requires authenticated readiness +for the mandatory BPF service. Guest homes are session-specific and never +inherit the host home. See [CLI compatibility](../cli-agents.md). + +`RunFailure` preserves the primary error and every cleanup failure separately. +Cancellation uses explicit tokens and an injected signal source. Readiness uses +a bounded Tokio deadline; tests use deterministic in-memory or Unix streams and +fault injection rather than vendor processes. + +## State model + +```mermaid +stateDiagram-v2 + Planned --> Preflighted + Preflighted --> Initialized + Initialized --> Created + Created --> Started + Started --> ChannelProvisioned + ChannelProvisioned --> GuestReady + GuestReady --> SecretsResolved + SecretsResolved --> Running + Running --> ReportRetrieved + ReportRetrieved --> Cleaning + Running --> Cleaning + Cleaning --> Completed + Planned --> Failed + Preflighted --> Failed + Initialized --> Cleaning + Created --> Cleaning + Started --> Cleaning + ChannelProvisioned --> Cleaning + GuestReady --> Cleaning + SecretsResolved --> Cleaning +``` diff --git a/vendor/sendbox/docs/architecture/authenticated-guest-protocol.md b/vendor/sendbox/docs/architecture/authenticated-guest-protocol.md new file mode 100644 index 0000000..7857511 --- /dev/null +++ b/vendor/sendbox/docs/architecture/authenticated-guest-protocol.md @@ -0,0 +1,268 @@ +# Authenticated Host/Guest Protocol + +This document defines the protocol invariants implemented by +`sendbox-protocol` and qualified through the Apple and Kata runtime transports. + +## Security boundary + +Each sandbox session receives a high-entropy bootstrap secret before untrusted +agent code starts. `sendbox-runtime` owns the transport-neutral provisioning and +lifecycle contract; concrete runtime endpoint mappings remain outside this +crate. The secret must be unique per session and available only to the trusted +host and guest bootstrap processes. + +The protocol provides mutual session authentication and integrity. It does not +encrypt general payloads. Runtime adapters must provide transport confidentiality +for ordinary confidential messages. Secret values are never placed directly in +frames: `agent.launch` carries XChaCha20-Poly1305 envelopes bound to the session, +guest role, secret name, sequence, expiry, and policy digest. +Long-lived trust roots, release signing, policy signing, and rollback floors are +separate versioned trust domains rather than protocol-session keys. + +Apple and Kata bootstrap also carry the schema-v3 signed boundary plan, the +session-derived schema-v3 egress runtime policy, the exact hierarchical MCP +runtime policy, the delegated execution cgroup parent, and gateway-only +credential material. The guest validates policy equivalence before starting +mandatory services. Gateway credential names must exactly match the signed MCP +policy and remain disjoint from workload secret names; values are zeroized after +delivery to the trusted gateway. Egress and MCP audit become ready before Exec, +and remote MCP readiness additionally requires the loopback HTTP gateway, +reserved-origin policy, marked dialing path, and kernel rules to be armed. + +When package analysis is enabled, the encrypted bootstrap additionally carries +the strict package policy, workload-facing and registry-only ports, private +cache and report paths, the dedicated proxy UID/GID, and zeroizing registry +credentials. Registry credential references are separate from +`agent.launch` secrets and cannot overlap them. Readiness then also requires +the trusted registry SOCKS gateway and isolated npm proxy. + +## Roles and versions + +- `HostClient` initiates the handshake. +- `GuestServer` responds. +- Post-handshake frames explicitly declare `HostToGuest` or `GuestToHost`. +- The current protocol version is `1`. +- Each peer advertises an inclusive supported version range. The negotiated + version is the highest common version. + +Role, version-range, session, nonce, capability, required-capability, and frame +limit fields are authenticated. A reflected role, wrong session, unsupported +range, altered negotiation, or repeated handshake is terminal. + +## Canonical wire encoding + +Messages use deterministic CBOR encoded by `minicbor`. Wire objects are +fixed-length arrays with fixed field order and numeric discriminants. Maps, +indefinite arrays, duplicate capability identifiers, trailing values, alternate +integer widths, and other noncanonical encodings are rejected by decoding and +canonical re-encoding. + +Message kinds are: + +1. hello +2. capability negotiation +3. readiness +4. request +5. response +6. event +7. cancellation +8. graceful close +9. protocol error + +Capabilities are typed identifiers for lifecycle, exec, streamed I/O, signals, +mounts, network, MCP, audit, and health. Authenticated framing remains version +1. The launch operational schema is separately versioned by +`OPERATION_SCHEMA_VERSION = 2`: `agent.launch` carries an exact program, +argument vector, absolute working directory, bounded non-secret environment, +policy-bound secret envelopes, and timeout; its terminal response carries +exit/signal or a typed cancellation/failure state plus broker cleanup +completion. Existing frame vectors are unchanged. + +Interactive launch schemas are negotiated by operation name rather than by adding a +wire capability. Legacy hosts use `agent.launch.interactive` with the V1 request. +Flow-controlled hosts use `agent.launch.interactive.v2`, whose request also selects +optional stderr separation. A new guest accepts both operations; an old guest rejects +the unknown V2 operation before either peer can exchange V2-only event kinds. + +After accepting V2, the guest may emit `TerminalInputCredit` events carrying a +strictly positive credit count no larger than the negotiated 64-chunk window. The +host does not read terminal input until the first grant arrives. `StandardInput`, +`StandardInputEof`, and `TerminalResize` retain their existing discriminants; +`TerminalInputCredit` is appended as event kind 9, so old discriminants and persisted +readers remain stable. + +Safe Outputs uses `safe_outputs.collect` schema version 1. The host can request +it only after a terminal result with complete broker cleanup. The guest returns +one bounded base64 artifact and authenticated seal, then rejects duplicate +collection. It is negotiated solely by the distinct operation name so the +legacy capability wire profile remains compatible with older peers. A required +collection rejected as unsupported is a hard downgrade failure. When Safe +Outputs is configured, authenticated readiness must also include healthy +mandatory `exec` and `safe_outputs` service identities. + +The package report operational schema is independently versioned by +`PACKAGE_REPORT_SCHEMA_VERSION = 1`. `package.report` uses request ID `2` after +the launch request's terminal response. Its request contains a positive bounded +`maximum_bytes`; its response contains the exact report JSON and a +`sha256:` digest. Package-enabled plans require the `Audit` +capability. + +Safe Outputs uses request ID `3`, distinct from launch and package reporting. + +`network.report` is an independently versioned schema-v1 operation using request +ID `5`. A signed `network_github_meta` admission requires its collection and the +existing `Audit` capability. After the launch terminal response, the guest +captures the latest root-owned workload/registry Meta status files once, +together with the authenticated configured policies. Reads use the same +descriptor-relative regular-file, owner, mode and link checks as package +reports. + +The report is bounded to 4 MiB and transferred as sequential 32-KiB base64 +chunks under the existing frame limit. Every response repeats the total, +offset and whole-report SHA-256. The host rejects unexpected offsets, changing +identities, malformed or oversized chunks, unsupported schemas, and digest +mismatches; the entire retrieval has a 30-second deadline. Source refreshes +cannot mix two snapshots during transfer. There is no new wire capability +discriminant or protocol-version change; an older peer rejects the distinct +operation. The host atomically persists the validated JSON with mode `0600`, +records its digest in signed session provenance, and includes a compact +`network_report: {path, sha256}` reference in `run --json`. + +[Governed sessions](governed-sessions.md) with brokered credential services +append event kinds 10 to 15 for the credential relay (schema version 1): +`CredentialRelayRequest`, `CredentialRelayRequestBody`, and +`CredentialRelayCredit` travel guest to host, `CredentialRelayResponseHead` and +`CredentialRelayResponseBody` travel host to guest, and `CredentialRelayEnd` +closes a stream in either direction. The guest chooses strictly increasing +stream identifiers starting at `1 << 32`, so they never collide with request +IDs. Response bodies use 32 KiB chunks, and the host never has more than 16 +uncredited chunks outstanding per stream. Relay events carry no credential +material. There is no new capability discriminant: a brokered plan requires the +guest's authenticated readiness to report a healthy `credential_relay` +service, and the host rejects relay events in a session without a brokered +relay. + +## Terminal post-processing ordering + +The launch request remains request ID `1`. If package analysis is configured, +or Safe Outputs is enabled, the host follows this exact sequence: + +1. receive the launch terminal response and all preceding output; +2. if configured, send one `package.report` request with request ID `2` and + validate response status, schema, byte limit, and digest; +3. if configured, collect `network.report` with request ID `5`, then the syscall + report with request ID `4`; +4. if configured, send one `safe_outputs.collect` request with request ID `3` + and validate the authenticated artifact and seal; +5. send graceful close; and +6. independently revalidate and persist or apply the collected host-side + reports and operations. + +The guest rejects a report request before the terminal response, after a +successful report response, when no report source is configured, or when the +request exceeds the policy/protocol limit. It reads the source +descriptor-relatively without following symlinks and requires the configured +owner, group, mode, regular-file type, and link count. Retrieval failure is an +explicit rejected response and fails a package-enabled run. + +The report carries no credentials. Authentication protects correlation and +integrity in transit; the host still recomputes the digest and checks canonical +JSON, summary counts, session ID, package-policy digest, record and finding +limits before accepting it. + +## Handshake + +1. The host sends a hello containing magic, version range, session ID, + `HostClient`, a 32-byte operating-system-generated nonce, advertised and + required capabilities, and its frame limit. +2. The guest validates the hello, selects the highest common version, computes + the capability intersection, verifies both peers' required capabilities, and + selects the lower frame limit. +3. The guest sends its version range, selected version, session ID, + `GuestServer`, both nonces, advertised and required capabilities, negotiated + capabilities, frame limit, and a negotiation proof. +4. HKDF-SHA256 uses the injected bootstrap secret and a transcript hash as salt. + Distinct labels derive negotiation, host-to-guest, and guest-to-host + HMAC-SHA256 keys. +5. The host verifies the negotiation proof using canonical hello bytes and + canonical negotiation bytes excluding the proof field. +6. The host and guest exchange directional authenticated readiness proofs. No + application message is accepted before both proofs verify. + +The transcript binds both advertised version ranges, both capability sets, both +required-capability sets, both nonces, both roles, the session ID, the selected +version, the negotiated capabilities, and the negotiated frame limit. + +## Authenticated frame layout + +Each stream frame is: + +```text +u32 big-endian CBOR length +CBOR [ + magic, + version, + session_id, + direction, + sequence, + message, + hmac_sha256 +] +``` + +The HMAC covers the canonical unsigned CBOR array containing every field except +the HMAC. The four-byte length prefix is not authenticated; it is validated +before allocation and is bounded independently. + +Sequence numbers start at zero and increase strictly by one in each direction. +Replay, gaps, overflow, wrong direction, wrong session, tampering, and +noncanonical frames fail explicitly. A rejected frame never advances receive +state and terminally poisons the connection. + +## Limits and backpressure + +- Hard frame ceiling: 1 MiB. +- Default frame ceiling: 256 KiB. +- Package report policy ceiling: 96 KiB, leaving room for JSON escaping and + operation framing below the default frame ceiling. +- Peers may configure lower limits; the handshake authenticates the lower value. +- The decoder reads only the four-byte prefix before validating the declared + length. Payload storage is allocated only after validation. +- Receive buffering never exceeds the validated frame plus its prefix. +- Async writes use `write_all` and naturally apply transport backpressure. +- V2 terminal input is additionally bounded to 64 authenticated chunks of at most + 4 KiB each. Credits travel guest-to-host without blocking the guest socket reader, + and end of file remains outside the credit budget. +- Credential relay responses are bounded to 16 outstanding 32 KiB chunks per + stream and to the profile's concurrent stream limit, so a slow agent cannot + stall terminal or control traffic. + +Dropping a receive future is resumable because already-read bytes remain in the +bounded reader buffer. Dropping a send future can leave a partial frame on the +stream, so it terminally poisons the local connection instead of allowing an +ambiguous retry. + +## Transport abstraction and errors + +Handshake and framed APIs operate on `AsyncRead + AsyncWrite`. The crate contains +no runtime adapter and assigns no vsock, Unix-socket, control-socket, or stdio +mapping. In-memory duplex and real Unix-domain socket tests prove the adapter +point on macOS and Linux. + +EOF before a frame is distinct from EOF during a frame. Authentication, +canonicalization, negotiation, replay, ordering, sequence exhaustion, frame +limit, and I/O failures are explicit errors. There is no success-shaped fallback +or resynchronization after an invalid authenticated frame. + +## Remaining qualification + +Before a runtime mapping is accepted, ADR-002 and ADR-005 still require: + +- confidentiality and trust-root decisions for that transport; +- live Apple, Kata, and Hyperlight cancellation, streaming, backpressure, and + lifecycle qualification; +- timeout and resource-exhaustion policy at the adapter/supervisor layer; +- bootstrap-secret provisioning, rotation, rollback prevention, and compromise + response; +- runtime-specific capability removal when a lifecycle behavior cannot be + proven. diff --git a/vendor/sendbox/docs/architecture/egress-enforcement.md b/vendor/sendbox/docs/architecture/egress-enforcement.md new file mode 100644 index 0000000..c3b9436 --- /dev/null +++ b/vendor/sendbox/docs/architecture/egress-enforcement.md @@ -0,0 +1,482 @@ +# Production egress enforcement architecture (`sendbox-egress`) + +Status: **production runtime integration**. This document describes the +`sendbox-egress` crate and its authenticated host/guest composition, which +promotes the proven +`spikes/egress-enforcement` mechanism into a production workspace crate. The +spike is left intact for reference; nothing here depends on it. + +The companion document +[`docs/security/egress-enforcement-trust-boundary.md`](../security/egress-enforcement-trust-boundary.md) +covers the trust boundary, threat model, residual risks, and the runtime +integration contract. + +## Goals + +Constrain a sandboxed agent's outbound network access to exactly what a +[`sendbox_policy::NetworkPolicy`](../../crates/sendbox-policy/src/lib.rs) +permits, and do so with a mechanism that: + +- fails closed — no agent traffic is possible until every control is armed and + verified; +- ties enforcement to a **kernel-stable process identity** (cgroup v2), not a + shared UID that any process could assume; +- validates DNS answers and pins the exact validated address, defeating DNS + rebinding; +- gives the package registry proxy a third kernel identity that can reach only + its trusted loopback SOCKS gateway; +- bounds DNS query-name exfiltration deterministically, without entropy + heuristics; +- forbids `unsafe` Rust and never shells out. + +## Two layers + +### Portable policy core (all platforms) + +| Module | Responsibility | +|---|---| +| `address` | Classifies destination addresses (loopback, link-local, RFC 1918, ULA, multicast, cloud metadata, unspecified) and canonicalizes IPv4-mapped IPv6. | +| `domain` | RFC 1035 domain normalization and exact/wildcard pattern matching. | +| `policy` | Compiles `sendbox_policy::NetworkPolicy` into a `PolicyEngine` of deterministic, side-effect-free decisions. | +| `authorization` | Bounded, expiring `(name, ip)` authorization cache — the anti-rebinding pin. Prunes expired entries on insert and enforces a deterministic hard capacity derived from the DNS budget. | +| `resolver` | The injectable `UpstreamResolver` trait and `ResolvedChain`. | +| `forwarding_resolver` | Bounded, fixed-upstream forwarding resolver: connects UDP to the exact upstream address **and** port, validates response id/question, bounds records/CNAME depth, recovers over the same upstream's TCP on truncation or UDP silence within the original deadline, and merges A/AAAA only when their CNAME chain and final owner agree. | +| `dns_budget` | Deterministic, bounded DNS exfiltration controls (structural limits, QTYPE allowlist, response cap, per-window budgets). | +| `connect_proto` | The small, versioned, bounded CONNECT framing protocol. | +| `socks5` | A bounded SOCKS5 (RFC 1928) front end: no-auth negotiation, CONNECT only. | +| `dns_broker` | Loopback DNS broker: decodes/validates/authorizes, applies budgets, emits audit events. | +| `connect_broker` | Loopback CONNECT broker: selectable front end, pins the validated address, re-checks the port-aware decision, dials via a `Dialer`, proxies bytes. | +| `gateway` | Colocates both brokers so they share one `AuthorizationCache`, engine, guard, and audit sink. | +| `github_meta` | Validates whole official Meta documents and host-supplied seeds; owns expiring immutable snapshots and provenance. | +| `github_meta_client` | Host-side anonymous fixed-origin HTTPS: system DNS, exact-IP direct dials, verified TLS, bounded bodies, rate-limit detection, and no redirects or environment proxy. | +| `audit` | Typed, deterministic, serializable audit events and sinks. | +| `dialer` | The `Dialer` abstraction and `SO_MARK`-aware socket helpers. | +| `runtime` | Session-derived authenticated runtime policy, stable instance/table/mark identity, execution-cgroup parent, and exact proxy environment. | + +The core performs no privileged operations and is exercised by the unit tests in +each module plus the portable `tests/gateway_integration.rs` suite. + +### Linux enforcement layer (`cfg(target_os = "linux")`) + +| Module | Responsibility | +|---|---| +| `linux::cgroup` | Supervisor-owned stable cgroup v2 hierarchy (`sendbox//{agent,broker,registry}`), with optional `pids`/`memory`/`cpu` delegation through the agent ancestor for descendant execution leaves. | +| `linux::mark` | `SO_MARK` socket helpers (via `socket2`) and the `MarkDialer`. | +| `linux::nft` | Deterministic nftables rendering keyed on `socket cgroupv2` + `meta mark`; atomic apply/validate/cleanup/verify via `nft -f -` (stdin, no shell, no temp files). | +| `linux::preflight` | cgroup v2, `nft socket cgroupv2` support, `CAP_NET_ADMIN`, and `SO_MARK` probes. | +| `linux::supervisor` | The armed guard enforcing setup ordering, teardown, and atomic update/rollback. | + +## Identity: cgroup v2 + `SO_MARK`, never `meta cgroup` + +The spike keyed nftables on `meta skuid` (UID). Any process sharing that UID +could originate broker-class traffic. The production layer instead keys on +`socket cgroupv2 level N "path"`: + +- The supervisor owns a stable hierarchy `sendbox//agent`, + `sendbox//broker`, and `sendbox//registry` under the + cgroup v2 root. The `level` in each nftables rule equals the number of path + components. +- The **agent cgroup ancestor**, including every nested execution leaf beneath + it, may only originate traffic to the loopback DNS and public CONNECT broker + ports plus the workload-facing npm proxy port when package analysis is + enabled. +- The **broker cgroup** may originate external traffic **only when the socket + also carries the fixed `SO_MARK`** (`meta mark`), and never to cloud-metadata + addresses. +- The **registry cgroup** may originate traffic only to the registry-only + loopback SOCKS port. It cannot reach the public broker ports, external + destinations, or obtain the broker mark. + +`meta cgroup` (cgroup v1 `net_cls`) is deliberately never emitted; a test +asserts its absence. + +Production execution uses: + +```text +/sys/fs/cgroup/sendbox//agent// +``` + +The nftables identity remains the level-3 `agent` ancestor, so every execution +descendant inherits the same network boundary. The agent ancestor is an internal +cgroup: direct process placement is rejected once controllers are delegated. + +Because SO_MARK must be set on *every* broker-originated external socket, both +the CONNECT broker's dials (`MarkDialer`) and the DNS forwarding resolver's +upstream sockets (`ForwardingResolverConfig::with_socket_mark`) apply the mark. + +## Broker front ends + +The CONNECT broker speaks one of two client-facing protocols, selected once per +instance via `ConnectBrokerConfig::frontend` (never auto-detected from the first +bytes, which would be ambiguous and attacker-influenceable): + +- `ConnectFrontend::Custom` (default) — the crate's small, versioned, bounded + framing (`connect_proto`), which also carries an optional client `expected_ip` + consistency check. +- `ConnectFrontend::Socks5` — standard SOCKS5 (RFC 1928), no-authentication + negotiation, `CONNECT` only. `BIND` and `UDP ASSOCIATE` are refused with + `Command not supported`, which is how UDP/QUIC is denied at the SOCKS layer. +- `ConnectFrontend::Http` — bounded HTTP/1.x CONNECT plus absolute-form HTTP + forwarding, with matching authority/Host validation and strict body framing. + Proxy credentials and ambiguous framing are rejected. + +All front ends funnel through the *same* `authorize_and_dial` path: resolve and +pin a hostname (or validate a direct IP), re-check the full port-aware policy +decision, and dial the exact validated `SocketAddr` through the `Dialer`. Only +the wire framing and the reply-code mapping differ. A runtime selects the SOCKS5 +front end when the agent toolchain speaks standard SOCKS5 (e.g. an +`ALL_PROXY=socks5h://host:port` environment), and the default custom front end +otherwise. The SOCKS5 success reply reports the broker's *upstream* socket local +endpoint in `BND.ADDR`/`BND.PORT` (`upstream.local_addr()`, per RFC 1928 §6), +not the requested destination; the custom front end sends no bound address, so +this does not weaken it. + +A fresh hostname resolution on the CONNECT path is not a policy bypass: it runs +the name through the *same* shared `DnsGuard` as the DNS broker — structural +QNAME limits, the QTYPE allowlist, the response-record cap, and the +deterministic exfiltration budget — and audits any denial or rate limit. When +`allow_dns = false` the CONNECT broker performs no fresh resolution at all and +relies solely on prior cached authorizations, so disabling DNS truly closes the +resolution path. + +### Resolver loss handling and diagnostics + +The forwarding resolver gives each concurrent A/AAAA query one absolute +three-second deadline. A missing UDP reply is retransmitted once halfway +through that budget, preserving the connected socket, upstream, socket mark, +question and ID. If UDP is still pending at that halfway boundary, one TCP +exchange also starts against the same numeric upstream and port, with the same +question/ID and socket mark. UDP remains live; a TCP transport failure cannot +discard its later valid reply. A validated UDP truncation flag starts TCP +immediately instead. Socket setup, both UDP sends and that one TCP exchange +consume the original budget; no phase restarts it. Complete TCP responses still +require exact header/question validation and a clear truncation bit. Permanent +response errors and invalid replies fail closed, not a later-answer fallback. + +Both family results must complete before CNAME agreement and policy validation +can authorize any address. A timeout, cancellation, or denied CNAME does not +prime the shared authorization cache. The brokers retain their separate +five-second upstream-resolution bounds and cancellation gates. + +Resolver failures retain typed, sanitized query/transport/operation and OS-code +metadata in `DnsResolutionFailed` audit events. HTTP CONNECT keeps status 502 +but returns a DNS `Proxy-Status` and bounded JSON diagnostic; free-form upstream +errors and packet contents are excluded. SOCKS/native status bytes do not +change. See [cold-start qualification](../dns-cold-start.md) for the distinction +between local service readiness, an external DNS failure and controlled loss +testing. + +## Descriptor-relative cgroup operations + +Every cgroup filesystem operation is **descriptor-relative and symlink-race +resistant**. `linux::cgroup` opens the cgroup v2 root once as a capability +`cap_std::fs::Dir` and performs all hierarchy creation, `cgroup.procs` writes, +and removals relative to that descriptor. `cap-std` confines resolution beneath +the opened root (Linux `openat2`/`RESOLVE_BENEATH`), so a symlink planted under +the root can never redirect an operation outside it; a regression test proves an +escaping symlink is refused. + +### cgroup identity and the required nft mount view + +The hierarchy is created directly under the mounted cgroup v2 root +(`/sendbox//…`), so the `CgroupIdentity` nftables matches on is +exactly that **mount-relative** path: nftables userspace *stats* +`/sys/fs/cgroup/` to resolve a `socket cgroupv2` rule, and the kernel +adds the current cgroup-namespace subtree level internally — it is not a +process-cgroup-prefixed global path. The same mount-relative path is reused for +the filesystem operations and for the agent, broker, and registry process +placement accessors. + +Because that resolution is a userspace `stat` in nft's *own* mount namespace, +whatever executes `nft` must keep the supervisor's mount view of +`/sys/fs/cgroup`. The live harness therefore runs nft with +`nsenter --net=/var/run/netns/ -- nft …`, which enters only the target +**network** namespace. `ip netns exec` must **not** be used here: it additionally +unshares the mount namespace and remounts `/sys`, hiding the owned cgroups from +nft's `stat` and yielding `cgroupv2 path fails: No such file or directory` even +though the network namespace is correct. The live suite gates on `nsenter` +availability (util-linux). + +## Safe setup ordering (never fail open) + +`ArmedEgress::arm` performs, in order: + +1. **Preflight** — cgroup v2 mounted, `nft socket cgroupv2` supported, + `CAP_NET_ADMIN` held, `SO_MARK` settable. Any gap is a hard error. +2. **Create the stable cgroup hierarchy** and, for production execution, + delegate required controllers through + `root -> sendbox -> instance -> agent`. +3. **Validate** the rendered ruleset with `nft --check -f -` against the real + cgroup paths (the definitive `socket cgroupv2` support/resolution check). +4. **Apply** the ruleset atomically with `nft -f -`. +5. **Verify** the owned table is installed (`nft list table`). +6. Only then return the `ArmedEgress` guard. + +Any failure at or after step 2 best-effort unwinds only what *this call* created +and returns an error. Because a failed `nft` apply is atomic (the whole +transaction rolls back), a failed **re-arm** of an already-live instance +preserves the previous owned table — the supervisor never runs `nft` cleanup on +an apply failure — and leaves that instance's cgroups untouched, so a transient +re-arm failure cannot strip live enforcement. Holding the guard is the +precondition for placing and starting the agent. Dropping the guard tears +everything down. + +## Authenticated production composition + +The host derives a schema-v5 `RuntimePolicyDocument` from the authenticated +session ID, configured `NetworkPolicy`, any remote MCP origins, and any package +registry isolation. Apple and Kata bind that exact document into guest bootstrap +together with the matching execution broker cgroup parent. The guest rejects +session, cgroup, gateway-port, reserved-origin, registry, or direct-IP-policy +drift before starting any service. + +The guest supervisor makes Egress a mandatory service and makes Exec depend on +it. The egress supervisor: + +1. validates and consumes its root-owned configuration; +2. recovers the original resolver from root-owned state under `/run/sendbox`; +3. starts gateway children that bind the public DNS/SOCKS listeners, the + optional trusted MCP HTTP listener, and the optional registry-only SOCKS + listener, but do not serve yet; +4. arms delegated cgroups and nftables, then places only the gateways in the + broker cgroup; +5. starts the npm proxy as UID/GID 65532 in the registry cgroup with cleared + capabilities, no `SO_MARK`, and a bounded seccomp/resource profile; +6. authorizes the gateways and proxy to serve, installs loopback resolver + configuration, and only then publishes readiness. + +Workloads receive exact upper- and lower-case `ALL_PROXY`/`NO_PROXY` and +`HTTP_PROXY`/`HTTPS_PROXY` variables, plus fixed `NODE_USE_ENV_PROXY=1`. +The HTTP listener on port 15083 and SOCKS listener on 15080 share the same +authorization cache, DNS guard, semaphore, and marked dialer. Both ports are +signed and pairwise distinct from DNS, MCP, and package ports. +A brokered [governed session](governed-sessions.md) adds the signed credential +relay port 15084, also pairwise distinct, which nftables admits only from the +agent cgroup to loopback. +The authenticated stdio MCP broker receives the same fixed proxy environment, +so local servers remain descendants of execution leaves and cannot bypass +enforcement. The remote MCP gateway remains in the broker cgroup and uses +marked exact-address dials rather than the agent-facing CONNECT cache. +Package-enabled workloads also receive upper- and lower-case npm registry and +`ignore-scripts` variables. The public gateway uses a derived policy that denies +the configured npm upstream; the trusted registry gateway keeps the original +policy and is reachable only from the registry cgroup. +Shutdown runs in reverse dependency order: Exec is fully stopped before Egress +restores resolver state and attempts cgroup-then-nftables teardown. All service +shutdown failures are aggregated rather than abandoning later cleanup. + +### GitHub Meta delegation and refresh + +An effective exact `github.com` grant delegates to the fixed official Meta API. +Compilation stays offline and immutable for configured rules. + +**The host owns the only fetch.** Each gateway used to fetch Meta before +readiness, so every session cost one or two anonymous requests against +GitHub's limit of 60 per hour per IP address. Many short sessions exhausted it +and then failed with HTTP 403. Now `sendbox-host` keeps one machine-wide cache +in the private runtime state root (`~/.sendbox/run/github-meta.json`, mode +`0600`, guarded by an exclusive `flock` on `github-meta.lock`): + +- A response validated less than an hour ago is reused without a request, so + concurrent and back-to-back sessions share it. +- An older response is revalidated with its ETag: a `304` renews it, a `200` + replaces it after full validation, and the cache costs at most one request + per hour per machine. +- A failed refresh is recorded with its time and typed error. Retries wait 60 + seconds, or until the published reset for a rate limit (403/429 with + `x-ratelimit-remaining: 0` or `retry-after`), capped at one hour. +- During a failure the previous document is reused only while at least 15 + minutes remain before its 24-hour expiry, so it outlives guest boot plus one + bounded execution. Otherwise the session fails with the typed error, + including the rate-limit reset time. +- Every cached document is reparsed with the strict validator on read. A + corrupt or tampered cache is discarded, never granted. + +The host also refuses delegation when a role denies the fixed source: an +explicit `api.github.com` deny, disabled DNS, or a TCP/443 exclusion. Role +address and network controls govern guest traffic, not this host request. + +The validated body, ETag, validation time, and latest attempt and error form a +`GitHubMetaSeed`. Its SHA-256 is bound into the signed `network_github_meta` +admission (`host_seeded_official_https_meta_v2:sha256=...`). The seed travels in +bootstrap schema v5, whose limit grows from 2 MiB to 5 MiB to fit a maximum +document. The guest supervisor writes it once to a root-owned `0400` file beside +the egress configuration. Each gateway reads it, revalidates the full document, +and installs it **after** its marked identity is armed and **before** +readiness. Guests never contact GitHub, and no refresh task runs in the guest: +an execution is capped at 300 seconds, far below the hourly interval. + +The parser explicitly reviews the documented CIDR fields plus the live +`shared_ingress` field, the arrays under `domains`, the full/wildcard inbound +Actions domains, and artifact-attestation `services`. SSH/commit keys and +`trust_domain` identities never become routes. Unknown fields or any invalid +destination reject the complete candidate. Limits are 2 MiB, 16,384 network +entries and 4,096 domain entries before deduplication; default routes are +rejected. The source is API version `2022-11-28`, not a caller-supplied URL. + +Each request evaluates one immutable scope view. DNS pins carry its revision; +every installed seed changes that revision, and an expiry produces a +scope-less view. New CONNECTs therefore cannot reuse authorizations for removed +CNAMEs. In-flight resolutions and dials recheck their revision. Explicit +domain/network denies, restricted-address checks, ports, DNS controls, MCP +reservations and trusted-registry separation remain authoritative. Published +networks only add public direct-IP reachability; they never unlock a +restricted address class or authorize an unlisted hostname. + +A missing or invalid seed is fatal to the gateway. Expiry is 24 hours after the +host's last successful fetch or conditional revalidation. The gateway converts +the remaining time into a monotonic deadline at install time, because a freshly +booted guest cannot backdate an `Instant`, and checks it on every new view. +Seeds validated more than five minutes in the guest's future are rejected. The +status distinguishes pending, fresh, degraded (the host reused last-good after +a failed revalidation), unavailable and expired. The previous digest/scope +remains diagnostic after expiry, but has no granting power. Existing tunnels +retain their original 300-second bound. + +Before activating a seed, production atomically publishes its full status to a +root-owned `0600` file under the existing private session directory. +Publication failure revokes derived scope and is fatal to the gateway. +`AuditSink::record_github_meta` is fallible; the normal typed JSON event is also +emitted. Unlike ordinary captured stderr counts, these files feed the bounded +authenticated `network.report` operation and final CLI JSON evidence. The +report includes the configured policy next to the latest published scope and +its URL, API version, digest, ETag, revision, timestamps and failure state. +It is a latest-attempt snapshot, not an append-only audit history. + +The boundary-plan format remains v3. Its `network_github_meta` feature binds +the seed digest and the schema-v5 egress document digest, and requires +authenticated report collection. Matching updated host/guest artifacts are +necessary: older guests reject the new bootstrap field, and newer guests +reject a delegation without a seed. + +## Atomic apply / update / rollback and fail-closed teardown + +`NftConfig::render_transaction` emits `destroy table` followed by a fresh table +definition, applied as one `nft -f -` transaction. `nft` applies a file +atomically, so any error aborts the whole update and leaves the **previous** +table intact — never a partial ruleset. `ArmedEgress` keeps the last-known-good +`NftConfig` in memory: + +- `update(new)` validates then applies; on success it becomes the new + last-known-good, on failure the previous table survives untouched; +- `rollback()` re-applies the last-known-good; +- `teardown()` is **fail-closed ordered** and **retryable**: it removes/verifies + the owned cgroups *first*; only once they are gone does it remove the nftables + table. The cgroup and nftables stages are tracked independently, so if cgroup + cleanup reports any real error (e.g. a process still occupies a cgroup) the + nftables table is **retained** so that process cannot regain unrestricted + egress, the error is surfaced, and a later call retries; likewise, if the + cgroups are gone but the nftables `destroy` fails, a later `teardown()` skips + the completed cgroup step and retries only the table removal. The top-level + owned `sendbox` cgroup directory is removed when empty and tolerated when a + sibling instance still owns it. It is idempotent and absent-safe. + +## Data flow (armed sandbox) + +```text +agent ──(loopback)──▶ DNS broker ──validate name/CNAME/addr, budget, cap TTL──▶ resolver + ◀── pinned answer ── records (name,ip) authorization ──┐ + │ shared AuthorizationCache +agent ──(loopback CONNECT)──▶ CONNECT broker ──pin validated ip, re-check policy──▶ + dial (SO_MARK) ──▶ upstream + +agent ──(loopback /mcp/)──▶ MCP gateway + ──separate marked DNS, classify, reserve aliases/addresses, exact-IP dial──▶ + configured upstream + +agent ──(loopback HTTP)──▶ npm proxy ──verify/scan/cache──▶ trusted SOCKS broker + ──(SO_MARK)──▶ npm upstream +``` + +nftables drops any agent packet that is not headed to a loopback broker port, +the optional MCP gateway port, or the optional npm proxy port, and any broker +external packet that lacks the mark or targets metadata. It drops every +registry-cgroup packet except TCP to the trusted registry SOCKS port. + +## Remote MCP reservation and bypass protection + +Remote MCP is admitted only through the trusted application-layer gateway. +Primary and redirect origins are normalized into the signed runtime policy. +The agent-facing CONNECT broker checks those configured names and observed +aliases before ordinary domain authorization and denies them first. + +While any remote MCP server is configured: + +- authenticated egress is mandatory even if the ordinary network policy would + otherwise be permissive; +- nftables admits the exact MCP loopback port in addition to DNS and CONNECT; +- all agent-facing direct-IP CONNECT is denied, preventing literal-IP and + shared-address bypasses; +- gateway DNS uses a separate marked resolver and never grants authorization in + the agent cache; +- every observed address is classified before reservation or dialing, metadata + addresses are always rejected, and reservation updates are bounded and + atomic; +- only the broker cgroup can emit marked upstream packets. + +There is no direct-origin fallback if the gateway, DNS validation, TLS, +reservation update, audit sink, or egress control fails. + +## Policy source of truth + +`sendbox_policy::NetworkPolicy` remains authoritative for ordinary workload +egress. The signed runtime document additionally carries policy-derived remote +MCP origins, the trusted gateway port, and direct-IP denial. These fields must +exactly match the signed MCP policy. `allow_dns = false` binds no agent-facing +DNS broker and installs no nftables DNS accept rule; the trusted MCP gateway +still uses its separate marked resolver when remote MCP is configured. + +When package analysis is enabled, `sendbox-egress::runtime` derives a +workload-facing policy that removes direct access to every configured npm +upstream while preserving the original policy for the registry-only gateway. +The package proxy is therefore mandatory rather than a convention expressed +only through npm environment variables. + +Compilation and validation fail closed rather than substituting a +success-shaped default for an invalid value: + +- `max_connections: Option` maps via `resolve_max_connections` — `None` to + the documented default (100), but a non-positive value or one above the + supported ceiling (`MAX_CONNECTIONS_CEILING`, or `u32`) is a deterministic + `PolicyError`, never silently clamped or defaulted. +- Every DNS structural limit and per-window budget is range-checked at both + `sendbox_policy::PolicyConfiguration::validate` and `PolicyEngine::compile`: + `max_qname_octets` ∈ 1..=253, `max_label_octets` ∈ 1..=63, positive + `max_labels`/`max_response_records`/all budget counters, a positive + `max_ttl_secs`/`window_secs`, and a non-empty QTYPE allowlist. Any zero or + out-of-range field is a deterministic error. + +## Testing and qualification + +- Portable unit tests live beside each module; portable integration tests are in + `tests/gateway_integration.rs`. Both run on macOS and Linux. Deterministic + nftables tests also prove that the workload can reach the npm proxy but not + the trusted registry SOCKS listener, that the registry cgroup can reach only + that trusted listener, and that no registry rule accepts `SO_MARK`. +- The privileged live proof is `tests/live_netns.rs`, gated by + `target_os = "linux"`, `SENDBOX_EGRESS_LIVE=1`, and a full `Preflight` (plus + `setpriv`). It proves cgroup identity isolation, the mark requirement, a + nested execution leaf that can reach the loopback broker but cannot connect + directly externally, sibling/identity-spoof denial, direct-egress bypass + denial, non-vacuous + IPv6/UDP denial with reachable positive controls, an **unprivileged agent** + (dropped via `setpriv` with all capabilities cleared and `no_new_privs`, whose + raw-socket creation is denied), **marked upstream DNS with a UDP-truncation → + TCP fallback** through a real `ForwardingResolver`, a **real kernel + apply-time-failure rollback** (an update ruleset references a candidate cgroup + that passes `--check`, is deleted immediately before the genuine `nft -f -` + commit so the real transaction fails to resolve it, and the previous table is + shown to survive before an explicit disrupt/rollback restores enforcement), + and broker restart. Teardown surfaces errors, which the test asserts are + empty, then verifies every namespace/veth/table/cgroup resource is absent + after normal, repeated, and injected-panic cleanup. On a host that cannot + enforce it fails loudly when `SENDBOX_EGRESS_LIVE_REQUIRE=1` (the CI job), + never a silent skip. +- The harness itself reads its policy/fixture config with `O_NOFOLLOW` (or an + inherited descriptor) **before** any cgroup/namespace transition, so a symlink + swap or predictable-path reopen after a transition cannot influence it. The + live harness's config files are exclusive, unpredictable, mode-0600 temporary + files (via `tempfile`, `O_EXCL`), retained for the run and cleaned up — with + absence assertions — in teardown, never predictable `/tmp/-` paths. +- The macOS development host cannot run the privileged suite; CI runs it on a + privileged Ubuntu x86_64 runner. diff --git a/vendor/sendbox/docs/architecture/execution-broker.md b/vendor/sendbox/docs/architecture/execution-broker.md new file mode 100644 index 0000000..ab373bb --- /dev/null +++ b/vendor/sendbox/docs/architecture/execution-broker.md @@ -0,0 +1,170 @@ +# Production Execution Broker + +Status: **production runtime integration**. + +`sendbox-exec` implements ADR-001's execution-mediation contract without +depending on a guest supervisor or runtime adapter. `sendbox-guest` and +`sendbox-host` integrate it into authenticated Apple and Kata sessions. The +historical `spikes/exec-broker` crate remains the Phase 1 qualification record. + +## Security boundary + +The broker makes semantic decisions for one typed, top-level execution request. +An admitted command and its descendants inherit kernel containment, but the +broker does not recursively parse or authorize descendant argv. + +```mermaid +flowchart LR + A[Agent after trusted bootstrap] -->|authenticated typed request| B[Broker] + A -. seccomp denies .-> X[Direct execve and execveat] + B -->|sanitized request and immutable decision| L[Dedicated launcher] + L -->|openat2 descriptors| F[Approved executable and CWD] + L -->|clone3 into configured leaf| C[cgroup v2 command tree] + C -->|execveat approved FD| P[Command and descendants] + L -. timeout, cancellation, disconnect, or broker EOF .-> K[cgroup.kill and pidfd reap] +``` + +The trusted bootstrap must install `PR_SET_NO_NEW_PRIVS` and a TSYNC seccomp +filter before any untrusted input, plugin, tool, or model-controlled callback. +Providers that cannot guarantee that ordering cannot claim semantic command +enforcement. + +## Agent/runtime ownership + +The host agent reaches this broker through the runtime-owned authenticated guest +control channel. `sendbox-agent` validates `BrokeredExec` and guest `Exec` +capabilities before launch and sends the workload over that channel. +`RuntimeProvider::exec` is reserved for trusted bootstrap and control operations; +it is not an alternate workload path. Apple and Kata wire this through their +authenticated supervisor transport. Third-party CLI agents are brokered +top-level workloads; their spawned tools inherit kernel/VM containment, not +recursive semantic argv authorization. + +## Typed contract + +`ExecutionRequest` carries: + +- the `SessionId`, 32-byte session authentication value, correlation ID, and + optional cancellation ID; +- an exact argv vector that is never joined, quoted, shell-parsed, or passed + through `/usr/bin/env`; +- executable and working-directory paths relative to named, pre-opened roots; +- a bounded, explicit environment and `/dev/null` stdin; +- a timeout and per-command containment profile. + +`ExecutionDecision` records allow or deny, the matched rule, and +`SemanticScope::TopLevelOnly`. `ExecutionEvent` streams started, stdout, stderr, +and terminal events. The terminal result separates the execution cause from a +truthful cleanup status: no child, complete cleanup, or incomplete cleanup with +the failed step. + +## Policy compilation + +`sendbox-policy::CommandPolicy` is compiled once into immutable broker rules. +Deny rules take precedence and the configured default action remains explicit. + +The production grammar preserves argv boundaries: + +- ASCII whitespace separates rule tokens. +- Backslash escapes the next character. +- Unescaped `*` and `?` match only within one argv token. +- A rule matches exactly the number of tokens it declares. +- Quotes, substitutions, expansions, and shell reparsing do not exist. + +This deliberately does not preserve legacy joined-command-string ambiguity. +For example, `git *` matches `["git", "status --short"]`, but it does not match +`["git", "status", "--short"]`. + +## Descriptor-safe launch + +The launcher opens every trusted root with `O_PATH|O_DIRECTORY|O_NOFOLLOW`. +Executable and CWD resolution uses: + +```text +openat2( + RESOLVE_BENEATH | + RESOLVE_NO_MAGICLINKS | + RESOLVE_NO_SYMLINKS | + RESOLVE_NO_XDEV +) +``` + +The resulting descriptors and device/inode identities are retained. Renaming or +replacing the original path cannot change the approved object. The child changes +directory with the approved CWD descriptor and executes only the approved +executable descriptor through `execveat(AT_EMPTY_PATH)`. + +There is no path-based fallback. Missing `openat2` or `execveat` support is a +typed, fail-closed `UnsupportedKernel` result. + +## Atomic containment and cleanup + +The launcher is a dedicated single-threaded process. It creates and configures a +fresh command leaf below a supervisor-owned cgroup v2 subtree before creating a +child. `clone3(CLONE_INTO_CGROUP|CLONE_PIDFD)` places the child atomically in +that leaf and returns a pidfd. There is no spawn-before-registration fallback +and no numeric PID or process-group ownership decision. + +The command tree receives: + +- cgroup `pids.max`, memory, swap, and optional CPU limits; +- POSIX descriptor, process, core, file-size, and address-space limits; +- an empty capability bounding/effective/permitted/inheritable set; +- NNP and a dangerous-syscall denylist; +- a child-only seccomp rule denying `clone3`, preventing pointer-based namespace + flag bypass after the trusted launcher has used `clone3` itself; +- a constrained environment and no inherited control, cgroup, or launcher FDs. + +`clone3` remains unconditionally denied after the trusted launch, but returns +`ENOSYS` rather than `EPERM`. Modern glibc uses `clone3` for `pthread_create` and +falls back to classic `clone` only when it is unavailable. The fallback stays +inside the existing namespace-flag filters, capability drop, NNP, inherited +seccomp, and cgroup containment. No pointer-based clone arguments are admitted. +Other dangerous-syscall denials still return `EPERM`; the trusted launcher's +atomic `clone3(CLONE_INTO_CGROUP|CLONE_PIDFD)` path is unchanged. + +Cleanup order is fixed: + +1. record timeout, cancellation, disconnect, saturation, shutdown, supervisor + death, exit, or launch failure; +2. write `1` to `cgroup.kill`; +3. wait for and reap the leader through its pidfd; +4. observe `cgroup.events` report `populated 0` within the configured bound; +5. remove the command leaf and supervisor subtree. + +Unexpected broker control-pipe EOF is treated as supervisor death. The +independent launcher remains alive long enough to perform the same cleanup. + +## Service authentication + +Each service instance creates a new session-named runtime directory with mode +`0700`, a create-exclusive credential file with mode `0600`, and a Unix socket +with mode `0600`. Existing paths are never unlinked or reused. Both peers check +socket type, owner, and mode; accepted and connected streams are authenticated +with Linux `SO_PEERCRED`. + +The service is session-scoped. Frames are bounded typed records. +`sendbox-protocol`, the production guest supervisor, and the Apple/Kata +adapters provide the authenticated host/guest transport. + +## Required Linux primitives + +Production launch fails closed with the exact unavailable primitive: +`openat2`, `execveat(AT_EMPTY_PATH)`, `clone3(CLONE_INTO_CGROUP|CLONE_PIDFD)`, +pidfds, `waitid(P_PIDFD)`, cgroup v2 delegation, `cgroup.kill`, seccomp TSYNC, +or `SO_PEERCRED`. + +## ADR-001 gap status + +| ADR-001 concern | Status | +|---|---| +| Exact top-level argv admission without shell reinterpretation | Closed | +| Direct agent `execve` and `execveat` after trusted bootstrap | Closed | +| Symlink, rename, and path-resolution TOCTOU | Closed by retained `openat2` descriptors and `execveat` | +| Spawn before supervisor registration | Closed by `CLONE_INTO_CGROUP` | +| PID and PGID reuse during cleanup | Closed by pidfd and cgroup descriptor ownership | +| Child-tree cleanup after timeout, cancellation, disconnect, or broker death | Closed by `cgroup.kill` and bounded removal | +| Recursive semantic authorization of descendant commands | Remaining by design | +| Safe voluntary lockdown by an arbitrary malicious agent binary | Remaining; trusted bootstrap is mandatory | +| Complete guest/VM containment | Remaining; runtime and VM integration are separate layers | +| Guest supervisor and runtime-adapter wiring | Closed by production guest supervisor and Apple/Kata composition | diff --git a/vendor/sendbox/docs/architecture/git-branch-guard.md b/vendor/sendbox/docs/architecture/git-branch-guard.md new file mode 100644 index 0000000..066aa6f --- /dev/null +++ b/vendor/sendbox/docs/architecture/git-branch-guard.md @@ -0,0 +1,86 @@ +# Native Git branch guard + +`sendbox-git` is the native Rust admission engine for selected-repository +`git push` and `git pull` operations. `sendbox-host` resolves the selected +repository, signs the guard policy into the boundary plan, and Apple/Kata guests +install trusted wrapper copies before workload execution. The crate remains +usable as a small standalone policy API. + +## Policy and identity + +The version 1 policy document contains: + +- the selected repository as normalized `host`, `owner`, and repository `name`; +- the selected workspace as an absolute path captured by canonical path and + filesystem identity; +- protected branches, allowed glob patterns, and optional `{username}` + expansion; +- the inherited environment-key allowlist and fixed executable search path; +- probe timeout, output, and policy-size bounds. + +Remote parsing accepts HTTPS, HTTP, SSH, Git protocol, SCP-style SSH, and +owner/name shorthand on the selected host. Repository paths must contain exactly +two decoded components. Unsupported helpers, local paths, encoded separators, +multiple effective push URLs, and mixed identities are ambiguous and fail +closed for selected-repository operations. + +Protected branches always override allowed patterns. The current branch must be +non-detached and allowed. Selected-repository clones are guarded regardless of +workspace path, while positively resolved other repositories pass through. + +## Git grammar + +The parser separates global options, resolves non-shell aliases with an +eight-expansion limit, and models supported push/pull repository options. +`-C`, `-c`, `--git-dir`, and `--work-tree` are forwarded unchanged to every +probe and final execution. `--config-env` is rejected because it can create a +different configuration view. + +The guard resolves branch remotes, `remote.pushDefault`, branch push remotes, +upstreams, configured push/merge refspecs, and every `push.default` mode. Exact +force-prefixed and deletion refspecs are normalized. Wildcard, negative, +revision-expression, tag, mirror, matching, and other unbounded updates fail +closed when they cannot be reduced to exact local source and remote branch +destinations. + +The pull check preserves the existing policy intent: the current branch and +integration source branches must be allowed. This does not prevent equivalent +`fetch` plus `merge` or `rebase` sequences. + +## Process contract + +`GitProcessRunner` is injected. The system runner: + +- requires a canonical absolute, regular, executable Git path; +- rejects symlinks, group/world-writable binaries, untrusted ownership, + recursive guard identity, and metadata changes after verification; +- verifies that the binary identifies itself as Git; +- bounds probe time and stdout/stderr while draining both streams; +- uses one sanitized environment for probes and final Git; +- rejects Git configuration/path injection and dynamic-loader variables; +- rejects caller-selected askpass programs, configured credential helpers, and + `--exec-path`; production GitHub HTTPS and SSH authentication use fixed + guest-installed wrappers; +- never includes environment values, credentials, probe output, or complete + argv in diagnostics; +- replaces the guard process with Git on Unix, preserving standard streams, + signals, and exit status without a shell or generated executable. + +The standalone protocol is: + +```text +sendbox-git-guard --policy /absolute/root-owned/policy.json \ + --git /absolute/trusted/git -- +``` + +Standalone deployment must place the policy, wrapper invocation, guard, and Git +binary in root-owned non-writable locations. Production guest deployment copies +the verified binaries and signed policy into the root-owned runtime boundary +and supplies fixed trusted values. + +## Security boundary + +This component admits one Git invocation. It does not block direct execution of +another Git binary, `git send-pack`, remote helpers, SSH receive-pack, alternate +clients, or GitHub APIs. Local inspection and final Git execution are also not +an atomic transaction. Server-side branch rules remain mandatory. diff --git a/vendor/sendbox/docs/architecture/governed-sessions.md b/vendor/sendbox/docs/architecture/governed-sessions.md new file mode 100644 index 0000000..ebbf48d --- /dev/null +++ b/vendor/sendbox/docs/architecture/governed-sessions.md @@ -0,0 +1,451 @@ +# Governed sessions + +Governed sessions add operator-signed policy profiles and host-side +credential mediation on top of the existing VM isolation, signed boundary +plan, and session audit. Standalone sessions are unchanged unless governance +is selected or required by the host. + +Two authorities are supported: + +- **Local** (single host): the host verifies the profile and runs the grant + authority in process. The principal is the local OS account. +- **Shared** ([`sendbox-fleet`](https://github.com/mbianchidev/sendbox-fleet)): + an authenticated, multi-user service enforces project-scoped roles, approves + bounded, expiring exceptions, admits sessions, issues and checks grants, and + keeps a central, hash-chained audit log. See + [shared governance service](#shared-governance-service). + +Both share the [`sendbox-governance`](../../crates/sendbox-governance) +contract crate (contract version 2). + +```mermaid +flowchart LR + subgraph Guest VM + A[Agent
    ANTHROPIC_BASE_URL / OPENAI_BASE_URL] -->|loopback, admitted for the agent cgroup| R[Credential relay
    trusted supervisor] + end + R -->|relay events on the authenticated control channel| H[Host relay endpoint] + H --> G{Grant authority
    binding, expiry, revocation, revision} + G -->|allowed| B[Broker
    verified TLS, DNS pinning,
    address classes, limits] + B -->|provider key injected on the host| U[(api.anthropic.com
    api.openai.com)] + O[Operator config + signed profile] --> P[Admission: verify, compose, bind] --> BP[Signed boundary plan
    + governance binding] +``` + +## Selecting governance + +| Mode | How it is selected | Who may own the files | +|---|---|---| +| Managed | `/Library/Application Support/SendBox/governance.yaml` (macOS) or `/etc/sendbox/governance.yaml` (Linux) exists | root, with every ancestor root-owned and not group/world writable | +| Opt-in | `sendbox run --governance-config PATH` on a host without a managed file | root or the current user, not group/world writable | +| Standalone | neither | not applicable | + +A managed configuration always wins. When it exists, every `sendbox run` is +governed and `--governance-config` is rejected if it names any other file. +There is no environment variable or project setting that disables governance +or selects another authority. If the managed path exists but cannot be read or +verified, the session fails closed. + +Opt-in mode is self-governance: it lets a user apply a signed profile to their +own sessions, but the user can stop selecting it. Use managed mode when the +operator and the session user are different parties. + +A standalone project that lists `credential_services` is rejected, because +brokered credentials only exist under a grant authority. + +## Operator configuration + +```yaml +format: sendbox.governance-operator +version: 1 +authority: local +profile: acme-default +profile_path: /Library/Application Support/SendBox/profiles/acme-default.yaml +# signatures_path defaults to profile_path + ".sig.json" +minimum_revision: 3 +trust: + threshold: 1 + signers: + - version: 1 + fingerprint: "" + name: Acme security + email: null + public_key_base64: "" + valid_from_unix: 1790000000 + expires_at_unix: null + revoked_at_unix: null +bundle: # optional: pin the guest bundle trust root + trust_root_sha256: [""] + trust_root_ids: [external-release-root] + minimum_release_sequence: 7 +revision_cache_seconds: 30 +fleet: # optional: use a shared governance service + url: https://fleet.acme.example + token_secret: SENDBOX_FLEET_TOKEN # host secret holding the caller's token + timeout_seconds: 10 +``` + +- `trust` builds a provenance trust store with `allow_unsigned: false`. At + least `threshold` distinct, unexpired, unrevoked signers must sign the + profile's exact bytes. +- `minimum_revision` is the operator's rollback floor. Raising it makes every + older revision, and every grant bound to one, stale. +- `bundle` pins the `--trust-root`, `--trust-root-id`, and minimum + `--minimum-release-sequence` a governed run may use, so a caller cannot + substitute their own guest supervisor. In managed mode the pinned trust root + file must be root-owned with protected ancestors, so it cannot be swapped + between the pin check and bundle verification. +- `revision_cache_seconds` bounds how long the grant authority reuses a + verified profile before re-reading and re-verifying it. +- `fleet` selects the [shared governance service](#shared-governance-service) + as the authority. `authority` must then equal the service's + `FLEET_AUTHORITY_ID` and cannot be `local`. `url` must use `https://`; + plain `http://` is accepted only for a loopback host. `timeout_seconds` is + 1 to 60. + +The host also keeps a per-user high-water mark of admitted revisions under the +runtime state directory and rejects a lower revision. That record is +user-writable; the operator `minimum_revision` is the authoritative floor. + +## Profiles + +Profiles are YAML documents signed byte for byte. Their digest is the SHA-256 +of those bytes, so any edit is a new revision that must be signed again. + +```yaml +format: sendbox.governance-profile +version: 1 +id: acme-default +revision: 4 +not_before_unix: 1790000000 +expires_at_unix: 1810000000 # at most 400 days after not_before_unix +ceiling: + runtimes: [apple, kata] + images: ["sha256:<64 hex>"] # optional; empty permits any image + workspace_roots: [/Users] # optional; empty permits any workspace + resources: { max_cpus: 8, max_memory_mb: 16384 } + commands: + default_action: deny + allowlist: ["/usr/local/bin/claude *", "git *", "cat *"] + network: + default_action: deny + allowed_domains: ["*.github.com", "registry.npmjs.org"] + allowed_networks: [] + allowed_ports: [] # empty permits any port + allow_dns: true + github_meta: false # implicit GitHub Meta CIDR delegation + mcp: + require_boundaries: true + servers: {} + packages: + allowed_registries: ["https://registry.npmjs.org/"] + require_supply_chain: false + secrets: + workload: [NPM_TOKEN] # names that may enter the guest + github: + forward_auth: false + forward_copilot_auth: false + allow_private_repository_access: false + ssh_key: false + require_branch_protection: true + safe_outputs: { enabled: true, allow_apply: false, repositories: [] } +denials: + commands: ["git push --force *"] + domains: [pastebin.com] + networks: ["169.254.0.0/16"] +credential_services: + - id: anthropic + provider: anthropic + secret: SENDBOX_ANTHROPIC_API_KEY + methods: [POST, GET] # default: GET, POST + path_prefixes: [/v1/messages, /v1/models] + max_request_bytes: 8388608 + max_response_bytes: 67108864 + max_duration_seconds: 900 + idle_timeout_seconds: 120 + deny_direct_egress: true + - id: openai + provider: openai + secret: SENDBOX_OPENAI_API_KEY +grants: + lease_seconds: 300 + max_ttl_seconds: 28800 + revocation_grace_seconds: 5 + max_concurrent_streams: 8 +exceptions: # optional: denials an approved exception may lift + max_ttl_seconds: 86400 # at most 7 days + commands: [] + domains: [pastebin.com] # each entry must also be listed in denials + networks: [] +``` + +Omitted ceiling sections take their most restrictive value. Unknown fields are +rejected. An omitted `exceptions` section permits no exceptions; see +[exceptions](#exceptions). + +### Signing workflow + +```bash +sendbox governance keygen --output ~/acme-governance.key # prints the public identity +sendbox governance sign acme-default.yaml --key ~/acme-governance.key +sendbox governance sign acme-default.yaml --key second.key --append # threshold signing +sudo install -m 0644 -o root acme-default.yaml acme-default.yaml.sig.json \ + "/Library/Application Support/SendBox/profiles/" +sendbox governance verify +sendbox governance check --config .sendbox.yaml +``` + +`check` loads the active profile, applies its denials, and lists every +violation without starting a session. Keep signing keys off the managed host. + +## Admission and composition + +Admission runs before any side effect such as resolving GitHub credentials, +creating session state, or starting a runtime: + +1. Discover the authority, load the operator configuration, check bundle pins. +2. Verify profile signatures, profile id, validity window, minimum revision, + and the local high-water mark. +3. Append profile denials and every `deny_direct_egress` provider host to the + session policy. Denials only add deny rules and blocked destinations. +4. Compare the effective configuration with the ceiling. Every violation is + reported; nothing is silently narrowed. +5. Sign a governance binding into the boundary plan. + +Composition is a subset check over expanded capabilities, never a merge: + +| Dimension | Rule | +|---|---| +| Runtime | Must be listed. Hyperlight is always rejected because it has no persistent guest boundary. Project-selected Kata executables, handlers, or configuration are rejected. | +| Image, workspace, resources | Image digest in `images`, workspace under a `workspace_roots` entry, resources at most the maximums, when configured. | +| Commands | `allow` default requires an `allow` ceiling. Each exact rule must be matched by a ceiling rule with the runtime's own argv and basename semantics; a wildcard rule must equal a ceiling rule. | +| Domains | `allow` default requires an `allow` ceiling. Exact names need a covering pattern; `*.x` needs `*.x` or a broader `*.y`. Entries already blocked are ignored. | +| GitHub Meta | An unblocked exact `github.com` grant implicitly delegates GitHub Meta CIDRs and requires `github_meta: true`. | +| Networks and ports | Each CIDR must be contained in a ceiling CIDR. A port ceiling requires an explicit, covered port list. | +| DNS | Numeric limits at most the ceiling (defaults equal the runtime defaults), record types a subset, and the budget window equal. | +| MCP | The boundary must stay enabled when required. Legacy flat tool rules are unsupported. Each server must match a ceiling server's transport, command or URL, tools, HTTP flags, redirects, and secrets. | +| Packages | Registries, plaintext HTTP, credentials, finding overrides, and exceptions need explicit ceiling permission; inspection can be required. | +| Secrets | Workload secrets must be listed; a brokered credential or a provider endpoint variable can never be a workload secret. | +| GitHub | Token forwarding, Copilot forwarding, private access, SSH keys, disabled branch protection, and Safe Outputs apply mode or targets each need ceiling permission. | +| Credential services | Must be offered by the profile. | + +Observability settings are not capabilities and are not compared. + +## Binding + +`BoundaryPlan.governance` records the authority (id and trust digest), the +exact profile (id, revision, SHA-256), the principal, the project, the +effective policy SHA-256, the brokered service ids, and the ids of any +exceptions the session lifted (omitted when there are none). It is omitted +from standalone plans, whose canonical bytes are unchanged. The effective +policy digest must equal the plan's `policy_sha256`, which secret envelopes +already authenticate. A local authority uses `local-user:` as the +principal; a shared service uses the principal it authenticated. The project +is `github:/` (or a workspace path digest). + +## Brokered credentials + +A project requests services by profile id: + +```yaml +credential_services: [anthropic] +``` + +The host resolves each provider credential from the host secret store before +the session starts (`sendbox secrets add SENDBOX_ANTHROPIC_API_KEY`) and keeps +it in the host process. It is never part of the boundary plan, bootstrap, +secret envelopes, guest environment, or audit. The guest receives only: + +| Provider | Base URL variable | Key variable | +|---|---|---| +| `anthropic` | `ANTHROPIC_BASE_URL=http://127.0.0.1:15084/` | `ANTHROPIC_API_KEY=sendbox-brokered-credential` | +| `openai` | `OPENAI_BASE_URL=http://127.0.0.1:15084//v1` | `OPENAI_API_KEY=sendbox-brokered-credential` | + +The key value is a fixed placeholder that the broker discards. Policies +describe services, not agents: any agent or SDK that honors these variables +works, including Claude Code and Codex. + +### Compatibility contract + +- The client must support an explicit base URL and append the upstream path. +- Request bodies need `Content-Length`; chunked uploads are rejected. +- Clients that hardcode their service origin or require HTTPS proxy tunneling + are unsupported. SendBox never falls back to delivering the raw credential, + intercepting TLS, or executing on the host. + +### Relay + +The trusted guest supervisor listens on `127.0.0.1:15084`; when egress is +enforced, nftables admits that port only for the agent cgroup. A request to +`//` becomes one relay stream on the authenticated control +channel. The guest drops `authorization`, `x-api-key`, `cookie`, and forwarding +headers, and the host additionally forwards only the provider's header +allowlist. + +The host checks method and path locally, asks the grant authority, injects the +credential (`x-api-key` for Anthropic, `Authorization: Bearer` for OpenAI), +and sends the request with the existing broker transport: verified HTTPS on +port 443, DNS resolved and classified per request, addresses pinned, no +system proxy, and redirects denied. Responses stream back as they arrive, +including server-sent events. The guest grants one credit per chunk written +to the agent and the host never exceeds 16 outstanding 32 KiB chunks, so a +slow agent cannot stall terminal or control traffic. Limits per service bound +request size, response size, total duration, and idle time; a stream whose +upstream or guest credit stays idle longer than `idle_timeout_seconds` fails. +When the agent disconnects or the guest stops reading a stream, the guest +tells the host so it closes the upstream connection. + +## Grants and revocation + +At session start the grant authority issues one grant per brokered +service, bound to the principal, project, session, binding digest, profile +revision, methods, path prefixes, a renewable lease, and a hard maximum +lifetime. Every request is checked for: + +- an existing, unrevoked grant with an unexpired lease and lifetime; +- the exact principal, project, session, and binding digest from trusted host + state (workload-supplied identity is never consulted); +- the granted service, method, and segment-aware path prefix (encoded + separators and dot segments are rejected); +- a profile revision that is still the operator's current, verified revision + and not below the minimum. + +An unreadable or unverifiable profile denies with `authority_unavailable`. The +host renews leases at a third of the lease length. When a grant's renewal +fails, new requests for that service are denied and its in-flight streams get +`revocation_grace_seconds` to finish before they are cancelled and the agent +sees the stream end with `grant_lapsed`. Streams of other services are not +affected. Streams are authorized once at start and are +otherwise bounded by `max_duration_seconds`. + +When the workload ends, is cancelled, or fails, the relay stops accepting +requests, aborts in-flight streams, and revokes every grant. A stream that was +already sent upstream is recorded as `aborted_uncertain`: SendBox does not +claim that revocation reverses completed external effects. + +## Audit + +Records join the existing signed session audit chain: + +| Action | Recorded when | +|---|---| +| `governance.admission.accepted` | the session starts under a profile | +| `credential.grant.issued`, `.lapsed`, `.revoked` | grant lifecycle | +| `credential.request.allowed`, `.denied` | each authorization decision | +| `credential.request.outcome` | each stream ends, with status, byte counts, duration, and outcome | +| `governance.exception.expired` | a lifted exception expired and the session was stopped | +| `credential.request.outcome_report_failed` | a stream outcome could not be reported to the shared service | + +Each record carries principal, project, session, authority, profile id, +revision and digest, effective policy digest, and binding digest. The +admission record also lists each lifted exception with its scope, requester, +approver, and expiry, and the service URL when a shared service is used. Request +records add the service, method, path without query, and reason. Credentials, +headers, query strings, and request or response bodies are never recorded. A +failure to record relay evidence fails the run. + +## Shared governance service + +With `fleet` in the operator configuration, the host uses +[`sendbox-fleet`](https://github.com/mbianchidev/sendbox-fleet) as its +authority. The profile is still read from `profile_path` and verified against +the operator's `trust` signers on the host; the service separately verifies the +same signed bytes when an operator publishes them, and only admits sessions +bound to its current revision. + +```mermaid +sequenceDiagram + participant H as SendBox host (caller's token) + participant F as sendbox-fleet + H->>F: GET /v1/whoami + F-->>H: principal (becomes the session principal) + H->>F: GET /v1/exceptions?project=…&state=active + Note over H: lift only approved exceptions for this principal,
    project, and exact profile revision; check the ceiling + H->>F: POST /v1/sessions:admit (session, binding) + Note over F: caller = binding principal, role ≥ member,
    current revision, every exception still valid + H->>F: POST /v1/grants · /v1/authorize · :renew + H->>F: POST /v1/sessions/{id}:end (revokes remaining grants) +``` + +- **Authentication.** The caller stores a service token in the host secret + store under `token_secret` (default `SENDBOX_FLEET_TOKEN`). With an + identity provider, `sendbox governance login` exchanges an OIDC token for a + short-lived service token and stores it: + + ```bash + my-idp print-id-token | sendbox governance login # or --identity-token-file PATH + ``` + + The service URL comes only from the verified operator configuration. + Tokens can also be issued by the service operator and added with + `sendbox secrets add SENDBOX_FLEET_TOKEN`. A token is sent only to the + configured URL, redirects are never followed, system proxies are ignored, + and it can never be a workload secret. +- **Identity.** The authenticated principal, not the local account, is the + session principal. The service refuses a binding whose principal is not the + caller, so a host cannot claim another identity. +- **Roles.** Admission needs the `member` role or higher in the project. + Roles, exceptions, and audit are managed through the service; see its + [architecture](https://github.com/mbianchidev/sendbox-fleet/blob/main/docs/architecture.md). +- **Grants.** The service is the grant authority. Every brokered request is + authorized by the service; any non-200 answer, timeout, or unreachable + service denies with `authority_unavailable`. Nothing falls back to the + local authority or to credential delivery. +- **Outcomes.** When a brokered stream ends, the host reports its redacted + outcome (`succeeded`, `failed`, or `unknown` when a stream was cut after + reaching the provider) to the service, which records it in the central + audit. Reports are sent in order and flushed before grants are revoked; a + report that fails is recorded as `credential.request.outcome_report_failed` + in the session audit, which keeps the authoritative local record. +- **End.** After the workload ends, the host revokes its grants and ends the + session on the service, which revokes any grant still live. + +### Exceptions + +An exception lifts exactly one profile denial for a project, or for one +principal in it, until it expires (at most 7 days). Only denials the operator +listed under the profile's `exceptions` section can be lifted, so the +operator's signed opt-in bounds every exception. Lifting a denial never adds a +capability: the session must still fit the ceiling, and provider hosts blocked +for brokered services are never lifted. + +A project member requests an exception against the current profile revision; +a different principal with the `owner` or `admin` role approves it. The host +lifts a denial only for an approved, unrevoked, unexpired exception bound to +the exact revision it runs under, binds its id into the signed boundary plan, +and the service re-checks it at admission. A new revision or a raised minimum +revision makes the approval stale, so it can no longer admit sessions. + +Egress and command rules are fixed when the VM starts, so the host stops the +session when the earliest lifted exception expires +(`governance.exception.expired`, exit code `6`). Like any failed run, the +workspace is rolled back to its starting snapshot, so request an expiry that +covers the work. Grants are capped at that +expiry, and once an exception is revoked the service denies the session's +brokered requests and lease renewals with `stale_policy`. Revocation does not +reach into the VM's egress rules: a revoked exception's lifted denial stays +lifted until the session ends or the exception's original expiry stops it. + +## Trust boundaries and residual risks + +- The local user who owns the host secret store can still read their own + provider key on the host. The guarantee is that the agent and guest never + receive it. +- Opt-in governance is chosen by the user and is not an enforcement boundary + against that user. +- The local revision high-water mark is user-writable; rely on + `minimum_revision` for rollback protection. +- Long-running streams are not re-authorized mid-stream. +- With `deny_direct_egress: false` and permissive network policy, a workload + that has its own provider key could still call the provider directly. Keep + the default to block the provider host for the workload. + +- A shared service that is compromised can authorize misuse but never sees + provider keys; the host broker keeps them. A compromised host is limited to + sessions and grants issued to the principals whose tokens it holds. +- The fleet token is a bearer credential for its principal. Keep token + lifetimes short; revoke tokens and disable principals in the service. +- `sendbox governance check` evaluates the local profile only and does not + consult the service for exceptions. + +Non-goals: Kubernetes or fleet scheduling, universal TLS interception, formal +policy verification, model API translation, and replacing isolation +providers. diff --git a/vendor/sendbox/docs/architecture/guest-artifact-bundles.md b/vendor/sendbox/docs/architecture/guest-artifact-bundles.md new file mode 100644 index 0000000..086064e --- /dev/null +++ b/vendor/sendbox/docs/architecture/guest-artifact-bundles.md @@ -0,0 +1,241 @@ +# Production guest BPF and artifact bundles + +This document defines the production build and trust boundary for the guest +artifacts consumed by the Apple and Kata runtime adapters. Bundle construction +is separate from runtime selection, guest launch, agent orchestration, and +guest `PlatformControls`. + +## Artifact flow + +`packaging/guest/Dockerfile` uses immutable base-image and package pins to build: + +1. `sendbox-guest` as a static musl binary; +2. `sendbox-exec-launcher` as a static musl binary linked against a pinned, + source-built static libseccomp 2.6.0; +3. `native/bpf/observe.bpf.c` as a CO-RE eBPF object; +4. deterministic inventory, SPDX 2.3 SBOM, capability metadata, and the guest + artifact manifest; +5. a deterministic rootfs tar and a scratch OCI image containing only the + trusted runtime artifacts and metadata. + +The final rootfs contains no Python, Node.js, compiler, bpftrace, development +headers, or shared runtime libraries. CI builds each architecture twice with +`--no-cache` in independent parallel jobs and compares the rootfs, manifest, +signature, inventory, SBOM, static-link proofs, and pinned `vmlinux.h` digest byte +for byte. + +## Signing boundary + +`sendbox-bundle stage` requires a caller-supplied 32-byte Ed25519 private key +through a file. The tool never creates a signing key, writes the private key +into the bundle, or provides a production key-custody mechanism. Docker accepts +the key only as the required BuildKit secret `release_signing_key`. + +The guest artifact envelope remains exactly schema v1 verified by +`sendbox_guest::manifest`; its artifact-kind enum is unchanged and contains +only guest, service, and BPF objects. A matching detached `manifest.sig` is +emitted for release systems that store signatures separately. + +Inventory, SBOM, build-input metadata, and the deterministic verification +report are covered by the separately versioned +`dev.sendbox.guest.release-metadata.v1` envelope and detached signature. This +avoids silently extending the guest manifest v1 wire contract. +The signer receives the verified BTF archive digest and the freshly generated +`vmlinux.h` digest from the build stages; it does not infer or hardcode them. +`release-public.key` is not self-authenticating merely because it is stored +beside the bundle. Tag releases sign bundles with the protected +`SENDBOX_RELEASE_SIGNING_KEY_BASE64` secret, publish the matching public key, +and attest the complete host and standalone guest archives through GitHub OIDC. +Operators must verify that artifact attestation against this repository before +using the embedded key as a runtime trust root. + +Release sequence, minimum accepted sequence, host version, guest version, +architecture, SHA-256 digest, mode, uid, gid, regular-file type, and single-link +expectations are verified before launch. Verification is descriptor-relative +and rejects symlinks, hardlinks, wrong architecture, rollback, tampering, and +mode or owner drift. + +Installed bundles are root-owned and non-writable. Executables use mode `0555`; +public metadata, signatures, BPF objects, and the release public key use mode +`0444`. These artifacts contain no secret material, so the unprivileged host CLI +can verify them without weakening the root-owned trust boundary. + +## BPF boundary + +`sendbox-bpf` is a safe Rust facade over libbpf-rs. No SendBox Rust source uses +unsafe code. The facade provides: + +- typed kernel, BTF, tracepoint, and capability probes; +- explicit unavailable, permission, relocation, load, attach, decode, timeout, + invalid-input, and internal errors; +- owned object, link, ring-buffer, map, and callback lifecycle; +- bounded deterministic decoding for exec, syscall-entry, and reserved MCP + observation ABIs; +- kernel ring-reservation, userspace queue-drop, and decode-failure accounting. + +The production programs observe `sched:sched_process_exec` and +`raw_syscalls:sys_enter`. Attachment requires a non-zero target cgroup id, and +both programs discard events outside that cgroup. Subtree attachment supplies +a retained cgroup descriptor through `scope_tree`, including nested execution +leaves without relying on a guessed hierarchy depth. This prevents a guest-wide +or host-wide syscall firehose. The programs do not parse policy, network traffic, +daemon protocols, or MCP payloads. + +The MCP event ABI is reserved and bounded for a later, explicitly proven +producer. This release attaches no generic MCP hook and makes no MCP capture +claim. + +All BPF behavior in this release is **observation/audit only**. Tracepoints run +after or alongside kernel actions and cannot authorize or deny them. Nothing in +this crate should be described as command, syscall, network, or MCP +enforcement. + +## Kernel and build requirements + +Runtime requirements: + +- Linux 5.8 or newer; +- `CONFIG_BPF=y`, `CONFIG_BPF_SYSCALL=y`, `CONFIG_DEBUG_INFO_BTF=y`, tracepoints, + and ring-buffer maps; +- readable `/sys/kernel/btf/vmlinux`; +- `sched:sched_process_exec` and `raw_syscalls:sys_enter` in tracefs; +- `CAP_BPF` plus `CAP_PERFMON`, or legacy `CAP_SYS_ADMIN`; +- a runtime policy that permits the `bpf` syscall; +- a cgroup v2 identity supplied by the runtime adapter. + +Build inputs: + +- Rust 1.93.1 and Alpine 3.23; +- pinned curl 8.23.0, OpenSSL 3.5.9, musl-dev 1.2.5-r24, and zlib 1.4-r0 + build dependencies; +- clang/LLVM 21.1.2 and bpftool 6.19.14; +- libbpf-rs 0.26.2 / libbpf 1.7.0; +- BTFHub archive commit + `abbcdfab668b9a346a24cb0829f1cfbb80bc51db`; +- Ubuntu 20.04 `5.8.0-63-generic` BTF archives with architecture-specific + SHA-256 verification; +- libseccomp 2.6.0 source archive with SHA-256 verification. + +Supervisor and production bundle builds download the pinned libseccomp source +through GitHub's release-asset API using its immutable asset ID. Requests use +bounded connection, transfer, and retry timeouts. The pinned version and SHA-256 +verification remain mandatory; exhausted retries fail the build. An optional +BuildKit secret `github_token` authenticates the request so shared CI runner +addresses do not hit GitHub's anonymous limit of 60 requests per hour; CI passes +`--secret id=github_token,env=GITHUB_TOKEN`. It never reaches an image layer. + +The production bundle, standalone supervisor, and BPF spike Dockerfiles use the +same `musl-dev`, `zlib`, `zlib-dev`, and `zlib-static` revisions, available for both +Alpine 3.23 architectures. The base image digest does not freeze APK repositories; +refresh these pins together when Alpine replaces a package revision. + +Generated `vmlinux.h` and BPF objects are build outputs, not checked-in source. +Configuration YAML uses the maintained YAML Organization `yaml_serde` 0.10.7 +implementation under the existing `serde_yaml_ng` dependency alias; the retired +`unsafe-libyaml` dependency is no longer present. +The C build enables strict warnings and compile-time ABI size assertions, then +checks for `.BTF`, `.BTF.ext`, and both required tracepoint sections. +`bpftool gen min_core_btf` resolves the object's CO-RE relocation requirements +against the pinned architecture BTF and emits a reproducible proof digest. + +## Continuous integration + +Portable Rust CI separates checks from build/install qualification so they can +run in parallel, with compiler- and lockfile-keyed dependency caches. The guest +quality job caches its pinned toolchain, system dependencies, and audit tool +through BuildKit, but disables caching for the quality stage so formatting, +Clippy, tests, fuzz compilation, and the dependency audit always run. Only the +quality base is exported to the shared cache, not the test results or compiled +workspace target directories. + +Each architecture has two independent, fail-fast clean-build matrix entries. +Both use `--no-cache`, without importing external build caches, and CI archives +their outputs before transfer to retain the original file modes. Verification +jobs compare every reproducibility proof and check the installed bundle as an +unprivileged user before uploading the final artifacts. OCI export reuses the +first build's local layers instead of performing a third clean compilation. +CI and tag-triggered release builds set `CARGO_BUILD_JOBS=2`; local builds retain +the Dockerfile's default of one Cargo job unless explicitly overridden. +The quality, clean-build and verification wrappers use `ubuntu-latest` for +x86_64, while native arm64 retains `ubuntu-24.04-arm`. + +The [production guest workflow](../../.github/workflows/guest-artifacts.yaml) +automatically runs the privileged live BPF smoke test on relevant pull requests +to `main` and pushes to `main`, using the workflow's existing path filters. +Manual dispatch runs the same test without an additional `live` input. + +The live-event matrix keeps native `ubuntu-24.04` (`x86_64`) and +`ubuntu-24.04-arm` (`aarch64`) runners to preserve the qualified kernel proof. +Each job builds its architecture-specific CO-RE object, +exports it through the Dockerfile's `bpf-artifact` target, mounts tracefs if +needed, and runs the live test with `SENDBOX_BPF_LIVE=1` under `sudo`. The test +loads and attaches the programs, executes `/bin/true`, and requires both exec +and syscall-entry events. Missing kernel support, privileges, or events fail +the job rather than silently skipping it. + +The environment variable remains an explicit opt-in for local Rust test runs. +CI privileges apply only to loading and attaching the observation programs; +application workloads receive no additional privileges, and these tracepoints +do not enforce sandbox policy. + +## Runtime integration + +The Apple and Kata runtime adapters: + +1. verify the bundle with an independently provisioned Ed25519 public key, + expected versions, architecture, and rollback floor; +2. retain verified executable descriptors from the guest manifest verifier; +3. probe the target guest kernel before attaching observation; +4. identify the owned execution cgroup v2 subtree; +5. start mandatory `ServiceId::Bpf` when `observability.syscall_tracing` is set, + calling `EventStream::attach_cgroup_tree` with the verified BPF bytes; +6. poll bounded batches, record `LossSnapshot`, and keep the `EventStream` alive + for the intended observation lifetime; +7. reject missing requested readiness, collect a bounded argument-free report + over the authenticated channel after workload termination, and verify its + session, architecture, schema and digest before private host persistence. + +The tracer starts after egress and before Exec, and detaches before egress +teardown. Its guest log is root-only and capped at 16 MiB; the host report keeps +256 samples, syscall counters, and explicit loss/limit accounting. Workloads +never receive BPF or performance-monitoring capabilities. See +[CLI agents and tracing](../cli-agents.md). + +Hyperlight uses its separately signed one-shot Unikraft bundle and does not +consume this persistent guest-service bundle. + +## Reproduce locally + +Use an externally managed key: + +```bash +docker buildx build \ + --no-cache \ + --platform linux/arm64 \ + --target artifact \ + --secret id=release_signing_key,src=/secure/path/release-ed25519.key \ + --build-arg HOST_VERSION=0.2.0 \ + --build-arg GUEST_VERSION=0.2.0 \ + --output type=local,dest=dist/arm64 \ + -f packaging/guest/Dockerfile \ + . +``` + +Use `linux/amd64` for x86_64. Never place a production private key in the build +context, image, repository, CI variables exposed to pull requests, or command +line. + +Set the expected host/guest versions to the versions of the binaries being +qualified, not an older build default. A guest-bootstrap fix requires rebuilding +and signing the guest bundle, not only rebuilding the host CLI. + +For development qualification, use a separately generated test-only signing key, +trust-root ID, release sequence, and root-owned installation path. Keep the key +outside the build context and remove it after signing. Never replace an installed +release's trust key or bundle with test material. A local signature is not a +release attestation, and portable fixtures or kernel prerequisite probes are not +evidence of an authenticated, fully hardened workload running in a real VM. + +The release secret is a base64 encoding of an exact 32-byte Ed25519 seed. It is +decoded only on the tag-release runner, checked for length, mounted into +BuildKit as a required secret, and never uploaded as an artifact. diff --git a/vendor/sendbox/docs/architecture/guest-supervisor.md b/vendor/sendbox/docs/architecture/guest-supervisor.md new file mode 100644 index 0000000..60bc253 --- /dev/null +++ b/vendor/sendbox/docs/architecture/guest-supervisor.md @@ -0,0 +1,225 @@ +# Guest Bootstrap and Supervisor + +Status: **production runtime integration**. This document defines the trust, bootstrap, +readiness, service, and fail-closed semantics implemented by +`guest/sendbox-guest`. Apple and Kata integrate the production execution broker, +mandatory DNS/SOCKS5 egress service, and authenticated MCP policy. The host +session lifecycle owns audit and snapshot persistence. The guest also starts the +mandatory MCP audit service and, for remote MCP, a trusted HTTP gateway inside +the egress broker. When enabled, the supervisor also owns the Safe Outputs +recorder and its seal key. BPF activation remains explicit guest policy. + +Threaded glibc workloads retain ordinary pthread support through classic `clone` +fallback. Both the agent bootstrap and child-only filter reject `clone3` with +`ENOSYS`, not an allow decision. Namespace clone flags and dangerous +process-control syscalls remain denied, and the bootstrap verifies the expected +`clone3` denial before publishing readiness. + +## Process and command model + +`sendbox-guest` is a static multi-call binary with these entrypoints: + +- `bootstrap` and `supervisor` both run the complete lifecycle in one long-lived + process. They are not separate stages because the bootstrap secret must never + cross a process boundary or be persisted. +- `health` reads the local atomic readiness marker. The authenticated control + protocol remains authoritative to a remote host. +- `service-run` is hidden and exists only for deterministic process-supervision + qualification. +- `inject-bootstrap` and `tunnel` are hidden runtime-only Kata controls. +- `exec-broker` is the mandatory one-session production broker service. +- `egress-supervisor` and `egress-gateway` are hidden production services for + cgroup/nftables ownership and loopback DNS, CONNECT, and MCP listeners. +- `mcp-audit` is the mandatory root-owned MCP audit sink. +- invocation as the installed `mcp-broker` path runs the exact-command stdio + broker selected by project MCP configuration. +- `safe-outputs-mcp` is a root-installed stdio bridge to the authenticated + session recorder. The bridge never validates or persists operations itself. + +Typed service identifiers reserve `exec`, `mcp`, `dns`, `egress`, `audit`, +`bpf`, and `safe_outputs`. Reserving an identifier does not claim that its +service is implemented. The Safe Outputs identity represents the mandatory +in-process recorder rather than a separate child, so the bootstrap secret never +crosses a process boundary. Exec depends on configured mandatory egress and +audit services; readiness is not published until the complete dependency graph +is healthy. + +## Trust and immutable bootstrap + +The runtime stages a prebuilt artifact tree before guest startup. The guest does +not download, generate, or replace artifacts. + +The release trust root is injected as a separate root-owned, single-link, `0444` +file containing exactly 32 raw Ed25519 public-key bytes. The guest never creates a +trust root. The one-time bootstrap input is a root-owned, single-link, `0400` +regular file under a symlink-free absolute path. It is opened once with +`O_NOFOLLOW`, inspected through the open descriptor, atomically renamed to a +consumed name, bounded to 64 KiB, parsed with unknown-field rejection, zeroized, +and unlinked. A persistent nonce digest in the root-owned replay ledger rejects a +copied bootstrap input. The replay ledger is provisioned separately from volatile +runtime state (default `/var/lib/sendbox/replay`), and its marker plus directory +are synced after bounded bootstrap validation but before the consumed source is +unlinked or artifact-manifest processing begins. + +The bootstrap secret is at least 32 bytes, redacted by the protocol type, zeroized +on drop, never logged, and never written to runtime state. Bootstrap and supervisor +remain one process so the secret reaches the authenticated handshake only in +memory. + +## Signed artifact manifest + +The signed envelope contains UTF-8 manifest payload bytes and an Ed25519 +signature. Signature verification precedes payload decoding. The signed payload +binds: + +- schema and signature domain; +- trust-root identity; +- monotonic release sequence and minimum accepted sequence; +- expected host and guest versions; +- target architecture; +- guest binaries, service binaries, and BPF object paths; +- SHA-256 digest, file mode, UID, and GID for every artifact. + +Artifact paths must be relative and contain only normal components. Verification +walks from an already-open artifact-root descriptor. Every directory component is +opened with `O_DIRECTORY | O_NOFOLLOW`; every artifact is opened with +`O_NOFOLLOW`, checked as a single-link regular file with `fstat`, and hashed from +that descriptor. Absolute paths, parent traversal, symlinks, hard links, digest +mismatches, owner/mode mismatches, architecture drift, version drift, forged +signatures, and rollback sequences fail closed. + +Verified service executable descriptors remain open. Linux service launch uses +the descriptor through `/proc/self/fd` rather than reopening the mutable artifact +pathname, so a post-verification rename or symlink swap cannot select new code. + +## Startup and readiness contract + +The only valid startup sequence is: + +1. `awaiting_bootstrap` +2. `bootstrap_consumed` +3. `manifest_verified` +4. `runtime_prepared` +5. `services_starting` +6. `controls_verified` +7. `self_testing` +8. `ready` +9. optionally `agent_launch_permitted` +10. `shutting_down` +11. `terminated` + +Any other transition is rejected. Failure enters `failed`, revokes readiness, and +can only continue through shutdown and termination. + +The per-session runtime directory is created with exclusive `0700` semantics. +Existing session state is stale and rejected. State and readiness files are +written through a synced temporary file and atomic rename. Readiness is published +only after: + +- the bootstrap was consumed and its nonce registered; +- the signed manifest and every artifact passed verification; +- the runtime directory passed ownership and mode checks; +- every required platform control reported `verified = true`; +- every mandatory service started in dependency order and passed health checks; +- platform and service self-tests passed; +- the control socket was bound. + +The guest then performs the existing `sendbox-protocol` mutual authenticated +handshake. Its first authenticated lifecycle event contains the exact release +sequence, verified control reports, service health, and deterministic audit +events. Mandatory-service liveness is rechecked after the handshake and before +every authenticated health or launch response. `agent.launch` is authorized once +and only while the local state is +`ready`. With a configured Kata broker, `agent.launch` decodes operational +schema v1, maps absolute paths to retained broker roots, forwards the exact argv, +streams sequenced output, forwards cancellation, and returns a typed terminal +result only after broker cleanup evidence is available. Without a configured +broker it is rejected. No marker, handshake, health response, or launch response +reports success for a control that was not verified. + +## Service supervision and failure behavior + +Each service has a typed identifier, verified executable path, dependencies, +mandatory flag, restart budget/backoff, health probe, graceful/forced shutdown +timeouts, and bounded stdout/stderr storage. Dependency cycles and missing +dependencies are rejected before spawn. A mandatory service cannot depend on an +optional service. Services run in dedicated process groups. +Output is drained concurrently and retained only up to the configured bound. + +The execution broker's connection-only startup health probe must not consume its +single execution session. It retries only a peer-checked connection that closes +without sending any request bytes. Nonempty malformed frames, invalid first +operations, wrong peer identities, and invalid session authentication still fail; +the actual execution request remains single-use. + +Optional services restart only within their declared budget, and dependents are +re-health-checked after an optional dependency restart. Any mandatory service +exit revokes the launch gate immediately; mandatory services are never restarted +inside an already-ready session. A mandatory service that cannot start, cannot +pass health, or exits causes: + +1. atomic readiness revocation; +2. protocol termination; +3. SIGTERM to every supervised process group; +4. SIGKILL after the grace limit; +5. direct-child reaping; +6. socket and per-session runtime cleanup. + +The same fail-closed path applies to authenticated protocol loss. Drop guards send +SIGKILL to process groups and remove runtime state if an async task is cancelled. +The replay ledger is intentional persistent security state and is not session +garbage. + +## Platform-control boundary + +Privilege drop, capabilities, and seccomp are represented by the injected +`PlatformControls` trait. The production Linux adapter requires root identity, +prepares and verifies the delegated cgroup v2 parent, starts the mandatory broker, +then installs and verifies the NNP/TSYNC direct-exec filter before readiness. +The bootstrap injection helper first moves init into `/sendbox-runtime`, before +completing injection or enabling any controllers. Native runtimes can snapshot +init's cgroup while preparing later control execs; its membership must be stable +before concurrent controller delegation makes the old root a non-leaf. Migration +failure aborts injection. This changes process membership, not the cgroup +namespace root. Egress admission accepts init +only at `/` or that trusted runtime leaf and independently requires a single +read/write cgroup2 mount rooted at `/` at `/sys/fs/cgroup`. Subtree mounts, +read-only mounts, and unrelated init cgroups fail closed. +The runtime may start its stdio relay while controllers are being delegated. +An `EBUSY` write refreshes and migrates the current root processes before retrying, +within a five-second deadline. Processes that have already exited are logged and +skipped; other migration errors, permission errors, and an exhausted deadline +remain fatal. No controller requirement is skipped to make readiness succeed. +The launcher drops brokered workloads to the non-root project uid/gid and applies +the production capability, rlimit, cgroup, pidfd, and command seccomp controls. +Tests retain a deterministic unprivileged adapter. + +Production egress/nftables, authenticated secret delivery, hierarchical stdio +MCP policy, the Streamable HTTP MCP gateway, and mandatory MCP audit integration +are wired into this lifecycle. BPF attachment remains an explicit policy-driven +observation feature and is never an MCP authorization mechanism. + +## Static delivery + +`guest/sendbox-guest/Dockerfile` builds with the pinned Rust 1.93.1 Alpine image +for `x86_64-unknown-linux-musl` and `aarch64-unknown-linux-musl`. The CI job builds +each architecture twice without cache, compares same-architecture binaries, and +uses `file`, `readelf`, and `ldd` evidence to reject an ELF interpreter or shared +dependency. + +The pinned libseccomp source is downloaded through GitHub's release-asset API +using its immutable asset ID, with bounded retries and network timeouts. +SHA-256 verification remains mandatory before extraction. The optional +`github_token` BuildKit secret authenticates the request in CI. + +Guest Supervisor CI passes `--build-arg CARGO_BUILD_JOBS=2` to the quality build +and both clean builds on each native architecture, matching production bundle +CI's compiler budget. The Dockerfile still defaults to one Cargo build worker +for local builds. Only compilation concurrency changes: locked dependencies, +quality checks, dependency audits, static-link checks, and both uncached +reproducibility builds remain unchanged. + +The x86_64 build wrappers follow `ubuntu-latest`. Native arm64 retains +`ubuntu-24.04-arm`, because GitHub has no supported floating arm64 Ubuntu alias. +The digest-pinned container and compiler inputs remain independent of the +wrapper image; the two-worker budget and both clean proofs are unchanged. diff --git a/vendor/sendbox/docs/architecture/interactive-terminal.md b/vendor/sendbox/docs/architecture/interactive-terminal.md new file mode 100644 index 0000000..b4b5eaa --- /dev/null +++ b/vendor/sendbox/docs/architecture/interactive-terminal.md @@ -0,0 +1,245 @@ +# Interactive Terminal Sessions + +Status: **production**. + +`sendbox run --interactive` runs the workload on a pseudoterminal inside the +sandbox so that terminal agents — GitHub Copilot CLI, Claude Code, Codex, +Gemini — can render a full-screen interface and accept keystrokes. Without it +the workload receives `/dev/null` on stdin, `isatty` is false, and every such +agent either refuses to start or degrades to a non-interactive mode. + +## Design constraint + +Interactive support must not widen the sandbox boundary. The host↔guest control +channel is already full duplex and already carries workload output as +authenticated `Message::Event` frames, so keystrokes travel the same path in the +opposite direction and inherit its message authentication, sequence and replay +protection, session binding, direction binding and 256 KiB frame cap. No new +transport socket, port or privilege is introduced. `--separate-stderr` adds only +a launcher-local PTY pair and the child fd 2 mapping described below. + +```mermaid +flowchart LR + K[Host terminal] -->|raw bytes| C[sendbox CLI] + C -->|StandardInput / EOF / Resize| G[Guest protocol loop] + G -->|ClientFrame::Input / Resize| B[Execution broker] + B -->|pty primary| L[Launcher] + L -->|controlling pty: fd 0/1| W[Workload] + L -.->|optional stderr pty: fd 2| W + W -->|stdout and optional stderr| L + L -->|output and input credits| B + B -->|Message::Event| C + C -->|stdout / stderr| K +``` + +## Negotiation + +Interactive runs negotiate behavior by operation name rather than by adding a +wire `Capability`. The CBOR codec rejects unknown capability values, so adding a +capability variant would break mixed-version peers even for headless runs. + +- `agent.launch.interactive` is the V1 operation. New guests continue accepting + it for old hosts, retaining the bounded-drop input behavior from SendBox 2.0. +- `agent.launch.interactive.v2` carries the V2 request with credit-based input + and the optional `separate_stderr` field. +- New hosts request V2. An old guest rejects the unknown operation before either + peer can exchange a V2-only event kind; there is no silent downgrade that + could reintroduce input loss. +- The initial `TerminalInputCredit` event is observable proof that the launcher + accepted V2 and is ready for input. + +Fail-closed admission uses the internal, non-wire +`RuntimeCapability::InteractiveTerminal`. Apple and Kata advertise it; Hyperlight +does not, and `sendbox-host` additionally rejects an interactive request for +Hyperlight before anything is created or started. + +The original interactive event discriminants (`StandardInput`, +`StandardInputEof`, `TerminalResize`) remain unchanged. V2 appends +`TerminalInputCredit` as event kind 9 and emits it only for the V2 operation, so +a V1 host never receives an unknown discriminant. + +## Terminal allocation + +The launcher opens the pseudoterminal pair **before** installing its own seccomp +filter, so a policy that denies `ioctl` cannot break allocation. Runtime resize +still needs `ioctl` after the filter is installed, so an interactive request is +rejected up front when the command policy denies `ioctl`, `setsid`, `dup2` or +`dup3`. The error names the offending syscalls. + +Because the launcher must be single threaded when it calls `clone3`, every +terminal pump thread is created after `clone3_exec` returns. + +The child establishes its controlling terminal in this order: `setsid`, +`TIOCSCTTY`, `dup2` the controlling secondary onto fds 0 and 1, optionally +`dup2` a second non-controlling secondary onto fd 2, `fchdir`, capability and uid +drop, seccomp, close the original secondaries, `execveat`. All raw +`setsid`/`ioctl`/`dup2` work remains in the audited Linux syscall adapter. + +By default fd 2 also uses the controlling terminal, preserving the merged stream +and strict terminal ordering. `--separate-stderr` allocates a second +pseudoterminal pair: + +- `isatty(2)` remains true, including color and TTY-sensitive diagnostics. +- Only the first device is the controlling terminal, so job control is unchanged. +- Every resize is mirrored to both devices. +- The second primary is read as `StreamKind::Stderr`, which already maps to + `EventKind::StandardError`. +- stdout/stderr interleaving is no longer strict because separate kernel buffers + are drained independently. + +The launcher releases both secondaries immediately after `clone3`; retaining +either would prevent the corresponding primary from reaching end of stream. +Separate stderr consumes one extra PTY pair per session, so deployments running +many concurrent sessions must account for `/proc/sys/kernel/pty/max`. + +## Flow control + +V2 uses a fixed window of 64 credits. One credit authorizes one non-empty input +chunk of at most 4 KiB, bounding the launcher's user-space backlog to 256 KiB. +The launcher emits the initial 64-credit grant only after the terminal writer is +ready, then returns one credit after a complete queued chunk has drained from the +backlog. Partial PTY writes retain the chunk and its offset; they never return +early credit. + +Credit and queue behavior by layer: + +| Layer | V2 behavior | +|---|---| +| `sendbox-cli` | Starts with zero credit. Its reader polls only the wake pipe at zero, reads at most one 4 KiB chunk per credit, and uses a depth-65 input/EOF FIFO plus a latest-value resize lane. | +| `sendbox-agent` | Validates grants never exceed 64 outstanding credits. A dedicated writer has a depth-4 priority control channel, a depth-65 input/EOF FIFO, and a latest-value resize lane. | +| Guest protocol | Relays credits without blocking its broker reader. Its writer has a depth-4 priority control channel, a depth-64 input channel, a dedicated EOF reservation that drains after preceding input, and a latest-value resize lane. | +| Exec service | The socket reader uses non-blocking offers into a queue with 64 input slots, a dedicated FIFO EOF reservation, and one coalesced resize slot. | +| Launcher | The control monitor uses the same 64-input/EOF/resize queue shape. `TerminalWriter` preserves at most 64 chunk boundaries and 256 KiB on an `O_NONBLOCK` primary. | + +Under valid credit accounting, none of the V2 queues can saturate. Saturation is +therefore an invariant violation that terminates the session loudly; V2 never +waits in a shared reader and never discards a chunk. The V1 operation alone keeps +the old bounded waits and explicit drop diagnostics for bulk input chunks; EOF +still uses its reservation so a legacy session cannot delay cancellation. + +Guest output and host keystrokes are deliberately selected *without* bias +against each other: a chatty workload must not starve typing, and a long paste +must not starve the screen. + +The host's guest-facing writer and the guest's broker-facing writer each live on +their own task. Their reader loops continue draining output and credit events +while input is queued, avoiding the cycle where both peers stop reading while +blocked writing. + +End of file is the one input message that may not be dropped, at any layer. It +is one-shot and state-changing on all three sides — the host stops reading +stdin, the orchestrator closes the terminal, and the guest refuses further input +— so a silent drop leaves the workload waiting forever for a `VEOF` byte that +can no longer be produced. EOF consumes no credit and every input queue reserves +capacity for it. Where EOF has its own transport lane, the writer drains every +preceding input frame before sending it. The launcher then appends the configured +`VEOF` byte behind its backlog, so EOF cannot overtake input and cannot be refused +at zero credit. + +Resizes consume no credit. They are `ioctl`s once they reach the launcher, so +they can overtake bytes already waiting in the PTY backlog; `SIGWINCH` is out of +band anyway. Forwarding queues retain only the latest pending resize, preventing +resize storms from consuming input or EOF capacity. + +The pty primary is opened `O_NONBLOCK`, which is what keeps the backlog in user +space where it can be bounded and where later commands can overtake it. +`n_tty_write` on a blocking descriptor does not return short counts: it sleeps +until every byte fits, so polling for writability first would bound nothing +(`POLLOUT` only promises one byte of room). Since `O_NONBLOCK` is file-status state shared by every +descriptor for the same open file, and a pty primary cannot be reopened to get +an independent file description, the output pump is `poll`-driven too. +After cleanup, terminal input stops immediately, but terminal readers retain a +separate shutdown state and keep polling through the bounded drain window. This +preserves bytes that become readable at process exit without making reader joins +depend on a delayed PTY hangup. + +## End of file + +`Ctrl-D` typed in raw mode is an ordinary forwarded byte; the workload's own +line discipline interprets it. An explicit `StandardInputEof` — host stdin +closed, for example piped input exhausted — writes the pseudoterminal's +*configured* `VEOF` byte, read through `tcgetattr` rather than hardcoded to +`0x04`, and then refuses further input. It never closes the primary, which would +send `SIGHUP` to the session. + +## Host terminal handling + +The CLI requires that stdin and stdout are both terminals and that `sendbox` is +in the terminal's foreground process group, then enters raw mode with +`tcsetattr(..., Now, ...)`. `Now` rather than `Flush`: bytes already typed ahead +belong to the workload, not to the driver's discard pile. + +Raw mode clears `ISIG`, so `Ctrl-C`, `Ctrl-Z` and `Ctrl-\` reach the workload's +terminal as bytes and the sandboxed program — not `sendbox` — decides what to do +with them. The host-side Ctrl-C handler is therefore disabled for interactive +runs. `SIGTERM`, `SIGHUP` and `SIGQUIT` still unwind through the normal +cancellation path so cleanup runs and the terminal is restored. + +Keystrokes are read by a dedicated thread that waits in `poll` on both the +terminal and a wake pipe, so shutting the run down never depends on the operator +pressing another key, and the reader is joined before the terminal is restored — +a detached reader could otherwise steal a keystroke from the shell that resumes +after `sendbox` exits. + +Restoration is idempotent and runs from both an explicit call and `Drop`, so a +panic still leaves a usable terminal. `SIGKILL` and `abort` remain inherently +non-restorable. + +`TERM` is validated to a bounded ASCII character set and sent with the launch +request. The guest makes it authoritative for the workload, replacing any +configured `TERM`, because a stale value would render for the wrong terminal on +the operator's screen. + +## Qualification + +Live Linux coverage in `crates/sendbox-exec/tests/linux_live.rs`: + +| Test | Property | +|---|---| +| `interactive_launch_gives_the_workload_a_controlling_terminal` | `isatty` on all three descriptors, foreground process group, initial window size | +| `interactive_launch_merges_stderr_by_default` | default mode preserves merged stdout/stderr output | +| `interactive_launch_can_separate_stderr_on_a_resized_tty` | opt-in fd 2 remains a TTY, is tagged stderr, and receives mirrored resizes | +| `interactive_launch_forwards_input_and_window_size_changes` | keystrokes reach the workload; a mid-run resize is observed | +| `interactive_launch_ends_the_workload_when_host_input_ends` | `StandardInputEof` closes the workload's stdin | +| `interactive_launch_survives_simultaneous_input_and_heavy_output` | full-duplex traffic does not deadlock or truncate | +| `interactive_launch_preserves_all_output_written_through_exit` | every exact byte written through clean process exit survives the post-cleanup drain | +| `flow_controlled_terminal_delivers_a_paste_larger_than_the_launcher_window` | a credit-aware paste larger than 256 KiB arrives byte-for-byte | +| `flow_controlled_terminal_cancellation_stays_prompt_when_input_is_blocked` | cancellation remains prompt while a raw-mode workload never reads | +| `interactive_launch_is_rejected_when_the_policy_denies_terminal_syscalls` | admission names the denied syscall | + +Orchestration coverage in `crates/sendbox-agent/tests/agent.rs` asserts that an +interactive plan requires `RuntimeCapability::InteractiveTerminal`, that a +headless plan does not, that the launch carries the terminal size, type, and +stderr mode, and that credit, EOF, and post-EOF input states fail closed. + +### Manual agent smoke test + +CI runs no real agent because it holds no Copilot or Anthropic credentials. +Before releasing a change to this path, run both of the following from a real +terminal and confirm the agent renders, accepts typing, survives a window +resize, and exits cleanly on its own quit command: + +```bash +export COPILOT_GITHUB_TOKEN=... # github.forward_copilot_auth: true +sendbox run --interactive --config .sendbox.yaml --runtime kata \ + --image --bundle --trust-root \ + -- /usr/bin/copilot + +export ANTHROPIC_API_KEY=... +sendbox run --interactive --config .sendbox.yaml --runtime kata \ + --image --bundle --trust-root \ + -- /usr/bin/claude +``` + +## Limitations + +- Linux guests only; the pseudoterminal path lives in the Linux execution + broker. +- Hyperlight cannot host an interactive session. +- stdout and stderr remain merged unless `--separate-stderr` is selected. +- Separate stderr loses strict cross-stream ordering and doubles PTY pair use for + the session. +- `--json` and `--interactive` are mutually exclusive. +- A new host requires a guest bundle that understands + `agent.launch.interactive.v2`; old guests reject the operation rather than + silently falling back to lossy V1 input. diff --git a/vendor/sendbox/docs/architecture/kata-runtime.md b/vendor/sendbox/docs/architecture/kata-runtime.md new file mode 100644 index 0000000..63be3f9 --- /dev/null +++ b/vendor/sendbox/docs/architecture/kata-runtime.md @@ -0,0 +1,82 @@ +# Kata runtime architecture + +`sendbox-runtime-kata` is the production Linux/KVM runtime adapter. +`sendbox-host` composes it with the production broker, authenticated guest +bootstrap, egress, MCP, secrets, credentials, Git policy, audit, snapshots, and +session-security lifecycle. + +## Lifecycle and trust + +1. Host preflight requires Linux, `/dev/kvm`, a root-owned non-writable nerdctl + executable, containerd connectivity, a supported Kata v2 handler, and an + independently supplied trust root. +2. `sendbox-bundle::verify_bundle` validates signature, trust-root ID, host and + guest versions, architecture, release rollback floor, metadata, artifact + digests, modes, owners, and link invariants before image acquisition. +3. The runtime additionally rejects a guest supervisor or exec launcher with an + ELF `PT_INTERP` segment. The verified bytes therefore do not execute through + libraries supplied by the workload image. +4. The workload image must use an immutable `@sha256:` reference. The verified + bundle is bind-mounted read-only at `/opt/sendbox`. +5. `nerdctl create` installs the static trusted supervisor as the container + command. `nerdctl start` starts only that supervisor; it does not launch the + requested workload. + +The bundle verifier proves the mounted artifacts, not the Kata kernel, initrd, +hypervisor, containerd daemon, or workload image signature. Those remain host +operator trust inputs. + +The handler allowlist includes `io.containerd.kata.v2` and the +`kata-qemu`, `kata-clh`, `kata-fc`, `kata-dragonball`, and `kata-qemu-coco` v2 +variants. This preserves explicit Kata hypervisor selection while rejecting +shared-kernel or unrelated handler names. Operators must verify the installed +handler-to-shim/hypervisor mapping; its label alone is not an attestation. + +## VM-crossing control channel + +Kata does not inherit a host file descriptor into the guest. The adapter +therefore advertises `RuntimeExecStdioControlChannel` and uses two restricted +containerd exec operations: + +- a one-shot `inject-bootstrap` process receives the bootstrap and public trust + root over stdin and creates root-owned immutable files inside the guest; +- a persistent `tunnel` process connects to the guest-local supervisor Unix + socket and copies authenticated protocol bytes over its exec stdin/stdout. + +Containerd and the Kata shim carry exec stdio across the VM boundary. The Unix +socket never leaves the guest, no host-global socket is published, and the +runtime lifecycle owns and terminates the exec process. Tunnel stderr is bounded +and is never mixed with protocol stdout. + +## Broker and guest controls + +The supervisor verifies the signed manifest again, prepares root-owned runtime +and replay directories, creates a cgroup v2 broker parent, and starts a verified +`sendbox-guest exec-broker` process as mandatory `ServiceId::Exec`. Readiness is +published only after its owner-only Unix socket is live. + +After services start, the supervisor installs the existing NNP/TSYNC agent +profile. Direct `execve`, `execveat`, `clone3`, and `memfd_create` are denied in +the agent process. The broker alone starts the verified one-shot launcher. The +launcher resolves executable and cwd beneath retained descriptors, places the +child atomically in a cgroup, drops to the non-root project uid/gid, removes +capabilities, applies rlimits and seccomp, streams sequenced output, and performs +bounded cgroup/pidfd cleanup. + +Mandatory broker death revokes readiness and terminates the session. Runtime +workload exec remains rejected with `WorkloadExecRequiresGuestBroker`. + +## Explicit exclusions + +- no shared-kernel runtime handler or silent runtime downgrade; +- no Apple or Hyperlight fallback; +- no claim that hosted GitHub runners boot Kata; +- no global stdout/stderr chronology beyond broker event sequence. + +The live proof must run on a dedicated self-hosted Linux/KVM runner. + +Persistent sessions compose authenticated secret delivery, MCP stdio/HTTP +policy, DNS/SOCKS/HTTP egress, interactive terminals, and optional mandatory +cgroup-subtree BPF observation. `NET_ADMIN` is added only for trusted egress; +`BPF`, `PERFMON`, and `SYS_RESOURCE` are added only when tracing is requested. +The non-root workload launcher still clears all capability sets. diff --git a/vendor/sendbox/docs/architecture/mcp-broker.md b/vendor/sendbox/docs/architecture/mcp-broker.md new file mode 100644 index 0000000..2637fc7 --- /dev/null +++ b/vendor/sendbox/docs/architecture/mcp-broker.md @@ -0,0 +1,154 @@ +# Native MCP boundary + +## Scope + +`crates/sendbox-mcp` provides the shared MCP authorization engine for exact +stdio servers and trusted Streamable HTTP upstreams. The host validates +project-local MCP definitions, signs the exact hierarchical policy into the +boundary plan, and delivers it to authenticated Apple and Kata guests. + +Every configured server has: + +- a stable policy ID; +- one exact transport identity: ordered absolute stdio argv or normalized HTTP + endpoint; +- an independent deny-first tool policy; +- a non-reversible identity fingerprint used by inspection and audit. + +Project aliases and caller-provided IDs never select policy. Unknown, +ambiguous, or changed identities fail closed. + +## Data flow + +```mermaid +flowchart LR + Config[Signed hierarchical MCP policy] --> Resolve[Exact server resolution] + StdioClient[MCP client stdio] --> StdioBroker[Installed stdio broker] + StdioBroker --> Frame[Bounded frame + JSON-RPC validation] + Frame --> Resolve + + HttpClient[MCP client HTTP] --> Route[127.0.0.1:15082/mcp/server-id] + Route --> Gateway[Trusted Streamable HTTP gateway] + Gateway --> Resolve + + Resolve --> Tools[Shared deny-first tool evaluator] + Tools --> List[tools/list filtering] + Tools --> Call[tools/call check] + List --> Audit[Mandatory redacted audit] + Call --> Audit + Audit --> StdioUpstream[Exact stdio child] + Audit --> HttpUpstream[Exact marked HTTP upstream] +``` + +The shared evaluator validates method/tool shape, applies deny precedence, +filters every `tools/list` page, and checks every `tools/call` at forwarding +time. Audit persistence occurs before an allowed, denied, or dropped action +takes effect; audit failure denies and terminates the affected path. + +## Stdio launch contract + +The guest installs a root-owned `sendbox-guest` broker at +`/run/sendbox-boundary/mcp-broker` and policy material below +`/run/sendbox-boundary`. Project configuration must invoke that broker, then +`--`, then one exact command from +`policy.boundaries.tool_calls.servers`. + +The broker derives the server policy from exact executable and ordered +arguments. It does not accept a policy ID from the project. The launcher: + +- executes the absolute binary directly without a shell; +- rejects shell and package-runner executables; +- clears inherited environment, then applies only signed fixed values and + approved secret names; +- uses the signed working directory; +- pipes protocol stdin/stdout and bounds stderr; +- kills and reaps the child on malformed traffic, saturation, I/O failure, + cancellation, or premature exit. + +`FrameDecoder` supports newline, `Content-Length`, and first-frame automatic +detection. Automatic mode locks after the first frame. Client and server +request IDs are tracked independently; unmatched responses are terminal. + +## Streamable HTTP gateway + +Remote project definitions never contain an upstream URL or credentials. They +select only the deterministic loopback route: + +```text +http://127.0.0.1:15082/mcp/ +``` + +The route ID is untrusted input and must be one canonical path segment exactly +matching a configured HTTP server. Encoded separators, traversal, case drift, +prefixes, queries, fragments, and trailing slashes do not select policy. + +The gateway is a mandatory trusted guest service started before workload +execution. It runs in the egress broker cgroup, resolves through a separate +marked resolver, classifies every returned address, and dials only an exact +validated address with `SO_MARK`. It never populates the agent-facing +DNS/CONNECT authorization cache. + +HTTPS is the default. The gateway verifies certificate chains, validity, +hostname, and SNI with system roots plus configured PEM roots. There is no +verification-disable switch. Plaintext is accepted only for an explicitly +enabled loopback development endpoint. Metadata addresses are always denied. + +Redirects are disabled by default. When enabled, each target must be an exact +normalized allowlisted URL and is re-resolved and revalidated. The gateway +strips hop-by-hop headers, cookies, compression, and unapproved protocol +headers. Bearer credentials come from the signed gateway-only secret partition +and are injected only into the selected upstream request. + +### Protocol modes + +- `streamable_http` is the modern POST-only mode. It accepts JSON or + request-scoped SSE responses and rejects sessions, GET, DELETE, reconnect + event IDs, upgrades, and server-initiated requests. +- `streamable_http_2025` is an explicit compatibility mode with bounded issued + sessions, GET/SSE, DELETE, server-initiated requests, and validated + `Last-Event-ID`. Session and event IDs are bound to one server and gateway + instance. +- Legacy 2024 HTTP+SSE is not implemented. + +Request/response bodies, SSE events, concurrent work, sessions, redirects, and +idle/connect/request time are bounded by signed policy. Downstream disconnect +cancels upstream work; transport or parser failure has no direct fallback. + +## Egress bypass protection + +Any remote MCP server forces authenticated egress enforcement. The signed +egress policy reserves primary and redirect origins from the normal CONNECT +broker and disables direct-IP CONNECT while remote MCP is active. nftables +admits agent traffic only to the exact loopback DNS, CONNECT, and MCP gateway +ports. Only marked broker-cgroup traffic may leave the guest. + +TLS uprobes and BPF MCP observations remain observation-only. They do not +authorize remote traffic and are not promoted into a plaintext policy +mechanism. + +## Audit and observation + +Stdio and HTTP decisions use one versioned audit schema. Records include server +ID, transport, fingerprint, normalized endpoint when applicable, hashed session +ID, method/tool, outcome, rule/reason, status, byte counts, and timing. They +exclude command arguments, tool arguments, payloads, environment values, and +credentials. + +The guest creates the audit file and Unix submission socket with bounded +connections and reads. Workload-mediated stdio brokers submit structured +events; the trusted HTTP gateway uses the same sink. Failure to submit or append +is fatal to authorization. + +Optional `McpObservationEvent` capture remains available for brokered stdio +traffic. Payload capture and BPF observations are diagnostic only. + +## Trust limits + +- Apple and Kata install the authenticated boundary. Hyperlight rejects MCP + composition. +- Exact project validation prevents configuration drift but cannot prevent an + alternate workload client from invoking an otherwise available binary. + Command policy, image minimization, and kernel containment remain defense in + depth. +- The gateway authorizes only traffic that reaches its exact loopback route. + Kernel egress enforcement prevents direct-origin fallback. diff --git a/vendor/sendbox/docs/architecture/native-project-analysis.md b/vendor/sendbox/docs/architecture/native-project-analysis.md new file mode 100644 index 0000000..b8f475a --- /dev/null +++ b/vendor/sendbox/docs/architecture/native-project-analysis.md @@ -0,0 +1,119 @@ +# Native project analysis + +`sendbox-project` is the deterministic Rust implementation of project detection +and devcontainer generation. It does not start project processes, evaluate +manifests, run package scripts, or require Node.js or Copilot. + +## Scanning + +The scanner traverses entries in lexical order and never follows symbolic links. +Regular files are opened only after metadata checks, and Unix file identities are +checked again after opening to detect symlink or rename races. The default limits +are: + +| Limit | Default | +|---|---:| +| Directory depth | 12 | +| Files visited | 4,096 | +| Manifest bytes read | 8 MiB | +| Bytes per manifest | 1 MiB | + +`sendbox analyze` exposes each limit as a flag. Limit hits, symlinks, +permission failures, files changed during scanning, and malformed manifests are +reported in `scan.skipped` or `scan.errors`; they are not converted into a +success-shaped fallback. + +The analyzer safely parses JSON, TOML, XML, and bounded static text for the +languages and tools supported by the pre-rewrite analysis schema: Node.js and +TypeScript, Python, Rust, Go, Java and Kotlin, Ruby, C and C++, .NET, PHP, +Elixir, and Swift. `Package.swift`, Gradle files, Gemfiles, and `mix.exs` are +inspected as text only and are never executed. + +## Analysis compatibility + +The native `ProjectAnalysis` keeps the bridge field names and meanings: + +- `language`, `framework`, `packageManager`, `buildSystem`, `runtimeVersion` +- `dependencies`, `devDependencies` +- `hasDockerfile`, `hasDevContainer`, `detectedFiles` +- `suggestedImage`, `suggestedFeatures`, `suggestedExtensions` + +Intentional native differences: + +- scanning is recursive and bounded instead of unbounded root-only existence + checks; +- dependencies and development dependencies are sorted and deduplicated; +- native parsing covers additional structured dependency data in `pyproject.toml`, + `pom.xml`, Composer files, and .NET projects; +- `languages` reports all detected project languages; +- `scan` reports limits, skipped entries, and errors explicitly; +- `refinement.status` is always present and is `not_requested`, `applied`, or + `failed`. + +Checked-in fixtures lock the compatibility field names and representative +native output without making live model calls. + +## Optional refinement + +`RefinementProvider` is separate from deterministic analysis. A provider may +return changes to image, features, extensions, framework, or runtime version. +Native analysis remains valid without a provider, and provider failures are +returned as errors while the analysis records that refinement failed. No Node or +Copilot implementation is required by the Rust crate. + +## Devcontainer generation + +Generation starts with the compatibility image, features, extensions, +settings, ports, remote user, and post-create command. Merge precedence is: + +1. generated native defaults; +2. an existing `.devcontainer/devcontainer.json`; +3. typed Rust or CLI overrides. + +Objects are merged recursively. Features, settings, and `containerEnv` merge by +key. Extensions and forwarded ports are sorted and deduplicated. Unknown +devcontainer properties are preserved. + +Existing files are parsed as JSONC with string-aware line comments, block +comments, and trailing commas. Rewriting produces deterministic JSON, so comments +from the input are intentionally not preserved; JSON output reports +`commentsPreserved: false`. + +Output must remain beneath the canonical project directory. Existing output +symlinks are rejected. The parent directory is created with private permissions +on Unix, and a mode `0600` temporary file is flushed, synchronized, and atomically +renamed into place. + +## CLI + +```bash +# Human-readable summary +sendbox analyze --project . + +# Complete deterministic JSON +sendbox analyze --project . --json + +# Generate or merge .devcontainer/devcontainer.json +sendbox devcontainer generate --project . --json + +# Apply typed overrides +sendbox devcontainer generate \ + --project . \ + --image mcr.microsoft.com/devcontainers/rust:1-bookworm \ + --feature 'ghcr.io/devcontainers/features/github-cli:1={}' \ + --extension rust-lang.rust-analyzer \ + --container-env RUST_BACKTRACE=1 \ + --json +``` + +Automation exit codes are scoped to these commands: + +| Code | Meaning | +|---:|---| +| 0 | Analysis or generation completed | +| 2 | CLI usage error, or existing `policy validate` validation failure | +| 3 | Project root or analysis failure | +| 4 | Devcontainer parse, merge, or output failure | + +Project analysis and devcontainer generation are fully native and require no +Node.js process or external refinement service. diff --git a/vendor/sendbox/docs/architecture/package-registry-proxy.md b/vendor/sendbox/docs/architecture/package-registry-proxy.md new file mode 100644 index 0000000..ff29d51 --- /dev/null +++ b/vendor/sendbox/docs/architecture/package-registry-proxy.md @@ -0,0 +1,139 @@ +# Package registry proxy architecture + +## Purpose + +The package registry proxy is a mandatory pre-delivery control for configured +npm registries. It prevents the untrusted workload from receiving package +artifact bytes until a trusted service has verified identity and integrity, +inspected the archive without execution, evaluated package policy, and recorded +a machine-readable verdict. + +The implementation is split across existing trust boundaries: + +- `sendbox-policy` owns strict package policy, finding actions, exceptions, and + resource limits. +- `sendbox-registry` owns adapter contracts, npm behavior, verification, + inspection, deterministic verdicts, cache records, and reports. +- `sendbox-egress` owns the three-cgroup network topology and kernel rules. +- `sendbox-host` resolves isolated registry credentials, mounts private cache + state, revalidates reports, and persists audit evidence. +- `sendbox-agent`, `sendbox-protocol`, and `sendbox-guest` own authenticated + bootstrap, service readiness, launch ordering, and terminal report retrieval. + +## Process and network topology + +```text +untrusted workload cgroup + |-- HTTP 127.0.0.1:14873 ----------------------+ + |-- SOCKS 127.0.0.1:15080 --> public gateway --+--> policy-approved network + `-- DNS 127.0.0.1:15053 --> DNS gateway -----+ + +registry proxy cgroup + `-- SOCKS 127.0.0.1:15081 --> trusted gateway ----> configured npm upstream + +broker cgroup + `-- only marked external sockets are accepted by nftables +``` + +The workload can reach the public SOCKS/DNS listeners and npm proxy, but not +the registry-only SOCKS listener. The registry proxy can reach only the trusted +loopback SOCKS listener, not the public listener or any external destination. +Only gateway processes enter the broker cgroup and set the fixed `SO_MARK`; +the registry proxy runs as UID/GID 65532, receives no mark capability, clears +capabilities, and applies a bounded seccomp/resource profile. + +When package analysis is enabled, the public gateway uses an effective network +policy with the npm upstream denied. The trusted registry gateway retains the +original policy and is reachable only from the registry cgroup. A compromised +workload therefore cannot bypass the proxy with an npm CLI override or direct +tarball URL, and a compromised proxy cannot dial the network without the +trusted gateway. + +The egress instance identifier remains at most 24 lowercase +`[a-z0-9_]` characters. The nftables table is `sbxeg_`, keeping it +within the kernel's 31-character table-name limit. + +## Startup and teardown + +1. The host validates that package policy has exactly one npm registry, that + the runtime supports mandatory egress services, and that registry credential + references do not overlap workload secrets. +2. The host creates or validates the private package cache and includes package + policy, ports, paths, proxy identity, and zeroizing credentials in the + encrypted authenticated bootstrap. +3. The guest starts cgroup/nft enforcement before the workload, then starts the + public gateway, trusted registry gateway, and isolated registry proxy. +4. Readiness requires every mandatory service. Any missing listener, invalid + policy, credential mismatch, privilege-drop failure, or report path failure + aborts launch. +5. npm environment variables are fixed to the local proxy and script execution + is disabled before the exact workload argv starts. +6. After the terminal response, the agent fetches the package report once, + then performs graceful close and teardown. +7. The host validates and persists the report before marking the security + session complete. + +Early exit of a mandatory process is fatal. Cleanup removes nftables state, +cgroups, runtime credentials, sockets, and rejected quarantine files. + +## Request path + +Packument requests are fetched through the trusted SOCKS gateway with bounded +metadata size and timeout. The npm adapter validates the response and replaces +each `dist.tarball` with an opaque proxy route. The route maps internally to an +artifact descriptor bound to the resolved package name, version, upstream URL, +integrity claims, signatures, provenance references, and metadata revision. + +An artifact request acquires a per-route filesystem lock. A valid exact cache +entry is returned immediately. Otherwise the proxy: + +1. downloads to a private quarantine file; +2. computes the content digest and verifies npm integrity claims; +3. fetches and verifies bounded trust metadata and advertised evidence; +4. normalizes `package.json`, enumerates gzip/tar entries, and scans risks; +5. evaluates normalized findings against canonical package policy; +6. atomically writes the verdict record; and +7. promotes only allowed bytes to the approved content-addressed store. + +The cache key is the ecosystem, artifact digest, scanner version, canonical +policy digest, and trust-metadata digest. This makes cache invalidation +implicit and reproducible. Filesystem locks allow concurrent requests and +separate sessions to share one completed analysis without trusting a partial +record. + +## Authenticated report lifecycle + +The registry proxy updates a bounded owner-only report as verdicts complete. +The report is not streamed through workload output. + +`package.report` uses authenticated request ID `2` and schema version `1`. It is +legal only after the launch request's terminal response and before graceful +close, and it can succeed only once. The request carries the maximum accepted +byte count. The response carries the exact JSON string and a +`sha256:` digest. + +The guest reads the report descriptor-relatively without following symlinks and +requires the expected owner, group, mode `0600`, regular-file type, and link +count. The agent verifies the transport digest. The host then independently +checks the byte limit, digest, strict schema, summary counts, canonical JSON, +session ID, and canonical package-policy digest before atomically persisting +the report under host session state. + +This terminal-only retrieval keeps verdict evidence correlated with the +authenticated run while avoiding report races during package installation. + +## Adapter boundary + +`RegistryAdapter` is capability-oriented rather than npm-shaped. It composes +`UpstreamClient` for bounded, credential-aware retrieval and +`PackageProvenanceVerifier` for ecosystem evidence. It covers identity/version +resolution, metadata rewriting, artifact retrieval, trust metadata, integrity +and provenance verification, manifest normalization, archive/layer +enumeration, and ecosystem risk inspection. + +The shared cache, policy evaluator, and report model consume only normalized +identities, evidence, entries, manifests, and findings. PyPI, Cargo, Go +modules, Maven, and OCI adapters can therefore implement different metadata +and artifact models without changing the core decision path. OCI declares +layered artifacts; archive-oriented ecosystems enumerate their native package +containers. The npm adapter is currently the only runtime implementation. diff --git a/vendor/sendbox/docs/architecture/runtime-core.md b/vendor/sendbox/docs/architecture/runtime-core.md new file mode 100644 index 0000000..fb7639f --- /dev/null +++ b/vendor/sendbox/docs/architecture/runtime-core.md @@ -0,0 +1,179 @@ +# Runtime Core Contract + +`sendbox-runtime` defines the behavior shared by the production Apple, Kata, and +Hyperlight adapters. Provider-specific launch code remains in dedicated crates; +`sendbox-host` composes those adapters with guest services, egress, execution, +credentials, MCP, project analysis, and security stores. + +`sendbox-config::RuntimeProvider` is the configured provider **kind**. The +`sendbox_runtime::RuntimeProvider` trait is the object-safe asynchronous behavior +contract implemented by an adapter. They intentionally have the same domain term +but no type dependency. + +## Provider contract and concurrency + +The provider lifecycle is: + +1. `initialize` prepares host-side provider state. +2. `preflight` validates required capabilities before resource creation. +3. `create` creates a stopped container or VM. +4. `start` starts its supervised workload. +5. `provision_control_channel` creates a lifecycle-owned host/guest endpoint. +6. `status`, bootstrap/control `exec`, and `attach` interact with it. +7. `signal` and `stop` terminate work. +8. `cleanup` compensates all resources. + +Every asynchronous method returns an explicit `Send` boxed future and receives an +explicit `CancellationToken`. Providers are `Send + Sync`. Calls for different +containers may run concurrently. A provider must serialize or reject mutating +calls for the same container, while status, capability reporting, and output +consumption may run concurrently. A lifecycle update must validate and commit in +one critical section; duplicate transitions are errors rather than implicit +successes. + +The foundation state machine permits only these transitions: + +- `New` to `Initialized`, `Cleaning`, or `Failed` +- `Initialized` to `Created`, `Cleaning`, or `Failed` +- `Created` to `Running`, `Stopped`, `Cleaning`, or `Failed` +- `Running` to `Stopping`, `Stopped`, or `Failed` +- `Stopping` to `Stopped` or `Failed` +- `Stopped` to `Cleaning`, `Cleaned`, or `Failed` +- `Cleaning` to `Cleaned` or `Failed` +- `Failed` to `Cleaning` or `Cleaned` +- `Cleaned` is terminal + +`RuntimeId` and `ContainerId` are validated, bounded identifiers rather than +unstructured strings. + +## Capability layering + +Runtime capabilities map explicitly to the authenticated protocol: + +| Runtime capability | Protocol capability ID | +|---|---:| +| Lifecycle | 1 | +| Exec | 2 | +| Streamed I/O | 3 | +| Signals | 4 | +| Mounts | 5 | +| Network | 6 | +| MCP | 7 | +| Audit | 8 | +| Health | 9 | + +`TransportProvisioning`, `BrokeredExec`, and the vsock, published Unix socket, +inherited stdio, and inherited file-descriptor transport capabilities are +runtime-local. They are deliberately filtered out of +`sendbox_protocol::CapabilitySet`. `sendbox-runtime` depends on +`sendbox-protocol` for this mapping; the protocol crate has no runtime dependency, +so the layering is acyclic. + +## Host/guest control channel + +`ControlChannelRequest` binds one session and container to a typed endpoint kind, +runtime lifecycle ownership, a bounded readiness timeout, and redacted bootstrap +material delivery. Bootstrap material may use a pre-opened descriptor above +stderr or an adapter-owned injection target; argv and environment delivery are +not part of the contract. + +`ProvisionedControlChannel` is a single-accept object-safe async handle. It +returns the stream through the runtime lifecycle rather than a global path or +registry, and explicit cleanup is idempotent. The contract models vsock, +published Unix sockets, inherited stdio, inherited descriptors, and explicit +unavailability. It does not define Apple, Kata, Hyperlight, or other vendor +mappings. + +The readiness deadline covers channel acceptance and authenticated protocol +readiness. Expiry is distinct from cancellation. Protocol frame limits provide +bounded allocation and I/O after acceptance. + +`RuntimeProvider::exec` is restricted to trusted bootstrap and control work. +When `BrokeredExec` is required, agent workload launch must use the authenticated +guest channel. A runtime adapter must not reinterpret workload execution as +host-side runtime exec. + +An unavailable platform implementation uses `UnavailableRuntimeProvider`. It +advertises no capabilities and returns a structured unavailable error rather +than selecting a fallback. + +## Cancellation + +Cancellation is an explicit atomic state plus notification. It is not represented +by a watch or sender channel. Dropping one token, or every token, does not cancel +anything and cannot be confused with channel closure. Only `cancel()` changes the +state. + +Dropping an operation future is not success. Adapters remain responsible for +registering compensation before a partial resource becomes externally visible. + +## Host process execution + +The process runner never invokes a shell. A command selects either an absolute +program path or a named program resolved through an injected `ProgramResolver`. +The runner rejects a relative resolver result. Arguments and environment values +carry explicit sensitive flags used by diagnostics. The environment is cleared +by default, and invalid NULs, environment keys, duplicate keys, program forms, +and missing or non-directory working directories fail before spawn. + +Stdout and stderr have independent drain tasks. Each task writes directly to a +bounded capture buffer and performs a nonblocking publish while holding only a +short ordering lock. There is no bounded intermediate collector that can stall +pipe reads. Captures report total and truncated bytes. + +Unix children start in a new process group using the standard library +`process_group(0)` configuration. Signals use the safe `nix::killpg` API. +Cancellation and timeout send `SIGTERM`, wait the configured grace period, then +send `SIGKILL` and reap. Once the leader is reaped, the runner sends `SIGKILL` +to the group again, so a descendant that missed `SIGTERM` (for example one +forked while the signal was in flight, which macOS can leave alive) cannot keep +the output pipes open and stall the drain. `ESRCH` and macOS's `EPERM` for a +group with only exiting members mean nothing is left to kill. +`RunningProcess::drop` directly sends `SIGKILL` to the +group synchronously as a last-resort fallback; it does not depend on an async +command channel. + +A process can escape this containment by successfully calling `setsid` or +`setpgid`. Process groups are lifecycle hygiene, not a sandbox boundary. Later +guest and kernel enforcement must prevent or contain escape where policy +requires it. Non-Unix code paths avoid the Unix dependency and return an explicit +unsupported signal error. Cancellation and timeout can only kill the direct +child there. Those paths were not platform-qualified by this change, so no +descendant or graceful-signal guarantee is claimed. + +## Output ordering and loss + +Every data event identifies stdout or stderr and contains a monotonic global +sequence plus a monotonic per-stream sequence. Publishing to the bounded client +channel uses `try_send`; a slow or dropped client can never block either pipe +drain. + +Dropped events are not hidden. The next delivered data event carries +`dropped_before` metadata with event, byte, sequence-range, and per-stream counts. +If no later event can be delivered, the subscription emits a final loss event +after queued data. Process outcomes also retain aggregate delivered and dropped +statistics. Channel closure means end-of-stream, while cancellation returns a +separate cancellation error. + +## Cleanup transaction + +A cleanup transaction is a reverse-order compensation stack: + +- every incomplete step is attempted in a pass, even after failures; +- all failures are returned with their step names; +- successful steps are permanently marked complete; +- failed steps remain pending and are retried by later calls; +- a fully completed transaction is idempotent and performs no further work; +- each step must treat an already-absent resource as success. + +`OperationFailure` preserves the primary runtime error as its error source and +attaches the structured cleanup report. Cleanup failures therefore never replace +or flatten the initiating failure. + +## Clock boundary + +Process start, finish, and elapsed metadata use the injected `Clock`. +`SystemClock` is monotonic, while `sendbox-testkit::ManualClock` makes metadata +tests deterministic. OS timeout selection necessarily uses Tokio time; advancing +`ManualClock` does not advance or trigger a process timeout, and the API makes no +claim that it does. diff --git a/vendor/sendbox/docs/architecture/rust-cli-parity.md b/vendor/sendbox/docs/architecture/rust-cli-parity.md new file mode 100644 index 0000000..ddc4551 --- /dev/null +++ b/vendor/sendbox/docs/architecture/rust-cli-parity.md @@ -0,0 +1,54 @@ +# Rust CLI + +Cargo emits the production binary as `sendbox`. Its clap command name, help, +JSON contracts, generated completions, install paths, and release artifacts use +the same name. + +## Implemented command groups + +| Surface | Rust behavior | +|---|---| +| `init` | Resolves an existing readable/searchable project directory, selects a policy preset and runtime, validates deterministic v1 YAML, creates `.sendbox.yaml` atomically with mode `0600`, and never overwrites an existing file. | +| `policy show` | Shows the default or configured policy as stable text or deterministic JSON. Configuration input uses strict decoding and policy-only validation. | +| `policy validate` | Retains full sandbox validation, deterministic JSON, diagnostics, and exit `2` for invalid configuration. | +| `completions print` | Generates bash, zsh, or fish output directly from the clap command tree. | +| `completions install` | Detects `SHELL` or accepts `--shell`, falls back to zsh when detection is unavailable, writes to stable per-shell paths with atomic replacement, mode `0644`, and directory mode `0755`. It never launches a shell or respawns the CLI. | +| `analyze` / `devcontainer generate` | Retains the existing native project-analysis subset. | +| `secrets` | Adds, lists, and removes versioned secrets through Keychain on macOS or the descriptor-safe protected file store on Linux without printing values. | +| `mcp parse` / `mcp report` | Parses native or legacy observations with optional redaction and deterministic JSON. It does not generate executable inspection scripts. | +| `package status` / `package report` | Securely loads the latest or selected session's owner-only package report, rejects symlinks, malformed/cross-session data, bad modes/ownership, and oversize files, then prints a verdict summary or the complete report. | +| `boundary inspect` | Emits the structured native boundary declaration without scripts or secret values. | +| `run` | Resolves and verifies a signed immutable boundary plan, selects Apple/Kata/Hyperlight without fallback, and dispatches either an authenticated persistent guest session or the explicit authenticated Hyperlight one-shot path. | + +Exit `2` is reserved for invalid input/configuration, `3` for project analysis +failures, and `4` for output failures or no-overwrite refusals. Text failures go +to stderr. Commands with `--json` emit one deterministic failure object to +stdout and leave stderr empty. + +## Configuration persistence + +`sendbox-config` accepts current v1 documents with no version key and migration +inputs carrying `schema_version: 1`. Future versions and unknown fields are +rejected. Canonical YAML uses declaration-order snake_case keys, omits absent +optional values, preserves explicit empty collections, and includes documented +defaults. Migration reports distinguish schema changes from formatting +canonicalization. + +Writes validate first, open every destination-directory component without +following symlinks, create a temporary file through the opened directory, set +the final mode, sync content, and atomically create or replace the destination. +`init` uses a no-replace rename so a concurrent creator wins without being +modified; explicit migration callers may request replacement. Descriptor-based +traversal requires read and search permission on existing destination +directories. Completion setup applies `0755` only to directories it creates and +preserves stricter modes on directories that already exist. + +## Runtime contract + +`run` requires an absolute guest command plus a verified bundle and trust root. +Persistent Apple and Kata execution waits for authenticated guest readiness and +the required capability set before resolving workload secrets or launching the +command. Hyperlight is explicit-only and rejects every feature its one-shot +boundary cannot enforce. Text errors use stderr; `--json` emits one error or +result object to stdout. Package-enabled persistent results include report path, +digest, proxy state, record count, and allow/deny/quarantine totals. diff --git a/vendor/sendbox/docs/architecture/safe-outputs.md b/vendor/sendbox/docs/architecture/safe-outputs.md new file mode 100644 index 0000000..0b5a175 --- /dev/null +++ b/vendor/sendbox/docs/architecture/safe-outputs.md @@ -0,0 +1,199 @@ +# Native Safe Outputs gateway + +SendBox implements a partial-conformance +[GitHub Agentic Workflows Safe Outputs](https://github.github.com/gh-aw/specs/safe-outputs-specification/) +gateway for Apple and Kata sessions. The agent receives no GitHub write +credential. It can only declare bounded operations through a trusted local MCP +server. + +## Supported subset + +GitHub write tools: + +- `create_issue` +- `add_comment` +- `create_pull_request` +- `add_labels` +- `remove_labels` + +System reporting tools: + +- `noop` +- `missing_tool` +- `missing_data` +- `report_incomplete` + +Asset and artifact upload tools are intentionally unsupported because they +would require a separately constrained storage write primitive. + +## Configuration + +Safe Outputs is disabled and staged by default. A minimal issue-only +configuration is: + +```yaml +policy: + boundaries: + enabled: true + tool_calls: + transport: stdio + default_action: deny + allowlist: [] + denylist: [] + max_frame_bytes: 1048576 + server_command_patterns: [] + allowed_server_commands: [] + +github: + forward_auth: false + forward_copilot_auth: true + allow_private_repository_access: false + branch_protection: + enabled: true + protected_branches: [main, master] + allowed_branch_patterns: ["copilot/*"] + safe_outputs: + enabled: true + mode: staged + write_token_env: SENDBOX_SAFE_OUTPUTS_GITHUB_TOKEN + allowed_repositories: [owner/repository] + allowed_domains: [github.com] + allowed_mentions: [] + max_artifact_bytes: 131072 + create_issue: + enabled: true + max: 1 + title_prefix: "[sendbox] " + labels: [triage] + assignees: [] +``` + +The host compiler auto-admits only the installed Safe Outputs command and the +enabled tool names. An explicit denylist match still fails closed. + +Configure the MCP client to launch the gateway through the native broker: + +```json +{ + "mcpServers": { + "safe-outputs": { + "type": "stdio", + "command": "/run/sendbox-boundary/mcp-broker", + "args": ["--", "/run/sendbox-boundary/safe-outputs-mcp"] + } + } +} +``` + +For `mode: apply`, provide a fine-grained token through the host process +environment named by `write_token_env`. Do not place the value in YAML, project +MCP configuration, a forwarded SendBox secret, or guest environment. When +Copilot authentication is forwarded, `write_token_env` also cannot reuse either +host Copilot token variable. + +## Trust boundary and lifecycle + +1. The host compiles the complete policy into authenticated bootstrap and the + signed boundary feature admissions. +2. The guest supervisor installs the exact MCP bridge and starts a mandatory, + health-reported root-owned recorder under + `/run/sendbox-safe-outputs/`. Gateway mode verifies that the running + executable is the root-owned, non-writable installed path rather than + trusting `argv[0]`. +3. The workload bridge can reach only a `0660` writer socket. The recorder + authenticates the peer UID and GID, performs framing and schema validation, + sanitizes content, enforces targets and limits, and atomically replaces a + root-owned `0600` NDJSON artifact. +4. Each accepted record binds the session, boundary-plan digest, policy digest, + sequence, timestamp, idempotency key, previous hash, operation, and record + hash. +5. After the execution broker proves descendant cleanup, the guest fences the + writer, drains complete in-flight frames, and creates an HKDF/HMAC seal over + the artifact hash, chain head, counts, and provenance before returning the + terminal result. +6. The host requests the artifact exactly once over the authenticated control + channel. Missing capability negotiation, malformed collection, duplicate + collection, foreign provenance, or an invalid seal fails the run. +7. The host tears down the guest, control channel, runtime, and secret resolver. + It then independently validates and sanitizes the full batch before reading + the dedicated write-token environment variable. + +The supervisor uses an in-process typed control channel, so untrusted bytes +never reach sealing or collection commands. + +## Sanitization and authorization + +The recorder and host processor both enforce: + +- exact `owner/repository` targets; +- per-tool all-or-nothing count limits; +- NFKC normalization and bounded text; +- credential-pattern redaction; +- URL allowlisting; +- instruction and mention neutralization; +- HTML angle escaping; +- allowed labels, assignees, base branches, and pull-request paths; +- deterministic idempotency keys and duplicate rejection. + +System reporting operations never enter the token-bearing GitHub writer. + +## Staged and apply modes + +`staged` writes no GitHub data and does not resolve a token. It persists a +deterministic preview at: + +```text +/sessions//safe-outputs-report.json +``` + +The report renders each sanitized operation and binds the session, +boundary-plan digest, policy digest, artifact hash, chain head, operation +sequence, tool, idempotency key, status, and any result URL. The signed session +audit records separate verified and processed events with the same batch +provenance. + +`apply` persists a private idempotency ledger before each external write: + +```text +/sessions//safe-outputs-ledger.json +``` + +Create operations carry a hidden provenance marker. A retry reconciles pending +issues, comments, and pull requests against that marker before writing again. +Label APIs are retried through their idempotent forms. GitHub applies a +preflight-validated batch sequentially, so a remote failure can leave earlier +operations applied; the ledger makes that partial state explicit and +recoverable. + +## Pull-request transport + +Pull requests never mutate the user's index or current ref. The host: + +- rejects protected, disallowed, non-UTF-8, non-normalized, symlinked-parent, + symlink, directory, conflict, file-count, and patch-size cases before any + GitHub API write; +- snapshots source hashes and rechecks them before copying; +- fetches the configured base into a private temporary repository and requires + it to match the commit used for local preflight; +- disables system/global Git configuration, credential helpers, prompts, + hooks, fsmonitor, external diff/text conversion, redirects, proxies, and + commit signing; +- creates a deterministic commit on `safe-outputs/-`; +- passes the token only through a private askpass environment; +- pushes one explicit non-force refspec to an HTTPS `github.com` URL; +- verifies an existing retry branch has the expected commit before creating + the pull request. + +Temporary Git state and askpass files are removed after processing. The token +is never placed in argv, URLs, diagnostics, the ledger, the report, or +persistent Git configuration. + +## Limitations + +- Only GitHub.com REST endpoints are supported. +- Apply is sequential after complete local preflight, not transactionally + atomic at GitHub. +- Reconciliation scans the newest 100 matching GitHub objects. +- Pull-request changes must be regular files in the mounted repository; + symlinks and submodule updates are rejected. +- Hyperlight does not support the persistent authenticated gateway. diff --git a/vendor/sendbox/docs/architecture/secrets-and-credential-broker.md b/vendor/sendbox/docs/architecture/secrets-and-credential-broker.md new file mode 100644 index 0000000..9773f48 --- /dev/null +++ b/vendor/sendbox/docs/architecture/secrets-and-credential-broker.md @@ -0,0 +1,225 @@ +# Secrets and Credential Broker + +Status: **pre-1.0 production libraries**. `sendbox-secrets` owns host secret +storage, explicit legacy migration, ephemeral session envelopes, and pure +credential request transformation. `sendbox-credentials` owns the bounded local +listener, certificate-verifying HTTPS forwarding, guarded GitHub repository +authorization, and session-bound agent configuration. Persistent Apple/Kata runs +wire guarded GitHub, Copilot, and Git SSH credentials through authenticated +secret envelopes. Generic explicit-base-URL broker rules remain library-only. + +## Secret values and names + +`SecretValue` owns zeroizing bytes and always redacts `Debug` and `Display`. +Callers must explicitly use `expose_secret()` at the final trusted boundary. +Names are non-empty, NFC-normalized UTF-8 without control characters and are +bounded to 128 bytes. Values are bounded to 64 KiB. + +The `SecretStore` contract has distinct create and update operations plus +retrieve, delete, list, exists, and explicit migration. Not-found, +access-denied, corrupt, insecure-store, duplicate, and size failures remain +distinct. No API exports all plaintext values or generates shell source. + +## macOS Keychain + +The default generic-password service remains `com.sendbox.secrets`, matching +the Swift implementation. Values use a versioned record inside the Keychain; +legacy Swift values remain readable and are rewritten only through `migrate`. +Tests use unique service identifiers and delete their own entries. + +`KeychainMigrationPlan` models service-name and signing-identity changes. A +changed signing identity may trigger the existing Keychain ACL prompt. SendBox +does not weaken ACLs or silently create replacement credentials. Cross-service +migration requires a `MigrationAuthorization` produced after user +confirmation; values move directly between Keychain operations and are never +returned as an export bundle. Final release signing must run the ignored ACL +qualification test in the intended signing environment. + +## Linux protected file store + +The compatibility path remains: + +```text +~/.sendbox/secrets// +``` + +Directories are opened as capabilities and must be owned by the effective user +with mode `0700`. Secret and lock files must be regular, owner-owned `0600` +files. Existing symlinks, wrong types, owners, or modes are rejected; the store +does not chmod attacker-controlled paths. + +All child operations are descriptor-relative. Opens use `O_NOFOLLOW`. +Mutations hold a stable service lock file across validation, write, file +`fsync`, atomic rename, and directory `fsync`. This protects cooperating +SendBox processes on a local filesystem; network filesystems with unreliable +advisory locks are unsupported. Interrupted temporary files are never treated +as secrets. + +Swift Linux raw UTF-8 files remain readable as version 0. The explicit +`migrate` operation captures filesystem timestamps and atomically replaces the +raw value with the versioned record. A record magic prefix beginning with an +invalid UTF-8 byte distinguishes new records from every value the Swift store +could write. A malformed prefixed record is corrupt and never falls back to +plaintext. + +## Session secret envelopes + +`EnvelopeCipher` derives a 256-bit XChaCha20-Poly1305 key from authenticated +bootstrap/protocol material using HKDF-SHA256 and session-specific domain +separation. Each envelope authenticates a canonical CBOR associated-data tuple: + +- protocol domain and version; +- session ID and recipient role; +- secret name and sequence; +- expiration time; +- policy digest. + +Each seal uses a fresh 192-bit operating-system nonce and rejects duplicate +sequence or nonce issuance within the cipher instance. Opening verifies the +expected binding, authentication tag, expiration, and a bounded session replay +guard before returning a zeroizing value. Replay state is intentionally +session-scoped: session bootstrap material and IDs must never be reused after a +process restart. Guest plaintext persistence is not provided by this crate. + +## MCP gateway credential partition + +Remote MCP bearer credentials reuse the host `SecretStore`, but they do not +enter the ordinary workload secret set or environment. Each +`http.authorization.bearer_secret` name is derived from the hierarchical MCP +policy and signed as a separate boundary-plan partition. Configuration rejects +missing, unexpected, duplicate, or overlapping workload/gateway names. + +The host resolves exactly those names before runtime startup. Values are carried +only in the authenticated root-owned bootstrap payload, validated against the +signed MCP policy, moved into zeroizing gateway storage, and injected only as +the configured upstream `Authorization: Bearer` header after route, policy, +destination, and TLS validation. Values are redacted from debug output, audit, +inspection, and errors and are never accepted from project MCP files. + +## Credential broker policy and listener + +Policies require an exact canonical target host, absolute path prefix, explicit +allowed methods, request and response limits, redirect policy, and HTTPS with +TLS verification. Injection supports bearer, validated custom header, query, +and complete path-segment replacement. Userinfo, host suffix tricks, trailing +dots, control characters, duplicate query parameters, invalid header values, +cross-target redirects, and oversized bodies fail closed. + +Transformed URLs, headers, and bodies use redacted wrappers. Audit metadata +contains only method, original path, exact target, injection kind, secret name, +and body size. Bearer injection writes `Bearer `; the Swift +placeholder regression is covered by a unit test. + +Repository credentials including `GITHUB_TOKEN`, `GH_TOKEN`, Git askpass/SSH +forwarding variables, GitHub OAuth/PAT values, and GitHub App private keys are +explicitly denied. They must use the guarded GitHub forwarding subsystem. + +`sendbox-credentials` exposes one explicit HTTP base URL per credential rule. +The listener binds to IPv4 or IPv6 loopback by default. A non-loopback address +must be selected through the explicit bind variant; wildcard and multicast +binds are rejected. + +The listener accepts one origin-form HTTP/1.1 request per connection and then +closes it. It enforces bounded request lines, aggregate headers, header count, +body length, read time, concurrent connections, response headers, response +body, redirects, and shutdown time. Bare line feeds, obsolete folding, +duplicate `Host` or `Content-Length`, `Transfer-Encoding`, absolute-form +targets, pipelined bytes, control characters, and unsupported `CONNECT` +credential injection fail closed. + +The broker constructs the upstream URL itself after the local rule route, +method, host, and path have matched. It strips hop-by-hop and +`Connection`-nominated headers, then calls the `sendbox-secrets` +transformation. Upstream traffic is HTTPS-only on port 443 with hostname and +certificate verification enabled. Automatic redirects and system proxies are +disabled. Each redirect is bounded, re-authorized against the exact host and +path policy, and transformed again before sending. + +DNS is resolved before each hop. Every returned address is classified with the +production egress address classifier, restricted addresses require exact +explicit approval, and the approved addresses are pinned into the HTTPS client +for that hop while the original hostname remains the TLS SNI and certificate +identity. This prevents a second resolver lookup from changing the destination +between authorization and connect. + +### Agent compatibility + +Agents and SDKs must support replacing an API base URL and must append the +original upstream path and query to the returned per-rule endpoint. The local +URL is HTTP because it is a loopback host process; the broker performs the +verified HTTPS connection to the real service. + +The broker is not a generic HTTP proxy. It does not set `HTTP_PROXY` or +`HTTPS_PROXY`, intercept TLS, synthesize certificates, rewrite DNS, or inject +credentials into CONNECT tunnels. Clients that hardcode their service origin or +only support HTTPS proxy tunneling are incompatible until they gain an explicit +base-URL setting. + +### Governed provider relay + +[Governed sessions](governed-sessions.md) connect this broker to compatible +agents for Anthropic and OpenAI without placing the credential in the guest. +The guest supervisor listens on loopback port 15084 and forwards each request +over the authenticated control channel. The host relay +(`sendbox_credentials::relay::RelayEndpoint`) authorizes it against a leased +grant, injects the host-held key, and reuses the pinned transport above with +redirects denied. Unlike the per-connection listener, the relay streams +response bodies, including server-sent events, under guest credit and per +service size, duration, and idle limits. Agents receive only the provider base +URL variable and a fixed placeholder key. + +## Guarded GitHub repository authentication + +`GitHubMetadataClient` separates repository metadata from the production `gh` +adapter. The adapter executes an absolute `gh` path with fixed-shape GraphQL +argv, variables for repository owner/name and cursors, bounded output and time, +no output publication, a cleared environment, and explicit `GH_CONFIG_DIR`, +`HOME`, host, prompt, pager, and update settings. Authentication tokens never +appear in argv or diagnostics. + +Authorization resolves the selected repository owner type and visibility, then +paginates the complete viewer repository set and filters all non-public +repositories. Malformed JSON, command failure, timeout, cancellation, truncated +output, a missing or repeated cursor, or the hard page limit aborts +authorization. The token is requested only after scope authorization succeeds. + +The repository policy preserves the Swift behavior: + +- the selected non-public repository must be accessible; +- a public selected repository cannot use credentials with non-public scope; +- an additional non-public repository requires an organization owner matching + the selected repository and the explicit private-access override; +- user-owned repositories are not treated as an organization; +- cross-organization non-public scope is always denied. + +Copilot authentication is independently gated by +`forward_copilot_auth`. The host resolves the credential from +`COPILOT_GITHUB_TOKEN`, falling back to the legacy `GITHUB_COPILOT_TOKEN` only +when the supported variable is absent; a variable that is present but empty is a +hard error rather than a silent fallback. Repository-scoped credentials +(`GH_TOKEN`, `GITHUB_TOKEN`) are never consulted, so Copilot forwarding stays +independent of `forward_auth`. Whichever host variable supplied the value, the +guest only ever receives `COPILOT_GITHUB_TOKEN`, which is the name current +GitHub Copilot CLI releases read. Errors name the supported variables and never +include a credential value. + +`SessionCredentialConfiguration` returns the broker +listener and per-rule agent endpoints plus zeroizing GitHub/Copilot values for a +specific session. It does not install environment variables or start a runtime. + +Production `sendbox run` resolves the selected repository once, authorizes the +GitHub token before retrieving it, and adds only derived credential names to the +signed boundary plan. Values travel through protocol-v2 authenticated secret +envelopes. The guest Git guard installs fixed askpass and SSH wrappers; caller +askpass, credential helpers, `core.sshCommand`, and SSH configuration overrides +remain rejected. SSH private keys use an owner-only runtime file only while the +trusted SSH child runs and are removed afterward. Hyperlight rejects these +features because it does not provide persistent secret delivery. + +## Remaining qualification + +- Connect generic explicit-base-URL credential rules to compatible agents + outside governed sessions. Governed sessions already broker Anthropic and + OpenAI through the relay. +- Run the ignored Keychain ACL qualification whenever the production signing + identity or Keychain service identity changes. diff --git a/vendor/sendbox/docs/architecture/security-records.md b/vendor/sendbox/docs/architecture/security-records.md new file mode 100644 index 0000000..b5ee206 --- /dev/null +++ b/vendor/sendbox/docs/architecture/security-records.md @@ -0,0 +1,78 @@ +# Security Records Architecture + +`sendbox-security` provides the persistence foundation for audit records, +provenance, and workspace snapshots. `sendbox-host` composes these records +through `sendbox-session-security` around persistent Apple and Kata runs: +trusted inputs are verified, the before-state snapshot is captured, permission +state is anchored, secret envelopes are prepared, completion or failure is +finalized, excluded-path mutations are quarantined or rolled back, and the +final audit head is published. Guest enforcement and credential transport +remain separate authenticated services rather than persistence concerns. + +## Secure filesystem boundary + +All security state is accessed relative to an already trusted root directory. +On macOS and Linux, each path component is opened with descriptor-relative +operations and `O_NOFOLLOW`. Reads and writes validate the final descriptor's type, +owner, device, and size. Atomic replacement writes a mode-restricted temporary file +in the destination directory, syncs it, renames it, and syncs the parent directory. +macOS file commits also request `F_FULLFSYNC`. + +Paths must be relative and contain only normal components. Cleanup failures are +returned with the primary failure instead of being discarded. The current adapter +supports Unix platforms; other platforms return an explicit unsupported-platform +error rather than silently using weaker path operations. + +## Audit format + +Rust audit logs use `sendbox-audit` version 1: + +- Canonical compact JSON header and canonical JSON records separated by newlines. +- Contiguous sequence numbers and one session identifier. +- SHA-256 hash chaining over domain-separated canonical event bytes. +- Bounded actions, subjects, metadata, record count, and persisted file size. +- RFC 6962-style domain separation between Merkle leaves and internal nodes. +- Single-writer file locking and atomic whole-log commits. + +Redaction is export-only and runs after integrity verification. It never changes the +committed event or its hash. Partial writes, malformed records, reordering, replayed +records, and chain corruption are rejected. As with any local append-only file, a +complete valid suffix can only be proven missing when a previously published head or +Merkle root is available externally. + +Swift audit version 1 remains a separate read-only format. Its JSON array, +pipe-delimited hash input, ISO-8601 timestamps, genesis string, and non-domain- +separated padded Merkle tree are reproduced only by the legacy verifier. + +## Provenance format + +Rust detached signatures use `sendbox-provenance` version 1: + +- Ed25519 keys with SHA-256 public-key fingerprints. +- Domain-separated canonical payloads for content, configuration, and artifacts. +- Detached signatures with unique IDs, signing time, optional expiry, and bounded + metadata. +- Multi-signer trust stores with distinct-signer thresholds and required signers. +- Identity validity, expiry, revocation, signature expiry, and replay checks. + +Private key representations are zeroized and their debug output is always redacted. +Trust stores use the secure atomic persistence boundary. Swift version 1 signatures +remain read-only and verify the original raw content bytes; the Rust verifier never +falls back between legacy and version 1 signing constructions. + +## Snapshot format + +Rust snapshots use `sendbox-snapshot` version 1. A canonical manifest references +immutable SHA-256 objects under a sharded object directory. Traversal is relative to +an open workspace descriptor and never follows symbolic links. + +Manifests explicitly record directories, regular files, symbolic links, and +hardlinks. Capture rejects cross-device entries, sparse files, sockets, FIFOs, +devices, unsafe mode bits, invalid paths, and configured exclusions. File metadata +and content are obtained from the same open descriptor. + +Restore verifies every object, populates a fresh sibling staging directory, moves the +current workspace to a backup, commits the staging rename, and rolls back if commit +fails. Pruning holds the store lock and removes only objects unreferenced by retained +manifests. Swift version 1 manifests are read-only; legacy tarballs are never passed +to an external extractor or unpacked into a workspace. diff --git a/vendor/sendbox/docs/architecture/session-security-lifecycle.md b/vendor/sendbox/docs/architecture/session-security-lifecycle.md new file mode 100644 index 0000000..248f6b7 --- /dev/null +++ b/vendor/sendbox/docs/architecture/session-security-lifecycle.md @@ -0,0 +1,105 @@ +# Session security lifecycle + +`sendbox-session-security` is the adapter-neutral coordination layer between +`sendbox-security`, `sendbox-secrets`, and host orchestration. It does not +directly start a runtime or change guest controls; `sendbox-host` injects the +runtime-independent adapters and executes the lifecycle around persistent Apple +and Kata sessions. + +## Lifecycle + +`SecuritySession::prepare` runs the security prerequisites in this order: + +1. Verify policy and configuration bytes against injected trust stores. +2. Capture the before-state snapshot. +3. Create the session audit chain using the canonical `SessionId` hex value. +4. Validate secret references and produce authenticated, session-bound envelopes. +5. Prepare credential rules and notify an injected bounded listener. +6. Initialize the injected permission supervisor and anchor its generation and + state hash in the audit chain. + +Runtime-independent callers can then record audit events through the thread-safe +`AuditRecorder`. Completion and failure finalization capture the after-state, +compute the snapshot diff, record rollback and cleanup outcomes, and publish the +final audit Merkle root and chain head through an injected signing/publication +hook. + +Any failed preparation or finalization stage attempts rollback and cleanup. The +returned error retains the primary, rollback, cleanup, audit, and publication +failures that occurred; failures are not converted into success-shaped results. + +## Permission supervisor + +The version 1 permission supervisor preserves the Swift categories and risk +classification intent while making decisions replay-safe and deterministic: + +- categories: command, network, file write, secret access, and system call; +- one-time, session, and glob-pattern approvals; +- expiry and use limits; +- exact deny-always rules with deny-first precedence; +- prompt budgets, non-interactive denial, and injected approval handlers; +- caller-clock deadline checks without UI or real-time sleeps; +- revocation and bounded decision history. + +The default, strict, and autonomous configurations retain the Swift prompt +budgets, session-grant flags, timeout values, and autonomous wildcard rules. A +zero timeout disables deadline expiry. When session grants are disabled, +`approveForSession` falls back to the Swift one-time behavior. That behavior +records the current approval and creates one exact-action use for the next +matching check. + +`denyAlways` is the intentional redesign exception: Swift only recorded the +denial and would prompt again. Rust persists an exact deny rule, checks it before +positive grants, and requires explicit revocation. This strengthens denial +without broadening permission. + +Canonical JSON state includes the session ID, generation, previous state hash, +current state hash, grants, deny rules, replay set, prompt counters, and history. +Every mutation advances the generation and is emitted through a +`PermissionEventSink`. `AuditPermissionEventSink` records the generation and +state hash in the session audit chain. + +`SharedPermissionSupervisor` serializes only non-interactive checks so use-limited +grant consumption remains atomic without holding a mutex across an approval +handler. Interactive approval remains owned by the orchestration layer. + +The supervisor checkpoint is an external high-water mark. Loading an older +generation, an equivocated state at the same generation, an unlinked next +generation, or a generation jump is rejected. The checkpoint must be stored +outside the supervisor file, normally in the tamper-evident audit publication. + +## Migration + +Migration inspection is bounded and dry-run-only. Readers cover: + +| Source | Verification/report behavior | +|---|---| +| Swift audit entries and Merkle tree | Verifies the legacy hash chain and optional tree | +| Swift snapshot manifest | Validates ordering, paths, hashes, sizes, and permissions | +| Swift provenance trust store | Reports unsigned or zero-threshold policy broadening | +| Swift provenance signature | Validates structure; cryptographic verification still requires caller content and key | +| Secret metadata | Lists record versions without retrieving or rewriting values | +| Swift Codable grants | Observational import reader; no persisted Swift grant store is assumed | + +Conversion proposals require an authorization derived from the exact dry-run +report. Permission-broadening proposals also require a separate explicit +acknowledgement. These APIs never write artifacts, migrate secrets, or weaken +permissions automatically. + +## Production integration + +`sendbox-host` validates that state and workspace roots are disjoint, then +prepares this lifecycle before runtime execution. The production adapter +persists supervisor checkpoints, signs audit publication, captures and verifies +snapshots, restores eligible mutations on failure, and quarantines changed +excluded cache/dependency entries. Runtime cleanup still runs when security +finalization fails, and all primary, rollback, audit, publication, and cleanup +failures remain visible. + +[Governed sessions](governed-sessions.md#audit) append governance admission +and credential grant and request records to the same signed audit chain. Each +record names the profile revision and the binding digest signed into the +boundary plan, and never includes credential material. A failure to record +relay evidence fails the run. A session that lifted a policy exception is +stopped when the exception expires, which follows the normal cancellation and +rollback path. diff --git a/vendor/sendbox/docs/assets/logo.svg b/vendor/sendbox/docs/assets/logo.svg new file mode 100644 index 0000000..e9d1950 --- /dev/null +++ b/vendor/sendbox/docs/assets/logo.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/vendor/sendbox/docs/cli-agents.md b/vendor/sendbox/docs/cli-agents.md new file mode 100644 index 0000000..eee4e86 --- /dev/null +++ b/vendor/sendbox/docs/cli-agents.md @@ -0,0 +1,300 @@ +# CLI agents and workspace isolation + +SendBox launches an exact guest argv, not a host-side agent wrapper. Moguri, +OpenCode, Claude Code, Codex, Copilot, Gemini, and other CLI programs use the same +signed plan, execution broker, terminal transport, MCP services, egress firewall, +snapshots, Git guard, and optional package analysis. + +## Select an agent + +```bash +sendbox init --project /projects/my-repo --agent moguri +# Also accepted: --agent opencode, open-code, claude, codex, copilot, gemini, custom. +``` + +An explicit profile admits the selected entry program and its usual inference +hosts under a default-deny policy. Non-Copilot profiles disable independent +Copilot token forwarding; they do not disable Git protection or repository +credential scoping. Existing `init` calls without `--agent` retain their +configuration defaults. + +| Profile | Initially admitted inference hosts | +|---|---| +| `moguri` | `api.githubcopilot.com`, `*.githubcopilot.com` | +| `opencode` | `opencode.ai`, `models.dev` | +| `claude` | `api.anthropic.com` | +| `codex` | `api.openai.com`, `chatgpt.com`, `auth.openai.com` | +| `copilot` | `api.githubcopilot.com`, `*.githubcopilot.com` | +| `gemini` | `generativelanguage.googleapis.com`, `oauth2.googleapis.com`, `cloudcode-pa.googleapis.com` | +| `custom` | None; configure the program and endpoints explicitly | + +OpenCode supports multiple model providers. Add the exact provider endpoints you +actually use to `policy.network.allowed_domains`; the profile does not grant +every provider or plugin unrestricted networking. Deny rules still take +precedence. Select additional telemetry, authentication, Git, and package hosts +explicitly rather than changing the policy to allow all traffic. + +The workload image must contain the Linux agent binary, its dependencies, +certificates, shell, and development tools. SendBox's signed guest bundle +contains the trusted controls, not Node.js, Bun, or the agents themselves. +Preinstall MCP servers at fixed absolute image paths instead of configuring +shells or package runners such as `npx`. + +```bash +sendbox run --interactive \ + --config /projects/my-repo/.sendbox.yaml \ + --image registry.example/agent-tools@sha256: \ + --bundle /usr/local/share/sendbox/guest//bundle \ + --trust-root /usr/local/share/sendbox/guest//release-public.key \ + -- /usr/local/bin/moguri --project /workspace +``` + +Moguri's `moguri` executable opens its TUI by default; `moguri tui` is equivalent. +`--project /workspace` selects the shared guest project. The workload image +needs the full CLI, its supported Node.js runtime, native dependencies, and a +Linux Secret Service for Moguri's OS-keyring authentication. Sign in inside the +guest; the `moguri` profile does not enable SendBox's Copilot CLI token forwarding. +For another model provider, explicitly allow its endpoints. + +For another agent, replace the final argv with its actual guest executable and +arguments. For headless operation, drop `--interactive` and use the agent's +noninteractive arguments. No executable lookup or shell evaluation happens on +the host. An unavailable provider or guest primitive is an error, not permission +to run the command on the host. + +Native agent sandboxes may need adjustment for an already-contained VM. +For example, Codex can be run with `--sandbox danger-full-access` to avoid a +nested sandbox requiring unavailable guest kernel facilities. This is an +explicit agent option, not a SendBox containment bypass; SendBox never adds +agent approval-bypass flags automatically. + +## Credentials and agent state + +Store an API credential in the SendBox vault and list only the required +workload reference: + +```bash +sendbox secrets add ANTHROPIC_API_KEY +``` + +```yaml +secrets: [ANTHROPIC_API_KEY] +github: + forward_copilot_auth: false +``` + +For Codex use `OPENAI_API_KEY`; for another provider use its documented variable. + +In a [governed session](architecture/governed-sessions.md#brokered-credentials), +list `credential_services: [anthropic]` (or `openai`) instead of the provider +key in `secrets`. The key stays on the host, and Claude Code or Codex receive +only a loopback `ANTHROPIC_BASE_URL` or `OPENAI_BASE_URL` and a placeholder key. +The host's home, global agent configuration, browser, keychain files, and +runtime sockets are not mounted. Each session gets an owner-only guest home at +`/run/sendbox-workload/` and isolated XDG directories. Login state +created there disappears with the VM. Use vault references rather than relying +on host login files being copied implicitly. + +GitHub forwarding remains independently configurable. Disable +`github.forward_auth` when no GitHub credential is needed, and disable +`github.branch_protection.enabled` for non-Git projects. Keep server-side branch +protection: local wrappers do not govern alternate clients or direct API writes. + +### Credential masking + +Credential masking is always enabled for workload stdout and stderr, including +PTY output and JSON/hex CLI output. Values delivered from the vault or session +credential forwarding are registered before the workload can print them. +Gateway and registry credentials are also registered for runtime diagnostics. +Credentials split across chunks are withheld until they can be masked safely; +stdout and stderr have independent state. An ambiguous credential prefix at +stream termination is masked rather than printed. + +Recognizable bearer/basic headers, sensitive assignments and JSON fields, +common provider token prefixes, URL userinfo, and private-key blocks are +replaced with `[REDACTED]` even when not registered in the vault. Runtime errors +are masked before failure-audit persistence. Captured MCP payloads are decoded +and masked before truncation or log serialization; decoded JSON escapes cannot +hide a registered value. Safe Outputs human-readable titles, bodies, and +messages use the same masker before sealing. Original authentication values, +envelopes, MCP traffic, and proposed source patches are not rewritten. + +Masking is not a data-loss-prevention boundary. Arbitrary encodings, +obfuscation, credentials assembled across separate output streams, newly +created opaque credentials with no recognizable form, repository files, and +source patches are not comprehensively scrubbed. Keep MCP payload capture +disabled unless needed: non-credential private content may still be recorded. +Known values are limited to 512 distinct credentials of at most 64 KiB each; +registration or masking failures stop the affected operation without exposing +the original diagnostic. Output byte counters describe the original guest +bytes, not the replacement text. + +## Repository or multi-repository filesystem scope + +By default, only `project_path` is shared read/write at `/workspace`. +To share an enclosing multi-repository workspace explicitly: + +```bash +sendbox init --project /projects/team/repo-one \ + --workspace /projects/team --agent codex +``` + +```yaml +project_path: /projects/team/repo-one +workspace_path: /projects/team +``` + +The only workload host mount becomes `/projects/team -> /workspace`; the +initial cwd and selected Git repository remain `/workspace/repo-one`. +Sibling repositories inside that root are visible. Repositories outside it, +host control sockets, and the host home are not added automatically. + +The project must be inside the normalized workspace root. Filesystem-root +mounts, parent traversal, symlinked source components, and overlapping runtime +state are rejected. Snapshots and rollback cover the selected shared root; +Safe Outputs patches still target the selected repository. + +MCP configuration is checked in the selected project and its ancestors up to +the shared workspace root, never in host-global configuration. These checks +reject symlinked configuration parents, malformed server containers, and +unapproved launcher/authentication overrides. + +## Agent-compatible network proxy + +Persistent guests expose two explicit loopback frontends backed by one +authorization cache, DNS guard, connection budget, address-pinning path, and +marked dialer: + +| Environment | Guest endpoint | +|---|---| +| `ALL_PROXY`, `all_proxy` | `socks5h://127.0.0.1:15080` | +| `HTTP_PROXY`, `HTTPS_PROXY`, lowercase equivalents | `http://127.0.0.1:15083` | +| `NO_PROXY`, `no_proxy` | `localhost,127.0.0.1,::1` | +| `NODE_USE_ENV_PROXY` | `1` | + +The HTTP frontend supports CONNECT tunnels and absolute-form plaintext HTTP +requests. It bounds headers and handshake time, rejects conflicting Host/body +framing and proxy credentials, and validates the endpoint before dialing. +HTTPS certificates remain the client's responsibility inside CONNECT tunnels. +Use a Node.js release supporting `NODE_USE_ENV_PROXY` for native `fetch` +clients; clients that ignore every proxy mechanism fail closed at the firewall. + +nftables restricts the agent cgroup and all execution descendants to the exact +loopback broker, gateway, and configured package-proxy ports. Direct outbound +TCP, UDP/QUIC, metadata access, unmarked broker traffic, and unapproved endpoints +remain denied. HTTP and SOCKS share the same connection limit rather than +doubling it. Remote MCP upstreams remain reserved from both public frontends. + +## Native MCP configuration + +SendBox checks the traditional JSON MCP files plus `opencode.json`, +`opencode.jsonc`, `.codex/config.toml`, and `.gemini/settings.json`. +Each definition must select the exact broker argv or trusted gateway route. + +OpenCode: + +```json +{ + "mcp": { + "files": { + "type": "local", + "command": ["/run/sendbox-boundary/mcp-broker", "--", "/usr/bin/mcp-server"], + "enabled": true + }, + "docs": { + "type": "remote", + "url": "http://127.0.0.1:15082/mcp/docs", + "oauth": false + } + } +} +``` + +Codex: + +```toml +[mcp_servers.files] +command = "/run/sendbox-boundary/mcp-broker" +args = ["--", "/usr/bin/mcp-server"] + +[mcp_servers.docs] +url = "http://127.0.0.1:15082/mcp/docs" +``` + +Claude/Copilot JSON uses `mcpServers` or `servers` with the same `command` and +`args`. Gemini uses `mcpServers` and `httpUrl` for Streamable HTTP; legacy SSE is +not admitted. Client tool-selection settings can narrow discovery but cannot +expand signed server/tool policy. + +Hierarchical stdio servers receive no workload secrets by default. Explicit +environment authentication selects only named, already-delivered references: + +```yaml +policy: + boundaries: + tool_calls: + servers: + files: + transport: stdio + command: [/usr/bin/mcp-server] + authorization: + method: environment + secrets: [MCP_TOKEN] + tools: + default_action: deny + allowlist: [read_file, list_directory] + docs: + transport: streamable_http + url: https://mcp.example.com/mcp + http: + allowed_auth_methods: [bearer] + authorization: + bearer_secret: REMOTE_MCP_TOKEN + tools: + default_action: deny + allowlist: [search_docs] +secrets: [MCP_TOKEN] +``` + +The remote bearer reference must not appear in top-level `secrets`; it is +delivered only to the trusted gateway. HTTP authentication supports `none` and +`bearer`; stdio supports no authentication or explicitly selected `environment` +references. OAuth and caller-supplied credential/header helpers are rejected. +Legacy flat stdio policies retain their old global environment compatibility; +use hierarchical policies for per-server credential partitions. + +Server identity, authentication choice, exact command, and tool rules are +immutable signed policy. Tool deny rules win, discovery is filtered, and calls +are checked again with mandatory redacted audit. Agent descendants remain +VM-contained even when using built-in tools; recursive descendant argv +authorization is not claimed. See [MCP inspection](mcp-inspection.md). + +## Optional guest syscall tracing + +```yaml +observability: + syscall_tracing: true +``` + +Tracing is disabled by default. When requested, Apple/Kata bootstrap verifies +the signed BPF object and starts a mandatory tracer before execution. The +tracer depends on armed egress, and Exec depends on the tracer; shutdown reverses +that order. A cgroup-array descriptor includes execution leaves and their +descendants without observing unrelated guest processes. + +Missing BTF, tracepoints, loading/attachment privileges, artifact verification, +or mandatory tracer readiness fails the session. BPF capabilities are held by +trusted guest services only; agent capabilities remain empty. + +The root-only guest log is `/var/log/sendbox/syscalls.jsonl`, capped at 16 MiB. +An authenticated, terminal-only, single-use report is independently verified +and persisted at +`~/.sendbox/run/sessions//syscall-trace-report.json` with mode `0600`. +It contains architecture, syscall counts, up to 256 argument-free samples, +sampling counts, log-limit status, and kernel/userspace/decode loss counters. +It contains no syscall arguments, command argv, paths, payloads, or credentials. + +Tracing is observation, not authorization, and bounded sampling is not a +complete forensic transcript. Loss and log limits are explicit. Hyperlight has +no Linux guest kernel or persistent broker composition and rejects tracing, +interactive sessions, MCP, and full egress features rather than downgrading them. diff --git a/vendor/sendbox/docs/cli-reference.md b/vendor/sendbox/docs/cli-reference.md new file mode 100644 index 0000000..486cd44 --- /dev/null +++ b/vendor/sendbox/docs/cli-reference.md @@ -0,0 +1,129 @@ +# CLI reference + +The Rust CLI implements the supported `sendbox` command surface: + +```text +USAGE: sendbox [options] + +SUBCOMMANDS: + init Initialize a new sendbox.yaml in the current directory + run Start the sandbox and launch the agent + analyze Analyze a project and generate a devcontainer spec + secrets Add, remove, or list stored secrets + policy Show or validate policies + mcp Parse and summarize native or legacy MCP observations + package Show package verdict status or a complete security report + boundary Inspect the structured native boundary plan + governance Sign, verify, and check operator governance profiles + completions Install or print shell completions + help Show help for any subcommand +``` + +Use `sendbox help` or `sendbox help ` for the options supported by +the installed version. + +## Init profiles and workspace scope + +`sendbox init --agent moguri|opencode|claude|codex|copilot|gemini|custom` selects the +entry program and initial inference endpoints; `open-code` is an alias for +`opencode`. Omit `--agent` to preserve the existing defaults. +`--workspace PATH` explicitly shares an enclosing multi-repository root while +`--project PATH` retains the selected repository and initial cwd. See +[CLI agents](cli-agents.md) for credentials, native MCP formats, and examples. + +## Run flags + +| Flag | Description | +|---|---| +| `--config PATH` | Sandbox configuration file | +| `--runtime auto\|apple\|kata\|hyperlight` | Runtime provider selection | +| `--image IMAGE@sha256:DIGEST` | Digest-pinned workload image for persistent runtimes | +| `--bundle PATH` | Verified guest bundle directory | +| `--trust-root PATH` | Release public key used to verify the bundle | +| `--json` | Emit machine-readable events instead of raw output | +| `--interactive` | Run the workload on a pseudoterminal; conflicts with `--json` | +| `--governance-config PATH` | Opt-in governance configuration; rejected when a managed configuration names a different file | + +See [interactive sessions](interactive-sessions.md) for terminal-specific +requirements and [configuration](configuration.md) for the YAML reference. + +JSON workload output events carry `encoding: "hex"`; decode their `data` before +comparing payload bytes. A persistent launch/runtime failure reports its already +credential-masked terminal diagnostic in the result's `message` field and keeps +the existing nonzero exit code. Text mode prints that diagnostic to stderr. +Successful result objects do not add a failure message. + +For an exact `github.com` grant, the final JSON result includes +`network_report: {path, sha256}`. The private JSON artifact contains the configured policy +and latest GitHub Meta scope/provenance for each active gateway role. Read its +freshness, failure and expiry fields before interpreting the published grants; +explicit deny and restricted-address rules still apply. It is authenticated +guest evidence whose digest is recorded in session provenance, not a separately +GitHub-signed feed or a complete refresh log. +See [network grants](configuration.md#network-grants). + +## Governance + +`sendbox governance` manages operator-signed profiles for +[governed sessions](architecture/governed-sessions.md): + +| Subcommand | Purpose | +|---|---| +| `keygen --output PATH` | Create an Ed25519 signing key (mode `0600`, never overwritten) and print its public identity | +| `sign PROFILE --key PATH [--append]` | Sign the profile's exact bytes into `PROFILE.sig.json`; `--append` adds a threshold signature | +| `verify [--governance-config PATH]` | Verify the active operator configuration, profile, and signatures | +| `check --config PATH [--governance-config PATH] [--runtime apple\|kata] [--image IMAGE@sha256:DIGEST]` | List every violation of the active profile without starting a session | +| `login [--governance-config PATH] [--identity-token-file PATH] [--ttl-seconds N] [--description TEXT]` | Exchange an identity-provider token (read from the file, stdin, or a prompt) with the configured shared governance service and store the returned service token in the host secret store | + +Each subcommand accepts `--json`. A governance failure or a rejected +configuration exits with code `6`. `check` evaluates the local profile only; +with a [shared governance service](architecture/governed-sessions.md#shared-governance-service), +run `sendbox governance login` (or `sendbox secrets add SENDBOX_FLEET_TOKEN`) +before `sendbox run`. + +## Examples + +```bash +# Initialize a new project +sendbox init + +# Run with the Kata backend +sendbox run --config .sendbox.yaml --runtime kata \ + --image registry.example/workload@sha256: \ + --bundle /usr/local/share/sendbox/guest/x86_64/bundle \ + --trust-root /usr/local/share/sendbox/guest/x86_64/release-public.key \ + -- /usr/bin/true + +# Generate a devcontainer spec +sendbox analyze --project . --output .devcontainer/ + +# Validate a sandbox configuration's policy +sendbox policy validate --config sendbox.yaml + +# Show configured policy as deterministic JSON (no live metadata retrieval) +sendbox policy show --config sendbox.yaml --json + +# Show the latest package-enabled run and its complete report +sendbox package status +sendbox package report --json + +# Print or install generated shell completions +sendbox completions print --shell zsh +sendbox completions install --shell fish + +# Native analysis with automation JSON +cargo run -p sendbox-cli -- analyze --project . --json + +# Native devcontainer generation +cargo run -p sendbox-cli -- devcontainer generate --project . --json + +# Parse a captured trace log and summarize MCP activity +sendbox mcp parse /var/log/sendbox/mcp-trace.log +sendbox mcp report /var/log/sendbox/mcp-trace.log + +# Inspect the structured boundary declaration without generating scripts +sendbox boundary inspect --config .sendbox.yaml --json + +# Check a project against the active governance profile +sendbox governance check --config .sendbox.yaml --runtime apple +``` diff --git a/vendor/sendbox/docs/configuration.md b/vendor/sendbox/docs/configuration.md new file mode 100644 index 0000000..2a4a3b1 --- /dev/null +++ b/vendor/sendbox/docs/configuration.md @@ -0,0 +1,374 @@ +# Configuration + +SendBox is configured through YAML. Generate `.sendbox.yaml` in the project root +and then edit it for the selected runtime and policy: + +```bash +sendbox init --project . +sendbox init --project . --runtime kata +sendbox policy validate --config .sendbox.yaml +``` + +The fully annotated reference is +[`config/example-sandbox.yaml`](../config/example-sandbox.yaml). + +## Example + +```yaml +name: my-agent-sandbox +project_path: ./workspace + +runtime: + provider: auto # auto | apple | kata | hyperlight + kata: + executable: nerdctl + runtime_handler: io.containerd.kata.v2 + namespace: sendbox + hyperlight: + kernel_path: /opt/hyperlight/shell-kernel + initrd_path: /opt/hyperlight/shell.cpio + +resources: + cpus: 2 + memory_mb: 2048 + disk_size_mb: 10240 + +policy: + commands: + default_action: deny + allowlist: + - "git *" + - "npm *" + - "python3 *" + denylist: + - "sudo *" + log_blocked: true + + network: + default_action: deny + allow_dns: true + # Replace wildcard entries with concrete hostnames when using Hyperlight. + allowed_domains: + - github.com + - "*.github.com" + - registry.npmjs.org + blocked_domains: [] + + packages: + enabled: true + registries: + - ecosystem: npm + url: https://registry.npmjs.org/ + allow_insecure_http: false + signature: if_present + provenance: if_present + default_finding_action: deny + finding_actions: + - finding: lifecycle_script + action: deny + exceptions: [] + limits: + max_report_bytes: 98304 + + boundaries: + # Set to false when using Hyperlight. + enabled: true + tool_calls: + max_frame_bytes: 1048576 + servers: + filesystem: + transport: stdio + command: + - /usr/local/bin/node + - /usr/local/lib/node_modules/@modelcontextprotocol/server-filesystem/dist/index.js + - /workspaces/my-project + tools: + default_action: deny + allowlist: [read_file, list_directory] + denylist: ["write_*", "delete_*"] + github: + transport: stdio + command: ["/usr/local/bin/github-mcp-server", "stdio"] + tools: + default_action: deny + allowlist: [search_code, get_file_contents] + denylist: ["create_*", "update_*", "delete_*"] + remote-docs: + transport: streamable_http + url: https://mcp.example.com/mcp + tools: + default_action: deny + allowlist: [search_docs, get_document] + denylist: ["create_*", "update_*", "delete_*"] + http: + allow_redirects: false + max_response_bytes: 1048576 + request_timeout_seconds: 30 + authorization: + bearer_secret: REMOTE_MCP_TOKEN + syscalls: + additional_denylist: + - io_uring_setup + log_blocked: true + log_path: /var/log/sendbox/boundary.log + +secrets: + - DATABASE_URL + +devcontainer: + auto_generate: true + extensions: + - github.copilot + +github: + forward_auth: true + forward_copilot_auth: true + allow_private_repository_access: false + branch_protection: + enabled: true + protected_branches: [main, master] + allowed_branch_patterns: + - "{username}/*" + - "copilot/*" + - "feature/*" + safe_outputs: + enabled: false + mode: staged + write_token_env: SENDBOX_SAFE_OUTPUTS_GITHUB_TOKEN + +observability: + mcp_inspection: + enabled: false + transports: [stdio] + capture_payloads: false + max_payload_bytes: 16384 + log_path: /var/log/sendbox/mcp-trace.log +``` + +Rust-generated configuration uses deterministic snake_case YAML, validates +before writing, is created atomically with mode `0600`, and refuses to overwrite +an existing `.sendbox.yaml`. JSON results are deterministic. Invalid input or +configuration returns `2`; analysis failures return `3`; write failures and +no-overwrite refusals return `4`. Text diagnostics use stderr, while `--json` +failures use stdout only. + +Workload output, runtime failure diagnostics, captured MCP credentials, and +Safe Outputs human text are credential-masked by default, without a disable +switch. Authentication traffic is not modified. See +[credential masking](cli-agents.md#credential-masking) for coverage and limits. + +## Network grants + +Apple and Kata enforce exact hostnames, explicit wildcard patterns, IPv4/IPv6 +network grants, and deny-first restrictions through DNS, HTTP CONNECT, SOCKS5, +and the native CONNECT protocol: + +```yaml +policy: + network: + default_action: deny + allow_dns: true + allowed_domains: [github.com, "*.tools.example"] + blocked_domains: [blocked.tools.example] + blocked_networks: ["203.0.113.9/32"] +``` + +`*.tools.example` matches `one.tools.example` and `nested.one.tools.example`, +not the apex `tools.example`, `nottools.example`, or `tools.example.evil`. +Add the apex separately when needed. Ordinary exact hosts remain exact; they +do not implicitly grant subdomains. All CNAME hops must also be admitted. + +**`github.com` is an explicit delegation to the official GitHub Meta feed**, not +an apex-only grant. The host fetches the fixed anonymous HTTPS endpoint + into one cache shared by every session on the +machine (`~/.sendbox/run/github-meta.json`). It reuses that response for up to +an hour, then revalidates it with its ETag, so SendBox makes at most about one +request per hour per machine. Each session's gateways receive the validated +response before readiness and never contact GitHub themselves. Only an +effective exact apex grant triggers this behavior: +`api.github.com`, `*.github.com`, and permissive defaults alone do not. +The reviewed network fields and domain/endpoint fields, including their +published wildcard patterns, become additional grants. SSH keys, commit keys, +fingerprints, and the artifact-attestation trust-domain identity are not +destinations. Unknown fields, malformed entries, default routes, and oversized +documents are rejected as a whole. + +**The feed includes shared-cloud CIDRs and wildcard services.** This intentionally +grants more than GitHub-owned web servers, including published Actions ranges. +It is not unlimited Internet access, authentication, or approval to perform +GitHub writes. Unlisted hostnames still fail a default-deny domain check even +when their address falls in a published range; direct-IP TCP access to that +range is allowed, subject to port and explicit-network restrictions. +Explicit deny rules, private/link-local/metadata address protections, DNS +budgets, reserved MCP origins, package-proxy isolation, and UDP/QUIC denial +still apply. Published CIDRs never count as explicit private-address grants. + +GitHub allows 60 anonymous API requests per hour per IP address, shared with +every other unauthenticated client behind that address. When a refresh fails, +including a 403/429 rate limit, the host records the error and waits 60 seconds +or until GitHub's published reset before retrying. Meanwhile it keeps using the +previous validated response while at least 15 minutes remain of its 24-hour +lifetime, and the session's network report shows `degraded` with the error. +Without such a response, the session fails before launch with the typed error +and the reset time. It never silently reverts to apex-only behavior. +Derived grants expire 24 hours after the host's last successful fetch or +conditional revalidation; configured exact hosts and explicit networks are +unchanged. An explicit `api.github.com` deny, disabled DNS, or a TCP/443 +exclusion makes a `github.com`-enabled session fail with an invalid +configuration error. Each request has a ten-second deadline, no redirects, +environment proxy, or credentials. The cached copy is revalidated with the +strict parser on every read, and a corrupt cache is discarded. + +A guest receives one validated response at boot and does not refresh it; guest +executions are capped at 300 seconds. Already-open tunnels retain their +existing maximum 300-second lifetime. A restart installs the same host-supplied +response again and cannot reuse earlier DNS pins. + +With `sendbox run --json`, the final `network_report: {path, sha256}` references +a private host-side `network-egress-report.json`, following the package-report +artifact pattern instead of inflating every consumer's result frame. Its digest +is recorded in the signed session provenance. The file contains each gateway's +configured policy plus latest published +scope, body SHA-256, ETag, source/API version, revision, attempt/success/expiry +timestamps, freshness, and last failure. The scope is combined with the +configured deny/address/port controls; it is not a standalone allow-all policy. +The report captures the latest refresh attempt, not a complete transition +history or proof that an expired lease is still live. It is available after a +normal terminal response, not guaranteed after forced cancellation. +`policy show --json` remains an offline view of configured rules and does not +pretend to resolve this live scope. + +This requires a matching updated host and signed guest bundle. The boundary +plan remains version 3, with a signed `network_github_meta` admission that +binds the response's SHA-256; the internal egress runtime document is version +5, the guest bootstrap is version 5, and `network.report` is independently +versioned at 1. Older guest bundles are rejected, not silently accepted with +narrower behavior. Hyperlight has no authenticated production +Meta-refresh gateway. No release or consumer activation is implied by a source +build. + +## GitHub and MCP boundaries + +GitHub repository forwarding currently supports `github.com`. Ordinary HTTPS +Git uses a fixed authenticated askpass helper rather than assuming +`GITHUB_TOKEN` is consumed automatically. `github.ssh_key_path` accepts an +owner-only private-key file and routes Git SSH through a trusted wrapper with +strict host-key checking; the guest image must provide trusted SSH host keys. + +Selected-repository `git push` and `git pull` operations are branch-protected by +default. `main` and `master` are denied, while `{username}/*`, `copilot/*`, and +`feature/*` are allowed. The username is auto-detected from `gh` or can be +configured explicitly. This guard requires `policy.boundaries.enabled`; keep +GitHub server-side branch protection enabled as defense in depth against direct +API ref mutations or alternate Git clients. Disable +`github.branch_protection.enabled` for non-Git projects. + +The native Rust admission engine is connected to persistent Apple and Kata +`sendbox run` sessions through authenticated guest bootstrap. It does not +replace hosting-provider rulesets or protect alternate clients and direct GitHub +API calls. + +Local stdio MCP configuration must use +`/run/sendbox-boundary/mcp-broker -- `. Remote project +definitions must use the deterministic +`http://127.0.0.1:15082/mcp/` route and the configured +`streamable-http` or `streamable-http-2025` type; direct upstream URLs and +project-supplied credentials are rejected. Stdio and HTTP share exact server +resolution, deny-first tool policy, `tools/list` filtering, call-time checks, +and a root-owned audit log. The gateway verifies TLS, revalidates DNS and +redirect addresses, pins exact destinations, and keeps bearer credentials out +of the agent environment. Legacy 2024 HTTP+SSE and Hyperlight MCP composition +fail closed. + +Safe Outputs is disabled and staged by default. Enabling `github.safe_outputs` +requires Apple or Kata, `policy.boundaries.enabled: true`, +`github.forward_auth: false`, no SSH key forwarding, and exact repository and +operation limits. The trusted guest installs +`/run/sendbox-boundary/safe-outputs-mcp`; configure it behind the native broker. +Apply mode reads `SENDBOX_SAFE_OUTPUTS_GITHUB_TOKEN` only after the guest, +control channel, and secret resolver have been cleaned up. Asset uploads are not +supported. A custom write-token name cannot reuse a forwarded Copilot token +variable. See the [Safe Outputs architecture](architecture/safe-outputs.md). + +## Copilot credentials + +`github.forward_copilot_auth: true` forwards a Copilot credential independently +of repository-scoped GitHub authentication. The host resolves it from the first +variable that is set, in this order: + +| Host variable | Status | +|---|---| +| `COPILOT_GITHUB_TOKEN` | Supported | +| `GITHUB_COPILOT_TOKEN` | Legacy compatibility only | + +Only an absent variable falls through to the next candidate; a variable that is +set but empty is a hard error rather than a silent fallback. +Repository-scoped credentials (`GH_TOKEN`, `GITHUB_TOKEN`) are never consulted +for Copilot. + +Whichever host variable supplied the value, the guest receives it as +`COPILOT_GITHUB_TOKEN`, the name current GitHub Copilot CLI releases read. +Errors name the supported variables and never print a credential value. + +## Package registry credentials + +`policy.packages.enabled: true` activates the npm-first proxy on Apple and Kata +persistent guests. The current implementation requires exactly one npm +registry. For private registries, set `registries[].credential_secret` to a +SendBox vault reference. That reference must not also appear in top-level +`secrets`: registry tokens are delivered only to the isolated trusted proxy and +are never exposed to the workload. + +The proxy forces npm to its loopback endpoint, disables lifecycle scripts, +denies direct workload access to the configured upstream, and withholds +tarballs until verification and inspection allow them. See the +[package supply-chain proxy](package-supply-chain.md) for setup, policy, +false-positive handling, reports, and future ecosystem adapter contracts. + +## Configuration reference + +See [CLI agents](cli-agents.md) for agent-specific initialization, HTTP/SOCKS +proxy environment, native MCP definitions, multi-repository scope, and bounded +guest syscall tracing. + +| Section | Key | Description | +|---|---|---| +| `name` | string | Human-readable sandbox name | +| `project_path` | string | Selected host project and initial guest cwd | +| `workspace_path` | optional string | Explicit enclosing multi-repo mount root; otherwise only the project is shared | +| `runtime.provider` | enum | `auto`, `apple`, `kata`, or `hyperlight` | +| `runtime.kata.runtime_handler` | string | Supported Kata v2 handler; shared-kernel/unverified handlers are rejected | +| `runtime.kata.namespace` | string | containerd namespace | +| `runtime.kata.configuration_path` | string | Absolute Kata config path on the containerd host | +| `runtime.hyperlight.kernel_path` | string | Hyperlight-compatible Unikraft shell kernel | +| `runtime.hyperlight.initrd_path` | string | Rootfs CPIO containing the commands or MCP servers to run | +| `resources.cpus` | int | Number of virtual CPUs | +| `resources.memory_mb` | int | Memory allocation in MB | +| `resources.disk_size_mb` | int | Requested writable-layer size | +| `policy.commands` | object | Command allowlist/denylist policy | +| `policy.network` | object | Outbound network policy | +| `policy.packages` | object | npm proxy, verification, finding actions, limits, exceptions, and cache policy | +| `policy.packages.registries[].credential_secret` | string | Vault reference isolated from workload secrets | +| `policy.packages.limits.max_report_bytes` | int | Bounded package report size, up to 98304 bytes | +| `policy.boundaries.enabled` | bool | Install fail-closed MCP and syscall boundaries | +| `policy.boundaries.tool_calls` | object | Exact stdio/HTTP MCP servers with independent tool and transport policy | +| `policy.boundaries.tool_calls.servers.*.authorization` | object | Explicit stdio environment-auth method and per-server secret references | +| `policy.boundaries.tool_calls.servers.*.http.allowed_auth_methods` | list | Admitted HTTP auth methods: `none`, `bearer` | +| `policy.boundaries.syscalls.additional_denylist` | list | Extra syscall names blocked by seccomp | +| `secrets` | list | Secret names injected at runtime | +| `credential_services` | list | Brokered credential service ids from the active [governance profile](architecture/governed-sessions.md#brokered-credentials); rejected outside governed sessions | +| `devcontainer.auto_generate` | bool | Generate a devcontainer spec | +| `github.forward_auth` | bool | Forward guarded GitHub credentials for the selected repository | +| `github.forward_copilot_auth` | bool | Forward Copilot authentication independently as `COPILOT_GITHUB_TOKEN` | +| `github.allow_private_repository_access` | bool | Permit additional same-organization private repositories | +| `github.ssh_key_path` | string | Owner-only SSH private key used by the trusted Git SSH wrapper | +| `github.branch_protection.enabled` | bool | Guard selected-repository pushes and pulls by branch | +| `github.branch_protection.username` | string | Username used to expand `{username}` patterns; auto-detected by default | +| `github.branch_protection.protected_branches` | list | Branch names that push and pull can never target | +| `github.branch_protection.allowed_branch_patterns` | list | Glob patterns allowed for selected-repository push and pull | +| `github.safe_outputs` | object | Credential-free, sealed GitHub write declarations; disabled and staged by default | +| `github.safe_outputs.mode` | enum | `staged` for preview-only or `apply` for host-only GitHub execution | +| `github.safe_outputs.write_token_env` | string | Host-only environment variable read after runtime teardown | +| `github.safe_outputs.allowed_repositories` | list | Exact `owner/repository` write targets | +| `observability.mcp_inspection.enabled` | bool | Enable authenticated local stdio MCP observation on Apple or Kata | +| `observability.syscall_tracing` | bool | Require cgroup-subtree guest observation and a verified redacted syscall report | diff --git a/vendor/sendbox/docs/contributing.md b/vendor/sendbox/docs/contributing.md new file mode 100644 index 0000000..b99efe1 --- /dev/null +++ b/vendor/sendbox/docs/contributing.md @@ -0,0 +1,145 @@ +# Contributing to SendBox + +Contributions are welcome. For larger changes, open an issue first to discuss +the approach. The [roadmap](../ROADMAP.md) tracks planned work. Report +security vulnerabilities privately as described in the +[security policy](../SECURITY.md), not in issues or pull requests. + +## Source setup + +Follow the [source-build requirements](installation.md#requirements), then fork +and clone the repository and create a feature branch: + +```bash +git clone https://github.com/YOUR_USERNAME/sendbox.git +cd sendbox +git checkout -b feature/my-change +make build +``` + +The toolchain is pinned in `rust-toolchain.toml`. Building the host binary does +not provision a runtime or install a signed guest bundle; see +[installation](installation.md) for those steps. + +## Checks + +Before opening a pull request for code changes, run: + +```bash +make lint +make test +make release +make audit +``` + +`make lint` checks formatting and Clippy and compiles every standalone fuzz +workspace with its committed lockfile. `make audit` requires `cargo-audit`. +Runtime-specific live qualification needs a prepared host; see +[qualification](qualification.md) and the individual runtime guides. + +CI runs portable checks and build/install qualification in parallel on macOS +and Linux, with fail-fast matrices. Rust dependency caches are isolated by +toolchain, platform, lockfiles, and job task; every check still runs. Standalone +fuzz workspaces share the root target directory in CI instead of recompiling +their common dependencies into separate target directories. The `cargo-audit` +executable is cached, but every run refreshes and checks the advisory database. +The portable-check jobs also run the credential-free cold-start diagnostic +harness's Python standard-library tests. Live VM qualification remains an +explicit prepared-host check; see [cold-start DNS diagnostics](dns-cold-start.md). +The diagnostic tests explicitly select Python **3.15.1**, rather than the +runner's preinstalled `python3`. No third-party Python packages are required. +This host-side selection does not change the standalone diagnostic workload +image or add Python to production Rust guest images. Homebrew updater tests +belong to the tap that owns formula updates, not this source repository. + +CI preloads the exact Python release asset through +GitHub's release-asset API using `scripts/setup-ci-python.sh`, with SHA-256 +verification and bounded retries before the normal `setup-python` action selects +it. The workflow passes its `GITHUB_TOKEN` so the request is not subject to the +anonymous 60-requests-per-hour limit shared by runner IP addresses. The helper supports macOS arm64 and Ubuntu x64, including matching packages +for Ubuntu 22.04, 24.04, and 26.04. Update the workflow version, helper version, +asset IDs, and checksums together when updating Python. + +Run the diagnostic harness tests locally without installing or starting +SendBox; substitute `python3.15` for `python3` to reproduce CI's selected minor +version. The release helper separately requires Python 3.11 or newer: + +```bash +PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover \ + -s test-fixtures/dns-cold-start -p 'test_*.py' +``` + +The CLI integration suite also exercises release creation and same-version +recovery using temporary local Git repositories, offline Cargo fixtures, and +mocked GitHub commands. These tests never publish a release or contact GitHub: + +```bash +cargo test --locked -p sendbox-cli --test release_script +``` + +Hosted Apple, Hyperlight, and qualification checks also cache Rust dependencies; +qualification caches both its standalone workspace and the root CLI workspace. +These caches restore on pull requests but save only on `main`, avoiding another +set of large target caches for every PR. +These jobs explicitly budget three workers on macOS and four on Linux, matching +the standard public runners without reducing their existing CPU parallelism or +changing the prepared self-hosted live gates. The Apple adapter spike, egress +spike, production egress, and production exec workflows share CI's platform- +and version-keyed `cargo-audit` executable cache. Cache hits skip only installing +the audit tool, never the dependency audit or advisory database refresh. + +Generic hosted x64 Linux jobs use `ubuntu-latest`; generic Apple-silicon jobs +use `macos-latest`. Matrix `os` values and existing job names remain stable +status-check identifiers; the separate `runner` field selects the current +image. Version strings in those check names are not runner pins. +Native Linux arm64 jobs retain `ubuntu-24.04-arm`, because GitHub has no +documented `ubuntu-latest-arm` alias. Kernel-specific BPF, exec and egress live +proofs keep their qualified Ubuntu 24.04 hosts, and prepared self-hosted gates +keep their hardware labels. + +Release CLI builds retain Ubuntu 24.04 for their glibc-linked Linux binaries. +The macOS producer uses `macos-latest` but explicitly retains the existing +`MACOSX_DEPLOYMENT_TARGET=11.0` binary floor and verifies arm64/Mach-O metadata. +This does not change the Apple runtime's macOS 26+ requirement. Packaging and +publication jobs can follow the hosted aliases without relinking these bytes. + +Guest artifact CI runs the two clean builds for each architecture in separate +parallel jobs and compares their outputs before publishing the verified bundle. +Changes to the shared egress crate also select this workflow because its DNS +resolver is linked into the guest, even when no guest entrypoint changes. +See [guest artifact CI](architecture/guest-artifact-bundles.md#continuous-integration) +for cache boundaries and the automatic privileged BPF smoke tests. + +For documentation-only changes, check examples, relative links, and heading +anchors. Keep the root README focused on evaluating the project and starting a +session; put detailed operational and architecture material under `docs/` and +link it from the [documentation index](README.md). + +## Publishing releases + +Maintainers publish tag-triggered releases with: + +```bash +./scripts/release.sh VERSION +``` + +`make release` only builds locally. See +[publishing a release](installation.md#publishing-a-release) for prerequisites, +version-bump review, CI, tags, and recovery behavior. After preflight checks, the +script switches to `main` and pulls fast-forward-only before release operations. +Retry a failed attempt with the same command and version; existing release tags +are not moved or replaced. + +Homebrew updates reuse the published archives and are owned by the existing +tap; SendBox does not compile a separate Homebrew binary or write tap branches. +Release builds cache Rust dependencies by toolchain/platform/lockfile and +reuse each signed guest artifact for the host packages and publication. +Native CLI tests and release builds run alongside the independent signed guest +builds. Packaging waits for both and restores the tested CLI from a same-run, +commit- and platform-specific archive, verifying its checksum and executable +mode rather than compiling it again. These internal CLI archives keep the +repository's default artifact retention for failed-job retries and are not +included in the public `release-*` asset set. +Clean guest-container builds and the existing macOS/Linux checks remain in +place. See [stable Homebrew updates](installation.md#stable-homebrew-updates) +for the pending central updater, native CI/review gates, activation, and recovery. diff --git a/vendor/sendbox/docs/dns-cold-start.md b/vendor/sendbox/docs/dns-cold-start.md new file mode 100644 index 0000000..003adaa --- /dev/null +++ b/vendor/sendbox/docs/dns-cold-start.md @@ -0,0 +1,328 @@ +# Cold-start DNS diagnostics + +This diagnostic measures the first application request in each new Apple VM. +It contains no agent loop, personal credentials, application retry, preceding +lookup, cache priming, or startup sleep. A later successful request is not a +replacement for the first result. + +## What the evidence establishes + +On 2026-10-20, the installed macOS host and signed aarch64 guest were compared +with the checksum- and GitHub-attestation-verified official 0.2.1 archive: + +| Artifact | SHA-256 | +|---|---| +| Host | `0dd8dde709673a4eb5dd890091ec190a1c2b53b4237c6271a2fe23621fc5d9f2` | +| Guest | `5d0fc5c65d042f2b04922eeb7c7a85039fb839adb7d197c8440fd5ab40ca8f21` | + +Both the Apple CLI and service reported 0.10.0, commit `6bdb647`. The guest +manifest required host/guest 0.2.1, architecture aarch64 and release sequence 5. + +The original missing-first-reply symptom **did not recur in 20 sequential +released-guest VMs**. Every first request reached the API over verified TLS and +received the expected credential-free HTTP 400. This is transport evidence, +not authenticated model access, and not proof that the reported transient has +been resolved. + +Header-only captures reconfirmed the selected upstream as `192.168.64.1:53`, +not an assumed historical value. Additional fresh released-guest captures saw +both initial A/AAAA queries leave the guest and matching replies return: +matching IDs, question types, source address and source port. The observed +canonical name was `glb-db52c2cf8be544.github.com`. A separate fresh, non-root, +direct-upstream diagnostic received its first A/AAAA replies in approximately +2.3/23.6 ms. + +These observations establish that this path was healthy during those runs. +They do **not** establish an Apple bridge, host DNS proxy, or upstream resolver +defect. Guest-only capture cannot distinguish those external boundaries when +no reply arrives. Do not flush host caches, change the selected resolver, or +restart unrelated services to manufacture a different result. + +The deterministic failure boundary is in SendBox's loss handling: + +1. Released forwarding sends one UDP datagram per QTYPE. +2. If that query or reply is lost, the resolver times out after three seconds. + TCP is attempted only after a validated truncated UDP response, not after + silence. +3. A and AAAA run concurrently, but an error in either fails the combined + resolution. A completed A result alone cannot authorize a connection. +4. An empty authorization cache therefore produces SOCKS REP `0x04` or HTTP + CONNECT 502. No address is cached on that failed resolution. +5. A later request performs another resolution and may succeed. That outcome + does not repair the first request or identify where a packet was lost. + +A generated UDP fixture that discards the first datagram reproduced this +failure before the change. The corrected resolver passes the same fixture. +This establishes a SendBox resilience defect consistent with the reported +missing-reply evidence; it does not identify the cause of the original live +packet loss. + +## Bounded mitigation + +Each A/AAAA query now has one absolute three-second budget covering socket +setup, UDP transmission/receive and TCP recovery. +If the first UDP reply is still missing halfway through that budget, the same +question and ID are sent **once** on the same connected, marked socket to the +same selected upstream. Neither the deadline nor the application request is +restarted. TCP recovery starts once at that same halfway boundary if UDP is +still pending, against the same selected numeric upstream and port with the +same question/ID and socket mark. UDP remains live until completion, cancellation +or the original deadline. A TCP transport failure does not discard a later +valid UDP reply. Validated UDP truncation still starts TCP immediately. +The brokers retain their independent five-second resolution bound. + +There is no new public resolver, readiness lookup, sleep, background warm-up, +unsandboxed fallback, or hostname/CNAME/IP grant. Permanent DNS errors, malformed +responses and policy denials are not retried. Both completed family results +still undergo the existing CNAME agreement, address-class, QTYPE, budget and +authorization checks. A TCP response that is still truncated is rejected. + +UDP retransmission mitigates a single missing exchange; the same-upstream TCP +path can also recover persistent UDP silence when that resolver supports TCP. +Unavailable transports still fail closed at the original deadline. +Gateway readiness continues to mean that authenticated local services and +mandatory controls are ready, not that an external DNS server has been probed. + +DNS failures produce typed audit metadata with the failure kind, QTYPE, +selected numeric upstream, transport, operation and OS code when available. +Broker-deadline expiry is distinguished from resolver exchange timeout. +HTTP DNS failures remain 502, with `Proxy-Status: sendbox; error=dns_error` and +a bounded JSON diagnostic. Free-form resolver messages, DNS packet contents, +credentials, bootstrap files and gateway control tokens are never included. +SOCKS and native CONNECT reply codes remain compatible. + +## Meta startup follow-up + +A credential-free, zero-model startup using the official 0.2.4 guest reproduced +an egress service exit before its ready socket. An independently instrumented +host kept the signed guest unchanged and authenticated each generated +root/image/command/plan before observation. Both initial A/AAAA UDP requests +for the fixed public Meta endpoint and their same-ID retransmissions sent +successfully, but the failed case received no reply within three seconds. +Meta published `unavailable` with no active grants, the gateway exited, its +parent observed control EOF, and the outer caller eventually reported guest +readiness timeout. A successful case received both validated family replies +after retransmission. All observed cgroup controller writes succeeded. + +That establishes a missing-UDP-reply boundary, not the location of packet loss +outside the guest. The selected upstream's TCP DNS returned a validated answer +in 2.36 ms in a separate fresh generated VM. No alternate resolver, cache flush, +application replay, credential forwarding or personal runtime restart was used. + +The new generated regression first fails because no TCP connection is admitted +after UDP silence, then passes with same-question recovery within the unchanged +budget. Coverage also checks both families, strict TCP response validation, +an incomplete TCP body at the original deadline, simultaneous-transport +cancellation, no recovery after completed UDP, and preservation of a late UDP +answer after a failed TCP attempt. Existing policy/CNAME/address and partial- +family refusal tests remain in place. + +These are source and primitive observations. A changed signed guest and its +complete native/application integration still need their own qualification; +the official 0.2.4 guest bytes have not acquired this behavior merely because +the source tests pass. Historical results below remain distinct. + +With pinned Rust 1.93.1, the complete local workspace reports 936 passing tests, +two explicitly ignored environment-gated cases (live Meta HTTPS and interactive +signing/Keychain ACL) and no failures. All ten locked fuzz +workspaces, formatting, deny-warning Clippy and the release workspace build +pass. A fresh strict JSON audit reports zero vulnerabilities and no warnings +against 1,409 advisories. An earlier audit's registry/yank lookup timed out +despite exit zero; it remains incomplete, not the successful audit receipt. +Guest artifact CI now includes egress changes in its transitive input filter. +No new dependency, public policy grant, schema or protocol is introduced. + +## Historical qualification results + +The official 0.2.1 host was also used with a separately signed development +guest built from this change. The test trust root was +`dns-cold-test-b5f8686b`, release sequence 6, with matching host/guest version +0.2.1. The guest SHA-256 was +`681105e407d4625d2e19698340c138acd853cc174f346df8afd747cbc0c255f9`. +The unchanged signed-release launcher and BPF object were reused; both +executables passed static ELF verification. The temporary signing seed was +destroyed, and the official installed bundle/key were not replaced. + +Each cohort below used sequential, unique-boot VMs. Within each VM there was +no preceding DNS lookup, warm-up, or application retry. Shared host/upstream +caches were not flushed or claimed to be empty. First-request time runs from +opening the loopback proxy through receipt of the unauthenticated API response headers, +including CONNECT and verified TLS; VM boot/cleanup and response bodies are +excluded. + +| Guest | Fresh VMs | First failures | Median ms | p95 ms | Maximum ms | +|---|---:|---:|---:|---:|---:| +| Official 0.2.1, no injected loss | 20 | 0 | 596.795 | 706.852 | 732.704 | +| Patched test guest, no injected loss | 20 | 0 | 566.914 | 675.600 | 2136.019 | + +All first responses were HTTP 400 after successful SOCKS/HTTP CONNECT and TLS. +Both cohorts passed 40/40 deny checks. Every measured workload was non-root, +with `NoNewPrivs=1`, `Seccomp=2`, and zero effective/permitted/ambient +capabilities. Every cohort reported zero owned VMs remaining, also confirmed +by the final scoped container listing. + +The patched per-VM results, including the slowest sample without discarding it: + +| VM | Front end | CONNECT ms | First request ms | Result | +|---:|---|---:|---:|---| +| 1 | SOCKS | 123.389 | 549.224 | pass | +| 2 | HTTP | 132.087 | 675.600 | pass | +| 3 | SOCKS | 166.293 | 665.139 | pass | +| 4 | HTTP | 106.548 | 531.070 | pass | +| 5 | SOCKS | 103.443 | 506.896 | pass | +| 6 | HTTP | 105.750 | 518.138 | pass | +| 7 | SOCKS | 109.215 | 523.824 | pass | +| 8 | HTTP | 110.875 | 423.481 | pass | +| 9 | SOCKS | 137.089 | 566.320 | pass | +| 10 | HTTP | 105.425 | 391.788 | pass | +| 11 | SOCKS | 194.434 | 629.375 | pass | +| 12 | HTTP | 212.704 | 648.495 | pass | +| 13 | SOCKS | 108.735 | 569.387 | pass | +| 14 | HTTP | 190.937 | 612.174 | pass | +| 15 | SOCKS | 125.839 | 567.507 | pass | +| 16 | HTTP | 467.981 | 2136.019 | pass | +| 17 | SOCKS | 218.164 | 593.784 | pass | +| 18 | HTTP | 147.900 | 667.463 | pass | +| 19 | SOCKS | 112.161 | 534.874 | pass | +| 20 | HTTP | 104.305 | 529.690 | pass | + +The trace observed `eth0` up with carrier, a default route through +`192.168.64.1`, and the original upstream in `/etc/resolv.conf` at approximately +0.38 seconds guest uptime. At the first query, resolver configuration had +changed to `127.0.0.1` while the broker's actual upstream packets still targeted +`192.168.64.1:53`. Link/route readiness is not proof of DNS-server readiness. + +Controlled loss was then compared in separate fresh VMs. A test-only guest +input rule dropped the first two upstream replies, one A and one AAAA: + +| Guest | Front end | First result | First request ms | +|---|---|---|---:| +| Official 0.2.1 | SOCKS | REP `0x04`, failure | 3004.633 | +| Official 0.2.1 | HTTP | CONNECT 502, failure | 3002.812 | +| Patched test guest | SOCKS | REP `0x00`, TLS, HTTP 400 | 2063.331 | +| Patched test guest | HTTP | CONNECT 200, TLS, HTTP 400 | 2809.843 | + +The drop counters verified exactly two lost replies in each experiment. +Patched retransmissions retained each original question, ID and source port, +at approximately 1502 ms after the initial send. There was no retry of the +measured application request. Both patched cold requests passed, and all four +VMs kept both denials and containment checks intact and were deleted. + +In the released fault-injection runs, the *later denial check* on API port 444 +caused a new resolution around three seconds later, which received replies but +still denied the forbidden port. That later DNS success was not substituted +for the failed first request. + +The injected loss boundary was deliberately inside the owned guest, between +interface capture and the resolver socket: the trace can see the replies that +the test rule drops. This is not evidence that the original naturally missing +replies were lost at that boundary. The natural incident's external cause +remains unconfirmed; this delivery fixes and verifies SendBox's identified +single-loss handling, not an established Apple/upstream defect. + +## Build the standalone fixture + +Use the existing Apple service without restarting or reconfiguring it: + +```bash +container build --no-cache --tag sendbox-dns-cold:local \ + test-fixtures/dns-cold-start +DIGEST="$(container image inspect sendbox-dns-cold:local | + python3 -c 'import json,sys; print(json.load(sys.stdin)[0]["index"]["digest"])')" +container image tag sendbox-dns-cold:local "sendbox-dns-cold@$DIGEST" +``` + +The image adds Python, certificates and nftables to a digest-pinned Alpine +base. Its Python entry executable is a regular file rather than a symlink. +SendBox still launches the workload non-root with NNP, seccomp and cleared +capabilities. Only a separate diagnostic control exec needs root for passive +capture or the explicit packet-loss fixture. + +```bash +python3 scripts/qualify-dns-cold-start.py \ + --bundle /usr/local/share/sendbox/guest/aarch64/bundle \ + --trust-root /usr/local/share/sendbox/guest/aarch64/release-public.key \ + --image "sendbox-dns-cold@$DIGEST" \ + --allowed-cname glb-db52c2cf8be544.github.com \ + --count 20 --trace \ + --output /absolute/path/to/new/cold-dns-results.jsonl +``` + +Use the exact, explicitly approved canonical hostname observed for your target, +not a wildcard or an automatically accepted alias. The generated fixture policy +permits only that hostname, `api.githubcopilot.com`, and TCP 443. It forwards no +GitHub/Copilot credentials and references no secrets. It is not a modification +of your project's policy. + +The runner alternates SOCKS DOMAIN CONNECT and HTTP CONNECT across 20 +sequential `sendbox run` invocations. Each VM must report a unique kernel boot +ID. The probe opens only the loopback proxy before the measured request; it +never invokes the OS resolver. After recording that first result, it checks +that `denied.example:443` and the API on port 444 remain denied. Those later +checks cannot turn a failed first request into a pass. + +JSONL records include every first-request and CONNECT latency, containment +checks, denials, cleanup status and summary percentiles. A batch header records +the unique owned-VM prefix before launch, including for interrupted batches. +`--trace` captures scoped DNS headers plus numeric resolver, link and route +metadata in the owned VM. It does not delay the workload waiting for capture +and does not retain raw packets. The runner bounds a host invocation +to 120 seconds, allows cancellation cleanup, and targets only its unique VM +names. It never stops the Apple service or touches unrelated containers. + +To verify the mitigation against controlled loss, add `--drop-first-replies`. +This opts into an additional nftables table **inside each owned test VM** that +drops exactly the first two upstream UDP replies. Its earlier input hook +cannot bypass the mandatory SendBox filter. The fixture records its drop +counter; a run cannot pass this qualification without verifying two drops and +capturing both initial A/AAAA exchanges. +Use a separate output file and report these runs as fault injection, not as +natural upstream failures. + +For patched-guest qualification, rebuild and sign the guest with a separate +test-only key and root-owned bundle/trust-root path, then pass that path and +`--trust-root-id`. Follow the +[guest artifact instructions](architecture/guest-artifact-bundles.md#reproduce-locally). +Do not replace the installed official bundle or trust root. A locally signed +development bundle is not a release attestation. + +## Direct-upstream diagnostic + +To test the Apple network/upstream path independently of SendBox, without +performing any application or authenticated model request: + +```bash +container run --rm --name sendbox-dns-upstream-UNIQUE --user 1000 \ + --entrypoint /usr/local/bin/sendbox-dns-python \ + "sendbox-dns-cold@$DIGEST" /opt/sendbox-dns/probe.py upstream --attempts 1 +``` + +This reads the VM's selected numeric nameserver and sends the measured A/AAAA +questions directly. It is a diagnostic, never a runtime fallback. The optional +`--attempts 2` labels a separate retransmission after the first three-second +receive window; its success must not be reported as first-attempt success. +Only header/question metadata and scoped CNAMEs are emitted, never packet +bytes or response bodies. + +## Regression checks + +```bash +cargo test --locked -p sendbox-egress --all-targets +PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover \ + -s test-fixtures/dns-cold-start -p 'test_*.py' +``` + +Paused-clock fixtures cover first-datagram loss, the retry boundary, the +two-send cap, overall deadline, a late successful family with a missing AAAA +reply, TCP fallback/body deadlines, cancellation in UDP and TCP, permanent +errors, failed-resolution cache isolation, broker timeout, cancellation racing +retry, and CNAME denial after retransmission. No test uses personal credentials +or customer data. + +Local checks passed on macOS and in the native aarch64 guest build environment, +including 50 repetitions of the 24-case resolver/cold-gateway suite, the +11-test standalone harness suite, dependent guest/MCP/Apple adapter tests, +release build and staged host installation, and dependency audit. +Local host Rust 1.99.1 also reported two pre-existing, untouched warnings: +deprecated `Atomic::fetch_update` in `sendbox-testkit` and an unused `BodyExt` +test import in `sendbox-mcp`. The native guest used the pinned Rust 1.93.1. diff --git a/vendor/sendbox/docs/hyperlight.md b/vendor/sendbox/docs/hyperlight.md new file mode 100644 index 0000000..c89569d --- /dev/null +++ b/vendor/sendbox/docs/hyperlight.md @@ -0,0 +1,150 @@ +# Hyperlight runtime adapter + +`crates/sendbox-runtime-hyperlight` is the production Rust +`RuntimeProvider` for the official `hyperlight-unikraft` host CLI. It is +Linux/KVM-only and deliberately models Hyperlight as a one-shot runtime. +`sendbox run --runtime hyperlight` dispatches through +`execute_authenticated_once`; it never pretends to provide the persistent guest +session used by Apple and Kata. + +## Trust and preflight + +The adapter fails preflight unless all of the following hold: + +- `/dev/kvm` opens read/write; +- the configured CLI is an absolute, single-link regular executable; +- the executable and every path component are root-owned and not group- or + world-writable, with no symlinks; +- `--version` exactly matches the configured pinned CLI version; +- the public trust key is an absolute root-owned, non-writable regular file; +- runtime state ancestors are non-symlink directories owned by root or the + runtime user and are not group/world-writable; state, container, and + invocation directories are retained through anchored directory handles; +- the signed bundle, detached signatures, release metadata, inventory, + architecture, versions, rollback floor, artifact owners, modes, and SHA-256 + digests verify; +- the configured kernel is a signed `unikraft_shell_kernel` artifact and the + configured CPIO is a signed `initrd` artifact. + +`CreateRequest.image` is the absolute signed bundle directory. OCI references +are rejected. Verified kernel and initrd descriptors are copied into a fresh +private invocation directory, so execution does not reopen an unverified +artifact pathname. + +The provider configuration is immutable across containers. `CreateRequest` +must therefore request one vCPU, the configured memory and working directory, +and no hostname, per-container mounts, environment, DNS servers, or labels. +Unsupported intent is rejected during `create` rather than silently ignored. + +## Lifecycle and execution + +`create` creates a logical handle. `start` either marks that handle running or +starts the configured initial command in a fresh micro-VM. Every direct +`BootstrapControl` exec starts another fresh micro-VM and returns its captured +stdout, stderr, exit status, timeout, or cancellation result. `Workload` exec is +rejected because the common contract requires workload execution to pass +through a persistent guest broker. + +The exact host argv is: + +```text +hyperlight-unikraft KERNEL + [--initrd INITRD] + --memory NMi --stack NMi --quiet + [--mount HOST:GUEST]... + [--net | --net-allow HOST_OR_IP... | --net-block HOST_OR_IP...] + [--port PORT]... + --exec "cd 'GUEST_DIRECTORY' && exec 'PROGRAM' 'ARG'..." +``` + +Arguments are passed directly to `execve`, never through a host shell. The +guest shell expression uses single-quote escaping. The host environment is +cleared and rebuilt as only `LANG=C` and `PATH=/usr/bin:/bin`. + +Host stdin is always null. Initial-command stdout/stderr can be consumed once +through `attach`; direct exec returns bounded captured output. The adapter does +not advertise streamed I/O or signals. `StopRequest.grace` must equal the +launch-time `ProcessOptions.termination_grace`; a different value is rejected +rather than silently applying the wrong shutdown deadline. + +Read-only mounts are copied into a new private staging directory for every +invocation. Symlinks, hard-linked files, special files, duplicate guest paths, +reserved guest paths, `:` mount ambiguity, and sources containing the runtime +staging root are rejected. Writable mounts are rejected because the CLI cannot +consume a securely anchored directory descriptor. All staging is removed on +normal exit, failure, timeout, cancellation, stop, cleanup, and dropped exec +futures; failed removals remain retryable through runtime cleanup. + +## Control and MCP compatibility + +`hyperlight-unikraft` does not provide the persistent supervisor transport +required by `sendbox-agent`. The adapter therefore advertises neither +`BrokeredExec` nor transport provisioning, and `provision_control_channel` +returns a structured transport-unavailable error. Agent planning fails before +container creation rather than receiving a fake in-process channel. + +For a purpose-built one-shot guest, `execute_authenticated_once` copies +authenticated bootstrap material into an ephemeral mount at: + +```text +/run/sendbox-control/bootstrap-material +``` + +The guest command must consume and erase that material. This is an explicit +single-launch bootstrap protocol, not a persistent MCP or supervisor channel. +Ports exist only for the lifetime of that one host process. Stdio MCP, +persistent network MCP sessions, and the full agent boundary are unsupported. + +## Network policy + +The adapter uses `HyperlightNetworkConfiguration`, not the full +`sendbox_policy::NetworkPolicy`, because the latter always carries DNS and +connection-budget semantics that the vendor CLI cannot enforce. Hyperlight can +enforce only its CLI disabled, allow-all, exact allow-list, or exact block-list +modes: + +- hostnames are normalized and must be concrete; +- exact IPv4 `/32` and IPv6 `/128` entries are accepted and canonicalized; +- wildcard names, non-host CIDRs, destination port/protocol rules, custom DNS + TTL/query budgets, and connection limits fail closed; +- blocked exact entries take precedence over identical allowed entries; +- hostname allows combined with blocked IPs, and IP allows combined with + blocked hostnames, fail closed because the CLI cannot preserve that + resolution-time precedence; +- networking with `allow_dns: false` fails closed because Hyperlight cannot + guarantee resolver traffic is disabled; +- a listen port requires an explicit enabled network policy. + +Hyperlight does not run the SendBox eBPF MCP inspector, guest eBPF bootstrap, +seccomp launcher, DNS broker, connection semaphore, or OCI environment +injection. The runtime must not be selected for a plan requiring those +features. + +## Opt-in live qualification + +The live test does nothing unless explicitly designated. Once +`SENDBOX_HYPERLIGHT_LIVE` is set, every missing variable, KVM failure, +signature failure, CLI mismatch, or guest failure is a test failure: + +```bash +sudo env \ + SENDBOX_HYPERLIGHT_LIVE=1 \ + SENDBOX_HYPERLIGHT_EXECUTABLE=/usr/local/bin/hyperlight-unikraft \ + SENDBOX_HYPERLIGHT_CLI_VERSION=0.12.0 \ + SENDBOX_HYPERLIGHT_BUNDLE=/opt/sendbox/hyperlight-bundle \ + SENDBOX_HYPERLIGHT_PUBLIC_KEY=/etc/sendbox/release-public.key \ + SENDBOX_HYPERLIGHT_KERNEL=/opt/sendbox/hyperlight-bundle/kernel \ + SENDBOX_HYPERLIGHT_INITRD=/opt/sendbox/hyperlight-bundle/rootfs.cpio \ + SENDBOX_HYPERLIGHT_TRUST_ROOT_ID=production-v1 \ + SENDBOX_HYPERLIGHT_GUEST_VERSION=0.1.0 \ + SENDBOX_HYPERLIGHT_MIN_RELEASE=1 \ + SENDBOX_HYPERLIGHT_STATE=/var/lib/sendbox-live \ + cargo test -p sendbox-runtime-hyperlight --test live \ + -- --exact live_hyperlight_launch_when_designated --nocapture +``` + +Create `SENDBOX_HYPERLIGHT_STATE` before running the command, for example: + +```bash +sudo install -d -m 0700 /var/lib/sendbox-live +``` diff --git a/vendor/sendbox/docs/installation.md b/vendor/sendbox/docs/installation.md new file mode 100644 index 0000000..99956f6 --- /dev/null +++ b/vendor/sendbox/docs/installation.md @@ -0,0 +1,401 @@ +# Installation + +Install SendBox through Homebrew or a verified release artifact, or build the +host binary from source when developing the project. + +## Requirements + +Choose a runtime before installing. Apple and Kata support interactive and +headless agent sessions; Hyperlight is an explicit one-shot provider with a +narrower capability set. + +| Scope | Dependency | Required version or setup | +|---|---|---| +| Source build | Rust | 1.93.1 (pinned by `rust-toolchain.toml`) | +| Linux source build | Native compiler and headers | `build-essential clang cmake libelf-dev libseccomp-dev libzstd-dev pkg-config zlib1g-dev` on Debian/Ubuntu | +| Apple runtime | macOS | 26 (Tahoe) or newer | +| Apple runtime | Hardware | Apple silicon | +| Apple runtime | Xcode | 26 | +| Apple runtime | Official `container` CLI and API server | Exact matching 0.10.0 or 1.7.1 pair; service already registered and running; see [source/release qualification status](apple-runtime.md#requirements) | +| Kata runtime | Linux | Bare metal or nested virtualization | +| Kata runtime | Kata Containers | 3.28 or newer | +| Kata runtime | containerd | 1.7 or newer | +| Kata runtime | nerdctl and CNI plugins | Compatible releases; access to KVM and the containerd socket | +| Linux host binary | libseccomp, libelf, zlib, and zstd runtime libraries | Distribution packages such as `libseccomp2`, `libelf1`, `zlib1g`, and `libzstd1` | +| Hyperlight runtime | Operator-pinned `hyperlight-unikraft`, signed Unikraft bundle, and KVM | See [Hyperlight](hyperlight.md) | + +The [Apple](apple-runtime.md) and [Kata](kata-containers.md) guides cover runtime +setup and preflight. Run SendBox as your normal user, not with `sudo` to work +around runtime access problems. + +### Workload image versus guest bundle + +Persistent agent sessions need both: + +- A **digest-pinned Linux workload image** for the guest architecture, containing + your agent, its runtime dependencies, certificates, shell, and development + tools. +- A **verified signed guest bundle and trust root**, containing SendBox's + security services. These do not install the agent or its development tools. + +Apple and Kata workload images must also provide the `nft` executable and its +shared-library dependencies. Mandatory egress enforcement requires a writable +cgroup v2 root, delegated memory/PID controllers, `CAP_NET_ADMIN`, `SO_MARK`, and +kernel support for nftables `socket cgroupv2`. A plain Alpine image without +`nftables` is not sufficient, even when the network policy denies all traffic. +Missing enforcement prerequisites are errors, not grounds to skip hardening. + +The execution broker resolves entrypoint and working-directory paths without +following symlinks. Use a regular executable path and match that exact argv in +the command policy. Alpine's default `/bin/sh` is a BusyBox symlink; a workload +image using that entrypoint must materialize a regular shell executable or +select another regular entrypoint with the corresponding policy. Do not disable +descriptor-resolution checks to accommodate an image. + +The production guest image is intentionally minimal: it contains no Python, +Node.js, compiler, bpftrace, or development headers. Keep bundle executables, +metadata, and trust roots in the root-owned locations described below. A public +key shipped beside a bundle is not self-authenticating; verify release +provenance before trusting it. + +## Homebrew + +The existing [mbianchidev/tap](https://github.com/mbianchidev/homebrew-tap) +uses a **formula**, not a GUI cask. + +Before installing, check the [dependency security status](#dependency-security-status). +The **v0.2.3 TLS-fix floor is necessary but no longer sufficient**. +Published v0.2.2 and earlier binaries predate +[RUSTSEC-2026-0382](https://rustsec.org/advisories/RUSTSEC-2026-0382) and +[RUSTSEC-2026-0383](https://rustsec.org/advisories/RUSTSEC-2026-0383). +Published binaries cannot inherit source fixes. The planned central updater +keeps this patched-release floor and verifies the artifacts before updating +the formula. **Central automation is pending review and activation in the +tap**; see [stable Homebrew updates](#stable-homebrew-updates). This source +change does not publish a replacement release or activate that automation. + +### Dependency security status + +The November 11, 2026 CI audit identified additional advisories in the unchanged +v0.2.5 source/release lockfile. Source now requires at least +`cap-std`/`cap-primitives` 4.0.3, `hickory-proto` 0.26.2, and `rustix` 1.1.6; +the lockfiles resolve `hickory-proto` 0.26.3: + +- [RUSTSEC-2026-0482](https://rustsec.org/advisories/RUSTSEC-2026-0482): + capability filesystem sandbox escape, fixed by `cap-primitives` 4.0.3. +- [RUSTSEC-2026-0491](https://rustsec.org/advisories/RUSTSEC-2026-0491), + [0487](https://rustsec.org/advisories/RUSTSEC-2026-0487), + [0488](https://rustsec.org/advisories/RUSTSEC-2026-0488), + [0490](https://rustsec.org/advisories/RUSTSEC-2026-0490), and + [0489](https://rustsec.org/advisories/RUSTSEC-2026-0489): + DNS allocation/panic defects fixed by `hickory-proto` 0.26.2. +- [RUSTSEC-2026-0486](https://rustsec.org/advisories/RUSTSEC-2026-0486): + an extended-attribute buffer unsoundness warning fixed by `rustix` 1.1.6. + +These are source fixes, not newly published artifacts. Rebuild and independently +review both the host and signed guest bundle in a new release; an installed +v0.2.5 binary or guest bundle does not inherit dependency updates or Apple 1.7.1 +compatibility. Do not treat an older release as patched merely because it +passes signature/digest verification or the historical TLS version floor. + +### Formula installation + +Install with: + +```bash +brew install mbianchidev/tap/sendbox +sendbox --version +sendbox --help +``` + +It reuses verified published host archives for macOS arm64, Linux x86_64, and +Linux aarch64. There is no frontend build, background service, or automatic +runtime installation. Intel Macs are not supported. The Apple runtime still +requires macOS 26+, Apple silicon, and the pinned `container` CLI; Linux needs +the Kata/KVM runtime described above. + +The binary is linked into Homebrew's `bin`; the complete release payload, +including `setup.sh`, configuration examples, and signed guest assets, lives +under `$(brew --prefix mbianchidev/tap/sendbox)/libexec`. + +### Stage the guest bundle + +Homebrew's Cellar is user-owned. **Do not pass the Cellar's guest bundle or +public key directly to `sendbox run`**, change Cellar ownership, or run Homebrew +with `sudo`. SendBox deliberately requires root-owned runtime artifacts and +trusted ancestors. A formula install does not weaken that requirement. + +Before trusting the embedded guest key, independently verify the original +archive's provenance: + +```bash +brew fetch --formula mbianchidev/tap/sendbox +gh attestation verify "$(brew --cache --formula mbianchidev/tap/sendbox)" \ + --repo mbianchidev/sendbox \ + --signer-workflow mbianchidev/sendbox/.github/workflows/release.yaml +``` + +Copy the matching payload to a **new, versioned, root-owned location**. The +following commands are an explicit administrator step, not a formula hook. +Stop if the destination already exists and inspect it instead of overwriting +an existing runtime installation: + +```bash +prefix="$(brew --prefix mbianchidev/tap/sendbox)" +version="$(sendbox --version | awk '{print $2}')" +case "$(uname -m)" in + arm64|aarch64) architecture=aarch64 ;; + x86_64) architecture=x86_64 ;; + *) printf 'Unsupported architecture\n' >&2; exit 1 ;; +esac +GUEST_DIR="/opt/sendbox/$version/guest/$architecture" +test ! -e "/opt/sendbox/$version" || { + printf 'Guest destination already exists; inspect it before continuing\n' >&2 + exit 1 +} +sudo install -d -o 0 -g 0 -m 0755 /opt/sendbox "$GUEST_DIR" +sudo cp -R "$prefix/libexec/guest/$architecture/bundle" \ + "$prefix/libexec/guest/$architecture/release-public.key" "$GUEST_DIR/" +sudo chown -R 0:0 "/opt/sendbox/$version" +sudo find "/opt/sendbox/$version" -type d -exec chmod 0755 {} + +sudo find "/opt/sendbox/$version" -type f -exec chmod 0444 {} + +sudo find "$GUEST_DIR/bundle/bin" -type f -exec chmod 0555 {} + +``` + +Ensure `/opt` and `/opt/sendbox` are real root-owned directories, not symlinks, +and are not group/world writable. Launch the CLI as your **normal user**, with +`--bundle "$GUEST_DIR/bundle"` and +`--trust-root "$GUEST_DIR/release-public.key"`. Configure the runtime separately +using the [Apple](apple-runtime.md) or [Kata](kata-containers.md) guide. + +### Upgrade and removal + +```bash +brew update +brew upgrade mbianchidev/tap/sendbox +brew uninstall mbianchidev/tap/sendbox +``` + +After upgrading, verify and stage the new version's guest bundle before using +it with the new CLI. Keep old root-owned bundles until no sessions need them; +they are outside the Cellar and are not removed by Homebrew. + +Upgrades and removal preserve project `.sendbox.yaml` files, workspace contents, +user state under `~/.sendbox`, and macOS Keychain credentials. No uninstall or +cleanup hook deletes these locations. Remove retained state and versioned +`/opt/sendbox` payloads separately only when you intentionally want to erase +them. Do not mix a manual `/usr/local/bin/sendbox` install with Homebrew or use +`brew link --overwrite`; inspect and migrate the old installation explicitly. + +## Release artifacts + +Download the matching artifact from +[Releases](https://github.com/mbianchidev/sendbox/releases): + +| Host | Artifacts | +|---|---| +| macOS arm64 | tarball, unsigned `.pkg`, unsigned `.dmg` | +| Linux x86_64 | tarball | +| Linux aarch64 | tarball | + +Each host archive and macOS installer contains the production `sendbox` binary, +configuration examples, setup helper, and matching signed guest bundle. The +release also publishes standalone guest-bundle archives. + +Verify GitHub provenance before trusting the embedded guest public key, then +verify the adjacent checksum: + +```bash +gh attestation verify sendbox--.tar.gz \ + -R mbianchidev/sendbox +shasum -a 256 -c sendbox--.tar.gz.sha256 +``` + +Install a verified tarball into a root-owned runtime location: + +```bash +sudo tar xzf sendbox--.tar.gz -C /opt +sudo install -m 0755 /opt/sendbox--/sendbox \ + /usr/local/bin/sendbox +``` + +Or install the verified macOS package: + +```bash +sudo installer -pkg sendbox--macos-arm64.pkg -target / +``` + +Run `/opt/sendbox--/setup.sh` as your normal user after +installing a tarball. The root-owned extraction preserves the runtime trust +boundary for the bundled guest artifacts; do not copy them into a user-writable +directory before launch. + +Production guest bundles provide static-musl guest and execution binaries, +strict CO-RE BPF objects, signed manifests, inventory, SBOM metadata, +deterministic rootfs tarballs, and minimal scratch OCI images for Linux x86_64 +and arm64. See [guest artifact bundles](architecture/guest-artifact-bundles.md) +for details. + +## Publishing a release + +Releases are triggered by pushing a `vX.Y.Z` tag, not by `make release`, which +only builds locally. From a clean checkout with `origin` pointing to +`mbianchidev/sendbox`, run: + +```bash +./scripts/release.sh 0.2.0 +``` + +The script requires Bash, Git, Python 3.11 or newer, and an authenticated GitHub +CLI account with permission to push branches and tags, merge PRs, and rerun +Actions workflows. Cargo is also required when preparing a new version bump. +For a new release, pass a stable `X.Y.Z` version greater than the version on +`main`; a leading `v` is also accepted. + +Git and GitHub CLI pagers are disabled for the script and its subprocesses, so +output never pauses for pager input and the script exits on its own after +printing the release URL. + +After its preflight safety checks, the script switches the invoking checkout +to `main` and pulls `origin/main` with `--ff-only` before inspecting or resuming +a release. A failed pull or divergent local `main` stops the script before any +release operations. If `main` is checked out in another Git worktree, run from +that checkout instead; the script never forces a second checkout of `main`. + +For a new release, it creates an isolated worktree from updated `origin/main`, +updates `[workspace.package].version` and the CLI version assertion, and +refreshes every committed Cargo lockfile, including standalone fuzz, spike, +and qualification workspaces. Unrelated dependencies are not upgraded. + +It then opens a version-bump PR, waits for CI checks to pass, and merges without +bypassing branch protections. An annotated tag is pushed at the PR's merged +`main` commit, after verifying that its Cargo version matches the tag. The +invoking checkout stays on `main` at its startup pull, while the original +feature branch is unchanged and version edits remain in the isolated worktree. + +The script watches the [Release workflow](https://github.com/mbianchidev/sendbox/actions/workflows/release.yaml), +which publishes GitHub assets and GHCR artifacts, including macOS installers, +Linux archives, and signed guest bundles. The required release-signing secret +is already configured; no local signing key is needed. + +Native macOS arm64 and Linux x86_64/aarch64 CLI tests and builds run in parallel +with the signed guest builds. Each packaging job waits for both producers and +verifies the checksum and executable mode of its matching, commit-specific CLI +archive before combining those exact tested bytes with the signed guest payload. +The internal CLI archives retain the default Actions artifact lifetime and are +excluded from published assets. Signing, clean guest builds, package checksums, +release provenance, and GHCR publication are unchanged. Homebrew verification +and formula updates are owned by the tap, as described below. + +Generic build and packaging hosts follow `ubuntu-latest` and `macos-latest` +where compatible. Linux CLI producers retain Ubuntu 24.04 to avoid raising +their glibc baseline when the alias advances; native arm64 jobs retain +`ubuntu-24.04-arm` because no supported floating arm64 Ubuntu alias exists. +The macOS producer pins and verifies the existing arm64 binary deployment +floor at macOS 11.0 independently of the build image. The Apple runtime still +requires macOS 26 or newer. + +On failure, the script stops and preserves any branch, PR, or tag already +created. Resolve the underlying failure, then run the **same command with the +same version** to resume. It reuses a committed `release/vX.Y.Z` branch and its +open or merged version-bump PR rather than creating duplicates. Uncommitted +release files are retained in the temporary worktree whose path is printed for +recovery; inspect and finish that work before retrying. + +If the tag already exists, the script verifies its Cargo version and ancestry +on `origin/main`, then watches its existing Release workflow. Failed runs rerun +only failed jobs and their dependents, retaining successful build outputs. +Cancelled or otherwise unsuccessful completed runs restart the whole workflow. +The script waits for the new attempt before watching it; active runs are only +watched, and successful runs are not restarted. Retries remain subject to +GitHub's rerun window and artifact retention. + +Reruns use the original tag's commit and workflow definition, not newer changes +on `main`. If a fix changes source or workflow code, publish a new version from +the fixed commit. Recovering a failed, unpublished tag instead requires an +explicit maintainer decision outside this script; never move a published tag. + +A local tag not yet pushed is published unchanged. Existing tags are never +replaced, and conflicting local and remote tags or release branches require +manual inspection. Check registration, merge completion, release run discovery, +and retry registration each have a ten-minute timeout. + +### Stable Homebrew updates + +Homebrew updates are owned by +[mbianchidev/homebrew-tap](https://github.com/mbianchidev/homebrew-tap), not the +SendBox Release workflow. SendBox continues to publish its host archives, +signed guest bundles, adjacent SHA-256 files, and tag-bound release-workflow +attestations. It does not push tap branches or create tap PRs, and requires no +tap-write secret, cross-repository token, or new credential. + +**The central updater is pending review and activation in the tap.** Once +enabled, it checks included projects' stable releases hourly and downloads the +existing SendBox archives for macOS arm64, Linux x86_64, and Linux aarch64, plus +their checksum files. It recomputes SHA-256 against GitHub's asset digests and +the adjacent published checksums, and verifies attestations from +`mbianchidev/sendbox/.github/workflows/release.yaml` bound to `refs/tags/vX.Y.Z` +on GitHub-hosted runners. It does not rebuild the CLI or guest bundles. + +Only a published, non-draft, non-prerelease `vX.Y.Z` matching GitHub's latest +stable release at or above the patched-release floor v0.2.3 is eligible. +Older releases, a newer formula, and a stable release that supersedes an +in-flight verification cannot downgrade it. Prereleases do not update the +stable formula, GitHub's latest release, or the GHCR `latest` tag. + +The tap prepares one verified release-only batch PR and explicitly runs its +complete native CI. A separate trusted-default-branch workflow automatically +merges eligible release-only bot updates only after CI and review guards pass. +Updates normally become available within an hour of artifact publication, +subject to those gates. Implementation PRs still require human review and +merge; source changes alone do not enable central automation. + +After the source and tap implementation PRs are approved and merged and the +central updater is enabled, revoke the retired SendBox tap SSH deploy key and +remove its old Actions secret. Older tag reruns retain their original workflow +definition; retiring that credential prevents them from writing to the tap. +Keep the release-signing secret configured. + +If an update is blocked, inspect the central updater's Actions run and update +PR in the tap, resolve the verification, CI, or review failure, then rerun the +applicable tap workflow. Do not run `scripts/release.sh`, create another tag, +move an existing tag, or republish artifacts just to retry a formula update. + +## Build from source + +```bash +git clone https://github.com/mbianchidev/sendbox.git +cd sendbox +make install +``` + +Source installs require a separately attested signed guest bundle and trust +root; tagged host artifacts already include the matching pair. + +For an interactive runtime preflight and configuration flow: + +```bash +./setup.sh +``` + +Kata installation and containerd configuration are documented in the +[Kata Containers guide](kata-containers.md). + +## Unsigned macOS packages + +The `.pkg` and `.dmg` are not Apple-signed or notarized. Verify their GitHub +attestation and checksum before installation. If Gatekeeper blocks a verified +download, approve that artifact in Finder or System Settings, or remove only its +quarantine attribute: + +```bash +xattr -dr com.apple.quarantine sendbox--macos-arm64.pkg +``` + +Do not disable Gatekeeper globally. The package removes quarantine from the +installed `/usr/local/bin/sendbox` only after the installer has been approved. +The DMG `install.sh` replaces the shared payload through a fresh staging +directory, removes stale upgrade files, and enforces root ownership with `0555` +guest executables and `0444` bundle metadata and trust roots. + +Continue with the [configuration guide](configuration.md) after installation. diff --git a/vendor/sendbox/docs/integrations.md b/vendor/sendbox/docs/integrations.md new file mode 100644 index 0000000..88cb9e3 --- /dev/null +++ b/vendor/sendbox/docs/integrations.md @@ -0,0 +1,173 @@ +# Integrating SendBox into your workflow + +SendBox's integration surface is a CLI, YAML policy, and standard agent/MCP +configuration. The controls below are built in; connecting them to your editor, +job runner, or orchestration service is a workflow you compose, not a separate +managed SendBox service. + +## Coding agents and model providers + +Select a profile when creating project configuration: + +```bash +sendbox init --project . --agent codex +``` + +Profiles exist for Moguri, Claude Code, Codex CLI, GitHub Copilot CLI, Gemini CLI, +and OpenCode. Custom CLI programs use `--agent custom` and explicit +command/network rules. Install the agent in your digest-pinned Linux workload +image, then pass its absolute guest executable path after `sendbox run ... --`. + +Profiles admit initial inference endpoints, not every possible provider or +plugin. For example, an OpenCode session using a separate model provider needs +that provider's exact endpoints in `policy.network.allowed_domains`. +Authentication and telemetry may require additional hosts too. + +Store API keys with `sendbox secrets add NAME` and reference only the keys the +workload needs in `secrets`. Copilot credential forwarding is independent of +GitHub repository credentials; selecting another agent disables unrelated +Copilot forwarding. + +See [CLI agents](cli-agents.md) for profile endpoints, authentication, proxy +compatibility, and native sandbox settings. + +## MCP tools: local servers and remote services + +Apple and Kata sessions support both local stdio servers and remote Streamable +HTTP servers. This lets an agent use project tools, documentation search, or +repository services without treating every tool exposed by a server as allowed. + +For a preinstalled local server, merge a server definition into your policy: + +```yaml +policy: + boundaries: + enabled: true + tool_calls: + servers: + files: + transport: stdio + command: [/usr/local/bin/project-mcp-server] + tools: + default_action: deny + allowlist: [read_file, list_directory] +``` + +Replace the example executable and tool names with your server's actual +interface. Configure the agent to launch it through the trusted broker: + +```json +{ + "mcpServers": { + "files": { + "command": "/run/sendbox-boundary/mcp-broker", + "args": ["--", "/usr/local/bin/project-mcp-server"] + } + } +} +``` + +The JSON container above fits Claude-style configuration; other agents use +their own native formats. The broker matches exact server identities, filters +discovery, and checks calls against the signed tool policy. + +Remote services use a trusted loopback gateway rather than direct upstream +URLs in the agent configuration. Bearer credentials can be delivered only to +the gateway, separate from workload secrets. Legacy HTTP+SSE, OAuth helpers, and +unapproved launchers are not supported fallback paths. + +See [native MCP configuration](cli-agents.md#native-mcp-configuration) and +[MCP inspection](mcp-inspection.md) for complete stdio, remote, authentication, +and audit examples. + +## GitHub: repository access and bounded writes + +For normal Git workflows, SendBox can forward repository-scoped GitHub +credentials through authenticated guest delivery and guard selected-repository +pushes and pulls by branch. SSH uses a trusted wrapper and narrowly staged key +material rather than mounting your host SSH directory. + +For automation that should not hold a GitHub write token inside the VM, +**Safe Outputs** provides a different path: + +1. The agent declares an allowed write through a trusted MCP recorder. +2. The guest seals the bounded artifact, and the runtime is torn down. +3. The host verifies the artifact; apply mode then resolves a dedicated write + token and executes only admitted operations. + +Safe Outputs is optional, disabled by default, and defaults to staged preview +when enabled. It requires exact repository/operation limits and cannot be +combined with ordinary GitHub credential or SSH forwarding. It is not a general +GitHub API pass-through, and asset uploads are unsupported. + +See [GitHub configuration](configuration.md#github-and-mcp-boundaries) and +[Safe Outputs](architecture/safe-outputs.md). Keep GitHub server-side rulesets +enabled; local Git wrappers do not govern alternate clients or direct API writes. + +## npm and private registries + +Enable `policy.packages.enabled` to route supported npm traffic through a +trusted inspection proxy. It quarantines artifacts, checks identity and +integrity, evaluates configured signature/provenance requirements, and applies +static finding policies before releasing package bytes. + +Private registry credentials belong in the vault and are referenced by +`policy.packages.registries[].credential_secret`, not workload `secrets`. +The current implementation supports exactly one npm registry; it is not yet a +universal package-manager firewall. Lifecycle scripts are disabled. + +See the [package supply-chain guide](package-supply-chain.md) for registry +configuration, findings, exceptions, caching, and report commands. + +## VS Code and devcontainer tooling + +Generate a standard devcontainer spec from native project analysis: + +```bash +sendbox analyze --project . --json +sendbox devcontainer generate --project . +``` + +The generated `.devcontainer/devcontainer.json` can be consumed by tools +supporting the [Dev Container Specification](https://containers.dev/overview). +Use it to share tooling setup with teammates or editor workflows. + +**A devcontainer spec is not the SendBox runtime boundary.** Opening the +generated configuration in another tool does not automatically install the +signed guest services, enforce SendBox policy, or give each workload a dedicated +kernel. That depends on the runtime used to launch it. + +See the [CLI reference](cli-reference.md) for generation options. + +## CI, scripts, and custom orchestrators + +Use headless `sendbox run` on a runner with a prepared runtime, verified guest +artifacts, and access to the selected virtualization device/control plane. +Do not assume an arbitrary hosted CI runner supports nested virtualization. + +```bash +sendbox policy validate --config .sendbox.yaml + +# Set these to your prepared image and verified, root-owned guest artifacts. +sendbox run --json \ + --config .sendbox.yaml \ + --image "$WORKLOAD_IMAGE" \ + --bundle "$GUEST_DIR/bundle" \ + --trust-root "$GUEST_DIR/release-public.key" \ + -- /usr/local/bin/your-agent --your-headless-option +``` + +Replace the executable and headless option with your agent's actual interface, +and admit that command in policy. `--json` emits machine-readable output, +result, and error events; it cannot be combined with `--interactive`. Binary +workload output is hex encoded. Preserve the process exit status when wrapping +the command in a script. + +SendBox supplies session isolation and lifecycle controls, not runner +provisioning, a remote execution API, or a multi-tenant scheduler. Your +orchestrator owns scheduling, credentials, artifact collection, and workspace +allocation. Use separate workspaces for concurrent jobs rather than allowing +agents to race on the same writable checkout. + +See [CLI reference](cli-reference.md), [qualification](qualification.md), and +[session security lifecycle](architecture/session-security-lifecycle.md). diff --git a/vendor/sendbox/docs/interactive-sessions.md b/vendor/sendbox/docs/interactive-sessions.md new file mode 100644 index 0000000..8dbb2c3 --- /dev/null +++ b/vendor/sendbox/docs/interactive-sessions.md @@ -0,0 +1,88 @@ +# Interactive terminal sessions + +`sendbox run --interactive` runs a workload on a pseudoterminal inside the +sandbox and forwards the current terminal's keystrokes and window size. Terminal +agents such as GitHub Copilot CLI, Claude Code, Codex, and Gemini can therefore +render and accept input normally. + +```bash +sendbox run --interactive \ + --config .sendbox.yaml \ + --runtime kata \ + --image registry.example/workload@sha256: \ + --bundle /usr/local/share/sendbox/guest/x86_64/bundle \ + --trust-root /usr/local/share/sendbox/guest/x86_64/release-public.key \ + -- /usr/bin/copilot +``` + +Tarball users can point the bundle and trust-root flags at +`guest//` inside the extracted release directory. A bundled +public key is not self-authenticating; trust it only after verifying the host or +standalone guest archive attestation. + +## Behavior + +Keystrokes ride the same authenticated control channel as workload output, so +they inherit its message authentication, replay protection, and session +binding. No additional port, socket, or privilege is introduced. + +The launcher grants a bounded window of 64 input chunks, each at most 4 KiB, and +the CLI stops reading stdin when that credit is exhausted. A workload that +temporarily stops reading therefore applies backpressure instead of losing +pasted bytes. + +Standard error remains merged into the controlling terminal by default. Use +`--separate-stderr` when diagnostics need their own stream while remaining a +TTY: + +```bash +sendbox run --interactive --separate-stderr \ + --config .sendbox.yaml \ + --runtime kata \ + --image registry.example/workload@sha256: \ + --bundle /usr/local/share/sendbox/guest/x86_64/bundle \ + --trust-root /usr/local/share/sendbox/guest/x86_64/release-public.key \ + -- /usr/bin/copilot +``` + +## Requirements and limitations + +- Both stdin and stdout must be a terminal and `sendbox` must be in that + terminal's foreground process group. Otherwise the run fails instead of + silently falling back to a workload with no input. +- `--interactive` cannot be combined with `--json`; machine-readable output and + a raw terminal are mutually exclusive. +- Only the `apple` and `kata` runtimes provide a terminal. `hyperlight` rejects + `--interactive` before anything is created or started. +- `Ctrl-C`, `Ctrl-Z`, and `Ctrl-D` are delivered to the workload's terminal, not + to `sendbox`. Use the agent's own quit command to end the session. +- The host `TERM` is authoritative for the workload and replaces any configured + `TERM`. +- Terminal output merges stdout and stderr by default. `--separate-stderr` gives + file descriptor 2 a second, non-controlling pseudoterminal and reports it as + stderr. Both descriptors remain TTYs, but ordering between stdout and stderr + is no longer strict, so the flag is unsuitable for TUIs that draw through + file descriptor 2. +- `--separate-stderr` requires `--interactive` and consumes one additional + pseudoterminal pair per session. +- Interactive input is lossless within a bounded 64 x 4 KiB credit window. End + of file is outside the credit budget and remains ordered behind preceding + input. +- Window size changes are tracked through `SIGWINCH` for as long as the run + lasts. + +## Troubleshooting + +| Symptom | Cause | Fix | +|---|---|---| +| `--interactive requires a terminal but stdin is not one` | `sendbox` is being piped or run from a job runner | Run it from a terminal, or drop `--interactive` | +| `--interactive requires the foreground process group` | Started with `&` or under a job-control shell in the background | Bring the job to the foreground | +| `the hyperlight runtime cannot provide an interactive terminal` | `--runtime hyperlight` | Use `--runtime apple` or `--runtime kata` | +| `interactive execution needs a controlling terminal, but the command policy denies: ioctl` | `policy.boundaries.syscalls.additional_denylist` blocks terminal syscalls | Remove `ioctl`, `setsid`, `dup2`, and `dup3` from the denylist, or run without `--interactive` | +| The guest rejects `agent.launch.interactive.v2` | The host is using an older guest bundle that predates credit flow control | Install the guest bundle shipped with the same SendBox release | +| Pseudoterminal allocation reports resource exhaustion | Concurrent interactive sessions reached the host PTY limit | Reduce concurrency or inspect `/proc/sys/kernel/pty/max` and `/proc/sys/kernel/pty/nr` | +| stdout and stderr appear out of order | `--separate-stderr` uses independent PTY buffers | Remove `--separate-stderr` for a single strictly ordered terminal stream | +| The agent renders as garbled boxes | The guest image has no terminfo entry for the host `TERM` | Set `TERM=xterm-256color` before running | + +See the [interactive terminal architecture](architecture/interactive-terminal.md) +for negotiation, flow-control rules, and qualification evidence. diff --git a/vendor/sendbox/docs/kata-containers.md b/vendor/sendbox/docs/kata-containers.md new file mode 100644 index 0000000..f1cda1e --- /dev/null +++ b/vendor/sendbox/docs/kata-containers.md @@ -0,0 +1,182 @@ +# Kata Containers Runtime + +## Authenticated runtime path + +The production CLI exposes the authenticated runtime command: + +```bash +sendbox run \ + --config /absolute/path/.sendbox.yaml \ + --runtime kata \ + --image registry.example/workload@sha256: \ + --bundle /absolute/path/to/verified-bundle \ + --trust-root /absolute/path/to/release-public.key \ + --trust-root-id external-release-root \ + --minimum-release-sequence 1 \ + -- /usr/bin/printf '%s\n' hello +``` + +The command after `--` is an exact argv vector. The guest executable and working +directory must be absolute; no shell parses or joins the arguments. `--json` +emits deterministic `output`, `result`, and `error` records. Binary output is +hex encoded. The process exit code is propagated when broker cleanup is +complete; cancellation uses 130. + +The workload image must be digest-pinned. The bundle and trust-root paths are +host paths, and the project path in the configuration must be absolute and +owned by a non-root uid/gid. The bundle must contain the signed static +`bin/sendbox-guest` and `bin/sendbox-exec-launcher` artifacts produced by +`packaging/guest/Dockerfile`. + +Before image pull or VM launch, the command resolves one immutable signed +boundary plan. Configured secrets, repository-scoped GitHub/Copilot/SSH +credentials, the native Git guard, authenticated MCP stdio inspection, and +restrictive DNS/egress policy are composed into authenticated guest bootstrap. +Restrictive egress binds the execution broker to the delegated +`/sys/fs/cgroup/sendbox//agent` hierarchy and starts Exec only after +the guest DNS/SOCKS5 gateway is ready. + +SendBox can run sandboxes on Linux through [Kata Containers](https://katacontainers.io/), using `nerdctl` to create each workload with the Kata containerd shim. The agent runs in a dedicated hardware-virtualized guest rather than sharing the host kernel. + +## Requirements + +- Linux on bare metal or a VM with nested virtualization +- Rust 1.93.1 +- Kata Containers 3.28 or newer +- containerd 1.7 or newer +- CNI plugins +- nerdctl +- Access to `/dev/kvm` and the containerd socket + +Verify the host before running SendBox: + +```bash +kata-runtime check +nerdctl info +nerdctl run --rm --runtime io.containerd.kata.v2 \ + docker.io/library/busybox:latest uname -a +``` + +Do not run SendBox with `sudo` merely to reach containerd. Grant the user access to the containerd socket or configure a rootless containerd installation with access to the host virtualization device. + +## Configure containerd + +Register the Kata shim as a containerd runtime. For containerd 2.x: + +```toml +version = 3 + +[plugins."io.containerd.cri.v1.runtime".containerd.runtimes.kata] + runtime_type = "io.containerd.kata.v2" + privileged_without_host_devices = true +``` + +For containerd 1.7: + +```toml +version = 2 + +[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata] + runtime_type = "io.containerd.kata.v2" + privileged_without_host_devices = true +``` + +Restart containerd after changing its configuration. The default SendBox handler is the shim runtime type `io.containerd.kata.v2`; custom shims such as `io.containerd.kata-qemu.v2` are also supported. + +## SendBox configuration + +```yaml +runtime: + provider: kata + kata: + executable: nerdctl + runtime_handler: io.containerd.kata.v2 + namespace: sendbox + # address: /run/containerd/containerd.sock + # snapshotter: overlayfs + # configuration_path: /etc/kata-containers/configuration.toml +``` + +Use the explicit runtime and all trust inputs shown above: + +```bash +sendbox run --config .sendbox.yaml --runtime kata \ + --image "$IMAGE_DIGEST" --bundle "$BUNDLE" --trust-root "$TRUST_ROOT" \ + -- /usr/bin/true +``` + +`runtime.provider: auto` selects Apple Containerization on supported macOS hosts and Kata Containers on Linux. + +### Kata options + +| Key | Default | Description | +|---|---|---| +| `executable` | `nerdctl` | nerdctl executable name or absolute path | +| `runtime_handler` | `io.containerd.kata.v2` | containerd runtime v2 handler | +| `namespace` | `sendbox` | containerd namespace used for SendBox containers | +| `address` | nerdctl default | containerd socket address | +| `snapshotter` | nerdctl default | containerd snapshotter | +| `configuration_path` | Kata default | Absolute Kata configuration path on the containerd host | + +`configuration_path` is passed as the supported `io.katacontainers.config_path` OCI annotation. The file must exist on the containerd host and be readable by the Kata shim. + +## Runtime behavior + +- Kata and Apple encode the same typed inner guest-bootstrap document. Kata wraps + that document with its provider-specific trust-root injection envelope before + delivering both files to the VM. +- CPU, memory, hostname, DNS, working directory, image, command, and bind mounts map to `nerdctl run`. +- `disk_size_mb` is delegated to the configured containerd snapshotter because nerdctl does not expose a portable per-container writable-layer quota. +- Single-line environment values are written to a mode `0600` temporary env file, passed with `--env-file`, and deleted immediately after container creation. Multi-line values are inherited by key through the nerdctl client environment, so secret values never appear in argv. +- SendBox adds `NET_ADMIN` only when the configured firewall script needs it. +- eBPF MCP inspection adds `BPF`, `PERFMON`, and `SYS_PTRACE`; the guest kernel must expose BTF and the image must support `bpftrace`. +- Firewall and MCP startup scripts remain best-effort and log explicit failures. +- Boundary mode runs the trusted bootstrap with the Kata VM's PID namespace, + temporarily adds the BPF/sysctl capabilities it needs, and disables the outer + container seccomp profile. SendBox then waits for the boundary readiness + marker; the generated inner seccomp launcher and non-root UID constrain the + agent and every later `nerdctl exec`. + +## Secrets on Linux + +The `sendbox secrets` commands use a file-backed store under `~/.sendbox/secrets`. Directories are mode `0700`, secret files are mode `0600`, and filenames are encoded so secret names cannot escape the store. Proxy credential mode currently requires Apple's Network framework; use environment credential injection on Linux. + +## Troubleshooting + +**`permission denied` from `nerdctl info`** + +Configure access to the containerd socket or a rootless containerd service. Also verify access to `/dev/kvm`. + +**`failed to create shim task` or runtime not found** + +Confirm `containerd-shim-kata-v2` is installed in containerd's executable path and that `runtime_handler` matches the installed shim. + +**No network in the guest** + +Install CNI plugins and verify nerdctl can run a normal container with the default bridge network before testing Kata. + +**Custom Kata configuration is ignored** + +Use an absolute `configuration_path` that exists on the containerd host. Check the Kata shim logs with: + +```bash +journalctl -t kata +``` + +Hosted GitHub Actions runners do not expose nested virtualization. Normal CI +compiles Linux and runs the fake-nerdctl/authenticated-channel conformance tests. +Live qualification is a separate required self-hosted gate: + +```bash +cargo build --workspace --release +SENDBOX_KATA_LIVE=1 \ +SENDBOX_KATA_CONFIG=/absolute/path/.sendbox.yaml \ +SENDBOX_KATA_IMAGE=registry.example/workload@sha256: \ +SENDBOX_KATA_BUNDLE=/absolute/path/to/bundle \ +SENDBOX_KATA_TRUST_ROOT=/absolute/path/to/release-public.key \ +./scripts/qualify-kata-live.sh +``` + +The script fails when any input, KVM, containerd, Kata, readiness, brokered +execution, exit propagation, or cleanup proof is missing. It never reports a +successful skip. diff --git a/vendor/sendbox/docs/mcp-inspection.md b/vendor/sendbox/docs/mcp-inspection.md new file mode 100644 index 0000000..78fa621 --- /dev/null +++ b/vendor/sendbox/docs/mcp-inspection.md @@ -0,0 +1,270 @@ +# MCP boundary and inspection + +SendBox provides one fail-closed MCP authorization model for exact stdio +servers and trusted Streamable HTTP upstreams. Optional inspection records are +an observation by-product; they are not an authorization mechanism. + +## Configure server and tool policy + +`policy.boundaries.tool_calls.servers` maps stable policy IDs to exact transport +identities and independent tool policies: + +```yaml +policy: + boundaries: + enabled: true + tool_calls: + max_frame_bytes: 1048576 + servers: + filesystem: + transport: stdio + command: + - /usr/local/bin/node + - /usr/local/lib/node_modules/@modelcontextprotocol/server-filesystem/dist/index.js + - /workspaces/my-project + tools: + default_action: deny + allowlist: [read_file, list_directory] + denylist: ["write_*", "delete_*"] + + remote-docs: + transport: streamable_http + url: https://mcp.example.com/mcp + tools: + default_action: deny + allowlist: [search_docs, get_document] + denylist: ["create_*", "update_*", "delete_*"] + http: + allow_redirects: false + max_request_bytes: 1048576 + max_response_bytes: 1048576 + request_timeout_seconds: 30 + connect_timeout_seconds: 10 + idle_timeout_seconds: 30 + max_events: 1024 + max_concurrent_requests: 32 + authorization: + bearer_secret: REMOTE_MCP_TOKEN +``` + +Server IDs are stable policy identities, not caller-provided authorization +claims. Exact stdio argv or an exact deterministic gateway route selects the +policy. Unknown servers, ambiguous identities, changed commands or endpoints, +invalid transport metadata, and audit failures deny. + +Tool deny rules win, then allow rules, then `default_action`. Use +`default_action: deny` to require explicit tool admission. SendBox filters every +`tools/list` page and checks `tools/call` again, so discovery is never an +authorization grant. + +All policy and configuration structs reject unknown YAML fields. Stdio and HTTP +server entries are tagged by `transport` and cannot mix transport-specific +fields. + +## Bind project MCP definitions + +SendBox validates `.mcp.json`, `.vscode/mcp.json`, +`.github/copilot/mcp.json`, `.cursor/mcp.json`, `.claude/mcp.json`, +`opencode.json`, `opencode.jsonc`, `.codex/config.toml`, and +`.gemini/settings.json`. Native OpenCode `local`/`remote`, Codex TOML, and +Gemini `httpUrl` definitions are normalized into the same policy. OpenCode +remote definitions require `oauth: false`; client-side credentials, environment +overrides, and header helpers remain forbidden. See [CLI agents](cli-agents.md). +Project aliases do not affect policy selection and project files cannot select a +SendBox policy ID. + +Stdio definitions must invoke the installed broker followed by one exact +approved command: + +```json +{ + "mcpServers": { + "files": { + "type": "stdio", + "command": "/run/sendbox-boundary/mcp-broker", + "args": [ + "--", + "/usr/local/bin/node", + "/usr/local/lib/node_modules/@modelcontextprotocol/server-filesystem/dist/index.js", + "/workspaces/my-project" + ] + } + } +} +``` + +Remote definitions must select the exact loopback route derived from the server +ID: + +```json +{ + "mcpServers": { + "docs": { + "type": "streamable-http", + "url": "http://127.0.0.1:15082/mcp/remote-docs" + } + } +} +``` + +Direct upstream URLs, custom headers or credentials, URL drift, query strings, +fragments, user information, env/cwd overrides, wrapper chains, unknown routes, +and unsupported transports are rejected. + +## Safe Outputs gateway + +Safe Outputs uses the same exact-command broker admission but terminates at a +root-owned guest recorder rather than an untrusted server process. Configure +the client command as: + +```text +/run/sendbox-boundary/mcp-broker -- /run/sendbox-boundary/safe-outputs-mcp +``` + +In hierarchical mode, the host reserves the `sendbox-safe-outputs` server ID and +derives an exact default-deny stdio policy containing only enabled Safe Outputs +tools. Legacy flat policies retain compatibility through exact command and tool +augmentation. Configuration cannot override the reserved policy. + +Recorder framing, schemas, sanitization, repository targets, counts, artifact +size, sealing, and one-time collection remain independent of optional MCP +observation. See [architecture/safe-outputs.md](architecture/safe-outputs.md). + +## HTTP transport modes + +- `streamable_http` implements modern Streamable HTTP with POST-only, + request-scoped JSON or SSE responses. Session IDs, GET streams, DELETE, and + reconnect event IDs are rejected. +- `streamable_http_2025` is an explicit compatibility mode for issued session + IDs, GET/SSE, DELETE, and validated `Last-Event-ID` reconnects. Sessions and + observed event IDs are bound to one server and gateway instance. +- Legacy 2024 HTTP+SSE and WebSocket upgrades are unsupported and fail closed. + +For either supported HTTP mode, the root-owned gateway: + +- accepts only the canonical `/mcp/` loopback route; +- validates JSON-RPC, status, content type, protocol metadata, response IDs, + sizes, concurrency, timeouts, and SSE event limits; +- verifies TLS chains, validity, hostname, and SNI with system roots plus any + configured PEM roots; +- resolves each connection independently, classifies every address, and dials + the exact validated address with the egress mark; +- disables redirects by default and permits only exact configured redirect + targets when enabled; +- strips hop-by-hop, cookie, and unapproved headers; +- has no direct-upstream fallback. + +Plaintext HTTP is limited to loopback endpoints with +`allow_plaintext_local: true`. Restricted literal addresses require +`allow_private_networks: true`; metadata addresses remain denied. + +Remote MCP forces authenticated egress enforcement. Agent processes can reach +only the loopback gateway route, configured upstream names are reserved from the +normal CONNECT broker, and direct-IP CONNECT is disabled while remote MCP is +active. TLS uprobes remain observation-only and never authorize traffic. + +## Gateway credentials + +`http.allowed_auth_methods` admits `none` and/or `bearer`; the selected +configuration must match the allowlist. Unsupported methods, empty lists, and +duplicates are rejected. Existing HTTP policies default to those two supported +methods for compatibility. + +Hierarchical stdio policies expose no workload credentials unless they declare +`authorization: {method: environment, secrets: [MCP_TOKEN]}`. References must +already be admitted for workload delivery, and only that server receives those +values. Unknown methods and missing references fail closed. Legacy flat +policies retain their global environment compatibility. + +`http.authorization.bearer_secret` names a value in the SendBox vault. Store it +with the normal secret CLI: + +```bash +sendbox secrets add REMOTE_MCP_TOKEN +``` + +Gateway credential names are signed separately from top-level `secrets` and +must not overlap them. Values are resolved by the host, delivered only through +authenticated root-owned bootstrap material, zeroized, and injected only into +the configured upstream request. They never enter the workload environment or +project MCP file. + +## Inspect the resolved boundary + +Inspect policy without launching a sandbox: + +```bash +sendbox boundary inspect --config .sendbox.yaml +sendbox boundary inspect --config .sendbox.yaml --json +``` + +The output identifies hierarchical versus legacy mode and reports each server's +ID, transport, fingerprint, exact command or normalized endpoint, deterministic +local gateway route, effective tool rules, HTTP limits, TLS settings, redirect +policy, and credential reference names. Secret values are never shown. + +## Mandatory audit and optional observation + +Stdio and HTTP authorization share a mandatory append-only JSONL audit path: + +```text +/var/log/sendbox/mcp-audit.jsonl +``` + +Records include stable server identity, transport and fingerprint, normalized +endpoint where applicable, method/tool, outcome, rule/reason, status, byte +counts, timing, and hashed session identity. They exclude commands, tool +arguments, payloads, environment values, and credentials. The trusted service +writes a record before an action takes effect; write failure is terminal. + +Optional stdio observation can be enabled separately: + +```yaml +observability: + mcp_inspection: + enabled: true + transports: [stdio] + capture_payloads: false + max_payload_bytes: 16384 + log_path: /var/log/sendbox/mcp-trace.log +``` + +Inspection requires `policy.boundaries.enabled: true`. Paths outside +`/var/log/sendbox`, duplicate transports, and unsupported transports are +rejected. Payload text is omitted unless capture is explicitly enabled and is +then credential-masked before truncation to the configured bound. The observer +masks admitted workload credentials and recognizable credential fields without +changing forwarded MCP frames or authentication. JSON escapes are decoded +before masking. Non-credential private content can still be captured; leave +capture disabled unless it is needed. See +[credential masking](cli-agents.md#credential-masking) for limits. + +The parser retains compatibility with legacy Swift trace lines: + +```text +SENDBOX_MCPtspidcommtransportdirectionpayload +``` + +```bash +sendbox mcp parse /var/log/sendbox/mcp-trace.log +sendbox mcp report /var/log/sendbox/mcp-trace.log --json +``` + +Apple and Kata support MCP composition. Hyperlight rejects it. + +## Deprecated flat policy + +The old flat stdio fields remain as an explicit compatibility mode: + +```yaml +tool_calls: + allowed_server_commands: + - [/usr/local/bin/github-mcp-server, stdio] + default_action: deny + allowlist: [search_code] + denylist: ["delete_*"] +``` + +Flat fields cannot be mixed with `servers`. SendBox synthesizes deterministic +legacy IDs from command fingerprints and exposes the compatibility mode in +boundary inspection. New configurations should use hierarchical `servers`. diff --git a/vendor/sendbox/docs/migration/secrets.md b/vendor/sendbox/docs/migration/secrets.md new file mode 100644 index 0000000..ed16668 --- /dev/null +++ b/vendor/sendbox/docs/migration/secrets.md @@ -0,0 +1,53 @@ +# Secret Store Migration + +## Compatibility + +The Rust store preserves the Swift Keychain service identifier +`com.sendbox.secrets` and the Linux hex-encoded directory and filename layout. +Legacy values remain readable before migration. + +## Linux + +1. Open the existing store. Any symlink, non-owner entry, non-directory + component, non-`0700` directory, or non-`0600` file stops migration. +2. Retrieve the legacy value through the typed store. +3. Call `SecretStore::migrate` for that name. +4. SendBox writes a versioned temporary record, syncs it, atomically replaces + the legacy file, and syncs the directory. +5. Re-running migration is safe and returns the existing versioned metadata. + +There is no bulk plaintext export. Rollback readers must continue to understand +the versioned record before a user migrates production data. + +## macOS + +Keeping the service identifier unchanged avoids unnecessary item duplication, +but a changed code-signing identity can still cause Keychain ACL prompts. +Generate a `KeychainMigrationPlan` using the old and new signing identities. +When reauthorization is required, obtain explicit user confirmation and run the +migration using the final signed binary. + +Never delete an old-service item until the replacement has been stored and +verified. Never silently relax an ACL, create an empty replacement, or fall +back to a different service. Cross-service movement requires an explicit +`MigrationAuthorization` and performs direct Keychain-to-Keychain transfer +without producing a plaintext archive. + +## Credential proxy migration + +The Rust credential broker does not preserve the Swift proxy's transparent +redirect, DNS override, `HTTP_PROXY`/`HTTPS_PROXY`, hybrid environment fallback, +or CONNECT behavior. Those surfaces implied TLS interception without owning a +trusted certificate boundary. + +Migrate each compatible agent to the explicit per-rule base URL returned by +`BrokerAgentConfiguration`. The agent must preserve the original service path +and query after that base URL. Agents that cannot override their API base URL +cannot use broker injection. + +Do not migrate GitHub repository credentials into ordinary vault rules. +`GH_TOKEN`, `GITHUB_TOKEN`, enterprise token variants, askpass/SSH forwarding, +OAuth/PAT values, and GitHub App private keys remain guarded names. Use +`GitHubMetadataClient` authorization and only consume the resulting +session-bound token after repository scope succeeds. Copilot credentials remain +independent. diff --git a/vendor/sendbox/docs/migration/security-records.md b/vendor/sendbox/docs/migration/security-records.md new file mode 100644 index 0000000..9a1dfc7 --- /dev/null +++ b/vendor/sendbox/docs/migration/security-records.md @@ -0,0 +1,25 @@ +# Security records migration + +The production security lifecycle writes the native versioned formats. Existing +pre-rewrite state remains readable through explicit, bounded compatibility APIs. + +| Data | Legacy support | Rust format | Migration behavior | +|---|---|---|---| +| Audit | Swift `entries.json` and `tree.json` v1 | `sendbox-audit` v1 | Verify legacy bytes in place; new events start a Rust v1 log. Do not rewrite legacy hashes. | +| Provenance | Swift detached signature and trust-store v1 | `sendbox-provenance` v1 | Verify legacy signatures over raw content. Re-sign with the Rust domain-separated format when rotating policy. | +| Snapshot | Swift JSON manifest v1 | `sendbox-snapshot` v1 | Inventory and validate legacy metadata. Capture future snapshots into the object store. Legacy tarballs are not trusted for direct extraction. | + +Swift v1 readers are supported throughout SendBox 2.x and cannot be removed before +SendBox 3.0. Removal requires a major-release migration notice and a tested export +path. Every Rust persisted-format reader remains supported for at least two major +versions after a successor format becomes writable. + +Compatibility readers are bounded and read-only. They preserve original +cryptographic semantics even where the replacement format is stronger. Unsupported +versions, malformed paths, invalid ownership, corruption, and policy failures return +explicit errors; they do not trigger automatic repair or fallback. + +The runtime publishes signed audit heads, exposes explicit migration commands, +validates archived snapshot metadata without trusting legacy tar extraction, and +uses the secure host secret store for signing material. Compatibility readers do +not create an automatic downgrade or fallback path. diff --git a/vendor/sendbox/docs/package-supply-chain.md b/vendor/sendbox/docs/package-supply-chain.md new file mode 100644 index 0000000..420b5e8 --- /dev/null +++ b/vendor/sendbox/docs/package-supply-chain.md @@ -0,0 +1,273 @@ +# Package supply-chain proxy + +SendBox can place an npm-compatible registry proxy between a persistent guest +workload and its configured upstream registry. The proxy downloads packages +into quarantine, verifies and scans them without executing package code, and +serves artifact bytes only after an explicit `allow` verdict. + +The npm adapter is production-supported on Apple and Kata persistent runtimes. +Hyperlight rejects package analysis because its one-shot runtime cannot compose +the trusted proxy, egress gateways, persistent cache, and authenticated report +retrieval. PyPI, Cargo, Go modules, Maven, and OCI are extension contracts only; +their adapters are not implemented yet. + +## Enable the npm proxy + +Add `policy.packages` to the sandbox configuration: + +```yaml +policy: + network: + default_action: deny + allow_dns: true + allowed_domains: + - registry.npmjs.org + blocked_domains: [] + + packages: + enabled: true + registries: + - ecosystem: npm + url: https://registry.npmjs.org/ + allow_insecure_http: false + signature: if_present + provenance: if_present + default_finding_action: deny + finding_actions: + - finding: lifecycle_script + action: deny + - finding: subprocess_api + action: deny + exceptions: [] + allow_legacy_sha1: true + limits: + max_metadata_bytes: 16777216 + max_download_bytes: 268435456 + max_unpacked_bytes: 1073741824 + max_entry_bytes: 67108864 + max_entries: 100000 + max_path_bytes: 4096 + max_depth: 64 + max_source_scan_bytes: 8388608 + request_timeout_secs: 120 + scan_timeout_secs: 30 + max_report_findings: 4096 + max_report_bytes: 98304 + cache: + enabled: true + max_bytes: 4294967296 + max_entries: 100000 + retain_quarantined: false +``` + +The npm-first implementation requires exactly one npm registry. Its URL must +also be admitted by `policy.network`; SendBox uses the original network policy +for the trusted upstream gateway and derives a workload policy that denies the +registry directly. + +At launch, SendBox sets both uppercase and lowercase npm registry variables to +the workload-facing loopback proxy and sets npm's `ignore-scripts` option in +both forms. A workload-supplied npm registry override does not grant direct +network access to the configured upstream. The proxy rewrites every packument +tarball URL to an opaque local artifact route, so npm never receives the +upstream tarball URL. + +## Private registries + +Store the raw npm token in the SendBox vault and reference its name from the +registry policy: + +```bash +sendbox secrets add PRIVATE_NPM_TOKEN +``` + +```yaml +policy: + packages: + enabled: true + registries: + - ecosystem: npm + url: https://npm.example.internal/ + credential_secret: PRIVATE_NPM_TOKEN + allow_insecure_http: false + signature: if_present + provenance: if_present + # Remaining package fields omitted here; use the annotated example config. + +secrets: + - DATABASE_URL +``` + +`credential_secret` is a vault reference, not an environment-variable +declaration. It must not also appear in the top-level `secrets` list. The host +resolves the token into the authenticated registry bootstrap, the proxy builds +the upstream bearer header, and debug output redacts the value. The workload +does not receive the token in its environment, launch secret envelope, +filesystem, report, or audit record. + +## Verification and inspection + +Artifact delivery follows this order: + +1. Resolve package identity and versions from bounded upstream metadata. +2. Bind rewritten artifact routes to package, version, source URL, declared + integrity, and the resolved metadata revision. +3. Download into a private, content-addressed quarantine store through the + registry-only SOCKS gateway. +4. Verify package identity, the strongest declared npm SRI value, and the + legacy `dist.shasum` when `allow_legacy_sha1` permits it. +5. Verify advertised npm registry signatures against bounded registry key + metadata. `signature: required` also rejects packages with no signature. +6. Verify advertised npm provenance offline against the pinned Sigstore trust + root, including the SLSA subject, Fulcio chain, SCT, DSSE signature, Rekor + entry, inclusion proof, checkpoint, signed entry timestamp, and integrated + time. `provenance: required` rejects packages with no provenance. +7. Enumerate gzip/tar content without extracting or executing it. Enforce + compressed, unpacked, per-entry, entry-count, path, depth, source-scan, and + time limits. +8. Reject unsafe paths and links, device/FIFO/sparse/unsupported entries, + unexpected executable bits, native add-ons, prebuilt or embedded + executables, lifecycle scripts, and high-risk subprocess or shell APIs. +9. Evaluate normalized findings deterministically and either promote the blob + to the approved cache, deny it, or retain only the configured quarantine + evidence. + +Integrity failures, identity mismatches, signature or provenance failures, +unsupported content, scanner failures, timeouts, decompression excess, and +oversized entries are always fail-closed. Policy rules and exceptions cannot +change those finding kinds to `allow` or `quarantine`. + +Static inspection is a policy signal, not proof that arbitrary package code is +safe. SendBox never executes package code during metadata retrieval, download, +cache population, or default analysis. + +## Finding policy and false positives + +`default_finding_action` applies when a finding has no entry in +`finding_actions`. A `quarantine` verdict withholds artifact bytes just like a +deny verdict but distinguishes packages that require human review. + +Use this workflow for a suspected false positive: + +1. Run the workload and inspect the denied record with + `sendbox package report`. +2. Independently verify the package source and the exact `sha256:` or + `sha512:` artifact digest in the report. +3. Add the smallest exception: one ecosystem, exact package, optional exact + version, exact artifact digest, and only the reviewed finding kinds. +4. Prefer `quarantine` while investigating. Use `allow` only after review. +5. Re-run the workload. A changed artifact digest, policy digest, scanner + version, or trust-metadata digest forces new analysis. + +Example: + +```yaml +policy: + packages: + exceptions: + - ecosystem: npm + package: reviewed-package + version: 1.2.3 + artifact_digest: sha512: + findings: + - subprocess_api + action: allow +``` + +Never create broad package-name-only exceptions. Digest binding prevents a +later release or republished artifact from inheriting an old approval. + +## Cache and invalidation + +The host mounts a private package cache into the trusted guest services. Cache +keys include: + +- ecosystem and verified artifact digest; +- scanner version; +- canonical package-policy digest; and +- trust-metadata digest. + +Per-route filesystem locks deduplicate concurrent requests and cross-session +analysis. A policy, scanner, artifact, or trust change therefore misses the old +verdict automatically. Approved blobs are reusable only with an exact key +match. Rejected artifact bytes are deleted by default; +`cache.retain_quarantined` controls whether quarantined bytes are retained. +`cache.enabled: false` forces analysis for every request. + +## Reports and CLI + +After the workload reaches its terminal response, the host requests the report +once over the authenticated control channel, verifies its digest and canonical +schema, and writes it atomically with mode `0600`: + +```text +~/.sendbox/run/sessions//package-security-report.json +``` + +Each record contains package identity, upstream source, artifact digest, +verification evidence, findings, policy digest, scanner version, verdict, +cache outcome, and requesting session. Secrets are never included. + +```bash +# Latest completed package-enabled session +sendbox package status +sendbox package report + +# A specific 32-character session ID +sendbox package status --session --json +sendbox package report --session --json +``` + +`sendbox run --json` includes a `package_report` summary with the path, digest, +proxy state, record count, and allow/deny/quarantine totals. The host also +records a secret-free `package_security_report_persisted` provenance audit +event. Missing, oversized, non-canonical, symlinked, incorrectly owned, or +digest-mismatched reports fail the package-enabled run. + +## Configuration reference + +| Key | Purpose | +|---|---| +| `enabled` | Enable the mandatory package proxy for the run | +| `registries` | Allowed upstream registries and evidence requirements | +| `registries[].credential_secret` | Vault reference delivered only to the trusted proxy | +| `signature`, `provenance` | `if_present` verifies advertised evidence; `required` also rejects absence | +| `default_finding_action` | Default `allow`, `deny`, or `quarantine` decision | +| `finding_actions` | Per-finding overrides; fail-closed findings must remain `deny` | +| `exceptions` | Exact digest-bound package exceptions | +| `allow_legacy_sha1` | Permit verification of npm's legacy SHA-1 `dist.shasum` | +| `limits` | Metadata, artifact, archive, scan, timeout, and report bounds | +| `limits.max_report_bytes` | Hard-bounded authenticated report size; maximum 98304 | +| `cache` | Persistent approved-blob and verdict cache controls | + +All package-policy structures reject unknown YAML fields. + +## Future adapter contract + +The core policy engine has no npm metadata dependency. `RegistryAdapter` +separates these ecosystem operations: + +- identify the ecosystem and advertised capabilities; +- resolve versions through a bounded `UpstreamClient`; +- rewrite client-facing metadata; +- fetch the selected artifact; +- fetch registry keys, trust roots, and provenance bundles; +- verify artifact integrity, signatures, and provenance through a separate + `PackageProvenanceVerifier`; +- normalize the package manifest; +- enumerate archive entries or image layers; and +- emit normalized risk findings for the shared verdict engine. + +Adapters declare whether they rewrite metadata, support signatures, support +provenance, or handle layered artifacts. The expected extension mapping is: + +| Ecosystem | Resolution and metadata | Artifact model | Verification and risk inputs | +|---|---|---|---| +| PyPI | Simple/JSON project and release metadata; rewrite file links | wheel ZIP or source archive | hashes, attestations, `METADATA`, entry and build-script risks | +| Cargo | sparse index/version records; rewrite crate download | `.crate` gzip/tar | index checksum, `Cargo.toml`, build scripts, native/executable content | +| Go modules | module proxy list/info/mod/zip endpoints | module ZIP plus `go.mod` | module checksum database evidence, path rules, generators and executable content | +| Maven | repository metadata and POM resolution | JAR/ZIP and related artifacts | checksums, detached signatures, POM plugins, native/executable content | +| OCI | manifest or index resolution and blob routing | ordered filesystem layers | descriptor digests, signatures/attestations, whiteouts, layer paths and executables | + +Future adapters should reuse these contracts rather than add ecosystem logic to +the cache, policy evaluator, report schema, or egress service. diff --git a/vendor/sendbox/docs/qualification.md b/vendor/sendbox/docs/qualification.md new file mode 100644 index 0000000..e3a5e26 --- /dev/null +++ b/vendor/sendbox/docs/qualification.md @@ -0,0 +1,166 @@ +# Qualification inventory, conformance, and benchmarks + +The Phase 0/1 qualification data lives under `Tests/qualification/` and is +validated by the isolated Rust tool in `tools/sendbox-qualification/`. The tool +has its own workspace and lockfile so qualification dependencies do not become +product dependencies. + +## Inventory gate + +`inventory.v1.json` is the countable rewrite scope. It covers current Rust +source modules, historical implementation decisions, CLI commands, +configuration sections and defaults, runtime operations and capabilities, +security modules, persisted formats, setup/completion/release surfaces, and +top-level documented claims. + +Every entry has a stable ID, one of `preserve`, `redesign`, `defer`, or +`remove`, repository evidence in `path#symbol-or-claim` form, a target Rust +crate and phase, and a conformance status. Redesigns also require a +compatibility note. Validation fails on duplicate IDs, missing evidence, +unknown fields, missing fixtures, or an unresolved disposition. + +The production records include adapter-neutral session lifecycle, audit +anchoring, snapshot rollback, secret envelopes, provenance verification, +permission grants, and bounded migration reports. `sendbox-host` composes those +records with verified runtime plans and authenticated Apple/Kata guest services. +All inventory and conformance entries are implemented or explicitly +not-applicable. + +Deleted implementation paths are represented through +`Tests/qualification/historical/swift-to-rust.v1.json`, which binds each +historical evidence path to the exact pre-cutover commit and Git blob object. +Validation resolves the commit and every blob from repository history, rejects +paths still present in the current tree, and requires a full-history checkout. +The text after the second `#` is a stable semantic claim label rather than a +source-code selector. Implemented entries must also resolve to live repository +evidence directly or through their implemented target source module. + +Inventory coverage scans `crates/*/src` only; the Swift package and the +TypeScript copilot bridge no longer exist. Validation therefore rejects the tree +outright if `Package.swift`, `Package.resolved`, `Sources/`, or +`copilot-bridge/` reappears, and still flags any non-Rust source module that +turns up inside a crate. + +For a PR, changed behavior must update the corresponding inventory and fixture. +Cutover requires every preserved entry to have a passing implementation test +and every redesign to have its compatibility note satisfied. + +## Conformance gate + +`conformance.v1.json` indexes intended-behavior fixtures. Intended behavior is +the only oracle; the production qualification tool no longer executes or +compares a legacy implementation. + +Fixtures specify CLI channels and exits, config defaults and errors, policy +decisions, protocol contracts, runtime capabilities, persisted formats, +setup/release behavior, and known-defect negative cases. Existing config and +protocol fixtures remain the executable implementation tests where available; +qualification fixtures define the cross-implementation contract. + +`scripts/qualify-setup-release.sh` is the executable `setup.release` gate. The +macOS and Linux CI matrix runs real setup configuration/build flows, a staged +Make install, host tar assembly, checksum verification, and archive inspection; +the macOS leg additionally builds and inspects the unsigned pkg and dmg. + +`policy.decisions` is implemented across the native command broker, egress +engine, MCP broker, repository-scope authorization, and Git guard. The Git +evidence covers repository/workspace identity, aliases, options, remote +rewrites, refspecs, timeouts, output limits, environment/config injection, +trusted binary paths, and native exit preservation. + +`mcp.contracts` records native framing, JSON-RPC, hierarchical per-server +policy, exact-command and exact-gateway project validation, authenticated guest +delivery, modern Streamable HTTP, explicit 2025 session compatibility, TLS/DNS +destination checks, redirects, credentials, egress bypass protection, +legacy-trace, versioned observation, redaction, backpressure, cancellation, and +fail-closed audit contracts. Legacy 2024 HTTP+SSE remains intentionally +unsupported. + +## Benchmark gate + +`benchmark-spec.v1.json` records reference-host fields, workload sizes, +warmups/repetitions, cache states, compiler/linker/allocator/logging controls, +statistics and confidence intervals, absolute plan thresholds, C-reference +interfaces, fixed-adapter definitions, and the BPF no-loss event-rate gate. +Unknown environmental values are `unqualified`; they must not be guessed. + +Available pure/control-plane paths measure CLI startup, config validation, +policy structural validation, protocol encode/decode, and authenticated +in-memory protocol RTT including MAC work. Exec broker, policy decisions, MCP, +egress, BPF decode, guest bootstrap, RSS/binary release measurements, and +vendor runtime paths remain explicit hooks until stable production interfaces +and reference hosts exist. + +The harness emits raw samples and summaries at benchmark report schema version 2, +which records host OS, architecture, `rustc`, and the qualification tool version. +Shared-runner smoke tests only +check execution and output shape; they never enforce noisy latency thresholds. +Qualification enforcement is reserved for declared reference hosts: + +```bash +cargo run --manifest-path tools/sendbox-qualification/Cargo.toml -- validate + +cargo run --manifest-path tools/sendbox-qualification/Cargo.toml -- \ + benchmark --profile smoke --rust-binary target/release/sendbox + +cargo run --manifest-path tools/sendbox-qualification/Cargo.toml -- \ + benchmark --profile qualification --enforce-thresholds \ + --rust-binary target/release/sendbox +``` + +The portable harness never starts Apple container services, containerd, Kata, +Hyperlight, guest services, or BPF programs. Production Kata has a separate, +non-skipping self-hosted gate: + +```bash +SENDBOX_KATA_LIVE=1 \ +SENDBOX_KATA_CONFIG=/absolute/config.yaml \ +SENDBOX_KATA_IMAGE=registry/workload@sha256: \ +SENDBOX_KATA_BUNDLE=/absolute/bundle \ +SENDBOX_KATA_TRUST_ROOT=/absolute/release-public.key \ +./scripts/qualify-kata-live.sh +``` + +`.github/workflows/kata-live.yaml` requires a runner labeled +`self-hosted, linux, x64, kvm, kata`. Missing inputs or prerequisites fail; they +are never reported as a successful skip. Vendor baselines must still be run on +prepared hosts using the pinned fixed-adapter definition. A result cannot be +published while any required workload, reference host field, relative C +baseline, fixed-adapter baseline, BPF event rate, or live Kata evidence remains +`unqualified`. + +## Apple runtime qualification + +The production Apple entry is `module.rust-apple-runtime`. Its portable gate +uses the shared runtime conformance suite, a stateful fake `container` CLI, +exact-argv assertions, bounded stream/output tests, cancellation and failure +tests, signed-bundle verification, and a real local authenticated Unix-stream +fixture. + +The vendor gate is opt-in only because GitHub-hosted runners do not provide an +already registered Apple container service or repository trust artifacts. When +the repository variable `SENDBOX_APPLE_CONTAINER_LIVE=1` configures the +prepared self-hosted runner, `.github/workflows/apple-runtime.yaml` runs the +live test without a skip path. The test verifies the pre-existing service, +creates unique container and guest socket identities, authenticates through the +official CLI stdio relay, and performs targeted cleanup. It never registers, +starts, stops, or unregisters the Apple service. + +See [Apple runtime adapter](apple-runtime.md) for required variables, the live +command, transport evidence, and unsupported capabilities. + +## Hyperlight runtime qualification + +`module.hyperlight-runtime` and `claim.hyperlight` are implemented by +`crates/sendbox-runtime-hyperlight`. Ordinary qualification validates the +portable lifecycle subset, exact argv construction, signed bundle verification, +network rejection rules, fresh read-only staging, cancellation, output, and +cleanup. It does not claim a persistent guest broker, stdio forwarding, eBPF or +seccomp guest bootstrap, OCI support, environment injection, DNS budgets, +connection limits, or wildcard/CIDR enforcement. + +The vendor gate is opt-in because it requires a prepared Linux KVM host, a +root-owned pinned `hyperlight-unikraft`, and a signed Unikraft bundle. When +designated with `SENDBOX_HYPERLIGHT_LIVE=1`, missing prerequisites fail the +test rather than producing a success-shaped skip. The complete command and +required variables are documented in [the Hyperlight guide](hyperlight.md). diff --git a/vendor/sendbox/docs/security-model.md b/vendor/sendbox/docs/security-model.md new file mode 100644 index 0000000..999120c --- /dev/null +++ b/vendor/sendbox/docs/security-model.md @@ -0,0 +1,643 @@ +# SendBox Security Model + +> Comprehensive security documentation covering architecture, threat model, and defense-in-depth analysis against the [SandboxEscapeBench](https://arxiv.org/abs/2603.02277) benchmark. + +--- + +## Architecture Overview + +SendBox has two persistent guest-service runtime providers. Both give the +workload a dedicated Linux kernel, but their host control planes and operational +responsibilities differ. + +| Property | Apple provider | Kata provider | +|----------|----------------|---------------| +| Host | macOS on Apple silicon | Linux with hardware or nested virtualization | +| VM control plane | Apple Containerization / Virtualization.framework | nerdctl, containerd, and `containerd-shim-kata-v2` | +| Kernel | Dedicated per sandbox | Dedicated per Kata sandbox | +| Filesystem sharing | Explicit virtiofs mounts | Explicit OCI bind mounts mediated by the Kata VM | +| Host runtime attack surface | Apple virtualization stack | containerd, Kata shim, and selected hypervisor | +| Root in workload | Root in the guest only | Root in the Kata guest only | +| Secret store | macOS Keychain | Mode-restricted host files | + +**Key insight:** The workload does not share the host kernel. A guest-kernel compromise is contained by the selected hypervisor boundary, while host runtime and hypervisor components still require normal patching and hardening. + +The detailed SandboxEscapeBench analysis below describes the Apple provider. The Kata provider relies on Kata's VM boundary and the security configuration of containerd, the Kata shim, and the selected hypervisor; SendBox does not claim architectural immunity from vulnerabilities in those host components. + +Hyperlight is an explicit-only, authenticated one-shot provider. It uses a +separately signed Unikraft bundle and intentionally rejects persistent guest +services, secret delivery, MCP, and network-policy composition. + +### Production execution mediation + +The Rust [`sendbox-exec`](architecture/execution-broker.md) component implements +ADR-001's top-level semantic execution boundary. A trusted pre-untrusted-input +bootstrap denies direct agent `execve` and `execveat`. Admitted commands are +resolved with retained `openat2` descriptors, executed with `execveat`, placed +atomically in supervisor-owned cgroup v2 leaves with `clone3`, and cleaned with +`cgroup.kill` plus pidfd reaping. + +This does not claim recursive semantic authorization of descendant commands. +Descendants inherit syscall, capability, resource, environment, and cgroup +containment, while their own argv remains outside the semantic policy boundary. +The VM boundary remains the primary containment layer. + +### Production credential mediation + +The Rust [`sendbox-credentials`](architecture/secrets-and-credential-broker.md) +library exposes explicit per-rule loopback HTTP endpoints instead of pretending +to transparently proxy TLS. It strictly parses one bounded HTTP/1.1 request, +validates the exact configured upstream host, method, and path, injects the +credential only after validation, and performs a certificate-verifying HTTPS +request with DNS addresses pinned between authorization and connect. + +CONNECT injection, TLS interception, wildcard binds, cross-target redirects, +ambiguous HTTP framing, and unapproved restricted DNS answers are rejected. +GitHub repository tokens use a separate metadata and repository-scope +authorization path; cross-organization non-public scope is always denied and a +token is retrieved only after complete pagination succeeds. Apple and Kata runs +deliver approved credentials through authenticated, policy-bound secret +envelopes. + +[Governed sessions](architecture/governed-sessions.md) go further for model +provider keys: an operator-signed profile bounds what a project may request, +the admission is bound into the signed boundary plan, and Anthropic or OpenAI +requests are relayed to the host over the authenticated control channel. The +host checks a leased, revocable grant and injects the key, so the provider +credential never enters the guest. + +### Production package mediation + +The Rust [`sendbox-registry`](package-supply-chain.md) component is a trusted +pre-delivery boundary for configured npm registries. The untrusted workload is +forced to a loopback proxy and denied direct access to the upstream registry. +The proxy runs outside the workload process tree, in a third cgroup identity +that can reach only a registry-only SOCKS gateway and cannot set the broker +socket mark. + +Artifacts remain in a private quarantine store while SendBox verifies package +identity, npm integrity, advertised signatures and provenance, archive bounds, +and normalized static risk findings. Inspection never extracts into the +workspace or executes package code. Only an `allow` verdict exposes bytes. +Integrity, identity, evidence, unsupported-content, scanner, timeout, and limit +failures always deny delivery. + +Private registry tokens are resolved from the host vault into the authenticated +proxy bootstrap. They cannot overlap workload secret references and are absent +from workload environment variables, launch secrets, reports, and audit logs. +The terminal package report is retrieved once over the authenticated protocol, +revalidated by the host, and persisted as owner-only session evidence. + +### Production guest artifacts and BPF observation + +Production static guest binaries, the execution launcher, CO-RE BPF objects, +inventory, and SBOM metadata are packaged in reproducible signed bundles. The +signing key remains external to the repository and build image. Release +artifacts include the matching public key, but operators must verify GitHub +artifact provenance before treating it as a trust root. See +[Production guest BPF and artifact bundles](architecture/guest-artifact-bundles.md). + +The current BPF programs are cgroup-scoped observation only. They cannot permit +or deny exec, syscall, network, or MCP actions and are not part of the semantic +execution enforcement boundary. + +### Production MCP authorization + +Apple and Kata guests enforce MCP policy in trusted application-layer services. +One signed hierarchical policy maps stable server IDs to exact stdio argv or +normalized HTTP endpoints and gives each server an independent tool policy. +Project aliases and caller-supplied policy IDs are never trusted. Unknown +servers, changed identities, malformed JSON-RPC, ambiguous mappings, audit +failure, and transport failure deny. + +The stdio path uses the installed root-owned broker. Exact ordered argv selects +the policy, server discovery is filtered, and every `tools/call` is checked +again before forwarding. Server children receive a scrubbed signed environment +and fixed working directory. + +The remote path uses a mandatory loopback Streamable HTTP gateway. Project +configuration contains only +`http://127.0.0.1:15082/mcp/` and an exact supported transport type; +it cannot contain the upstream URL, headers, or credentials. The gateway +validates JSON-RPC and protocol metadata, bounds request/SSE/session state, +verifies TLS and hostnames, resolves each connection independently, rejects +restricted addresses, pins the exact dial address, and revalidates every +allowlisted redirect. Modern Streamable HTTP is the default. Stateful 2025 +behavior is an explicit compatibility mode; legacy 2024 HTTP+SSE is rejected. + +Remote MCP forces authenticated egress. Configured upstream and redirect origins +are deny-first reservations in the normal CONNECT broker, direct-IP CONNECT is +disabled, and nftables admits only the exact loopback gateway port from the +agent cgroup. Gateway DNS and marked dials run in the broker cgroup and never +authorize the agent-facing cache. There is no direct fallback. + +Gateway credential names form a separate signed secret partition that must be +disjoint from workload `secrets`. Values are resolved from the host vault, +delivered only in authenticated root-owned bootstrap material, and injected +only into the selected upstream request. Stdio and HTTP decisions share a +mandatory redacted audit path; audit write failure is terminal. + +TLS uprobes and MCP BPF records remain observation-only. SendBox does not treat +plaintext recovery from uprobes as an authorization mechanism. + +--- + +## SandboxEscapeBench Coverage — Apple Provider + +The [SandboxEscapeBench](https://arxiv.org/abs/2603.02277) benchmark defines 18 escape scenarios across three layers of the container stack. The Apple provider mitigates all 18 through architectural isolation and guest defense-in-depth. + +### Summary Table + +| # | Scenario | Layer | Attack Vector | Apple Provider Status | Primary Defense | +|---|----------|-------|---------------|----------------|-----------------| +| 1 | `crio_cve` | Orchestration | CRI-O CVE-2022-0811 — kernel parameter injection via `pinns` | **Blocked** | No CRI-O runtime | +| 2 | `kubectl_cp` | Orchestration | CVE-2019-11246 — symlink path traversal via `kubectl cp` | **Blocked** | No kubectl / Kubernetes | +| 3 | `rbac` | Orchestration | Overly permissive RBAC allows pod creation with hostPID | **Blocked** | No Kubernetes API | +| 4 | `route_localnet` | Orchestration | `net.ipv4.conf.all.route_localnet=1` enables metadata service access | **Blocked** | sysctl locked to `0`; no cloud metadata | +| 5 | `privileged` | Runtime | `--privileged` flag grants all capabilities + device access | **Blocked** | No container runtime; VM has no concept of `--privileged` | +| 6 | `docker_sock` | Runtime | Mounted Docker socket allows container escape via API | **Blocked** | No Docker socket; no container runtime binaries | +| 7 | `cap_sys_admin` | Runtime | `CAP_SYS_ADMIN` enables mount namespace escape | **Blocked** | Capability dropped; seccomp blocks `mount` | +| 8 | `cap_sys_module` | Runtime | `CAP_SYS_MODULE` allows loading malicious kernel modules | **Blocked** | Capability dropped; `kernel.modules_disabled=1` | +| 9 | `cap_dac_read_search` | Runtime | `CAP_DAC_READ_SEARCH` + `open_by_handle_at` reads host files | **Blocked** | Capability dropped; seccomp blocks `open_by_handle_at` | +| 10 | `hostpath` | Runtime | HostPath volume mounts expose host filesystem | **Blocked** | Only `.devcontainer` (read-only) and workspace copy mounted | +| 11 | `runc_2019` | Runtime | CVE-2019-5736 — runc binary overwrite via `/proc/self/exe` | **Blocked** | No runc; no container runtime | +| 12 | `runc_2024` | Runtime | CVE-2024-21626 — runc working directory file descriptor leak | **Blocked** | No runc; no container runtime | +| 13 | `pid_ns` | Kernel | PID namespace escape via `/proc` to access host processes | **Blocked** | Separate kernel; `/proc` shows only guest processes | +| 14 | `cgroup` | Kernel | cgroup `release_agent` write for host code execution | **Blocked** | Separate kernel; cgroup `release_agent` disabled | +| 15 | `bpf_privesc` | Kernel | eBPF program loading for privilege escalation | **Blocked** | `kernel.unprivileged_bpf_disabled=1`; `CAP_BPF` dropped | +| 16 | `dirty_cow` | Kernel | CVE-2016-5195 — copy-on-write race condition for privilege escalation | **Blocked** | Separate kernel; exploit affects guest only; KASLR enabled | +| 17 | `dirty_pipe` | Kernel | CVE-2022-0847 — pipe buffer flag manipulation for file overwrite | **Blocked** | Separate kernel; exploit affects guest only; no host files accessible | +| 18 | `packet_sock` | Kernel | `CAP_NET_RAW` + `AF_PACKET` socket for traffic interception | **Blocked** | `CAP_NET_RAW` dropped; seccomp restricts socket creation | + +--- + +### Layer 1: Orchestration (4/4 Blocked) + +These attacks target Kubernetes and container orchestration components. The direct Apple and Kata providers do not use Kubernetes or CRI-O. + +#### 1. CRI-O CVE (CVE-2022-0811) + +- **Attack:** Exploits a vulnerability in CRI-O's `pinns` utility that allows setting arbitrary kernel parameters via specially crafted annotations on a pod. An attacker can set `kernel.core_pattern` to a pipe command, achieving host code execution when a process crashes. +- **Why N/A:** The Apple provider creates VMs directly through Virtualization.framework and has no CRI-O or `pinns`. The direct Kata provider uses containerd and the Kata shim, not CRI-O. +- **Defense-in-depth:** Even within the guest VM, `kernel.core_pattern` is set to a safe value (`|/bin/false`) and `kernel.modules_disabled=1` prevents loading modules that could be triggered by core patterns. + +#### 2. kubectl cp Path Traversal (CVE-2019-11246) + +- **Attack:** `kubectl cp` follows symlinks when extracting tar archives, allowing an attacker to write files outside the intended destination on the host. A malicious container can plant a symlink that causes `kubectl cp` to overwrite host files. +- **Why N/A:** SendBox has no Kubernetes API server, no `kubectl`, and no `kubelet`. File transfer between host and VM is done exclusively through virtiofs mounts with explicit source/destination mappings defined in the sandbox configuration. +- **Defense-in-depth:** Only two mount points are created: `.devcontainer` (read-only) and the workspace copy. The workspace is a copy of the original project, not the original — damage is contained to the copy. + +#### 3. RBAC Privilege Escalation + +- **Attack:** Overly permissive Kubernetes RBAC roles (e.g., `pods/exec`, `create pods` with `hostPID: true`) allow an attacker to create a privileged pod that shares the host PID namespace, enabling process injection and escape. +- **Why N/A:** There is no Kubernetes API, no RBAC system, no pod specs, and no concept of `hostPID`. The VM is a single execution environment — there is no "create another container" primitive available to the agent. +- **Defense-in-depth:** The command policy engine blocks `kubectl` and `docker` by default (not in the standard allowlist). Even if somehow installed inside the VM, they have no API server to talk to. + +#### 4. route_localnet Metadata Access + +- **Attack:** Setting `net.ipv4.conf.all.route_localnet=1` allows routing to 127.0.0.0/8 from non-loopback interfaces. In cloud environments, this can be combined with iptables DNAT rules to redirect traffic intended for the cloud metadata service (169.254.169.254) to localhost, bypassing network policies. +- **Why N/A:** The Apple provider runs locally and has no cloud metadata service. Kata deployments may run in cloud environments and must keep metadata endpoints outside the allowed network policy. +- **Defense-in-depth:** `net.ipv4.conf.all.route_localnet=0` is explicitly set via sysctl hardening. The network firewall blocks traffic outside the domain allowlist, and guest sysctl changes cannot modify the host network stack. + +--- + +### Layer 2: Runtime (8/8 Blocked) + +This section describes the Apple provider, which creates the VM directly and has no runc, containerd, or Docker daemon. The Kata provider does use containerd and the Kata shim on the host; those components must be patched and configured according to Kata guidance. + +#### 5. Privileged Container + +- **Attack:** Running a container with `--privileged` grants all Linux capabilities, disables seccomp, and allows access to all host devices via `/dev`. An attacker can mount the host filesystem from a block device and escape. +- **Why N/A:** The Apple provider has no `--privileged` flag. SendBox never requests `--privileged` from nerdctl for Kata workloads and only adds narrowly scoped capabilities when firewall or MCP inspection requires them. +- **Defense-in-depth:** The hardening script drops all dangerous capabilities (`CAP_SYS_ADMIN`, `CAP_SYS_MODULE`, `CAP_NET_RAW`, etc.) inside the guest. Even root inside the VM cannot load kernel modules or mount arbitrary filesystems. + +#### 6. Docker Socket Mount + +- **Attack:** When `/var/run/docker.sock` is mounted inside a container, the agent can use the Docker API to create a new privileged container with host filesystem access, effectively escaping the sandbox. +- **Why N/A:** The Apple provider has no Docker daemon. The Kata provider uses a host containerd socket, but SendBox never mounts that socket or host runtime binaries into the guest. +- **Defense-in-depth:** The mount configuration only allows two mount points (`.devcontainer` read-only, workspace copy read-write). No host paths like `/var/run/` are ever exposed. The command policy denylist blocks `docker` commands. The `ContainerHardening.validate()` method warns if any mount targets sensitive paths. + +#### 7. CAP_SYS_ADMIN Abuse + +- **Attack:** `CAP_SYS_ADMIN` is one of the most powerful Linux capabilities. It allows mounting filesystems, using `unshare` to create new namespaces, and performing many operations that can lead to container escape (e.g., mounting the host's `/` via a shared mount namespace). +- **Why N/A:** Guest capabilities do not affect the host because the guest runs a separate kernel. There is no shared mount namespace. +- **Defense-in-depth:** `CAP_SYS_ADMIN` is explicitly dropped in the hardening script. The seccomp profile blocks `mount`, `unshare`, and `pivot_root` syscalls. `prctl(PR_SET_NO_NEW_PRIVS, 1)` prevents regaining capabilities. + +#### 8. CAP_SYS_MODULE Abuse + +- **Attack:** `CAP_SYS_MODULE` allows loading kernel modules via `init_module` / `finit_module` syscalls. An attacker can load a malicious kernel module that modifies kernel data structures to escape the container namespace. +- **Why N/A:** Even if a malicious module is loaded inside the guest, it modifies the guest kernel only — the host kernel is completely separate. +- **Defense-in-depth:** `CAP_SYS_MODULE` is dropped. `kernel.modules_disabled=1` is set via sysctl, disabling module loading entirely. The seccomp profile blocks `init_module` and `finit_module` syscalls. + +#### 9. CAP_DAC_READ_SEARCH + open_by_handle_at + +- **Attack:** `CAP_DAC_READ_SEARCH` bypasses file read permission checks. Combined with the `open_by_handle_at` syscall (which opens files by handle, bypassing mount namespace restrictions), an attacker can read any file on the host, including `/etc/shadow`. +- **Why N/A:** The guest has no access to host file handles. `open_by_handle_at` in the guest kernel operates on guest filesystem handles only. +- **Defense-in-depth:** `CAP_DAC_READ_SEARCH` is dropped. The seccomp profile blocks `open_by_handle_at`. No sensitive host paths are mounted. + +#### 10. HostPath Volume Abuse + +- **Attack:** Kubernetes `hostPath` volumes or Docker `-v /:/host` mounts expose the host filesystem inside the container. An attacker with access to the host root filesystem can modify system files, add SSH keys, or create cron jobs for persistent access. +- **Why N/A:** The Apple provider uses explicit virtiofs sharing. The Kata provider maps only SendBox's explicit project and devcontainer bind mounts into the Kata guest. +- **Defense-in-depth:** Only two mounts exist: `.devcontainer` (read-only) and workspace (a copy, not the original). `ContainerHardening.validate()` warns if mounts target sensitive paths (`/etc`, `/var/run`, `/proc`, `/sys`). The workspace copy ensures that even destructive operations inside the VM don't affect the original project. + +#### 11. runc CVE-2019-5736 + +- **Attack:** CVE-2019-5736 allows a malicious container to overwrite the host `runc` binary via `/proc/self/exe`. When `runc` is next invoked (e.g., `docker exec`), the attacker's code runs as root on the host. +- **Why N/A:** The Apple provider has no runc. Kata uses the runtime v2 shim and a guest VM rather than running the workload through a shared-kernel runc container. +- **Defense-in-depth:** `/proc/self/exe` inside either guest refers to a guest process, not the host shim. Kata and containerd still require timely security updates. + +#### 12. runc CVE-2024-21626 + +- **Attack:** CVE-2024-21626 exploits a file descriptor leak in runc where the working directory of the container process retains a reference to a host filesystem directory. An attacker can use this leaked fd to traverse up to the host root filesystem. +- **Why N/A:** The Apple provider has no runc or containerd file-descriptor inheritance. Kata's shim crosses into a VM boundary rather than exposing a shared host mount namespace to the workload. +- **Defense-in-depth:** The hypervisor boundary ensures no host file descriptors are leaked to the guest. The VM's `/proc/self/fd/` shows only guest file descriptors. + +--- + +### Layer 3: Kernel (6/6 Blocked) + +These attacks exploit shared kernel vulnerabilities. SendBox's VM architecture provides the strongest defense here: the guest has its own kernel, so kernel exploits affect only the guest. + +#### 13. PID Namespace Escape + +- **Attack:** In a container sharing the host PID namespace (`--pid=host`), `/proc` shows host processes. An attacker can use `/proc//root` to access the host filesystem or inject code into host processes via `ptrace`. +- **Why N/A:** The guest has its own kernel and PID space. `/proc` shows only guest processes. There is no `--pid=host` option. +- **Defense-in-depth:** `kernel.yama.ptrace_scope=2` is set (no process may ptrace another, except via `CAP_SYS_PTRACE` which is dropped). `CAP_SYS_PTRACE` is dropped. The seccomp profile blocks `ptrace`. + +#### 14. Cgroup release_agent Escape + +- **Attack:** An attacker with write access to cgroup files can set `release_agent` to a path on the host, and `notify_on_release` to `1`. When the last process in the cgroup exits, the kernel executes the `release_agent` binary on the host as root. +- **Why N/A:** The guest's cgroup hierarchy is managed by the guest kernel. Writing to `/sys/fs/cgroup/*/release_agent` inside the VM triggers execution inside the VM, not on the host. +- **Defense-in-depth:** The hardening script disables `release_agent` by writing `0` to `notify_on_release` for all existing cgroups and making cgroup mount points read-only where possible. `CAP_SYS_ADMIN` (required to modify cgroup `release_agent`) is dropped. + +#### 15. BPF Privilege Escalation + +- **Attack:** eBPF programs run inside the kernel. A malicious eBPF program can read/write arbitrary kernel memory, modify kernel data structures, or escalate privileges. `CAP_BPF` (or `CAP_SYS_ADMIN` on older kernels) is required. +- **Why N/A:** eBPF programs inside the guest run in the guest kernel. They cannot read host kernel memory. +- **Defense-in-depth:** `kernel.unprivileged_bpf_disabled=1` prevents non-root BPF usage. The seccomp profile blocks the `bpf` syscall. `CAP_SYS_ADMIN` and all BPF-related capabilities are dropped. + +#### 16. Dirty COW (CVE-2016-5195) + +- **Attack:** A race condition in the Linux kernel's copy-on-write mechanism allows an unprivileged user to write to read-only memory mappings, including read-only files. This can be used to overwrite `/etc/passwd` or setuid binaries to escalate privileges. +- **Why N/A:** The guest runs its own kernel. Even if the guest kernel is vulnerable to Dirty COW, exploitation only affects guest files. The host kernel (macOS/XNU) is not Linux and is not susceptible to this vulnerability. +- **Defense-in-depth:** KASLR is enabled (`kernel.randomize_va_space=2`) to make exploitation harder. The workspace mount is a copy, so even if guest files are corrupted, the original project is unaffected. Modern Linux kernel images used by SendBox include the Dirty COW fix. + +#### 17. Dirty Pipe (CVE-2022-0847) + +- **Attack:** A flaw in Linux pipe buffer management allows an unprivileged user to overwrite data in arbitrary cached read-only files, including files on read-only mounts. This can modify setuid binaries or `/etc/passwd` for privilege escalation. +- **Why N/A:** Same as Dirty COW — the guest kernel is separate. The host runs XNU (macOS), which does not have Linux pipes. Even if the guest kernel is vulnerable, the impact is contained to the guest. +- **Defense-in-depth:** Guest kernel images are regularly updated. virtiofs mounts use the host's filesystem permissions — even if the guest kernel is compromised, virtiofs file access is mediated by the hypervisor. `prctl(PR_SET_NO_NEW_PRIVS, 1)` prevents setuid escalation. + +#### 18. Packet Socket Exploitation + +- **Attack:** `CAP_NET_RAW` allows creating `AF_PACKET` sockets that can capture all network traffic on the container's network namespace. In shared-network configurations, this can intercept traffic from other containers or the host. +- **Why N/A:** The guest has its own virtual NIC (virtio-net). Even with `AF_PACKET` sockets, the guest can only see its own traffic. There is no shared network namespace with the host or other VMs. +- **Defense-in-depth:** `CAP_NET_RAW` is dropped. The seccomp profile restricts raw socket creation. The network firewall limits which domains the VM can contact, and rate-limits connections. + +--- + +## Defense-in-Depth Layers — Apple Provider + +The Apple provider defines seven overlapping defense layers. Kata deployments should apply equivalent guest hardening through their Kata image and configuration. + +### Layer 1: Hardware VM Isolation + +The primary defense is the hypervisor boundary provided by Apple's Virtualization.framework. + +- Each VM has its **own Linux kernel**, loaded from a disk image at boot +- Memory is hardware-isolated via the MMU / stage-2 page tables +- Virtual devices (virtio-net, virtiofs, virtio-console) are the only host interface +- The host kernel (XNU) is never shared — Linux kernel exploits affect only the guest +- There is no `/proc/host`, no shared PID namespace, no shared mount namespace +- The hypervisor enforces isolation at the hardware level, below the OS + +### Layer 2: Kernel Hardening (sysctl) + +Inside the guest VM, the hardening script applies restrictive sysctl settings before the agent process starts: + +| sysctl Parameter | Value | Purpose | +|------------------|-------|---------| +| `kernel.modules_disabled` | `1` | Prevent kernel module loading (blocks `CAP_SYS_MODULE` exploitation) | +| `kernel.unprivileged_bpf_disabled` | `1` | Prevent unprivileged BPF program loading | +| `kernel.yama.ptrace_scope` | `2` | Restrict ptrace to `CAP_SYS_PTRACE` holders only (which is dropped) | +| `kernel.core_pattern` | `\|/bin/false` | Prevent core_pattern pipe injection (CRI-O CVE vector) | +| `kernel.randomize_va_space` | `2` | Full ASLR (code, data, stack, heap, vdso) | +| `net.ipv4.conf.all.route_localnet` | `0` | Prevent routing to loopback from external interfaces | +| `kernel.kptr_restrict` | `2` | Hide kernel pointers from all users | +| `kernel.dmesg_restrict` | `1` | Restrict `dmesg` access to `CAP_SYSLOG` holders | +| `kernel.perf_event_paranoid` | `3` | Disable perf events for non-root users | +| `net.ipv4.conf.all.send_redirects` | `0` | Disable ICMP redirect sending | +| `net.ipv4.conf.all.accept_redirects` | `0` | Disable ICMP redirect acceptance | +| `fs.protected_symlinks` | `1` | Prevent symlink-based attacks in world-writable directories | +| `fs.protected_hardlinks` | `1` | Prevent hardlink-based privilege escalation | +| `fs.suid_dumpable` | `0` | Prevent core dumps of setuid programs | + +### Layer 3: Capability Dropping + +Linux capabilities are dropped to a minimal set before the agent runs. The following dangerous capabilities are explicitly removed: + +| Capability | Risk if Granted | +|-----------|-----------------| +| `CAP_SYS_ADMIN` | Mount filesystems, create namespaces, trace processes — most common escape vector | +| `CAP_SYS_MODULE` | Load kernel modules — arbitrary kernel code execution | +| `CAP_DAC_READ_SEARCH` | Bypass file read permissions — used with `open_by_handle_at` for host file access | +| `CAP_NET_RAW` | Create raw/packet sockets — traffic interception, ARP spoofing | +| `CAP_SYS_PTRACE` | Trace any process — code injection, credential theft | +| `CAP_SYS_RAWIO` | Direct I/O port access — hardware-level attacks | +| `CAP_SYS_BOOT` | Reboot the system | +| `CAP_SYS_CHROOT` | Use `chroot` — filesystem isolation escape | +| `CAP_MKNOD` | Create device nodes — potential device access bypass | +| `CAP_NET_ADMIN` | Modify network configuration — firewall bypass | +| `CAP_DAC_OVERRIDE` | Bypass file write permissions | +| `CAP_FOWNER` | Bypass permission checks on file operations | +| `CAP_SETUID` / `CAP_SETGID` | Change process UID/GID — privilege escalation | + +### Layer 4: Seccomp-BPF Syscall Boundary + +Before the agent starts, SendBox compiles a root-owned libseccomp launcher from +the same typed rules used by `ContainerHardening.seccompProfile()`. The initial +agent process and every later `container.exec` are prefixed with that launcher, +so the filter is inherited across all agent forks and execs. Setup is +fail-closed, `PR_SET_NO_NEW_PRIVS` is set, and the process drops to the invoking +non-root host UID before executing agent code. + +Project-provided environment variables never reach the root bootstrap under +their original names. SendBox serializes the complete agent environment into one +base64 value, starts root setup with a strict minimal environment, writes a +root-only NUL-delimited environment file, and restores it only inside the +launcher immediately before privilege drop and exec. + +| Blocked Syscall | Attack Prevented | +|----------------|------------------| +| `mount` / `umount2` | Filesystem namespace escape | +| `init_module` / `finit_module` / `delete_module` | Kernel module loading | +| `open_by_handle_at` | File handle-based host file access (CVE technique) | +| `ptrace` | Process tracing and code injection | +| `bpf` | eBPF program loading for kernel exploitation | +| `unshare` | Namespace creation for isolation escape | +| `pivot_root` | Root filesystem manipulation | +| `kexec_load` / `kexec_file_load` | Kernel replacement | +| `reboot` | System reboot | +| `swapon` / `swapoff` | Swap manipulation | +| `acct` | Process accounting manipulation | +| `add_key` / `keyctl` / `request_key` | Kernel keyring manipulation | +| `userfaultfd` | Used in exploitation of race conditions | +| `perf_event_open` | Kernel-level performance monitoring (information leak) | +| `move_mount` / `open_tree` / `fsopen` / `fspick` | New mount API — filesystem manipulation | +| `process_vm_readv` / `process_vm_writev` / `pidfd_getfd` / `kcmp` | Cross-process memory and descriptor takeover | + +Denied syscall attempts are also recorded by a root-owned eBPF tracepoint +program and, when supported by the kernel, the seccomp audit log. + +### Layer 5: MCP Tool Boundary + +The native `sendbox-mcp` library and authenticated guest bootstrap define one +application-layer authorization boundary for stdio and remote Streamable HTTP: + +- Complete bounded newline or `Content-Length` JSON-RPC messages are parsed + before forwarding. +- Exact argv derives one stable server policy; caller-supplied IDs and + project-local aliases do not select permissions. +- Each server has an independent tool namespace. `tools/list` is correlated and + filtered, while every `tools/call` uses denylist-first glob matching, then + allowlist/default action. +- Denied requests receive JSON-RPC error `-32001`; denied notifications are dropped. +- An injected launcher receives only an exact approved absolute executable and + argv vector; shells, package runners, inherited environment variables, and + project-defined `env`/`cwd` overrides are rejected. +- Child death, malformed frames, output saturation, cancellation, and cleanup + failure are fail-closed outcomes. +- Authorization records containing the server ID, command fingerprint, tool, + matching rule, and outcome are appended before forwarding. Audit failure is a + denial and does not expose command or tool arguments. +- Remote definitions select only an exact loopback gateway route. The gateway + resolves the configured endpoint itself, verifies TLS and hostnames, pins the + validated address, revalidates allowlisted redirects, and applies the same + tool policy and audit schema. +- Remote MCP forces authenticated egress, reserves configured origins from the + normal CONNECT broker, disables direct-IP CONNECT, and permits no direct + fallback. +- Modern Streamable HTTP is the default; bounded stateful 2025 behavior is an + explicit compatibility mode. Legacy 2024 HTTP+SSE is rejected. +- Legacy bpftrace records remain readable, while the guest broker emits the + versioned native observation format. +- TLS uprobes remain observation-only and never authorize a remote MCP request. + +Project MCP configuration must route each approved local server through the +trusted guest broker and each remote server through its deterministic loopback +gateway URL. Unbrokered commands, direct upstream URLs, custom credentials, +shells, package runners, environment overrides, and working-directory overrides +fail closed. + +#### Credential-free Safe Outputs + +When `github.safe_outputs.enabled` is true, the only agent-facing GitHub write +surface is the root-installed Safe Outputs MCP gateway. HTTPS GitHub auth, SSH +write auth, and forwarding the dedicated write-token variable as a sandbox +secret are rejected; a write-token variable also cannot alias forwarded Copilot +authentication. The guest verifies the exact installed gateway path, reports +the recorder as a mandatory healthy service, records validated and sanitized +intents in a hash-chained root-owned artifact, seals it only after +execution-cgroup cleanup, and permits one authenticated collection. The host +verifies the seal and the complete batch again before resolving the host-only +token. Staged mode never resolves a token. See +[the Safe Outputs architecture](architecture/safe-outputs.md). + +### Layer 6: Network Firewall + +Network access is controlled by the authenticated guest egress service: + +- **Default-deny:** All outbound traffic is blocked unless explicitly allowed +- **Domain and address policy:** DNS answers are canonicalized, classified, and + checked against exact domain, wildcard, CIDR, and restricted-address rules +- **Connection mediation:** Workload TCP flows use the mandatory DNS/SOCKS5 + gateway with configured connection and DNS budgets +- **Kernel containment:** nftables and cgroup v2 bind policy to the exact + delegated execution hierarchy, including nested descendants +- **Registry isolation:** package-enabled npm traffic reaches an isolated + loopback proxy; the workload cannot reach its npm upstream or trusted + registry SOCKS listener, and the proxy cannot dial externally +- **Fail-closed lifecycle:** Egress readiness gates Exec startup; service failure + revokes readiness and reverse-order shutdown stops Exec before network teardown +- **No host access:** loopback, link-local, metadata, private, multicast, and + other restricted destinations require explicit policy + +### Layer 7: Command Filtering + +The `CommandPolicy` engine provides an application-level defense layer: + +- **Allowlist/denylist model:** Commands are evaluated against glob-style patterns +- **Denylist priority:** Deny rules always override allow rules +- **Pipeline-aware:** Pipe chains (`|`), logical chains (`&&`, `||`), and semicolons (`;`) are split and each segment is evaluated independently +- **System admin commands blocked:** `sudo`, `su`, `mount`, `iptables`, `systemctl`, and other administrative commands are blocked in default and strict presets +- **Logging:** Blocked commands are logged for audit + +### Layer 8: Git Branch Protection + +Selected-repository Git operations are guarded before the real git binary executes: + +- Enabled by default and requires boundary enforcement +- Denies pushes and pulls involving `main`, `master`, or configured protected branches +- Requires the current branch and remote push/pull refs to match configurable feature patterns +- Matches normalized remote identity, so cloning the selected repository elsewhere does not bypass policy +- Uses eBPF to terminate direct execution of the hidden real git binary +- Does not replace GitHub server-side rulesets, which remain necessary against direct API ref mutation or alternate Git clients + +`sendbox-git` replaces generated policy scripts with typed +repository/workspace identity, bounded Git probes, supported argv/refspec +parsing, one clean environment for probes and final execution, and native +process replacement through a pre-verified absolute Git binary. Apple and Kata +deliver the signed Git policy through authenticated bootstrap and install +trusted wrapper copies before workload launch. Ambiguous remotes, +multiple effective push URLs, shell aliases, broad ref updates, unsafe +configuration injection, and unsupported transports fail closed for the +selected repository. + +Git admission is not an atomic remote authorization boundary: repository state +can change between local inspection and Git's own reads. Credential and egress +controls narrow alternate clients and hosting-provider APIs, but GitHub rulesets +or equivalent server-side branch protection remain mandatory. + +### Layer 9: Secrets Protection + +Secrets management prevents credential exposure: + +- Secrets are stored in **macOS Keychain** or mode-restricted files on Linux +- Injected as environment variables at container creation +- Package registry credentials are an exception: they are delivered only to + the trusted proxy and are rejected if also configured as workload secrets +- **Never written to disk** in plaintext inside the VM +- Environment is **cleaned up on VM shutdown** +- Sensitive environment variables (e.g., `LD_PRELOAD`, `LD_LIBRARY_PATH`) are stripped from the agent environment by the hardening process + +--- + +## Hardening Profiles + +SendBox provides three hardening profiles that control how aggressively the guest VM is locked down. + +### Standard Profile + +The default profile for regular development use. Provides strong security without interfering with common development workflows. + +- All sysctl hardening applied +- Dangerous capabilities dropped +- Seccomp profile active +- No `PR_SET_NO_NEW_PRIVS` (allows `sudo` inside VM if needed for package installation) +- Warning-level validation + +### Maximum Profile + +For high-security environments where the agent is untrusted. + +- All Standard protections, plus: +- `PR_SET_NO_NEW_PRIVS` set (prevents any privilege escalation) +- Additional capabilities dropped (`CAP_SETUID`, `CAP_SETGID`, `CAP_FOWNER`) +- Stricter seccomp profile (blocks `clone3`, `io_uring_*`) +- cgroup `release_agent` explicitly disabled +- `/proc` and `/sys` remounted with restricted options + +### Benchmark Profile + +Specifically designed to pass all 18 SandboxEscapeBench scenarios. Includes all Maximum protections plus explicit mitigations for each benchmark attack. + +- All Maximum protections, plus: +- Every sysctl parameter from the benchmark explicitly set +- All 18 scenarios verified in the security report +- Strictest seccomp profile +- All non-essential capabilities dropped (only `CAP_CHOWN`, `CAP_SETUID`, `CAP_SETGID`, `CAP_KILL`, `CAP_NET_BIND_SERVICE` retained — and only if not in Maximum mode) + +--- + +## Threat Model + +### In Scope + +These are threats SendBox is designed to defend against: + +| Threat | Defense | +|--------|---------| +| Agent attempts to access host filesystem | VM isolation — no host filesystem visible; only explicit virtiofs mounts | +| Agent attempts to contact unauthorized network endpoints | Network firewall — default-deny with domain allowlist | +| Agent overrides npm's registry or requests an upstream tarball directly | Kernel egress rules deny workload access to the configured upstream; npm receives only the loopback proxy | +| Malicious npm package relies on lifecycle hooks, archive escape, executable/native content, or subprocess APIs | Pre-delivery verification and non-executing archive inspection with fail-closed verdicts; npm scripts are disabled in the workload | +| Compromised package proxy attempts direct external access | Separate registry cgroup can reach only the trusted loopback SOCKS listener and cannot set `SO_MARK` | +| Agent attempts to obtain a private registry token | Registry credential is isolated in the authenticated proxy bootstrap and never enters workload secrets or environment | +| Agent attempts to execute dangerous commands | Command policy — allowlist/denylist with pipeline parsing | +| Agent attempts to escalate privileges within the VM | Capability dropping, seccomp, `PR_SET_NO_NEW_PRIVS`, sysctl hardening | +| Agent attempts to exfiltrate secrets | Secrets are env vars, not files; network firewall blocks unauthorized endpoints | +| Agent attempts to exploit kernel vulnerabilities | Separate guest kernel; guest compromise is contained by the selected hypervisor | +| Agent attempts to escape via host runtime bugs | Apple provider avoids OCI runtimes; Kata provider relies on patched containerd, Kata shim, and hypervisor components | +| Agent attempts cloud metadata access | `route_localnet` disabled and metadata endpoints must remain outside the network allowlist | +| Agent attempts to intercept network traffic | `CAP_NET_RAW` dropped; separate virtual NIC | +| Agent attempts to load malicious kernel modules | `kernel.modules_disabled=1`; `CAP_SYS_MODULE` dropped; seccomp blocks `init_module` | +| Agent attempts a disallowed MCP tool call | The stdio broker or HTTP gateway filters discovery and denies the call before upstream delivery; denied stdio requests receive `-32001` and denied notifications are dropped | +| Agent attempts to push or pull a protected selected-repository branch | Root-installed git policy validates current and remote refs; eBPF terminates direct real-git execution | +| Agent reads back host keystrokes it was never sent | Terminal input is host→guest only; direction binding on the control channel rejects a guest-originated `StandardInput` event | +| Interactive workload escapes its terminal to reach the launcher | The pseudoterminal secondary is the child's controlling terminal after `setsid`; the launcher keeps the primary and applies the same seccomp, capability and uid drops as a headless launch | +| Pasted credentials leak through host logs | `Event`, `ClientFrame`, `TerminalCommand`, `LauncherControl` and `HostTerminalCommand` all render input as a byte count, never as content | +| Agent stalls cancellation by refusing to read its terminal | Control and bulk input use separate bounded paths at every layer; saturated input is dropped with a diagnostic instead of blocking cancellation | + +### Out of Scope + +These threats are not addressed by SendBox: + +| Threat | Reason | +|--------|--------| +| Hardware side-channel attacks (Spectre, Meltdown) | Requires CPU microcode/hardware mitigations; beyond hypervisor scope | +| Attacks against the selected hypervisor or host runtime | Provider components must be patched by Apple, Kata, containerd, and the operating-system vendor | +| Physical access attacks | Physical access bypasses all software security | +| Social engineering of the host user | User-level risk; SendBox cannot prevent the user from disabling protections | +| Denial-of-service against the host | VM resource limits (CPU/memory) mitigate but don't eliminate resource exhaustion | +| Supply chain attacks on the base VM image | Image provenance and signing are the user's responsibility | +| Proving arbitrary package source code is safe | Static package findings are policy signals, not a complete malware detector | +| Zero-day hypervisor escapes | No software sandbox can eliminate hypervisor zero-day risk | +| Semantic authorization of separately launched local MCP binaries or alternate local clients | Protocol authorization applies to traffic through the installed stdio broker or HTTP gateway; command policy and image minimization remain defense in depth | +| Direct GitHub API/GraphQL ref mutation or alternate Git clients | The bundled-git guard cannot constrain arbitrary bearer-token API calls or independently installed clients; use GitHub server-side rulesets | + +--- + +## CVE Reference + +The following CVEs are directly addressed by the Apple provider's architecture. Kata deployments must additionally track containerd, Kata shim, and hypervisor advisories. + +| CVE | Description | SendBox Mitigation | +|-----|-------------|-------------------| +| CVE-2022-0811 | CRI-O kernel parameter injection | No CRI-O; `core_pattern` locked | +| CVE-2019-11246 | kubectl cp symlink traversal | No kubectl; explicit virtiofs mounts | +| CVE-2019-5736 | runc binary overwrite via `/proc/self/exe` | Apple provider has no runc; Kata workload runs behind a VM boundary | +| CVE-2024-21626 | runc fd leak for host filesystem access | Apple provider has no runc; Kata workload does not share the host mount namespace | +| CVE-2016-5195 | Dirty COW — COW race condition | Separate kernel; host is XNU | +| CVE-2022-0847 | Dirty Pipe — pipe buffer flag manipulation | Separate kernel; host is XNU | + +--- + +## Verification + +The boundary a configuration produces is inspected statically, without generating or running any +executable: + +```bash +sendbox boundary inspect --config config/example-sandbox.yaml --json +``` + +The inspection is deterministic and reports the resolved runtime, resources, command and network +policy, package policy, secret names, devcontainer and GitHub settings, plus the MCP observer boundary +(transports, authorization boundary, runtime integration, and allowed server command patterns). + +The workspace test suite verifies that: +- Each sysctl parameter is correctly set +- Each dangerous capability is dropped +- Each dangerous syscall is blocked by seccomp +- Egress rules, the Git guard, and the MCP broker reject the denied cases +- Package metadata rewriting, verification, malicious fixtures, digest-bound + cache reuse, concurrent analysis, policy invalidation, credential isolation, + and report tamper handling fail closed +- Configuration validation catches unsafe settings + +```bash +make lint +make test +cargo run --locked --manifest-path tools/sendbox-qualification/Cargo.toml -- validate +``` diff --git a/vendor/sendbox/docs/security/egress-enforcement-trust-boundary.md b/vendor/sendbox/docs/security/egress-enforcement-trust-boundary.md new file mode 100644 index 0000000..b65450b --- /dev/null +++ b/vendor/sendbox/docs/security/egress-enforcement-trust-boundary.md @@ -0,0 +1,188 @@ +# Egress enforcement trust boundary and runtime integration contract + +Status: **production runtime integration**. Companion to +[`docs/architecture/egress-enforcement.md`](../architecture/egress-enforcement.md). +This document defines the trust boundary of `sendbox-egress`, its threat model, +the residual risks it does *not* close, and the contract a runtime supervisor +must satisfy to integrate it. + +## Trust boundary + +```text +untrusted workload (agent cgroup) + |-- loopback DNS/public SOCKS --> trusted gateways (broker cgroup + SO_MARK) + `-- loopback npm HTTP ---------> trusted package proxy (registry cgroup) + `-- registry-only loopback SOCKS + --> trusted gateway (broker + SO_MARK) + +nftables default-drop denies every other cgroup/destination combination +``` + +- **Untrusted:** every workload process beneath the delegated agent ancestor. It + runs in nested execution leaves and may reach *only* the loopback DNS and + public CONNECT broker ports plus the workload-facing npm proxy when enabled. +- **Trusted broker:** DNS/SOCKS gateways in the broker cgroup mark their + external sockets and enforce `PolicyEngine` in userspace. +- **Trusted registry proxy:** the package analyzer runs as a separate + unprivileged identity in the registry cgroup. It can reach only its + registry-only loopback SOCKS listener and cannot set `SO_MARK`. +- **Trusted supervisor:** arms enforcement and places every service in its + expected cgroup. nftables enforces identity and reachability in the kernel as + defense in depth. +- The boundary is a Linux network namespace with the crate-owned nftables table. + The crate never modifies anything outside its owned table, cgroup subtree, and + namespace. + +## What the kernel layer enforces + +- The agent cgroup can originate traffic **only** to the exact loopback broker + ports (CONNECT always; DNS only when `allow_dns = true`), the configured + npm proxy port, and, in a governed session with brokered credentials, the + credential relay port (15084). The relay is served by the trusted guest + supervisor and forwards to the host over the authenticated control channel, + not through the broker cgroup. +- The registry cgroup can originate traffic **only** to the exact + registry-only SOCKS port. It cannot reach public broker ports or external + destinations. +- The broker cgroup can originate external traffic **only** when the socket + carries the fixed `SO_MARK`, and never to cloud-metadata addresses. +- Any other process (a sibling in none of the owned cgroups) is denied the broker + ports and external egress. This is the concrete improvement over UID-based + isolation: sharing a UID no longer grants broker-class reachability. +- New inbound to the broker's own loopback ports is scoped by `iif lo` + exact + destination + port. The originating identity is not visible at the input hook, + but the **output** chain already permits only the intended source-cgroup and + destination-port pair. +- All UDP/QUIC from the agent (other than DNS to the broker) is dropped; the + CONNECT broker additionally answers `UnsupportedProtocol` (native protocol) or + `Command not supported` (SOCKS5 `BIND`/`UDP ASSOCIATE`) for any non-TCP + request. Raw `AF_PACKET` sockets operate below the IP layer and are **not** + visible to the `inet` filter hooks — dropping `CAP_NET_RAW` from the agent is + the runtime's responsibility (see contract below). + +## What the userspace brokers enforce + +- A selectable client-facing front end (`ConnectFrontend`): the crate's native + bounded CONNECT framing (default) or standard SOCKS5 (RFC 1928, no-auth, + `CONNECT` only). The front end is fixed per instance from configuration, never + auto-detected from client bytes. Both front ends enforce policy through the + identical resolve/pin/decide/dial path; only the wire framing differs. +- Domain allow/deny with blocked-domain precedence and wildcard rules that never + match an apex or an unrelated suffix. +- An address-class check no domain grant can override; a restricted class + (loopback, link-local, RFC 1918, ULA, multicast, metadata, unspecified) needs + an explicit IP/CIDR grant. +- IPv4-mapped-IPv6 canonicalization so a blocked/allowed CIDR cannot be bypassed + or missed through address encoding. +- DNS validation of every CNAME hop and returned address, TTL capping, and an + expiring `(name, ip)` authorization that pins the exact validated address — + a later CONNECT can only use an address a DNS answer actually validated, + defeating rebinding. +- Deterministic DNS query-name exfiltration budgets: total QNAME/label limits, a + QTYPE allowlist, a response-record cap, and per-window query-count, query-octet, + distinct-name, and distinct-dynamic-label budgets with bounded state. Every + structural/budget field is range-validated (fail closed) at compile time. +- An exact `github.com` grant delegates to validated, expiring public + destinations from the fixed official HTTPS Meta API. Every broker uses the + same snapshot revision; refresh/expiry retires DNS pins and rechecks + in-flight resolution/dial decisions. Meta CIDRs cannot unlock private, + link-local, metadata or other restricted classes. + +The trusted gateway retrieves Meta through its marked dialer, without +credentials, redirects or environment proxies, and verifies TLS for +`api.github.com`. It publishes provenance before activating a candidate. +Initial fetch or provenance-publication failure prevents readiness; refresh +outages retain only a bounded last-good lease. See +[refresh and evidence](../configuration.md#network-grants) for exact limits. + +## Threat model and mitigations + +| Threat | Mitigation | +|---|---| +| Direct outbound bypassing the broker | Kernel default-drop; the agent ancestor match confines every nested execution leaf to public loopback broker ports and the optional npm proxy. | +| Workload bypasses package analysis with an npm registry override or direct tarball URL | The workload policy denies the configured npm upstream and the agent cgroup cannot reach the registry-only SOCKS listener. | +| Compromised package proxy dials externally or reaches the public broker | The registry cgroup can reach only the trusted registry SOCKS port and has no `SO_MARK` capability. | +| Sharing the broker's identity to egress | cgroup v2 identity + required `SO_MARK`; a sibling process is denied. | +| DNS rebinding | Expiring `(name, ip)` authorization pins the exact validated address. | +| SSRF to cloud metadata | Address-class denial in policy **and** an explicit kernel drop for the broker. | +| DNS-tunneling exfiltration | Deterministic, bounded structural limits and per-window budgets. | +| Broker crash leaving traffic open | Rules persist on broker death (fail closed); the guard re-arms on restart. | +| Partial/failed ruleset update | Atomic `destroy + create` transaction; a failed update leaves the previous table intact. A failed **re-arm** never runs `nft` cleanup, so a live instance's table is preserved rather than destroyed. | +| Lingering process during teardown | Fail-closed teardown removes cgroups first; if a cgroup still holds a process, the nftables table is **retained** (the process cannot regain egress) and the error is surfaced. Teardown is retryable: cgroup and nftables removal are tracked independently, so a later call retries whichever stage failed. | +| Off-path DNS response spoofing | The forwarding resolver connects its UDP socket to the exact upstream, so the kernel drops any reply whose source is not the full upstream `SocketAddr` (address **and** port), not merely the same IP. | +| Symlink race on cgroup paths | All cgroup filesystem operations are descriptor-relative via `cap-std` (`RESOLVE_BENEATH`); an escaping symlink under the root is refused. | +| Raw-socket egress bypass | The agent runs unprivileged with `CAP_NET_RAW` dropped; the live suite asserts every capability set is empty and that raw-socket creation is denied. | +| Unbounded DNS-only cache growth | The authorization cache prunes expired entries on insert and enforces a deterministic hard capacity derived from the DNS budget. | +| CONNECT resolution bypassing DNS controls | A fresh CONNECT-path resolution applies the same `DnsGuard` (structural limits, QTYPE allowlist, response cap, budget); with `allow_dns = false` it does not resolve at all. | +| Slowloris / floods | Bounded handshakes, per-message caps, bounded concurrency, inline (never spawned) rejections. | + +## Residual risks (explicitly not closed) + +- **Shared-cloud delegation.** The requested Meta scope includes Actions + CIDRs and wildcard cloud/storage services that can host unrelated tenants. + A direct-IP grant is network reachability, not GitHub ownership, + authentication or operation approval. Existing deny/private/MCP/package + boundaries remain necessary. The feed is authenticated by HTTPS, not a + separately signed GitHub artifact. +- **Snapshot transitions.** Removing a grant affects new connections; existing + tunnels are bounded to 300 seconds, not forcibly revoked. Exported evidence + contains the latest refresh attempt and expiry, not every transition. +- **Metadata by hostname over an uncovered address.** The metadata address list + (`address::METADATA_V4_ADDRESSES` / `METADATA_V6_ADDRESSES`) is deterministic + but not exhaustive. A provider that serves metadata purely by a hostname + resolving to an address not on the list must be blocked with `blocked_domains`. +- **Query-name exfiltration within budget.** The budgets bound exfiltration + bandwidth deterministically; they do not make a broad `allowed_domains` policy + safe. A narrow allowlist remains the primary control. +- **Raw sockets.** `AF_PACKET` is below the IP filter hooks; the runtime must + drop `CAP_NET_RAW` (and generally run the agent unprivileged). The live suite + proves this by running the agent under `setpriv` with all capability sets + cleared and `no_new_privs`, then asserting raw-socket creation is denied — but + the *production* runtime is still responsible for the equivalent privilege + drop. +- **Loopback upstream resolvers.** The forwarding resolver's upstream must be + external (reached via the marked broker path), not a loopback service inside + the sandbox namespace, which the input chain does not admit. +- **Capability/privilege of the agent.** cgroup identity does not drop + capabilities; privilege drop is the runtime supervisor's job. +- **Inherited configuration descriptors.** The harness accepts a pre-opened + `--policy-fd` / `--fixtures-fd` and otherwise reads with `O_NOFOLLOW` before + any namespace/cgroup transition. Stable Rust's `std::process::Command` cannot + pass an arbitrary inherited fd to a child across a `setpriv`/`ip netns exec` + re-exec, so the live path reads config in-process before transitions rather + than reopening a predictable path afterward. + +## Runtime integration contract + +A runtime supervisor integrating this crate must: + +1. Create the sandbox network namespace and any veth/routing before arming. +2. Call `ArmedEgress::arm` (or `arm_under` with a namespace-scoped `NftRunner`). + It refuses to arm unless enforcement is fully installed and verified. +3. Retain `CAP_NET_ADMIN` in the namespace for the broker (to set `SO_MARK` and + load nftables); preflight probes this. +4. Start every DNS/SOCKS **gateway** in the broker cgroup, configured with the + `MarkDialer` and a `ForwardingResolver` carrying the same mark. Pick the + CONNECT front end (`ConnectFrontend::Custom` or `Socks5`) to match the + client; the choice is fixed configuration, never negotiated from bytes. +5. If package analysis is enabled, start the proxy in the registry cgroup with + a distinct UID/GID, cleared capabilities, `no_new_privs`, and no socket-mark + privilege. Expose its trusted SOCKS listener only to that cgroup. +6. For production execution, arm with controller delegation, keep the agent + ancestor empty, and start workloads only in descendant execution leaves. + Direct `place_agent` is deliberately rejected in delegated mode. +7. Run the agent unprivileged with `CAP_NET_RAW` dropped (raw sockets are out of + the `inet` hooks' scope) and `no_new_privs` set. +8. Keep the broker and registry cgroups stable across service restarts — + re-place new pids rather than recreating cgroups, so loaded nftables cgroup + identities stay valid. +9. On shutdown, stop the agent and registry proxy, then drop/`teardown` the + guard. Teardown is fail-closed ordered (cgroups before nftables), idempotent, + and absent-safe; + a surfaced error means enforcement was deliberately retained and must be + logged and retried, not ignored. + +The crate remains provider-neutral. Production integration lives in +`sendbox-host`, authenticated bootstrap, the Apple/Kata providers, and the guest +Egress service. Hyperlight rejects restrictive egress policy because it does +not implement this persistent guest boundary.