From 4745556f073c92cdbc397ff175af263f06e5d8a5 Mon Sep 17 00:00:00 2001 From: htjulia Date: Tue, 24 Nov 2026 17:53:49 +0900 Subject: [PATCH 1/2] test: make two tests pass reliably on Linux CI runners Running the CI job in a Linux container before the first workflow run found two tests that only pass on a fast macOS host: - The OCI fake-docker tests wrote the script from the test process and ran it at once. A concurrent test's fork could inherit the write handle, so exec failed with "Text file busy" (1 in 3 runs). A separate cp process now creates the script; 15 Linux runs in a row pass. - The worker debug-session test used a 300 ms request watchdog, which an ordinary request (the worker compiles the component per request) can exceed on a slow runner. The watchdog is 2 s and the breakpoint wait 2.5 s, so the test still checks that a stopped request skips it. Tags: test, ci Co-Authored-By: htjulia --- .../tests/async_host_composition.rs | 7 +-- crates/protrus-runtime-oci/src/lib.rs | 47 ++++++++++++------- 2 files changed, 33 insertions(+), 21 deletions(-) diff --git a/crates/protrus-host/tests/async_host_composition.rs b/crates/protrus-host/tests/async_host_composition.rs index 8bd48db..4acce87 100644 --- a/crates/protrus-host/tests/async_host_composition.rs +++ b/crates/protrus-host/tests/async_host_composition.rs @@ -3296,8 +3296,9 @@ async fn a_worker_debug_session_stops_a_request_in_the_worker_and_skips_the_requ .set_breakpoint(&session, BreakpointSpec::Function(handler.clone())) .await .unwrap(); - // The watchdog is shorter than the pause below; a debugged module's requests skip it. - deployment.worker_proxy.set_request_timeout_millis(300); + // The watchdog is shorter than the pause below; a debugged module's requests skip it. It + // still leaves room for an ordinary request, which compiles the component on a slow runner. + deployment.worker_proxy.set_request_timeout_millis(2_000); let request = tokio::spawn(get(deployment.application(), "/hello")); let stop = relay @@ -3308,7 +3309,7 @@ async fn a_worker_debug_session_stops_a_request_in_the_worker_and_skips_the_requ assert_eq!((stop.module_id.as_str(), stop.revision), ("hello", 1)); assert_eq!(stop.frames[0].function, handler); assert!(!stop.frames[0].locals.is_empty(), "the worker reads the handler's locals"); - tokio::time::sleep(Duration::from_millis(600)).await; + tokio::time::sleep(Duration::from_millis(2_500)).await; assert!(!request.is_finished(), "the request waits at the breakpoint"); assert_eq!(relay.current(&session).await.unwrap().as_deref(), Some(&*stop)); let listed = relay.list().await; diff --git a/crates/protrus-runtime-oci/src/lib.rs b/crates/protrus-runtime-oci/src/lib.rs index 476326d..e5e1964 100644 --- a/crates/protrus-runtime-oci/src/lib.rs +++ b/crates/protrus-runtime-oci/src/lib.rs @@ -1204,6 +1204,23 @@ impl OciWorkerLaunch { #[cfg(test)] mod tests { + /// Writes an executable fake `docker` at `path`. A separate `cp` process creates the file, so + /// this test process never holds a write handle on it: on Linux a concurrent test's fork could + /// inherit that handle and make running the script fail with `Text file busy`. + #[cfg(unix)] + fn fake_docker(path: &std::path::Path, script: &str) { + use std::os::unix::fs::PermissionsExt; + let source = path.with_extension("src"); + std::fs::write(&source, script).unwrap(); + assert!(std::process::Command::new("cp") + .arg(&source) + .arg(path) + .status() + .unwrap() + .success()); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).unwrap(); + } + use super::*; use protrus_runtime_worker::{PROTOCOL_VERSION, WorkerHttpTarget}; use std::{ @@ -1633,7 +1650,7 @@ mod tests { #[cfg(unix)] #[test] fn docker_cli_removes_a_stale_deterministic_name_before_run() { - use std::{fs, os::unix::fs::PermissionsExt}; + use std::fs; let base = std::env::temp_dir().join(format!( "protrus-oci-reconcile-{}-{}", @@ -1646,16 +1663,14 @@ mod tests { fs::create_dir(&base).unwrap(); let log = base.join("docker.log"); let script = base.join("docker"); - fs::write( + fake_docker( &script, format!( "#!/bin/sh\nprintf '%s ' \"$@\" >> {}\nprintf '\\n' >> {}\nexit 1\n", log.display(), log.display() - ), - ) - .unwrap(); - fs::set_permissions(&script, fs::Permissions::from_mode(0o700)).unwrap(); + ).as_ref(), + ); let engine = DockerCliEngine { binary: script, ..Default::default() @@ -1676,18 +1691,16 @@ mod tests { #[cfg(unix)] #[test] fn docker_cli_stops_the_primary_and_associated_runtimes_together() { - use std::{fs, os::unix::fs::PermissionsExt}; + use std::fs; let base = std::env::temp_dir().join(format!("protrus-oci-stop-{}", std::process::id())); fs::create_dir(&base).unwrap(); let log = base.join("docker.log"); let script = base.join("docker"); - fs::write( + fake_docker( &script, - format!("#!/bin/sh\nprintf '%s ' \"$@\" > {}\n", log.display()), - ) - .unwrap(); - fs::set_permissions(&script, fs::Permissions::from_mode(0o700)).unwrap(); + format!("#!/bin/sh\nprintf '%s ' \"$@\" > {}\n", log.display()).as_ref(), + ); let engine = DockerCliEngine { binary: script, ..Default::default() @@ -1707,17 +1720,15 @@ mod tests { #[cfg(unix)] #[test] fn gateway_pair_is_not_running_when_an_associated_runtime_exits() { - use std::{fs, os::unix::fs::PermissionsExt}; + use std::fs; let base = std::env::temp_dir().join(format!("protrus-oci-running-{}", std::process::id())); fs::create_dir(&base).unwrap(); let script = base.join("docker"); - fs::write( + fake_docker( &script, - "#!/bin/sh\nif [ \"$4\" = gateway ]; then echo false; else echo true; fi\n", - ) - .unwrap(); - fs::set_permissions(&script, fs::Permissions::from_mode(0o700)).unwrap(); + "#!/bin/sh\nif [ \"$4\" = gateway ]; then echo false; else echo true; fi\n".as_ref(), + ); let engine = DockerCliEngine { binary: script, ..Default::default() From 812c93cdbd44698d80a4ff21e04c5612cc8bd5f4 Mon Sep 17 00:00:00 2001 From: htjulia Date: Tue, 24 Nov 2026 18:10:11 +0900 Subject: [PATCH 2/2] docs: add the public release documentation, user guide and CI Prepares the repository to be made public (the visibility change itself is separate): - README, LICENSE (MPL-2.0), CHANGELOG, CONTRIBUTING (code map, invariants, the local command CI runs), SECURITY (threat model and scope), CODE_OF_CONDUCT and ROADMAP (including what is deliberately not ported). - An English user guide in docs/guide/ (getting started, signing and deploying, configuration, isolation and workers, sharing code, host services, debugging, databases), written against this branch with the commands and programs it shows actually run. - .github: CODEOWNERS, FUNDING, PR and issue templates, grouped Dependabot, and CI: cargo test --workspace and cargo audit behind a single required ci-complete job; the Docker OCI tests run on main and on demand. - AGENTS.md leaves the repository; it stays local as working notes. - Stale statements fixed: the debug tools on worker/oci in the runbook, the async-wasm note in the SQLx pool guide, the ModuleStatus.kind comment, and an internal reference in design 04. Closes #103 Tags: docs, ci, release Co-Authored-By: htjulia --- .github/CODEOWNERS | 5 + .github/FUNDING.yml | 15 + .github/ISSUE_TEMPLATE/bug_report.yml | 67 +++ .github/ISSUE_TEMPLATE/config.yml | 8 + .github/ISSUE_TEMPLATE/feature_request.yml | 35 ++ .github/PULL_REQUEST_TEMPLATE.md | 47 ++ .github/dependabot.yml | 40 ++ .github/workflows/ci.yml | 101 +++++ .gitignore | 3 + AGENTS.md | 15 - CHANGELOG.md | 61 +++ CODE_OF_CONDUCT.md | 72 +++ CONTRIBUTING.md | 100 +++++ LICENSE | 373 ++++++++++++++++ README.md | 130 ++++++ ROADMAP.md | 64 +++ SECURITY.md | 76 ++++ crates/protrus-web/src/lib.rs | 3 +- .../04-deployment-and-runtime-protocol.md | 2 +- docs/guide/01-getting-started.md | 245 +++++++++++ docs/guide/02-building-and-signing-modules.md | 412 ++++++++++++++++++ docs/guide/03-deploying-and-operating.md | 391 +++++++++++++++++ docs/guide/04-configuration.md | 186 ++++++++ docs/guide/05-isolation-and-workers.md | 225 ++++++++++ docs/guide/06-sharing-code.md | 155 +++++++ docs/guide/07-host-services.md | 240 ++++++++++ docs/guide/08-debugging-and-observability.md | 139 ++++++ docs/guide/09-databases.md | 175 ++++++++ docs/guide/README.md | 37 ++ docs/operations/async-sqlx-scope-pools.md | 10 +- docs/operations/protrus-host-runbook.md | 20 +- 31 files changed, 3422 insertions(+), 30 deletions(-) create mode 100644 .github/CODEOWNERS create mode 100644 .github/FUNDING.yml create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml delete mode 100644 AGENTS.md create mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 ROADMAP.md create mode 100644 SECURITY.md create mode 100644 docs/guide/01-getting-started.md create mode 100644 docs/guide/02-building-and-signing-modules.md create mode 100644 docs/guide/03-deploying-and-operating.md create mode 100644 docs/guide/04-configuration.md create mode 100644 docs/guide/05-isolation-and-workers.md create mode 100644 docs/guide/06-sharing-code.md create mode 100644 docs/guide/07-host-services.md create mode 100644 docs/guide/08-debugging-and-observability.md create mode 100644 docs/guide/09-databases.md create mode 100644 docs/guide/README.md diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..ae33f2f --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,5 @@ +# Default owner for everything in the repo. +# Must be a GitHub login (username), not a display name — htcom-code's display +# name happens to be "htjulia", but @-references resolve by login only. +# See https://docs.github.com/articles/about-code-owners +* @htcom-code diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..367a43f --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,15 @@ +# These are supported funding model platforms + +github: htcom-code +#patreon: # Replace with a single Patreon username +#open_collective: # Replace with a single Open Collective username +#ko_fi: # Replace with a single Ko-fi username +#tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +#community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +#liberapay: # Replace with a single Liberapay username +#issuehunt: # Replace with a single IssueHunt username +#lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +#polar: # Replace with a single Polar username +#buy_me_a_coffee: # Replace with a single Buy Me a Coffee username +#thanks_dev: # Replace with a single thanks.dev username +#custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..b152c78 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,67 @@ +name: Bug report +description: Protrus misbehaves — wrong result, crash, leaked worker/container, or a gate / isolation / MCP / debug fault. +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + Thanks for the report. **Protrus** is a Rust host for signed WebAssembly component + modules: it verifies, deploys, routes, hot-swaps and unloads them in-process, in worker + processes, or in OCI containers, behind a `/platform` REST and MCP control plane. + + The reports we most want: + - **A gate that let something through** — an unsigned or untrusted artifact, a refused + capability, or a failing candidate that ended up serving. + - **A serving revision lost** — a failed update, rollback or restart that left a module + down or routed to the wrong revision. + - **Leftovers** — worker processes, containers, sockets or networks that outlive their module. + - **Protean parity** — a REST / MCP / config / error contract that differs from Java Protean + without a `non-parity` note in `docs/design/`. + + **Security issues:** do **not** file here — see [SECURITY.md](../blob/main/SECURITY.md). + - type: textarea + id: reproducer + attributes: + label: Minimal reproducer + description: The bootstrap JSON, the signed manifest, and the REST/MCP calls that trigger the bug. A failing test is ideal. + render: json + validations: + required: true + - type: textarea + id: expected + attributes: + label: Expected behaviour + description: What you expected Protrus to do (and, if relevant, what Java Protean does). + validations: + required: true + - type: textarea + id: actual + attributes: + label: Actual behaviour + description: What happened instead. Include the HTTP status / MCP error and the host's stderr events. + validations: + required: true + - type: dropdown + id: topology + attributes: + label: Host topology (`execution_mode`) + options: + - async-wasm + - worker + - oci + validations: + required: true + - type: input + id: version + attributes: + label: Protrus version or commit + placeholder: e.g. 0.1.0 or a commit SHA + validations: + required: true + - type: input + id: environment + attributes: + label: OS / Rust toolchain / Docker + placeholder: e.g. Ubuntu 24.04, rustc 1.97.1, Docker 28 + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..499323a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: Security vulnerability + url: https://github.com/htcom-code/protrus/security/advisories/new + about: Report a vulnerability privately — do not open a public issue. See SECURITY.md. + - name: Question / usage help + url: https://github.com/htcom-code/protrus/discussions + about: For "how do I …" questions and embedding help, open a Discussion rather than a bug report. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..d31f186 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,35 @@ +name: Feature request +description: Suggest a Protrus capability — lifecycle, gates, isolation, worker/OCI, MCP, debugging, data access, or an embedding API. +labels: ["enhancement"] +body: + - type: markdown + attributes: + value: | + **Protrus** is a library: embedders cannot patch it where they use it, so it aims to carry + every Java Protean capability, exposed or not as the embedder chooses. Before proposing, + please check [ROADMAP.md](../blob/main/ROADMAP.md) — some things are deliberately not done: + + | Not planned | Why | + | --- | --- | + | Compiling Java (or any) source on the server | Modules are pre-built, signed Wasm components | + | Returning a module's source (`get_module_source`) | A component cannot be turned back into source | + | JVM-only knobs (`worker.jvm-args`, executor pools, shared classpath dirs) | No JVM; the Wasm equivalents are described in `docs/design/30` | + | Java bridge wire format (`/__bridge/invoke`, reflection JSON, HMAC) | Host services use named `service@version` calls over private sockets | + - type: textarea + id: problem + attributes: + label: Problem / use case + description: What are you trying to do, and what is missing or awkward today? + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Proposed solution + description: The API, config key, manifest field or behaviour you would like. If Java Protean already has it, name the class or key. + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: Alternatives considered diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..c73ca99 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,47 @@ + + +## What & why + + + +## Type of change + +- [ ] `fix` — bug fix (no new API) +- [ ] `feat` — new capability (lifecycle, gates, isolation, worker/OCI, MCP, debug, data access) +- [ ] `perf` — performance, no observable behaviour change +- [ ] `docs` — documentation only +- [ ] `refactor` / `chore` / `test` / `ci` — no behaviour change + +## Invariants (see CONTRIBUTING.md) + +- [ ] **Protean parity** — every changed HTTP / MCP / config / error surface was checked against the + Java Protean contract; any deliberate difference is recorded as `non-parity` in `docs/design/` + (reason, user impact, migration, verification). +- [ ] **No gate bypass** — nothing deploys or launches an artifact without the signature and + promotion gates; worker and OCI launches still re-verify. +- [ ] **Revision fencing** — a failed candidate never replaces the serving revision. +- [ ] **Capability boundary** — a module gets only what it was granted; no secret reaches argv, + environment, container labels or logs. +- [ ] **No leftovers** — workers, containers, sockets and Docker test fixtures are cleaned up. + +## Verification + +```bash +cargo test --workspace +# OCI / Docker paths, when touched: +cargo test -p protrus-host --test mcp_scenarios -- --ignored +cargo test -p protrus-host --test async_host_composition -- --ignored +``` + +- [ ] `cargo test --workspace` passes (Docker-backed tests ran, or say why not) +- [ ] No new `cargo clippy --workspace --all-targets` warnings +- [ ] Docs updated if behaviour or configuration changed (`README.md`, `docs/guide/`, `docs/design/`) + +## Related + + diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..e11e8a0 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,40 @@ +version: 2 +updates: + # The Rust workspace (crates/*). Grouped so one PR carries a coherent set of bumps. + - package-ecosystem: cargo + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 5 + groups: + # wasmtime and its crates move in lockstep (one release number); the component host, + # the linker and the guest-debug API are all pinned to it. + wasmtime: + patterns: + - "wasmtime*" + - "wasi-*" + - "cranelift-*" + # sqlx crates share one version line (the SQL module store and the worker DB adapters). + sqlx: + patterns: + - "sqlx*" + # Everything else that is not a major bump. + rust-minor-and-patch: + update-types: ["minor", "patch"] + exclude-patterns: + - "wasmtime*" + - "wasi-*" + - "cranelift-*" + - "sqlx*" + # poc/* and examples/artifacts/* are guest-component fixtures with their own lockfiles; + # their versions follow the WIT world, not Dependabot. + + # GitHub Actions used in .github/workflows/. + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 5 + groups: + actions: + patterns: ["*"] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b2b502a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,101 @@ +# GitHub Actions CI. The gate is `cargo test --workspace` (the same command as CONTRIBUTING.md) +# plus a RustSec audit; `ci-complete` is the single required status. +# +# What runs where: +# - test: the whole workspace. Guest-component fixtures are built on the fly with the +# wasm32-unknown-unknown target and wasm-tools. GitHub-hosted ubuntu runners ship Docker, so +# the PostgreSQL / MySQL tests that start throwaway containers run here too. +# - docker-integration: the `#[ignore]`d OCI tests (container scenario, signed OCI pairs). They +# build the production Linux worker image inside Docker, which takes minutes, so they run on +# pushes to main and on demand rather than on every PR, and are not part of the gate. + +name: CI + +on: + push: + branches: [main] + paths: + - "**/*.rs" + - "**/Cargo.toml" + - "**/Cargo.lock" + - "**/*.wit" + - "**/*.sh" + - "poc/worker-container-fixture/**" + - "examples/**" + - ".github/workflows/ci.yml" + # No paths filter on pull_request on purpose: every PR runs the workflow so the required + # `ci-complete` check always reports. A filtered PR trigger skips the whole workflow on a + # docs-only PR and leaves the required check waiting forever. + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + CARGO_TERM_COLOR: always + # Incremental caches only grow on CI; they are never reused across runs. + CARGO_INCREMENTAL: "0" + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v7.0.1 + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc + with: + toolchain: "1.97.1" + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@v2.9.3 + - uses: taiki-e/install-action@v2.90.8 + with: + tool: wasm-tools@1.263.0 + - name: test + run: cargo test --workspace --locked + + audit: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7.0.1 + - uses: taiki-e/install-action@v2.90.8 + with: + tool: cargo-audit + - name: RustSec advisories + run: cargo audit + + docker-integration: + if: github.event_name != 'pull_request' + needs: test + runs-on: ubuntu-latest + timeout-minutes: 90 + steps: + - uses: actions/checkout@v7.0.1 + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc + with: + toolchain: "1.97.1" + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@v2.9.3 + - uses: taiki-e/install-action@v2.90.8 + with: + tool: wasm-tools@1.263.0 + - name: container scenario + run: cargo test --locked -p protrus-host --test mcp_scenarios -- --ignored + - name: signed OCI pairs + run: cargo test --locked -p protrus-host --test async_host_composition -- --ignored + + # The single required status: green only when every gate job succeeded. + ci-complete: + if: always() + needs: [test, audit] + runs-on: ubuntu-latest + steps: + - name: gate + run: | + echo "test=${{ needs.test.result }} audit=${{ needs.audit.result }}" + [ "${{ needs.test.result }}" = success ] && [ "${{ needs.audit.result }}" = success ] diff --git a/.gitignore b/.gitignore index 884257b..dde5dd7 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,6 @@ target/ /artifacts/ /poc/component-echo/src/bindings.rs /poc/module-component/src/bindings.rs + +# Agent working notes are kept locally, not in the public repository. +AGENTS.md diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index 3806b60..0000000 --- a/AGENTS.md +++ /dev/null @@ -1,15 +0,0 @@ -# Protrus 작업 전제 조건 - -Protrus는 형제 저장소 `../protean`의 동적 모듈 플랫폼을 Rust로 이식하는 프로젝트다. - -기능, HTTP REST 경로/요청/응답, SSE 이벤트, MCP 도구·resource·transport, 설정 키, 오류 계약, -운영 Console 계약을 새로 추가하거나 변경하기 전에는 반드시 다음을 수행한다. - -1. `../protean`에서 대응 Java production source를 찾고, 실제 controller mapping·입력·출력·부작용을 확인한다. -2. 대응 Java test와 필요하면 `protean-console`, `java_mcp`의 소비자 fixture를 확인한다. -3. Protrus 설계 문서의 parity/non-parity 결정을 대조한다. -4. 확인 근거가 없는 표면은 임의의 URL, JSON shape, query parameter, 이벤트 이름, 또는 호환 별칭으로 공개하지 않는다. -5. Rust에서 의도적으로 다른 계약을 채택할 때에는 구현 전에 설계 문서에 `non-parity` 사유와 사용자 영향, - migration note, 검증 조건을 기록한다. - -`/platform`은 고정된 control-plane namespace다. `/v1` 등의 대체 namespace를 임의로 도입하지 않는다. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..d2e4584 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,61 @@ +# Changelog + +All notable changes to this project are documented here. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project adheres to +[Semantic Versioning](https://semver.org/spec/v2.0.0.html). Protrus is pre-1.0: the public API +may change between minor versions. + +## [Unreleased] + +First public version (0.1.0, not yet tagged): a Rust port of the Protean dynamic module +platform that hosts signed WebAssembly components. + +### Added + +- **Module lifecycle** — install, update (hot swap), rollback, uninstall and approval over + `/platform` REST and MCP, with Protean's tool names, request/response shapes and RFC 9457 + error problems; durable revisions and startup reconcile. +- **Module stores** — filesystem, or SQL over `module_store_url` (SQLite, PostgreSQL, MySQL). +- **Promotion gates** — Ed25519 signature (`gate.signature.required`, default on; + `gate.signature.keys`), bundled unit tests (`gate.tests-enabled`, opt-in), capability policy + (`gate.review-enabled`), and candidate verification before routing. +- **Topologies** — in-process (async wasmtime), worker processes, and OCI container pairs + (read-only root filesystem, dropped capabilities, `no-new-privileges`, PID/memory limits, + `--internal` network, verified gateway image). +- **Per-module isolation** — manifest `isolation_mode` and `isolation.mode`; worker hosts mix + in-process and worker modules, OCI hosts in-process and container modules. +- **Worker packing** — pooled worker processes (`worker.modules-per-worker`, default 128; + `worker.min-warm`), hot-swap placement, auto-restart (`worker.auto-restart`), graceful + shutdown (`worker.shutdown-grace-ms`). +- **Sharing code** — shared libs (`/platform/shared-libs`) and LIBRARY modules (`exports`, + `uses`, DAG and ambiguity checks, propagation to dependents in every topology). +- **Host services** — `HostBridgeServices` and manifest `bridged_services`, reached in-process + and over the worker RPC bridge (`worker.rpc-bridge`). +- **Data access** — request-bound database capability; scoped PostgreSQL/MySQL provisioning and + scope administration for worker and container modules. +- **Runtime configuration** — Protean's configuration keys and tiers at `/platform/config` and + over MCP, with each JVM-only key listed and refused with its reason. +- **Observability and debugging** — request traces and metrics, console streams, guest traps + with frames, and interactive debug sessions in every topology. +- **Scenario runbooks** — Protean's `java_mcp` runbooks replayed against the production binary + (`examples/scenarios/`). + +### Security + +- Dependencies updated to clear RustSec advisories, including eight in wasmtime 50.0.1 that let + a module crash the host or grow its memory; the SQLite and `rsa` advisories were removed by + moving to sqlx 0.9 (MySQL now requires TLS or `mysql_native_password`), and the unmaintained + `serde_yaml` was replaced with `serde_norway`. +- A signature that is present is always verified, even with `gate.signature.required` off; + worker and OCI launches re-apply the gate switches at every launch. + +### Fixed + +Defects found and fixed before the first release: + +- An approved module re-ran the promotion gates instead of promoting the parked descriptor. +- An OCI pair crash restarted every module instead of only the crashed one. +- The OCI host left worker and gateway containers running after a graceful shutdown. +- A module whose worker process had already died could not be uninstalled. +- The OCI control plane dropped `runtimeId` and LIBRARY `exports` from module status. +- Docker-backed tests left fixture images, networks and containers behind. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..bf87e5e --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,72 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +- Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery, and sexual attention or advances of + any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, + without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +htjulia1@gmail.com. All complaints will be reviewed and investigated promptly +and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +https://www.contributor-covenant.org/version/2/1/code_of_conduct.html. + +[homepage]: https://www.contributor-covenant.org diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c8a4a78 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,100 @@ +# Contributing to Protrus + +Protrus is a Rust port of [Protean](https://github.com/htcom-code/protean), a dynamic module +platform. It hosts signed WebAssembly components and keeps Protean's control-plane contracts: +the `/platform` REST routes, the MCP tools, the runtime configuration keys and the error +shapes. Contributions are welcome — please read this first. + +## Getting started + +Requirements: + +- Rust **1.97** or newer (`rust-version` in `Cargo.toml`) with the `wasm32-unknown-unknown` + target: `rustup target add wasm32-unknown-unknown` +- [`wasm-tools`](https://github.com/bytecodealliance/wasm-tools) on `PATH` — the tests build + their guest-component fixtures with it (`cargo install wasm-tools --locked`) +- Docker, for the PostgreSQL / MySQL tests and the OCI tests + +The command CI runs is the command to run locally: + +```bash +cargo test --workspace +``` + +If you touch the OCI path (containers, gateway, pair watch), also run the `#[ignore]`d Docker +tests. They build the Linux worker image the first time, which takes a few minutes: + +```bash +cargo test -p protrus-host --test mcp_scenarios -- --ignored +cargo test -p protrus-host --test async_host_composition -- --ignored +``` + +## Code map + +| Crate | Role | +| --- | --- | +| `protrus-core` | Module records, revisions, generations, the `RuntimeBackend` trait, isolation modes | +| `protrus-artifact` | The signed manifest (`ManifestV1`) and artifact envelope | +| `protrus-gate` | `DeploymentService`: the gate pipeline, lifecycle, rollback, reconcile, LIBRARY binding | +| `protrus-config` | The runtime configuration registry (Protean's keys, tiers and outcomes) | +| `protrus-router` | Exact-route registry from `(method, path)` to a module revision | +| `protrus-runtime-wasm` | The component host (wasmtime), shared-lib linking, debug sessions, unit tests | +| `protrus-runtime-worker` | Worker process protocol, supervisor, packing pool, HTTP proxy | +| `protrus-runtime-oci` | OCI worker + gateway pairs over the Docker CLI | +| `protrus-store-fs` / `-sql` / `-sqlx` | Module stores (filesystem, SQL) and database adapters | +| `protrus-web` | `/platform` REST, MCP, traces, debug surface | +| `protrus-host` | The `protrus-host` and `protrus-worker` binaries and the host compositions | +| `protrus-observe` | Traces, guest traps, metrics | +| `protrus-testkit` | Shared test fixtures and the backend matrix | + +The design documents in [`docs/design/`](docs/design/) record every decision, including each +deliberate difference from Protean. They are written in Korean. The user guide is in +[`docs/guide/`](docs/guide/). + +## Invariants — do not break these + +1. **Protean parity.** A REST / MCP / config / error surface is added or changed only after + reading the corresponding Java Protean source and tests. A deliberate difference is recorded + as `non-parity` in `docs/design/` *before* it is implemented: the reason, the user impact, a + migration note and how it is verified. `/platform` is the fixed control-plane namespace. +2. **No gate bypass.** Nothing deploys, approves, rolls back, reconciles or launches an artifact + without the signature and promotion gates. Worker and OCI launches re-verify. +3. **Revision fencing.** A failed candidate never replaces the serving revision; routes move only + after a candidate is active. +4. **Capability boundary.** A module gets only what its signed manifest asks for and the host + allows. No secret reaches argv, environment variables, container labels or logs. +5. **No leftovers.** Workers, containers, sockets and secret files are removed when their module + stops or the host shuts down. Tests clean up their Docker fixtures and temporary directories. + +## How changes are checked + +- Unit tests next to the code, host integration tests in `crates/protrus-host/tests/`. +- **Scenario manifests** in [`examples/scenarios/`](examples/scenarios/) replay Protean's + `java_mcp` runbooks against the production `protrus-host` binary over HTTP and MCP + (`crates/protrus-host/tests/mcp_scenarios.rs`). A runbook step Protrus cannot run is listed + under `not_applicable` with the reason. +- `cargo audit` runs in CI; do not add a dependency with an open RustSec advisory. +- `cargo clippy --workspace --all-targets` should not gain new warnings. The tree is not + `rustfmt`-clean; do not reformat code you are not changing. + +## Build artifacts + +`target/` grows quickly with a large workspace. Clean it now and then +(`cargo clean`, or [`cargo-sweep`](https://github.com/holmgr/cargo-sweep)), and keep the +guest-fixture directories (`poc/*/target`, `examples/artifacts/*/target`) out of commits. + +## Commits, branches and pull requests + +- **Commits** follow [Conventional Commits](https://www.conventionalcommits.org/): + `type(scope): subject` in the imperative, with a body that says why. +- **Branches** are `/`, lowercase with hyphens + (e.g. `fix/worker-socket-cleanup`). +- **Open an issue first** for anything beyond a typo, then a PR that links it. PRs are + squash-merged, so the PR title becomes the commit subject on `main`. Fill in the PR + template's invariant checklist. +- Code comments, commit messages, PRs, test names and user-facing strings are in English. + +## License + +By contributing you agree that your contributions are licensed under the +[Mozilla Public License 2.0](LICENSE). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d0a1fa1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/README.md b/README.md new file mode 100644 index 0000000..e782ebd --- /dev/null +++ b/README.md @@ -0,0 +1,130 @@ +# Protrus + +[![CI](https://github.com/htcom-code/protrus/actions/workflows/ci.yml/badge.svg)](https://github.com/htcom-code/protrus/actions/workflows/ci.yml) +[![License: MPL 2.0](https://img.shields.io/badge/License-MPL_2.0-brightgreen.svg)](LICENSE) + +**Protrus hosts signed WebAssembly component modules and swaps them at runtime — in-process, in +worker processes, or in hardened OCI containers — behind a `/platform` REST and MCP control +plane.** It is a Rust port of [Protean](https://github.com/htcom-code/protean), the Spring Boot +dynamic module platform, and keeps Protean's control-plane contracts: the REST routes, the MCP +tools, the runtime configuration keys and the error shapes. + +Where Protean compiles Java source on the server, Protrus deploys **pre-built, signed Wasm +components**: nothing is compiled or evaluated at runtime, and a module reaches only the host +capabilities its signed manifest asks for and the host allows. + +## Contents + +- [Features](#features) +- [Quick start](#quick-start) +- [How it works](#how-it-works) +- [Documentation](#documentation) +- [Relationship to Protean](#relationship-to-protean) +- [Contributing](#contributing) +- [License](#license) + +## Features + +- **Runtime lifecycle** — install, update (hot swap), rollback, uninstall and approval, with + durable revisions and reconcile on restart. A failed candidate never replaces the serving + revision. +- **Promotion gates** — Ed25519 signatures (required by default), bundled unit tests, + capability policy, and candidate verification before a route moves. +- **Isolation per module** — in-process (wasmtime), packed worker processes, or OCI container + pairs (read-only root filesystem, no capabilities, internal network, verified gateway), chosen + per module with `isolation_mode`. +- **Sharing code** — shared libs and LIBRARY modules linked into their dependents in every + topology, with propagation when a library changes. +- **Host services and data** — named host services (`bridge.call`), and request-bound, + scope-limited database access with PostgreSQL/MySQL provisioning. +- **Control plane** — `/platform` REST, MCP over Streamable HTTP and stdio, a runtime + configuration registry with live / future / restart tiers, traces, metrics, and interactive + debugging of Wasm guests. + +## Quick start + +Requirements: Rust 1.97 or newer. + +```bash +cargo build --release -p protrus-host # builds protrus-host and protrus-worker +``` + +Write a bootstrap file for the in-process (`async-wasm`) topology. Paths must be absolute: + +```json +{ + "execution_mode": "async-wasm", + "state_root": "/srv/protrus/state", + "artifact_root": "/srv/protrus/artifacts", + "trusted_signers_hex": {}, + "config": {"mcp.enabled": true} +} +``` + +Start the host on a listen address and talk to it: + +```console +$ ./target/release/protrus-host host.json 127.0.0.1:8080 +{"event":"protrus_host_listening","address":"127.0.0.1:8080"} + +$ curl -s http://127.0.0.1:8080/platform/modules +[] +$ curl -s http://127.0.0.1:8080/platform/runtimes +[{"runtimeId":"main","mode":"in-process","scope":null,"state":"LIVE","sinceEpochMs":1795509367120,"moduleIds":[]}] +$ curl -s -X POST http://127.0.0.1:8080/platform/mcp \ + -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' \ + -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' +{"jsonrpc":"2.0","id":1,"result":{"tools":[{"name":"protean.list_modules", ... +``` + +To deploy something you need a component and a signing key trusted by the host +(`trusted_signers_hex`). The [user guide](docs/guide/) walks through building a component, +signing it, deploying it and operating it. + +## How it works + +```text + /platform REST · MCP · traces · debug + │ + DeploymentService ── gates: signature → tests → policy → verification + │ module store (fs / SQLite / PostgreSQL / MySQL) + ┌─────────────────┼──────────────────────┐ + in-process worker container + (async wasmtime) (pooled processes, (OCI worker + gateway pair, + private sockets) internal network) +``` + +A host runs one **topology** (`execution_mode`: `async-wasm`, `worker` or `oci`). A worker host +also runs in-process modules, and an OCI host also runs in-process modules, chosen per module by +the signed manifest's `isolation_mode` or the `isolation.mode` default. Requests are routed by +exact `(method, path)` to the active revision; the control plane never shares a listener with +module code. + +## Documentation + +- [User guide](docs/guide/) — getting started, signing and deploying modules, configuration, + isolation and workers, sharing code, host services, debugging, databases. +- [Design documents](docs/design/) — the architecture and every decision, including each + deliberate difference from Protean (written in Korean). +- [Scenario runbooks](examples/scenarios/) — Protean's MCP runbooks replayed against the host + binary. +- [Roadmap](ROADMAP.md) · [Changelog](CHANGELOG.md) · [Security](SECURITY.md) + +## Relationship to Protean + +Protrus ports Protean feature by feature and keeps its external contracts, so Protean's console +and MCP clients work against it. Where the runtime differs — Wasm components instead of Java +classes, named host services instead of Spring beans, a signed manifest instead of a server-side +compile — the difference is recorded as `non-parity` in the design documents with its reason, +user impact and migration note. [ROADMAP.md](ROADMAP.md) lists what is deliberately not ported. + +## Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md) for the build, the invariants every change keeps, and +the commit and PR conventions. Please read the [Code of Conduct](CODE_OF_CONDUCT.md). + +## License + +Copyright (c) 2026 htjulia + +Licensed under the [Mozilla Public License 2.0](LICENSE). diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..a43d9a1 --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,64 @@ +# Protrus Roadmap + +Protrus is a library: it aims to carry every Java Protean capability, and the embedding +application decides what to expose. This page lists what is shipped, what is planned, and — as +importantly — what is **deliberately not done** and why, so a missing item is not mistaken for +an oversight. + +## Legend + +| Mark | Meaning | +| --- | --- | +| Shipped | In `main`, covered by tests or scenario runbooks | +| Planned | Accepted, not yet built | +| Candidate | Under consideration; support undecided | +| Not planned | Deliberately out of scope, with the reason | + +Deliberate differences from Protean that *are* shipped are recorded as `non-parity` in +[`docs/design/`](docs/design/) (Korean) with the reason, user impact and migration note. + +## Shipped + +- **Module lifecycle** — install, update (hot swap), rollback, uninstall, approval, reconcile on + restart, durable revisions, module stores on the filesystem or SQL (SQLite, PostgreSQL, MySQL). +- **Promotion gates** — Ed25519 signature (required by default), bundled unit tests (opt-in), + capability policy, candidate verification before routing. +- **Three topologies, per-module isolation** — in-process (async wasmtime), worker processes + (packed, `worker.modules-per-worker` 128 by default, warm pool, auto-restart), and OCI + container pairs with a hardened profile and a verified gateway. `isolation_mode` per module. +- **Sharing code** — shared libs and LIBRARY modules (`exports` / `uses`), propagated to + dependents in every topology. +- **Host services** — named `service@version` bridge calls from modules, in-process and over the + worker RPC bridge. +- **Data access** — request-bound database capability, scoped PostgreSQL/MySQL provisioning for + worker and container modules. +- **Control plane** — `/platform` REST, MCP (Streamable HTTP and stdio), runtime configuration + registry with Protean's keys and tiers, traces and metrics, console streams. +- **Debugging** — guest traps with frames, interactive sessions (breakpoints, stepping, + variables) in every topology. + +## Planned + +- **Container packing.** Process workers pack modules (Protean `worker.modules-per-worker`); + OCI pairs still carry one module each, because each pair has its own gateway. Packing several + modules behind one gateway is the next isolation step. +- **Release artifacts.** Tagged releases with prebuilt `protrus-host` / `protrus-worker` + binaries and the worker container image. + +## Candidate + +- **Signing CLI.** Artifacts are signed today with the `protrus-artifact` crate API + (see [`docs/guide/`](docs/guide/)); a small command-line signer would make the first deploy + easier. +- **crates.io publication** of the library crates. + +## Not planned + +| Item | Why | +| --- | --- | +| Compiling source on the server (Protean compiles Java at runtime) | Modules are pre-built, signed Wasm components; the host never compiles or evaluates code | +| Returning a module's source (`get_module_source`) | A component cannot be turned back into its source | +| JVM-only configuration — `worker.jvm-args`, `worker.runtime`, `worker.sidecar.*`, `worker.container.jar`, `module.shared-lib-dir`, `module.executor.pool-size` | There is no JVM, classpath or managed executor; each key is listed with its reason and answers `REJECTED_INVALID` / `REQUIRES_RESTART` like Protean | +| `worker.datasource.url` | A worker reaches only its signed scope's database, through provisioned credentials, never a configured URL | +| Java bridge wire format — `/__bridge/invoke`, reflection JSON, `bridge.*` auth keys | Host services are named calls over owner-only private sockets; socket permissions replace the HMAC/token | +| JDI evaluate, redefine and attach | No WebAssembly equivalent; breakpoints, stepping, frames and variables are supported | diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..f2b55df --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,76 @@ +# Security Policy + +## Reporting a vulnerability + +Please report security issues **privately** — do not open a public issue for an unpatched +vulnerability. + +- Use GitHub's **"Report a vulnerability"** (Security → Advisories) on this repository: + , or +- email the maintainer at **htjulia1@gmail.com**. + +Include a description, the affected version or commit, the host topology (`execution_mode`), and +a minimal reproducer (a failing test, or a bootstrap JSON + signed manifest + REST/MCP calls). +We will acknowledge the report and work with you on a fix and coordinated disclosure. + +## Supported versions + +Protrus is pre-1.0. Fixes land on the active line, and the public API may change between minor +versions. + +| Version | Supported | +| --- | --- | +| 0.1.x | Yes | + +## Threat model + +Protrus hosts **pre-built, signed WebAssembly components**. It never compiles or evaluates +source. What a module can reach is decided by the host, not by the module: + +- **Wasm sandbox.** A component sees only the WIT imports the host links: `config`, `observe`, + `control`, `bridge`, `db` (and the stream world for ABI 2). There is no filesystem, socket, + clock or process access, and every request runs under a fuel budget and a deadline. +- **Signed artifacts.** An artifact's manifest and files are covered by an Ed25519 signature + that is verified against the host's trust store before it deploys (`gate.signature.required` + defaults to **true**). A signature that is present is always verified, even when signatures + are not required. Worker and OCI launches verify again at every launch. +- **Promotion gates.** Signature → unit tests (opt-in) → capability policy → candidate + verification. A candidate that fails never replaces the serving revision. +- **Capability grants.** A module gets a capability only when its signed manifest asks for it + and the host's policy allows it. Database access is scoped (`db` + a signed `scope`); host + services (`bridge`) are reachable only when the manifest declares them and the host registered + them. +- **Process and container isolation.** `worker` runs modules in separate processes; `container` + runs them in OCI containers with a read-only root filesystem, all Linux capabilities dropped, + `no-new-privileges`, PID and memory limits, a non-root user, and an `--internal` network + reached only through a host-verified gateway. Secrets reach workers as owner-only files or + mounts, never through argv, environment variables or container labels. +- **The control plane is a deployment entry point.** `/platform` and MCP can install code. + MCP is **off by default** (`mcp.enabled`), debug tools too (`mcp.debug.enabled`). Protrus + does not authenticate callers itself: the embedding application supplies the identity and the + `ControlAuthorizer`. Never expose `/platform` or MCP unauthenticated on an untrusted network. + +## Scope + +**In scope** — Protrus bugs with security impact: + +- a gate that can be **bypassed**: an unsigned or untrusted artifact that deploys or launches, + a capability granted that the manifest or policy did not allow, or a failing candidate that + ends up serving; +- a component escaping the Wasm sandbox, or reaching a host import it was not granted; +- a module reaching another module's database scope, host services it did not declare, or the + host's secrets; +- worker or container isolation that fails to contain (writable root filesystem, kept + capabilities, a route around the internal network or the gateway); +- control-plane endpoints reachable or authorizable when they should not be (MCP or debug tools + active while disabled, authorization skipped); +- a module exhausting host memory, threads or processes beyond its configured limits. + +**Out of scope:** + +- a module doing what its granted capabilities allow (a granted `db` scope or bridged service + is the host's decision); +- an embedding application that exposes `/platform` or MCP without authentication; +- denial of service by an authorized operator (deploying many modules, raising limits); +- vulnerabilities in third-party dependencies with no Protrus-specific exploit path — report + those upstream (CI runs `cargo audit` on every change). diff --git a/crates/protrus-web/src/lib.rs b/crates/protrus-web/src/lib.rs index 62e44ac..40c9deb 100644 --- a/crates/protrus-web/src/lib.rs +++ b/crates/protrus-web/src/lib.rs @@ -3405,7 +3405,8 @@ pub struct ModuleStatus { pub bridged_interfaces: Vec, /// Protean's shared-lib parent-tier generation; here the shared-lib store generation. pub bound_generation: Option, - /// Protean `ModuleKind`. LIBRARY modules are not ported (design 30 P*), so always `NORMAL`. + /// Protean `ModuleKind`: `LIBRARY` for a module that publishes a library generation, else + /// `NORMAL` (design 01 §6). pub kind: &'static str, pub exports: Vec, pub uses: Vec, diff --git a/docs/design/04-deployment-and-runtime-protocol.md b/docs/design/04-deployment-and-runtime-protocol.md index 3d7d10e..83e7cfa 100644 --- a/docs/design/04-deployment-and-runtime-protocol.md +++ b/docs/design/04-deployment-and-runtime-protocol.md @@ -106,7 +106,7 @@ Protean `VerificationGate`를 이식한다. module이 plan을 선언하면 후 B` 그대로다. Linux는 `/proc/self/statm`의 현재 RSS, 그 밖의 Unix는 `getrusage`의 최대 RSS다. Java도 GC 잡음 때문에 정밀하지 않다고 하므로 넉넉한 값을 권장한다. -**non-parity** (brain `knowledge/protrus/protean-differences` 레지스터에도 기록) +**non-parity** | Java | Rust | 사용자 영향 | 검증 | | --- | --- | --- | --- | diff --git a/docs/guide/01-getting-started.md b/docs/guide/01-getting-started.md new file mode 100644 index 0000000..64f5563 --- /dev/null +++ b/docs/guide/01-getting-started.md @@ -0,0 +1,245 @@ +# 1. Getting started + +This page builds the host, explains the three host topologies, and starts a host you can talk to. +Every command and output below was run against this repository; long outputs are trimmed. + +## Prerequisites + +| For | You need | +| --- | --- | +| Building the host | Rust 1.97 or newer (the workspace `rust-version`) | +| Building modules ([page 2](02-building-and-signing-modules.md)) | the `wasm32-unknown-unknown` target (`rustup target add wasm32-unknown-unknown`) and [`wasm-tools`](https://github.com/bytecodealliance/wasm-tools) | +| Signing keys | OpenSSL 3 or newer (Ed25519 support), or any Ed25519 tool | +| The `oci` topology ([page 5](05-isolation-and-workers.md#oci-host-requirements)) | Docker | +| The examples on these pages | `curl` and `jq` | + +## Build + +From the repository root: + +```sh +cargo build --release -p protrus-host +ls target/release/protrus-host target/release/protrus-worker +``` + +```text +target/release/protrus-host +target/release/protrus-worker +``` + +- `protrus-host` is the server: the `/platform` control plane, MCP, and module traffic. +- `protrus-worker` is the out-of-process worker. The `worker` topology starts it as a child + process; the `oci` topology runs it inside a container image. You never start it by hand. + +The rest of this guide assumes `PROTRUS_REPO` points at your checkout: + +```sh +export PROTRUS_REPO=/path/to/protrus +``` + +## Choose a topology + +The host reads one JSON bootstrap file. Its `execution_mode` field selects the topology. When the +field is absent, the host starts in `oci` mode, which needs Docker and several extra fields; set +the field explicitly. + +| `execution_mode` | Modules run | Isolation modes served | Default for a module that names none | Extra requirements | +| --- | --- | --- | --- | --- | +| `async-wasm` | in the host process | `in-process` | `in-process` | none | +| `worker` | in pooled `protrus-worker` child processes, or in the host | `in-process`, `worker` | `worker` | `worker_program`, `control_socket_root` | +| `oci` (default) | in Docker worker+gateway container pairs, or in the host | `in-process`, `container` | `container` | Docker, pinned images, an internal network, a control secret, a signed gateway profile | + +Start with `async-wasm`: it has no moving parts outside the host process. See +[page 5](05-isolation-and-workers.md) for how modules are placed on the other two. + +## The bootstrap file + +The bootstrap file is private host configuration, not a module manifest and not an API. Fields +common to all topologies: + +| Field | Required | Meaning | +| --- | --- | --- | +| `execution_mode` | no (default `oci`) | `async-wasm`, `worker` or `oci` | +| `state_root` | yes | Absolute path. Module records (file store), the signed artifact store (`worker`/`oci`), shared libs, scope records | +| `artifact_root` | yes | Absolute path. `async-wasm`: the signed artifact store. `worker`/`oci`: where verified artifacts are materialized for workers | +| `trusted_signers_hex` | yes (may be `{}`) | Signer key id to 32-byte Ed25519 public key, hex. See [page 2](02-building-and-signing-modules.md#trust-the-key-on-the-host) | +| `identity` | no, but see below | `{"principal": "...", "bearer_token_file": "/abs/path"}`: the bearer token that authorizes changes | +| `allowed_capabilities` | no (default empty) | Capabilities a signed manifest may declare, for example `["db"]` | +| `module_store_url` | no | SQL module store URL; see [page 9](09-databases.md#module-store-backends) | +| `config` | no | Initial values of runtime config keys, for example `{"mcp.enabled": true}`; see [page 4](04-configuration.md) | + +Mode-specific fields are listed with each topology: `async-wasm` adds `sqlite_scopes` and +`module_db_scopes` ([page 9](09-databases.md)); `worker` adds `control_socket_root`, +`worker_program`, `worker_args` and `database_provisioning`; `oci` adds the container fields on +[page 5](05-isolation-and-workers.md#oci-host-requirements). + +Things that commonly trip up a first start: + +- **All paths must be absolute.** A relative `state_root` fails with + `module-store.dir must be an absolute path`. +- **Without `identity`, every change is refused.** Reads (`GET /platform/*`, read-only MCP tools) + are open, but deploys, config changes and every other write answer `403 FORBIDDEN` + (`authenticated host identity is required`). Clients send + `Authorization: Bearer `, where the token is the file's content without its trailing + newline. +- **The token file must be private.** It must be a regular file that group and others cannot + read (mode `0600`), or startup fails with + `host bearer token file must not be accessible by group or others`. +- **MCP is off by default.** Set `"mcp.enabled": true` in `config`, or `/platform/mcp` answers 404. +- **Unknown top-level fields are ignored**, so a misspelled field name (for example + `trusted_signer_hex`) silently does nothing. Unknown keys inside `config` do stop startup + (`bootstrap config: unknown config key: ...`). +- Some fields moved into `config`. The old fields `gate_approval_required`, `mcp_enabled`, + `mcp_stdio`, `container_auto_restart` and `database_provisioning.allowed_scopes` stop startup + with a message naming the key that replaced them. + +## Start an async-wasm host + +```sh +mkdir -p /tmp/protrus-demo && cd /tmp/protrus-demo +umask 077 +openssl rand -hex 32 > operator-token +cat > async-wasm.json <<'EOF' +{ + "execution_mode": "async-wasm", + "state_root": "/tmp/protrus-demo/state", + "artifact_root": "/tmp/protrus-demo/artifacts", + "trusted_signers_hex": {}, + "identity": { + "principal": "operator", + "bearer_token_file": "/tmp/protrus-demo/operator-token" + }, + "config": { + "mcp.enabled": true + } +} +EOF +"$PROTRUS_REPO/target/release/protrus-host" async-wasm.json 127.0.0.1:8088 +``` + +The command line is exactly `protrus-host `. The directories are +created on first use. Once the listener is bound, the host writes one JSON event to stderr +(stdout is reserved for MCP stdio): + +```text +{"event":"protrus_host_listening","address":"127.0.0.1:8088"} +``` + +With port `0` the operating system picks a free port; read it from this event. + +`trusted_signers_hex` is empty for now, so the host trusts no signer yet and would refuse every +signed deploy. [Page 2](02-building-and-signing-modules.md) creates a key and adds it. + +## Verify it + +In a second terminal: + +```sh +curl -s http://127.0.0.1:8088/platform/modules +curl -s http://127.0.0.1:8088/platform/runtimes +curl -s http://127.0.0.1:8088/platform/config/isolation.mode +``` + +```text +[] +[{"runtimeId":"main","mode":"in-process","scope":null,"state":"LIVE","sinceEpochMs":1795509858576,"moduleIds":[]}] +{"key":"isolation.mode","value":"in-process","tier":"FUTURE","liveApplicable":true} +``` + +A change without the token is refused; with it, it applies: + +```sh +curl -s -X PATCH http://127.0.0.1:8088/platform/config \ + -H 'content-type: application/json' -d '{"trace.capacity": 500}' +curl -s -X PATCH http://127.0.0.1:8088/platform/config \ + -H 'content-type: application/json' \ + -H "Authorization: Bearer $(cat /tmp/protrus-demo/operator-token)" \ + -d '{"trace.capacity": 500}' +``` + +```text +{"type":"urn:protean:error:forbidden","title":"Forbidden","status":403,"code":"FORBIDDEN","detail":"authenticated host identity is required","traceId":"e5991ca0-8c88-4d1b-8e4a-34441257e9b5"} +{"applied":true,"outcomes":[{"key":"trace.capacity","tier":"LIVE","outcome":"APPLIED_LIVE","reason":null}]} +``` + +Every response carries an `x-request-id` header, and every error body is an RFC 9457 problem +(`application/problem+json`) whose `traceId` is that id. Send your own `X-Request-Id` to correlate +requests. + +Stop the host with Ctrl-C or `SIGTERM`. Deployed modules are stored under `state_root`; the next +start redeploys them before it accepts requests. + +## Start a worker host + +The worker topology needs the absolute path of `protrus-worker` and a directory for the Unix +sockets between host and workers. The JSON below is written with an unquoted heredoc so the +shell fills in `$PROTRUS_REPO`: + +```sh +cd /tmp/protrus-demo +cat > worker.json </-.streams.sock` +inside it. + +## Start an OCI host + +The `oci` topology needs images, a Docker network, a control secret and a signed gateway profile +prepared before startup. [Page 5](05-isolation-and-workers.md#oci-host-requirements) lists them; +[`docs/examples/protrus-host-bootstrap.json`](../examples/protrus-host-bootstrap.json) is a +complete bootstrap with placeholder digests and keys, and +[`docs/operations/protrus-host-runbook.md`](../operations/protrus-host-runbook.md) is the +operations runbook for it. + +## Startup errors + +| Message | Cause | +| --- | --- | +| `usage: protrus-host ` | Missing argument | +| `unsupported host execution_mode: ...` | `execution_mode` is not `async-wasm`, `worker` or `oci` | +| `module-store.dir must be an absolute path`, `... paths must be absolute` | A relative path in the bootstrap | +| `host bearer token file must not be accessible by group or others` | Token file mode is not `0600` | +| `bootstrap config: unknown config key: ...` | A typo in a `config` key | +| `bootstrap config: worker.jvm-args: JVM-only in Protean; ...` | A Protean key that has no Protrus equivalent | +| `bootstrap field ... was replaced by the config key ...` | A removed bootstrap field; move it into `config` | +| `no strategy for default isolation.mode='worker' (available: [in-process])` | `isolation.mode` names a mode this topology does not serve | +| `worker executable is missing or not a regular file` | `worker_program` is wrong | +| `trusted signer ... must be a 32-byte hex key` | A malformed `trusted_signers_hex` value | + +Next: [build and sign a module](02-building-and-signing-modules.md). diff --git a/docs/guide/02-building-and-signing-modules.md b/docs/guide/02-building-and-signing-modules.md new file mode 100644 index 0000000..80e28b1 --- /dev/null +++ b/docs/guide/02-building-and-signing-modules.md @@ -0,0 +1,412 @@ +# 2. Building and signing a module + +A Protrus module is a WebAssembly component, wrapped with a manifest into an artifact that is +signed with Ed25519. The host runs only artifacts whose signature verifies against a key it +trusts. This page builds a component, signs it, and teaches the host to trust the key. + +## The component world + +The world is defined in [`poc/module-component/wit/module.wit`](../../poc/module-component/wit/module.wit) +(package `protrus:module@0.1.0`): + +```wit +world module { + import config; + import observe; + import control; + import bridge; + import db; + use types.{request, response, module-error}; + export handle: func(request: request) -> result; +} + +world tested-module { + include module; + export tests; +} +``` + +| Item | What the module gets | +| --- | --- | +| `handle(request)` | Called once per HTTP request routed to the module. `request` has `method`, `path`, `headers` and `body`. There is **no query string**: send inputs in the body or headers. `path` is the full request path, so one component can serve several routes. | +| `module-error` | `bad-request`, `forbidden`, `internal`, `timeout`; returned instead of a response | +| `config.get(key)` | Always `none` in the current host: no per-module configuration source is wired yet | +| `observe.log` / `observe.event` | Accepted; output is not exported while serving requests. Logs written during unit tests are captured when `mcp.capture-test-output` is on | +| `control.cancelled()` | `true` once the host has cancelled the request (deadline, shutdown) | +| `bridge.call(service, version, input)` | A host service the embedding application registered; see [page 7](07-host-services.md) | +| `db.begin(scope)` | A request-bound transaction; see [page 9](09-databases.md) | +| `tests.run(name)` | Only in `tested-module`: the unit tests the promotion gate runs ([page 3](03-deploying-and-operating.md#promotion-gates)) | + +Imports a component does not use do not appear in the built component. Request and response +bodies are limited to 1 MiB each. Component ABI version 1 is this world; version 2 adds HTTP +streaming imports (WIT in `poc/module-component/wit-v02`) and requires the signed `stream` +capability. + +## Build a component + +A minimal module crate, outside the repository workspace: + +```text +hello-module/ + Cargo.toml + wit/module.wit # copied from $PROTRUS_REPO/poc/module-component/wit/module.wit + src/lib.rs +``` + +`Cargo.toml`: + +```toml +[package] +name = "hello-module" +version = "0.1.0" +edition = "2024" +publish = false + +[lib] +crate-type = ["cdylib"] + +[dependencies] +wit-bindgen = "0.41" + +[workspace] +``` + +`src/lib.rs`: + +```rust +wit_bindgen::generate!({ path: "wit", world: "module" }); + +use protrus::module::observe; + +struct Hello; + +impl Guest for Hello { + fn handle(request: Request) -> Result { + observe::log(observe::Level::Info, &format!("{} {}", request.method, request.path)); + let name = String::from_utf8(request.body) + .map_err(|_| ModuleError::BadRequest("body is not UTF-8".into()))?; + Ok(Response { + status: 200, + headers: vec![("content-type".into(), "text/plain".into())], + body: format!("hello, {}", name.trim()).into_bytes(), + }) + } +} + +export!(Hello); +``` + +Build the core module, then wrap it as a component: + +```sh +cd /tmp/protrus-demo +mkdir -p hello-module/src hello-module/wit +cp "$PROTRUS_REPO/poc/module-component/wit/module.wit" hello-module/wit/ +# write hello-module/Cargo.toml and hello-module/src/lib.rs as above +cd hello-module +cargo build --release --target wasm32-unknown-unknown +wasm-tools component new target/wasm32-unknown-unknown/release/hello_module.wasm \ + -o hello.component.wasm +wasm-tools component wit hello.component.wasm | head -8 +``` + +```text +package root:component; + +world root { + import protrus:module/types@0.1.0; + import protrus:module/observe@0.1.0; + use protrus:module/types@0.1.0.{request, response, module-error}; + + export handle: func(request: request) -> result; +``` + +Build for `wasm32-unknown-unknown`, not a WASI target: the host links only the +`protrus:module` imports (plus shared libs and libraries), so a component that imports WASI +interfaces fails with `component linker validation failed`. A component must also export +`handle`. + +More examples live in +[`examples/artifacts/scenario-modules`](../../examples/artifacts/scenario-modules): one crate +with a Cargo feature per module (`wk-calc`, `ip-echo`, a module with bundled tests +`wk-gatefail`, the shared-lib components `acme-pricing*`, and the consumer `price-only`). +Its [`build.sh`](../../examples/artifacts/scenario-modules/build.sh) runs the same two steps per +feature and writes `target/.wasm`. + +## The signed artifact + +`protrus-artifact` ([`crates/protrus-artifact/src/lib.rs`](../../crates/protrus-artifact/src/lib.rs)) +defines the artifact: + +- `ArtifactBundle { manifest: ManifestV1, files }`. `files` maps relative paths to bytes; the + component must be at `component.wasm`. Other paths (for example `resources/...`) are allowed. +- `SignedArtifact { bundle, signer_key_id, signature }`. The signature is Ed25519 over the + bundle's canonical bytes (the manifest as key-sorted JSON, then each file framed by length). + The artifact digest, `sha256:`, is the SHA-256 of the same bytes. + +`ManifestV1` fields. Everything in the manifest is covered by the signature; fields marked +"omitted when empty" are left out of the canonical bytes when unset, so older digests stay valid. + +| Field | Type | Meaning | +| --- | --- | --- | +| `api_version`, `kind` | string | Free-form labels for a module (`"protrus/v1"`, `"module"` in the examples). A gateway profile uses `kind: "gateway-profile"` ([page 5](05-isolation-and-workers.md#oci-host-requirements)) | +| `id` | string | Module id: 1 to 63 of `a-z`, `0-9`, `-`, not starting or ending with `-` | +| `version` | string | Your display version. The host's own `version` in module status is the revision number, not this | +| `component_abi_version` | integer | `1` (default, omitted) or `2` (streaming, needs the `stream` capability) | +| `scope` | string, optional | Database scope; see [page 9](09-databases.md). Must equal the deploy record's `scope` | +| `routes` | list of `{method, path}` | The routes the author intends; see the note on routes below | +| `capabilities` | list of strings | Capabilities the module asks for, for example `db`, `stream`. Each must be in the host's `allowed_capabilities` while `gate.review-enabled` is on; no duplicates | +| `dependencies` | list of `{name}` | Shared libs to link, by store name, in link order ([page 6](06-sharing-code.md#shared-libs)) | +| `verification` | object, optional | Probes run against the candidate before it is routed ([page 3](03-deploying-and-operating.md#promotion-gates)) | +| `tests` | list of strings | Unit test names run through the `tests` export ([page 3](03-deploying-and-operating.md#promotion-gates)) | +| `module_kind` | `"NORMAL"` or `"LIBRARY"`, optional | `LIBRARY` lends interfaces to other modules ([page 6](06-sharing-code.md#library-modules)) | +| `exports` | list of strings | WIT interfaces a LIBRARY lends, for example `acme:pricing/discount` | +| `uses` | list of strings | LIBRARY module ids this module links | +| `isolation_mode` | `"in-process"`, `"worker"` or `"container"`, optional | Where the module runs; absent follows the host's `isolation.mode` ([page 5](05-isolation-and-workers.md)) | +| `bridged_services` | list of `"service@version"` | Host services the module calls ([page 7](07-host-services.md)) | + +## Create a signing key + +There is no signing CLI. Any Ed25519 key works; with OpenSSL: + +```sh +cd /tmp/protrus-demo +openssl genpkey -algorithm ed25519 -out release-1.pem +openssl pkey -in release-1.pem -outform DER | tail -c 32 > release-1.seed +openssl pkey -in release-1.pem -pubout -outform DER | tail -c 32 | xxd -p -c 64 +openssl pkey -in release-1.pem -pubout -outform DER | base64 +``` + +```text +32c23ac2deec6481edc2efcea35ce3f2fdb99632f4fb3568325e646b1a0d2aa8 +MCowBQYDK2VwAyEAMsI6wt7sZIHtwu/Oo1zj8v25ljL0+zVoMl5kaxoNKqg= +``` + +- `release-1.seed` is the raw 32-byte private key. Keep it, and the PEM, secret. +- The hex line is the public key in the form `trusted_signers_hex` takes. +- The Base64 line is the public key as X.509 `SubjectPublicKeyInfo`, the form the + `gate.signature.keys` config key takes. + +## Sign with a small Rust program + +The program below builds the bundle, signs it with `SignedArtifact::sign`, and prints the deploy +envelope that `POST /platform/modules` and the MCP tool `protean.deploy_module` accept. It was +compiled and used as shown; the only line you change is the repository path in `Cargo.toml`. + +`sign-module/Cargo.toml`: + +```toml +[package] +name = "sign-module" +version = "0.1.0" +edition = "2024" +publish = false + +[dependencies] +protrus-artifact = { path = "/path/to/protrus/crates/protrus-artifact" } +protrus-core = { path = "/path/to/protrus/crates/protrus-core" } +ed25519-dalek = "3.0.0" +serde_json = "1" + +[workspace] +``` + +`sign-module/src/main.rs`: + +```rust +//! Signs a component as a Protrus module and prints the deploy envelope that +//! `POST /platform/modules` and the MCP tool `protean.deploy_module` accept. +//! +//! usage: sign-module ... +use ed25519_dalek::SigningKey; +use protrus_artifact::{ArtifactBundle, ManifestV1, Route, SignedArtifact}; +use protrus_core::{DesiredState, ModuleId, ModuleRecord, ObservedState, Revision}; +use serde_json::json; +use std::{collections::BTreeMap, env, fs}; + +fn main() -> Result<(), Box> { + let args: Vec = env::args().skip(1).collect(); + let [seed_file, key_id, component, module_id, version, revision, routes @ ..] = args.as_slice() + else { + return Err("usage: sign-module ...".into()); + }; + + // A 32-byte Ed25519 seed. Keep it secret; the host only needs the public key. + let seed: [u8; 32] = fs::read(seed_file)? + .try_into() + .map_err(|_| "the seed file must hold exactly 32 bytes")?; + let key = SigningKey::from_bytes(&seed); + let public_hex: String = key.verifying_key().to_bytes().iter().map(|b| format!("{b:02x}")).collect(); + eprintln!("trusted_signers_hex entry: \"{key_id}\": \"{public_hex}\""); + + let module_id = ModuleId::parse(module_id.as_str())?; + let routes: Vec = routes + .iter() + .map(|route| { + let (method, path) = route.split_once(' ').ok_or("a route is \"METHOD /path\"")?; + Ok(Route { method: method.into(), path: path.into() }) + }) + .collect::>()?; + + let manifest = ManifestV1 { + api_version: "protrus/v1".into(), + kind: "module".into(), + id: module_id.clone(), + version: version.clone(), + component_abi_version: 1, + scope: None, + routes: routes.clone(), + capabilities: vec![], + dependencies: vec![], + verification: None, + tests: vec![], + module_kind: None, + exports: vec![], + uses: vec![], + isolation_mode: None, + bridged_services: vec![], + }; + let bundle = ArtifactBundle { + manifest, + files: BTreeMap::from([("component.wasm".to_owned(), fs::read(component)?)]), + }; + let signed = SignedArtifact::sign(bundle, key_id.as_str(), &key)?; + + // The record names the exact artifact; the server checks id, digest and scope against it. + let record = ModuleRecord { + module_id: module_id.clone(), + revision: Revision(revision.parse()?), + scope: None, + artifact_digest: signed.bundle.digest()?.0, + dependency_generations: vec![], + provided_generation: None, + observed_binding: None, + sticky_reason: None, + routes: vec![], + pending_cleanup: vec![], + desired_state: DesiredState::Active, + observed_state: ObservedState::Absent, + }; + let envelope = json!({ + "idempotency_key": format!("{module_id}-{revision}"), + "expected_revision": null, + "record": record, + "routes": routes, + "signed_artifact": signed, + }); + println!("{}", serde_json::to_string(&envelope)?); + Ok(()) +} +``` + +Build it and sign the component as module `hello`, revision 1, serving `POST /hello`: + +```sh +cd /tmp/protrus-demo +cargo build --release --manifest-path sign-module/Cargo.toml +sign-module/target/release/sign-module release-1.seed release-1 \ + hello-module/hello.component.wasm hello 1.0.0 1 "POST /hello" > hello-1.json +``` + +```text +trusted_signers_hex entry: "release-1": "32c23ac2deec6481edc2efcea35ce3f2fdb99632f4fb3568325e646b1a0d2aa8" +``` + +To set more manifest fields (`capabilities`, `scope`, `isolation_mode`, `bridged_services`, +`module_kind`, ...), edit the `ManifestV1` literal. A `scope` must be set on both the manifest +and the record. + +## The deploy envelope + +`hello-1.json`, with the signed bundle shown as its manifest only: + +```sh +jq '{idempotency_key, expected_revision, record, routes, + signer: .signed_artifact.signer_key_id, manifest: .signed_artifact.bundle.manifest}' hello-1.json +``` + +```json +{ + "idempotency_key": "hello-1", + "expected_revision": null, + "record": { + "module_id": "hello", + "revision": 1, + "artifact_digest": "sha256:938960abca8e65659759697e07f1daa69d112635c27bec2c7cf275b0ba479267", + "dependency_generations": [], + "provided_generation": null, + "observed_binding": null, + "sticky_reason": null, + "routes": [], + "pending_cleanup": [], + "desired_state": "active", + "observed_state": "absent" + }, + "routes": [{ "method": "POST", "path": "/hello" }], + "signer": "release-1", + "manifest": { + "api_version": "protrus/v1", + "kind": "module", + "id": "hello", + "version": "1.0.0", + "routes": [{ "method": "POST", "path": "/hello" }], + "capabilities": [] + } +} +``` + +| Envelope field | Meaning | +| --- | --- | +| `idempotency_key` | Replaying the same key with the same record and routes returns the earlier result; the same key with different content is a conflict | +| `expected_revision` | `null`, or the revision the module must currently have (optimistic concurrency); a mismatch is `409 STATE_CONFLICT` | +| `record.module_id`, `record.revision`, `record.artifact_digest`, `record.scope` | Must match the signed artifact's id, digest and scope. Each deploy of a module uses a new revision; a revision cannot be rebound to another artifact | +| `record.*` (other fields) | Server-owned; the host overwrites them. Send them as shown | +| `routes` | The routes the host installs: exact `METHOD /path` matches. They must be exactly the manifest's signed `routes` (same set); paths must start with `/`, must not contain `//`, and must not be under `/platform` | +| `signed_artifact` | The `SignedArtifact`. In JSON its `signature` and file contents are arrays of byte values | + +The envelope fields outside `signed_artifact` are not signed, so you can change +`idempotency_key` or `expected_revision` without re-signing. Routes are signed: the host refuses +an envelope whose `routes` differ from the manifest's (`deployment routes must match the signed +manifest routes`), so generate both from the same source, as the program above does. + +## Trust the key on the host + +Add the public key to the bootstrap and restart the host: + +```json +"trusted_signers_hex": { + "release-1": "32c23ac2deec6481edc2efcea35ce3f2fdb99632f4fb3568325e646b1a0d2aa8" +} +``` + +The key id is what the artifact's `signer_key_id` names. A signer the host does not know is +refused at the signature gate: + +```text +{"type":"urn:protean:error:gate-failed","title":"Promotion gate failed","status":422,"detail":"promotion gate signature failed: untrusted signer release-1","code":"GATE_FAILED","gate":"signature",...} +``` + +Keys can also be added without a restart through the LIVE config key `gate.signature.keys`, +which takes key id to Base64 X.509 public key: + +```sh +curl -s -X PATCH http://127.0.0.1:8088/platform/config -H 'content-type: application/json' \ + -H "Authorization: Bearer $(cat /tmp/protrus-demo/operator-token)" \ + -d "{\"gate.signature.keys\": {\"release-1\": \"$(openssl pkey -in release-1.pem -pubout -outform DER | base64)\"}}" +``` + +```text +{"applied":true,"outcomes":[{"key":"gate.signature.keys","tier":"LIVE","outcome":"APPLIED_LIVE","reason":null}]} +``` + +A key set this way lasts until the host stops. Stored modules are re-verified at every start, +and a module whose signer is no longer trusted stays `degraded` with +`stickyReason: "gate signature rejected deployment: untrusted signer ..."`. Put every key you +rely on in the bootstrap, either in `trusted_signers_hex` or as +`"config": {"gate.signature.keys": {...}}`. + +`gate.signature.required` (LIVE, default `true`) can be turned off to accept unsigned artifacts: +an artifact whose `signer_key_id` and `signature` are both empty. An artifact that carries a +signature is always verified, whatever the switch says. + +Next: [deploy and operate it](03-deploying-and-operating.md). diff --git a/docs/guide/03-deploying-and-operating.md b/docs/guide/03-deploying-and-operating.md new file mode 100644 index 0000000..c469dc7 --- /dev/null +++ b/docs/guide/03-deploying-and-operating.md @@ -0,0 +1,391 @@ +# 3. Deploying and operating + +The control plane lives under `/platform`, over REST and over MCP. Both reach the same services +and the same authorization. Module traffic is served at the module's own routes on the same +listener. + +The examples continue from [page 2](02-building-and-signing-modules.md): an `async-wasm` host on +`127.0.0.1:8088` that trusts `release-1`, and the envelope `hello-1.json`. Every change needs the +bearer token: + +```sh +cd /tmp/protrus-demo +TOKEN="Authorization: Bearer $(cat /tmp/protrus-demo/operator-token)" +``` + +## Install + +```sh +curl -s -X POST http://127.0.0.1:8088/platform/modules -H 'content-type: application/json' \ + -H "$TOKEN" --data-binary @hello-1.json | jq . +``` + +```json +{ + "id": "hello", + "version": "1", + "trustTier": "TRUSTED", + "desiredState": "ACTIVE", + "controllerFqcn": null, + "mode": "in-process", + "needsSharedBeans": false, + "bridgedInterfaces": [], + "boundGeneration": 0, + "kind": "NORMAL", + "exports": [], + "uses": [], + "boundLibraryGenerations": [], + "libraryGeneration": null, + "scope": null, + "runtimeId": "main", + "observedState": "active", + "artifactDigest": "sha256:938960abca8e65659759697e07f1daa69d112635c27bec2c7cf275b0ba479267", + "dependencyGenerations": [], + "stickyReason": null +} +``` + +The answer is `201 Created` with `Location: /platform/modules/hello`. The module now serves its +route: + +```sh +curl -s -X POST http://127.0.0.1:8088/hello -d 'world' +``` + +```text +hello, world +``` + +A route matches on exact method and path; there are no path templates or prefixes. The query +string is ignored for matching and is not passed to the component. An unmatched request is +`404`. Sending the same envelope again is an idempotent replay and returns the same result. + +## Module status fields + +`GET /platform/modules`, `GET /platform/modules/{id}`, the deploy responses and the MCP module +tools all return this object. + +| Field | Meaning | +| --- | --- | +| `id` | Module id | +| `version` | The **revision** number as a string, not the manifest's `version`. Use it for rollback | +| `desiredState` | `ACTIVE`, `PENDING_APPROVAL` or `INACTIVE` | +| `observedState` | `absent`, `preparing`, `active`, `draining` or `degraded` | +| `stickyReason` | Why the module is not on its latest wish, for example a failed restart or rebind. The previous revision keeps serving where it can | +| `mode` | Isolation mode it runs under: `in-process`, `worker` or `container` | +| `runtimeId` | `main` for in-process, the worker or container runtime id otherwise; `null` unless active | +| `artifactDigest` | Digest of the artifact this revision runs | +| `scope` | Database scope, or `null` | +| `kind`, `exports`, `libraryGeneration` | `LIBRARY` modules ([page 6](06-sharing-code.md#library-modules)) | +| `uses`, `boundLibraryGenerations` | Libraries this module links and their generations | +| `boundGeneration`, `dependencyGenerations` | Shared-lib store generation and the exact lib bytes bound (`shared-lib:@`) ([page 6](06-sharing-code.md#shared-libs)) | +| `needsSharedBeans`, `bridgedInterfaces` | Host services the module declares ([page 7](07-host-services.md)) | +| `trustTier`, `controllerFqcn` | Protean compatibility fields; always `TRUSTED` and `null` | + +## Update + +Sign a new revision. The program from page 2 takes the revision as an argument; this one adds a +second route: + +```sh +sign-module/target/release/sign-module release-1.seed release-1 \ + hello-module/hello.component.wasm hello 1.1.0 2 "POST /hello" "POST /hello/v2" > hello-2.json +jq '.expected_revision = 1' hello-2.json > hello-2-guarded.json +curl -s -X PUT http://127.0.0.1:8088/platform/modules/hello -H 'content-type: application/json' \ + -H "$TOKEN" --data-binary @hello-2-guarded.json | jq '{id, version, observedState, artifactDigest}' +``` + +```json +{ + "id": "hello", + "version": "2", + "observedState": "active", + "artifactDigest": "sha256:2bb91beeb7e91e728abc91c90cd040f5084bbd5732fa290c00b0b940b113eef4" +} +``` + +The new revision is prepared and verified while the old one serves, then the routes switch +atomically. If preparation fails, the old revision keeps serving. `PUT` needs the module to +exist (`404 MODULE_NOT_FOUND` otherwise) and the path id to match the body. `POST` to +`/platform/modules` with a new revision also updates an existing module; `PUT` is authorized as +an update rather than a deploy. + +`expected_revision` guards against concurrent changes. Sent again under a new idempotency key +after the update above, it fails: + +```json +{ + "type": "urn:protean:error:state-conflict", + "title": "State conflict", + "status": 409, + "detail": "revision conflict: expected Some(Revision(1)), actual Some(Revision(2))", + "code": "STATE_CONFLICT", + "traceId": "dcb566a9-9e1f-4ca7-b6cf-1b1be7270178" +} +``` + +A module's isolation mode cannot change through an update; uninstall and install again. + +## History and rollback + +```sh +curl -s http://127.0.0.1:8088/platform/modules/hello/routes +curl -s http://127.0.0.1:8088/platform/modules/hello/versions | jq -c '.[] | {version, artifactDigest}' +``` + +```text +[{"methods":["POST"],"patterns":["/hello"]},{"methods":["POST"],"patterns":["/hello/v2"]}] +{"version":"2","artifactDigest":"sha256:2bb91beeb7e91e728abc91c90cd040f5084bbd5732fa290c00b0b940b113eef4"} +{"version":"1","artifactDigest":"sha256:938960abca8e65659759697e07f1daa69d112635c27bec2c7cf275b0ba479267"} +``` + +Roll back by revision. Rollback redeploys the stored artifact of that revision as a **new** +revision: + +```sh +curl -s -X POST 'http://127.0.0.1:8088/platform/modules/hello/rollback?version=1' -H "$TOKEN" \ + | jq '{id, version, artifactDigest}' +curl -s http://127.0.0.1:8088/platform/modules/hello/routes +``` + +```text +{ + "id": "hello", + "version": "3", + "artifactDigest": "sha256:938960abca8e65659759697e07f1daa69d112635c27bec2c7cf275b0ba479267" +} +[{"methods":["POST"],"patterns":["/hello"]}] +``` + +## Approval + +With `gate.approval.required` on (LIVE, default `false`), a new install is parked as +`PENDING_APPROVAL` and serves nothing until someone approves it. Updates of an already active +module are not parked. + +```sh +curl -s -X PATCH http://127.0.0.1:8088/platform/config -H 'content-type: application/json' \ + -H "$TOKEN" -d '{"gate.approval.required": true}' +sign-module/target/release/sign-module release-1.seed release-1 \ + hello-module/hello.component.wasm greeter 1.0.0 1 "POST /greet" > greeter-1.json +curl -s -X POST http://127.0.0.1:8088/platform/modules -H 'content-type: application/json' \ + -H "$TOKEN" --data-binary @greeter-1.json | jq '{id, desiredState, observedState}' +curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:8088/greet -d x +curl -s -X POST 'http://127.0.0.1:8088/platform/modules/greeter/approve?approver=alice' \ + -H "$TOKEN" | jq '{id, desiredState, observedState}' +curl -s -X POST http://127.0.0.1:8088/greet -d 'alice' +``` + +```text +{"applied":true,"outcomes":[{"key":"gate.approval.required","tier":"LIVE","outcome":"APPLIED_LIVE","reason":null}]} +{ + "id": "greeter", + "desiredState": "PENDING_APPROVAL", + "observedState": "absent" +} +404 +{ + "id": "greeter", + "desiredState": "ACTIVE", + "observedState": "active" +} +hello, alice +``` + +`approver` is required (`400` without it). `POST /platform/modules/{id}/reject?approver=...` +removes a pending module and answers `204`. A pending module is listed by +`GET /platform/modules/{id}` but not by `GET /platform/modules`, which lists installed modules +that are not pending. + +## Uninstall + +```sh +curl -s -o /dev/null -w '%{http_code}\n' -X DELETE http://127.0.0.1:8088/platform/modules/greeter -H "$TOKEN" +``` + +```text +204 +``` + +The routes are removed first; on `worker` and `oci` hosts the worker module or container pair is +drained and stopped. + +## Promotion gates + +Every deploy and update runs through these checks, in order. A failure is `422 GATE_FAILED` +with the gate's name in `gate`, and the previous revision keeps serving. Approving a pending +install does not run the first three again: the deploy that parked it already passed them. + +| Gate | Checks | Switch (LIVE) | +| --- | --- | --- | +| `signature` | Signer trusted, signature valid, manifest id, digest and scope equal the record | `gate.signature.required` (default `true`): when off, unsigned artifacts are accepted; signed ones are still verified | +| `tests` | Calls the component's `tests.run(name)` for each name in the manifest's `tests`, each in a fresh instance. While on, a module that bundles no tests is refused (`unit tests are required (tests must be bundled)`) | `gate.tests-enabled` (default `false`). `mcp.capture-test-output` appends what failing tests logged | +| `policy` | Every declared capability is in `allowed_capabilities`; none is declared twice | `gate.review-enabled` (default `true`) | +| `verification` | After preparation, before routing: the manifest's `verification` probes are sent to the candidate | none; runs when the manifest has a plan | + +A verification plan uses Protean's JSON names: + +```json +"verification": { + "integration": [{"method": "GET", "path": "/hello", "expectedStatus": 200, "bodyContains": "hello"}], + "loadPath": "/hello", + "concurrency": 4, + "requestsPerThread": 10, + "maxAvgLatencyMs": 200, + "maxHeapGrowthBytes": 50000000 +} +``` + +`integration` probes default to `GET`. The load run (`loadPath` with `concurrency`) sends `GET` +requests and fails on non-2xx answers or when the average latency or the host's resident-memory +growth exceeds the limits. + +## Patch and resource reload + +`PATCH /platform/modules/{id}` and `POST /platform/modules/{id}/reload-resources` take a delta +plus the complete signed artifact the delta produces. The host has no signing key: it checks that +applying the delta to the stored base artifact gives exactly the signed candidate, then deploys +it as a new revision. Body fields: + +| Field | Meaning | +| --- | --- | +| `idempotency_key`, `expected_revision`, `record`, `routes` | As in the deploy envelope | +| `base_digest` | Digest of the stored artifact the delta applies to | +| `add_or_replace` | Path to file bytes (byte arrays) | +| `remove` | Paths to delete | +| `version` | New manifest `version`, optional | +| `signed_artifact` | The signed result | + +`reload-resources` accepts only paths under `resources/`. + +## REST reference + +All paths are under the fixed `/platform` namespace. Reads are open; every change needs the +host identity ([page 1](01-getting-started.md#the-bootstrap-file)). + +| Method and path | Does | Answer | +| --- | --- | --- | +| `GET /platform/modules` | Installed modules (not pending) | `200` list of module status | +| `POST /platform/modules` | Install or update from a deploy envelope | `201` status, `Location` header | +| `POST /platform/modules/from-manifest` | The same envelope as YAML | `201` status | +| `GET /platform/modules/{id}` | One module, pending included | `200` status, `404 MODULE_NOT_FOUND` | +| `PUT /platform/modules/{id}` | Update an existing module | `200` status | +| `PATCH /platform/modules/{id}` | Update from a signed delta | `200` status | +| `DELETE /platform/modules/{id}` | Uninstall | `204` | +| `GET /platform/modules/{id}/routes` | Installed routes | `200` `[{methods, patterns}]` | +| `GET /platform/modules/{id}/versions` | Revision history, newest first | `200` list of status | +| `POST /platform/modules/{id}/approve?approver=` | Promote a pending install | `200` status | +| `POST /platform/modules/{id}/reject?approver=` | Drop a pending install | `204` | +| `POST /platform/modules/{id}/rollback?version=` | Redeploy a stored revision as a new revision | `200` status | +| `POST /platform/modules/{id}/reload-resources` | Update `resources/` from a signed delta | `200` status | +| `GET /platform/runtimes` | `main` and every worker or container, with hosted module ids | `200` list | +| `GET`, `PATCH /platform/config`, `GET /platform/config/{key}` | Runtime config ([page 4](04-configuration.md)) | | +| `GET /platform/traces`, `/traces/metrics`, `/traces/stream` | Request traces ([page 8](08-debugging-and-observability.md)) | | +| `GET`, `POST /platform/shared-libs`, `GET`, `DELETE /platform/shared-libs/{name}` | Shared-lib store ([page 6](06-sharing-code.md#shared-libs)) | | +| `/platform/scopes...` | DB scopes, only when the host auto-provisions ([page 9](09-databases.md#worker-and-oci-auto-provisioned-scopes)) | | +| `POST`, `GET`, `DELETE /platform/mcp` | MCP Streamable HTTP, when `mcp.enabled` | | + +With `admin.enabled: false` (restart), `/platform/modules`, `/config`, `/traces`, `/scopes` and +`/shared-libs` answer `404`; `/platform/runtimes` and MCP keep working. + +Errors are RFC 9457 problems with a stable `code`: + +| Status | `code` | Typical cause | +| --- | --- | --- | +| 400 | `INVALID_ARGUMENT` | Malformed envelope, invalid route, missing `approver`, unknown config key | +| 403 | `FORBIDDEN` | No or wrong bearer token | +| 404 | `MODULE_NOT_FOUND`, `SHARED_LIB_NOT_FOUND` | Unknown id | +| 409 | `STATE_CONFLICT` | Revision conflict, isolation-mode change, unsupported mode, library not active | +| 422 | `GATE_FAILED` | A promotion gate refused the artifact (`gate` names which) | +| 500 | `INTERNAL_ERROR` | Runtime or store failure; read `detail` | + +## MCP + +Enable with `"config": {"mcp.enabled": true}` (restart). The endpoint is `POST /platform/mcp` +(JSON-RPC, protocol `2025-11-25`), `GET` for the notification stream and `DELETE` to end a +session. Set `mcp.stdio: true` as well to serve MCP on the host's stdin and stdout; stdio +requests are treated as the local operator and may change things without a token. + +```sh +curl -s -i http://127.0.0.1:8088/platform/mcp -H 'content-type: application/json' \ + -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25"}}' +``` + +```text +mcp-session-id: mcp-1 +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","capabilities":{"tools":{"listChanged":true},"resources":{"subscribe":true},"prompts":{},"logging":{},"completions":{}},"serverInfo":{"name":"protean","version":"0.1.0"}}} +``` + +Send `Mcp-Session-Id` on later requests if you want session features (notifications, +cancellation); plain `tools/call` requests work without it. The bearer token works exactly as on +REST. + +`protean.deploy_module` and `protean.update_module` take the deploy envelope itself as +`arguments`: + +```sh +sign-module/target/release/sign-module release-1.seed release-1 \ + hello-module/hello.component.wasm hello-mcp 1.0.0 1 "POST /hello-mcp" > hello-mcp-1.json +jq '{jsonrpc: "2.0", id: 2, method: "tools/call", + params: {name: "protean.deploy_module", arguments: .}}' hello-mcp-1.json \ + | curl -s http://127.0.0.1:8088/platform/mcp -H 'content-type: application/json' \ + -H "$TOKEN" --data-binary @- \ + | jq '.result | {isError, text: .content[0].text, mode: .structuredContent.mode}' +``` + +```json +{ + "isError": false, + "text": "Module hello-mcp deployed (ACTIVE)", + "mode": "in-process" +} +``` + +A tool call refused by authorization is a tool error, not an HTTP error: + +```text +{"isError":true,"text":"[PERMISSION_DENIED] authenticated host identity is required"} +``` + +The structured problem is in the result's `_meta["org.htcom.protean/problem"]`, with `code`, +`detail` and the `action` and `tool` that were denied. + +| Tools | Arguments | Notes | +| --- | --- | --- | +| `protean.list_modules` | `query`, `mode`, `trustTier`, `limit`, `cursor` (all optional) | Read | +| `protean.get_module`, `protean.module_versions` | `id` | Read | +| `protean.list_runtimes` | `mode`, `scope` (optional) | Read | +| `protean.deploy_module`, `protean.update_module` | the deploy envelope | | +| `protean.patch_module`, `protean.reload_module_resources` | `id` plus the patch body | | +| `protean.rollback_module` | `id`, `version` (the revision, as a string) | | +| `protean.uninstall_module` | `id` | | +| `protean.approve_module`, `protean.reject_module` | `id`, `approver` | | +| `protean.query_traces`, `protean.module_metrics` | see [page 8](08-debugging-and-observability.md) | Read | +| `config.list`, `config.get`, `config.set` | `key`; `changes` for `config.set` | `config.set` is a change | +| `protean.deploy_shared_lib`, `list_shared_libs`, `get_shared_lib`, `remove_shared_lib` | see [page 6](06-sharing-code.md#shared-libs) | | +| `protean.scope_list`, `scope_get`, `scope_create`, `scope_open`, `scope_close`, `scope_detach`, `scope_destroy` | `name`; `confirm` for destroy | Listed always; answer `STATE_CONFLICT` without auto-provisioning | +| `debug.*` | see [page 8](08-debugging-and-observability.md#mcp-debug-tools) | Need `mcp.debug.enabled` | + +The scenario files in [`examples/scenarios`](../../examples/scenarios) are complete, tested +sequences of MCP calls and HTTP requests against each topology; each `"deploy"` step stands for +a `deploy_module` call whose arguments are a signed envelope like the one above. + +Other MCP features: + +- Resources `protean://modules`, `protean://modules/{id}/versions`, + `protean://modules/{id}/routes` and `protean://traces`; subscribers get + `notifications/resources/updated` when a module changes. +- A `tools/call` with `_meta.progressToken` is answered as a server-sent event stream of + `notifications/progress` (deploy stages `gates (signature/capability)`, `prepare`, + `verification`, `active (ACTIVE)`) ending with the result. `notifications/cancelled` stops a + deploy at the next stage while the previous revision keeps serving. +- List methods return at most 100 entries plus `nextCursor`. +- `mcp.strict-schema` (LIVE) validates tool arguments and results against their schemas. +- `mcp.session.enabled: false` (restart) turns sessions off. +- Setting `mcp.authorization.resource` serves OAuth protected-resource metadata at + `/.well-known/oauth-protected-resource`. + +Design 17 ([`docs/design/17-mcp-session-and-extension-contract.md`](../design/17-mcp-session-and-extension-contract.md), +in Korean) is the full MCP contract. + +Next: [configuration](04-configuration.md). diff --git a/docs/guide/04-configuration.md b/docs/guide/04-configuration.md new file mode 100644 index 0000000..ec8f0aa --- /dev/null +++ b/docs/guide/04-configuration.md @@ -0,0 +1,186 @@ +# 4. Configuration + +Protrus has two layers of configuration: + +- The **bootstrap file** ([page 1](01-getting-started.md#the-bootstrap-file)): paths, binaries, + images, signer keys, identity, database admin settings. Read once at startup. +- The **runtime config registry**: Protean's `protean.*` keys, with the same names, types and + defaults (two defaults differ, see below). Initial values come from the bootstrap `config` map; + many keys can be changed at runtime over `/platform/config` or the MCP `config.*` tools. + +The registry is implemented in +[`crates/protrus-config/src/lib.rs`](../../crates/protrus-config/src/lib.rs). The full table of +all 64 keys, with the decision behind each, is +[design 30](../design/30-runtime-config-registry.md) (in Korean). + +## Tiers + +Each key has a tier that says when a change takes effect: + +| Tier | Takes effect | Change at runtime | +| --- | --- | --- | +| `LIVE` | Immediately | Yes | +| `FUTURE` | For instances created afterward (the next placement, the next container) | Yes | +| `RESTART_CONDITIONAL` | Decides which components the host builds at startup | No: set it in the bootstrap and restart | +| `RESTART_ARTIFACT` | Built into something made at startup | No: set it in the bootstrap and restart | + +`liveApplicable` in each entry tells you whether a change applies on **this** host now. A +`LIVE` or `FUTURE` key is `false` when no consumer on this topology reads it, for example the +`worker.*` keys on an `async-wasm` host. + +## Set initial values + +Put keys in the bootstrap `config` map. The `protean.` prefix is optional. + +```json +"config": { + "mcp.enabled": true, + "gate.approval.required": true, + "trace.metrics.enabled": true +} +``` + +The host validates every key at startup: an unknown key, a value of the wrong type, or a +Protean key that has no Protrus equivalent (for example `worker.jvm-args`) stops startup with a +message naming the key. + +## Read and change at runtime + +```sh +curl -s http://127.0.0.1:8088/platform/config # every key +curl -s http://127.0.0.1:8088/platform/config/trace.capacity # one key +``` + +Each entry is `{"key", "value", "tier", "liveApplicable"}`. Secret keys +(`worker.db.admin-password`) show `"***"` when set. + +`PATCH /platform/config` takes an object of key to value, needs the host identity (`$TOKEN` as +set on [page 3](03-deploying-and-operating.md)), and applies the batch atomically: if any key +is unknown or invalid, nothing is applied. + +```sh +curl -s -X PATCH http://127.0.0.1:8088/platform/config -H 'content-type: application/json' \ + -H "$TOKEN" -d '{"trace.capacity": 1000, "mcp.debug.enabled": true}' | jq . +``` + +```json +{ + "applied": true, + "outcomes": [ + { "key": "trace.capacity", "tier": "LIVE", "outcome": "APPLIED_LIVE", "reason": null }, + { "key": "mcp.debug.enabled", "tier": "RESTART_CONDITIONAL", "outcome": "REQUIRES_RESTART", + "reason": "requires restart: decides which components the host builds at startup" } + ] +} +``` + +A key that needs a restart is reported, not applied, and does not abort the batch. An invalid +value does: + +```sh +curl -s -X PATCH http://127.0.0.1:8088/platform/config -H 'content-type: application/json' \ + -H "$TOKEN" -d '{"trace.capacity": 0, "gate.approval.required": true}' | jq . +``` + +```json +{ + "applied": false, + "outcomes": [ + { "key": "trace.capacity", "tier": "LIVE", "outcome": "REJECTED_INVALID", "reason": "must be >= 1" }, + { "key": "gate.approval.required", "tier": "LIVE", "outcome": "NOT_APPLIED_BATCH_ABORTED", + "reason": "batch aborted due to another invalid/unknown key" } + ] +} +``` + +The answer is `200` when the batch applied and `400` when it did not. Outcomes are +`APPLIED_LIVE`, `APPLIED_FUTURE`, `REQUIRES_RESTART`, `REJECTED_UNKNOWN`, `REJECTED_INVALID` +and `NOT_APPLIED_BATCH_ABORTED`. MCP `config.set` takes `{"changes": {...}}` and returns the +same result. + +Each applied change is logged on stderr: + +```text +{"event":"protrus_config_changed","actor":"rest","keys":["gate.approval.required"]} +``` + +**Runtime changes are not persisted.** A restart starts again from the bootstrap `config` map. +Copy any change you want to keep into the bootstrap. + +## Key groups + +Defaults are Protean's, except `gate.signature.required` (`true`) and `gate.tests-enabled` +(`false`). + +### Gates and approval (all LIVE, all topologies) + +| Key | Default | Effect | +| --- | --- | --- | +| `gate.signature.required` | `true` | Off accepts unsigned artifacts ([page 2](02-building-and-signing-modules.md#trust-the-key-on-the-host)) | +| `gate.signature.keys` | `{}` | Extra trusted keys, id to Base64 X.509 Ed25519 public key | +| `gate.review-enabled` | `true` | Off skips the capability policy gate | +| `gate.tests-enabled` | `false` | Runs bundled unit tests before deploy | +| `gate.approval.required` | `false` | New installs wait for approval | +| `gate.signature.shared-lib-required` | `false` | Shared-lib uploads must be signed | +| `mcp.capture-test-output` | `false` | Failing unit-test output in the gate message | + +### Module execution + +| Key | Tier | Default | Effect | +| --- | --- | --- | --- | +| `module.request-timeout-ms` | LIVE | `0` (none) | Per-request deadline; `0` still leaves the in-process fuel limit | +| `isolation.mode` | FUTURE | the topology's default | Mode for modules whose manifest names none ([page 5](05-isolation-and-workers.md)) | +| `module.shared-lib.eager-invalidation` | LIVE | `true` | Redeploy dependents when a shared lib changes | +| `module.shared-lib-store-dir` | RESTART_ARTIFACT | `""` (`/shared-libs`) | Shared-lib store location | + +### Workers and containers + +| Key | Tier | Default | Topology | +| --- | --- | --- | --- | +| `worker.modules-per-worker` | FUTURE | `128` | `worker` | +| `worker.min-warm` | FUTURE | `0` | `worker` | +| `worker.auto-restart` | LIVE | `false` | `worker` | +| `worker.shutdown-grace-ms` | LIVE | `5000` | `worker` | +| `worker.rpc-bridge` | RESTART_CONDITIONAL | `false` | `worker` ([page 7](07-host-services.md)) | +| `worker.container.auto-restart` | LIVE | `false` | `oci` | +| `worker.container.image`, `.network`, `.memory` (`512m`), `.pids-limit` (`1024`), `.seccomp`, `.db-host` (`host.docker.internal`) | FUTURE | | `oci` | + +See [page 5](05-isolation-and-workers.md) for what each does. + +### Databases + +`worker.db.auto-provision` (RESTART_CONDITIONAL), `worker.db.scopes` (LIVE), +`worker.db.allow-destroy` (LIVE), `worker.db.admin-url`, `worker.db.admin-username`, +`worker.db.admin-password` (FUTURE, secret), and `module-store.backend`, `module-store.dir`, +`module-store.dialect` (restart). See [page 9](09-databases.md). + +### MCP and admin surface (restart unless noted) + +| Key | Default | Effect | +| --- | --- | --- | +| `admin.enabled` | `true` | Off: admin REST paths answer 404 | +| `mcp.enabled` | `false` | Mount `/platform/mcp` | +| `mcp.stdio` | `false` | Also serve MCP on stdio (needs `mcp.enabled`) | +| `mcp.session.enabled` | `true` | Issue MCP sessions | +| `mcp.debug.enabled` | `false` | Allow the `debug.*` tools | +| `mcp.debug.session-idle-timeout` | `PT30M` | Interactive debug sessions resume after this idle time | +| `mcp.strict-schema` | `false` | LIVE: validate tool input and output | +| `mcp.authorization.resource` | unset | Serve OAuth protected-resource metadata | +| `mcp.authorization.authorization-servers`, `scopes-supported`, `bearer-methods-supported` | `[]`, `[]`, `["header"]` | LIVE, used when `resource` is set | + +### Traces (all LIVE except the last two, which are FUTURE) + +`trace.enabled` (`true`), `trace.capacity` (`200`), `trace.summary-window-ms` (`60000`), +`trace.metrics.enabled` (`false`), `trace.metrics.latency-buckets` (`20`), +`trace.metrics.max-modules` (`512`). See [page 8](08-debugging-and-observability.md). + +### Keys with no Protrus equivalent + +JVM-only keys (`worker.jvm-args`, `worker.runtime`, `worker.container.jar`, `worker.sidecar.*`, +`module.shared-lib-dir`), `module.executor.pool-size`, `worker.datasource.url`, and the +`bridge.*` HTTP bridge keys (Protrus bridges over a private socket instead) are listed for +compatibility. Setting them in the bootstrap stops startup. At runtime a change to one of them +is rejected (`REJECTED_INVALID`, which aborts the batch) or, for a restart-tier key, reported as +`REQUIRES_RESTART` with the reason. + +Next: [isolation and workers](05-isolation-and-workers.md). diff --git a/docs/guide/05-isolation-and-workers.md b/docs/guide/05-isolation-and-workers.md new file mode 100644 index 0000000..3c57243 --- /dev/null +++ b/docs/guide/05-isolation-and-workers.md @@ -0,0 +1,225 @@ +# 5. Isolation and workers + +Each module runs under one isolation mode. Which modes are available depends on the host's +topology: + +| Topology | Modes served | Default (`isolation.mode`) | +| --- | --- | --- | +| `async-wasm` | `in-process` | `in-process` | +| `worker` | `in-process`, `worker` | `worker` | +| `oci` | `in-process`, `container` | `container` | + +- `in-process`: the component runs inside the host process, on the runtime reported as `main`. + Fastest, but a module shares the host's process. +- `worker`: the component runs in a `protrus-worker` child process. Several modules share one + worker ("packing"). +- `container`: the component runs in its own Docker container pair, one module per pair. + +## How a module's mode is chosen + +1. The signed manifest's `isolation_mode`, if set. +2. Otherwise `isolation.mode` (FUTURE) as it is at deploy time. A bootstrap value must be one of + the host's modes or startup fails (`no strategy for default isolation.mode=...`). + +A mode the host does not serve is refused with `409 STATE_CONFLICT` +(`unknown isolation mode: worker (available: [in-process])`). The mode is fixed for the life of +the installed module: an update that would resolve to another mode is refused +(`cannot change the isolation mode of module ... via update`); uninstall and install again. +Restarts, rollbacks and shared-lib rebinds keep the mode the module runs under. + +Some modules must be in a particular mode: + +| Module | Allowed modes | +| --- | --- | +| `LIBRARY` ([page 6](06-sharing-code.md#library-modules)) | `in-process` only; pin `isolation_mode: "in-process"` on `worker` and `oci` hosts | +| Declares `bridged_services` ([page 7](07-host-services.md)) | `in-process`; `worker` only while `worker.rpc-bridge` is on; never `container` | +| Declares a `scope` while the host auto-provisions ([page 9](09-databases.md)) | `worker` or `container`; `in-process` is refused | + +## Worker topology + +### Packing + +The host starts empty workers and loads modules into them over a pool socket. Placement and +retirement follow Protean's pool: + +| Key | Tier | Default | Effect | +| --- | --- | --- | --- | +| `worker.modules-per-worker` | FUTURE | `128` | Modules one worker may hold; read at every placement | +| `worker.min-warm` | FUTURE | `0` | Empty workers to keep instead of retiring them | + +- **Placement:** the first live worker, in spawn order, that has room and does not already hold + the same module id. A new revision is never placed next to its old revision, so an update + moves the module to another worker. When nothing fits, a new worker starts. Workers are not + pre-started. +- **Retirement:** a worker that becomes empty is retired (state `RETIRING`, then gone) when its + module moved to another worker in an update, when the load that started it failed, when it + died, or when more than `worker.min-warm` empty workers would remain. Otherwise it stays warm + and shows in `/platform/runtimes` with no modules. +- **Shared fate:** modules in one worker share its process. If it dies, all of them are down, + and they all report the same `runtimeId`. +- Under database auto-provisioning a worker holds modules of one scope only, and `min-warm` is + treated as `0`. + +`GET /platform/runtimes` (or MCP `protean.list_runtimes`) shows the layout: + +```text +[{"runtimeId":"main","mode":"in-process","scope":null,"state":"LIVE","sinceEpochMs":1795509423662,"moduleIds":[]}, + {"runtimeId":"worker-47543-d2cce2bd5ad0655f","mode":"worker","scope":null,"state":"LIVE","sinceEpochMs":1795509426557,"moduleIds":["ip-echo"]}] +``` + +`state` is `LIVE` or `RETIRING`. + +### Crashes and auto-restart + +The host watches its workers. With `worker.auto-restart` (LIVE) off, the default, a module whose +worker exits stays down until it is updated or the host restarts. With it on, the module is +redeployed at the same revision on a fresh worker. Each crash is logged: + +```text +{"event":"protrus_worker_crash","module_id":"ip-echo","revision":1,"runtime_id":"worker-47543-d2cce2bd5ad0655f","outcome":"restarted"} +``` + +With the switch off, `outcome` is `left down (worker.auto-restart is off)`. + +### Shutdown and timeouts + +- On `SIGTERM` or Ctrl-C the host stops every worker: `SIGTERM`, then `SIGKILL` after + `worker.shutdown-grace-ms` (LIVE, default `5000`; `0` kills at once). Workers do not outlive a + graceful host stop; after a `SIGKILL` of the host they can. +- `module.request-timeout-ms` (LIVE, default `0` = none) is enforced on the host side of the + proxy. Past it the client gets a timeout answer while the worker finishes on its own. +- Requests and responses through a worker are limited to 1 MiB. + +### Bootstrap fields + +| Field | Meaning | +| --- | --- | +| `control_socket_root` | Absolute directory for the host-to-worker Unix sockets (owner-only, mode `0600`). Keep the path short | +| `worker_program` | Absolute path of `protrus-worker` | +| `worker_args` | Extra arguments for it (default none) | +| `database_provisioning` | Optional; see [page 9](09-databases.md#worker-and-oci-auto-provisioned-scopes) | + +On a worker host the signed artifact store is `/artifacts`, and verified bundles are +materialized read-only under `artifact_root` for workers to load. + +## OCI host requirements + +The `oci` topology runs each container module as a **pair**: a worker container on an internal +Docker network with no published port, and a gateway container that is the only thing published, +on `127.0.0.1` with a random port. This is a deliberate difference from Protean (which publishes +the worker directly), so that worker egress can be denied; see +[design 05](../design/05-worker-protocol.md) (in Korean), section "P5 production gateway +profile". + +Prepare, before the host starts: + +1. **Images.** A worker image whose entrypoint is a Linux `protrus-worker`, and a gateway image + that listens on port 8080 and forwards to the `WORKER_ORIGIN` the host passes it. + [`poc/worker-container-fixture/Dockerfile.runtime`](../../poc/worker-container-fixture/Dockerfile.runtime) + builds a worker image from this repository; the `Dockerfile` and `gateway.js` next to it are + a test gateway. Containers run as user `65532:65532`. +2. **Pinned image ids.** The bootstrap names images by id, not tag: + `docker image inspect --format '{{.Id}}' ` prints the `sha256:...` value. +3. **An internal network** for workers: `docker network create --internal `. +4. **A control secret file.** The host reads it and mounts it read-only into each worker at + `/etc/protrus/control-secret`. Never put the secret in JSON, arguments or environment. The + container user must be able to read the file. +5. **A control socket directory** (`control_socket_root`), bind-mounted into the worker at the + same path. The container user must be able to create its socket there. +6. **A signed gateway profile.** An artifact with `kind: "gateway-profile"` whose only file, + `gateway-image.digest`, holds exactly the gateway image id, signed by a key in + `trusted_signers_hex` and published into `/artifacts/`. The host refuses to start + unless the profile verifies and attests `gateway_image_digest`. + +A program that signs and publishes the profile, compiled against this repository (same +`Cargo.toml` as the signing program on [page 2](02-building-and-signing-modules.md#sign-with-a-small-rust-program)): + +```rust +//! Signs a gateway profile that attests a gateway image id, and publishes it into the +//! OCI host's artifact store (`/artifacts/`). Prints the profile digest for +//! `gateway_profile_artifact_digest`. +//! +//! usage: gateway-profile +use ed25519_dalek::SigningKey; +use protrus_artifact::{ArtifactBundle, ArtifactRepository, FsArtifactRepository, ManifestV1, SignedArtifact}; +use protrus_core::ModuleId; +use std::{collections::BTreeMap, env, fs}; + +fn main() -> Result<(), Box> { + let args: Vec = env::args().skip(1).collect(); + let [seed_file, key_id, state_root, gateway_image] = args.as_slice() else { + return Err("usage: gateway-profile ".into()); + }; + let seed: [u8; 32] = fs::read(seed_file)? + .try_into() + .map_err(|_| "the seed file must hold exactly 32 bytes")?; + let manifest = ManifestV1 { + api_version: "protrus/v1".into(), + kind: "gateway-profile".into(), + id: ModuleId::parse("gateway-profile")?, + version: "1".into(), + component_abi_version: 1, + scope: None, + routes: vec![], + capabilities: vec![], + dependencies: vec![], + verification: None, + tests: vec![], + module_kind: None, + exports: vec![], + uses: vec![], + isolation_mode: None, + bridged_services: vec![], + }; + let bundle = ArtifactBundle { + manifest, + // The exact image id the host's `gateway_image_digest` names, with no newline. + files: BTreeMap::from([("gateway-image.digest".to_owned(), gateway_image.as_bytes().to_vec())]), + }; + let signed = SignedArtifact::sign(bundle, key_id.as_str(), &SigningKey::from_bytes(&seed))?; + let digest = FsArtifactRepository::new(state_root).publish(&signed)?; + println!("{}", digest.0); + Ok(()) +} +``` + +### OCI bootstrap fields + +In addition to the common fields ([page 1](01-getting-started.md#the-bootstrap-file)): + +| Field | Required | Meaning | +| --- | --- | --- | +| `control_socket_root` | yes | Absolute directory for worker control sockets | +| `control_secret_file` | yes | Absolute path of the control secret | +| `worker_image_digest` | yes | `sha256:` id of the worker image | +| `gateway_image_digest` | yes | `sha256:` id of the gateway image | +| `gateway_profile_artifact_digest` | yes | Digest of the signed gateway profile in `/artifacts/` | +| `worker_network` | yes | The internal Docker network | +| `worker_command`, `gateway_command` | no | Arguments appended after the image (default: the image's entrypoint alone) | +| `pair_watch_interval_ms` | no (`1000`) | How often pairs are checked for crashes; must not be `0` | +| `database_provisioning` | no | See [page 9](09-databases.md#worker-and-oci-auto-provisioned-scopes) | + +[`docs/examples/protrus-host-bootstrap.json`](../examples/protrus-host-bootstrap.json) is a +complete example with placeholder values. + +### Container settings + +Each worker container runs with a read-only root filesystem, all Linux capabilities dropped, +`no-new-privileges`, a 64 MiB `/tmp` tmpfs, and these FUTURE keys, read at each spawn: + +| Key | Default | Notes | +| --- | --- | --- | +| `worker.container.image` | `worker_image_digest` | Must be a pinned `sha256:` id; a value different from an explicit bootstrap field is a startup error | +| `worker.container.network` | `worker_network` | Must not be empty | +| `worker.container.memory` | `512m` | Docker memory size | +| `worker.container.pids-limit` | `1024` | | +| `worker.container.seccomp` | `""` | Path of a seccomp profile | +| `worker.container.db-host` | `host.docker.internal` | Replaces `localhost`/`127.0.0.1` in the scoped database URL given to containers | + +`worker.container.auto-restart` (LIVE, default `false`): when a pair crashes, the host asks for +the stored signed record to be reconciled once; it never starts an unverified replacement. +Pair-watch outcomes are logged as `protrus_pair_watch` events. On a graceful stop the host +removes its pairs. The [runbook](../operations/protrus-host-runbook.md) covers gateway rollback +and crash response. + +Next: [sharing code](06-sharing-code.md). diff --git a/docs/guide/06-sharing-code.md b/docs/guide/06-sharing-code.md new file mode 100644 index 0000000..b156929 --- /dev/null +++ b/docs/guide/06-sharing-code.md @@ -0,0 +1,155 @@ +# 6. Sharing code between modules + +Protrus has two ways for modules to share code. Both are WebAssembly components that export WIT +interfaces; a module that imports an interface of the same name gets it linked in. + +| | Shared lib | LIBRARY module | +| --- | --- | --- | +| What it is | A named blob in the host's shared-lib store | A signed module with `module_kind: "LIBRARY"` | +| Uploaded through | `/platform/shared-libs`, MCP `protean.deploy_shared_lib` | The normal deploy (`POST /platform/modules`) | +| Signed | Optional (`gate.signature.shared-lib-required`) | Always, like any module | +| A module names it in | `dependencies: [{"name": "..."}]` | `uses: [""]` | +| Versioned by | Store generation and the bytes' sha256 | The library's revision | +| Change propagates to dependents | Yes, by redeploying them | Yes, by redeploying them | + +In both cases the dependent module's component imports the interface (for example +`acme:pricing/discount`) and the host links the provider's export into it. The provider may not +import host interfaces or use resources. + +The example components are in +[`examples/artifacts/scenario-modules`](../../examples/artifacts/scenario-modules): +`acme-pricing` exports `acme:pricing/discount` (`world lib` in `wit/pricing.wit`), and +`price-only` is a module that imports it (`world consumer`). The scenarios +[`shared-lib-mcp.json`](../../examples/scenarios/shared-lib-mcp.json), +[`shared-module-mcp.json`](../../examples/scenarios/shared-module-mcp.json) and +[`shared-module-worker-mcp.json`](../../examples/scenarios/shared-module-worker-mcp.json) walk +through both mechanisms step by step. + +## Shared libs + +### Upload + +`POST /platform/shared-libs` is multipart. Send one `file` part per lib with parallel `name` and +`version` fields, and optionally parallel `signerKeyId` and `signature` fields. The whole upload +is limited to 10 MiB and is stored as one new generation. + +```sh +curl -s -X POST http://127.0.0.1:8088/platform/shared-libs -H "$TOKEN" \ + -F name=acme-pricing -F version=1.0.0 -F file=@acme-pricing.wasm | jq . +``` + +```json +{ + "generation": 1, + "libs": [ + { + "name": "acme-pricing", + "version": "1.0.0", + "sha256": "9c178a3f0b2a004cebe562bab2510a786dfcb6ccdc7767d6ab8410dd5b71517a", + "size": 20513, + "signerKeyId": null, + "signature": null + } + ] +} +``` + +| Route | Does | +| --- | --- | +| `GET /platform/shared-libs` | `{generation, libs}` | +| `GET /platform/shared-libs/{name}` | One lib's metadata, or `404 SHARED_LIB_NOT_FOUND` | +| `POST /platform/shared-libs` | Upload; `201` with the new view | +| `DELETE /platform/shared-libs/{name}` | Remove from future generations; `204` | + +Over MCP, `protean.deploy_shared_lib` takes `name`, `version`, `bytesBase64` and optionally +`signerKeyId` and `signature`; `protean.list_shared_libs`, `protean.get_shared_lib` (`name`) and +`protean.remove_shared_lib` (`name`) mirror the routes. + +Uploading the same name and version with different bytes is `409 STATE_CONFLICT`. Uploading +bytes the store already has publishes nothing new. + +With `gate.signature.shared-lib-required` (LIVE, default `false`) on, every lib needs a Base64 +Ed25519 signature over its bytes from a trusted key; an unsigned or bad one is +`422 GATE_FAILED` (`promotion gate shared-lib-signature failed: ...`). + +The store lives in `module.shared-lib-store-dir` (restart), or `/shared-libs` when +that key is empty, and is restored at startup. + +### Link + +A module declares the libs it links in its signed manifest, by name, in link order: + +```rust +dependencies: vec![ManifestDependency { name: "acme-pricing".into() }], +``` + +(`protrus_artifact::ManifestDependency` in the signing program from +[page 2](02-building-and-signing-modules.md#sign-with-a-small-rust-program).) The signature +covers the names, not the bytes. At deploy time the host binds each name to the lib's current +bytes and records them in the module's `dependencyGenerations` as +`shared-lib:@`. A lib that is not stored, does not compile, or does not provide +what the module imports fails the deploy; the previous revision keeps serving. + +### Change a lib + +When a lib is replaced with different bytes or removed and +`module.shared-lib.eager-invalidation` (LIVE, default `true`) is on, every active module that +uses it is redeployed as a new revision against the store as it is now. A module that fails keeps +its previous revision and shows the reason in `stickyReason`. Each outcome is logged as a +`protrus_shared_lib_rebind` event. With the key off, modules keep their bound bytes until they are +redeployed. Bytes that no lib and no installed module uses are deleted after each change. + +All three topologies link shared libs. Workers read them from `/blobs`, which an OCI +container gets as a read-only mount at the same path. + +## LIBRARY modules + +A LIBRARY is a module that serves no routes and lends WIT interfaces to other modules. + +Sign the library with these manifest fields and no routes (`routes` empty in both the manifest +and the envelope): + +```rust +module_kind: Some("LIBRARY".into()), +exports: vec!["acme:pricing/discount".into()], +isolation_mode: Some("in-process".into()), +``` + +and the consumer with: + +```rust +uses: vec!["pricing-lib".into()], +``` + +Rules: + +- **Deploy the library first.** A consumer whose `uses` names a module that is not an active + LIBRARY is refused: `module uses library 'L', which is not an active library module (deploy it first)`. +- **Libraries run in-process.** A LIBRARY is published from the host process. On `worker` and + `oci` hosts, whose default mode is not `in-process`, pin `isolation_mode: "in-process"` or the + deploy fails with `LIBRARY modules run on in-process isolation (design 01 §6); module '...' is routed to worker (pin isolation_mode: in-process)`. + Consumers may run in any mode; a worker or container consumer gets the library's component + read-only and links it before any shared libs. +- **No routes.** A LIBRARY with routes is refused (`a LIBRARY module serves no routes`). +- **No ambiguity.** Two libraries used together may not export the same interface, and `uses` + must not form a cycle. +- `module_kind` is `NORMAL` (the default) or `LIBRARY`; anything else is refused. + +Status fields: the library reports `kind: "LIBRARY"`, its `exports`, and `libraryGeneration` +(its revision). A consumer reports `uses` and `boundLibraryGenerations`. From +[`shared-module-worker-mcp.json`](../../examples/scenarios/shared-module-worker-mcp.json), a +consumer on a worker host: + +```json +{ "id": "shop", "mode": "worker", "uses": ["pricing-lib"], "boundLibraryGenerations": [1] } +``` + +Updating the library publishes a new generation and redeploys its active consumers as new +revisions; a consumer that fails keeps its previous revision and becomes sticky. At startup the +host brings libraries up before their consumers. Uninstalling a library does not check for +consumers, as in Protean. + +[Design 01](../design/01-runtime-architecture.md) section 6.1 (in Korean) has the full LIBRARY +contract and how it differs from Protean. + +Next: [host services](07-host-services.md). diff --git a/docs/guide/07-host-services.md b/docs/guide/07-host-services.md new file mode 100644 index 0000000..c663ff1 --- /dev/null +++ b/docs/guide/07-host-services.md @@ -0,0 +1,240 @@ +# 7. Host services (the bridge) + +A module can call services that the application embedding Protrus provides, through the +`protrus:module/bridge` import: + +```wit +interface bridge { + record failure { code: string, message: string } + call: func(service: string, version: string, input: list) -> result, failure>; +} +``` + +This is Protrus's counterpart of Protean's shared beans. It is a **library API for +embedders**: the stock `protrus-host` binary registers no services, so on it every bridge call +answers `not_found`. To offer services, build your own host around the `protrus-host` crate, as +below. + +## Three parties must agree + +1. **The embedder registers** a handler under an exact `service` and `version` on the + deployment's `bridge_services` (`protrus_host::bridge::HostBridgeServices`). Each topology's + deployment has the field: `AsyncWasmDeployment`, `WorkerProcessDeployment`, + `DockerOciDeployment`. A later registration under the same name and version replaces the + earlier one. Names may not contain `@`. +2. **The module declares** what it calls in its signed manifest: + `bridged_services: ["greeter@1"]`. Each entry must be `service@version`, or the deploy fails + (`bridged services must be named service@version`). +3. **The module calls** `bridge.call("greeter", "1", input)`. + +A call to a service the module did not declare, or one nobody registered, fails with code +`not_found`. Services are looked up at call time, so you can register them before or after +modules deploy. + +A module that declares services reports them in its status: +`"needsSharedBeans": true, "bridgedInterfaces": ["greeter@1"]`. + +## Where a bridged module may run + +| Mode | Bridge | +| --- | --- | +| `in-process` | Called directly in the host process | +| `worker` | Only while `worker.rpc-bridge` is on (RESTART_CONDITIONAL, default `false`). The host serves each such module on a private, owner-only Unix socket in `control_socket_root`; the worker connects once when it loads the module | +| `container` | Never | + +A module that declares `bridged_services` and resolves to a mode that cannot serve them is +refused before anything is prepared. On a `worker` host with `worker.rpc-bridge` off: + +```text +{"type":"urn:protean:error:state-conflict","title":"State conflict","status":409,"detail":"isolation mode 'worker' does not support module 'ip-echo' (e.g. shared-bean dependency). Deployment rejected.","code":"STATE_CONFLICT",...} +``` + +Pin such a module with `isolation_mode: "in-process"`, or turn `worker.rpc-bridge` on. + +## Limits and failures + +Per request, a module may make 16 bridge calls, with at most 64 KiB of input and 64 KiB of +output each. The failure codes the module can see: + +| `code` | Cause | +| --- | --- | +| `not_found` | Not declared by the module, or not registered | +| `quota_exceeded` | More than 16 calls in one request | +| `input_too_large`, `output_too_large` | Over 64 KiB | +| `cancelled` | The request was cancelled | +| anything else | Returned by your handler's `BridgeFailure { code, message }` | + +Input and output are opaque bytes: you choose the encoding (JSON, protobuf, ...). + +## Example: embed async-wasm with a service + +The program below composes the `async-wasm` topology itself, registers `greeter@1`, deploys one +signed envelope at startup, and serves module traffic with a read-only `/platform`. It was +compiled against this repository and run as shown; the only line you change is the repository +path in `Cargo.toml`. + +`embed-bridge/Cargo.toml`: + +```toml +[package] +name = "embed-bridge" +version = "0.1.0" +edition = "2024" +publish = false + +[dependencies] +protrus-host = { path = "/path/to/protrus/crates/protrus-host" } +protrus-web = { path = "/path/to/protrus/crates/protrus-web" } +protrus-runtime-wasm = { path = "/path/to/protrus/crates/protrus-runtime-wasm" } +axum = "0.8.9" +serde_json = "1" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread"] } + +[workspace] +``` + +`embed-bridge/src/main.rs`: + +```rust +//! Embeds the async-wasm topology, registers a host service that modules reach through +//! `protrus:module/bridge`, deploys one signed envelope at startup and serves the data plane +//! with a read-only `/platform`. +//! +//! usage: embed-bridge +use protrus_host::{AsyncWasmBootstrapConfig, AsyncWasmDeployment}; +use protrus_runtime_wasm::{ + async_component_host::{AsyncBridgeService, BridgeFuture}, + component_host::BridgeFailure, +}; +use protrus_web::{AuthenticatedPrincipal, ControlAction, ControlAuthorizer, DeployInput}; +use std::{env, fs, sync::Arc}; + +/// `greeter@1`: answers "hello, ". Input and output are opaque bytes (64 KiB each by +/// default); the format between module and service is yours to define. +struct Greeter; + +impl AsyncBridgeService for Greeter { + fn call(&self, input: &[u8]) -> BridgeFuture<'_> { + let input = input.to_vec(); + Box::pin(async move { + if input.is_empty() { + return Err(BridgeFailure { code: "bad_input".into(), message: "empty name".into() }); + } + let mut output = b"hello, ".to_vec(); + output.extend(input); + Ok(output) + }) + } +} + +/// Reads are open; every change over `/platform` is refused. +struct ReadOnly; + +impl ControlAuthorizer for ReadOnly { + fn authorize( + &self, + _principal: Option<&AuthenticatedPrincipal>, + action: ControlAction, + _module_id: Option<&str>, + ) -> Result<(), String> { + if action == ControlAction::Read { Ok(()) } else { Err("read-only host".into()) } + } +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + let args: Vec = env::args().skip(1).collect(); + let [bootstrap, envelope, listen] = args.as_slice() else { + return Err("usage: embed-bridge ".into()); + }; + let config: AsyncWasmBootstrapConfig = serde_json::from_slice(&fs::read(bootstrap)?)?; + let deployment = AsyncWasmDeployment::from_config(config)?; + + // Register before deploying: a module that declares `greeter@1` in `bridged_services` + // reaches it; a module that does not declare it gets `not_found`. + deployment + .bridge_services + .register("greeter", "1", Arc::new(Greeter))?; + + let input: DeployInput = serde_json::from_slice(&fs::read(envelope)?)?; + let outcome = deployment + .deploy(input.try_into()?) + .map_err(|error| error.to_string())?; + eprintln!("deployed {} revision {}", outcome.record.module_id, outcome.record.revision.0); + + let application = deployment.router_with_authorizer(false, Arc::new(ReadOnly)); + let listener = tokio::net::TcpListener::bind(listen.as_str()).await?; + axum::serve(listener, application).await?; + Ok(()) +} +``` + +`AsyncWasmBootstrapConfig` is the same JSON as the `async-wasm` bootstrap on +[page 1](01-getting-started.md#start-an-async-wasm-host) (`execution_mode`, `identity` and +`config` are not used by this program). + +A module that calls the service, built like `hello-module` on +[page 2](02-building-and-signing-modules.md#build-a-component): + +```rust +wit_bindgen::generate!({ path: "wit", world: "module" }); + +use protrus::module::bridge; + +struct Caller; + +impl Guest for Caller { + fn handle(request: Request) -> Result { + let (status, body) = match bridge::call("greeter", "1", &request.body) { + Ok(output) => (200, output), + Err(failure) => (502, format!("{}: {}", failure.code, failure.message).into_bytes()), + }; + Ok(Response { status, headers: vec![], body }) + } +} + +export!(Caller); +``` + +Sign it as `greet-caller` with `POST /call` and, in the signing program's manifest, +`bridged_services: vec!["greeter@1".into()]`. Then: + +```sh +embed-bridge/target/release/embed-bridge embed.json greet-caller-1.json 127.0.0.1:60372 +``` + +```text +deployed greet-caller revision 1 +``` + +```sh +curl -s -X POST http://127.0.0.1:60372/call -d 'bridge' +curl -s -X POST http://127.0.0.1:60372/call +curl -s http://127.0.0.1:60372/platform/modules | jq -c '.[0] | {needsSharedBeans, bridgedInterfaces}' +curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:60372/platform/modules \ + -H 'content-type: application/json' --data-binary @hello-1.json +``` + +```text +hello, bridge +bad_input: empty name +{"needsSharedBeans":true,"bridgedInterfaces":["greeter@1"]} +403 +``` + +Notes for embedders: + +- The handler receives only `input`. To dispatch on the names yourself, implement + `call_named(service, version, input)` too; the default forwards to `call`. +- This example skips what the `protrus-host` binary adds: the config registry, MCP, traces, + shared libs and the bearer-token identity. Read + [`crates/protrus-host/src/bin/protrus-host.rs`](../../crates/protrus-host/src/bin/protrus-host.rs) + for the full composition of each topology, and add + `deployment.bridge_services.register(...)` there. +- `router()` without an authorizer allows every change; always pass a `ControlAuthorizer` on + anything reachable from outside. + +[Design 07](../design/07-wasm-abi-and-capabilities.md) section 6 (in Korean) is the bridge ABI +and the registration contract. + +Next: [debugging and observability](08-debugging-and-observability.md). diff --git a/docs/guide/08-debugging-and-observability.md b/docs/guide/08-debugging-and-observability.md new file mode 100644 index 0000000..a0d350f --- /dev/null +++ b/docs/guide/08-debugging-and-observability.md @@ -0,0 +1,139 @@ +# 8. Debugging and observability + +## Host log events + +The host writes structured JSON events, one per line, to **stderr** (stdout is reserved for MCP +stdio). Collect stderr. Events you will see: + +| `event` | When | +| --- | --- | +| `protrus_host_listening` | The listener is bound; carries `address` | +| `protrus_reconcile`, `protrus_reconcile_skipped` | Startup redeploy of stored modules: `recovered`/`total`, and each module that could not come back with its `error` | +| `protrus_config_changed` | A runtime config change: `actor` (`rest` or `mcp:`) and `keys` | +| `protrus_gate_skipped` | A deploy skipped the unit-test gate because `gate.tests-enabled` is off | +| `protrus_worker_crash`, `protrus_worker_shutdown` | Worker exits and host shutdown (`worker` topology) | +| `protrus_pair_watch`, `protrus_pair_watch_registry_error`, `protrus_oci_shutdown` | Container pair supervision (`oci` topology) | +| `protrus_shared_lib_rebind`, `protrus_shared_lib_rebind_error`, `protrus_shared_lib_skipped` | Shared-lib changes propagating to modules | +| `protrus_scope_admin` | DB scope operations | +| `protrus_wasm_scope_ignored`, `protrus_in_process_scope_ignored` | A module's `scope` has no effect where it runs | + +After a restart, look for `protrus_reconcile_skipped`. A module that fails to come back is left +`degraded` with the reason in `stickyReason`, and the host still starts: + +```text +{"event":"protrus_reconcile_skipped","error":"gate signature rejected deployment: untrusted signer release-2"} +{"event":"protrus_reconcile","recovered":2,"total":3} +``` + +## Request traces + +Every request the host serves, `/platform` included, is recorded in an in-memory ring. Requests +served by a module carry its id; the rest are attributed to `(platform)`. The ring is not +persisted. + +```sh +curl -s 'http://127.0.0.1:8088/platform/traces?moduleId=hello&limit=1' | jq . +``` + +```json +[ + { + "seq": 2, + "epochMillis": 1795509889139, + "method": "POST", + "uri": "/hello", + "pattern": null, + "moduleId": "hello", + "status": 200, + "latencyMs": 8, + "error": null, + "traceId": "e56c105b-9dbb-48bf-8d31-1aeb125ac222" + } +] +``` + +`traceId` is the request's `X-Request-Id`, so a client-side id leads straight to the trace. + +| Route | Query parameters | +| --- | --- | +| `GET /platform/traces` | `limit` (default 50), `moduleId`, `errorsOnly`, `status`, `minLatencyMs`, `since` (epoch ms), `beforeSeq` (page into the past) | +| `GET /platform/traces/metrics` | `moduleId`. Per-module count, error count and rate, latency percentiles, max, last seen. Empty unless `trace.metrics.enabled` | +| `GET /platform/traces/stream` | Server-sent events for a live console: `ready`, then `trace`, `metrics`, `modules` and `summary` events | + +MCP: `protean.query_traces` (same filters, result `{enabled, traces}`), +`protean.module_metrics` (`moduleId`, result `{enabled, metrics}`), and the resource +`protean://traces` (newest 50). + +Trace keys, all LIVE: `trace.enabled` (`true`), `trace.capacity` (`200`; lowering it trims at +once), `trace.summary-window-ms` (`60000`), `trace.metrics.enabled` (`false`). FUTURE, for +modules tracked afterward: `trace.metrics.latency-buckets` (`20`), `trace.metrics.max-modules` +(`512`). + +## Guest traps + +When a module's code traps (a Rust panic, an out-of-bounds access, running out of fuel), the +request fails with `500` and the host records the trap with its WebAssembly backtrace: module id, +revision, time, the trap message, and frames (`module`, `function`, `offset`, and `file`/`line` +when the component was built with DWARF debug info). The last 256 traps are kept. Traps from +workers and containers are reported back to the host with the failed response, so all three +topologies record them. + +For readable frames, build the component with debug info, for example +`CARGO_PROFILE_RELEASE_DEBUG=true cargo build --release --target wasm32-unknown-unknown`. +Only the file name is kept, not the build path. + +## MCP debug tools + +The `debug.*` tools are always listed but refuse with `DEBUG_DISABLED` until the host starts +with `"config": {"mcp.debug.enabled": true}` (restart): + +```text +{"isError":true,"text":"[DEBUG_DISABLED] debug surface disabled (protean.mcp.debug.enabled=false)"} +``` + +Once enabled they need the host identity, like any change. + +| Tool | Arguments | Result | +| --- | --- | --- | +| `debug.traps` | `id` (optional), `limit` (default 20) | Recent traps, newest first | +| `debug.frames` | `id`, or `sessionId` | The module's last trap backtrace, or the stopped request's frames | +| `debug.await_stop` | `id` or `sessionId`, `timeoutMs` (default 10000) | Waits for the module's next trap, or the session's next stop | +| `debug.launch` | `id` | Opens an interactive session on a deployed module; returns `sessionId` | +| `debug.set_breakpoint` | `sessionId` and one of `file`+`line` (needs DWARF), `function`, or `offset` (+ `module`) | Applies to requests that start afterward | +| `debug.continue` | `sessionId` | Resumes the stopped request | +| `debug.step` | `sessionId`, `depth` (`over`, `into`, `out`) | Executes one instruction and stops | +| `debug.get_variables` | `sessionId`, `frame` (default 0) | WebAssembly locals (`local`); they have no names | +| `debug.list_sessions` | | Open sessions | +| `debug.terminate` | `sessionId` | Ends the session and resumes everything it stopped | + +A typical session: + +1. `debug.launch {"id": "hello"}` returns a `sessionId`. +2. `debug.set_breakpoint {"sessionId": ..., "function": "..."}`. +3. Send a request to the module. It stops at the breakpoint and waits. +4. `debug.await_stop {"sessionId": ...}` reports where it stopped; `debug.frames` and + `debug.get_variables` inspect it; `debug.step` or `debug.continue` moves on. +5. `debug.terminate` ends the session. + +Sessions run where the module runs: in the host process for `in-process` modules, inside the +worker or container otherwise. A request left stopped resumes by itself after +`mcp.debug.session-idle-timeout` (restart, default `PT30M`, an ISO 8601 duration). Evaluating +expressions and redefining code are not available for WebAssembly. + +The scenarios [`worker-mcp.json`](../../examples/scenarios/worker-mcp.json) and +[`container-mcp.json`](../../examples/scenarios/container-mcp.json) include complete debug +sessions. [Design 17](../design/17-mcp-session-and-extension-contract.md) section 5 (in Korean) +is the debug contract. + +## Checklist when a module does not answer + +| Symptom | Check | +| --- | --- | +| `404` on the module's path | `GET /platform/modules/{id}/routes`; routes match exact method and path | +| `404` right after deploy with approval on | `desiredState` is `PENDING_APPROVAL`; approve it | +| `500` from the module | `debug.traps` (with `mcp.debug.enabled`), or `/platform/traces?errorsOnly=true` | +| Module `degraded` after restart | `stickyReason`, and `protrus_reconcile_skipped` on stderr | +| Deploy refused | The problem's `code` and `gate`: `GATE_FAILED` (signature, tests, policy, verification) or `STATE_CONFLICT` (revision, mode, library) | +| Every change `403` | Missing `identity` in the bootstrap, or wrong `Authorization: Bearer` token | + +Next: [databases](09-databases.md). diff --git a/docs/guide/09-databases.md b/docs/guide/09-databases.md new file mode 100644 index 0000000..cee5250 --- /dev/null +++ b/docs/guide/09-databases.md @@ -0,0 +1,175 @@ +# 9. Databases + +Databases appear in two unrelated places: + +- **Module data:** a module reaches a database through the `protrus:module/db` import, inside a + named **scope**. How scopes are backed depends on the topology. +- **The module store:** where the host keeps its module records. A file store by default, or + SQLite, PostgreSQL or MySQL. + +## Module data access + +### The guest API + +```wit +interface db { + record failure { code: string, message: string } + resource transaction { + query: func(statement: string, parameters: list) -> result, failure>; + commit: func() -> result<_, failure>; + rollback: func() -> result<_, failure>; + } + begin: func(scope: string) -> result; +} +``` + +- `begin(scope)` opens a transaction in a scope the module was granted. A transaction lives at + most as long as the request; one not committed is rolled back. +- `parameters` is a **compact JSON array** (exactly as `serde_json::to_vec` writes it, no extra + whitespace): `null`, booleans, + 64-bit integers, finite floats, strings, and `{"$bytes": ""}` for binary. For + example `[42,"alice",{"$bytes":"aGVsbG8="}]`. Anything else fails with `invalid_parameters`. +- `query` returns the **first column of the first row** as bytes. A statement must return a + row: use `RETURNING` for writes, and build structured results in SQL (for example a JSON + document) when you need more than one value. +- Driver errors are reported as `driver_error` without details, so SQL text and connection data + do not leak to the module. An unknown or ungranted scope is `scope_forbidden`. + +The module must declare the `db` capability in its signed manifest, and the host must allow it +(`"allowed_capabilities": ["db"]` while `gate.review-enabled` is on). + +### async-wasm: host-owned SQLite scopes + +The `async-wasm` topology maps scope names to SQLite databases in its bootstrap, and grants +scopes per module id: + +```json +"allowed_capabilities": ["db"], +"sqlite_scopes": { + "orders": "sqlite:///srv/protrus/db/orders.sqlite?mode=rwc" +}, +"module_db_scopes": { + "orders-api": ["orders"] +} +``` + +| Field | Rule | +| --- | --- | +| `sqlite_scopes` | Scope name to SQLite URL. The database path must be absolute | +| `module_db_scopes` | Exact module id to the scopes its revisions may open. Every scope must exist in `sqlite_scopes` | + +A module that declares `db` but has no grant fails to deploy +(`artifact requests database capability but the module has no host scope grant`). The manifest's +`scope` field is ignored on this topology (a `protrus_wasm_scope_ignored` event is logged); access +comes only from these grants. The schema is yours to create. + +### worker and oci: auto-provisioned scopes + +On `worker` and `oci` hosts the host can create a PostgreSQL schema and a restricted login per +scope, and hand each worker only its own scope's credentials. PostgreSQL is the only supported +database for provisioning. + +Enable it with a `database_provisioning` section: + +```json +"allowed_capabilities": ["db"], +"database_provisioning": { + "database_url": "postgres://db.internal:5432/postgres", + "admin_user": "provisioner", + "admin_password_file": "/etc/protrus/db-admin-password", + "secret_directory": "/var/lib/protrus/db-secrets", + "container_db_host": "host.docker.internal" +}, +"config": { + "worker.db.scopes": ["orders", "billing"] +} +``` + +| Field | Meaning | +| --- | --- | +| `database_url` | Admin connection URL, without credentials in it | +| `admin_user`, `admin_password_file` | The privileged identity; the password file path must be absolute | +| `secret_directory` | Absolute, private directory where per-scope credentials are written | +| `container_db_host` | `oci` only: replaces `localhost`/`127.0.0.1` in the URL given to containers (default `host.docker.internal`) | + +Related keys: + +| Key | Tier | Meaning | +| --- | --- | --- | +| `worker.db.auto-provision` | RESTART_CONDITIONAL | Unset: on when the section exists. `false` turns it off; `true` without the section fails startup | +| `worker.db.scopes` | LIVE | Seed scopes. Empty means one scope, `default` | +| `worker.db.admin-url`, `admin-username`, `admin-password` | FUTURE | Override the section's admin settings; read at each provision, detach and destroy, so you can rotate them live. A key and a field that are both set must agree | +| `worker.db.allow-destroy` | LIVE (`false`) | Required for `destroy` | + +A scoped module: + +- declares `scope` in its signed manifest **and** in the deploy record (they must be equal), and + the `db` capability; +- deploys only into a known scope in state `ACTIVE`; +- runs as `worker` or `container`; an `in-process` module with a scope is refused while the host + auto-provisions; +- shares a worker only with modules of the same scope. + +The worker receives the path of an owner-only credential file and the scope name; passwords never +appear in arguments or environment variables. In a container the file is mounted read-only. + +### Scope administration + +These routes exist only while the host auto-provisions. The MCP tools `protean.scope_*` are +always listed and answer `STATE_CONFLICT` otherwise. + +| Route | MCP tool | Does | +| --- | --- | --- | +| `GET /platform/scopes` | `protean.scope_list` | All scopes: `{name, state, dialectId, modules}` | +| `GET /platform/scopes/{name}` | `protean.scope_get` | One scope; empty `404` if unknown | +| `POST /platform/scopes` with `{"name": "..."}` | `protean.scope_create` | Add a scope; `201` with `Location` | +| `POST /platform/scopes/{name}/close` | `protean.scope_close` | Refuse new deploys; running modules keep serving | +| `POST /platform/scopes/{name}/open` | `protean.scope_open` | Back to `ACTIVE` | +| `POST /platform/scopes/{name}/detach` | `protean.scope_detach` | Uninstall the scope's modules and disable its login; data kept | +| `POST /platform/scopes/{name}/destroy?confirm={name}` | `protean.scope_destroy` | Drop the schema and login, irreversibly. Needs `worker.db.allow-destroy: true` and `confirm` equal to the name | + +States are `ACTIVE`, `CLOSED` and `DETACHED`. Scopes created through the API are recorded under +`/scopes/`. A host restarted while a scope is `CLOSED` still starts; that scope's +modules stay `degraded` until it is reopened and the host restarts. + +[Design 29](../design/29-db-scope-provisioning-contract.md) has the provisioning contract and +[`docs/operations/async-sqlx-scope-pools.md`](../operations/async-sqlx-scope-pools.md) shows how an +embedding host registers its own PostgreSQL or MySQL pools per scope. + +## Module store backends + +By default the host keeps module records as files under `state_root` (or `module-store.dir`). +To keep them in a database instead, set `module_store_url` in the bootstrap **and** +`module-store.backend: "jdbc"` in `config`; one without the other stops startup. + +```json +"module_store_url": "sqlite:///tmp/protrus-demo/modules.db?mode=rwc", +"config": { + "mcp.enabled": true, + "module-store.backend": "jdbc" +} +``` + +```text +{"key":"module-store.backend","value":"jdbc","tier":"RESTART_CONDITIONAL","liveApplicable":false} +{"key":"module-store.dir","value":"","tier":"RESTART_ARTIFACT","liveApplicable":false} +{"key":"module-store.dialect","value":"sqlite","tier":"RESTART_ARTIFACT","liveApplicable":false} +``` + +| Database | URL form | Notes | +| --- | --- | --- | +| SQLite | `sqlite:///abs/path/modules.db?mode=rwc` | `mode=rwc` creates the file | +| PostgreSQL | `postgres://user:password@host:5432/db` | | +| MySQL, MariaDB | `mysql://user:password@host:3306/db` | Without TLS the account must use `mysql_native_password`: Protrus disables the RSA password exchange that other MySQL authentication plugins need over plain connections | + +The dialect is detected from the URL scheme; `module-store.dialect` (`sqlite`, `postgresql`, +`mysql`) overrides it. At startup the host creates the `module` and `module_version` tables if +they are missing and runs a self-check that writes and rolls back two 128 KiB rows; a database +that cannot store them fails startup. Artifacts, shared libs and scope records stay on the file +system under `state_root` either way. + +The URL is in the bootstrap file, so protect that file like any other credential. + +[Design 03](../design/03-artifact-and-store.md) section 5 (in Korean) is the store contract. + +Back to the [guide index](README.md). diff --git a/docs/guide/README.md b/docs/guide/README.md new file mode 100644 index 0000000..f62fc4a --- /dev/null +++ b/docs/guide/README.md @@ -0,0 +1,37 @@ +# Protrus user guide + +Protrus is a Rust port of the Protean dynamic module platform. A Protrus host runs signed +WebAssembly component modules and lets you install, update, roll back and remove them at runtime +through a REST control plane under `/platform` and through MCP. + +This guide is for operators and integrators using Protrus for the first time. It is written +against the code in this repository; the commands and outputs shown were run on it. + +| Page | Covers | +| --- | --- | +| [1. Getting started](01-getting-started.md) | Build, the three host topologies, the bootstrap file, starting and checking a host | +| [2. Building and signing a module](02-building-and-signing-modules.md) | The component world, building a component, the signed manifest, keys and signing | +| [3. Deploying and operating](03-deploying-and-operating.md) | Install, update, rollback, approval, uninstall, gates, the REST and MCP reference | +| [4. Configuration](04-configuration.md) | The runtime config registry, tiers, `/platform/config`, key groups | +| [5. Isolation and workers](05-isolation-and-workers.md) | Isolation modes per host, worker packing, auto-restart, OCI container requirements | +| [6. Sharing code](06-sharing-code.md) | Shared libs and LIBRARY modules | +| [7. Host services](07-host-services.md) | The bridge: registering services in an embedding host | +| [8. Debugging and observability](08-debugging-and-observability.md) | Log events, request traces, guest traps, MCP debug sessions | +| [9. Databases](09-databases.md) | Database scopes and provisioning, module store backends | + +## The shortest path + +1. Build: `cargo build --release -p protrus-host` ([page 1](01-getting-started.md#build)). +2. Start an `async-wasm` host with an `identity` token ([page 1](01-getting-started.md#start-an-async-wasm-host)). +3. Build a component and sign it with an Ed25519 key ([page 2](02-building-and-signing-modules.md)). +4. Add the public key to `trusted_signers_hex` and restart ([page 2](02-building-and-signing-modules.md#trust-the-key-on-the-host)). +5. `POST /platform/modules` with the signed envelope, then call the module's route ([page 3](03-deploying-and-operating.md#install)). + +## Where else to look + +- [`docs/operations/protrus-host-runbook.md`](../operations/protrus-host-runbook.md): operating + the host, especially the `oci` topology. +- [`docs/design/`](../design/README.md): the design documents, including every intentional + difference from Protean. They are written in Korean. +- [`examples/scenarios/`](../../examples/scenarios): end-to-end MCP scenarios for each topology, + run by `cargo test -p protrus-host --test mcp_scenarios`. diff --git a/docs/operations/async-sqlx-scope-pools.md b/docs/operations/async-sqlx-scope-pools.md index 203d33c..4145ee5 100644 --- a/docs/operations/async-sqlx-scope-pools.md +++ b/docs/operations/async-sqlx-scope-pools.md @@ -1,10 +1,10 @@ # Async SQLx scope pool operations -This guide applies to embedding hosts that already compose the async Wasm data plane and inject -`AsyncDatabaseCapability`. The current `protrus-host` binary serves OCI workers through -`router_with_worker_dispatch`; it does not activate async Wasm components or consume SQLx pools. -Adding pool values to its bootstrap config alone would have no effect. Production `protrus-host` -support depends on a separate decision and implementation for async Wasm deployment composition. +This guide covers the SQLx scope pools behind the async Wasm data plane's `AsyncDatabaseCapability`. +The `protrus-host` binary composes it for `execution_mode: "async-wasm"`, where the bootstrap's +`sqlite_scopes` and `module_db_scopes` grant SQLite scopes to modules; embedding hosts can inject +their own pools the same way. Worker and container modules reach scoped PostgreSQL/MySQL databases +through provisioning instead (see `docs/guide/09-databases.md`). `protrus-store-sqlx` uses host-owned pools mapped to exact `scope` names. It does not create or delete databases, schemas, users, or grants. The host must provision a dedicated database identity diff --git a/docs/operations/protrus-host-runbook.md b/docs/operations/protrus-host-runbook.md index c89088a..0a1383c 100644 --- a/docs/operations/protrus-host-runbook.md +++ b/docs/operations/protrus-host-runbook.md @@ -152,14 +152,18 @@ protected resource metadata at `/.well-known/oauth-protected-resource`, with the live `mcp.authorization.authorization-servers`, `scopes-supported`, and `bearer-methods-supported` (default `["header"]`) lists. -The debug tools `debug.frames`, `debug.await_stop`, and `debug.traps` are -always listed and refuse with `DEBUG_DISABLED` unless `mcp.debug.enabled: true` -is in the bootstrap `config` map (it needs a restart). They read the guest traps -the `async-wasm` execution mode records: the last trap of a module (`id`) with -its Wasm frames, the next one (`timeoutMs`, default 10000), or the most recent -across modules. Frames carry source file names and lines when the module was -built with DWARF. Breakpoints, stepping, and evaluation are not available on -Wasm; in `worker` and `oci` the tools stay disabled (design 17 §5.1). +The debug tools (`debug.list_sessions`, `debug.launch`, `debug.set_breakpoint`, +`debug.continue`, `debug.step`, `debug.await_stop`, `debug.frames`, +`debug.get_variables`, `debug.terminate`, `debug.traps`) are always listed and +refuse with `DEBUG_DISABLED` unless `mcp.debug.enabled: true` is in the bootstrap +`config` map (it needs a restart). Guest traps are recorded on every execution +mode (workers and containers report them to the host proxy): the last trap of a +module (`id`) with its Wasm frames, the next one (`timeoutMs`, default 10000), or +the most recent across modules. Frames carry source file names and lines when the +module was built with DWARF. Interactive sessions (breakpoints, stepping, frames, +variables) open where the module runs: in the host for in-process modules, in the +module's worker or container otherwise. Evaluation and redefinition have no Wasm +counterpart (design 17 §5). The shared-lib tools (`protean.deploy_shared_lib`, `list_shared_libs`, `get_shared_lib`, `remove_shared_lib`) and `/platform/shared-libs` manage the