From bd04b4e64b08203933b9012dd6550593cdcc1475 Mon Sep 17 00:00:00 2001 From: Johnny Greco Date: Wed, 18 Nov 2026 18:10:00 +0000 Subject: [PATCH 1/2] Update omm for the OpenShell v0.1.9 middleware contract omm create failed for every OpenShell release since v0.1.0 because the supervisor middleware proto imports extension.proto, which omm did not download. The starter templates also still implemented the v0.0.86 contract. Generator: - Download the OpenShell protos that the middleware proto imports, record them in the manifest, and compile them into the Python bindings. - Publish each generator-owned proto file on update by exchange, add, or removal with rollback, and refuse to overwrite an unrecorded file that differs from the imported one. - Require the HTTP hooks contract (OpenShell v0.1.9 or newer) in omm create and report older releases before generating anything. Templates: - Negotiate extension protocol metadata in Describe. - Implement HttpHooks.EvaluateHttpRequestHook with preflight and whole-body extension points in the Python and Rust starters. Verification: - Add scripts/verify-openshell-release.sh, which generates both starters and sends sandbox traffic through them behind a real OpenShell gateway. Signed-off-by: Johnny Greco --- .../openshell-middleware-manager/AGENTS.md | 4 + .../openshell-middleware-manager/README.md | 80 ++- .../scripts/verify-openshell-release.sh | 514 ++++++++++++++++ .../src/openshell_middleware_manager/cli.py | 4 +- .../openshell_middleware_manager/generator.py | 367 +++++++++--- .../templates/python/README.md | 60 +- .../templates/python/src/package/server.py | 107 +++- .../templates/python/tests/test_server.py | 186 ++++-- .../templates/rust/README.md | 70 ++- .../templates/rust/build.rs | 2 +- .../templates/rust/src/lib.rs | 430 ++++++++++++-- .../templates/rust/src/main.rs | 1 + .../tests/test_generator.py | 559 +++++++++++++++++- 13 files changed, 2132 insertions(+), 252 deletions(-) create mode 100755 projects/tools/openshell-middleware-manager/scripts/verify-openshell-release.sh diff --git a/projects/tools/openshell-middleware-manager/AGENTS.md b/projects/tools/openshell-middleware-manager/AGENTS.md index 46227d25..0a3f4d83 100644 --- a/projects/tools/openshell-middleware-manager/AGENTS.md +++ b/projects/tools/openshell-middleware-manager/AGENTS.md @@ -34,6 +34,10 @@ Read `README.md` and `pyproject.toml` before changing this project. - Do not format, type-check, or edit generated Python protobuf and gRPC files. - After changing a template, generate a project in a temporary directory and run its documented checks when practical. +- After changing a template or how the OpenShell contract is downloaded, run + `scripts/verify-openshell-release.sh` when Docker is available. It runs a + private gateway from a temporary directory and leaves any installed OpenShell + untouched. ## Tests diff --git a/projects/tools/openshell-middleware-manager/README.md b/projects/tools/openshell-middleware-manager/README.md index 1943dd21..6f5c9af5 100644 --- a/projects/tools/openshell-middleware-manager/README.md +++ b/projects/tools/openshell-middleware-manager/README.md @@ -2,7 +2,7 @@ `openshell-middleware-manager` creates and updates Python or Rust services for OpenShell supervisor middleware. Each new project starts as a working pass-through gRPC -service. It includes the protocol file for one OpenShell release, tests, +service. It includes the protocol files for one OpenShell release, tests, dependency locks, and instructions for registering the service. The CLI does not install or change OpenShell. @@ -58,7 +58,7 @@ Generate and run a Python starter with the installed command: ```sh omm create audit-headers \ --language python \ - --openshell-version v0.0.86 \ + --openshell-version v0.1.9 \ --output /tmp/audit-headers cd /tmp/audit-headers @@ -71,7 +71,7 @@ Or generate and run a Rust starter: ```sh omm create audit-headers \ --language rust \ - --openshell-version v0.0.86 \ + --openshell-version v0.1.9 \ --output /tmp/audit-headers-rust cd /tmp/audit-headers-rust @@ -82,10 +82,11 @@ cargo run --locked -- 127.0.0.1:50051 The output path must not exist. Pin an OpenShell tag when you need repeatable builds. Use `--openshell-version latest` when you want the newest release. -The starter templates still use the older `max_body_bytes` binding field, so -`omm create` does not yet support v0.0.116. Validation stops without publishing -that starter. `omm update` can refresh an existing service already compatible -with the newer contract. +New projects implement OpenShell's HTTP hooks, so `omm create` needs OpenShell +v0.1.9 or newer. For an older release, it reports an error without creating a +project. Version 0.0.1 of this package creates starters for the earlier v0.0.86 +contract. `omm update` can refresh an existing project to any middleware-capable +release that the project's own code is compatible with. Run `omm --help` for all options and `omm --version` for the installed OMM version. By default, `omm` derives the Python package name from the project @@ -103,13 +104,14 @@ To choose a release or update a project in another directory: ```sh omm update /path/to/audit-headers \ - --openshell-version v0.0.90 + --openshell-version v0.1.9 ``` `omm update` reads `.openshell-middleware-manifest.json` to find the project language -and Python package. It downloads the selected `supervisor_middleware.proto`, -regenerates Python protobuf and gRPC bindings when needed, updates `uv.lock` or -`Cargo.lock`, and writes the version and protocol checksum to the manifest. +and Python package. It downloads the selected `supervisor_middleware.proto` and +the OpenShell protocol files it imports, regenerates Python protobuf and gRPC +bindings when needed, updates `uv.lock` or `Cargo.lock`, and writes the version +and protocol checksums to the manifest. The manifest must name `openshell-middleware-manager` as its generator. Python updates run `uv sync` and then `uv run pytest` by default. If a project @@ -117,7 +119,7 @@ needs additional build steps, supply its normal validation command: ```sh omm update /path/to/my-middleware \ - --openshell-version v0.0.116 --check-command 'make check' + --openshell-version v0.1.9 --check-command 'make check' ``` The command runs in the staged project with its isolated Python environment, @@ -130,18 +132,20 @@ in a separate environment from the project's runtime dependencies. Each project contains: -- a pass-through implementation of `Describe`, `ValidateConfig`, and - `EvaluateHttpRequest`; -- the exact `supervisor_middleware.proto` from the selected OpenShell release; +- a pass-through implementation of `Describe`, `ValidateConfig`, and the + `HttpHooks.EvaluateHttpRequestHook` request hook; +- the exact `supervisor_middleware.proto` from the selected OpenShell release, + with the OpenShell protocol files it imports; - generated Python gRPC bindings or Rust Tonic build configuration; - tests and lint/type-check configuration; - `uv.lock` or `Cargo.lock`; and -- `.openshell-middleware-manifest.json` with the release, source URL, and protocol - checksum. +- `.openshell-middleware-manifest.json` with the release, source URLs, and protocol + checksums. -Start by implementing policy behavior in the generated `validate_config` and -`evaluate_http_request` functions. The generated README explains how to run the -service and register it with OpenShell. +Start by implementing policy behavior in the generated `validate_config`, +`evaluate_http_request_preflight`, and `evaluate_http_request_body` functions. +The generated README explains how to run the service and register it with +OpenShell. ## How `omm` protects your files @@ -151,10 +155,12 @@ check passes. If the output path already exists, including as a symlink, the command stops without changing it. `omm update` works on a temporary copy of the project. It changes only the -protocol, generated bindings or Rust build files, lockfile, and manifest. It +protocol files, generated bindings or Rust build files, lockfile, and manifest. It runs the project checks before replacing those files. Your implementation files -stay unchanged. If a file replacement fails, `omm` restores the files it -already replaced. +stay unchanged, including your own files in `proto/`. If a release imports a +protocol file whose name a different file in `proto/` already uses, `omm update` +stops so that you can move your file. If a file replacement fails, `omm` +restores the files it already replaced. A lock prevents two `omm` processes from changing the same path at once. Normal failures remove the lock and temporary files. If an update and its @@ -192,5 +198,33 @@ uv build Unit tests use local protocol fixtures. They do not contact GitHub or run `uv` or Cargo inside generated projects. +## Check a real OpenShell release + +To check that generated services work with an OpenShell release, run: + +```sh +scripts/verify-openshell-release.sh --openshell-version v0.1.9 +``` + +The script needs Linux, Docker, `curl`, `openssl`, and `uv`. Rust starters also +need Cargo with `rustfmt` and `clippy`. It downloads that release's gateway and +CLI into a temporary directory, verifies their checksums, and runs them from +there. It does not install OpenShell or change an existing installation. The +script then: + +1. creates a Python and a Rust starter with `omm create`, refreshes each with + `omm update`, and runs each starter's documented checks; +2. starts the starters and a gateway that registers them, which succeeds only + when the gateway accepts each starter's `Describe` response; +3. creates a sandbox whose policy attaches each starter, sends a request + through it, and confirms that OpenShell logged the middleware invocation; + and +4. stops the starter and confirms that OpenShell blocks the same request. + +Use `--language python` or `--language rust` to check one language. Omit +`--openshell-version` to check the latest release. The script prints `ALL PASS` +and removes its temporary directory when every check passes. Run it with +`--help` for the remaining options. + See [RELEASING.md](https://github.com/NVIDIA/OpenShell-Research/blob/main/projects/tools/openshell-middleware-manager/RELEASING.md) for the local PyPI release process. diff --git a/projects/tools/openshell-middleware-manager/scripts/verify-openshell-release.sh b/projects/tools/openshell-middleware-manager/scripts/verify-openshell-release.sh new file mode 100755 index 00000000..c09e0b85 --- /dev/null +++ b/projects/tools/openshell-middleware-manager/scripts/verify-openshell-release.sh @@ -0,0 +1,514 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +set -euo pipefail + +PROJECT_DIRECTORY=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +RELEASE_URL="https://github.com/NVIDIA/OpenShell/releases" +SANDBOX_BASE_IMAGE="${OMM_VERIFY_SANDBOX_BASE_IMAGE:-nvcr.io/nvidia/base/ubuntu:24.04}" +UPSTREAM_HOST="host.openshell.internal" + +usage() { + echo "Usage: $0 [--openshell-version TAG|latest] [--language python|rust|all] [--work-dir DIR]" + echo + echo "Check that omm starters work with a real OpenShell release. The script downloads" + echo "that release's gateway and CLI into a work directory, generates a starter with" + echo "omm create, refreshes it with omm update, runs the starter's documented checks," + echo "and sends sandbox traffic through the running starter. It installs nothing." + echo + echo "Requires Linux, Docker, curl, openssl, and uv. Rust also needs cargo with" + echo "rustfmt and clippy. Set OMM_VERIFY_HOST to an IPv4 address that the gateway" + echo "and sandbox supervisors can both reach when detection picks the wrong one." + echo "The work directory is kept when a check fails or --work-dir names it." +} + +OPENSHELL_VERSION="latest" +REQUESTED_LANGUAGE="all" +WORK_DIRECTORY="" + +while [[ $# -gt 0 ]]; do + case "$1" in + --openshell-version | --language | --work-dir) + if [[ $# -lt 2 ]]; then + usage >&2 + exit 2 + fi + case "$1" in + --openshell-version) OPENSHELL_VERSION="$2" ;; + --language) REQUESTED_LANGUAGE="$2" ;; + --work-dir) WORK_DIRECTORY="$2" ;; + esac + shift + ;; + -h | --help) + usage + exit 0 + ;; + *) + usage >&2 + exit 2 + ;; + esac + shift +done + +case "$REQUESTED_LANGUAGE" in + all) LANGUAGES=(python rust) ;; + python | rust) LANGUAGES=("$REQUESTED_LANGUAGE") ;; + *) + echo "verify: --language must be 'python', 'rust', or 'all'" >&2 + exit 2 + ;; +esac + +fail() { + echo "FAIL $1" >&2 + exit 1 +} + +pass() { + echo "PASS $1" +} + +[[ "$(uname -s)" == "Linux" ]] || fail "this check supports Linux hosts only" +REQUIRED_COMMANDS=(curl docker openssl sha256sum tar uv) +if [[ " ${LANGUAGES[*]} " == *" rust "* ]]; then + REQUIRED_COMMANDS+=(cargo) +fi +for COMMAND in "${REQUIRED_COMMANDS[@]}"; do + command -v "$COMMAND" >/dev/null 2>&1 || fail "missing required command: $COMMAND" +done +docker info >/dev/null 2>&1 || fail "the Docker daemon is not reachable" +# Generated projects must use their own environments, not the caller's. +unset VIRTUAL_ENV + +case "$(uname -m)" in + x86_64) ARCHITECTURE="x86_64" ;; + aarch64 | arm64) ARCHITECTURE="aarch64" ;; + *) fail "unsupported architecture: $(uname -m)" ;; +esac + +if [[ "$OPENSHELL_VERSION" == "latest" ]]; then + LATEST_URL=$(curl -fsSL -o /dev/null -w '%{url_effective}' "$RELEASE_URL/latest") + OPENSHELL_VERSION="${LATEST_URL##*/}" +elif [[ "$OPENSHELL_VERSION" != v* ]]; then + OPENSHELL_VERSION="v$OPENSHELL_VERSION" +fi +[[ "$OPENSHELL_VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([+-][0-9A-Za-z._-]+)?$ ]] || + fail "invalid OpenShell version: $OPENSHELL_VERSION" + +RUN_ID="omm-verify-$$-$RANDOM" +KEEP_WORK_DIRECTORY=true +if [[ -z "$WORK_DIRECTORY" ]]; then + WORK_DIRECTORY=$(mktemp -d) + KEEP_WORK_DIRECTORY=false +fi +mkdir -p "$WORK_DIRECTORY" +WORK_DIRECTORY=$(cd "$WORK_DIRECTORY" && pwd) +[[ ! -e "$WORK_DIRECTORY/python" && ! -e "$WORK_DIRECTORY/rust" ]] || + fail "work directory already holds a generated starter: $WORK_DIRECTORY" +LOG_DIRECTORY="$WORK_DIRECTORY/logs" +BIN_DIRECTORY="$WORK_DIRECTORY/openshell" +SANDBOX_IMAGE="omm-verify/sandbox-curl:$RUN_ID" +mkdir -p "$LOG_DIRECTORY" "$BIN_DIRECTORY" "$WORK_DIRECTORY/xdg" + +declare -A MIDDLEWARE_PORT MIDDLEWARE_PID +GATEWAY_PID="" +UPSTREAM_PID="" +SANDBOXES=() +SANDBOX_IMAGE_BUILT=false + +# Keep the downloaded OpenShell away from the caller's OpenShell settings and state. +OPENSHELL_ENVIRONMENT=(env) +while IFS= read -r VARIABLE; do + OPENSHELL_ENVIRONMENT+=(-u "$VARIABLE") +done < <(compgen -e | grep '^OPENSHELL_' || true) +OPENSHELL_ENVIRONMENT+=( + "XDG_CONFIG_HOME=$WORK_DIRECTORY/xdg/config" "XDG_DATA_HOME=$WORK_DIRECTORY/xdg/data" + "XDG_STATE_HOME=$WORK_DIRECTORY/xdg/state" "XDG_CACHE_HOME=$WORK_DIRECTORY/xdg/cache" +) + +openshell_cli() { + "${OPENSHELL_ENVIRONMENT[@]}" "$BIN_DIRECTORY/openshell" \ + --gateway-endpoint "http://127.0.0.1:$GATEWAY_PORT" "$@" +} + +stop_process() { + local pid="$1" + if [[ -n "$pid" ]]; then + kill "$pid" 2>/dev/null || true + wait "$pid" 2>/dev/null || true + fi +} + +cleanup() { + local status=$? + trap - EXIT + local sandbox language + for sandbox in "${SANDBOXES[@]}"; do + openshell_cli sandbox delete "$sandbox" >>"$LOG_DIRECTORY/cleanup.log" 2>&1 || true + done + # The gateway removes sandbox containers asynchronously after it accepts a deletion. + local containers + for _ in {1..30}; do + containers=$(docker ps -aq --filter "label=openshell.ai/sandbox-namespace=$RUN_ID") + [[ -n "$containers" ]] || break + sleep 1 + done + stop_process "$GATEWAY_PID" + # Only this run uses this sandbox label, so anything left under it is this run's to remove. + containers=$(docker ps -aq --filter "label=openshell.ai/sandbox-namespace=$RUN_ID") + if [[ -n "$containers" ]]; then + echo "INFO removing sandbox containers that the gateway left behind" >&2 + # shellcheck disable=SC2086 # one container ID per word + docker rm -f $containers >>"$LOG_DIRECTORY/cleanup.log" 2>&1 || true + fi + for language in "${!MIDDLEWARE_PID[@]}"; do + stop_process "${MIDDLEWARE_PID[$language]}" + done + stop_process "$UPSTREAM_PID" + if [[ "$SANDBOX_IMAGE_BUILT" == true ]]; then + docker rmi "$SANDBOX_IMAGE" >>"$LOG_DIRECTORY/cleanup.log" 2>&1 || true + fi + if [[ "$status" -eq 0 && "$KEEP_WORK_DIRECTORY" == false ]]; then + rm -rf "${WORK_DIRECTORY:?}" + else + echo "INFO work directory: $WORK_DIRECTORY" >&2 + fi + exit "$status" +} +trap cleanup EXIT + +run_logged() { + local label="$1" log="$LOG_DIRECTORY/$2.log" + shift 2 + if ! "$@" >>"$log" 2>&1; then + tail -n 40 "$log" >&2 + fail "$label (see $log)" + fi + pass "$label" +} + +free_port() { + uv run --no-project python -c \ + 'import socket; s = socket.socket(); s.bind(("", 0)); print(s.getsockname()[1])' +} + +wait_for_port() { + local port="$1" pid="$2" label="$3" + for _ in {1..60}; do + kill -0 "$pid" 2>/dev/null || fail "$label exited before listening" + if (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; then + return + fi + sleep 0.5 + done + fail "$label did not listen on port $port" +} + +# Each run_* function replaces its background subshell, so $! is the service itself. +run_middleware() { + local language="$1" listen="0.0.0.0:${MIDDLEWARE_PORT[$1]}" + if [[ "$language" == "python" ]]; then + exec "$WORK_DIRECTORY/python/.venv/bin/omm-verify-python" --listen "$listen" + fi + exec "$WORK_DIRECTORY/rust-target/debug/omm-verify-rust" "$listen" +} + +run_upstream() { + exec "$WORK_DIRECTORY/upstream-environment/bin/python" "$WORK_DIRECTORY/upstream.py" \ + "$UPSTREAM_PORT" +} + +run_gateway() { + exec "${OPENSHELL_ENVIRONMENT[@]}" "$BIN_DIRECTORY/openshell-gateway" \ + --compute-driver docker --config "$WORK_DIRECTORY/gateway.toml" \ + --bind-address 127.0.0.1 --port "$GATEWAY_PORT" --health-port "$HEALTH_PORT" \ + --metrics-port 0 --log-level info --disable-tls \ + --db-url "sqlite://$WORK_DIRECTORY/gateway.db" +} + +start_middleware() { + local language="$1" + run_middleware "$language" >>"$LOG_DIRECTORY/middleware-$language.log" 2>&1 & + MIDDLEWARE_PID[$language]=$! + wait_for_port "${MIDDLEWARE_PORT[$language]}" "${MIDDLEWARE_PID[$language]}" \ + "$language middleware" +} + +# Run curl in the sandbox. Prints the response body, then the status code on the last line. +sandbox_request() { + local sandbox="$1" payload="$2" + openshell_cli sandbox exec --name "$sandbox" --no-tty -- \ + curl -sS --max-time 20 -w '\n%{http_code}' \ + -X POST "http://$UPSTREAM_HOST:$UPSTREAM_PORT/echo" \ + -H 'content-type: text/plain' --data "$payload" 2>>"$LOG_DIRECTORY/requests.log" +} + +upstream_request_count() { + grep -c '^request ' "$LOG_DIRECTORY/upstream.log" || true +} + +# --------------------------------------------------------------------------------------- +echo "INFO verifying omm against OpenShell $OPENSHELL_VERSION for: ${LANGUAGES[*]}" + +# run_logged calls this inside an `if`, where `set -e` is off, so each command returns on failure. +download_release_archive() { + local archive="$1" checksums="$2" file + for file in "$archive" "$checksums"; do + curl -fsSL -o "$BIN_DIRECTORY/$file" \ + "$RELEASE_URL/download/$OPENSHELL_VERSION/$file" || return 1 + done + (cd "$BIN_DIRECTORY" && grep " $archive\$" "$checksums" | sha256sum --check --status) || + return 1 + tar -xzf "$BIN_DIRECTORY/$archive" -C "$BIN_DIRECTORY" +} +run_logged "downloaded and checksum-verified the OpenShell $OPENSHELL_VERSION gateway" setup \ + download_release_archive "openshell-gateway-$ARCHITECTURE-unknown-linux-gnu.tar.gz" \ + openshell-gateway-checksums-sha256.txt +run_logged "downloaded and checksum-verified the OpenShell $OPENSHELL_VERSION CLI" setup \ + download_release_archive "openshell-$ARCHITECTURE-unknown-linux-musl.tar.gz" \ + openshell-checksums-sha256.txt +[[ "$("$BIN_DIRECTORY/openshell-gateway" --version)" == "openshell-gateway ${OPENSHELL_VERSION#v}" ]] || + fail "downloaded gateway does not report version ${OPENSHELL_VERSION#v}" + +# --- generate each starter, refresh it with omm update, and run its documented checks --- +omm() { + uv run --project "$PROJECT_DIRECTORY" omm "$@" +} + +for LANGUAGE in "${LANGUAGES[@]}"; do + PROJECT="$WORK_DIRECTORY/$LANGUAGE" + run_logged "omm create --language $LANGUAGE --openshell-version $OPENSHELL_VERSION" \ + "create-$LANGUAGE" \ + omm create "omm-verify-$LANGUAGE" --language "$LANGUAGE" \ + --openshell-version "$OPENSHELL_VERSION" --output "$PROJECT" + grep -q "\"openshell_version\": \"$OPENSHELL_VERSION\"" \ + "$PROJECT/.openshell-middleware-manifest.json" || + fail "$LANGUAGE manifest does not record $OPENSHELL_VERSION" + run_logged "omm update --openshell-version $OPENSHELL_VERSION ($LANGUAGE)" \ + "update-$LANGUAGE" omm update "$PROJECT" --openshell-version "$OPENSHELL_VERSION" + + cd "$PROJECT" + if [[ "$LANGUAGE" == "python" ]]; then + run_logged "python starter: uv sync --locked" checks-python uv sync --locked + run_logged "python starter: ruff format --check" checks-python \ + uv run ruff format --check . + run_logged "python starter: ruff check" checks-python uv run ruff check . + run_logged "python starter: ty check" checks-python uv run ty check + run_logged "python starter: pytest" checks-python uv run pytest + run_logged "python starter: uv build" checks-python uv build + else + export CARGO_TARGET_DIR="$WORK_DIRECTORY/rust-target" + run_logged "rust starter: cargo fmt --check" checks-rust cargo fmt --check + run_logged "rust starter: cargo clippy -D warnings" checks-rust \ + cargo clippy --all-targets --all-features -- -D warnings + run_logged "rust starter: cargo test --locked" checks-rust cargo test --locked + run_logged "rust starter: cargo build --locked" checks-rust cargo build --locked + fi + cd "$WORK_DIRECTORY" +done + +# --- start the starters, an echo upstream, and the OpenShell gateway ---------------------- +HOST_ADDRESS="${OMM_VERIFY_HOST:-}" +if [[ -z "$HOST_ADDRESS" ]]; then + HOST_ADDRESS=$(ip -4 route get 1.1.1.1 2>/dev/null | + awk '{ for (i = 1; i < NF; i++) if ($i == "src") { print $(i + 1); exit } }' || true) +fi +[[ "$HOST_ADDRESS" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ && "$HOST_ADDRESS" != 127.* ]] || + fail "set OMM_VERIFY_HOST to a non-loopback IPv4 address of this host" + +for LANGUAGE in "${LANGUAGES[@]}"; do + MIDDLEWARE_PORT[$LANGUAGE]=$(free_port) + start_middleware "$LANGUAGE" +done + +UPSTREAM_PORT=$(free_port) +cat >"$WORK_DIRECTORY/upstream.py" <<'UPSTREAM' +import sys +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + +class Handler(BaseHTTPRequestHandler): + def do_POST(self) -> None: + body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) + print(f"request {self.command} {self.path} {len(body)} bytes", flush=True) + self.send_response(200) + self.send_header("Content-Type", "text/plain") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: object) -> None: + pass + + +ThreadingHTTPServer(("0.0.0.0", int(sys.argv[1])), Handler).serve_forever() +UPSTREAM +uv venv --quiet "$WORK_DIRECTORY/upstream-environment" +run_upstream >"$LOG_DIRECTORY/upstream.log" 2>&1 & +UPSTREAM_PID=$! +wait_for_port "$UPSTREAM_PORT" "$UPSTREAM_PID" "echo upstream" + +mkdir -p "$WORK_DIRECTORY/jwt" +openssl genpkey -algorithm ed25519 -out "$WORK_DIRECTORY/jwt/signing.pem" 2>/dev/null +openssl pkey -in "$WORK_DIRECTORY/jwt/signing.pem" -pubout \ + -out "$WORK_DIRECTORY/jwt/public.pem" 2>/dev/null +echo "$RUN_ID" >"$WORK_DIRECTORY/jwt/kid" + +# A unique sandbox label keeps this gateway from managing any other gateway's containers. +cat >"$WORK_DIRECTORY/gateway.toml" <>"$WORK_DIRECTORY/gateway.toml" <"$LOG_DIRECTORY/gateway.log" 2>&1 & +GATEWAY_PID=$! +GATEWAY_HEALTHY=false +for _ in {1..60}; do + if ! kill -0 "$GATEWAY_PID" 2>/dev/null; then + tail -n 20 "$LOG_DIRECTORY/gateway.log" >&2 + fail "the gateway rejected the registered starters at startup" + fi + if curl -fsS "http://127.0.0.1:$HEALTH_PORT/healthz" >/dev/null 2>&1; then + GATEWAY_HEALTHY=true + break + fi + sleep 1 +done +[[ "$GATEWAY_HEALTHY" == true ]] || fail "the gateway did not become healthy" +pass "OpenShell $OPENSHELL_VERSION gateway started after Describe on every registered starter" + +openshell_cli gateway info -o json >"$LOG_DIRECTORY/gateway-info.json" 2>>"$LOG_DIRECTORY/setup.log" || + fail "openshell gateway info" +cat >"$WORK_DIRECTORY/check_negotiation.py" <<'NEGOTIATION' +import json +import sys + +extensions = json.load(open(sys.argv[1]))["extensions"] +extension = next(item for item in extensions if item["configured_name"] == sys.argv[2]) +assert extension["kind"] == "supervisor-middleware", extension +assert extension["protocol_version"] == "1.0", extension +assert "openshell.supervisor-middleware.http-hooks" in extension["required_capabilities"], extension +NEGOTIATION +for LANGUAGE in "${LANGUAGES[@]}"; do + run_logged "gateway negotiated protocol 1.0 with HTTP hooks for the $LANGUAGE starter" setup \ + uv run --no-project python "$WORK_DIRECTORY/check_negotiation.py" \ + "$LOG_DIRECTORY/gateway-info.json" "omm-verify-$LANGUAGE" +done + +# --- send sandbox traffic through each starter -------------------------------------------- +mkdir -p "$WORK_DIRECTORY/image" +printf 'FROM %s\nRUN apt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/*\n' \ + "$SANDBOX_BASE_IMAGE" >"$WORK_DIRECTORY/image/Dockerfile" +run_logged "built a sandbox image with curl" setup \ + docker build --quiet --tag "$SANDBOX_IMAGE" "$WORK_DIRECTORY/image" +SANDBOX_IMAGE_BUILT=true + +for LANGUAGE in "${LANGUAGES[@]}"; do + NAME="omm-verify-$LANGUAGE" + SANDBOX="omm-${LANGUAGE:0:2}-$RANDOM" + PAYLOAD="omm verification payload for $LANGUAGE" + # The attachment that the generated README documents. + cat >"$WORK_DIRECTORY/policy-$LANGUAGE.yaml" <"$LOG_DIRECTORY/sandbox-$LANGUAGE.log" 2>&1 || true + if grep 'http_event_kind:middleware_invocation' "$LOG_DIRECTORY/sandbox-$LANGUAGE.log" | + grep -q 'ALLOWED.*failed:false'; then + INVOCATION_LOGGED=true + break + fi + sleep 1 + done + [[ "$INVOCATION_LOGGED" == true ]] || + fail "OpenShell did not log an allowed middleware invocation for the $LANGUAGE starter" + pass "OpenShell logged an allowed middleware invocation for the $LANGUAGE starter" + + # Negative control: the request must depend on the starter answering. + UPSTREAM_REQUESTS=$(upstream_request_count) + stop_process "${MIDDLEWARE_PID[$LANGUAGE]}" + unset "MIDDLEWARE_PID[$LANGUAGE]" + RESPONSE=$(sandbox_request "$SANDBOX" "$PAYLOAD") || true + [[ "$RESPONSE" == *'"error":"middleware_failed"'*"\"middleware\":\"$NAME\""*$'\n403' ]] || + fail "OpenShell did not block the request while the $LANGUAGE starter was down: $RESPONSE" + [[ "$(upstream_request_count)" == "$UPSTREAM_REQUESTS" ]] || + fail "the blocked request still reached the upstream" + pass "OpenShell blocked the request while the $LANGUAGE starter was stopped (HTTP 403)" + + start_middleware "$LANGUAGE" + RESPONSE="" + for _ in {1..15}; do + RESPONSE=$(sandbox_request "$SANDBOX" "$PAYLOAD") && [[ "$RESPONSE" == *$'\n200' ]] && break + sleep 1 + done + [[ "$RESPONSE" == "$PAYLOAD"$'\n200' ]] || + fail "requests did not recover after the $LANGUAGE starter restarted: $RESPONSE" + pass "requests passed again after the $LANGUAGE starter restarted" +done + +echo "ALL PASS omm works with OpenShell $OPENSHELL_VERSION (${LANGUAGES[*]})" diff --git a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/cli.py b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/cli.py index de4aa409..d864a6c1 100644 --- a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/cli.py +++ b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/cli.py @@ -72,7 +72,7 @@ def create( typer.Option( "--openshell-version", "--version", - help="OpenShell release tag (for example v0.0.86), or latest.", + help="OpenShell release tag (for example v0.1.9), or latest.", ), ], output: Annotated[ @@ -122,7 +122,7 @@ def update( typer.Option( "--openshell-version", "--version", - help="OpenShell release tag (for example v0.0.86), or latest.", + help="OpenShell release tag (for example v0.1.9), or latest.", ), ] = "latest", check_command: Annotated[ diff --git a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/generator.py b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/generator.py index 4711c9fb..89721c23 100644 --- a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/generator.py +++ b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/generator.py @@ -29,13 +29,26 @@ from functools import partial from importlib.resources import files from pathlib import Path +from typing import Any from openshell_middleware_manager import __version__ _REPOSITORY_URL = "https://github.com/NVIDIA/OpenShell" _RAW_URL = "https://raw.githubusercontent.com/NVIDIA/OpenShell" -_PROTO_PATH = "proto/supervisor_middleware.proto" +_PROTO_DIRECTORY = "proto" +_PROTO_NAME = "supervisor_middleware.proto" +_PROTO_IMPORT_PATTERN = re.compile( + r'^[ \t]*import[ \t]+(?:public[ \t]+)?"([^"]+)"[ \t]*;', re.MULTILINE +) +_PROTO_BLOCK_COMMENT_PATTERN = re.compile(r"/\*.*?\*/", re.DOTALL) +_PROTO_NAME_PATTERN = re.compile(r"^[A-Za-z0-9_]+\.proto$") +_BUNDLED_PROTO_PREFIX = "google/protobuf/" +_HTTP_HOOKS_SERVICE = b"service HttpHooks" +_FIRST_HTTP_HOOKS_RELEASE = "v0.1.9" _GRPCIO_TOOLS_VERSION = "1.81.1" +_GENERATED_SIBLING_IMPORT_PATTERN = re.compile( + r"^(?:import (\w+_pb2) as |from (\w+_pb2) import )", re.MULTILINE +) _VERSION_PATTERN = re.compile(r"^v\d+\.\d+\.\d+(?:[+-][0-9A-Za-z._-]+)?$") _PYTHON_PACKAGE_PATTERN = re.compile(r"^[a-z][a-z0-9_]*$") _PROJECT_NAME_PATTERN = re.compile(r"^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$") @@ -147,6 +160,25 @@ class ProjectMetadata: language: str python_package: str | None + proto_imports: tuple[str, ...] + + +@dataclass(frozen=True) +class ProtoFile: + """One file of the middleware contract downloaded from an OpenShell release.""" + + name: str + content: bytes + source: str + + +@dataclass(frozen=True) +class ProtoPublication: + """How an update publishes each generator-owned file in a project's proto directory.""" + + replaced: tuple[str, ...] + added: tuple[str, ...] + removed: tuple[str, ...] @dataclass(frozen=True) @@ -187,7 +219,8 @@ def replacements(self) -> Mapping[str, str]: } -DownloadProto = Callable[[str], tuple[bytes, str]] +# (OpenShell version, file name in the release's proto directory) -> (content, source URL) +DownloadProto = Callable[[str, str], tuple[bytes, str]] CommandRunner = Callable[[str, Path, str], None] @@ -222,17 +255,17 @@ def create_project( reservation.staging_path.mkdir(mode=0o700) staging_path = reservation.staging_path staging_path.chmod(0o755) - proto, proto_url = downloader(version) - _validate_proto(proto, version) + contract = _download_contract(version, downloader) + _require_http_hooks(contract[0].content, version) _render_project(staging_path, language, context) - proto_path = staging_path / "proto" / "supervisor_middleware.proto" - proto_path.parent.mkdir(parents=True, exist_ok=True) - proto_path.write_bytes(proto) + proto_directory = staging_path / _PROTO_DIRECTORY + proto_directory.mkdir() + for proto_file in contract: + (proto_directory / proto_file.name).write_bytes(proto_file.content) _write_manifest( staging_path, version=version, - proto_url=proto_url, - proto=proto, + contract=contract, language=language, python_package=context.package_name if language == "python" else None, ) @@ -300,14 +333,12 @@ def update_project( _validate_existing_project(project_dir) _copy_project_to_staging(project_dir, reservation.staging_path) staging_path = reservation.staging_path - proto, proto_url = downloader(version) - _validate_proto(proto, version) - _refresh_generated_artifacts( + contract = _download_contract(version, downloader) + proto_publication = _refresh_generated_artifacts( staging_path, metadata=metadata, version=version, - proto_url=proto_url, - proto=proto, + contract=contract, ) runner(metadata.language, staging_path, metadata.python_package or "unused") _verify_lock(legacy_reservation) @@ -323,7 +354,7 @@ def update_project( metadata.language, metadata.python_package, ) - _publish_generated_artifacts(staging_path, project_dir, metadata) + _publish_generated_artifacts(staging_path, project_dir, metadata, proto_publication) published = True except PublicationRollbackError: preserve_recovery = True @@ -407,7 +438,7 @@ def _normalize_version(requested: str) -> str: value = f"v{value}" if not _VERSION_PATTERN.fullmatch(value): raise ProjectError( - f"invalid OpenShell version '{requested}'; expected a tag such as v0.0.86" + f"invalid OpenShell version '{requested}'; expected a tag such as v0.1.9" ) return value @@ -430,8 +461,41 @@ def _resolve_latest_version() -> str: return version -def _download_proto(version: str) -> tuple[bytes, str]: - url = f"{_RAW_URL}/{version}/{_PROTO_PATH}" +def _download_contract(version: str, downloader: DownloadProto) -> tuple[ProtoFile, ...]: + """Download the middleware proto, then every OpenShell proto it imports.""" + contract: dict[str, ProtoFile] = {} + pending = [_PROTO_NAME] + while pending: + name = pending.pop() + if name in contract: + continue + content, source = downloader(version, name) + if name == _PROTO_NAME: + _validate_proto(content, version) + contract[name] = ProtoFile(name=name, content=content, source=source) + pending.extend(_openshell_imports(content, version)) + middleware_proto = contract.pop(_PROTO_NAME) + return (middleware_proto, *sorted(contract.values(), key=lambda proto_file: proto_file.name)) + + +def _openshell_imports(proto: bytes, version: str) -> list[str]: + """Name the OpenShell proto files that a proto imports from its own directory.""" + names = [] + source = _PROTO_BLOCK_COMMENT_PATTERN.sub("", proto.decode(errors="replace")) + for imported in _PROTO_IMPORT_PATTERN.findall(source): + if imported.startswith(_BUNDLED_PROTO_PREFIX): + continue + if not _PROTO_NAME_PATTERN.fullmatch(imported): + raise ProjectError( + f"contract for {version} imports an unsupported proto path: {imported}" + ) + names.append(imported) + return names + + +def _download_proto(version: str, name: str) -> tuple[bytes, str]: + proto_path = f"{_PROTO_DIRECTORY}/{name}" + url = f"{_RAW_URL}/{version}/{proto_path}" request = urllib.request.Request( url, headers={"User-Agent": f"{_TOOL_NAME}/{__version__}"}, @@ -442,14 +506,14 @@ def _download_proto(version: str) -> tuple[bytes, str]: except urllib.error.HTTPError as error: if error.code == 404: raise ProjectError( - f"{version} does not expose {_PROTO_PATH}; choose a middleware-capable release" + f"{version} does not expose {proto_path}; choose a middleware-capable release" ) from error raise ProjectError( - f"could not download {_PROTO_PATH} for {version}: HTTP {error.code}" + f"could not download {proto_path} for {version}: HTTP {error.code}" ) from error except (OSError, urllib.error.URLError, http.client.IncompleteRead) as error: raise ProjectError( - f"could not download {_PROTO_PATH} for {version}: {_network_error_reason(error)}" + f"could not download {proto_path} for {version}: {_network_error_reason(error)}" ) from error @@ -490,6 +554,14 @@ def _validate_proto(proto: bytes, version: str) -> None: ) +def _require_http_hooks(proto: bytes, version: str) -> None: + if _HTTP_HOOKS_SERVICE not in proto: + raise ProjectError( + f"{version} predates the HTTP hooks that new middleware projects implement; " + f"choose OpenShell {_FIRST_HTTP_HOOKS_RELEASE} or newer" + ) + + def _validate_destination(destination: Path) -> None: if os.path.lexists(destination): raise ProjectError(f"output path must not already exist: {destination}") @@ -513,7 +585,7 @@ def _verify_project_identity(project_dir: Path, device: int, inode: int) -> None raise ProjectError("project path changed during update; refusing to publish") -def _read_project_metadata(project_dir: Path) -> ProjectMetadata: +def _read_manifest(project_dir: Path) -> dict[str, Any]: manifest_path = project_dir / _MANIFEST_FILENAME if manifest_path.is_symlink() or not manifest_path.is_file(): raise ProjectError( @@ -525,6 +597,29 @@ def _read_project_metadata(project_dir: Path) -> ProjectMetadata: raise ProjectError(f"could not read project manifest: {error}") from error if not isinstance(manifest, dict): raise ProjectError("project manifest must contain a JSON object") + return manifest + + +def _manifest_proto_imports(manifest: Mapping[str, Any]) -> tuple[str, ...]: + """Name the imported proto files that a manifest records as generator-owned.""" + entries = manifest.get("proto_imports", []) + if not isinstance(entries, list): + raise ProjectError("project manifest proto_imports must be a list") + names = [] + for entry in entries: + name = entry.get("name") if isinstance(entry, dict) else None + if ( + not isinstance(name, str) + or not _PROTO_NAME_PATTERN.fullmatch(name) + or name == _PROTO_NAME + ): + raise ProjectError("project manifest has an invalid proto_imports entry") + names.append(name) + return tuple(names) + + +def _read_project_metadata(project_dir: Path) -> ProjectMetadata: + manifest = _read_manifest(project_dir) generator = manifest.get("generator") generator_name = generator.get("name") if isinstance(generator, dict) else None @@ -533,7 +628,7 @@ def _read_project_metadata(project_dir: Path) -> ProjectMetadata: languages = manifest.get("languages") if languages not in (["python"], ["rust"]): raise ProjectError("project manifest must identify exactly one supported language") - language = languages[0] + language: str = manifest["languages"][0] python_package = manifest.get("python_package") if language == "python": if not isinstance(python_package, str) or not _PYTHON_PACKAGE_PATTERN.fullmatch( @@ -543,8 +638,14 @@ def _read_project_metadata(project_dir: Path) -> ProjectMetadata: elif python_package is not None: raise ProjectError("Rust project manifest must set python_package to null") + proto_imports = _manifest_proto_imports(manifest) + _validate_refresh_targets(project_dir, language, python_package) - return ProjectMetadata(language=language, python_package=python_package) + return ProjectMetadata( + language=language, + python_package=python_package, + proto_imports=proto_imports, + ) def _validate_refresh_targets(project_dir: Path, language: str, python_package: str | None) -> None: @@ -601,16 +702,41 @@ def _refresh_generated_artifacts( *, metadata: ProjectMetadata, version: str, - proto_url: str, - proto: bytes, -) -> None: + contract: Sequence[ProtoFile], +) -> ProtoPublication: _validate_refresh_targets( project_dir, metadata.language, metadata.python_package, ) - proto_path = project_dir / "proto" / "supervisor_middleware.proto" - proto_path.write_bytes(proto) + proto_directory = project_dir / _PROTO_DIRECTORY + middleware_proto, *imported_protos = contract + (proto_directory / middleware_proto.name).write_bytes(middleware_proto.content) + replaced = [middleware_proto.name] + added = [] + for proto_file in imported_protos: + proto_path = proto_directory / proto_file.name + _reject_irregular_file(proto_path) + if not proto_path.exists(): + added.append(proto_file.name) + elif ( + proto_file.name in metadata.proto_imports + or proto_path.read_bytes() == proto_file.content + ): + replaced.append(proto_file.name) + else: + raise ProjectError( + f"{proto_path.relative_to(project_dir)} already exists and differs from the " + f"file that OpenShell {version} imports; move it before updating" + ) + proto_path.write_bytes(proto_file.content) + removed = [] + for stale_name in sorted(set(metadata.proto_imports) - {file.name for file in contract}): + stale_path = proto_directory / stale_name + _reject_irregular_file(stale_path) + if stale_path.exists(): + stale_path.unlink() + removed.append(stale_name) if metadata.language == "python": if metadata.python_package is None: # pragma: no cover - checked during discovery raise AssertionError("Python package is required") @@ -623,11 +749,21 @@ def _refresh_generated_artifacts( _write_manifest( project_dir, version=version, - proto_url=proto_url, - proto=proto, + contract=contract, language=metadata.language, python_package=metadata.python_package, ) + return ProtoPublication( + replaced=tuple(replaced), + added=tuple(added), + removed=tuple(removed), + ) + + +def _reject_irregular_file(path: Path) -> None: + """Refuse to write through a symlink or over a directory in a generated-file slot.""" + if os.path.lexists(path) and (path.is_symlink() or not path.is_file()): + raise ProjectError(f"generated artifact must be a regular file: {path}") def _acquire_lock( @@ -845,11 +981,12 @@ def _publish_exchange(source: Path, destination: Path) -> None: ) source_name = os.fsencode(source.name) destination_name = os.fsencode(destination.name) - result = _exchange_at( + result = _rename_at( source_parent_fd, source_name, destination_parent_fd, destination_name, + exchange=True, ) if result != 0: _raise_exchange_error(destination) @@ -861,11 +998,12 @@ def _publish_exchange(source: Path, destination: Path) -> None: if source_attached and destination_attached: return - reverse_result = _exchange_at( + reverse_result = _rename_at( source_parent_fd, source_name, destination_parent_fd, destination_name, + exchange=True, ) if reverse_result != 0: error_number = ctypes.get_errno() @@ -881,12 +1019,67 @@ def _publish_exchange(source: Path, destination: Path) -> None: os.close(destination_parent_fd) -def _exchange_at( +def _publish_move(source: Path, destination: Path) -> None: + """Atomically move a validated regular file to a path that must not exist yet.""" + source_parent_fd = _open_parent_directory_no_follow(source) + destination_parent_fd = _open_parent_directory_no_follow(destination) + try: + source_stat = os.stat(source.name, dir_fd=source_parent_fd, follow_symlinks=False) + if not stat.S_ISREG(source_stat.st_mode): + raise ProjectError( + "generated artifacts changed type during update; refusing to publish" + ) + source_name = os.fsencode(source.name) + destination_name = os.fsencode(destination.name) + result = _rename_at( + source_parent_fd, + source_name, + destination_parent_fd, + destination_name, + exchange=False, + ) + if result != 0: + if ctypes.get_errno() == errno.EEXIST: + raise ProjectError( + f"a file appeared during update; refusing to overwrite it: {destination}" + ) + _raise_exchange_error(destination) + source_attached = _directory_fd_matches_path(source.parent, source_parent_fd) + destination_attached = _directory_fd_matches_path( + destination.parent, + destination_parent_fd, + ) + if source_attached and destination_attached: + return + + reverse_result = _rename_at( + destination_parent_fd, + destination_name, + source_parent_fd, + source_name, + exchange=False, + ) + if reverse_result != 0: + error_number = ctypes.get_errno() + raise PublicationRollbackError( + "an artifact parent changed during publication and the anchored move " + f"could not be reversed: {os.strerror(error_number)}" + ) + raise ProjectError("an artifact parent changed during publication; the move was reversed") + finally: + os.close(source_parent_fd) + os.close(destination_parent_fd) + + +def _rename_at( source_parent_fd: int, source_name: bytes, destination_parent_fd: int, destination_name: bytes, + *, + exchange: bool, ) -> int: + """Exchange two entries, or move one entry without replacing an existing destination.""" if sys.platform.startswith("linux"): library = ctypes.CDLL(None, use_errno=True) try: @@ -895,11 +1088,11 @@ def _exchange_at( raise ProjectError( "this Linux runtime cannot atomically publish a project update" ) from error - exchange_flag = 2 + rename_flag = 2 if exchange else 1 elif sys.platform == "darwin": # pragma: no cover - platform-specific library = ctypes.CDLL(None, use_errno=True) rename = library.renameatx_np - exchange_flag = 0x00000002 + rename_flag = 0x00000002 if exchange else 0x00000004 else: # pragma: no cover - unsupported platform raise ProjectError("this platform cannot atomically publish a project update") rename.argtypes = ( @@ -915,7 +1108,7 @@ def _exchange_at( source_name, destination_parent_fd, destination_name, - exchange_flag, + rename_flag, ) @@ -986,34 +1179,52 @@ def _validate_exchange_entries( def _publish_generated_artifacts( - staged_project: Path, project_dir: Path, metadata: ProjectMetadata + staged_project: Path, + project_dir: Path, + metadata: ProjectMetadata, + proto_publication: ProtoPublication, ) -> None: - """Exchange refreshed artifacts in place, rolling back a normal publication failure.""" - relative_paths = [ - Path("proto/supervisor_middleware.proto"), - Path("uv.lock" if metadata.language == "python" else "Cargo.lock"), - ] + """Publish refreshed artifacts in place, rolling back a normal publication failure.""" + proto_directory = Path(_PROTO_DIRECTORY) + exchanged_paths = [proto_directory / name for name in proto_publication.replaced] + exchanged_paths.append(Path("uv.lock" if metadata.language == "python" else "Cargo.lock")) if metadata.language == "python": if metadata.python_package is None: # pragma: no cover - checked during discovery raise AssertionError("Python package is required") - relative_paths.append(Path("src") / metadata.python_package / "bindings") - relative_paths.append(Path(_MANIFEST_FILENAME)) + exchanged_paths.append(Path("src") / metadata.python_package / "bindings") + exchanged_paths.append(Path(_MANIFEST_FILENAME)) + + # Each step is (source, destination, exchange). A move's reverse swaps its two paths. + steps = [ + *( + (staged_project / proto_directory / name, project_dir / proto_directory / name, False) + for name in proto_publication.added + ), + *( + (project_dir / proto_directory / name, staged_project / proto_directory / name, False) + for name in proto_publication.removed + ), + *( + (staged_project / relative_path, project_dir / relative_path, True) + for relative_path in exchanged_paths + ), + ] - exchanged: list[Path] = [] + completed: list[tuple[Path, Path, bool]] = [] try: - for relative_path in relative_paths: - _publish_exchange( - staged_project / relative_path, - project_dir / relative_path, - ) - exchanged.append(relative_path) + for source, destination, exchange in steps: + if exchange: + _publish_exchange(source, destination) + else: + _publish_move(source, destination) + completed.append((source, destination, exchange)) except (ProjectError, OSError) as publish_error: try: - for relative_path in reversed(exchanged): - _publish_exchange( - staged_project / relative_path, - project_dir / relative_path, - ) + for source, destination, exchange in reversed(completed): + if exchange: + _publish_exchange(source, destination) + else: + _publish_move(destination, source) except (ProjectError, OSError) as rollback_error: raise PublicationRollbackError( "artifact publication and rollback both failed; inspect the project and " @@ -1057,15 +1268,23 @@ def _write_manifest( project_dir: Path, *, version: str, - proto_url: str, - proto: bytes, + contract: Sequence[ProtoFile], language: str, python_package: str | None, ) -> None: + middleware_proto, *imported_protos = contract manifest = { "openshell_version": version, - "proto_source": proto_url, - "proto_sha256": hashlib.sha256(proto).hexdigest(), + "proto_source": middleware_proto.source, + "proto_sha256": hashlib.sha256(middleware_proto.content).hexdigest(), + "proto_imports": [ + { + "name": proto_file.name, + "source": proto_file.source, + "sha256": hashlib.sha256(proto_file.content).hexdigest(), + } + for proto_file in imported_protos + ], "languages": [language], "python_package": python_package, "generator": { @@ -1124,7 +1343,8 @@ def _prepare_python_project( ) -> None: uv = _require_command("uv") bindings_dir = project_dir / "src" / package_name / "bindings" - proto_path = project_dir / "proto" / "supervisor_middleware.proto" + proto_directory = project_dir / _PROTO_DIRECTORY + proto_names = (_PROTO_NAME, *_manifest_proto_imports(_read_manifest(project_dir))) _run( ( uv, @@ -1136,23 +1356,27 @@ def _prepare_python_project( "python", "-m", "grpc_tools.protoc", - f"-I{proto_path.parent}", + f"-I{proto_directory}", f"--python_out={bindings_dir}", f"--pyi_out={bindings_dir}", f"--grpc_python_out={bindings_dir}", - str(proto_path), + *(str(proto_directory / name) for name in proto_names), ), cwd=project_dir, ) grpc_module = bindings_dir / "supervisor_middleware_pb2_grpc.py" - generated = grpc_module.read_text() absolute_import = "import supervisor_middleware_pb2 as supervisor__middleware__pb2" - relative_import = "from . import supervisor_middleware_pb2 as supervisor__middleware__pb2" - if absolute_import not in generated: + if absolute_import not in grpc_module.read_text(): raise ProjectError( "generated gRPC module has an unexpected import layout; no project was published" ) - grpc_module.write_text(generated.replace(absolute_import, relative_import, 1)) + # protoc imports sibling modules by bare name, which fails inside a package. + for generated_module in bindings_dir.glob("*_pb2*.py*"): + generated_module.write_text( + _GENERATED_SIBLING_IMPORT_PATTERN.sub( + _relative_sibling_import, generated_module.read_text() + ) + ) with tempfile.TemporaryDirectory(prefix=f"{_TOOL_NAME}-python-") as environment: process_environment = os.environ.copy() @@ -1176,6 +1400,13 @@ def _prepare_python_project( ) +def _relative_sibling_import(match: re.Match[str]) -> str: + plain_import, public_import = match.groups() + if plain_import is not None: + return f"from . import {plain_import} as " + return f"from .{public_import} import " + + def _prepare_rust_project(project_dir: Path) -> None: cargo = _require_command("cargo") with tempfile.TemporaryDirectory(prefix=f"{_TOOL_NAME}-rust-") as target_dir: diff --git a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/README.md b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/README.md index 16697343..17ea4b32 100644 --- a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/README.md +++ b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/README.md @@ -2,7 +2,11 @@ A Python OpenShell supervisor middleware starter. It is pinned to the OpenShell contract recorded in `.openshell-middleware-manifest.json` and starts as a pass-through: -valid pre-credentials HTTP requests are allowed without mutation. +valid pre-credentials HTTP requests continue without mutation. + +The service implements OpenShell's HTTP hooks and requires the +`openshell.supervisor-middleware.http-hooks` capability. Use it with a gateway +and sandbox supervisors running OpenShell v0.1.9 or newer. ## Develop @@ -24,9 +28,31 @@ uv run __DISTRIBUTION_NAME__ --listen 127.0.0.1:50051 ``` The server implementation is in `src/__PACKAGE_NAME__/server.py`. Extend -`validate_config` and `evaluate_http_request` with your policy and request -handling. Keep transport adaptation at this boundary and move substantial -domain logic into separate modules. +`validate_config`, `evaluate_http_request_preflight`, and +`evaluate_http_request_body` with your policy and request handling. Keep +transport adaptation at this boundary and move substantial domain logic into +separate modules. + +`evaluate_http_request_preflight` receives the request target, headers, and +policy config. It can continue, deny, or change headers. To inspect or replace +the body, select whole-body inspection when OpenShell offers it: + +```python +if pb2.HTTP_BODY_MODE_WHOLE_BODY in preflight.permitted_body_modes: + return pb2.HttpRequestHookResult( + preflight_result=pb2.HttpPreflightResult( + inspect=pb2.HttpInspect( + whole_body=pb2.HttpWholeBodyMode( + max_body_bytes=preflight.limits.max_whole_body_bytes + ) + ) + ) + ) +``` + +OpenShell then sends the complete body to `evaluate_http_request_body`. The starter +does not implement streaming (DUPLEX) inspection; selecting it requires handling +the `input_chunk` and `input_end` events in `evaluate_http_request_event`. ## Connect OpenShell @@ -37,13 +63,15 @@ the development server to a reachable interface: uv run __DISTRIBUTION_NAME__ --listen 0.0.0.0:50051 ``` -Register the running service in the gateway configuration: +Start the service before the gateway, then register it in the gateway +configuration and restart the gateway: ```toml [[openshell.supervisor.middleware]] name = "__SERVICE_NAME__" grpc_endpoint = "http://:50051" -max_body_bytes = 4194304 +allow_insecure_transport = true +max_payload_bytes = 4194304 timeout = "500ms" ``` @@ -51,9 +79,23 @@ Replace `` with a host IP or DNS name reachable from both the gateway and sandbox supervisors; loopback works only when every process shares the middleware's network namespace. Binding outside loopback is an explicit opt-in because the development server is unauthenticated and insecure; -restrict port exposure to trusted networks. Then reference `__SERVICE_NAME__` from -a sandbox policy's middleware stage. Review the supervisor middleware documentation -for the policy syntax supported by your pinned OpenShell release. +restrict port exposure to trusted networks. `allow_insecure_transport` lets a +gateway that signs extension tokens call this plaintext endpoint without one. + +Attach the registered service to destination hosts in a sandbox policy: + +```yaml +network_middlewares: + __SERVICE_NAME__: + middleware: __SERVICE_NAME__ + endpoints: + include: + - api.example.com +``` + +OpenShell blocks matching requests while the service is unavailable, because +HTTP hook middleware always fails closed. Review the supervisor middleware +documentation for the policy syntax supported by your pinned OpenShell release. ## Version-matched generated files diff --git a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/src/package/server.py b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/src/package/server.py index b4de2975..aa542ae7 100644 --- a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/src/package/server.py +++ b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/src/package/server.py @@ -7,58 +7,118 @@ import argparse import asyncio -from collections.abc import Sequence +from collections.abc import AsyncIterator, Sequence import grpc +from __PACKAGE_NAME__.bindings import extension_pb2 from __PACKAGE_NAME__.bindings import supervisor_middleware_pb2 as pb2 from __PACKAGE_NAME__.bindings import supervisor_middleware_pb2_grpc as pb2_grpc SERVICE_NAME = "__SERVICE_NAME__" SERVICE_VERSION = "0.1.0" -MAX_BODY_BYTES = 4 * 1024 * 1024 -MAX_MESSAGE_BYTES = MAX_BODY_BYTES + 1024 * 1024 +PROTOCOL_MAJOR = 1 +PROTOCOL_MINOR = 0 +CONTRACT_CAPABILITY = "openshell.supervisor-middleware.contract" +HTTP_HOOKS_CAPABILITY = "openshell.supervisor-middleware.http-hooks" +CAPABILITIES = (CONTRACT_CAPABILITY, HTTP_HOOKS_CAPABILITY) +MAX_PAYLOAD_BYTES = 4 * 1024 * 1024 +MAX_MESSAGE_BYTES = MAX_PAYLOAD_BYTES + 1024 * 1024 def build_manifest() -> pb2.MiddlewareManifest: - """Describe the operation and phase supported by this service.""" + """Describe the operation, phase, and protocol contract supported by this service.""" return pb2.MiddlewareManifest( name=SERVICE_NAME, - service_version=SERVICE_VERSION, bindings=[ pb2.MiddlewareBinding( operation=pb2.SUPERVISOR_MIDDLEWARE_OPERATION_HTTP_REQUEST, phase=pb2.SUPERVISOR_MIDDLEWARE_PHASE_PRE_CREDENTIALS, - max_body_bytes=MAX_BODY_BYTES, + max_payload_bytes=MAX_PAYLOAD_BYTES, ) ], + # Requiring the HTTP hooks capability selects HttpHooks for the HTTP binding. + extension=extension_pb2.PeerMetadata( + protocol_version=extension_pb2.ProtocolVersion( + major=PROTOCOL_MAJOR, + minor=PROTOCOL_MINOR, + ), + implementation_name=SERVICE_NAME, + implementation_version=SERVICE_VERSION, + supported_capabilities=CAPABILITIES, + required_capabilities=CAPABILITIES, + ), ) +def find_protocol_mismatch(request: pb2.MiddlewareDescribeRequest) -> str | None: + """Explain why the calling gateway or supervisor cannot use this service.""" + if not request.HasField("gateway"): + return "the caller did not provide protocol metadata" + caller = request.gateway + if caller.protocol_version.major != PROTOCOL_MAJOR: + return f"the caller uses unsupported protocol major {caller.protocol_version.major}" + missing = sorted(set(CAPABILITIES) - set(caller.supported_capabilities)) + if missing: + return f"the caller does not support required capabilities: {', '.join(missing)}" + unsupported = sorted(set(caller.required_capabilities) - set(CAPABILITIES)) + if unsupported: + return f"the caller requires unsupported capabilities: {', '.join(unsupported)}" + return None + + def validate_config(request: pb2.ValidateConfigRequest) -> pb2.ValidateConfigResponse: """Validate service-specific config before OpenShell admits a policy.""" return pb2.ValidateConfigResponse(valid=True) -def evaluate_http_request(request: pb2.HttpRequestEvaluation) -> pb2.HttpRequestResult: - """Allow a valid pre-credentials request without mutation.""" - if request.phase != pb2.SUPERVISOR_MIDDLEWARE_PHASE_PRE_CREDENTIALS: - return pb2.HttpRequestResult( - decision=pb2.DECISION_DENY, - reason="unsupported middleware phase", - reason_code="unsupported_phase", +def evaluate_http_request_preflight( + preflight: pb2.HttpRequestHookPreflight, +) -> pb2.HttpRequestHookResult: + """Decide from the request head whether to continue, deny, or inspect the body.""" + if preflight.phase != pb2.SUPERVISOR_MIDDLEWARE_PHASE_PRE_CREDENTIALS: + return pb2.HttpRequestHookResult( + deny=pb2.HttpDenial( + diagnostics=pb2.MiddlewareDiagnostics( + reason="unsupported middleware phase", + reason_code="unsupported_phase", + ) + ) ) - return pb2.HttpRequestResult(decision=pb2.DECISION_ALLOW) + return pb2.HttpRequestHookResult( + preflight_result=pb2.HttpPreflightResult(continue_without_body=pb2.HttpContinue()) + ) + + +def evaluate_http_request_body(body: pb2.HttpWholeBody) -> pb2.HttpRequestHookResult: + """Keep, replace, or deny a complete body after preflight selected whole-body inspection.""" + return pb2.HttpRequestHookResult( + whole_body_result=pb2.HttpWholeBodyResult(unchanged=pb2.HttpUnchanged()) + ) + + +def evaluate_http_request_event( + event: pb2.HttpRequestHookEvent, +) -> pb2.HttpRequestHookResult | None: + """Answer one hook stream event, or return None for an event that takes no result.""" + if event.HasField("preflight"): + return evaluate_http_request_preflight(event.preflight) + if event.HasField("whole_body"): + return evaluate_http_request_body(event.whole_body) + return None -class Middleware(pb2_grpc.SupervisorMiddlewareServicer): +class Middleware(pb2_grpc.SupervisorMiddlewareServicer, pb2_grpc.HttpHooksServicer): """Adapt gRPC calls to the middleware's application functions.""" async def Describe( self, - request: object, + request: pb2.MiddlewareDescribeRequest, context: grpc.aio.ServicerContext, ) -> pb2.MiddlewareManifest: + mismatch = find_protocol_mismatch(request) + if mismatch is not None: + await context.abort(grpc.StatusCode.FAILED_PRECONDITION, mismatch) return build_manifest() async def ValidateConfig( @@ -68,12 +128,15 @@ async def ValidateConfig( ) -> pb2.ValidateConfigResponse: return validate_config(request) - async def EvaluateHttpRequest( + async def EvaluateHttpRequestHook( self, - request: pb2.HttpRequestEvaluation, + request_iterator: AsyncIterator[pb2.HttpRequestHookEvent], context: grpc.aio.ServicerContext, - ) -> pb2.HttpRequestResult: - return evaluate_http_request(request) + ) -> AsyncIterator[pb2.HttpRequestHookResult]: + async for event in request_iterator: + result = evaluate_http_request_event(event) + if result is not None: + yield result def create_server() -> grpc.aio.Server: @@ -84,7 +147,9 @@ def create_server() -> grpc.aio.Server: ("grpc.max_send_message_length", MAX_MESSAGE_BYTES), ) ) - pb2_grpc.add_SupervisorMiddlewareServicer_to_server(Middleware(), server) + middleware = Middleware() + pb2_grpc.add_SupervisorMiddlewareServicer_to_server(middleware, server) + pb2_grpc.add_HttpHooksServicer_to_server(middleware, server) return server diff --git a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/tests/test_server.py b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/tests/test_server.py index 4c5eadc4..c177f146 100644 --- a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/tests/test_server.py +++ b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/tests/test_server.py @@ -2,30 +2,102 @@ # SPDX-License-Identifier: Apache-2.0 import asyncio +from collections.abc import AsyncIterator, Awaitable, Callable import grpc +import pytest +from __PACKAGE_NAME__.bindings import extension_pb2 from __PACKAGE_NAME__.bindings import supervisor_middleware_pb2 as pb2 from __PACKAGE_NAME__.bindings import supervisor_middleware_pb2_grpc as pb2_grpc from __PACKAGE_NAME__.server import ( - MAX_BODY_BYTES, + CONTRACT_CAPABILITY, + HTTP_HOOKS_CAPABILITY, MAX_MESSAGE_BYTES, + MAX_PAYLOAD_BYTES, SERVICE_NAME, build_manifest, create_server, - evaluate_http_request, + evaluate_http_request_body, + evaluate_http_request_event, + evaluate_http_request_preflight, + find_protocol_mismatch, validate_config, ) -def test_manifest_advertises_pre_credentials_http() -> None: +def caller_metadata( + *, + major: int = 1, + supported: tuple[str, ...] = (CONTRACT_CAPABILITY, HTTP_HOOKS_CAPABILITY), + required: tuple[str, ...] = (CONTRACT_CAPABILITY,), +) -> pb2.MiddlewareDescribeRequest: + return pb2.MiddlewareDescribeRequest( + gateway=extension_pb2.PeerMetadata( + protocol_version=extension_pb2.ProtocolVersion(major=major, minor=0), + implementation_name="openshell/gateway", + implementation_version="test", + supported_capabilities=supported, + required_capabilities=required, + ) + ) + + +def run_with_server(exercise: Callable[[grpc.aio.Channel], Awaitable[None]]) -> None: + async def run() -> None: + server = create_server() + port = server.add_insecure_port("127.0.0.1:0") + assert port != 0 + await server.start() + options = ( + ("grpc.max_send_message_length", MAX_MESSAGE_BYTES), + ("grpc.max_receive_message_length", MAX_MESSAGE_BYTES), + ) + try: + async with grpc.aio.insecure_channel(f"127.0.0.1:{port}", options=options) as channel: + await exercise(channel) + finally: + await server.stop(grace=0) + + asyncio.run(run()) + + +def test_manifest_advertises_pre_credentials_http_hooks() -> None: manifest = build_manifest() assert manifest.name == SERVICE_NAME assert len(manifest.bindings) == 1 assert manifest.bindings[0].operation == pb2.SUPERVISOR_MIDDLEWARE_OPERATION_HTTP_REQUEST assert manifest.bindings[0].phase == pb2.SUPERVISOR_MIDDLEWARE_PHASE_PRE_CREDENTIALS - assert manifest.bindings[0].max_body_bytes == MAX_BODY_BYTES + assert manifest.bindings[0].max_payload_bytes == MAX_PAYLOAD_BYTES + assert manifest.extension.protocol_version.major == 1 + assert manifest.extension.protocol_version.minor == 0 + assert manifest.extension.implementation_name == SERVICE_NAME + assert CONTRACT_CAPABILITY in manifest.extension.supported_capabilities + assert HTTP_HOOKS_CAPABILITY in manifest.extension.supported_capabilities + assert HTTP_HOOKS_CAPABILITY in manifest.extension.required_capabilities + + +def test_compatible_caller_has_no_protocol_mismatch() -> None: + assert find_protocol_mismatch(caller_metadata()) is None + + +@pytest.mark.parametrize( + ("request_message", "reason"), + [ + (pb2.MiddlewareDescribeRequest(), "did not provide protocol metadata"), + (caller_metadata(major=2), "unsupported protocol major 2"), + (caller_metadata(supported=(CONTRACT_CAPABILITY,)), HTTP_HOOKS_CAPABILITY), + (caller_metadata(required=("example.unknown",)), "example.unknown"), + ], +) +def test_incompatible_caller_is_explained( + request_message: pb2.MiddlewareDescribeRequest, reason: str +) -> None: + mismatch = find_protocol_mismatch(request_message) + + assert mismatch is not None + assert reason in mismatch def test_default_config_is_valid() -> None: @@ -35,54 +107,82 @@ def test_default_config_is_valid() -> None: assert response.reason == "" -def test_valid_request_is_allowed_without_mutation() -> None: - response = evaluate_http_request( - pb2.HttpRequestEvaluation( +def test_valid_request_continues_without_mutation() -> None: + result = evaluate_http_request_preflight( + pb2.HttpRequestHookPreflight( phase=pb2.SUPERVISOR_MIDDLEWARE_PHASE_PRE_CREDENTIALS, ) ) - assert response.decision == pb2.DECISION_ALLOW - assert response.has_body is False - assert response.header_mutations == [] + assert result.WhichOneof("result") == "preflight_result" + assert result.preflight_result.WhichOneof("decision") == "continue_without_body" + assert result.preflight_result.header_mutations == [] def test_unsupported_phase_is_denied() -> None: - response = evaluate_http_request(pb2.HttpRequestEvaluation()) + result = evaluate_http_request_preflight(pb2.HttpRequestHookPreflight()) - assert response.decision == pb2.DECISION_DENY - assert response.reason_code == "unsupported_phase" + assert result.WhichOneof("result") == "deny" + assert result.deny.diagnostics.reason_code == "unsupported_phase" -def test_transport_accepts_maximum_body_inside_full_envelope() -> None: - async def exercise() -> None: - server = create_server() - port = server.add_insecure_port("127.0.0.1:0") - assert port != 0 - await server.start() - options = ( - ("grpc.max_send_message_length", MAX_MESSAGE_BYTES), - ("grpc.max_receive_message_length", MAX_MESSAGE_BYTES), +def test_whole_body_is_kept_unchanged() -> None: + result = evaluate_http_request_body(pb2.HttpWholeBody(data=b"request body")) + + assert result.WhichOneof("result") == "whole_body_result" + assert result.whole_body_result.WhichOneof("body") == "unchanged" + + +def test_events_without_results_are_ignored() -> None: + assert evaluate_http_request_event(pb2.HttpRequestHookEvent(begin=pb2.HttpBegin())) is None + assert ( + evaluate_http_request_event( + pb2.HttpRequestHookEvent(session_end=pb2.MiddlewareSessionEnd()) ) - try: - async with grpc.aio.insecure_channel(f"127.0.0.1:{port}", options=options) as channel: - stub = pb2_grpc.SupervisorMiddlewareStub(channel) - response = await stub.EvaluateHttpRequest( - pb2.HttpRequestEvaluation( - phase=pb2.SUPERVISOR_MIDDLEWARE_PHASE_PRE_CREDENTIALS, - context=pb2.RequestContext( - request_id="max-body-request", - sandbox_id="max-body-sandbox", - ), - headers=[ - pb2.HttpHeader(name="content-type", value="application/octet-stream") - ], - body=b"x" * MAX_BODY_BYTES, - middleware_name=SERVICE_NAME, - ) - ) - finally: - await server.stop(grace=0) - assert response.decision == pb2.DECISION_ALLOW + is None + ) + + +def test_describe_negotiates_with_the_caller() -> None: + async def exercise(channel: grpc.aio.Channel) -> None: + stub = pb2_grpc.SupervisorMiddlewareStub(channel) + + manifest = await stub.Describe(caller_metadata()) + assert manifest.name == SERVICE_NAME + + with pytest.raises(grpc.aio.AioRpcError) as error: + await stub.Describe(pb2.MiddlewareDescribeRequest()) + assert error.value.code() == grpc.StatusCode.FAILED_PRECONDITION + + run_with_server(exercise) + + +def test_hook_stream_answers_preflight_and_maximum_body() -> None: + async def events() -> AsyncIterator[pb2.HttpRequestHookEvent]: + yield pb2.HttpRequestHookEvent( + preflight=pb2.HttpRequestHookPreflight( + phase=pb2.SUPERVISOR_MIDDLEWARE_PHASE_PRE_CREDENTIALS, + context=pb2.RequestContext( + request_id="max-body-request", + sandbox_id="max-body-sandbox", + ), + middleware_name=SERVICE_NAME, + request=pb2.HttpRequestPreflightHead( + headers=[pb2.HttpHeader(name="content-type", value="application/octet-stream")], + ), + ) + ) + yield pb2.HttpRequestHookEvent(begin=pb2.HttpBegin()) + yield pb2.HttpRequestHookEvent(whole_body=pb2.HttpWholeBody(data=b"x" * MAX_PAYLOAD_BYTES)) + yield pb2.HttpRequestHookEvent(session_end=pb2.MiddlewareSessionEnd()) + + async def exercise(channel: grpc.aio.Channel) -> None: + stub = pb2_grpc.HttpHooksStub(channel) + results = [result async for result in stub.EvaluateHttpRequestHook(events())] + + assert [result.WhichOneof("result") for result in results] == [ + "preflight_result", + "whole_body_result", + ] - asyncio.run(exercise()) + run_with_server(exercise) diff --git a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/README.md b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/README.md index c9e6c0fb..a5a9cd62 100644 --- a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/README.md +++ b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/README.md @@ -2,7 +2,11 @@ A Rust OpenShell supervisor middleware starter. It is pinned to the OpenShell contract recorded in `.openshell-middleware-manifest.json` and starts as a pass-through: -valid pre-credentials HTTP requests are allowed without mutation. +valid pre-credentials HTTP requests continue without mutation. + +The service implements OpenShell's HTTP hooks and requires the +`openshell.supervisor-middleware.http-hooks` capability. Use it with a gateway +and sandbox supervisors running OpenShell v0.1.9 or newer. ## Develop @@ -20,10 +24,40 @@ Start the middleware on loopback for local development: cargo run --locked -- 127.0.0.1:50051 ``` -The service implementation is in `src/lib.rs`. Extend `validate_config` and -`evaluate_http_request` with your policy and request handling. Keep transport -adaptation at this boundary and move substantial domain logic into separate -modules. +The service implementation is in `src/lib.rs`. Extend `validate_config`, +`evaluate_http_request_preflight`, and `evaluate_http_request_body` with your +policy and request handling. Keep transport adaptation at this boundary and +move substantial domain logic into separate modules. + +`evaluate_http_request_preflight` receives the request target, headers, and +policy config. It can continue, deny, or change headers. To inspect or replace +the body, select whole-body inspection when OpenShell offers it: + +```rust +let whole_body = pb::HttpBodyMode::WholeBody as i32; +if preflight.permitted_body_modes.contains(&whole_body) { + let max_body_bytes = preflight + .limits + .as_ref() + .map_or(0, |limits| limits.max_whole_body_bytes); + return pb::HttpRequestHookResult { + result: Some(HookResult::PreflightResult(pb::HttpPreflightResult { + decision: Some(pb::http_preflight_result::Decision::Inspect( + pb::HttpInspect { + mode: Some(pb::http_inspect::Mode::WholeBody( + pb::HttpWholeBodyMode { max_body_bytes }, + )), + }, + )), + ..Default::default() + })), + }; +} +``` + +OpenShell then sends the complete body to `evaluate_http_request_body`. The starter +does not implement streaming (DUPLEX) inspection; selecting it requires handling +the `input_chunk` and `input_end` events in `evaluate_http_request_event`. ## Connect OpenShell @@ -34,13 +68,15 @@ the development server to a reachable interface: cargo run --locked -- 0.0.0.0:50051 ``` -Register the running service in the gateway configuration: +Start the service before the gateway, then register it in the gateway +configuration and restart the gateway: ```toml [[openshell.supervisor.middleware]] name = "__SERVICE_NAME__" grpc_endpoint = "http://:50051" -max_body_bytes = 4194304 +allow_insecure_transport = true +max_payload_bytes = 4194304 timeout = "500ms" ``` @@ -48,9 +84,23 @@ Replace `` with a host IP or DNS name reachable from both the gateway and sandbox supervisors; loopback works only when every process shares the middleware's network namespace. Binding outside loopback is an explicit opt-in because the development server is unauthenticated and insecure; -restrict port exposure to trusted networks. Then reference `__SERVICE_NAME__` from -a sandbox policy's middleware stage. Review the supervisor middleware documentation -for the policy syntax supported by your pinned OpenShell release. +restrict port exposure to trusted networks. `allow_insecure_transport` lets a +gateway that signs extension tokens call this plaintext endpoint without one. + +Attach the registered service to destination hosts in a sandbox policy: + +```yaml +network_middlewares: + __SERVICE_NAME__: + middleware: __SERVICE_NAME__ + endpoints: + include: + - api.example.com +``` + +OpenShell blocks matching requests while the service is unavailable, because +HTTP hook middleware always fails closed. Review the supervisor middleware +documentation for the policy syntax supported by your pinned OpenShell release. ## Version-matched generated files diff --git a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/build.rs b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/build.rs index ff030cc9..50b0f596 100644 --- a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/build.rs +++ b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/build.rs @@ -6,7 +6,7 @@ fn main() -> Result<(), Box> { std::env::set_var("PROTOC", protobuf_src::protoc()); } - println!("cargo:rerun-if-changed=proto/supervisor_middleware.proto"); + println!("cargo:rerun-if-changed=proto"); tonic_prost_build::configure() .build_client(true) .build_server(true) diff --git a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/src/lib.rs b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/src/lib.rs index 51f6c954..95b70848 100644 --- a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/src/lib.rs +++ b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/src/lib.rs @@ -1,17 +1,41 @@ //! Pass-through OpenShell supervisor middleware service. -use tonic::{Request, Response, Status}; +use std::pin::Pin; -pub mod pb { - tonic::include_proto!("openshell.middleware.v1"); +use tokio_stream::{Stream, StreamExt}; +use tonic::{Request, Response, Status, Streaming}; + +mod proto { + pub mod extension { + pub mod v1 { + tonic::include_proto!("openshell.extension.v1"); + } + } + pub mod middleware { + pub mod v1 { + tonic::include_proto!("openshell.middleware.v1"); + } + } } +pub use proto::extension::v1 as extension; +pub use proto::middleware::v1 as pb; + +use pb::http_hooks_server::{HttpHooks, HttpHooksServer}; use pb::supervisor_middleware_server::{SupervisorMiddleware, SupervisorMiddlewareServer}; pub const SERVICE_NAME: &str = "__SERVICE_NAME__"; pub const SERVICE_VERSION: &str = "0.1.0"; -pub const MAX_BODY_BYTES: u64 = 4 * 1024 * 1024; -pub const MAX_MESSAGE_BYTES: usize = MAX_BODY_BYTES as usize + 1024 * 1024; +pub const PROTOCOL_MAJOR: u32 = 1; +pub const PROTOCOL_MINOR: u32 = 0; +pub const CONTRACT_CAPABILITY: &str = "openshell.supervisor-middleware.contract"; +pub const HTTP_HOOKS_CAPABILITY: &str = "openshell.supervisor-middleware.http-hooks"; +pub const CAPABILITIES: [&str; 2] = [CONTRACT_CAPABILITY, HTTP_HOOKS_CAPABILITY]; +pub const MAX_PAYLOAD_BYTES: u64 = 4 * 1024 * 1024; +pub const MAX_MESSAGE_BYTES: usize = MAX_PAYLOAD_BYTES as usize + 1024 * 1024; + +/// Ordered results that a streaming RPC returns to OpenShell. +pub type ResultStream = Pin> + Send>>; #[derive(Debug, Default)] pub struct Middleware; @@ -22,19 +46,81 @@ pub fn middleware_service() -> SupervisorMiddlewareServer { .max_encoding_message_size(MAX_MESSAGE_BYTES) } +pub fn http_hooks_service() -> HttpHooksServer { + HttpHooksServer::new(Middleware) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES) +} + pub fn build_manifest() -> pb::MiddlewareManifest { + let capabilities: Vec = CAPABILITIES.iter().map(ToString::to_string).collect(); pb::MiddlewareManifest { name: SERVICE_NAME.to_owned(), - service_version: SERVICE_VERSION.to_owned(), bindings: vec![pb::MiddlewareBinding { operation: pb::SupervisorMiddlewareOperation::HttpRequest as i32, phase: pb::SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: MAX_BODY_BYTES, - timeout: String::new(), + max_payload_bytes: MAX_PAYLOAD_BYTES, + ..Default::default() }], + // Requiring the HTTP hooks capability selects HttpHooks for the HTTP binding. + extension: Some(extension::PeerMetadata { + protocol_version: Some(extension::ProtocolVersion { + major: PROTOCOL_MAJOR, + minor: PROTOCOL_MINOR, + }), + implementation_name: SERVICE_NAME.to_owned(), + implementation_version: SERVICE_VERSION.to_owned(), + supported_capabilities: capabilities.clone(), + required_capabilities: capabilities, + }), + ..Default::default() } } +/// Explain why the calling gateway or supervisor cannot use this service. +pub fn find_protocol_mismatch(request: &pb::MiddlewareDescribeRequest) -> Option { + let Some(caller) = &request.gateway else { + return Some("the caller did not provide protocol metadata".to_owned()); + }; + let major = caller + .protocol_version + .as_ref() + .map_or(0, |version| version.major); + if major != PROTOCOL_MAJOR { + return Some(format!( + "the caller uses unsupported protocol major {major}" + )); + } + let missing: Vec<&str> = CAPABILITIES + .into_iter() + .filter(|capability| { + !caller + .supported_capabilities + .iter() + .any(|c| c == capability) + }) + .collect(); + if !missing.is_empty() { + return Some(format!( + "the caller does not support required capabilities: {}", + missing.join(", ") + )); + } + let unsupported: Vec<&str> = caller + .required_capabilities + .iter() + .map(String::as_str) + .filter(|capability| !CAPABILITIES.contains(capability)) + .collect(); + if !unsupported.is_empty() { + return Some(format!( + "the caller requires unsupported capabilities: {}", + unsupported.join(", ") + )); + } + None +} + pub fn validate_config(_request: pb::ValidateConfigRequest) -> pb::ValidateConfigResponse { pb::ValidateConfigResponse { valid: true, @@ -42,27 +128,71 @@ pub fn validate_config(_request: pb::ValidateConfigRequest) -> pb::ValidateConfi } } -pub fn evaluate_http_request(request: pb::HttpRequestEvaluation) -> pb::HttpRequestResult { - if request.phase != pb::SupervisorMiddlewarePhase::PreCredentials as i32 { - return pb::HttpRequestResult { - decision: pb::Decision::Deny as i32, - reason: "unsupported middleware phase".to_owned(), - reason_code: "unsupported_phase".to_owned(), - ..Default::default() +/// Decide from the request head whether to continue, deny, or inspect the body. +pub fn evaluate_http_request_preflight( + preflight: pb::HttpRequestHookPreflight, +) -> pb::HttpRequestHookResult { + use pb::http_request_hook_result::Result as HookResult; + + if preflight.phase != pb::SupervisorMiddlewarePhase::PreCredentials as i32 { + return pb::HttpRequestHookResult { + result: Some(HookResult::Deny(pb::HttpDenial { + diagnostics: Some(pb::MiddlewareDiagnostics { + reason: "unsupported middleware phase".to_owned(), + reason_code: "unsupported_phase".to_owned(), + ..Default::default() + }), + })), }; } - pb::HttpRequestResult { - decision: pb::Decision::Allow as i32, - ..Default::default() + pb::HttpRequestHookResult { + result: Some(HookResult::PreflightResult(pb::HttpPreflightResult { + decision: Some(pb::http_preflight_result::Decision::ContinueWithoutBody( + pb::HttpContinue {}, + )), + ..Default::default() + })), + } +} + +/// Keep, replace, or deny a complete body after preflight selected whole-body inspection. +pub fn evaluate_http_request_body(_body: pb::HttpWholeBody) -> pb::HttpRequestHookResult { + pb::HttpRequestHookResult { + result: Some(pb::http_request_hook_result::Result::WholeBodyResult( + pb::HttpWholeBodyResult { + body: Some(pb::http_whole_body_result::Body::Unchanged( + pb::HttpUnchanged {}, + )), + ..Default::default() + }, + )), + } +} + +/// Answer one hook stream event, or return `None` for an event that takes no result. +pub fn evaluate_http_request_event( + event: pb::HttpRequestHookEvent, +) -> Option { + use pb::http_request_hook_event::Event; + + match event.event? { + Event::Preflight(preflight) => Some(evaluate_http_request_preflight(preflight)), + Event::WholeBody(body) => Some(evaluate_http_request_body(body)), + _ => None, } } #[tonic::async_trait] impl SupervisorMiddleware for Middleware { + type EvaluateWebSocketSessionStream = ResultStream; + async fn describe( &self, - _request: Request<()>, + request: Request, ) -> Result, Status> { + if let Some(mismatch) = find_protocol_mismatch(request.get_ref()) { + return Err(Status::failed_precondition(mismatch)); + } Ok(Response::new(build_manifest())) } @@ -73,86 +203,282 @@ impl SupervisorMiddleware for Middleware { Ok(Response::new(validate_config(request.into_inner()))) } + // Legacy HTTP hook that OpenShell deprecates for removal in 0.2.0. Delete this + // method when a contract update drops the RPC. async fn evaluate_http_request( &self, - request: Request, + _request: Request, ) -> Result, Status> { - Ok(Response::new(evaluate_http_request(request.into_inner()))) + Err(Status::unimplemented("this service implements HTTP hooks")) + } + + async fn evaluate_web_socket_session( + &self, + _request: Request>, + ) -> Result, Status> { + Err(Status::unimplemented( + "this service declares no WebSocket binding", + )) + } +} + +#[tonic::async_trait] +impl HttpHooks for Middleware { + type EvaluateHttpRequestHookStream = ResultStream; + type EvaluateHttpResponseHookStream = ResultStream; + + async fn evaluate_http_request_hook( + &self, + request: Request>, + ) -> Result, Status> { + let results = request.into_inner().filter_map(|event| match event { + Ok(event) => evaluate_http_request_event(event).map(Ok), + Err(status) => Some(Err(status)), + }); + Ok(Response::new(Box::pin(results))) + } + + async fn evaluate_http_response_hook( + &self, + _request: Request>, + ) -> Result, Status> { + Err(Status::unimplemented( + "this service declares no HTTP response binding", + )) } } #[cfg(test)] mod tests { use super::*; + use pb::http_hooks_client::HttpHooksClient; + use pb::http_request_hook_event::Event; + use pb::http_request_hook_result::Result as HookResult; use pb::supervisor_middleware_client::SupervisorMiddlewareClient; use tokio::net::TcpListener; + use tokio::task::JoinHandle; use tokio_stream::wrappers::TcpListenerStream; + use tonic::Code; use tonic::transport::Server; + fn caller_metadata( + major: u32, + supported: &[&str], + required: &[&str], + ) -> pb::MiddlewareDescribeRequest { + pb::MiddlewareDescribeRequest { + gateway: Some(extension::PeerMetadata { + protocol_version: Some(extension::ProtocolVersion { major, minor: 0 }), + implementation_name: "openshell/gateway".to_owned(), + implementation_version: "test".to_owned(), + supported_capabilities: supported.iter().map(ToString::to_string).collect(), + required_capabilities: required.iter().map(ToString::to_string).collect(), + }), + } + } + + fn compatible_caller() -> pb::MiddlewareDescribeRequest { + caller_metadata(PROTOCOL_MAJOR, &CAPABILITIES, &[CONTRACT_CAPABILITY]) + } + + async fn serve() -> (String, JoinHandle<()>) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + Server::builder() + .add_service(middleware_service()) + .add_service(http_hooks_service()) + .serve_with_incoming(TcpListenerStream::new(listener)) + .await + .unwrap(); + }); + (format!("http://{address}"), server) + } + #[test] - fn manifest_advertises_pre_credentials_http() { + fn manifest_advertises_pre_credentials_http_hooks() { let manifest = build_manifest(); assert_eq!(manifest.name, SERVICE_NAME); assert_eq!(manifest.bindings.len(), 1); - assert_eq!(manifest.bindings[0].max_body_bytes, MAX_BODY_BYTES); + assert_eq!( + manifest.bindings[0].operation, + pb::SupervisorMiddlewareOperation::HttpRequest as i32 + ); + assert_eq!( + manifest.bindings[0].phase, + pb::SupervisorMiddlewarePhase::PreCredentials as i32 + ); + assert_eq!(manifest.bindings[0].max_payload_bytes, MAX_PAYLOAD_BYTES); + let extension = manifest.extension.unwrap(); + assert_eq!( + extension.protocol_version, + Some(extension::ProtocolVersion { major: 1, minor: 0 }) + ); + assert_eq!(extension.implementation_name, SERVICE_NAME); + assert_eq!(extension.supported_capabilities, CAPABILITIES); + assert_eq!(extension.required_capabilities, CAPABILITIES); + } + + #[test] + fn compatible_caller_has_no_protocol_mismatch() { + assert_eq!(find_protocol_mismatch(&compatible_caller()), None); } #[test] - fn valid_request_is_allowed_without_mutation() { - let response = evaluate_http_request(pb::HttpRequestEvaluation { + fn incompatible_caller_is_explained() { + let cases = [ + ( + pb::MiddlewareDescribeRequest::default(), + "did not provide protocol metadata", + ), + ( + caller_metadata(2, &CAPABILITIES, &[CONTRACT_CAPABILITY]), + "unsupported protocol major 2", + ), + ( + caller_metadata(1, &[CONTRACT_CAPABILITY], &[CONTRACT_CAPABILITY]), + HTTP_HOOKS_CAPABILITY, + ), + ( + caller_metadata(1, &CAPABILITIES, &["example.unknown"]), + "example.unknown", + ), + ]; + for (request, reason) in cases { + let mismatch = find_protocol_mismatch(&request).unwrap(); + assert!(mismatch.contains(reason), "{mismatch}"); + } + } + + #[test] + fn default_config_is_valid() { + let response = validate_config(pb::ValidateConfigRequest::default()); + assert!(response.valid); + assert!(response.reason.is_empty()); + } + + #[test] + fn valid_request_continues_without_mutation() { + let result = evaluate_http_request_preflight(pb::HttpRequestHookPreflight { phase: pb::SupervisorMiddlewarePhase::PreCredentials as i32, ..Default::default() }); - assert_eq!(response.decision, pb::Decision::Allow as i32); - assert!(!response.has_body); - assert!(response.header_mutations.is_empty()); + let Some(HookResult::PreflightResult(preflight_result)) = result.result else { + panic!("expected a preflight result"); + }; + assert_eq!( + preflight_result.decision, + Some(pb::http_preflight_result::Decision::ContinueWithoutBody( + pb::HttpContinue {} + )) + ); + assert!(preflight_result.header_mutations.is_empty()); } #[test] fn unsupported_phase_is_denied() { - let response = evaluate_http_request(pb::HttpRequestEvaluation::default()); - assert_eq!(response.decision, pb::Decision::Deny as i32); - assert_eq!(response.reason_code, "unsupported_phase"); + let result = evaluate_http_request_preflight(pb::HttpRequestHookPreflight::default()); + let Some(HookResult::Deny(denial)) = result.result else { + panic!("expected a denial"); + }; + assert_eq!(denial.diagnostics.unwrap().reason_code, "unsupported_phase"); } - #[tokio::test] - async fn transport_accepts_maximum_body_inside_full_envelope() { - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let server = tokio::spawn(async move { - Server::builder() - .add_service(middleware_service()) - .serve_with_incoming(TcpListenerStream::new(listener)) - .await - .unwrap(); + #[test] + fn whole_body_is_kept_unchanged() { + let result = evaluate_http_request_body(pb::HttpWholeBody { + data: b"request body".to_vec(), + ..Default::default() }); - let mut client = SupervisorMiddlewareClient::connect(format!("http://{address}")) + let Some(HookResult::WholeBodyResult(body_result)) = result.result else { + panic!("expected a whole-body result"); + }; + assert_eq!( + body_result.body, + Some(pb::http_whole_body_result::Body::Unchanged( + pb::HttpUnchanged {} + )) + ); + } + + #[test] + fn events_without_results_are_ignored() { + for event in [ + Event::Begin(pb::HttpBegin::default()), + Event::SessionEnd(pb::MiddlewareSessionEnd::default()), + ] { + let result = + evaluate_http_request_event(pb::HttpRequestHookEvent { event: Some(event) }); + assert_eq!(result, None); + } + } + + #[tokio::test] + async fn describe_negotiates_with_the_caller() { + let (endpoint, server) = serve().await; + let mut client = SupervisorMiddlewareClient::connect(endpoint).await.unwrap(); + + let manifest = client.describe(compatible_caller()).await.unwrap(); + assert_eq!(manifest.into_inner().name, SERVICE_NAME); + + let status = client + .describe(pb::MiddlewareDescribeRequest::default()) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + server.abort(); + } + + #[tokio::test] + async fn hook_stream_answers_preflight_and_maximum_body() { + let (endpoint, server) = serve().await; + let mut client = HttpHooksClient::connect(endpoint) .await .unwrap() .max_encoding_message_size(MAX_MESSAGE_BYTES) .max_decoding_message_size(MAX_MESSAGE_BYTES); - - let response = client - .evaluate_http_request(pb::HttpRequestEvaluation { + let events = [ + Event::Preflight(pb::HttpRequestHookPreflight { phase: pb::SupervisorMiddlewarePhase::PreCredentials as i32, context: Some(pb::RequestContext { request_id: "max-body-request".to_owned(), sandbox_id: "max-body-sandbox".to_owned(), ..Default::default() }), - headers: vec![pb::HttpHeader { - name: "content-type".to_owned(), - value: "application/octet-stream".to_owned(), - }], - body: vec![b'x'; MAX_BODY_BYTES as usize], middleware_name: SERVICE_NAME.to_owned(), + request: Some(pb::HttpRequestPreflightHead { + headers: vec![pb::HttpHeader { + name: "content-type".to_owned(), + value: "application/octet-stream".to_owned(), + }], + ..Default::default() + }), + ..Default::default() + }), + Event::Begin(pb::HttpBegin::default()), + Event::WholeBody(pb::HttpWholeBody { + data: vec![b'x'; MAX_PAYLOAD_BYTES as usize], ..Default::default() - }) + }), + Event::SessionEnd(pb::MiddlewareSessionEnd::default()), + ] + .map(|event| pb::HttpRequestHookEvent { event: Some(event) }); + + let mut results = client + .evaluate_http_request_hook(tokio_stream::iter(events)) .await .unwrap() .into_inner(); + let mut kinds = Vec::new(); + while let Some(result) = results.message().await.unwrap() { + kinds.push(match result.result { + Some(HookResult::PreflightResult(_)) => "preflight_result", + Some(HookResult::WholeBodyResult(_)) => "whole_body_result", + _ => "unexpected", + }); + } - assert_eq!(response.decision, pb::Decision::Allow as i32); + assert_eq!(kinds, ["preflight_result", "whole_body_result"]); server.abort(); } } diff --git a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/src/main.rs b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/src/main.rs index 7af6266b..037b54e7 100644 --- a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/src/main.rs +++ b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/src/main.rs @@ -12,6 +12,7 @@ async fn main() -> Result<(), Box> { println!("serving __SERVICE_NAME__ on {address}"); Server::builder() .add_service(__RUST_LIB_NAME__::middleware_service()) + .add_service(__RUST_LIB_NAME__::http_hooks_service()) .serve(address) .await?; Ok(()) diff --git a/projects/tools/openshell-middleware-manager/tests/test_generator.py b/projects/tools/openshell-middleware-manager/tests/test_generator.py index 5ccff60e..409e9d59 100644 --- a/projects/tools/openshell-middleware-manager/tests/test_generator.py +++ b/projects/tools/openshell-middleware-manager/tests/test_generator.py @@ -6,6 +6,7 @@ import ctypes import email.message import errno +import hashlib import http.client import json import os @@ -22,17 +23,52 @@ PROTO = b"""syntax = "proto3"; package openshell.middleware.v1; +import "google/protobuf/struct.proto"; service SupervisorMiddleware { rpc EvaluateHttpRequest(HttpRequestEvaluation) returns (HttpRequestResult); } +service HttpHooks { + rpc EvaluateHttpRequestHook(stream HttpRequestHookEvent) returns (stream HttpRequestHookResult); +} message HttpRequestEvaluation {} message HttpRequestResult {} +message HttpRequestHookEvent {} +message HttpRequestHookResult {} """ UPDATED_PROTO = PROTO + b"// refreshed contract\n" +IMPORTING_PROTO = PROTO.replace( + b'import "google/protobuf/struct.proto";', + b'import "google/protobuf/struct.proto";\nimport "extension.proto";', +) +EXTENSION_PROTO = b"""syntax = "proto3"; +package openshell.extension.v1; +message PeerMetadata {} +""" + + +def local_proto(version: str, name: str) -> tuple[bytes, str]: + assert name == "supervisor_middleware.proto" + return PROTO, f"https://example.test/OpenShell/{version}/{name}" + + +def contract_downloader(files: dict[str, bytes]) -> generator.DownloadProto: + def download(version: str, name: str) -> tuple[bytes, str]: + return files[name], f"https://example.test/OpenShell/{version}/proto/{name}" + + return download -def local_proto(version: str) -> tuple[bytes, str]: - return PROTO, f"https://example.test/OpenShell/{version}/supervisor_middleware.proto" +def write_manifest(project: Path, *, proto_imports: list[str]) -> None: + (project / ".openshell-middleware-manifest.json").write_text( + json.dumps( + { + "generator": {"name": "openshell-middleware-manager"}, + "languages": ["python"], + "python_package": "audit_headers", + "proto_imports": [{"name": name} for name in proto_imports], + } + ) + ) def no_op_runner(language: str, project: Path, package: str) -> None: @@ -96,6 +132,126 @@ def test_generates_rust_project_with_normalized_crate_name(tmp_path: Path) -> No assert manifest["python_package"] is None +def test_create_downloads_and_records_imported_contract_files(tmp_path: Path) -> None: + destination = tmp_path / "audit-headers" + requested: list[str] = [] + files = {"supervisor_middleware.proto": IMPORTING_PROTO, "extension.proto": EXTENSION_PROTO} + + def download(version: str, name: str) -> tuple[bytes, str]: + requested.append(name) + return contract_downloader(files)(version, name) + + create_project( + name="audit-headers", + language="python", + requested_version="v1.2.3", + destination=destination, + download_proto=download, + command_runner=no_op_runner, + ) + + assert requested == ["supervisor_middleware.proto", "extension.proto"] + assert (destination / "proto/supervisor_middleware.proto").read_bytes() == IMPORTING_PROTO + assert (destination / "proto/extension.proto").read_bytes() == EXTENSION_PROTO + manifest = json.loads((destination / ".openshell-middleware-manifest.json").read_text()) + assert manifest["proto_source"].endswith("/v1.2.3/proto/supervisor_middleware.proto") + assert manifest["proto_sha256"] == hashlib.sha256(IMPORTING_PROTO).hexdigest() + assert manifest["proto_imports"] == [ + { + "name": "extension.proto", + "source": "https://example.test/OpenShell/v1.2.3/proto/extension.proto", + "sha256": hashlib.sha256(EXTENSION_PROTO).hexdigest(), + } + ] + + +def test_contract_download_follows_each_openshell_import_once() -> None: + files = { + "supervisor_middleware.proto": PROTO + b'import "b.proto";\nimport public "a.proto";\n', + "a.proto": ( + b'import "b.proto";\nimport "a.proto";\n// import "commented.proto";\n' + b'/* An example:\nimport "example.proto";\n*/\n' + ), + "b.proto": ( + b'import "google/protobuf/duration.proto";\nimport "supervisor_middleware.proto";\n' + ), + } + requested: list[str] = [] + + def download(version: str, name: str) -> tuple[bytes, str]: + requested.append(name) + return contract_downloader(files)(version, name) + + contract = generator._download_contract("v1.2.3", download) + + assert [proto_file.name for proto_file in contract] == [ + "supervisor_middleware.proto", + "a.proto", + "b.proto", + ] + assert sorted(requested) == ["a.proto", "b.proto", "supervisor_middleware.proto"] + + +@pytest.mark.parametrize( + "imported", + ["../outside.proto", "nested/extension.proto", "/etc/extension.proto", "extension.txt"], +) +def test_create_rejects_unsupported_import_paths(tmp_path: Path, imported: str) -> None: + proto = PROTO + f'import "{imported}";\n'.encode() + requested: list[str] = [] + + def download(version: str, name: str) -> tuple[bytes, str]: + requested.append(name) + return proto, f"https://example.test/{version}/{name}" + + with pytest.raises(ProjectError, match="unsupported proto path"): + create_project( + name="project", + language="rust", + requested_version="v1.2.3", + destination=tmp_path / "project", + download_proto=download, + command_runner=no_op_runner, + ) + + assert requested == ["supervisor_middleware.proto"] + assert list(tmp_path.iterdir()) == [] + + +def test_create_requires_the_http_hooks_contract(tmp_path: Path) -> None: + legacy_proto = PROTO.replace(b"service HttpHooks", b"service LegacyHooks") + + with pytest.raises(ProjectError, match=r"v0\.1\.8 predates the HTTP hooks.*v0\.1\.9 or newer"): + create_project( + name="project", + language="python", + requested_version="v0.1.8", + destination=tmp_path / "project", + download_proto=lambda version, name: (legacy_proto, f"https://example.test/{version}"), + command_runner=no_op_runner, + ) + + assert list(tmp_path.iterdir()) == [] + + +def test_contract_validation_accepts_a_proto_without_the_legacy_rpc(tmp_path: Path) -> None: + legacy_rpc = b" rpc EvaluateHttpRequest(HttpRequestEvaluation) returns (HttpRequestResult);\n" + assert legacy_rpc in PROTO + hooks_only_proto = PROTO.replace(legacy_rpc, b"") + + result = create_project( + name="project", + language="python", + requested_version="v0.2.0", + destination=tmp_path / "project", + download_proto=lambda version, name: (hooks_only_proto, f"https://example.test/{version}"), + command_runner=no_op_runner, + ) + + assert result.openshell_version == "v0.2.0" + assert (tmp_path / "project/proto/supervisor_middleware.proto").read_bytes() == hooks_only_proto + + def test_updates_python_generated_artifacts_and_preserves_user_code(tmp_path: Path) -> None: destination = tmp_path / "audit-headers" create_project( @@ -112,8 +268,8 @@ def test_updates_python_generated_artifacts_and_preserves_user_code(tmp_path: Pa old_binding.write_text("old generated code\n") project_inode = destination.stat().st_ino - def updated_proto(version: str) -> tuple[bytes, str]: - return UPDATED_PROTO, f"https://example.test/OpenShell/{version}/proto" + def updated_proto(version: str, name: str) -> tuple[bytes, str]: + return UPDATED_PROTO, f"https://example.test/OpenShell/{version}/proto/{name}" result = update_project( project_dir=destination, @@ -137,6 +293,259 @@ def updated_proto(version: str) -> tuple[bytes, str]: assert not list(tmp_path.glob(".audit-headers.openshell-middleware-manager.*")) +def test_update_tracks_imported_contract_files(tmp_path: Path) -> None: + destination = tmp_path / "audit" + create_project( + name="audit", + language="rust", + requested_version="v0.0.86", + destination=destination, + download_proto=local_proto, + command_runner=no_op_runner, + ) + manifest_path = destination / ".openshell-middleware-manifest.json" + manifest = json.loads(manifest_path.read_text()) + del manifest["proto_imports"] # written by generators that predate imported contract files + manifest_path.write_text(json.dumps(manifest)) + user_proto = destination / "proto/user_owned.proto" + user_proto.write_text("// user file\n") + user_proto_inode = user_proto.stat().st_ino + proto_directory_inode = (destination / "proto").stat().st_ino + + def proto_files() -> list[str]: + return sorted(path.name for path in (destination / "proto").iterdir()) + + update_project( + project_dir=destination, + requested_version="v1.2.3", + download_proto=contract_downloader( + {"supervisor_middleware.proto": IMPORTING_PROTO, "extension.proto": EXTENSION_PROTO} + ), + command_runner=no_op_runner, + ) + + assert proto_files() == ["extension.proto", "supervisor_middleware.proto", "user_owned.proto"] + assert (destination / "proto/extension.proto").read_bytes() == EXTENSION_PROTO + manifest = json.loads(manifest_path.read_text()) + assert [entry["name"] for entry in manifest["proto_imports"]] == ["extension.proto"] + + def fail_runner(language: str, project: Path, package: str) -> None: + del language, project, package + raise ProjectError("validation failed") + + replaced_import = { + "supervisor_middleware.proto": PROTO + b'import "options.proto";\n', + "options.proto": b"// options\n", + } + with pytest.raises(ProjectError, match="validation failed"): + update_project( + project_dir=destination, + requested_version="v1.2.4", + download_proto=contract_downloader(replaced_import), + command_runner=fail_runner, + ) + assert proto_files() == ["extension.proto", "supervisor_middleware.proto", "user_owned.proto"] + + update_project( + project_dir=destination, + requested_version="v1.2.4", + download_proto=contract_downloader(replaced_import), + command_runner=no_op_runner, + ) + + assert proto_files() == ["options.proto", "supervisor_middleware.proto", "user_owned.proto"] + assert user_proto.read_text() == "// user file\n" + assert user_proto.stat().st_ino == user_proto_inode + assert (destination / "proto").stat().st_ino == proto_directory_inode + assert not list(tmp_path.glob(".audit.openshell-middleware-manager.*")) + manifest = json.loads(manifest_path.read_text()) + assert [entry["name"] for entry in manifest["proto_imports"]] == ["options.proto"] + + +def test_failed_publication_restores_added_and_removed_proto_files( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + destination = tmp_path / "audit" + create_project( + name="audit", + language="rust", + requested_version="v0.1.9", + destination=destination, + download_proto=contract_downloader( + {"supervisor_middleware.proto": IMPORTING_PROTO, "extension.proto": EXTENSION_PROTO} + ), + command_runner=no_op_runner, + ) + original_manifest = (destination / ".openshell-middleware-manifest.json").read_bytes() + original_exchange = generator._publish_exchange + + def fail_lockfile_exchange(source: Path, target: Path) -> None: + if target.name == "Cargo.lock": + raise ProjectError("publication failed") + original_exchange(source, target) + + monkeypatch.setattr(generator, "_publish_exchange", fail_lockfile_exchange) + + with pytest.raises(ProjectError, match="publication failed"): + update_project( + project_dir=destination, + requested_version="v1.2.3", + download_proto=contract_downloader( + { + "supervisor_middleware.proto": PROTO + b'import "options.proto";\n', + "options.proto": b"// options\n", + } + ), + command_runner=no_op_runner, + ) + + assert sorted(path.name for path in (destination / "proto").iterdir()) == [ + "extension.proto", + "supervisor_middleware.proto", + ] + assert (destination / "proto/extension.proto").read_bytes() == EXTENSION_PROTO + assert (destination / "proto/supervisor_middleware.proto").read_bytes() == IMPORTING_PROTO + assert (destination / ".openshell-middleware-manifest.json").read_bytes() == original_manifest + + +@pytest.mark.parametrize("matches_contract", [True, False]) +def test_update_adopts_only_an_identical_unrecorded_proto_file( + tmp_path: Path, matches_contract: bool +) -> None: + destination = tmp_path / "audit" + create_project( + name="audit", + language="rust", + requested_version="v0.0.86", + destination=destination, + download_proto=local_proto, + command_runner=no_op_runner, + ) + original_manifest = (destination / ".openshell-middleware-manifest.json").read_bytes() + user_proto = destination / "proto/extension.proto" + user_content = EXTENSION_PROTO if matches_contract else b"// the user's own file\n" + user_proto.write_bytes(user_content) + + def update() -> None: + update_project( + project_dir=destination, + requested_version="v0.1.9", + download_proto=contract_downloader( + {"supervisor_middleware.proto": IMPORTING_PROTO, "extension.proto": EXTENSION_PROTO} + ), + command_runner=no_op_runner, + ) + + if matches_contract: + update() + manifest = json.loads((destination / ".openshell-middleware-manifest.json").read_text()) + assert [entry["name"] for entry in manifest["proto_imports"]] == ["extension.proto"] + else: + with pytest.raises( + ProjectError, match=r"proto/extension\.proto already exists and differs" + ): + update() + assert ( + destination / ".openshell-middleware-manifest.json" + ).read_bytes() == original_manifest + assert (destination / "proto/supervisor_middleware.proto").read_bytes() == PROTO + assert user_proto.read_bytes() == user_content + + +def test_update_does_not_overwrite_a_proto_file_created_during_validation(tmp_path: Path) -> None: + destination = tmp_path / "audit" + create_project( + name="audit", + language="rust", + requested_version="v0.0.86", + destination=destination, + download_proto=local_proto, + command_runner=no_op_runner, + ) + original_manifest = (destination / ".openshell-middleware-manifest.json").read_bytes() + concurrent_proto = destination / "proto/extension.proto" + + def create_file_during_validation(language: str, project: Path, package: str) -> None: + no_op_runner(language, project, package) + concurrent_proto.write_text("// created while omm validated the update\n") + + with pytest.raises(ProjectError, match="appeared during update"): + update_project( + project_dir=destination, + requested_version="v0.1.9", + download_proto=contract_downloader( + {"supervisor_middleware.proto": IMPORTING_PROTO, "extension.proto": EXTENSION_PROTO} + ), + command_runner=create_file_during_validation, + ) + + assert concurrent_proto.read_text() == "// created while omm validated the update\n" + assert (destination / "proto/supervisor_middleware.proto").read_bytes() == PROTO + assert (destination / ".openshell-middleware-manifest.json").read_bytes() == original_manifest + + +def test_update_does_not_require_the_http_hooks_contract(tmp_path: Path) -> None: + destination = tmp_path / "audit" + create_project( + name="audit", + language="rust", + requested_version="v0.1.9", + destination=destination, + download_proto=local_proto, + command_runner=no_op_runner, + ) + legacy_proto = PROTO.replace(b"service HttpHooks", b"service LegacyHooks") + + update_project( + project_dir=destination, + requested_version="v0.1.8", + download_proto=lambda version, name: (legacy_proto, f"https://example.test/{version}"), + command_runner=no_op_runner, + ) + + assert (destination / "proto/supervisor_middleware.proto").read_bytes() == legacy_proto + + +@pytest.mark.parametrize("updated_contract_imports_extension", [True, False]) +def test_update_refuses_symlinked_imported_proto_without_touching_target( + tmp_path: Path, updated_contract_imports_extension: bool +) -> None: + destination = tmp_path / "audit" + importing_contract = { + "supervisor_middleware.proto": IMPORTING_PROTO, + "extension.proto": EXTENSION_PROTO, + } + create_project( + name="audit", + language="rust", + requested_version="v0.1.9", + destination=destination, + download_proto=contract_downloader(importing_contract), + command_runner=no_op_runner, + ) + external = tmp_path / "external.proto" + external.write_text("external contract\n") + imported_proto = destination / "proto/extension.proto" + imported_proto.unlink() + imported_proto.symlink_to(external) + updated_contract = ( + importing_contract + if updated_contract_imports_extension + else {"supervisor_middleware.proto": UPDATED_PROTO} + ) + + with pytest.raises(ProjectError, match="must be a regular file"): + update_project( + project_dir=destination, + requested_version="v1.2.3", + download_proto=contract_downloader(updated_contract), + command_runner=no_op_runner, + ) + + assert external.read_text() == "external contract\n" + assert imported_proto.is_symlink() + + @pytest.mark.parametrize("fails", [False, True]) def test_update_custom_check_runs_before_publication( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, fails: bool @@ -203,7 +612,7 @@ def fail_runner(language: str, project: Path, package: str) -> None: update_project( project_dir=destination, requested_version="v1.2.3", - download_proto=lambda version: (UPDATED_PROTO, f"https://example.test/{version}"), + download_proto=lambda version, name: (UPDATED_PROTO, f"https://example.test/{version}"), command_runner=fail_runner, ) @@ -243,7 +652,7 @@ def fail_second_exchange(source: Path, target: Path) -> None: update_project( project_dir=destination, requested_version="v1.2.3", - download_proto=lambda version: (UPDATED_PROTO, f"https://example.test/{version}"), + download_proto=lambda version, name: (UPDATED_PROTO, f"https://example.test/{version}"), command_runner=no_op_runner, ) @@ -280,7 +689,7 @@ def fail_publication_and_rollback(source: Path, target: Path) -> None: update_project( project_dir=destination, requested_version="v1.2.3", - download_proto=lambda version: (UPDATED_PROTO, f"https://example.test/{version}"), + download_proto=lambda version, name: (UPDATED_PROTO, f"https://example.test/{version}"), command_runner=no_op_runner, ) @@ -342,6 +751,29 @@ def test_update_rejects_symlink_and_missing_project_paths(tmp_path: Path) -> Non '"languages": ["rust"], "python_package": "unexpected"}', "must set python_package", ), + ( + '{"generator": {"name": "openshell-middleware-manager"}, ' + '"languages": ["rust"], "python_package": null, "proto_imports": {}}', + "proto_imports must be a list", + ), + ( + '{"generator": {"name": "openshell-middleware-manager"}, ' + '"languages": ["rust"], "python_package": null, ' + '"proto_imports": [{"name": "../escape.proto"}]}', + "invalid proto_imports entry", + ), + ( + '{"generator": {"name": "openshell-middleware-manager"}, ' + '"languages": ["rust"], "python_package": null, ' + '"proto_imports": ["extension.proto"]}', + "invalid proto_imports entry", + ), + ( + '{"generator": {"name": "openshell-middleware-manager"}, ' + '"languages": ["rust"], "python_package": null, ' + '"proto_imports": [{"name": "supervisor_middleware.proto"}]}', + "invalid proto_imports entry", + ), ], ) def test_update_rejects_invalid_manifest(tmp_path: Path, manifest: str, message: str) -> None: @@ -424,7 +856,7 @@ def test_update_rejects_symlinked_proto_directory_without_touching_target( update_project( project_dir=destination, requested_version="v1.2.3", - download_proto=lambda version: (UPDATED_PROTO, f"https://example.test/{version}"), + download_proto=lambda version, name: (UPDATED_PROTO, f"https://example.test/{version}"), command_runner=no_op_runner, ) @@ -456,7 +888,7 @@ def test_update_rejects_symlinked_python_package_without_touching_target( update_project( project_dir=destination, requested_version="v1.2.3", - download_proto=lambda version: (UPDATED_PROTO, f"https://example.test/{version}"), + download_proto=lambda version, name: (UPDATED_PROTO, f"https://example.test/{version}"), command_runner=no_op_runner, ) @@ -495,7 +927,7 @@ def inspect_staging(language: str, project: Path, package: str) -> None: update_project( project_dir=destination, requested_version="v1.2.3", - download_proto=lambda version: (UPDATED_PROTO, f"https://example.test/{version}"), + download_proto=lambda version, name: (UPDATED_PROTO, f"https://example.test/{version}"), command_runner=inspect_staging, ) @@ -532,7 +964,7 @@ def replace_proto_ancestor(language: str, staged_project: Path, package: str) -> update_project( project_dir=destination, requested_version="v1.2.3", - download_proto=lambda version: (UPDATED_PROTO, f"https://example.test/{version}"), + download_proto=lambda version, name: (UPDATED_PROTO, f"https://example.test/{version}"), command_runner=replace_proto_ancestor, ) @@ -573,7 +1005,7 @@ def replace_parent_then_exchange(source: Path, target: Path) -> None: update_project( project_dir=destination, requested_version="v1.2.3", - download_proto=lambda version: (UPDATED_PROTO, f"https://example.test/{version}"), + download_proto=lambda version, name: (UPDATED_PROTO, f"https://example.test/{version}"), command_runner=no_op_runner, ) @@ -838,8 +1270,8 @@ def fail_runner(language: str, project: Path, package: str) -> None: def test_rejects_an_unexpected_proto(tmp_path: Path) -> None: - def invalid_proto(version: str) -> tuple[bytes, str]: - return b"not a proto", f"https://example.test/{version}" + def invalid_proto(version: str, name: str) -> tuple[bytes, str]: + return b"not a proto", f"https://example.test/{version}/{name}" with pytest.raises(ProjectError, match="not a supported"): create_project( @@ -946,10 +1378,13 @@ def test_download_proto_returns_content_and_source(monkeypatch: pytest.MonkeyPat response = FakeResponse(body=PROTO) monkeypatch.setattr(generator.urllib.request, "urlopen", lambda *args, **kwargs: response) - content, source = generator._download_proto("v1.2.3") + content, source = generator._download_proto("v1.2.3", "supervisor_middleware.proto") assert content == PROTO assert source.endswith("/v1.2.3/proto/supervisor_middleware.proto") + assert generator._download_proto("v1.2.3", "extension.proto")[1] == ( + "https://raw.githubusercontent.com/NVIDIA/OpenShell/v1.2.3/proto/extension.proto" + ) def test_download_proto_translates_network_failure(monkeypatch: pytest.MonkeyPatch) -> None: @@ -961,7 +1396,7 @@ def fail(*args: object, **kwargs: object) -> None: monkeypatch.setattr(generator.time, "sleep", lambda _: None) with pytest.raises(ProjectError, match=r"could not download.*missing"): - generator._download_proto("v1.2.3") + generator._download_proto("v1.2.3", "supervisor_middleware.proto") def test_network_error_reason_handles_plain_os_error() -> None: @@ -983,7 +1418,7 @@ def transient(*args: object, **kwargs: object) -> FakeResponse: monkeypatch.setattr(generator.urllib.request, "urlopen", transient) monkeypatch.setattr(generator.time, "sleep", lambda _: None) - assert generator._download_proto("v1.2.3")[0] == PROTO + assert generator._download_proto("v1.2.3", "supervisor_middleware.proto")[0] == PROTO assert attempts == 3 @@ -1003,7 +1438,7 @@ def interrupted_then_complete(*args: object, **kwargs: object) -> FakeResponse: monkeypatch.setattr(generator.urllib.request, "urlopen", interrupted_then_complete) monkeypatch.setattr(generator.time, "sleep", lambda _: None) - assert generator._download_proto("v1.2.3")[0] == PROTO + assert generator._download_proto("v1.2.3", "supervisor_middleware.proto")[0] == PROTO assert attempts == 2 @@ -1030,7 +1465,7 @@ def fail(*args: object, **kwargs: object) -> None: expected_message = "middleware-capable release" if status == 404 else "HTTP 503" with pytest.raises(ProjectError, match=expected_message): - generator._download_proto("v1.2.3") + generator._download_proto("v1.2.3", "supervisor_middleware.proto") assert attempts == expected_attempts @@ -1228,6 +1663,56 @@ def validate_then_detach(*arguments) -> None: assert destination.read_text() == "concurrent replacement\n" +def test_move_publishes_into_an_absent_destination_only(tmp_path: Path) -> None: + source = tmp_path / "staged/extension.proto" + destination = tmp_path / "project/extension.proto" + source.parent.mkdir() + destination.parent.mkdir() + source.write_text("new import\n") + + generator._publish_move(source, destination) + + assert not source.exists() + assert destination.read_text() == "new import\n" + + source.write_text("newer import\n") + with pytest.raises(ProjectError, match="appeared during update"): + generator._publish_move(source, destination) + + assert source.read_text() == "newer import\n" + assert destination.read_text() == "new import\n" + + +def test_move_refuses_a_source_that_is_not_a_regular_file(tmp_path: Path) -> None: + source = tmp_path / "staged/extension.proto" + destination = tmp_path / "project/extension.proto" + source.mkdir(parents=True) + destination.parent.mkdir() + + with pytest.raises(ProjectError, match="changed type during update"): + generator._publish_move(source, destination) + + assert source.is_dir() + assert not destination.exists() + + +def test_move_reverses_when_open_parent_is_detached( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + source = tmp_path / "staged/extension.proto" + destination = tmp_path / "project/extension.proto" + source.parent.mkdir() + destination.parent.mkdir() + source.write_text("new import\n") + monkeypatch.setattr(generator, "_directory_fd_matches_path", lambda path, descriptor: False) + + with pytest.raises(ProjectError, match=r"parent changed.*move was reversed"): + generator._publish_move(source, destination) + + assert source.read_text() == "new import\n" + assert not destination.exists() + + class FakeRename: def __init__(self, error_number: int) -> None: self.error_number = error_number @@ -1320,7 +1805,9 @@ def test_prepare_python_generates_relative_import_and_smoke_checks( bindings = tmp_path / "src" / "audit_headers" / "bindings" bindings.mkdir(parents=True) (tmp_path / "proto").mkdir() - (tmp_path / "proto/supervisor_middleware.proto").write_bytes(PROTO) + (tmp_path / "proto/supervisor_middleware.proto").write_bytes(IMPORTING_PROTO) + (tmp_path / "proto/extension.proto").write_bytes(EXTENSION_PROTO) + write_manifest(tmp_path, proto_imports=["extension.proto"]) calls: list[tuple[str, ...]] = [] monkeypatch.setattr(generator, "_require_command", lambda command: f"/tools/{command}") @@ -1333,15 +1820,40 @@ def fake_run(command, *, cwd, environment=None) -> None: calls.append(tuple(command)) if "grpc_tools.protoc" in command: (bindings / "supervisor_middleware_pb2_grpc.py").write_text( - "import supervisor_middleware_pb2 as supervisor__middleware__pb2\n" + "import grpc\nimport supervisor_middleware_pb2 as supervisor__middleware__pb2\n" + ) + (bindings / "supervisor_middleware_pb2.py").write_text( + "from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2\n" + "import extension_pb2 as extension__pb2\n" + "from extension_pb2 import *\n" ) + (bindings / "supervisor_middleware_pb2.pyi").write_text( + "import extension_pb2 as _extension_pb2\n" + "from extension_pb2 import PeerMetadata as PeerMetadata\n" + ) + (bindings / "extension_pb2.py").write_text("DESCRIPTOR = None\n") monkeypatch.setattr(generator, "_run", fake_run) generator._prepare_python_project(tmp_path, "audit_headers", check_command=check_command) - generated = (bindings / "supervisor_middleware_pb2_grpc.py").read_text() - assert generated.startswith("from . import supervisor_middleware_pb2") + assert calls[0][-2:] == ( + str(tmp_path / "proto/supervisor_middleware.proto"), + str(tmp_path / "proto/extension.proto"), + ) + assert (bindings / "supervisor_middleware_pb2_grpc.py").read_text() == ( + "import grpc\nfrom . import supervisor_middleware_pb2 as supervisor__middleware__pb2\n" + ) + assert (bindings / "supervisor_middleware_pb2.py").read_text() == ( + "from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2\n" + "from . import extension_pb2 as extension__pb2\n" + "from .extension_pb2 import *\n" + ) + assert (bindings / "supervisor_middleware_pb2.pyi").read_text() == ( + "from . import extension_pb2 as _extension_pb2\n" + "from .extension_pb2 import PeerMetadata as PeerMetadata\n" + ) + assert (bindings / "extension_pb2.py").read_text() == "DESCRIPTOR = None\n" assert len(calls) == 3 assert calls[1][1] == "sync" assert calls[2] == ( @@ -1360,6 +1872,7 @@ def test_prepare_python_rejects_unexpected_generated_import( bindings.mkdir(parents=True) (tmp_path / "proto").mkdir() (tmp_path / "proto/supervisor_middleware.proto").write_bytes(PROTO) + write_manifest(tmp_path, proto_imports=[]) monkeypatch.setattr(generator, "_require_command", lambda command: f"/tools/{command}") def fake_run(command, *, cwd, environment=None) -> None: From 6c7b6e05c7d3469a1cbe564c2c8c0f665480beb3 Mon Sep 17 00:00:00 2001 From: Johnny Greco Date: Wed, 18 Nov 2026 18:46:23 +0000 Subject: [PATCH 2/2] Address panel review findings for omm v0.1.9 support - Rust starter: build with tonic's generated default stubs and delete the hand-written "unimplemented" methods and stream types. A contract that adds or removes an RPC the starter does not implement, such as the removal of EvaluateHttpRequest announced for OpenShell 0.2.0, no longer breaks generated projects. - Verification script: turn errexit off inside the cleanup handler so a failing cleanup command cannot skip stopping the gateway and services or replace the exit status. - Generated READMEs: list the imported protocol files as part of the downloaded contract that the manifest records. Signed-off-by: Johnny Greco --- .../scripts/verify-openshell-release.sh | 1 + .../templates/python/README.md | 6 ++-- .../templates/rust/README.md | 6 ++-- .../templates/rust/build.rs | 1 + .../templates/rust/src/lib.rs | 34 +------------------ 5 files changed, 11 insertions(+), 37 deletions(-) diff --git a/projects/tools/openshell-middleware-manager/scripts/verify-openshell-release.sh b/projects/tools/openshell-middleware-manager/scripts/verify-openshell-release.sh index c09e0b85..afb97981 100755 --- a/projects/tools/openshell-middleware-manager/scripts/verify-openshell-release.sh +++ b/projects/tools/openshell-middleware-manager/scripts/verify-openshell-release.sh @@ -144,6 +144,7 @@ stop_process() { cleanup() { local status=$? + set +e trap - EXIT local sandbox language for sandbox in "${SANDBOXES[@]}"; do diff --git a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/README.md b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/README.md index 17ea4b32..d20a4c24 100644 --- a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/README.md +++ b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/python/README.md @@ -99,9 +99,11 @@ documentation for the policy syntax supported by your pinned OpenShell release. ## Version-matched generated files -- `proto/supervisor_middleware.proto` is the exact downloaded contract. +- `proto/supervisor_middleware.proto` and the OpenShell protocol files it imports are + the exact downloaded contract. - `src/__PACKAGE_NAME__/bindings/` contains generated protobuf and gRPC modules. -- `.openshell-middleware-manifest.json` records the release, source URL, and SHA-256. +- `.openshell-middleware-manifest.json` records the release and each protocol file's + source URL and SHA-256. - `uv.lock` records the Python dependency solution. Commit these files. Refresh all version-matched artifacts together with: diff --git a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/README.md b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/README.md index a5a9cd62..dc6d885d 100644 --- a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/README.md +++ b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/README.md @@ -104,9 +104,11 @@ documentation for the policy syntax supported by your pinned OpenShell release. ## Version-matched generated files -- `proto/supervisor_middleware.proto` is the exact downloaded contract. +- `proto/supervisor_middleware.proto` and the OpenShell protocol files it imports are + the exact downloaded contract. - `build.rs` generates Rust modules into Cargo's `OUT_DIR` from that contract. -- `.openshell-middleware-manifest.json` records the release, source URL, and SHA-256. +- `.openshell-middleware-manifest.json` records the release and each protocol file's + source URL and SHA-256. - `Cargo.lock` records the Rust dependency solution. Commit these files. Refresh all version-matched artifacts together with: diff --git a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/build.rs b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/build.rs index 50b0f596..51ce3ecc 100644 --- a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/build.rs +++ b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/build.rs @@ -10,6 +10,7 @@ fn main() -> Result<(), Box> { tonic_prost_build::configure() .build_client(true) .build_server(true) + .generate_default_stubs(true) .compile_protos(&["proto/supervisor_middleware.proto"], &["proto"])?; Ok(()) diff --git a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/src/lib.rs b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/src/lib.rs index 95b70848..8964ea2e 100644 --- a/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/src/lib.rs +++ b/projects/tools/openshell-middleware-manager/src/openshell_middleware_manager/templates/rust/src/lib.rs @@ -184,8 +184,6 @@ pub fn evaluate_http_request_event( #[tonic::async_trait] impl SupervisorMiddleware for Middleware { - type EvaluateWebSocketSessionStream = ResultStream; - async fn describe( &self, request: Request, @@ -202,50 +200,20 @@ impl SupervisorMiddleware for Middleware { ) -> Result, Status> { Ok(Response::new(validate_config(request.into_inner()))) } - - // Legacy HTTP hook that OpenShell deprecates for removal in 0.2.0. Delete this - // method when a contract update drops the RPC. - async fn evaluate_http_request( - &self, - _request: Request, - ) -> Result, Status> { - Err(Status::unimplemented("this service implements HTTP hooks")) - } - - async fn evaluate_web_socket_session( - &self, - _request: Request>, - ) -> Result, Status> { - Err(Status::unimplemented( - "this service declares no WebSocket binding", - )) - } } #[tonic::async_trait] impl HttpHooks for Middleware { - type EvaluateHttpRequestHookStream = ResultStream; - type EvaluateHttpResponseHookStream = ResultStream; - async fn evaluate_http_request_hook( &self, request: Request>, - ) -> Result, Status> { + ) -> Result>, Status> { let results = request.into_inner().filter_map(|event| match event { Ok(event) => evaluate_http_request_event(event).map(Ok), Err(status) => Some(Err(status)), }); Ok(Response::new(Box::pin(results))) } - - async fn evaluate_http_response_hook( - &self, - _request: Request>, - ) -> Result, Status> { - Err(Status::unimplemented( - "this service declares no HTTP response binding", - )) - } } #[cfg(test)]