diff --git a/.agents/skills/helm-dev-environment/SKILL.md b/.agents/skills/helm-dev-environment/SKILL.md index 15198a891f..2355e5c3f9 100644 --- a/.agents/skills/helm-dev-environment/SKILL.md +++ b/.agents/skills/helm-dev-environment/SKILL.md @@ -256,15 +256,19 @@ Key Helm values: ### Keycloak OIDC -One-time setup — only needed once per cluster lifetime: +Initial setup — rerun it whenever you want to rotate the development CA: ```bash mise run keycloak:k8s:setup ``` This deploys Keycloak (`quay.io/keycloak/keycloak:24.0`) into the `keycloak` namespace, -imports the openshell realm from `scripts/keycloak-realm.json`, and prints a port-forward -command for acquiring tokens from the CLI. +imports the openshell realm from `scripts/keycloak-realm.json`, generates a short-lived +development TLS certificate, and publishes its trust anchor as the +`openshell-keycloak-ca` ConfigMap in the OpenShell namespace. The command prints a +port-forward command for acquiring tokens from the CLI. Rerunning setup rotates the +development certificate and trust anchor; redeploy the gateway afterward so it reloads +the mounted CA bundle. Then activate OIDC in the OpenShell Helm chart: 1. Uncomment `#- ci/values-keycloak.yaml` in `skaffold.yaml` @@ -355,4 +359,4 @@ for dependencies still declared in `Chart.yaml`. | `deploy/helm/openshell/ci/values-tls-disabled.yaml` | Lint-only: TLS + auth disabled (reverse-proxy edge termination) | | `deploy/kube/manifests/envoy-gateway-openshell.yaml` | GatewayClass for Envoy Gateway (`mise run helm:gateway:apply`) | | `tasks/scripts/helm-k3s-local.sh` | k3d cluster create/delete/start/stop/status | -| `tasks/scripts/keycloak-k8s-setup.sh` | Keycloak deploy + realm import | +| `tasks/scripts/keycloak-k8s-setup.sh` | Keycloak deploy, realm import, and development TLS trust anchor | diff --git a/.agents/skills/launch-openshell-gator/SKILL.md b/.agents/skills/launch-openshell-gator/SKILL.md index 763dc779a2..80a84ca744 100644 --- a/.agents/skills/launch-openshell-gator/SKILL.md +++ b/.agents/skills/launch-openshell-gator/SKILL.md @@ -13,7 +13,7 @@ For gator's PR/issue validation policy, load `gator-gate` inside the launched sa ## Non-Negotiable Rules -- Keep normal gator launches supervised: use `--watch --background` and let the in-sandbox supervisor own sleeping and relaunching bounded cycles. +- Keep normal gator launches supervised: use `--watch` and let the in-sandbox supervisor own sleeping and relaunching bounded cycles. - Do not add passive `sleep` loops in the operator session to watch gator. Check logs or status once, then report the current state or launch a proper watcher outside the model session only when explicitly asked. - Do not change the default gator model in `scripts/agents/gator/agent.yaml` for experiments. Use `CODEX_MODEL=...` and, if needed, a temporary `--from` Docker context or `--codex-bin` override. - Do not push to contributor branches, approve, merge, post `/ok to test`, or broaden gator scope unless the operator explicitly authorized that action. @@ -34,7 +34,6 @@ For gator's PR/issue validation policy, load `gator-gate` inside the launched sa | `scripts/agents/gator/bin/validate-review-findings` | Enforces the blocker evidence schema and downgrades unsupported hypotheses. | | `scripts/agents/gator/prompts/gator.md` | Rendered top-level prompt template baked into the payload. | | `scripts/agents/gator/skills/gator-gate/SKILL.md` | In-sandbox gator state-machine skill. | -| `scripts/agents/gator/logs/` | Background launch and supervisor logs. | ## Preflight @@ -156,11 +155,12 @@ sandbox_name="gator-pr-${pr_number}-supervised" --gateway "$gateway_name" \ --name "$sandbox_name" \ --watch \ - --background \ "Review and monitor PR #${pr_number} through the gator-gate workflow. Scope this invocation only to PR #${pr_number}." ``` -The launcher queries gateway's selected compute driver, builds gator image in matching Docker or Podman image store, stages immutable payload, imports provider profiles, configures provider credentials and refresh, creates and uploads sandbox payload, then starts agent supervisor with `sandbox exec`. It writes a background log under `scripts/agents/gator/logs/`. `CONTAINER_ENGINE`, when set, must match gateway driver. +The launcher queries the gateway's selected compute driver, builds the gator image in the matching Docker or Podman image store, stages the immutable payload, imports provider profiles, configures provider credentials and refresh, and starts the agent supervisor as the sandbox's canonical main process. The detached main process survives loss of the host CLI connection and reconnects to a restarted gateway. Unless `--keep` is set, the sandbox is marked ephemeral so the gateway deletes it after the supervisor exits. `CONTAINER_ENGINE`, when set, must match the gateway driver. + +The launcher streams image-build and provisioning output until the detached workload is ready, then exits. Use `openshell logs ` or the TUI for runtime output. ### Launch An Issue Or Issue/PR Pair @@ -177,7 +177,6 @@ sandbox_name="gator-issue-${issue_number}-supervised" --gateway "$gateway_name" \ --name "$sandbox_name" \ --watch \ - --background \ "Run gator on issue #${issue_number}. Scope this invocation only to issue #${issue_number}." ``` @@ -198,7 +197,6 @@ sandbox_name="gator-pr-${pr_number}-supervised" --gateway "$gateway_name" \ --name "$sandbox_name" \ --watch \ - --background \ "Review and monitor PR #${pr_number} with linked issue #${issue_number} through the gator-gate workflow. Scope this invocation only to PR #${pr_number} and issue #${issue_number}." ``` @@ -219,7 +217,6 @@ sandbox_name="gator-pr-${pr_number}-supervised" --gateway "$gateway_name" \ --name "$sandbox_name" \ --watch \ - --background \ "Review and monitor PR #${pr_number} through the gator-gate workflow. Scope this invocation only to PR #${pr_number}. The operator explicitly authorizes applying the test:e2e label, posting /ok to test for the current head SHA, and rerunning the relevant current-head workflow when the E2E Label Help bot says that is required." ``` @@ -241,7 +238,6 @@ CODEX_MODEL=gpt-5.6-sol \ --gateway "$gateway_name" \ --name "$sandbox_name" \ --watch \ - --background \ "Review and monitor PR #${pr_number} through the gator-gate workflow. Scope this invocation only to PR #${pr_number}. This launch is intentionally testing Codex model gpt-5.6-sol via the CLI launcher." ``` @@ -266,7 +262,6 @@ CODEX_MODEL=gpt-5.6-sol \ --name "$sandbox_name" \ --from "$tmp_context" \ --watch \ - --background \ "Review and monitor PR #${pr_number} through the gator-gate workflow. Scope this invocation only to PR #${pr_number}." ``` @@ -274,19 +269,15 @@ CODEX_MODEL=gpt-5.6-sol \ ### Read The Launch Result -The launcher prints the log path when `--background` is used: - -```text -Started in background. Log: scripts/agents/gator/logs/.log -``` - -Read that file directly. Important markers: +The launcher streams image-build and provisioning output to the terminal. Important markers: - `Built image ...` means the local image build completed. - `Created sandbox: ` means OpenShell accepted the sandbox. - `openshell-agent: starting watch cycle` means the in-sandbox supervisor began a bounded cycle. - `OpenAI Codex v...` plus `model: ...` confirms the Codex CLI and model actually used. - `OPENSHELL_AGENT_RESULT {...}` is the bounded-cycle sentinel. In watch mode, the supervisor sleeps and relaunches after this line. +- `/sandbox/.openshell-agent/status.json` is the atomic current state snapshot. Its `result.notes` field is Gator's plain-language diagnosis and next action for that cycle. +- `/sandbox/.openshell-agent/history.jsonl` contains the latest 100 supervisor transitions, including active-cycle starts and completed cycle results. - `openshell-agent: still running watch cycle ...` is a heartbeat during long active model cycles. - `review_feedback_lookup_failed` means Gator could not build the required cross-SHA feedback ledger and deliberately skipped a context-free review. @@ -314,6 +305,11 @@ If `sandbox get` is not supported by the local CLI shape, use `openshell sandbox | `status=terminal_failure` | Unrecoverable or stale immutable payload. | Inspect the reason; rebuild/relaunch for `stale_gator_payload`. | | `status=complete` | Target closed, merged, or one-shot complete. | Delete sandbox if no longer needed. | +Prefer the state snapshot over scraping transient `/tmp` cycle output. Use the +history file to tell whether a failure is repeating or whether the supervisor +has begun a fresh cycle. Runtime logs remain useful for full command output and +transport diagnostics. + ## Restarting A Gator Restart when the payload must change, the sandbox is wedged without a sentinel, the model/tooling version changed, or a transient failure repeats past the useful retry point. @@ -339,7 +335,6 @@ openshell --gateway "$gateway_name" sandbox delete "$sandbox_name" --gateway "$gateway_name" \ --name "$sandbox_name" \ --watch \ - --background \ "" ``` @@ -401,7 +396,6 @@ When you launch or inspect gator, report: - Sandbox name. - Gateway name. -- Log path. - Target issue/PR scope. - Harness and model when relevant. - Whether image build and sandbox creation succeeded. diff --git a/.github/workflows/conformance.yml b/.github/workflows/conformance.yml index 242f8c7d01..ff944ad58c 100644 --- a/.github/workflows/conformance.yml +++ b/.github/workflows/conformance.yml @@ -150,7 +150,7 @@ jobs: name: openshell-conformance-x86_64-unknown-linux-musl path: conformance-input - - name: Run RPM gateway continuity conformance + - name: Run RPM smoke conformance shell: bash run: | set -euo pipefail @@ -169,11 +169,9 @@ jobs: --distro fedora \ --with podman-rootless \ --with selinux \ - --copy "${candidate_cli_package[0]}:/var/lib/openshell-conformance/candidate/openshell.rpm" \ - --copy "${candidate_gateway_package[0]}:/var/lib/openshell-conformance/candidate/openshell-gateway.rpm" \ + --install "${candidate_cli_package[0]}" \ + --install "${candidate_gateway_package[0]}" \ --copy conformance-input/openshell-conformance:/tmp/openshell-conformance \ - --copy nix/test-guest/conformance-plans/gateway-upgrade-restart.toml:/tmp/conformance-plan.toml \ - --provision openshell-rpm-latest-release \ + --provision openshell-rpm \ --provision gateway-podman \ - --provision openshell-rpm-gateway-upgrade \ - -- /tmp/openshell-conformance run --plan /tmp/conformance-plan.toml + -- /tmp/openshell-conformance run smoke diff --git a/Cargo.lock b/Cargo.lock index 716cb10eb2..511277fe93 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4013,7 +4013,6 @@ dependencies = [ "serde_json", "tempfile", "tokio", - "toml", ] [[package]] @@ -4058,6 +4057,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-types", "tracing", "url", ] @@ -4441,6 +4441,7 @@ version = "0.0.0" dependencies = [ "clap", "futures", + "http 1.4.0", "miette", "nix 0.29.0", "openshell-core", diff --git a/Cargo.toml b/Cargo.toml index 9fbcc9a8c8..e916b4c52a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ tokio = { version = "1.43", features = ["full"] } # gRPC/Protobuf tonic = "0.14" +tonic-types = "0.14" tonic-prost = "0.14" tonic-prost-build = "0.14" prost = "0.14" diff --git a/architecture/build.md b/architecture/build.md index a5dcfe9241..caea7cd602 100644 --- a/architecture/build.md +++ b/architecture/build.md @@ -221,6 +221,8 @@ Runtime layout: gateway bundles z3, so the image does not need a distro-provided z3 runtime. The base is pinned to a multi-architecture digest; distro security updates require refreshing that digest and rebuilding the gateway image. + Updating the container's glibc package does not raise the binary's glibc + compatibility floor. - **VM driver**: host GNU-linked binary installed at `/usr/libexec/openshell/openshell-driver-vm` in Linux packages and published as a release artifact. Linux GNU VM driver binaries must not reference @@ -292,12 +294,9 @@ pulls and explicit publication. OCI pulls require a trusted manifest digest and retain that provenance with the local entry; mutable tags are used only for explicit publication. -CLI conformance runs after target provisioning. Action-free scenarios operate -only through the configured OpenShell CLI. A versioned conformance plan may add -an ordered sequence of target-supplied host-side actions, such as a gateway -restart, while the scenario remains responsible for black-box sandbox -continuity checks. The plan exposes opaque executable paths and timeouts rather -than driver or package-manager configuration; target setup owns those details. +CLI conformance runs after target provisioning and operates only through the +configured OpenShell CLI. The smoke scenario verifies the black-box sandbox +lifecycle by creating, inspecting, executing in, and deleting a sandbox. ## Python Wheel Packaging diff --git a/architecture/gateway.md b/architecture/gateway.md index 1f3e712a6d..a470edb75a 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -53,6 +53,15 @@ The gateway validates this requirement before constructing the selected driver. ## Protocol and Auth +Gateway validation and concurrency errors use the standard rich gRPC error +envelope. Shared field validators attach `google.rpc.BadRequest`, and conditional +write conflicts attach `google.rpc.ErrorInfo` with a stable reason and current +version when available. `google.rpc.RetryInfo` expresses a minimum retry delay; +it does not establish that a mutation is safe to repeat. SDKs retain the original +transport status, metadata, and unknown details alongside decoded fields. +Python cleanup inspects the original gRPC call beneath a typed error wrapper, +preserving missing-resource handling without suppressing other failures. + The gateway listens on one service port and multiplexes gRPC and HTTP traffic. The default local single-user deployment mode is mTLS user authentication: clients present a certificate signed by the local deployment CA, and the @@ -215,7 +224,7 @@ Supported auth modes: | Plaintext | Local development or a trusted reverse proxy boundary. | | Unauthenticated local users | Trusted Kubernetes dev or fully trusted proxy deployments only. | | Cloudflare JWT | Edge-authenticated deployments where Cloudflare Access supplies identity. | -| OIDC | Bearer-token auth for users, with browser or device-code PKCE and client credentials login. JWKS validation accepts RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, and EdDSA (Ed25519) signing keys. | +| OIDC | Bearer-token auth for users, with browser or device-code PKCE and client credentials login. Discovery and JWKS retrieval require HTTPS, reject redirects, and pin JWKS to the issuer origin or an explicit origin allowlist. JWKS validation accepts RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, and EdDSA (Ed25519) signing keys. | The CLI persists the scopes requested during OIDC login in gateway metadata and reuses them when refreshing an access token. This preserves the intended API diff --git a/architecture/sandbox.md b/architecture/sandbox.md index 53c26a56bc..859181b279 100644 --- a/architecture/sandbox.md +++ b/architecture/sandbox.md @@ -491,6 +491,10 @@ Security-relevant sandbox behavior uses OCSF structured events; internal diagnostics use ordinary tracing. The OCSF device describes the sandbox environment, with type ID Other and type label `Sandbox`; its operating system is a separate attribute. +HTTP Activity records contain a request or response; early rejections with only +connection context use Network Activity. Producer regression tests validate +required fields and `at_least_one` constraints against the vendored OCSF 1.8 +schemas. ## Policy Proposals diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index bffd137c09..fdec4ce7e5 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -1372,7 +1372,7 @@ enum SandboxCommands { no_tty: bool, /// Start the canonical main process without attaching to it. - #[arg(long, conflicts_with_all = ["editor", "no_keep"])] + #[arg(long, conflicts_with = "editor")] detach: bool, /// Auto-create missing providers from local credentials. @@ -5461,10 +5461,35 @@ mod tests { } #[test] - fn sandbox_create_detach_rejects_ephemeral_sandbox() { - let result = - Cli::try_parse_from(["openshell", "sandbox", "create", "--detach", "--no-keep"]); - assert!(result.is_err()); + fn sandbox_create_detach_accepts_ephemeral_sandbox() { + let cli = Cli::try_parse_from([ + "openshell", + "sandbox", + "create", + "--detach", + "--no-keep", + "--", + "worker", + ]) + .expect("detached ephemeral sandbox should parse"); + + match cli.command { + Some(Commands::Sandbox { + command: + Some(SandboxCommands::Create { + detach, + no_keep, + command, + .. + }), + .. + }) => { + assert!(detach); + assert!(no_keep); + assert_eq!(command, ["worker"]); + } + other => panic!("expected SandboxCommands::Create, got: {other:?}"), + } } #[test] diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index 6434f66f4b..d3cccefb76 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -1700,6 +1700,46 @@ async fn detached_command_does_not_declare_main_process_attachment() { assert!(!requests[0].await_main_process_attachment); } +#[tokio::test] +async fn detached_ephemeral_command_delegates_cleanup_to_gateway() { + let server = run_server().await; + let fake_ssh_dir = tempfile::tempdir().unwrap(); + let xdg_dir = tempfile::tempdir().unwrap(); + let _env = test_env(&fake_ssh_dir, &xdg_dir); + let tls = test_tls(&server); + install_fake_ssh(&fake_ssh_dir); + + run::sandbox_create( + &server.endpoint, + "openshell", + run::SandboxCreateConfig { + name: Some("detached-ephemeral-main"), + keep: false, + command: &["worker".into()], + detach: true, + ..test_config() + }, + "default", + &tls, + ) + .await + .expect("detached ephemeral sandbox create should succeed"); + + let requests = create_requests(&server).await; + assert!(!requests[0].await_main_process_attachment); + assert_eq!( + requests[0] + .annotations + .get("openshell.nvidia.com/retention") + .map(String::as_str), + Some("ephemeral") + ); + assert!( + deleted_names(&server).await.is_empty(), + "the gateway owns cleanup after a detached canonical process exits" + ); +} + #[tokio::test] async fn sandbox_create_sends_driver_config_json() { let server = run_server().await; diff --git a/crates/openshell-conformance-cli/src/main.rs b/crates/openshell-conformance-cli/src/main.rs index c7f35bc13f..c9c0beb5e0 100644 --- a/crates/openshell-conformance-cli/src/main.rs +++ b/crates/openshell-conformance-cli/src/main.rs @@ -3,19 +3,11 @@ //! Standalone runner for `OpenShell` CLI conformance scenarios. -use std::fmt::Write; -use std::future::Future; -use std::io::Read; use std::path::PathBuf; -use std::pin::Pin; use std::process::ExitCode; -use std::sync::Arc; use clap::{Parser, Subcommand, ValueEnum}; -use openshell_conformance::{ - ConformancePlan, HostAction, HostActionExecutor, OpenShellRunner, PlanRun, Scenario, - default_scenarios, scenario, scenarios, -}; +use openshell_conformance::{OpenShellRunner, Scenario, scenario, scenarios}; use serde::Serialize; #[derive(Debug, Parser)] @@ -36,16 +28,13 @@ enum Command { #[arg(long, value_enum, default_value_t = OutputFormat::Text)] output: OutputFormat, }, - /// Run action-free scenarios, named scenarios, or an explicit plan. + /// Run all registered scenarios, or named scenarios. Run { - /// Action-free scenario names. Omit to run every action-free scenario. + /// Scenario names. Omit to run every registered scenario. scenarios: Vec, /// Explicit path to the `OpenShell` CLI. Defaults to `openshell` on PATH. #[arg(long)] openshell_bin: Option, - /// Versioned TOML conformance plan. Use '-' to read the plan from stdin. - #[arg(long, conflicts_with = "scenarios")] - plan: Option, #[arg(long, value_enum, default_value_t = OutputFormat::Text)] output: OutputFormat, }, @@ -93,9 +82,8 @@ async fn execute(cli: Cli) -> Result<(), String> { Command::Run { scenarios: requested, openshell_bin, - plan, output, - } => run(&requested, openshell_bin, plan, output).await, + } => run(&requested, openshell_bin, output).await, } } @@ -126,63 +114,20 @@ fn list(output: OutputFormat) -> Result<(), String> { async fn run( requested: &[String], binary: Option, - plan_path: Option, output: OutputFormat, ) -> Result<(), String> { - if let Some(plan_path) = plan_path { - let plan = read_plan(&plan_path)?; - return run_plan(&plan, binary, output).await; - } - let selected = select_scenarios(requested)?; let mut results = Vec::with_capacity(selected.len()); for candidate in selected { - let plan_run = default_plan_run(candidate.name); - results.push(run_scenario(candidate, &plan_run, binary.as_ref(), None).await); + results.push(run_scenario(candidate, binary.as_ref()).await); } render_results(results, output) } -async fn run_plan( - plan: &ConformancePlan, - binary: Option, - output: OutputFormat, -) -> Result<(), String> { - let executor: Arc = Arc::new(ProcessHostAction); - let mut results = Vec::with_capacity(plan.runs.len()); - for plan_run in &plan.runs { - let candidate = scenario(&plan_run.scenario) - .expect("validated conformance plan references a registered scenario"); - let result = - run_scenario(candidate, plan_run, binary.as_ref(), Some(executor.clone())).await; - let result = match (result.passed, &plan.diagnostics) { - (false, Some(diagnostics)) => append_diagnostics(result, &executor, diagnostics).await, - _ => result, - }; - let passed = result.passed; - results.push(result); - if !passed { - break; - } - } - - render_results(results, output) -} - -fn default_plan_run(scenario: &str) -> PlanRun { - PlanRun { - scenario: scenario.to_string(), - workload_expectation: None, - actions: Vec::new(), - } -} - async fn run_scenario( candidate: &'static Scenario, - plan_run: &PlanRun, binary: Option<&PathBuf>, - host_action_executor: Option>, ) -> ScenarioResult<'static> { let runner = binary.map_or_else( || OpenShellRunner::new(candidate.name), @@ -198,12 +143,9 @@ async fn run_scenario( }; } }; - if let Some(host_action_executor) = host_action_executor { - runner = runner.with_host_action_executor(host_action_executor); - } eprintln!("CLI conformance run ID: {}", runner.id()); let scenario_result = match runner.check_gateway_status().await { - Ok(()) => candidate.run(&mut runner, plan_run).await, + Ok(()) => candidate.run(&mut runner).await, Err(error) => Err(error), }; let outcome = runner.finish(scenario_result).await; @@ -214,19 +156,6 @@ async fn run_scenario( } } -async fn append_diagnostics( - mut result: ScenarioResult<'static>, - executor: &Arc, - diagnostics: &openshell_conformance::PlanDiagnostics, -) -> ScenarioResult<'static> { - let action = diagnostics.as_action(); - if let Err(error) = executor.execute(&action).await { - let diagnostic = result.diagnostic.get_or_insert_default(); - let _ = write!(diagnostic, "\n\nsecondary diagnostics failure:\n{error}"); - } - result -} - fn render_results( results: Vec>, output: OutputFormat, @@ -262,86 +191,20 @@ fn render_results( } } -fn read_plan(path: &PathBuf) -> Result { - let contents = if path.as_os_str() == "-" { - let mut input = String::new(); - std::io::stdin() - .read_to_string(&mut input) - .map_err(|error| format!("read conformance plan from stdin: {error}"))?; - input - } else { - std::fs::read_to_string(path) - .map_err(|error| format!("read conformance plan {}: {error}", path.display()))? - }; - ConformancePlan::parse(&contents).map_err(|error| format!("invalid conformance plan: {error}")) -} - fn select_scenarios(requested: &[String]) -> Result, String> { if requested.is_empty() { - return Ok(default_scenarios().collect()); + return Ok(scenarios().iter().collect()); } requested .iter() .map(|name| { - let candidate = scenario(name).ok_or_else(|| { + scenario(name).ok_or_else(|| { format!("unknown scenario '{name}'; run `openshell-conformance list`") - })?; - if candidate.requires_plan() { - return Err(format!( - "scenario '{name}' requires an explicit --plan; run `openshell-conformance list`" - )); - } - Ok(candidate) + }) }) .collect() } -struct ProcessHostAction; - -impl HostActionExecutor for ProcessHostAction { - fn execute( - &self, - action: &HostAction, - ) -> Pin> + Send + '_>> { - let name = action.name.clone(); - let command = action.command.clone(); - let timeout = action.timeout(); - let timeout_secs = action.timeout_secs; - Box::pin(async move { - let mut process = tokio::process::Command::new(&command); - process.kill_on_drop(true); - let output = tokio::time::timeout(timeout, process.output()) - .await - .map_err(|_| { - format!( - "host action {:?} command '{}' timed out after {}s", - name, - command.display(), - timeout_secs, - ) - })? - .map_err(|error| { - format!( - "start host action {:?} command '{}': {error}", - name, - command.display(), - ) - })?; - if output.status.success() { - return Ok(()); - } - Err(format!( - "host action {:?} command '{}' exited {:?}:\nstdout:\n{}\nstderr:\n{}", - name, - command.display(), - output.status.code(), - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr), - )) - }) - } -} - #[cfg(test)] mod tests { use clap::Parser; @@ -352,7 +215,7 @@ mod tests { fn selects_all_scenarios_by_default() { assert_eq!( select_scenarios(&[]).expect("select all").len(), - default_scenarios().count() + scenarios().len() ); } @@ -368,14 +231,6 @@ mod tests { assert!(error.contains("openshell-conformance list")); } - #[test] - fn action_scenario_requires_an_explicit_plan() { - let error = select_scenarios(&["sandbox-continuity".to_string()]) - .expect_err("action scenario requires a plan"); - - assert!(error.contains("requires an explicit --plan")); - } - #[test] fn parses_binary_override_and_json_output() { let cli = Cli::try_parse_from([ @@ -399,14 +254,4 @@ mod tests { assert_eq!(openshell_bin, Some(PathBuf::from("/opt/openshell"))); assert_eq!(output, OutputFormat::Json); } - - #[test] - fn parses_plan_from_stdin() { - let cli = Cli::try_parse_from(["openshell-conformance", "run", "--plan", "-"]) - .expect("parse plan from stdin"); - let Command::Run { plan, .. } = cli.command else { - panic!("expected run") - }; - assert_eq!(plan, Some(PathBuf::from("-"))); - } } diff --git a/crates/openshell-conformance/Cargo.toml b/crates/openshell-conformance/Cargo.toml index 2c355a0052..7b67258045 100644 --- a/crates/openshell-conformance/Cargo.toml +++ b/crates/openshell-conformance/Cargo.toml @@ -15,7 +15,6 @@ rand.workspace = true serde.workspace = true serde_json.workspace = true tokio.workspace = true -toml.workspace = true [dev-dependencies] tempfile = "3" diff --git a/crates/openshell-conformance/src/lib.rs b/crates/openshell-conformance/src/lib.rs index 7b28fa688e..0691d99ef0 100644 --- a/crates/openshell-conformance/src/lib.rs +++ b/crates/openshell-conformance/src/lib.rs @@ -4,7 +4,6 @@ //! Reusable support for portable `OpenShell` CLI conformance scenarios. pub mod executor; -pub mod plan; mod scenarios; use std::collections::BTreeSet; @@ -24,56 +23,25 @@ use tokio::time::sleep; use self::executor::{CliExecutionError, CliExecutor, ProcessCli}; -pub use plan::{ConformancePlan, HostAction, PlanDiagnostics, PlanRun, WorkloadExpectation}; -pub use scenarios::{SANDBOX_CONTINUITY_SCENARIO, SMOKE_SCENARIO}; +pub use scenarios::SMOKE_SCENARIO; /// An installed conformance scenario. #[derive(Debug)] pub struct Scenario { pub name: &'static str, pub description: &'static str, - requires_plan: bool, - run: for<'a> fn(&'a mut OpenShellRunner, &'a PlanRun) -> ScenarioFuture<'a>, - validate_plan_run: Option, + run: for<'a> fn(&'a mut OpenShellRunner) -> ScenarioFuture<'a>, } pub type ScenarioFuture<'a> = Pin> + Send + 'a>>; -type PlanRunValidator = fn(&PlanRun) -> Result<(), String>; impl Scenario { - pub async fn run( - &self, - runner: &mut OpenShellRunner, - plan_run: &PlanRun, - ) -> Result<(), String> { - self.validate_plan_run(plan_run)?; - (self.run)(runner, plan_run).await - } - - pub fn validate_plan_run(&self, plan_run: &PlanRun) -> Result<(), String> { - self.validate_plan_run.map_or_else( - || default_validate_plan_run(plan_run), - |validate| validate(plan_run), - ) - } - - /// Whether this scenario may run only through an explicit target plan. - pub fn requires_plan(&self) -> bool { - self.requires_plan + pub async fn run(&self, runner: &mut OpenShellRunner) -> Result<(), String> { + (self.run)(runner).await } } -fn default_validate_plan_run(plan_run: &PlanRun) -> Result<(), String> { - if plan_run.workload_expectation.is_some() || !plan_run.actions.is_empty() { - return Err(format!( - "scenario {:?} does not accept workload_expectation or actions", - plan_run.scenario - )); - } - Ok(()) -} - -const SCENARIOS: &[Scenario] = &[SMOKE_SCENARIO, SANDBOX_CONTINUITY_SCENARIO]; +const SCENARIOS: &[Scenario] = &[SMOKE_SCENARIO]; /// Returns every scenario compiled into this distribution. pub fn scenarios() -> &'static [Scenario] { @@ -85,13 +53,6 @@ pub fn scenario(name: &str) -> Option<&'static Scenario> { scenarios().iter().find(|candidate| candidate.name == name) } -/// Returns scenarios that need no host-level disruption capability. -pub fn default_scenarios() -> impl Iterator { - scenarios() - .iter() - .filter(|scenario| !scenario.requires_plan) -} - const CLEANUP_TIMEOUT: Duration = Duration::from_mins(2); pub const STATUS_TIMEOUT: Duration = Duration::from_secs(30); const GATEWAY_STATUS_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(10); @@ -284,26 +245,12 @@ struct AuthenticationOutput { /// Runs `OpenShell` commands for one conformance scenario and owns its cleanup. pub struct OpenShellRunner { cli: Arc, - host_action_executor: Option>, run_id: String, scenario: String, known_sandboxes: BTreeSet, finished: bool, } -/// Executes one target-supplied host-side action from an explicit plan. -/// -/// This intentionally differs from [`CliExecutor`]: that executor models -/// `OpenShell` CLI invocations through the runner's configured binary and emits -/// structured command results, while an action is a plan-owned executable with -/// no caller-provided arguments. -pub trait HostActionExecutor: Send + Sync { - fn execute( - &self, - action: &HostAction, - ) -> Pin> + Send + '_>>; -} - /// A runner command with diagnostic context but no timeout yet. pub struct CommandStep<'a> { runner: &'a OpenShellRunner, @@ -345,7 +292,6 @@ impl OpenShellRunner { pub fn with_executor(cli: Arc, scenario: &str) -> Self { Self { cli, - host_action_executor: None, run_id: generate_run_id(), scenario: scenario.to_string(), known_sandboxes: BTreeSet::new(), @@ -353,36 +299,6 @@ impl OpenShellRunner { } } - /// Attaches the target-side executor used only by explicit plan actions. - #[must_use] - pub fn with_host_action_executor( - mut self, - host_action_executor: Arc, - ) -> Self { - self.host_action_executor = Some(host_action_executor); - self - } - - /// Execute a target-supplied action declared by the active plan. - pub async fn execute_host_action(&self, action: &HostAction) -> Result<(), String> { - let Some(host_action_executor) = &self.host_action_executor else { - return Err(format!( - "{} requires a host action executor; run this scenario through an explicit plan", - self.context(&format!("action/{}", action.name)) - )); - }; - eprintln!( - "{} applying target host action", - self.context(&format!("action/{}", action.name)) - ); - host_action_executor.execute(action).await.map_err(|error| { - format!( - "{} failed: {error}", - self.context(&format!("action/{}", action.name)) - ) - }) - } - pub fn id(&self) -> &str { &self.run_id } diff --git a/crates/openshell-conformance/src/plan.rs b/crates/openshell-conformance/src/plan.rs deleted file mode 100644 index 955c4b7765..0000000000 --- a/crates/openshell-conformance/src/plan.rs +++ /dev/null @@ -1,243 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Versioned, target-supplied execution plans for conformance scenarios. - -use std::path::{Path, PathBuf}; -use std::time::Duration; - -use serde::Deserialize; - -use crate::scenario; - -pub const PLAN_VERSION: u32 = 1; - -#[derive(Debug, Deserialize)] -pub struct ConformancePlan { - pub version: u32, - #[serde(default)] - pub runs: Vec, - pub diagnostics: Option, -} - -#[derive(Debug, Deserialize)] -pub struct PlanRun { - pub scenario: String, - pub workload_expectation: Option, - #[serde(default)] - pub actions: Vec, -} - -#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] -#[serde(rename_all = "kebab-case")] -pub enum WorkloadExpectation { - Reconciled, -} - -#[derive(Clone, Debug, Deserialize)] -pub struct HostAction { - pub name: String, - pub command: PathBuf, - pub timeout_secs: u64, -} - -impl HostAction { - pub fn timeout(&self) -> Duration { - Duration::from_secs(self.timeout_secs) - } -} - -#[derive(Debug, Deserialize)] -pub struct PlanDiagnostics { - pub command: PathBuf, - pub timeout_secs: u64, -} - -impl PlanDiagnostics { - pub fn as_action(&self) -> HostAction { - HostAction { - name: "diagnostics".to_string(), - command: self.command.clone(), - timeout_secs: self.timeout_secs, - } - } -} - -impl ConformancePlan { - pub fn parse(input: &str) -> Result { - let plan = toml::from_str::(input).map_err(|error| error.to_string())?; - plan.validate()?; - Ok(plan) - } - - fn validate(&self) -> Result<(), String> { - if self.version != PLAN_VERSION { - return Err(format!( - "unsupported conformance plan version {}; expected {PLAN_VERSION}", - self.version - )); - } - if self.runs.is_empty() { - return Err("conformance plan must contain at least one run".to_string()); - } - if let Some(diagnostics) = &self.diagnostics { - validate_command( - "diagnostics", - &diagnostics.command, - diagnostics.timeout_secs, - )?; - } - for run in &self.runs { - let Some(scenario) = scenario(&run.scenario) else { - return Err(format!( - "unknown scenario {:?}; run `openshell-conformance list`", - run.scenario - )); - }; - scenario.validate_plan_run(run)?; - for action in &run.actions { - validate_command( - &format!("action {:?}", action.name), - &action.command, - action.timeout_secs, - )?; - } - } - Ok(()) - } -} - -fn validate_command(label: &str, command: &Path, timeout_secs: u64) -> Result<(), String> { - if !command.is_absolute() { - return Err(format!( - "{label} command must be an absolute path: {}", - command.display() - )); - } - if timeout_secs == 0 { - return Err(format!("{label} timeout_secs must be greater than zero")); - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[cfg(not(windows))] - const RESTART_GATEWAY_COMMAND: &str = "/usr/local/libexec/restart-gateway"; - #[cfg(windows)] - const RESTART_GATEWAY_COMMAND: &str = r"C:\usr\local\libexec\restart-gateway"; - - #[cfg(not(windows))] - const DIAGNOSTICS_COMMAND: &str = "/usr/local/libexec/diagnostics"; - #[cfg(windows)] - const DIAGNOSTICS_COMMAND: &str = r"C:\usr\local\libexec\diagnostics"; - - #[test] - fn parses_a_smoke_and_continuity_plan() { - let plan = ConformancePlan::parse(&format!( - r#" - version = 1 - - [[runs]] - scenario = "smoke" - - [[runs]] - scenario = "sandbox-continuity" - workload_expectation = "reconciled" - - [[runs.actions]] - name = "gateway-upgrade" - command = '{RESTART_GATEWAY_COMMAND}' - timeout_secs = 120 - "#, - )) - .expect("valid plan"); - - assert_eq!(plan.runs.len(), 2); - assert_eq!(plan.runs[1].actions[0].name, "gateway-upgrade"); - } - - #[test] - fn parses_plan_diagnostics() { - let plan = ConformancePlan::parse(&format!( - r#" - version = 1 - - [diagnostics] - command = '{DIAGNOSTICS_COMMAND}' - timeout_secs = 60 - - [[runs]] - scenario = "smoke" - "#, - )) - .expect("valid plan with diagnostics"); - - assert_eq!( - plan.diagnostics - .expect("diagnostics configured") - .as_action() - .name, - "diagnostics" - ); - } - - #[test] - fn rejects_a_relative_action_command() { - let error = ConformancePlan::parse( - r#" - version = 1 - - [[runs]] - scenario = "sandbox-continuity" - workload_expectation = "reconciled" - - [[runs.actions]] - name = "gateway-restart" - command = "restart-gateway" - timeout_secs = 120 - "#, - ) - .expect_err("relative command must fail"); - - assert!(error.contains("absolute path")); - } - - #[test] - fn rejects_an_actionless_continuity_run() { - let error = ConformancePlan::parse( - r#" - version = 1 - - [[runs]] - scenario = "sandbox-continuity" - workload_expectation = "reconciled" - "#, - ) - .expect_err("continuity requires an action"); - - assert!(error.contains("requires at least one action")); - } - - #[test] - fn default_validation_rejects_actions_for_smoke() { - let error = ConformancePlan::parse( - r#" - version = 1 - - [[runs]] - scenario = "smoke" - - [[runs.actions]] - name = "gateway-restart" - command = "/usr/local/libexec/restart-gateway" - timeout_secs = 120 - "#, - ) - .expect_err("smoke does not accept actions"); - - assert!(error.contains("does not accept workload_expectation or actions")); - } -} diff --git a/crates/openshell-conformance/src/scenarios/mod.rs b/crates/openshell-conformance/src/scenarios/mod.rs index c5211b3690..bd6abdc7af 100644 --- a/crates/openshell-conformance/src/scenarios/mod.rs +++ b/crates/openshell-conformance/src/scenarios/mod.rs @@ -3,8 +3,6 @@ //! Registered, portable conformance scenarios. -mod sandbox_continuity; mod smoke; -pub use sandbox_continuity::SANDBOX_CONTINUITY_SCENARIO; pub use smoke::SMOKE_SCENARIO; diff --git a/crates/openshell-conformance/src/scenarios/sandbox_continuity.rs b/crates/openshell-conformance/src/scenarios/sandbox_continuity.rs deleted file mode 100644 index 81f8d4657e..0000000000 --- a/crates/openshell-conformance/src/scenarios/sandbox_continuity.rs +++ /dev/null @@ -1,207 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Product-visible sandbox continuity across host-side actions. - -use std::time::Duration; - -use serde::Deserialize; - -use crate::{ - HostAction, OpenShellRunner, PlanRun, Poll, Scenario, ScenarioFuture, WorkloadExpectation, -}; - -const CREATE_TIMEOUT: Duration = Duration::from_mins(10); -const COMMAND_TIMEOUT: Duration = Duration::from_mins(2); -const RECOVERY_TIMEOUT: Duration = Duration::from_mins(4); -const RECOVERY_INTERVAL: Duration = Duration::from_secs(2); - -#[derive(Debug, Deserialize)] -struct SandboxState { - name: String, - phase: String, -} - -/// Certify sandbox state and workspace continuity across host-side actions. -pub const SANDBOX_CONTINUITY_SCENARIO: Scenario = Scenario { - name: "sandbox-continuity", - description: "Verify sandbox state and workspace continuity across planned host actions.", - requires_plan: true, - run: run_sandbox_continuity, - validate_plan_run: Some(validate_plan_run), -}; - -fn run_sandbox_continuity<'a>( - runner: &'a mut OpenShellRunner, - plan_run: &'a PlanRun, -) -> ScenarioFuture<'a> { - Box::pin(async move { run_sandbox_continuity_inner(runner, plan_run).await }) -} - -fn validate_plan_run(plan_run: &PlanRun) -> Result<(), String> { - if plan_run.workload_expectation != Some(WorkloadExpectation::Reconciled) { - return Err( - "scenario 'sandbox-continuity' requires workload_expectation = \"reconciled\"" - .to_string(), - ); - } - if plan_run.actions.is_empty() { - return Err("scenario 'sandbox-continuity' requires at least one action".to_string()); - } - Ok(()) -} - -async fn run_sandbox_continuity_inner( - runner: &mut OpenShellRunner, - plan_run: &PlanRun, -) -> Result<(), String> { - // The VM driver permits at most 19 characters in a sandbox name. - let running_name = format!("ct-{}-r", runner.id()); - let stopped_name = format!("ct-{}-s", runner.id()); - let marker = format!("openshell-sandbox-continuity-{}", runner.id()); - let marker_path = "/sandbox/.openshell-sandbox-continuity"; - let running_script = - format!("printf '%s\\n' '{marker}' > {marker_path}; while true; do sleep 1; done"); - - create_retained_sandbox(runner, &running_name, &running_script, "running").await?; - assert_marker(runner, &running_name, marker_path, &marker, "pre-action").await?; - - create_retained_sandbox( - runner, - &stopped_name, - "while true; do sleep 1; done", - "stopped", - ) - .await?; - let stop = runner - .step("stop") - .description(format!("sandbox '{stopped_name}' stops")) - .with_timeout(COMMAND_TIMEOUT) - .run(&["sandbox", "stop", &stopped_name]) - .await - .map_err(|error| error.to_string())?; - stop.require_success()?; - wait_for_phase(runner, &stopped_name, "Stopped", "stopped-before-actions").await?; - - for action in &plan_run.actions { - apply_action_and_assert( - runner, - action, - &running_name, - &stopped_name, - marker_path, - &marker, - ) - .await?; - } - Ok(()) -} - -#[allow(clippy::too_many_arguments)] -async fn apply_action_and_assert( - runner: &mut OpenShellRunner, - action: &HostAction, - running_name: &str, - stopped_name: &str, - marker_path: &str, - marker: &str, -) -> Result<(), String> { - let step = format!("after-{}", action.name); - runner.execute_host_action(action).await?; - runner.check_gateway_status().await?; - wait_for_phase(runner, running_name, "Ready", &format!("running-{step}")).await?; - wait_for_phase(runner, stopped_name, "Stopped", &format!("stopped-{step}")).await?; - assert_marker(runner, running_name, marker_path, marker, &step).await -} - -async fn create_retained_sandbox( - runner: &mut OpenShellRunner, - name: &str, - script: &str, - step: &str, -) -> Result<(), String> { - runner.track_sandbox(name); - let create = runner - .step(format!("create-{step}")) - .description(format!("retained sandbox '{name}' is created")) - .with_timeout(CREATE_TIMEOUT) - .run(&[ - "sandbox", "create", "--name", name, "--from", "base", "--detach", "--no-tty", "--", - "sh", "-lc", script, - ]) - .await - .map_err(|error| error.to_string())?; - create.require_success() -} - -async fn assert_marker( - runner: &OpenShellRunner, - name: &str, - path: &str, - marker: &str, - step: &str, -) -> Result<(), String> { - let result = runner - .step(format!("marker-{step}")) - .description(format!("sandbox '{name}' retains its workspace marker")) - .with_timeout(COMMAND_TIMEOUT) - .run(&[ - "sandbox", "exec", "--name", name, "--no-tty", "--", "cat", path, - ]) - .await - .map_err(|error| error.to_string())?; - result.require_success()?; - if result.stdout().lines().any(|line| line.trim() == marker) { - Ok(()) - } else { - Err(result.failure_diagnostic(&format!( - "sandbox '{name}' stdout contains marker {marker:?}" - ))) - } -} - -async fn wait_for_phase( - runner: &mut OpenShellRunner, - name: &str, - expected_phase: &str, - step: &str, -) -> Result<(), String> { - let name = name.to_string(); - let expected_phase = expected_phase.to_string(); - let step = step.to_string(); - let poll_step = step.clone(); - runner - .poll_until( - &poll_step, - RECOVERY_TIMEOUT, - RECOVERY_INTERVAL, - async move |runner| { - let result = runner - .step(format!("{step}/get")) - .description(format!("sandbox '{name}' reaches phase {expected_phase}")) - .with_timeout(COMMAND_TIMEOUT) - .run(&["sandbox", "get", &name, "--output", "json"]) - .await; - match result { - Ok(result) if !result.success() => Poll::Pending( - result.failure_diagnostic(&format!("sandbox '{name}' can be retrieved")), - ), - Ok(result) => match result.json::() { - Ok(state) if state.name != name => Poll::Failed(format!( - "sandbox get returned {:?}; expected '{name}'", - state.name - )), - Ok(state) if state.phase == expected_phase => Poll::Ready(()), - Ok(state) => Poll::Pending(format!( - "sandbox '{name}' phase is {:?}; expected {expected_phase:?}", - state.phase - )), - Err(error) => Poll::Failed(error.to_string()), - }, - Err(error) => Poll::Pending(error.to_string()), - } - }, - ) - .await - .map_err(|error| error.to_string()) -} diff --git a/crates/openshell-conformance/src/scenarios/smoke.rs b/crates/openshell-conformance/src/scenarios/smoke.rs index 59f2d2b38f..7da9ef2210 100644 --- a/crates/openshell-conformance/src/scenarios/smoke.rs +++ b/crates/openshell-conformance/src/scenarios/smoke.rs @@ -5,7 +5,7 @@ use std::time::{Duration, Instant}; -use crate::{OpenShellRunner, PlanRun, STATUS_TIMEOUT, Scenario, ScenarioFuture}; +use crate::{OpenShellRunner, STATUS_TIMEOUT, Scenario, ScenarioFuture}; use serde::Deserialize; use tokio::time::sleep; @@ -32,12 +32,10 @@ struct SandboxListPage { pub const SMOKE_SCENARIO: Scenario = Scenario { name: "smoke", description: "Create, inspect, execute in, and delete a base sandbox.", - requires_plan: false, run: run_smoke, - validate_plan_run: None, }; -fn run_smoke<'a>(runner: &'a mut OpenShellRunner, _plan_run: &'a PlanRun) -> ScenarioFuture<'a> { +fn run_smoke(runner: &mut OpenShellRunner) -> ScenarioFuture<'_> { Box::pin(async move { run_smoke_inner(runner).await }) } diff --git a/crates/openshell-core/Cargo.toml b/crates/openshell-core/Cargo.toml index aa58f04700..601232def8 100644 --- a/crates/openshell-core/Cargo.toml +++ b/crates/openshell-core/Cargo.toml @@ -18,6 +18,7 @@ prost = { workspace = true } prost-types = { workspace = true } tonic = { workspace = true, features = ["channel", "tls-aws-lc"] } tonic-prost = { workspace = true } +tonic-types = { workspace = true } tokio = { workspace = true } tokio-stream = { workspace = true } thiserror = { workspace = true } diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index c308ac37e0..d3ad066608 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -319,9 +319,21 @@ pub struct TlsConfig { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct OidcConfig { - /// OIDC issuer URL (e.g., `http://localhost:8180/realms/openshell`). + /// OIDC issuer URL (e.g., `https://idp.example.com/realms/openshell`). pub issuer: String, + /// Permit cleartext OIDC metadata and JWKS requests to numeric loopback + /// addresses. This is a development-only escape hatch and never permits + /// cleartext requests to hostnames or non-loopback addresses. + #[serde(default)] + pub dangerously_allow_insecure_http: bool, + + /// Additional origins from which JWKS may be loaded. Entries must be + /// origins such as `https://www.googleapis.com`, without a path, query, + /// credentials, or fragment. The issuer origin is always allowed. + #[serde(default)] + pub jwks_allowed_origins: Vec, + /// Expected audience (`aud`) claim. Typically the OIDC client ID. pub audience: String, diff --git a/crates/openshell-core/src/lib.rs b/crates/openshell-core/src/lib.rs index b244431795..bd109992c5 100644 --- a/crates/openshell-core/src/lib.rs +++ b/crates/openshell-core/src/lib.rs @@ -44,6 +44,7 @@ pub mod proposals; pub mod proto; pub mod proto_struct; pub mod provider_credentials; +pub mod rpc_error; pub mod sandbox_env; pub mod secrets; pub mod settings; diff --git a/crates/openshell-core/src/rpc_error.rs b/crates/openshell-core/src/rpc_error.rs new file mode 100644 index 0000000000..3942d6c1f3 --- /dev/null +++ b/crates/openshell-core/src/rpc_error.rs @@ -0,0 +1,172 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Standard gRPC error details shared by gateway handlers and SDK clients. +//! +//! Retry guidance describes recovery from a failure. It never establishes that +//! repeating an arbitrary mutation is safe. + +use std::collections::HashMap; +use std::time::Duration; + +use prost::Message; +use tonic::{Code, Status}; +pub use tonic_types::{ErrorDetails, StatusExt}; + +/// Domain of gateway-owned machine-readable error reasons. +pub const ERROR_DOMAIN: &str = "openshell.nvidia.com"; + +/// Decode supported details without trusting inconsistent envelopes or delays. +/// Unknown and malformed details remain available on the original status. +pub fn decode_details(status: &Status) -> Option { + let envelope = tonic_types::pb::Status::decode(status.details()).ok()?; + if envelope.code != status.code() as i32 || envelope.message != status.message() { + return None; + } + let mut details = ErrorDetails::new(); + for detail in envelope.details { + match detail.type_url.rsplit('/').next() { + Some("google.rpc.BadRequest") => { + if let Ok(value) = tonic_types::pb::BadRequest::decode(detail.value.as_slice()) { + for violation in value.field_violations { + details.add_bad_request_violation(violation.field, violation.description); + } + } + } + Some("google.rpc.ErrorInfo") => { + if let Ok(value) = tonic_types::pb::ErrorInfo::decode(detail.value.as_slice()) { + details.set_error_info(value.reason, value.domain, value.metadata); + } + } + Some("google.rpc.RetryInfo") => { + if let Ok(value) = tonic_types::pb::RetryInfo::decode(detail.value.as_slice()) + && let Some(delay) = value.retry_delay + && (0..=315_576_000_000).contains(&delay.seconds) + && (0..1_000_000_000).contains(&delay.nanos) + { + details.set_retry_info(Some(Duration::new( + delay.seconds.cast_unsigned(), + delay.nanos.cast_unsigned(), + ))); + } + } + _ => {} + } + } + Some(details) +} + +/// Return a field-level validation failure without reflecting the field value. +pub fn invalid_argument(field: &str, message: impl Into) -> Status { + let message = message.into(); + let mut details = ErrorDetails::with_bad_request_violation(field, message.clone()); + details.set_error_info("INVALID_ARGUMENT", ERROR_DOMAIN, HashMap::new()); + Status::with_error_details(Code::InvalidArgument, message, details) +} + +/// Return a precondition failure with a stable reason. +pub fn failed_precondition(reason: &str, message: impl Into) -> Status { + Status::with_error_details( + Code::FailedPrecondition, + message, + ErrorDetails::with_error_info(reason, ERROR_DOMAIN, HashMap::new()), + ) +} + +/// A conditional write lost a race. Read fresh state before trying a new write. +pub fn resource_version_conflict(message: impl Into, version: Option) -> Status { + let mut metadata = HashMap::from([("recovery".into(), "REFRESH_STATE".into())]); + if let Some(version) = version { + metadata.insert("current_resource_version".into(), version.to_string()); + } + Status::with_error_details( + Code::Aborted, + message, + ErrorDetails::with_error_info("RESOURCE_VERSION_CONFLICT", ERROR_DOMAIN, metadata), + ) +} + +/// Return a transient failure with a minimum delay for retry-safe operations. +pub fn unavailable(reason: &str, message: impl Into, delay: Duration) -> Status { + let mut details = ErrorDetails::with_error_info(reason, ERROR_DOMAIN, HashMap::new()); + details.set_retry_info(Some(delay)); + Status::with_error_details(Code::Unavailable, message, details) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decode_ignores_invalid_delay_and_preserves_other_details() { + let status = invalid_argument("name", "invalid name"); + let mut envelope = tonic_types::pb::Status::decode(status.details()).unwrap(); + envelope.details.push(prost_types::Any { + type_url: "type.googleapis.com/google.rpc.RetryInfo".into(), + value: tonic_types::pb::RetryInfo { + retry_delay: Some(prost_types::Duration { + seconds: -1, + nanos: 0, + }), + } + .encode_to_vec(), + }); + envelope.details.push(prost_types::Any { + type_url: "type.googleapis.com/google.rpc.BadRequest".into(), + value: vec![255], + }); + let status = Status::with_details( + status.code(), + status.message(), + envelope.encode_to_vec().into(), + ); + let details = decode_details(&status).unwrap(); + assert!(details.retry_info().is_none()); + assert_eq!( + details.bad_request().unwrap().field_violations[0].field, + "name" + ); + let mismatched = Status::with_details( + Code::Internal, + status.message(), + status.details().to_vec().into(), + ); + assert!(decode_details(&mismatched).is_none()); + } + + #[test] + fn validation_identifies_the_field_and_reason() { + let status = invalid_argument("spec.command[0]", "must not be empty"); + let details = status.get_error_details(); + assert_eq!(status.code(), Code::InvalidArgument); + let violation = &details.bad_request().unwrap().field_violations[0]; + assert_eq!(violation.field, "spec.command[0]"); + assert_eq!(violation.description, "must not be empty"); + assert_eq!(details.error_info().unwrap().domain, ERROR_DOMAIN); + assert!(details.retry_info().is_none()); + } + + #[test] + fn conflict_requires_fresh_state_without_blind_retry_delay() { + let status = resource_version_conflict("concurrent write", Some(17)); + let details = status.get_error_details(); + let info = details.error_info().unwrap(); + assert_eq!(status.code(), Code::Aborted); + assert_eq!(info.reason, "RESOURCE_VERSION_CONFLICT"); + assert_eq!(info.metadata["recovery"], "REFRESH_STATE"); + assert_eq!(info.metadata["current_resource_version"], "17"); + assert!(details.retry_info().is_none()); + } + + #[test] + fn temporary_unavailability_has_a_reason_and_delay() { + let status = unavailable("GATEWAY_NOT_READY", "try later", Duration::from_secs(1)); + let details = status.get_error_details(); + assert_eq!(status.code(), Code::Unavailable); + assert_eq!(details.error_info().unwrap().reason, "GATEWAY_NOT_READY"); + assert_eq!( + details.retry_info().unwrap().retry_delay, + Some(Duration::from_secs(1)) + ); + } +} diff --git a/crates/openshell-ocsf/Cargo.toml b/crates/openshell-ocsf/Cargo.toml index 69c7b7e0aa..af387c88cf 100644 --- a/crates/openshell-ocsf/Cargo.toml +++ b/crates/openshell-ocsf/Cargo.toml @@ -10,6 +10,10 @@ rust-version.workspace = true license.workspace = true repository.workspace = true +[features] +# Share vendored-schema assertions with producer regression tests. +test-support = [] + [dependencies] chrono = { version = "0.4", features = ["serde"] } serde = { workspace = true } diff --git a/crates/openshell-ocsf/src/builders/http.rs b/crates/openshell-ocsf/src/builders/http.rs index a46032a505..8dd94a1905 100644 --- a/crates/openshell-ocsf/src/builders/http.rs +++ b/crates/openshell-ocsf/src/builders/http.rs @@ -10,7 +10,7 @@ use crate::events::{HttpActivityEvent, OcsfEvent}; use crate::objects::{Actor, Endpoint, FirewallRule, HttpRequest, HttpResponse}; /// Builder for HTTP Activity [4002] events. -pub struct HttpActivityBuilder<'a> { +pub struct HttpActivityBuilder<'a, Context = MissingHttpContext> { ctx: &'a EventContext, activity: ActivityId, action: Option, @@ -26,9 +26,35 @@ pub struct HttpActivityBuilder<'a> { message: Option, status_detail: Option, unmapped: serde_json::Map, + context: std::marker::PhantomData, } -impl<'a> HttpActivityBuilder<'a> { +/// Marker for an HTTP Activity builder that has neither request nor response. +pub struct MissingHttpContext; + +/// Marker for an HTTP Activity builder that has a request or response. +pub struct HasHttpContext; + +impl<'a> HttpActivityBuilder<'a, MissingHttpContext> { + /// Start building an HTTP Activity event. + /// + /// An HTTP Activity must include an HTTP request or response before it can + /// be built. + /// + /// ```compile_fail + /// use openshell_ocsf::{EventContext, HttpActivityBuilder}; + /// + /// let ctx = EventContext { + /// sandbox_id: String::new(), + /// sandbox_name: String::new(), + /// container_image: String::new(), + /// hostname: String::new(), + /// product_version: String::new(), + /// proxy_ip: "127.0.0.1".parse().unwrap(), + /// proxy_port: 3128, + /// }; + /// HttpActivityBuilder::new(&ctx).build(); + /// ``` #[must_use] pub fn new(ctx: &'a EventContext) -> Self { Self { @@ -47,19 +73,78 @@ impl<'a> HttpActivityBuilder<'a> { message: None, status_detail: None, unmapped: serde_json::Map::new(), + context: std::marker::PhantomData, } } + #[must_use] + pub fn http_request(self, req: HttpRequest) -> HttpActivityBuilder<'a, HasHttpContext> { + self.with_http_request(req) + } + + #[must_use] + pub fn http_response(self, resp: HttpResponse) -> HttpActivityBuilder<'a, HasHttpContext> { + self.with_http_response(resp) + } +} + +impl HttpActivityBuilder<'_, HasHttpContext> { #[must_use] pub fn http_request(mut self, req: HttpRequest) -> Self { self.http_request = Some(req); self } + #[must_use] pub fn http_response(mut self, resp: HttpResponse) -> Self { self.http_response = Some(resp); self } +} + +impl<'a, Context> HttpActivityBuilder<'a, Context> { + fn with_http_request(self, req: HttpRequest) -> HttpActivityBuilder<'a, HasHttpContext> { + HttpActivityBuilder { + ctx: self.ctx, + activity: self.activity, + action: self.action, + disposition: self.disposition, + severity: self.severity, + status: self.status, + http_request: Some(req), + http_response: self.http_response, + src_endpoint: self.src_endpoint, + dst_endpoint: self.dst_endpoint, + actor: self.actor, + firewall_rule: self.firewall_rule, + message: self.message, + status_detail: self.status_detail, + unmapped: self.unmapped, + context: std::marker::PhantomData, + } + } + + fn with_http_response(self, resp: HttpResponse) -> HttpActivityBuilder<'a, HasHttpContext> { + HttpActivityBuilder { + ctx: self.ctx, + activity: self.activity, + action: self.action, + disposition: self.disposition, + severity: self.severity, + status: self.status, + http_request: self.http_request, + http_response: Some(resp), + src_endpoint: self.src_endpoint, + dst_endpoint: self.dst_endpoint, + actor: self.actor, + firewall_rule: self.firewall_rule, + message: self.message, + status_detail: self.status_detail, + unmapped: self.unmapped, + context: std::marker::PhantomData, + } + } + #[must_use] pub fn src_endpoint(mut self, ep: Endpoint) -> Self { self.src_endpoint = Some(ep); @@ -78,6 +163,62 @@ impl<'a> HttpActivityBuilder<'a> { self } + #[must_use] + pub fn activity(mut self, id: ActivityId) -> Self { + self.activity = id; + self + } + + #[must_use] + pub fn action(mut self, id: ActionId) -> Self { + self.action = Some(id); + self + } + + #[must_use] + pub fn disposition(mut self, id: DispositionId) -> Self { + self.disposition = Some(id); + self + } + + #[must_use] + pub fn actor_process(mut self, process: crate::objects::Process) -> Self { + self.actor = Some(Actor { process }); + self + } + + #[must_use] + pub fn dst_endpoint(mut self, endpoint: Endpoint) -> Self { + self.dst_endpoint = Some(endpoint); + self + } + + #[must_use] + pub fn firewall_rule(mut self, name: &str, rule_type: &str) -> Self { + self.firewall_rule = Some(FirewallRule::new(name, rule_type)); + self + } + + #[must_use] + pub fn severity(mut self, id: SeverityId) -> Self { + self.severity = id; + self + } + + #[must_use] + pub fn status(mut self, id: StatusId) -> Self { + self.status = Some(id); + self + } + + #[must_use] + pub fn message(mut self, msg: impl Into) -> Self { + self.message = Some(msg.into()); + self + } +} + +impl HttpActivityBuilder<'_, HasHttpContext> { #[must_use] pub fn build(self) -> OcsfEvent { let activity_name = self.activity.http_label().to_string(); @@ -118,13 +259,6 @@ impl<'a> HttpActivityBuilder<'a> { } } -impl_activity_setter!(HttpActivityBuilder); -impl_action_disposition_setters!(HttpActivityBuilder); -impl_actor_process_setter!(HttpActivityBuilder); -impl_dst_endpoint_setter!(HttpActivityBuilder); -impl_firewall_rule_setter!(HttpActivityBuilder); -impl_builder_setters!(HttpActivityBuilder); - #[cfg(test)] mod tests { use super::*; diff --git a/crates/openshell-ocsf/src/enums/activity.rs b/crates/openshell-ocsf/src/enums/activity.rs index e31fea85a9..5152bcca09 100644 --- a/crates/openshell-ocsf/src/enums/activity.rs +++ b/crates/openshell-ocsf/src/enums/activity.rs @@ -47,6 +47,23 @@ pub enum ActivityId { } impl ActivityId { + /// Map an HTTP method to its HTTP Activity identifier. + #[must_use] + pub fn for_http_method(method: &str) -> Self { + match method.to_ascii_uppercase().as_str() { + "CONNECT" => Self::Open, + "DELETE" => Self::Close, + "GET" => Self::Reset, + "HEAD" => Self::Fail, + "OPTIONS" => Self::Refuse, + "POST" => Self::Traffic, + "PUT" => Self::Listen, + "TRACE" => Self::Trace, + "PATCH" => Self::Patch, + _ => Self::Other, + } + } + /// Returns a human-readable label for this activity in a network context. #[must_use] pub fn network_label(self) -> &'static str { @@ -163,6 +180,13 @@ mod tests { assert_eq!(ActivityId::Patch.http_label(), "Patch"); } + #[test] + fn maps_http_methods_to_http_activity_ids() { + assert_eq!(ActivityId::for_http_method("GET"), ActivityId::Reset); + assert_eq!(ActivityId::for_http_method("post"), ActivityId::Traffic); + assert_eq!(ActivityId::for_http_method("PROPFIND"), ActivityId::Other); + } + #[test] fn test_activity_process_labels() { assert_eq!(ActivityId::Open.process_label(), "Launch"); diff --git a/crates/openshell-ocsf/src/lib.rs b/crates/openshell-ocsf/src/lib.rs index e2bb0e8f3d..e65301e0c1 100644 --- a/crates/openshell-ocsf/src/lib.rs +++ b/crates/openshell-ocsf/src/lib.rs @@ -32,7 +32,7 @@ pub mod format; pub mod objects; pub mod tracing_layers; -#[cfg(test)] +#[cfg(any(test, feature = "test-support"))] pub mod validation; // --- Core event types --- diff --git a/crates/openshell-ocsf/src/validation/mod.rs b/crates/openshell-ocsf/src/validation/mod.rs index 28545337b0..8df2832faa 100644 --- a/crates/openshell-ocsf/src/validation/mod.rs +++ b/crates/openshell-ocsf/src/validation/mod.rs @@ -3,8 +3,8 @@ //! Schema validation utilities for testing OCSF events against vendored schemas. //! -//! These utilities are gated behind `#[cfg(test)]` — they are only available -//! in test builds. +//! Available in this crate's tests or through the `test-support` feature for +//! producer regression tests. pub mod schema; diff --git a/crates/openshell-ocsf/src/validation/schema.rs b/crates/openshell-ocsf/src/validation/schema.rs index ee21619ba0..73adeb9c6a 100644 --- a/crates/openshell-ocsf/src/validation/schema.rs +++ b/crates/openshell-ocsf/src/validation/schema.rs @@ -56,12 +56,26 @@ pub fn validate_required_fields(event: &Value, schema: &Value) { _ => return, }; + if let Some(fields) = schema + .get("constraints") + .and_then(|constraints| constraints.get("at_least_one")) + .and_then(Value::as_array) + { + assert!( + fields + .iter() + .filter_map(Value::as_str) + .any(|field| { event.get(field).is_some_and(|value| !value.is_null()) }), + "Missing at_least_one field from {fields:?}" + ); + } + for (name, def) in &attrs { let is_required = def.get("requirement").and_then(|r| r.as_str()) == Some("required"); let is_profile_field = def.get("profile").is_some() || def.get("profiles").is_some(); if is_required && !is_profile_field { assert!( - event.get(name).is_some(), + event.get(name).is_some_and(|value| !value.is_null()), "Missing required field '{name}' in OCSF event. Event keys: {:?}", event.as_object().map(|o| o.keys().collect::>()) ); @@ -92,6 +106,32 @@ pub fn validate_enum_value(event: &Value, field: &str, schema: &Value) { mod tests { use super::*; + #[test] + fn network_and_http_require_at_least_one_non_null_field() { + for (class, fields) in [ + ("network_activity", ["src_endpoint", "dst_endpoint"]), + ("http_activity", ["http_request", "http_response"]), + ] { + let schema = load_class_schema(class); + let mut event = serde_json::json!({ + "class_uid": schema["uid"], "severity_id": 1, "metadata": {}, + "time": 12345, "type_uid": 0, "activity_id": 0, "category_uid": 4 + }); + assert!( + std::panic::catch_unwind(|| validate_required_fields(&event, &schema)).is_err() + ); + for field in fields { + event[field] = Value::Null; + assert!( + std::panic::catch_unwind(|| validate_required_fields(&event, &schema)).is_err() + ); + event[field] = serde_json::json!({}); + validate_required_fields(&event, &schema); + event.as_object_mut().unwrap().remove(field); + } + } + } + #[test] fn test_load_class_schemas() { // These tests only pass when the vendored schemas are present diff --git a/crates/openshell-sandbox/Cargo.toml b/crates/openshell-sandbox/Cargo.toml index 3463f03767..c5a737d868 100644 --- a/crates/openshell-sandbox/Cargo.toml +++ b/crates/openshell-sandbox/Cargo.toml @@ -26,6 +26,7 @@ openshell-supervisor-process = { path = "../openshell-supervisor-process" } # Async runtime tokio = { workspace = true } +http = { workspace = true } # gRPC (tonic::Status downcast in error mapping) tonic = { workspace = true, features = ["channel", "tls-native-roots"] } @@ -76,6 +77,7 @@ telemetry = ["openshell-core/telemetry"] bundled-ca-roots = ["openshell-supervisor-network/bundled-ca-roots"] [dev-dependencies] +openshell-ocsf = { path = "../openshell-ocsf", features = ["test-support"] } tempfile = "3" temp-env = "0.3" tokio-tungstenite = { workspace = true } diff --git a/crates/openshell-sandbox/src/google_cloud_metadata.rs b/crates/openshell-sandbox/src/google_cloud_metadata.rs index 9e1e179872..7f90389ef6 100644 --- a/crates/openshell-sandbox/src/google_cloud_metadata.rs +++ b/crates/openshell-sandbox/src/google_cloud_metadata.rs @@ -13,10 +13,13 @@ //! discover it via the `GCE_METADATA_HOST` environment variable, which is //! set to the loopback address by `child_env_with_gcp_resolved()`. +use http::StatusCode; use miette::{IntoDiagnostic, Result}; use openshell_core::provider_credentials::ProviderCredentialState; use openshell_core::secrets; -use openshell_ocsf::{ActivityId, HttpActivityBuilder, SeverityId, StatusId, ocsf_emit}; +use openshell_ocsf::{ + ActivityId, HttpActivityBuilder, HttpRequest, SeverityId, StatusId, ocsf_emit, +}; use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; type MetadataResponse = (u16, &'static str, String); @@ -82,21 +85,27 @@ fn route_request( headers: &[(String, String)], ) -> MetadataResponse { if method != "GET" { + let status = StatusCode::METHOD_NOT_ALLOWED.as_u16(); emit_metadata_event( - ActivityId::Refuse, + method, + status, SeverityId::Low, StatusId::Failure, &format!("metadata: unsupported method {method}"), ); - return (405, "text/html", "Method Not Allowed".to_string()); + return (status, "text/html", "Method Not Allowed".to_string()); } if let Err(resp) = validate_metadata_headers(headers) { emit_metadata_event( - ActivityId::Refuse, + method, + resp.0, SeverityId::Medium, StatusId::Failure, - &format!("metadata: header validation failed for {path}"), + &format!( + "metadata: header validation failed for {}", + path.split('?').next().unwrap_or(path) + ), ); return resp; } @@ -106,9 +115,9 @@ fn route_request( let recursive = query.split('&').any(|p| p == "recursive=true"); match route { - PATH_TOKEN => handle_token(ctx), - PATH_EMAIL => handle_env(ctx, ENV_GCP_SERVICE_ACCOUNT_EMAIL), - PATH_PROJECT_ID => handle_env(ctx, ENV_GCP_PROJECT_ID), + PATH_TOKEN => handle_token(ctx, method), + PATH_EMAIL => handle_env(ctx, method, ENV_GCP_SERVICE_ACCOUNT_EMAIL), + PATH_PROJECT_ID => handle_env(ctx, method, ENV_GCP_PROJECT_ID), PATH_ALIASES => (200, "text/plain", "default\n".to_string()), PATH_SCOPES => ( 200, @@ -132,14 +141,16 @@ fn route_request( } "/computeMetadata/v1/instance" => (200, "text/plain", "service-accounts/\n".to_string()), _ => { + let status = StatusCode::NOT_FOUND.as_u16(); emit_metadata_event( - ActivityId::Refuse, + method, + status, SeverityId::Low, StatusId::Failure, &format!("metadata: unknown path {route}"), ); ( - 404, + status, "application/json", serde_json::json!({"error": "not_found"}).to_string(), ) @@ -147,8 +158,9 @@ fn route_request( } } -fn handle_token(ctx: &MetadataContext) -> MetadataResponse { +fn handle_token(ctx: &MetadataContext, method: &str) -> MetadataResponse { let Some((placeholder, expires_in)) = ctx.credentials.gcp_token_response() else { + let status = StatusCode::SERVICE_UNAVAILABLE.as_u16(); let has_resolver = ctx.credentials.resolver().is_some(); let (msg, error_key) = if has_resolver { ( @@ -161,16 +173,18 @@ fn handle_token(ctx: &MetadataContext) -> MetadataResponse { "credentials_unavailable", ) }; - emit_metadata_event(ActivityId::Fail, SeverityId::Medium, StatusId::Failure, msg); + emit_metadata_event(method, status, SeverityId::Medium, StatusId::Failure, msg); return ( - 503, + status, "application/json", serde_json::json!({"error": error_key}).to_string(), ); }; + let status = StatusCode::OK.as_u16(); emit_metadata_event( - ActivityId::Open, + method, + status, SeverityId::Informational, StatusId::Success, "metadata: token placeholder served", @@ -181,7 +195,7 @@ fn handle_token(ctx: &MetadataContext) -> MetadataResponse { "expires_in": expires_in, "token_type": "Bearer" }); - (200, "application/json", body.to_string()) + (status, "application/json", body.to_string()) } fn handle_service_account_recursive(ctx: &MetadataContext) -> MetadataResponse { @@ -209,28 +223,32 @@ fn handle_service_account_recursive(ctx: &MetadataContext) -> MetadataResponse { /// Unlike `handle_token` which serves placeholders, this resolves to the real /// value. This matches real GCE metadata server behavior and is safe because /// these values are non-secret configuration (project IDs, email addresses). -fn handle_env(ctx: &MetadataContext, env_key: &str) -> MetadataResponse { +fn handle_env(ctx: &MetadataContext, method: &str, env_key: &str) -> MetadataResponse { let Some(resolver) = ctx.credentials.resolver() else { + let status = StatusCode::SERVICE_UNAVAILABLE.as_u16(); emit_metadata_event( - ActivityId::Fail, + method, + status, SeverityId::Medium, StatusId::Failure, &format!("metadata: {env_key} request but no credentials configured"), ); - return (503, "text/plain", String::new()); + return (status, "text/plain", String::new()); }; let placeholder = secrets::placeholder_for_env_key(env_key); resolver.resolve_placeholder(&placeholder).map_or_else( || { + let status = StatusCode::NOT_FOUND.as_u16(); emit_metadata_event( - ActivityId::Fail, + method, + status, SeverityId::Low, StatusId::Failure, &format!("metadata: {env_key} not configured"), ); ( - 404, + status, "application/json", serde_json::json!({"error": "not_found"}).to_string(), ) @@ -305,18 +323,41 @@ where } fn emit_metadata_event( - activity: ActivityId, + method: &str, + response_code: u16, severity: SeverityId, status: StatusId, message: &str, ) { - let event = HttpActivityBuilder::new(crate::ocsf_ctx()) - .activity(activity) + ocsf_emit!(build_metadata_event( + method, + response_code, + severity, + status, + message + )); +} + +fn build_metadata_event( + method: &str, + response_code: u16, + severity: SeverityId, + status: StatusId, + message: &str, +) -> openshell_ocsf::OcsfEvent { + HttpActivityBuilder::new(crate::ocsf_ctx()) + .activity(ActivityId::for_http_method(method)) + .http_request(HttpRequest { + http_method: method.parse().expect("HTTP method parsing is infallible"), + url: None, + }) + .http_response(openshell_ocsf::HttpResponse { + code: response_code, + }) .severity(severity) .status(status) .message(message.to_string()) - .build(); - ocsf_emit!(event); + .build() } #[cfg(test)] @@ -342,6 +383,51 @@ mod tests { vec![("Metadata-Flavor".to_string(), "Google".to_string())] } + #[test] + fn metadata_events_include_response_for_ocsf18() { + use openshell_ocsf::tracing_layers::OcsfJsonlLayer; + use openshell_ocsf::validation::{ + load_class_schema, validate_enum_value, validate_required_fields, + }; + use tracing_subscriber::prelude::*; + + let schema = load_class_schema("http_activity"); + for (method, path, headers, expected_code, expected_activity_id) in [ + ("GET", PATH_TOKEN, flavor_headers(), 200, 3), + ("GET", "/?token=secret-query", Vec::new(), 403, 3), + ("GET", "/unknown", flavor_headers(), 404, 3), + ("POST", PATH_TOKEN, flavor_headers(), 405, 6), + ("GET", PATH_TOKEN, flavor_headers(), 503, 3), + ("GET", PATH_EMAIL, flavor_headers(), 404, 3), + ] { + let env = if expected_code == 503 { + HashMap::new() + } else { + HashMap::from([("GCP_ADC_ACCESS_TOKEN".to_string(), "test-token".to_string())]) + }; + let ctx = make_context(env); + let log = tempfile::NamedTempFile::new().unwrap(); + let subscriber = + tracing_subscriber::registry().with(OcsfJsonlLayer::new(log.reopen().unwrap())); + let response = tracing::subscriber::with_default(subscriber, || { + route_request(&ctx, method, path, &headers) + }); + assert_eq!(response.0, expected_code); + let output = std::fs::read_to_string(log.path()).unwrap(); + let json: serde_json::Value = serde_json::from_str(&output).unwrap(); + assert_eq!(json["http_response"]["code"], response.0); + assert!(!output.contains("secret-query"), "{output}"); + assert_eq!( + json["activity_id"], expected_activity_id, + "method: {method}" + ); + assert_eq!(json["http_request"]["http_method"], method); + assert!(json["http_request"].get("url").is_none()); + validate_required_fields(&json, &schema); + validate_enum_value(&json, "activity_id", &schema); + } + } + #[test] fn token_returns_placeholder_not_real_value() { let ctx = make_context(HashMap::from([( diff --git a/crates/openshell-sdk/src/client.rs b/crates/openshell-sdk/src/client.rs index c789aded99..c236742739 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -1179,17 +1179,7 @@ fn sandbox_template_from_response( } fn map_status(status: tonic::Status) -> SdkError { - let message = status.message().to_string(); - match status.code() { - tonic::Code::NotFound => SdkError::NotFound { message }, - tonic::Code::AlreadyExists => SdkError::AlreadyExists { message }, - tonic::Code::InvalidArgument => SdkError::invalid_config(message), - tonic::Code::Unauthenticated | tonic::Code::PermissionDenied => SdkError::auth(message), - _ => SdkError::Rpc { - code: status.code() as i32, - message, - }, - } + SdkError::from_status(status) } #[cfg(test)] diff --git a/crates/openshell-sdk/src/error.rs b/crates/openshell-sdk/src/error.rs index 343d66fd05..be61bb00e9 100644 --- a/crates/openshell-sdk/src/error.rs +++ b/crates/openshell-sdk/src/error.rs @@ -5,6 +5,7 @@ //! TUI, language bindings) can decide how to render or remap each kind. use miette::Diagnostic; +pub use openshell_core::rpc_error::ErrorDetails; use thiserror::Error; /// SDK result type alias. @@ -24,6 +25,8 @@ pub enum SdkError { InvalidConfig { /// Error message. message: String, + /// Original gateway status, when validation happened remotely. + status: Option>, }, /// TLS material parse or rustls config build failure. @@ -57,6 +60,8 @@ pub enum SdkError { message: String, /// Whether retrying the same operation may succeed. retryable: bool, + /// Original gateway status, when authentication happened remotely. + status: Option>, }, /// Local IO failure (file read, listener bind, socket). @@ -74,6 +79,8 @@ pub enum SdkError { NotFound { /// Error message. message: String, + /// Original gateway status, including details and metadata. + status: Box, }, /// Gateway reported the requested object already exists (gRPC `AlreadyExists`). @@ -82,6 +89,8 @@ pub enum SdkError { AlreadyExists { /// Error message. message: String, + /// Original gateway status, including details and metadata. + status: Box, }, /// Catch-all for gRPC errors not mapped to a more specific variant. @@ -92,6 +101,8 @@ pub enum SdkError { code: i32, /// Error message. message: String, + /// Original gateway status, including unknown details and metadata. + status: Box, }, } @@ -100,6 +111,7 @@ impl SdkError { pub fn invalid_config(message: impl Into) -> Self { Self::InvalidConfig { message: message.into(), + status: None, } } @@ -122,6 +134,7 @@ impl SdkError { Self::Auth { message: message.into(), retryable: false, + status: None, } } @@ -130,9 +143,59 @@ impl SdkError { Self::Auth { message: message.into(), retryable, + status: None, } } + /// Map a gateway failure while retaining its complete transport status. + pub fn from_status(status: tonic::Status) -> Self { + let message = status.message().to_owned(); + let code = status.code(); + let status = Box::new(status); + match code { + tonic::Code::NotFound => Self::NotFound { message, status }, + tonic::Code::AlreadyExists => Self::AlreadyExists { message, status }, + tonic::Code::InvalidArgument => Self::InvalidConfig { + message, + status: Some(status), + }, + tonic::Code::Unauthenticated | tonic::Code::PermissionDenied => Self::Auth { + message, + retryable: false, + status: Some(status), + }, + _ => Self::Rpc { + code: code as i32, + message, + status, + }, + } + } + + /// Complete original status, including unrecognized details and metadata. + pub fn grpc_status(&self) -> Option<&tonic::Status> { + match self { + Self::InvalidConfig { status, .. } | Self::Auth { status, .. } => status.as_deref(), + Self::NotFound { status, .. } + | Self::AlreadyExists { status, .. } + | Self::Rpc { status, .. } => Some(status), + _ => None, + } + } + + /// Decode standard rich details. Malformed details never replace the failure. + /// The original bytes remain accessible through [`Self::grpc_status`]. + pub fn error_details(&self) -> Option { + self.grpc_status() + .and_then(openshell_core::rpc_error::decode_details) + } + + /// Server-suggested minimum retry delay, if supplied. + /// This does not establish that repeating a mutation is safe. + pub fn retry_delay(&self) -> Option { + self.error_details()?.retry_info()?.retry_delay + } + /// Stable string code for cross-language binding consumers. /// /// Returns one of: `invalid_config`, `tls`, `connect`, `auth`, `io`, @@ -168,3 +231,67 @@ impl SdkError { } } } + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::rpc_error; + use openshell_core::rpc_error::StatusExt; + + #[test] + fn preserves_details_and_metadata_for_every_status_class() { + for code in [ + tonic::Code::InvalidArgument, + tonic::Code::NotFound, + tonic::Code::AlreadyExists, + tonic::Code::Unauthenticated, + tonic::Code::PermissionDenied, + tonic::Code::Aborted, + tonic::Code::Unavailable, + ] { + let mut status = tonic::Status::with_error_details( + code, + "invalid name", + rpc_error::invalid_argument("name", "invalid name").get_error_details(), + ); + status + .metadata_mut() + .insert("request-id", "test-correlation".parse().unwrap()); + let original = status.details().to_vec(); + let error = SdkError::from_status(status); + let raw = error.grpc_status().unwrap(); + assert_eq!(raw.code(), code); + assert_eq!(raw.details(), original); + assert_eq!( + raw.metadata().get("request-id").unwrap(), + "test-correlation" + ); + assert_eq!( + error + .error_details() + .unwrap() + .bad_request() + .unwrap() + .field_violations[0] + .field, + "name" + ); + } + } + + #[test] + fn malformed_details_do_not_replace_the_original_error() { + let status = + tonic::Status::with_details(tonic::Code::Unavailable, "offline", vec![255].into()); + let error = SdkError::from_status(status); + assert_eq!(error.grpc_status().unwrap().details(), &[255]); + assert!(error.error_details().is_none()); + assert!(error.retry_delay().is_none()); + } + + #[test] + fn local_errors_have_no_transport_status() { + assert!(SdkError::invalid_config("local").grpc_status().is_none()); + assert!(SdkError::auth("local").error_details().is_none()); + } +} diff --git a/crates/openshell-server/src/auth/oidc.rs b/crates/openshell-server/src/auth/oidc.rs index 303dcb3c53..002385de95 100644 --- a/crates/openshell-server/src/auth/oidc.rs +++ b/crates/openshell-server/src/auth/oidc.rs @@ -19,6 +19,7 @@ use openshell_core::OidcConfig; use reqwest::Client; use serde::Deserialize; use std::collections::{HashMap, HashSet}; +use std::net::IpAddr; use std::str::FromStr; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -52,6 +53,11 @@ const STALE_KEY_GRACE_MULTIPLIER: u32 = 3; /// against the issuer's JWKS endpoint. const KID_MISS_REFRESH_COOLDOWN: Duration = Duration::from_secs(1); +/// OIDC metadata is small. These limits bound memory consumption before JSON +/// deserialization while leaving ample room for large enterprise key sets. +const OIDC_DISCOVERY_MAX_BYTES: usize = 64 * 1024; +const JWKS_MAX_BYTES: usize = 1024 * 1024; + /// Cached JWKS key set fetched from the OIDC issuer. /// /// A `refresh_mutex` ensures that only one refresh runs at a time, @@ -92,6 +98,176 @@ struct OidcDiscovery { jwks_uri: String, } +fn is_numeric_loopback(host: &str) -> bool { + match host.parse::() { + Ok(IpAddr::V4(address)) => address.is_loopback(), + Ok(IpAddr::V6(address)) => { + address.is_loopback() + || address + .to_ipv4_mapped() + .is_some_and(|mapped| mapped.is_loopback()) + } + Err(_) => false, + } +} + +fn validate_oidc_url( + value: &str, + description: &str, + dangerously_allow_insecure_http: bool, +) -> Result { + let parsed = url::Url::parse(value) + .map_err(|error| format!("{description} must be an absolute URL: {error}"))?; + + if parsed.host_str().is_none() || !parsed.username().is_empty() || parsed.password().is_some() { + return Err(format!( + "{description} must include a host and must not include credentials" + )); + } + + match parsed.scheme() { + "https" => Ok(parsed), + "http" + if dangerously_allow_insecure_http + && parsed.host_str().is_some_and(is_numeric_loopback) => + { + Ok(parsed) + } + "http" if dangerously_allow_insecure_http => Err(format!( + "{description} may use insecure HTTP only with a numeric loopback address" + )), + "http" => Err(format!( + "{description} must use HTTPS; numeric-loopback HTTP requires the development-only dangerously_allow_insecure_http acknowledgement" + )), + scheme => Err(format!( + "{description} must use HTTPS, not the '{scheme}' scheme" + )), + } +} + +fn validate_jwks_origin( + value: &str, + dangerously_allow_insecure_http: bool, +) -> Result { + let origin = validate_oidc_url( + value, + "OIDC JWKS allowed origin", + dangerously_allow_insecure_http, + )?; + if origin.path() != "/" || origin.query().is_some() || origin.fragment().is_some() { + return Err(format!( + "OIDC JWKS allowed origin '{value}' must not include a path, query, or fragment" + )); + } + Ok(origin) +} + +fn validate_jwks_url( + value: &str, + issuer: &url::Url, + config: &OidcConfig, +) -> Result { + let jwks = validate_oidc_url( + value, + "OIDC discovery jwks_uri", + config.dangerously_allow_insecure_http, + )?; + if jwks.fragment().is_some() { + return Err("OIDC discovery jwks_uri must not include a fragment".to_string()); + } + if jwks.origin() == issuer.origin() { + return Ok(jwks); + } + + for allowed in &config.jwks_allowed_origins { + let allowed = validate_jwks_origin(allowed, config.dangerously_allow_insecure_http)?; + if jwks.origin() == allowed.origin() { + return Ok(jwks); + } + } + + Err(format!( + "OIDC discovery jwks_uri origin '{}' does not match issuer origin '{}'; add the JWKS origin to jwks_allowed_origins only if it is trusted", + jwks.origin().ascii_serialization(), + issuer.origin().ascii_serialization(), + )) +} + +fn is_json_content_type(value: &reqwest::header::HeaderValue) -> bool { + let Ok(value) = value.to_str() else { + return false; + }; + let media_type = value.split(';').next().map(str::trim).unwrap_or_default(); + media_type.eq_ignore_ascii_case("application/json") + || media_type + .to_ascii_lowercase() + .strip_prefix("application/") + .is_some_and(|subtype| subtype.ends_with("+json")) +} + +async fn fetch_bounded_json( + client: &Client, + url: &url::Url, + description: &str, + max_bytes: usize, +) -> Result { + let mut response = client + .get(url.clone()) + .send() + .await + .map_err(|error| format!("{description} request failed: {error}"))?; + + if !response.status().is_success() { + return Err(format!( + "{description} request returned HTTP {}", + response.status() + )); + } + if !response + .headers() + .get(reqwest::header::CONTENT_TYPE) + .is_some_and(is_json_content_type) + { + return Err(format!( + "{description} response must use an application/json or application/*+json content type" + )); + } + if response + .content_length() + .is_some_and(|length| length > max_bytes as u64) + { + return Err(format!( + "{description} response exceeds the {max_bytes}-byte limit" + )); + } + + let initial_capacity = response + .content_length() + .and_then(|length| usize::try_from(length).ok()) + .unwrap_or_default() + .min(max_bytes); + let mut body = Vec::with_capacity(initial_capacity); + while let Some(chunk) = response + .chunk() + .await + .map_err(|error| format!("{description} response body failed: {error}"))? + { + let next_length = body + .len() + .checked_add(chunk.len()) + .ok_or_else(|| format!("{description} response length overflow"))?; + if next_length > max_bytes { + return Err(format!( + "{description} response exceeds the {max_bytes}-byte limit" + )); + } + body.extend_from_slice(&chunk); + } + + serde_json::from_slice(&body) + .map_err(|error| format!("{description} response parse failed: {error}")) +} + /// JWKS key set. #[derive(Deserialize)] struct JwkSet { @@ -399,6 +575,17 @@ impl JwksCache { /// Create a new JWKS cache, discovering the JWKS URI and fetching the /// initial key set. pub async fn new(config: &OidcConfig) -> Result { + let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let http = Client::builder() + .timeout(Duration::from_secs(10)) + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|e| format!("failed to create HTTP client: {e}"))?; + + Self::new_with_client(config, http).await + } + + async fn new_with_client(config: &OidcConfig, http: Client) -> Result { if config.jwks_ttl_secs == 0 { return Err( "jwks_ttl_secs must be greater than zero (0 would refresh on every request and \ @@ -407,27 +594,35 @@ impl JwksCache { ); } - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - let http = Client::builder() - .timeout(Duration::from_secs(10)) - .build() - .map_err(|e| format!("failed to create HTTP client: {e}"))?; + let issuer_url = validate_oidc_url( + &config.issuer, + "OIDC issuer", + config.dangerously_allow_insecure_http, + )?; + if issuer_url.query().is_some() || issuer_url.fragment().is_some() { + return Err("OIDC issuer must not include a query or fragment".to_string()); + } + // Validate every configured exception at startup, even when the + // discovery document ultimately uses the issuer origin. + for allowed in &config.jwks_allowed_origins { + validate_jwks_origin(allowed, config.dangerously_allow_insecure_http)?; + } // Discover JWKS URI from the OIDC discovery endpoint. - let discovery_url = format!( + let discovery_url = url::Url::parse(&format!( "{}/.well-known/openid-configuration", config.issuer.trim_end_matches('/') - ); + )) + .map_err(|error| format!("failed to construct OIDC discovery URL: {error}"))?; info!(url = %discovery_url, "Discovering OIDC configuration"); - let discovery: OidcDiscovery = http - .get(&discovery_url) - .send() - .await - .map_err(|e| format!("OIDC discovery request failed: {e}"))? - .json() - .await - .map_err(|e| format!("OIDC discovery response parse failed: {e}"))?; + let discovery: OidcDiscovery = fetch_bounded_json( + &http, + &discovery_url, + "OIDC discovery", + OIDC_DISCOVERY_MAX_BYTES, + ) + .await?; // Validate the discovery document's issuer matches our configured issuer. let expected = config.issuer.trim_end_matches('/'); @@ -438,11 +633,13 @@ impl JwksCache { )); } - info!(jwks_uri = %discovery.jwks_uri, "OIDC JWKS URI discovered"); + let jwks_uri = validate_jwks_url(&discovery.jwks_uri, &issuer_url, config)?; + + info!(jwks_uri = %jwks_uri, "OIDC JWKS URI discovered"); let cache = Self { keys: Arc::new(RwLock::new(HashMap::new())), - jwks_uri: discovery.jwks_uri, + jwks_uri: jwks_uri.to_string(), ttl: Duration::from_secs(config.jwks_ttl_secs), last_refresh: Arc::new(RwLock::new( Instant::now() @@ -474,15 +671,10 @@ impl JwksCache { async fn refresh_keys(&self) -> Result<(), String> { debug!(uri = %self.jwks_uri, "Refreshing JWKS keys"); - let jwk_set: JwkSet = self - .http - .get(&self.jwks_uri) - .send() - .await - .map_err(|e| format!("JWKS fetch failed: {e}"))? - .json() - .await - .map_err(|e| format!("JWKS parse failed: {e}"))?; + let jwks_uri = url::Url::parse(&self.jwks_uri) + .map_err(|error| format!("cached JWKS URI became invalid: {error}"))?; + let jwk_set: JwkSet = + fetch_bounded_json(&self.http, &jwks_uri, "JWKS", JWKS_MAX_BYTES).await?; let mut new_keys = HashMap::new(); let mut poisoned_kids = HashSet::new(); @@ -716,6 +908,292 @@ impl Authenticator for OidcAuthenticator { mod tests { use super::*; + fn transport_test_config(issuer: impl Into) -> OidcConfig { + OidcConfig { + issuer: issuer.into(), + dangerously_allow_insecure_http: false, + jwks_allowed_origins: Vec::new(), + audience: "test-audience".to_string(), + jwks_ttl_secs: 3600, + roles_claim: "roles".to_string(), + admin_role: "admin".to_string(), + user_role: "user".to_string(), + scopes_claim: String::new(), + } + } + + #[tokio::test] + async fn oidc_rejects_http_issuer_without_development_acknowledgement() { + let error = JwksCache::new(&transport_test_config("http://127.0.0.1:9/issuer")) + .await + .expect_err("cleartext issuers must fail before discovery"); + + assert!( + error.contains("must use HTTPS"), + "unexpected error: {error}" + ); + } + + #[tokio::test] + async fn oidc_rejects_non_loopback_http_even_when_acknowledged() { + let mut config = transport_test_config("http://192.0.2.1/issuer"); + config.dangerously_allow_insecure_http = true; + + let error = JwksCache::new(&config) + .await + .expect_err("the escape hatch must remain limited to numeric loopback"); + + assert!( + error.contains("only with a numeric loopback"), + "unexpected error: {error}" + ); + } + + #[test] + fn oidc_rejects_http_jwks_from_https_discovery() { + let issuer = url::Url::parse("https://idp.example.com/issuer").unwrap(); + let config = transport_test_config(issuer.as_str()); + + let error = validate_jwks_url("http://idp.example.com/jwks", &issuer, &config) + .expect_err("HTTPS discovery must not establish an HTTP trust root"); + + assert!( + error.contains("must use HTTPS"), + "unexpected error: {error}" + ); + } + + #[test] + fn oidc_rejects_cross_origin_jwks_unless_origin_is_allowlisted() { + let issuer = url::Url::parse("https://accounts.example.com/issuer").unwrap(); + let mut config = transport_test_config(issuer.as_str()); + let jwks = "https://keys.example.com/oauth/jwks"; + + let error = validate_jwks_url(jwks, &issuer, &config) + .expect_err("untrusted cross-origin JWKS must be rejected"); + assert!( + error.contains("does not match issuer origin"), + "unexpected error: {error}" + ); + + config.jwks_allowed_origins = vec!["https://keys.example.com".to_string()]; + assert_eq!( + validate_jwks_url(jwks, &issuer, &config) + .expect("an explicitly trusted origin should be accepted") + .as_str(), + jwks + ); + } + + #[test] + fn oidc_json_content_types_are_strict() { + use reqwest::header::HeaderValue; + + assert!(is_json_content_type(&HeaderValue::from_static( + "application/json; charset=utf-8" + ))); + assert!(is_json_content_type(&HeaderValue::from_static( + "application/jwk-set+json" + ))); + assert!(!is_json_content_type(&HeaderValue::from_static( + "text/html" + ))); + } + + #[tokio::test] + async fn oidc_loads_discovery_and_jwks_from_tls_idp_with_rotated_local_ca() { + use rcgen::{BasicConstraints, CertificateParams, IsCa, KeyPair}; + use rustls::pki_types::PrivateKeyDer; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let mut old_ca_params = CertificateParams::new(Vec::::new()).unwrap(); + old_ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + let old_ca_key = KeyPair::generate().unwrap(); + let old_ca_cert = old_ca_params.self_signed(&old_ca_key).unwrap(); + + let mut ca_params = CertificateParams::new(Vec::::new()).unwrap(); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + let ca_key = KeyPair::generate().unwrap(); + let ca_cert = ca_params.self_signed(&ca_key).unwrap(); + + let server_params = CertificateParams::new(vec!["localhost".to_string()]).unwrap(); + let server_key = KeyPair::generate().unwrap(); + let server_cert = server_params + .signed_by(&server_key, &ca_cert, &ca_key) + .unwrap(); + let server_config = rustls::ServerConfig::builder() + .with_no_client_auth() + .with_single_cert( + vec![server_cert.der().clone()], + PrivateKeyDer::Pkcs8(server_key.serialize_der().into()), + ) + .unwrap(); + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server_config)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let issuer = format!("https://localhost:{port}/issuer"); + let discovery = serde_json::json!({ + "issuer": issuer, + "jwks_uri": format!("{issuer}/jwks"), + }) + .to_string(); + let jwks = serde_json::json!({ + "keys": [{ + "kid": TEST_KID, + "kty": "RSA", + "n": TEST_RSA_KEY.modulus_b64, + "e": TEST_RSA_KEY.exponent_b64, + }], + }) + .to_string(); + + let server = tokio::spawn(async move { + let mut responses_served = 0; + while responses_served < 2 { + let (stream, _) = listener.accept().await.unwrap(); + let Ok(mut stream) = acceptor.accept(stream).await else { + // A client with the retired CA aborts the TLS handshake. + continue; + }; + responses_served += 1; + let mut request = Vec::new(); + let mut chunk = [0_u8; 1024]; + loop { + let read = stream.read(&mut chunk).await.unwrap(); + if read == 0 { + break; + } + request.extend_from_slice(&chunk[..read]); + if request.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + let request = String::from_utf8_lossy(&request); + let body = if request.starts_with("GET /issuer/.well-known/openid-configuration ") { + &discovery + } else if request.starts_with("GET /issuer/jwks ") { + &jwks + } else { + panic!("unexpected TLS IdP request: {request}"); + }; + let response = format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ); + stream.write_all(response.as_bytes()).await.unwrap(); + stream.shutdown().await.unwrap(); + } + }); + + let old_client = Client::builder() + .add_root_certificate( + reqwest::Certificate::from_pem(old_ca_cert.pem().as_bytes()).unwrap(), + ) + .build() + .unwrap(); + old_client + .get(format!("{issuer}/.well-known/openid-configuration")) + .send() + .await + .expect_err("a client retaining only the retired CA must reject the IdP"); + + // Initialization succeeds after the client receives the rotated trust + // anchor, and both discovery and JWKS stay on the authenticated channel. + let client = Client::builder() + .add_root_certificate(reqwest::Certificate::from_pem(ca_cert.pem().as_bytes()).unwrap()) + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + let config = transport_test_config(issuer.clone()); + let cache = JwksCache::new_with_client(&config, client) + .await + .expect("TLS discovery and JWKS should accept the rotated CA"); + + let token = mint_rs256( + &claims_for(&issuer, "test-audience", now_secs() + 3600), + TEST_KID, + ); + cache + .validate_token(&token) + .await + .expect("the key loaded over TLS should validate tokens"); + server.await.unwrap(); + } + + #[tokio::test] + async fn oidc_rejects_redirected_discovery() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/issuer/.well-known/openid-configuration")) + .respond_with( + ResponseTemplate::new(302).append_header("location", "http://127.0.0.1:9"), + ) + .mount(&server) + .await; + let mut config = transport_test_config(format!("{}/issuer", server.uri())); + config.dangerously_allow_insecure_http = true; + + let error = JwksCache::new(&config) + .await + .expect_err("redirects must not move OIDC trust establishment"); + + assert!( + error.contains("HTTP 302"), + "unexpected redirect error: {error}" + ); + } + + #[tokio::test] + async fn oidc_rejects_oversized_discovery_response() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/issuer/.well-known/openid-configuration")) + .respond_with( + ResponseTemplate::new(200) + .set_body_raw(vec![b' '; OIDC_DISCOVERY_MAX_BYTES + 1], "application/json"), + ) + .mount(&server) + .await; + let mut config = transport_test_config(format!("{}/issuer", server.uri())); + config.dangerously_allow_insecure_http = true; + + let error = JwksCache::new(&config) + .await + .expect_err("oversized metadata must be rejected before parsing"); + + assert!( + error.contains("exceeds the 65536-byte limit"), + "unexpected size error: {error}" + ); + } + + #[tokio::test] + async fn oidc_rejects_non_json_discovery_response() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/issuer/.well-known/openid-configuration")) + .respond_with(ResponseTemplate::new(200).set_body_raw("{}", "text/html")) + .mount(&server) + .await; + let mut config = transport_test_config(format!("{}/issuer", server.uri())); + config.dangerously_allow_insecure_http = true; + + let error = JwksCache::new(&config) + .await + .expect_err("metadata with an unsafe media type must be rejected"); + + assert!(error.contains("content type"), "unexpected error: {error}"); + } + #[test] fn health_is_unauthenticated() { assert!(is_unauthenticated_method("/openshell.v1.OpenShell/Health")); @@ -946,6 +1424,8 @@ mod tests { JwksCache::new(&OidcConfig { issuer, + dangerously_allow_insecure_http: true, + jwks_allowed_origins: Vec::new(), audience: TEST_AUDIENCE.to_owned(), jwks_ttl_secs: 3600, roles_claim: "realm_access.roles".to_owned(), @@ -1283,6 +1763,8 @@ mod tests { fn test_oidc_config(issuer: &str) -> OidcConfig { OidcConfig { issuer: issuer.to_string(), + dangerously_allow_insecure_http: true, + jwks_allowed_origins: Vec::new(), audience: "test-audience".to_string(), jwks_ttl_secs: 3600, roles_claim: "roles".to_string(), diff --git a/crates/openshell-server/src/auth/workspace_authz.rs b/crates/openshell-server/src/auth/workspace_authz.rs index 2958d656c7..2341cb7874 100644 --- a/crates/openshell-server/src/auth/workspace_authz.rs +++ b/crates/openshell-server/src/auth/workspace_authz.rs @@ -109,7 +109,8 @@ pub async fn authorize_list_workspace_selector( pub fn selected_workspace_name(selector: Option<&WorkspaceSelector>) -> Result<&str, Status> { match selected_workspace(selector)? { WorkspaceSelection::Workspace(workspace) => Ok(workspace), - WorkspaceSelection::AllWorkspaces(_) => Err(Status::invalid_argument( + WorkspaceSelection::AllWorkspaces(_) => Err(openshell_core::rpc_error::invalid_argument( + "workspace_scope", "all_workspaces is not supported by this request", )), } @@ -119,7 +120,12 @@ pub fn selected_workspace_name(selector: Option<&WorkspaceSelector>) -> Result<& fn selected_workspace(selector: Option<&WorkspaceSelector>) -> Result<&WorkspaceSelection, Status> { let selection = selector .and_then(|selector| selector.selection.as_ref()) - .ok_or_else(|| Status::invalid_argument("workspace_scope is required"))?; + .ok_or_else(|| { + openshell_core::rpc_error::invalid_argument( + "workspace_scope", + "workspace_scope is required", + ) + })?; if let WorkspaceSelection::Workspace(workspace) = selection { crate::grpc::workspace::validate_workspace_name(workspace)?; diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index 9b01b749a4..ca7396f2bc 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -162,6 +162,24 @@ struct RunArgs { #[arg(long, env = "OPENSHELL_OIDC_ISSUER")] oidc_issuer: Option, + /// Development only: permit OIDC metadata and JWKS over HTTP when the + /// endpoint uses a numeric loopback address. + #[arg( + long, + env = "OPENSHELL_OIDC_DANGEROUSLY_ALLOW_INSECURE_HTTP", + default_value_t = false, + action = ArgAction::Set + )] + oidc_dangerously_allow_insecure_http: bool, + + /// Additional HTTPS origins allowed to serve the issuer's JWKS. + #[arg( + long, + env = "OPENSHELL_OIDC_JWKS_ALLOWED_ORIGINS", + value_delimiter = ',' + )] + oidc_jwks_allowed_origins: Vec, + /// Enable mTLS client certificate authentication for local single-user gateways. /// /// When unset, this defaults on for drivers registered as local @@ -535,6 +553,8 @@ fn prepare_server_config_with_drivers( if let Some(issuer) = args.oidc_issuer.clone() { config = config.with_oidc(openshell_core::OidcConfig { issuer, + dangerously_allow_insecure_http: args.oidc_dangerously_allow_insecure_http, + jwks_allowed_origins: args.oidc_jwks_allowed_origins.clone(), audience: args.oidc_audience.clone(), jwks_ttl_secs: args.oidc_jwks_ttl, roles_claim: args.oidc_roles_claim.clone(), @@ -1096,6 +1116,15 @@ fn merge_file_into_args(args: &mut RunArgs, file: &GatewayFileSection, matches: if args.oidc_issuer.is_none() && arg_defaulted(matches, "oidc_issuer") { args.oidc_issuer = Some(oidc.issuer.clone()); } + if arg_defaulted(matches, "oidc_dangerously_allow_insecure_http") { + args.oidc_dangerously_allow_insecure_http = oidc.dangerously_allow_insecure_http; + } + if args.oidc_jwks_allowed_origins.is_empty() + && arg_defaulted(matches, "oidc_jwks_allowed_origins") + { + args.oidc_jwks_allowed_origins + .clone_from(&oidc.jwks_allowed_origins); + } if arg_defaulted(matches, "oidc_audience") { args.oidc_audience.clone_from(&oidc.audience); } @@ -1442,6 +1471,25 @@ mod tests { assert!(!cli.run.enable_loopback_service_http); } + #[test] + fn command_parses_oidc_insecure_http_acknowledgement_value() { + let _lock = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let _guard = EnvVarGuard::remove("OPENSHELL_OIDC_DANGEROUSLY_ALLOW_INSECURE_HTTP"); + + let cli = Cli::try_parse_from([ + "openshell-gateway", + "--db-url", + "sqlite::memory:", + "--oidc-dangerously-allow-insecure-http", + "true", + ]) + .expect("launcher-style boolean flag and value should parse"); + + assert!(cli.run.oidc_dangerously_allow_insecure_http); + } + #[test] fn command_reads_server_san_from_env() { let _lock = ENV_LOCK @@ -2827,6 +2875,8 @@ compute_driver = "podman" .unwrap_or_else(std::sync::PoisonError::into_inner); let _g1 = EnvVarGuard::remove("OPENSHELL_OIDC_ISSUER"); let _g2 = EnvVarGuard::remove("OPENSHELL_OIDC_AUDIENCE"); + let _g3 = EnvVarGuard::remove("OPENSHELL_OIDC_DANGEROUSLY_ALLOW_INSECURE_HTTP"); + let _g4 = EnvVarGuard::remove("OPENSHELL_OIDC_JWKS_ALLOWED_ORIGINS"); let (mut args, matches) = parse_with_args(&["openshell-gateway", "--db-url", "sqlite::memory:"]); @@ -2835,12 +2885,19 @@ compute_driver = "podman" [openshell.gateway.oidc] issuer = "https://idp.example.com" audience = "openshell-cli" +dangerously_allow_insecure_http = true +jwks_allowed_origins = ["https://keys.example.com"] "#, ); merge_file_into_args(&mut args, &file.openshell.gateway, &matches); assert_eq!(args.oidc_issuer.as_deref(), Some("https://idp.example.com")); assert_eq!(args.oidc_audience, "openshell-cli"); + assert!(args.oidc_dangerously_allow_insecure_http); + assert_eq!( + args.oidc_jwks_allowed_origins, + ["https://keys.example.com".to_string()] + ); } #[test] diff --git a/crates/openshell-server/src/config_file.rs b/crates/openshell-server/src/config_file.rs index 6601d3735b..a1441d53ec 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -745,6 +745,8 @@ client_ca_path = "/etc/openshell/certs/client-ca.pem" [openshell.gateway.oidc] issuer = "https://idp.example.com/realms/openshell" audience = "openshell-cli" +jwks_allowed_origins = ["https://keys.example.com"] +dangerously_allow_insecure_http = false [openshell.drivers.kubernetes] namespace = "agents" @@ -768,7 +770,12 @@ namespace = "agents" Some(openshell_core::PolicyValidationFailureMode::RetainLastValid) ); assert!(gw.tls.is_some()); - assert!(gw.oidc.is_some()); + let oidc = gw.oidc.as_ref().expect("OIDC config parses"); + assert!(!oidc.dangerously_allow_insecure_http); + assert_eq!( + oidc.jwks_allowed_origins, + ["https://keys.example.com".to_string()] + ); assert_eq!( gw.credential_drivers.as_deref(), Some(&["kubernetes-secrets".to_string()][..]) diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index d2665ee6b8..97f07164ba 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -82,11 +82,14 @@ pub fn persistence_error_to_status( match err { PersistenceError::Conflict { current_resource_version, - } => Status::aborted(format!( - "{} failed due to concurrent modification (current resource_version: {})", - operation, - current_resource_version.map_or_else(|| "unknown".to_string(), |v| v.to_string()) - )), + } => openshell_core::rpc_error::resource_version_conflict( + format!( + "{} failed due to concurrent modification (current resource_version: {})", + operation, + current_resource_version.map_or_else(|| "unknown".to_string(), |v| v.to_string()) + ), + current_resource_version, + ), other => Status::internal(format!("{operation} failed: {other}")), } } diff --git a/crates/openshell-server/src/grpc/validation.rs b/crates/openshell-server/src/grpc/validation.rs index dac34524c1..85bf1371a8 100644 --- a/crates/openshell-server/src/grpc/validation.rs +++ b/crates/openshell-server/src/grpc/validation.rs @@ -12,6 +12,7 @@ use openshell_core::proto::{ CredentialHandle, ExecSandboxRequest, Provider, SandboxPolicy as ProtoSandboxPolicy, SandboxSpec, SandboxTemplate, }; +use openshell_core::rpc_error::invalid_argument; use prost::Message; use tonic::Status; @@ -44,32 +45,36 @@ pub(super) const MAX_MAIN_PROCESS_ARGV_SIZE: usize = 256 * 1024; /// Environment values and workdir reject both NUL and newlines. pub(super) fn validate_exec_request_fields(req: &ExecSandboxRequest) -> Result<(), Status> { if req.command.len() > MAX_EXEC_COMMAND_ARGS { - return Err(Status::invalid_argument(format!( - "command array exceeds {MAX_EXEC_COMMAND_ARGS} argument limit" - ))); + return Err(invalid_argument( + "command", + format!("command array exceeds {MAX_EXEC_COMMAND_ARGS} argument limit"), + )); } for (i, arg) in req.command.iter().enumerate() { if arg.len() > MAX_EXEC_ARG_LEN { - return Err(Status::invalid_argument(format!( - "command argument {i} exceeds {MAX_EXEC_ARG_LEN} byte limit" - ))); + return Err(invalid_argument( + &format!("command[{i}]"), + format!("command argument {i} exceeds {MAX_EXEC_ARG_LEN} byte limit"), + )); } - reject_null_char(arg, &format!("command argument {i}"))?; + reject_null_char(arg, &format!("command[{i}]"))?; } for (key, value) in &req.environment { if value.len() > MAX_EXEC_ARG_LEN { - return Err(Status::invalid_argument(format!( - "environment value for '{key}' exceeds {MAX_EXEC_ARG_LEN} byte limit" - ))); + return Err(invalid_argument( + "environment", + format!("environment value for '{key}' exceeds {MAX_EXEC_ARG_LEN} byte limit"), + )); } - reject_control_chars(value, &format!("environment value for '{key}'"))?; + reject_control_chars(value, "environment")?; } validate_exec_env_entries(&req.environment, "environment")?; if !req.workdir.is_empty() { if req.workdir.len() > MAX_EXEC_WORKDIR_LEN { - return Err(Status::invalid_argument(format!( - "workdir exceeds {MAX_EXEC_WORKDIR_LEN} byte limit" - ))); + return Err(invalid_argument( + "workdir", + format!("workdir exceeds {MAX_EXEC_WORKDIR_LEN} byte limit"), + )); } reject_control_chars(&req.workdir, "workdir")?; } @@ -86,9 +91,10 @@ pub(super) fn reject_control_chars(value: &str, field_name: &str) -> Result<(), /// Reject null bytes in a user-supplied value. pub(super) fn reject_null_char(value: &str, field_name: &str) -> Result<(), Status> { if value.bytes().any(|b| b == 0) { - return Err(Status::invalid_argument(format!( - "{field_name} contains null bytes" - ))); + return Err(invalid_argument( + field_name, + format!("{field_name} contains null bytes"), + )); } Ok(()) } @@ -96,9 +102,10 @@ pub(super) fn reject_null_char(value: &str, field_name: &str) -> Result<(), Stat /// Reject newline and carriage return characters in a user-supplied value. pub(super) fn reject_newline_chars(value: &str, field_name: &str) -> Result<(), Status> { if value.bytes().any(|b| b == b'\n' || b == b'\r') { - return Err(Status::invalid_argument(format!( - "{field_name} contains newline or carriage return characters" - ))); + return Err(invalid_argument( + field_name, + format!("{field_name} contains newline or carriage return characters"), + )); } Ok(()) } @@ -117,28 +124,34 @@ pub(super) fn validate_dns1123_label(name: &str, field: &str) -> Result<(), Stat return Ok(()); } if name.len() > MAX_NAME_LEN { - return Err(Status::invalid_argument(format!( - "{field} exceeds maximum length ({} > {MAX_NAME_LEN})", - name.len() - ))); + return Err(invalid_argument( + field, + format!( + "{field} exceeds maximum length ({} > {MAX_NAME_LEN})", + name.len() + ), + )); } if !name .chars() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') { - return Err(Status::invalid_argument(format!( - "{field} must contain only lowercase alphanumeric characters or hyphens", - ))); + return Err(invalid_argument( + field, + format!("{field} must contain only lowercase alphanumeric characters or hyphens"), + )); } if name.starts_with('-') || name.ends_with('-') { - return Err(Status::invalid_argument(format!( - "{field} must not start or end with a hyphen", - ))); + return Err(invalid_argument( + field, + format!("{field} must not start or end with a hyphen"), + )); } if name.contains("--") { - return Err(Status::invalid_argument(format!( - "{field} must not contain consecutive hyphens", - ))); + return Err(invalid_argument( + field, + format!("{field} must not contain consecutive hyphens"), + )); } Ok(()) } @@ -159,10 +172,13 @@ pub(super) fn validate_sandbox_spec(name: &str, spec: &SandboxSpec) -> Result<() // --- spec.log_level --- if spec.log_level.len() > MAX_LOG_LEVEL_LEN { - return Err(Status::invalid_argument(format!( - "log_level exceeds maximum length ({} > {MAX_LOG_LEVEL_LEN})", - spec.log_level.len() - ))); + return Err(invalid_argument( + "spec.log_level", + format!( + "log_level exceeds maximum length ({} > {MAX_LOG_LEVEL_LEN})", + spec.log_level.len() + ), + )); } // --- spec.environment --- @@ -209,20 +225,26 @@ pub(super) fn validate_sandbox_governance_spec( fn validate_sandbox_name(name: &str) -> Result<(), Status> { if !name.is_empty() && name.len() > MAX_ROUTABLE_NAME_LEN { - return Err(Status::invalid_argument(format!( - "name exceeds maximum length ({} > {MAX_ROUTABLE_NAME_LEN})", - name.len() - ))); + return Err(invalid_argument( + "name", + format!( + "name exceeds maximum length ({} > {MAX_ROUTABLE_NAME_LEN})", + name.len() + ), + )); } validate_dns1123_label(name, "name") } fn validate_sandbox_provider_count(spec: &SandboxSpec) -> Result<(), Status> { if spec.providers.len() > MAX_PROVIDERS { - return Err(Status::invalid_argument(format!( - "providers list exceeds maximum ({} > {MAX_PROVIDERS})", - spec.providers.len() - ))); + return Err(invalid_argument( + "spec.providers", + format!( + "providers list exceeds maximum ({} > {MAX_PROVIDERS})", + spec.providers.len() + ), + )); } Ok(()) } @@ -231,9 +253,10 @@ fn validate_sandbox_policy_size(spec: &SandboxSpec) -> Result<(), Status> { if let Some(ref policy) = spec.policy { let size = policy.encoded_len(); if size > MAX_POLICY_SIZE { - return Err(Status::invalid_argument(format!( - "policy serialized size exceeds maximum ({size} > {MAX_POLICY_SIZE})" - ))); + return Err(invalid_argument( + "spec.policy", + format!("policy serialized size exceeds maximum ({size} > {MAX_POLICY_SIZE})"), + )); } } @@ -242,26 +265,30 @@ fn validate_sandbox_policy_size(spec: &SandboxSpec) -> Result<(), Status> { fn validate_main_process_command(command: &[String]) -> Result<(), Status> { if command.len() > MAX_MAIN_PROCESS_ARGS { - return Err(Status::invalid_argument(format!( - "spec.command exceeds {MAX_MAIN_PROCESS_ARGS} argument limit" - ))); + return Err(invalid_argument( + "spec.command", + format!("spec.command exceeds {MAX_MAIN_PROCESS_ARGS} argument limit"), + )); } if command[0].is_empty() { - return Err(Status::invalid_argument( + return Err(invalid_argument( + "spec.command[0]", "spec.command[0] must not be empty", )); } let argv_size: usize = command.iter().map(String::len).sum(); if argv_size > MAX_MAIN_PROCESS_ARGV_SIZE { - return Err(Status::invalid_argument(format!( - "spec.command total size exceeds {MAX_MAIN_PROCESS_ARGV_SIZE} byte limit" - ))); + return Err(invalid_argument( + "spec.command", + format!("spec.command total size exceeds {MAX_MAIN_PROCESS_ARGV_SIZE} byte limit"), + )); } for (index, argument) in command.iter().enumerate() { if argument.len() > MAX_EXEC_ARG_LEN { - return Err(Status::invalid_argument(format!( - "spec.command[{index}] exceeds {MAX_EXEC_ARG_LEN} byte limit" - ))); + return Err(invalid_argument( + &format!("spec.command[{index}]"), + format!("spec.command[{index}] exceeds {MAX_EXEC_ARG_LEN} byte limit"), + )); } reject_null_char(argument, &format!("spec.command[{index}]"))?; } @@ -271,7 +298,10 @@ fn validate_main_process_command(command: &[String]) -> Result<(), Status> { fn validate_gpu_request_fields(spec: &SandboxSpec) -> Result<(), Status> { if openshell_core::gpu::sandbox_gpu_count(spec.resource_requirements.as_ref()) == Some(0) { - return Err(Status::invalid_argument("gpu count must be greater than 0")); + return Err(invalid_argument( + "spec.resource_requirements.gpu.count", + "gpu count must be greater than 0", + )); } Ok(()) @@ -281,15 +311,18 @@ fn validate_gpu_request_fields(spec: &SandboxSpec) -> Result<(), Status> { fn validate_sandbox_template(tmpl: &SandboxTemplate) -> Result<(), Status> { // String fields. for (field, value) in [ - ("template.image", &tmpl.image), - ("template.runtime_class_name", &tmpl.runtime_class_name), - ("template.agent_socket", &tmpl.agent_socket), + ("spec.template.image", &tmpl.image), + ("spec.template.runtime_class_name", &tmpl.runtime_class_name), + ("spec.template.agent_socket", &tmpl.agent_socket), ] { if value.len() > MAX_TEMPLATE_STRING_LEN { - return Err(Status::invalid_argument(format!( - "{field} exceeds maximum length ({} > {MAX_TEMPLATE_STRING_LEN})", - value.len() - ))); + return Err(invalid_argument( + field, + format!( + "{field} exceeds maximum length ({} > {MAX_TEMPLATE_STRING_LEN})", + value.len() + ), + )); } } @@ -299,38 +332,44 @@ fn validate_sandbox_template(tmpl: &SandboxTemplate) -> Result<(), Status> { MAX_TEMPLATE_MAP_ENTRIES, MAX_MAP_KEY_LEN, MAX_MAP_VALUE_LEN, - "template.labels", + "spec.template.labels", )?; validate_string_map( &tmpl.annotations, MAX_TEMPLATE_MAP_ENTRIES, MAX_MAP_KEY_LEN, MAX_MAP_VALUE_LEN, - "template.annotations", + "spec.template.annotations", )?; validate_string_map( &tmpl.environment, MAX_TEMPLATE_MAP_ENTRIES, MAX_MAP_KEY_LEN, MAX_MAP_VALUE_LEN, - "template.environment", + "spec.template.environment", )?; // Struct fields (serialized size). if let Some(ref s) = tmpl.resources { let size = s.encoded_len(); if size > MAX_TEMPLATE_STRUCT_SIZE { - return Err(Status::invalid_argument(format!( - "template.resources serialized size exceeds maximum ({size} > {MAX_TEMPLATE_STRUCT_SIZE})" - ))); + return Err(invalid_argument( + "spec.template.resources", + format!( + "template.resources serialized size exceeds maximum ({size} > {MAX_TEMPLATE_STRUCT_SIZE})" + ), + )); } } if let Some(ref s) = tmpl.driver_config { let size = s.encoded_len(); if size > MAX_TEMPLATE_STRUCT_SIZE { - return Err(Status::invalid_argument(format!( - "template.driver_config serialized size exceeds maximum ({size} > {MAX_TEMPLATE_STRUCT_SIZE})" - ))); + return Err(invalid_argument( + "spec.template.driver_config", + format!( + "template.driver_config serialized size exceeds maximum ({size} > {MAX_TEMPLATE_STRUCT_SIZE})" + ), + )); } reject_gateway_owned_driver_config_keys(s)?; } @@ -352,10 +391,13 @@ fn reject_gateway_owned_driver_config_keys(config: &prost_types::Struct) -> Resu }; for key in GATEWAY_OWNED_DRIVER_CONFIG_KEYS { if driver_config.fields.contains_key(*key) { - return Err(Status::invalid_argument(format!( - "template.driver_config.{driver_name}.{key} is set by the gateway \ + return Err(invalid_argument( + "spec.template.driver_config", + format!( + "template.driver_config.{driver_name}.{key} is set by the gateway \ and cannot be supplied by the caller" - ))); + ), + )); } } } @@ -371,23 +413,32 @@ pub(super) fn validate_string_map( field_name: &str, ) -> Result<(), Status> { if map.len() > max_entries { - return Err(Status::invalid_argument(format!( - "{field_name} exceeds maximum entries ({} > {max_entries})", - map.len() - ))); + return Err(invalid_argument( + field_name, + format!( + "{field_name} exceeds maximum entries ({} > {max_entries})", + map.len() + ), + )); } for (key, value) in map { if key.len() > max_key_len { - return Err(Status::invalid_argument(format!( - "{field_name} key exceeds maximum length ({} > {max_key_len})", - key.len() - ))); + return Err(invalid_argument( + field_name, + format!( + "{field_name} key exceeds maximum length ({} > {max_key_len})", + key.len() + ), + )); } if value.len() > max_value_len { - return Err(Status::invalid_argument(format!( - "{field_name} value exceeds maximum length ({} > {max_value_len})", - value.len() - ))); + return Err(invalid_argument( + field_name, + format!( + "{field_name} value exceeds maximum length ({} > {max_value_len})", + value.len() + ), + )); } } Ok(()) @@ -431,9 +482,12 @@ fn validate_env_entries( ) -> Result<(), Status> { let total_size: usize = map.iter().map(|(k, v)| k.len() + v.len()).sum(); if total_size > MAX_ENV_SERIALIZED_SIZE { - return Err(Status::invalid_argument(format!( - "{field_name} total size exceeds {MAX_ENV_SERIALIZED_SIZE} byte limit ({total_size} bytes)" - ))); + return Err(invalid_argument( + field_name, + format!( + "{field_name} total size exceeds {MAX_ENV_SERIALIZED_SIZE} byte limit ({total_size} bytes)" + ), + )); } validate_env_entries_inner(map, field_name, &[]) } @@ -452,16 +506,18 @@ fn validate_env_entries_inner( ) -> Result<(), Status> { for (key, value) in map { if !super::provider::is_valid_env_key(key) { - return Err(Status::invalid_argument(format!( - "{field_name} keys must match ^[A-Za-z_][A-Za-z0-9_]*$; got '{key}'" - ))); + return Err(invalid_argument( + field_name, + format!("{field_name} keys must match ^[A-Za-z_][A-Za-z0-9_]*$; got '{key}'"), + )); } if key.starts_with("OPENSHELL_") && !allowed_openshell_keys.contains(&key.as_str()) { - return Err(Status::invalid_argument(format!( - "{field_name} keys starting with OPENSHELL_ are reserved; got '{key}'" - ))); + return Err(invalid_argument( + field_name, + format!("{field_name} keys starting with OPENSHELL_ are reserved; got '{key}'"), + )); } - reject_control_chars(value, &format!("{field_name} value for '{key}'"))?; + reject_control_chars(value, field_name)?; } Ok(()) } @@ -474,15 +530,19 @@ fn validate_env_entries_inner( pub(super) fn validate_provider_fields(provider: &Provider) -> Result<(), Status> { let name_len = provider.metadata.as_ref().map_or(0, |m| m.name.len()); if name_len > MAX_NAME_LEN { - return Err(Status::invalid_argument(format!( - "provider.name exceeds maximum length ({name_len} > {MAX_NAME_LEN})" - ))); + return Err(invalid_argument( + "provider.metadata.name", + format!("provider.name exceeds maximum length ({name_len} > {MAX_NAME_LEN})"), + )); } if provider.r#type.len() > MAX_PROVIDER_TYPE_LEN { - return Err(Status::invalid_argument(format!( - "provider.type exceeds maximum length ({} > {MAX_PROVIDER_TYPE_LEN})", - provider.r#type.len() - ))); + return Err(invalid_argument( + "provider.type", + format!( + "provider.type exceeds maximum length ({} > {MAX_PROVIDER_TYPE_LEN})", + provider.r#type.len() + ), + )); } validate_provider_mutable_fields(provider) } @@ -512,20 +572,27 @@ pub(super) fn validate_provider_mutable_fields(provider: &Provider) -> Result<() "provider.config", )?; if provider.credential_expires_at_ms.len() > MAX_PROVIDER_CREDENTIALS_ENTRIES { - return Err(Status::invalid_argument(format!( - "provider.credential_expires_at_ms exceeds maximum entries ({} > {MAX_PROVIDER_CREDENTIALS_ENTRIES})", - provider.credential_expires_at_ms.len() - ))); + return Err(invalid_argument( + "provider.credential_expires_at_ms", + format!( + "provider.credential_expires_at_ms exceeds maximum entries ({} > {MAX_PROVIDER_CREDENTIALS_ENTRIES})", + provider.credential_expires_at_ms.len() + ), + )); } for (key, value) in &provider.credential_expires_at_ms { if key.len() > MAX_MAP_KEY_LEN { - return Err(Status::invalid_argument(format!( - "provider.credential_expires_at_ms key exceeds maximum length ({} > {MAX_MAP_KEY_LEN})", - key.len() - ))); + return Err(invalid_argument( + "provider.credential_expires_at_ms", + format!( + "provider.credential_expires_at_ms key exceeds maximum length ({} > {MAX_MAP_KEY_LEN})", + key.len() + ), + )); } if *value < 0 { - return Err(Status::invalid_argument( + return Err(invalid_argument( + "provider.credential_expires_at_ms", "provider.credential_expires_at_ms value must be greater than or equal to 0", )); } @@ -536,16 +603,22 @@ pub(super) fn validate_provider_mutable_fields(provider: &Provider) -> Result<() fn validate_provider_credential_sources(provider: &Provider) -> Result<(), Status> { let total_credentials = provider.credentials.len() + provider.credential_handles.len(); if total_credentials > MAX_PROVIDER_CREDENTIALS_ENTRIES { - return Err(Status::invalid_argument(format!( - "provider credential sources exceed maximum entries ({total_credentials} > {MAX_PROVIDER_CREDENTIALS_ENTRIES})" - ))); + return Err(invalid_argument( + "provider.credentials", + format!( + "provider credential sources exceed maximum entries ({total_credentials} > {MAX_PROVIDER_CREDENTIALS_ENTRIES})" + ), + )); } for key in provider.credential_handles.keys() { if provider.credentials.contains_key(key) { - return Err(Status::invalid_argument(format!( - "provider credential key '{key}' cannot be present in both provider.credentials and provider.credential_handles" - ))); + return Err(invalid_argument( + "provider.credential_handles", + format!( + "provider credential key '{key}' cannot be present in both provider.credentials and provider.credential_handles" + ), + )); } } Ok(()) @@ -555,23 +628,32 @@ fn validate_provider_credential_handles( credential_handles: &std::collections::HashMap, ) -> Result<(), Status> { if credential_handles.len() > MAX_PROVIDER_CREDENTIALS_ENTRIES { - return Err(Status::invalid_argument(format!( - "provider.credential_handles exceeds maximum entries ({} > {MAX_PROVIDER_CREDENTIALS_ENTRIES})", - credential_handles.len() - ))); + return Err(invalid_argument( + "provider.credential_handles", + format!( + "provider.credential_handles exceeds maximum entries ({} > {MAX_PROVIDER_CREDENTIALS_ENTRIES})", + credential_handles.len() + ), + )); } for (credential_key, handle) in credential_handles { if credential_key.len() > MAX_MAP_KEY_LEN { - return Err(Status::invalid_argument(format!( - "provider.credential_handles key exceeds maximum length ({} > {MAX_MAP_KEY_LEN})", - credential_key.len() - ))); + return Err(invalid_argument( + "provider.credential_handles", + format!( + "provider.credential_handles key exceeds maximum length ({} > {MAX_MAP_KEY_LEN})", + credential_key.len() + ), + )); } if !super::provider::is_valid_env_key(credential_key) { - return Err(Status::invalid_argument(format!( - "provider.credential_handles keys must match ^[A-Za-z_][A-Za-z0-9_]*$; got '{credential_key}'" - ))); + return Err(invalid_argument( + "provider.credential_handles", + format!( + "provider.credential_handles keys must match ^[A-Za-z_][A-Za-z0-9_]*$; got '{credential_key}'" + ), + )); } validate_credential_handle( handle, @@ -593,8 +675,8 @@ fn validate_credential_handle(handle: &CredentialHandle, field_name: &str) -> Re &format!("{field_name}.metadata"), )?; for (key, value) in &handle.metadata { - reject_control_chars(key, &format!("{field_name}.metadata key"))?; - reject_control_chars(value, &format!("{field_name}.metadata value for '{key}'"))?; + reject_control_chars(key, &format!("{field_name}.metadata"))?; + reject_control_chars(value, &format!("{field_name}.metadata"))?; } Ok(()) } @@ -605,9 +687,10 @@ fn validate_required_credential_handle_string( component: &str, ) -> Result<(), Status> { if value.trim().is_empty() { - return Err(Status::invalid_argument(format!( - "{field_name}.{component} is required" - ))); + return Err(invalid_argument( + &format!("{field_name}.{component}"), + format!("{field_name}.{component} is required"), + )); } validate_optional_credential_handle_string(value, field_name, component) } @@ -618,10 +701,13 @@ fn validate_optional_credential_handle_string( component: &str, ) -> Result<(), Status> { if value.len() > MAX_MAP_VALUE_LEN { - return Err(Status::invalid_argument(format!( - "{field_name}.{component} exceeds maximum length ({} > {MAX_MAP_VALUE_LEN})", - value.len() - ))); + return Err(invalid_argument( + &format!("{field_name}.{component}"), + format!( + "{field_name}.{component} exceeds maximum length ({} > {MAX_MAP_VALUE_LEN})", + value.len() + ), + )); } reject_control_chars(value, &format!("{field_name}.{component}")) } @@ -1040,9 +1126,47 @@ pub(super) fn level_matches(log_level: &str, min_level: &str) -> bool { mod tests { use super::*; use openshell_core::proto::SandboxSpec; + use openshell_core::rpc_error::StatusExt; use std::collections::HashMap; use tonic::Code; + #[test] + fn sandbox_and_exec_validation_return_wire_field_paths() { + let cases = [ + ( + validate_sandbox_spec("UPPER", &SandboxSpec::default()).unwrap_err(), + "name", + ), + ( + validate_sandbox_spec( + "", + &SandboxSpec { + command: vec![String::new()], + ..Default::default() + }, + ) + .unwrap_err(), + "spec.command[0]", + ), + ( + validate_exec_request_fields(&ExecSandboxRequest { + command: vec!["a\0b".into()], + ..Default::default() + }) + .unwrap_err(), + "command[0]", + ), + ]; + for (status, field) in cases { + assert_eq!(status.code(), Code::InvalidArgument); + let details = status.get_error_details(); + assert_eq!( + details.bad_request().unwrap().field_violations[0].field, + field + ); + } + } + use crate::grpc::{ MAX_ENVIRONMENT_ENTRIES, MAX_LOG_LEVEL_LEN, MAX_MAP_KEY_LEN, MAX_MAP_VALUE_LEN, MAX_NAME_LEN, MAX_POLICY_SIZE, MAX_PROVIDER_CONFIG_ENTRIES, diff --git a/crates/openshell-server/src/provider_profile_sources.rs b/crates/openshell-server/src/provider_profile_sources.rs index a62d9dc201..83081c5d5e 100644 --- a/crates/openshell-server/src/provider_profile_sources.rs +++ b/crates/openshell-server/src/provider_profile_sources.rs @@ -200,10 +200,14 @@ impl ProviderProfileSource for GatewayInterceptorProfileSource { ) -> Result { let InterceptorProfileSnapshot { revision, profiles } = Self::snapshot(self).await.map_err(|err| { - Status::unavailable(format!( - "provider profile source '{}' snapshot failed: {err}", - self.source_id() - )) + openshell_core::rpc_error::unavailable( + "PROFILE_SOURCE_UNAVAILABLE", + format!( + "provider profile source '{}' snapshot failed: {err}", + self.source_id() + ), + std::time::Duration::from_secs(1), + ) })?; let profiles = profiles .into_iter() diff --git a/crates/openshell-supervisor-network/Cargo.toml b/crates/openshell-supervisor-network/Cargo.toml index 9961f4b31e..e4a2f12917 100644 --- a/crates/openshell-supervisor-network/Cargo.toml +++ b/crates/openshell-supervisor-network/Cargo.toml @@ -56,6 +56,7 @@ default = ["bundled-ca-roots"] bundled-ca-roots = ["dep:webpki-roots"] [dev-dependencies] +openshell-ocsf = { path = "../openshell-ocsf", features = ["test-support"] } openshell-supervisor-middleware-builtins = { path = "../openshell-supervisor-middleware-builtins" } tonic = { workspace = true } temp-env = "0.3" diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 32de13f67d..31acd3a7fd 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -150,7 +150,18 @@ fn normalized_endpoint_host(host: &str) -> &str { .trim_end_matches('.') } -async fn reject_request_authority_mismatch(client: &mut W, ctx: &L7EvalContext) -> Result<()> +fn method_only_request(method: &str) -> HttpRequest { + HttpRequest { + http_method: method.parse().expect("HTTP method parsing is infallible"), + url: None, + } +} + +async fn reject_request_authority_mismatch( + client: &mut W, + ctx: &L7EvalContext, + method: &str, +) -> Result<()> where W: AsyncWrite + Unpin, { @@ -165,7 +176,7 @@ where .into_diagnostic()?; client.flush().await.into_diagnostic()?; - ocsf_emit!(build_request_authority_mismatch_event(ctx)); + ocsf_emit!(build_request_authority_mismatch_event(ctx, method)); ocsf_emit!(build_request_authority_mismatch_finding(ctx)); Ok(()) } @@ -275,9 +286,14 @@ where .await } -fn build_request_authority_mismatch_event(ctx: &L7EvalContext) -> openshell_ocsf::OcsfEvent { +fn build_request_authority_mismatch_event( + ctx: &L7EvalContext, + method: &str, +) -> openshell_ocsf::OcsfEvent { HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(ActivityId::Fail) + .activity(ActivityId::for_http_method(method)) + .http_request(method_only_request(method)) + .http_response(openshell_ocsf::HttpResponse { code: 403 }) .action(ActionId::Denied) .disposition(DispositionId::Blocked) .severity(SeverityId::High) @@ -314,10 +330,16 @@ fn build_request_authority_mismatch_finding(ctx: &L7EvalContext) -> openshell_oc fn build_credential_resolution_event( ctx: &L7EvalContext, + method: &str, endpoint_mismatch: bool, ) -> openshell_ocsf::OcsfEvent { + let response_code = if endpoint_mismatch { 403 } else { 500 }; HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(ActivityId::Fail) + .activity(ActivityId::for_http_method(method)) + .http_request(method_only_request(method)) + .http_response(openshell_ocsf::HttpResponse { + code: response_code, + }) .action(ActionId::Denied) .disposition(DispositionId::Blocked) .severity(if endpoint_mismatch { @@ -359,6 +381,7 @@ fn build_credential_endpoint_mismatch_finding(ctx: &L7EvalContext) -> openshell_ pub(crate) async fn reject_credential_resolution( client: &mut W, ctx: &L7EvalContext, + method: &str, error: &secrets::UnresolvedPlaceholderError, ) -> Result<()> where @@ -385,7 +408,11 @@ where .into_diagnostic()?; client.flush().await.into_diagnostic()?; - ocsf_emit!(build_credential_resolution_event(ctx, endpoint_mismatch)); + ocsf_emit!(build_credential_resolution_event( + ctx, + method, + endpoint_mismatch + )); if endpoint_mismatch { ocsf_emit!(build_credential_endpoint_mismatch_finding(ctx)); @@ -464,7 +491,7 @@ where if let Some(observer) = observer { observer.observe_credential_failure(error.is_endpoint_mismatch()); } - reject_credential_resolution(client, ctx, error).await?; + reject_credential_resolution(client, ctx, &request.action, error).await?; Ok(None) } else if report .downcast_ref::() @@ -724,14 +751,14 @@ where } }; if !request_authority_matches_endpoint(&req, ctx) { - reject_request_authority_mismatch(client, ctx).await?; + reject_request_authority_mismatch(client, ctx, &req.action).await?; return Ok(()); } let route_target = match secrets::redact_target_for_policy(&req.target) { Ok(target) => target, Err(error) => { - reject_credential_resolution(client, ctx, &error).await?; + reject_credential_resolution(client, ctx, &req.action, &error).await?; return Ok(()); } }; @@ -866,7 +893,7 @@ where if let Some(observer) = observer.as_ref() { observer.observe_credential_failure(error.is_endpoint_mismatch()); } - reject_credential_resolution(client, ctx, &error).await?; + reject_credential_resolution(client, ctx, &req.action, &error).await?; return Ok(()); } }; @@ -1588,7 +1615,7 @@ where } }; if !request_authority_matches_endpoint(&req, ctx) { - reject_request_authority_mismatch(client, ctx).await?; + reject_request_authority_mismatch(client, ctx, &req.action).await?; return Ok(()); } if deny_h2c_upgrade_if_requested(&req, config, ctx, client).await? { @@ -1604,7 +1631,7 @@ where let redacted_target = match secrets::redact_target_for_policy(&req.target) { Ok(target) => target, Err(error) => { - reject_credential_resolution(client, ctx, &error).await?; + reject_credential_resolution(client, ctx, &req.action, &error).await?; return Ok(()); } }; @@ -2043,7 +2070,7 @@ where if let Some(observer) = observer.as_ref() { observer.observe(EndpointResult::PolicyDenied); } - reject_request_authority_mismatch(client, ctx).await?; + reject_request_authority_mismatch(client, ctx, &req.action).await?; return Ok(()); } if close_if_stale(engine.generation_guard(), ctx) { @@ -2056,7 +2083,7 @@ where if let Some(observer) = observer.as_ref() { observer.observe_credential_failure(error.is_endpoint_mismatch()); } - reject_credential_resolution(client, ctx, &error).await?; + reject_credential_resolution(client, ctx, &req.action, &error).await?; return Ok(()); } }; @@ -2323,7 +2350,7 @@ where let req = parsed.request; let graphql_info = parsed.info; if !request_authority_matches_endpoint(&req, ctx) { - reject_request_authority_mismatch(client, ctx).await?; + reject_request_authority_mismatch(client, ctx, &req.action).await?; return Ok(()); } if deny_h2c_upgrade_if_requested(&req, config, ctx, client).await? { @@ -2337,7 +2364,7 @@ where let redacted_target = match secrets::redact_target_for_policy(&req.target) { Ok(target) => target, Err(error) => { - reject_credential_resolution(client, ctx, &error).await?; + reject_credential_resolution(client, ctx, &req.action, &error).await?; return Ok(()); } }; @@ -2988,7 +3015,7 @@ where } }; if !request_authority_matches_endpoint(&req, ctx) { - reject_request_authority_mismatch(client, ctx).await?; + reject_request_authority_mismatch(client, ctx, &req.action).await?; return Ok(()); } if close_if_stale(generation_guard, ctx) { @@ -3001,7 +3028,7 @@ where let redacted_target = match secrets::redact_target_for_policy(&req.target) { Ok(target) => target, Err(error) => { - reject_credential_resolution(client, ctx, &error).await?; + reject_credential_resolution(client, ctx, &req.action, &error).await?; return Ok(()); } }; @@ -3378,6 +3405,46 @@ mod tests { (state, resolver) } + #[test] + fn early_http_rejections_include_method_and_response() { + use openshell_ocsf::validation::{ + load_class_schema, validate_enum_value, validate_required_fields, + }; + let ctx = L7EvalContext { + host: "example.com".into(), + port: 443, + ..Default::default() + }; + let schema = load_class_schema("http_activity"); + for (event, method, response_code) in [ + ( + build_request_authority_mismatch_event(&ctx, "GET"), + "GET", + 403, + ), + ( + build_credential_resolution_event(&ctx, "POST", true), + "POST", + 403, + ), + ( + build_credential_resolution_event(&ctx, "HEAD", false), + "HEAD", + 500, + ), + ] { + let json = event.to_json().unwrap(); + assert_eq!(json["class_uid"], 4002); + assert_eq!(json["dst_endpoint"]["domain"], "example.com"); + assert_eq!(json["action_id"], 2); + assert_eq!(json["http_request"]["http_method"], method); + assert!(json["http_request"].get("url").is_none()); + assert_eq!(json["http_response"]["code"], response_code); + validate_required_fields(&json, &schema); + validate_enum_value(&json, "activity_id", &schema); + } + } + #[test] fn websocket_preflight_input_carries_real_sandbox_name() { let sandbox = openshell_ocsf::EventContext { @@ -3555,7 +3622,7 @@ mod tests { "credential mismatch must not write upstream" ); - let activity = build_credential_resolution_event(ctx, true) + let activity = build_credential_resolution_event(ctx, "GET", true) .to_json() .expect("serialize credential mismatch activity"); assert_eq!(activity["status_detail"], "credential_endpoint_mismatch"); @@ -3616,7 +3683,7 @@ mod tests { "credential mismatch must not write upstream" ); - let activity = build_credential_resolution_event(&ctx, true) + let activity = build_credential_resolution_event(&ctx, "GET", true) .to_json() .unwrap(); assert_eq!(activity["status_detail"], "credential_endpoint_mismatch"); @@ -5208,7 +5275,7 @@ network_policies: forwarded.is_empty(), "mismatched request authority must not write upstream" ); - let activity = build_request_authority_mismatch_event(&event_ctx) + let activity = build_request_authority_mismatch_event(&event_ctx, "GET") .to_json() .expect("serialize authority mismatch activity"); assert_eq!(activity["status_detail"], "request_authority_mismatch"); diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index ddd977583d..f57e9f3202 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -16,6 +16,7 @@ use crate::opa::{NetworkAction, OpaEngine, PolicyGenerationGuard}; use crate::policy_dns::{MappingLookupError, PolicyEndpointId, ResolvedEndpointStore}; use crate::policy_local::{POLICY_LOCAL_HOST, PolicyLocalContext}; use crate::upstream_proxy::{self, UpstreamProxyConfig}; +use http::StatusCode; use miette::{IntoDiagnostic, Result}; use openshell_core::activity::{ActivitySender, try_record_activity}; use openshell_core::denial::DenialEvent; @@ -30,7 +31,7 @@ use openshell_core::policy::ProxyPolicy; use openshell_core::provider_credentials::{ProviderCredentialSnapshot, ProviderCredentialState}; use openshell_core::secrets::{self, SecretResolver, rewrite_header_line_checked}; use openshell_ocsf::{ - ActionId, ActivityId, DispositionId, Endpoint, HttpActivityBuilder, HttpRequest, + ActionId, ActivityId, DispositionId, Endpoint, HttpActivityBuilder, HttpRequest, HttpResponse, NetworkActivityBuilder, Process, SeverityId, StatusId, Url as OcsfUrl, ocsf_emit, }; #[cfg(target_os = "linux")] @@ -72,9 +73,19 @@ const FORWARD_ENCODED_SLASH_REJECTION_DETAIL: &str = #[cfg(target_os = "linux")] const SIDECAR_SUPERVISOR_TOPOLOGY: &str = "sidecar"; -fn emit_credential_endpoint_mismatch(host: &str, port: u16, policy_name: &str) { - let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(ActivityId::Fail) +fn build_credential_endpoint_mismatch_event( + method: &str, + host: &str, + port: u16, + policy_name: &str, +) -> openshell_ocsf::OcsfEvent { + HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::for_http_method(method)) + .http_request(HttpRequest { + http_method: method.parse().expect("HTTP method parsing is infallible"), + url: None, + }) + .http_response(HttpResponse { code: 403 }) .action(ActionId::Denied) .disposition(DispositionId::Blocked) .severity(SeverityId::High) @@ -85,7 +96,11 @@ fn emit_credential_endpoint_mismatch(host: &str, port: u16, policy_name: &str) { "Credential use denied: credential is not authorized for {host}:{port}" )) .status_detail("credential_endpoint_mismatch") - .build(); + .build() +} + +fn emit_credential_endpoint_mismatch(method: &str, host: &str, port: u16, policy_name: &str) { + let event = build_credential_endpoint_mismatch_event(method, host, port, policy_name); ocsf_emit!(event); let finding = crate::l7::build_credential_endpoint_mismatch_finding( policy_name, @@ -1368,7 +1383,7 @@ fn build_forward_allow_ocsf_event( policy: &str, ) -> openshell_ocsf::OcsfEvent { HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(ActivityId::Other) + .activity(ActivityId::for_http_method(method)) .action(ActionId::Allowed) .disposition(DispositionId::Allowed) .severity(SeverityId::Informational) @@ -1387,13 +1402,46 @@ fn build_forward_allow_ocsf_event( fn build_forward_parse_error_ocsf_event(path: &str) -> openshell_ocsf::OcsfEvent { HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(ActivityId::Fail) + .activity(ActivityId::Other) + .http_response(HttpResponse { + code: StatusCode::BAD_REQUEST.as_u16(), + }) .severity(SeverityId::Low) .status(StatusId::Failure) .message(format!("FORWARD parse error for {path}")) .build() } +/// Build the rejection event for an absolute-form request whose scheme is not +/// supported by the forward proxy. The request URL is omitted because paths may +/// contain credentials; the method and generated response provide the HTTP +/// context required by OCSF 1.8. +fn build_forward_unsupported_scheme_ocsf_event( + method: &str, + scheme: &str, + host: &str, + port: u16, +) -> openshell_ocsf::OcsfEvent { + HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::for_http_method(method)) + .http_request(HttpRequest { + http_method: method.parse().expect("HTTP method parsing is infallible"), + url: None, + }) + .http_response(HttpResponse { + code: StatusCode::BAD_REQUEST.as_u16(), + }) + .action(ActionId::Denied) + .disposition(DispositionId::Rejected) + .severity(SeverityId::Informational) + .status(StatusId::Failure) + .dst_endpoint(Endpoint::from_domain(host, port)) + .message(format!( + "FORWARD rejected: unsupported scheme {scheme} for {host}:{port}" + )) + .build() +} + #[allow(clippy::too_many_arguments)] fn build_forward_l7_parse_rejection_ocsf_event( peer_addr: SocketAddr, @@ -1409,7 +1457,7 @@ fn build_forward_l7_parse_rejection_ocsf_event( detail: &str, ) -> openshell_ocsf::OcsfEvent { HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(ActivityId::Other) + .activity(ActivityId::for_http_method(method)) .action(ActionId::Denied) .disposition(DispositionId::Blocked) .severity(SeverityId::Medium) @@ -1535,7 +1583,7 @@ fn build_forward_destination_deny_ocsf_event( }; HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(ActivityId::Other) + .activity(ActivityId::for_http_method(method)) .action(ActionId::Denied) .disposition(DispositionId::Blocked) .severity(SeverityId::Medium) @@ -4420,17 +4468,7 @@ async fn handle_forward_proxy( } if scheme != "http" { - let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(ActivityId::Refuse) - .action(ActionId::Denied) - .disposition(DispositionId::Rejected) - .severity(SeverityId::Informational) - .status(StatusId::Failure) - .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .message(format!( - "FORWARD rejected: unsupported scheme {scheme} for {host_lc}:{port}" - )) - .build(); + let event = build_forward_unsupported_scheme_ocsf_event(method, &scheme, &host_lc, port); ocsf_emit!(event); if scheme == "https" { respond( @@ -5484,7 +5522,7 @@ async fn handle_forward_proxy( if let Some(observer) = endpoint_observer.as_ref() { observer.observe_credential_failure(true); } - emit_credential_endpoint_mismatch(&host_lc, port, policy_str); + emit_credential_endpoint_mismatch(method, &host_lc, port, policy_str); respond( client, &build_json_error_response( @@ -5718,7 +5756,8 @@ async fn handle_forward_proxy( .end(openshell_core::proto::MiddlewareSessionEndReason::Cancellation) .await; } - crate::l7::relay::reject_credential_resolution(client, &l7_ctx, error).await?; + crate::l7::relay::reject_credential_resolution(client, &l7_ctx, method, error) + .await?; return Ok(()); } if report @@ -7091,7 +7130,7 @@ network_policies: let json = event.to_json().unwrap(); assert_eq!(json["class_name"], "HTTP Activity"); - assert_eq!(json["activity_name"], "Other"); + assert_eq!(json["activity_name"], "Get"); assert_eq!(json["action"], "Denied"); assert_eq!(json["disposition"], "Blocked"); assert_eq!(json["severity"], "Medium"); @@ -10268,6 +10307,36 @@ network_policies: assert!(!malformed.contains("real-secret")); } + #[test] + fn unsupported_forward_scheme_event_omits_request_url() { + use openshell_ocsf::validation::{load_class_schema, validate_required_fields}; + + let event = + build_forward_unsupported_scheme_ocsf_event("GET", "https", "api.example.com", 443); + let json = event.to_json().unwrap(); + + assert_eq!(json["http_request"]["http_method"], "GET"); + assert!(json["http_request"].get("url").is_none()); + assert_eq!(json["http_response"]["code"], 400); + validate_required_fields(&json, &load_class_schema("http_activity")); + } + + #[test] + fn credential_endpoint_mismatch_event_includes_method_and_response() { + use openshell_ocsf::validation::{load_class_schema, validate_required_fields}; + + let event = + build_credential_endpoint_mismatch_event("POST", "api.example.com", 443, "bound"); + let json = event.to_json().unwrap(); + + assert_eq!(json["class_uid"], 4002); + assert_eq!(json["activity_name"], "Post"); + assert_eq!(json["http_request"]["http_method"], "POST"); + assert!(json["http_request"].get("url").is_none()); + assert_eq!(json["http_response"]["code"], 403); + validate_required_fields(&json, &load_class_schema("http_activity")); + } + #[test] fn forward_credentials_capture_endpoint_resolver_and_revision_together() { use openshell_core::proto::{StaticCredentialBinding, StaticCredentialEndpointBinding}; diff --git a/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs b/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs index 9b2b6e82a6..5948cd5224 100644 --- a/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs +++ b/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs @@ -208,7 +208,7 @@ fn representative_adapter_denials_preserve_ocsf_fields() { )) .unwrap(); assert_eq!(forward["class_name"], "HTTP Activity"); - assert_eq!(forward["activity_name"], "Other"); + assert_eq!(forward["activity_name"], "Post"); assert_eq!(forward["action"], "Denied"); assert_eq!(forward["disposition"], "Blocked"); assert_eq!(forward["severity"], "Medium"); @@ -267,7 +267,7 @@ fn representative_adapter_allows_preserve_ocsf_fields() { )) .unwrap(); assert_eq!(forward["class_name"], "HTTP Activity"); - assert_eq!(forward["activity_name"], "Other"); + assert_eq!(forward["activity_name"], "Get"); assert_eq!(forward["action"], "Allowed"); assert_eq!(forward["disposition"], "Allowed"); assert_eq!(forward["severity"], "Informational"); diff --git a/crates/openshell-supervisor-process/Cargo.toml b/crates/openshell-supervisor-process/Cargo.toml index 2e2120f1d0..7076c02f70 100644 --- a/crates/openshell-supervisor-process/Cargo.toml +++ b/crates/openshell-supervisor-process/Cargo.toml @@ -45,6 +45,7 @@ socket2 = { workspace = true } tempfile = "3" [dev-dependencies] +openshell-ocsf = { path = "../openshell-ocsf", features = ["test-support"] } tempfile = "3" [lints] diff --git a/deploy/docker/Dockerfile.gateway b/deploy/docker/Dockerfile.gateway index 52f2b27db3..0576c2e465 100644 --- a/deploy/docker/Dockerfile.gateway +++ b/deploy/docker/Dockerfile.gateway @@ -8,7 +8,7 @@ # # Distroless Debian provides the glibc runtime required by the binary. -ARG GATEWAY_BASE_IMAGE=gcr.io/distroless/cc-debian13:nonroot@sha256:c31ff9abcb1910f3ab25c7957bdaf0bfe12a01eb546e8df2282f1c8f682b606c +ARG GATEWAY_BASE_IMAGE=gcr.io/distroless/cc-debian13:nonroot@sha256:54df941ed0d06a1bd95ef5e0ce391fd8d9f94b64782dc9a60062727849ee3f97 FROM ${GATEWAY_BASE_IMAGE} AS gateway ARG TARGETARCH diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index 3c32e24b67..83753cdeaf 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -273,7 +273,9 @@ discovery endpoint or its TLS CA. | server.oidc.adminRole | string | `""` | Role name for admin access. Leave empty (with userRole also empty) for authentication-only mode. Both must be set or both empty. | | server.oidc.audience | string | `"openshell-cli"` | Expected audience claim for the API resource server. This should match the server's --oidc-audience, NOT the CLI client ID. | | server.oidc.caConfigMapName | string | `""` | Name of a ConfigMap containing a CA certificate bundle (key: ca.crt) for verifying the OIDC issuer's TLS certificate. Required when the issuer uses a non-public CA (e.g. OpenShift ingress, private PKI). | +| server.oidc.dangerouslyAllowInsecureHttp | bool | `false` | Development only: permit cleartext OIDC requests to numeric loopback addresses. This never permits HTTP to hostnames or non-loopback addresses. | | server.oidc.issuer | string | `""` | OIDC issuer URL (e.g. https://keycloak.example.com/realms/openshell). | +| server.oidc.jwksAllowedOrigins | list | `[]` | Additional trusted HTTPS origins allowed to serve JWKS. The issuer origin is always allowed. Entries must not include a path or query. | | server.oidc.jwksTtl | int | `3600` | JWKS key cache TTL in seconds. Must be greater than zero. | | server.oidc.rolesClaim | string | `""` | Dot-separated path to the roles array in the JWT claims. Keycloak: "realm_access.roles", Entra ID: "roles", Okta: "groups". | | server.oidc.scopesClaim | string | `""` | Dot-separated path to the scopes array in the JWT claims. | diff --git a/deploy/helm/openshell/ci/values-keycloak.yaml b/deploy/helm/openshell/ci/values-keycloak.yaml index cc6ca658bf..6df74e3258 100644 --- a/deploy/helm/openshell/ci/values-keycloak.yaml +++ b/deploy/helm/openshell/ci/values-keycloak.yaml @@ -3,7 +3,7 @@ # OIDC configuration overlay for a local Keycloak instance in k3s. # -# Run the one-time setup task first: +# Run the setup task first (rerun it to rotate the development CA): # mise run keycloak:k8s:setup # # Then layer this file on top of values.yaml when deploying: @@ -15,7 +15,8 @@ # Issuer note: the setup task configures Keycloak with KC_HOSTNAME set to the # in-cluster service hostname, so tokens always carry that hostname as `iss` # regardless of how they were obtained (e.g. via a localhost port-forward). -# The gateway fetches JWKS from this URL inside the cluster. +# The gateway fetches JWKS over TLS from this URL inside the cluster. The setup +# task creates the Keycloak development CA ConfigMap referenced below. # # CLI token acquisition: keep a port-forward running while using openshell login: # kubectl -n keycloak port-forward svc/keycloak 9090:80 @@ -23,7 +24,8 @@ server: oidc: # Must match KC_HOSTNAME set by keycloak:k8s:setup (in-cluster service hostname). - issuer: "http://keycloak.keycloak.svc.cluster.local/realms/openshell" + issuer: "https://keycloak.keycloak.svc.cluster.local:443/realms/openshell" + caConfigMapName: "openshell-keycloak-ca" # Must match the client ID in the imported realm (openshell-cli). audience: "openshell-cli" # Short TTL for dev so JWKS key rotation is picked up quickly. diff --git a/deploy/helm/openshell/templates/gateway-config.yaml b/deploy/helm/openshell/templates/gateway-config.yaml index 2c2b8216ee..7075aafc50 100644 --- a/deploy/helm/openshell/templates/gateway-config.yaml +++ b/deploy/helm/openshell/templates/gateway-config.yaml @@ -118,9 +118,11 @@ data: {{- if .Values.server.oidc.issuer }} [openshell.gateway.oidc] - issuer = {{ .Values.server.oidc.issuer | quote }} - audience = {{ .Values.server.oidc.audience | quote }} - jwks_ttl_secs = {{ .Values.server.oidc.jwksTtl }} + issuer = {{ .Values.server.oidc.issuer | quote }} + dangerously_allow_insecure_http = {{ .Values.server.oidc.dangerouslyAllowInsecureHttp }} + jwks_allowed_origins = {{ .Values.server.oidc.jwksAllowedOrigins | toJson }} + audience = {{ .Values.server.oidc.audience | quote }} + jwks_ttl_secs = {{ .Values.server.oidc.jwksTtl }} {{- if .Values.server.oidc.rolesClaim }} roles_claim = {{ .Values.server.oidc.rolesClaim | quote }} {{- end }} diff --git a/deploy/helm/openshell/tests/gateway_config_test.yaml b/deploy/helm/openshell/tests/gateway_config_test.yaml index 2cf7705b8e..28b6eca35a 100644 --- a/deploy/helm/openshell/tests/gateway_config_test.yaml +++ b/deploy/helm/openshell/tests/gateway_config_test.yaml @@ -122,6 +122,20 @@ tests: path: data["gateway.toml"] pattern: '\[openshell\.gateway\.otlp\]' + - it: renders OIDC transport security settings + template: templates/gateway-config.yaml + set: + server.oidc.issuer: https://issuer.example.com + server.oidc.dangerouslyAllowInsecureHttp: false + server.oidc.jwksAllowedOrigins[0]: https://keys.example.com + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: '(?m)^dangerously_allow_insecure_http\s*=\s*false$' + - matchRegex: + path: data["gateway.toml"] + pattern: '(?m)^jwks_allowed_origins\s*=\s*\["https://keys.example.com"\]$' + - it: treats a null OTLP map as disabled template: templates/gateway-config.yaml set: diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index 432af61195..8de3b00e95 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -419,6 +419,12 @@ server: oidc: # -- OIDC issuer URL (e.g. https://keycloak.example.com/realms/openshell). issuer: "" + # -- Development only: permit cleartext OIDC requests to numeric loopback + # addresses. This never permits HTTP to hostnames or non-loopback addresses. + dangerouslyAllowInsecureHttp: false + # -- Additional trusted HTTPS origins allowed to serve JWKS. The issuer + # origin is always allowed. Entries must not include a path or query. + jwksAllowedOrigins: [] # -- Expected audience claim for the API resource server. # This should match the server's --oidc-audience, NOT the CLI client ID. audience: "openshell-cli" diff --git a/docs/kubernetes/access-control.mdx b/docs/kubernetes/access-control.mdx index 3fd7a66ecb..251c67c054 100644 --- a/docs/kubernetes/access-control.mdx +++ b/docs/kubernetes/access-control.mdx @@ -52,6 +52,9 @@ The `audience` value must match the client ID configured in your identity provid | Value | Default | Purpose | |---|---|---| | `server.oidc.issuer` | `""` | OIDC issuer URL. Empty disables OIDC. | +| `server.oidc.dangerouslyAllowInsecureHttp` | `false` | Development-only acknowledgement for numeric-loopback HTTP. It does not allow cluster-service or remote HTTP issuers. | +| `server.oidc.jwksAllowedOrigins` | `[]` | Additional trusted HTTPS origins allowed to serve JWKS. | +| `server.oidc.caConfigMapName` | `""` | ConfigMap containing the private issuer CA in `ca.crt`. | | `server.oidc.audience` | `openshell-cli` | Expected `aud` claim in the JWT. | | `server.oidc.jwksTtl` | `3600` | JWKS key cache TTL in seconds. Must be greater than zero. | | `server.oidc.rolesClaim` | `""` | Dot-separated path to the roles array in JWT claims. | @@ -59,6 +62,11 @@ The `audience` value must match the client ID configured in your identity provid | `server.oidc.userRole` | `""` | Role name that grants standard user access. | | `server.oidc.scopesClaim` | `""` | Dot-separated path to the scopes array in JWT claims. | +The issuer must use HTTPS. The gateway rejects discovery and JWKS redirects, +limits response sizes, requires a JSON media type, and rejects a `jwks_uri` on +a different origin unless that origin appears in `jwksAllowedOrigins`. Use +`server.oidc.caConfigMapName` for issuers signed by a private CA. + ### Auth-only mode vs. RBAC mode Leave both `adminRole` and `userRole` empty to use auth-only mode: any request with a valid JWT from the configured issuer is accepted, but no role distinction is enforced. diff --git a/docs/observability/ocsf-json-export.mdx b/docs/observability/ocsf-json-export.mdx index 8a5b6430e7..29771f5678 100644 --- a/docs/observability/ocsf-json-export.mdx +++ b/docs/observability/ocsf-json-export.mdx @@ -168,6 +168,10 @@ The `class_uid` field identifies the event type: | 5019 | Device Config State Change | `CONFIG:` | | 6002 | Application Lifecycle | `LIFECYCLE:` | +HTTP Activity records include request or response details. Rejections that have +parsed a request, including early credential-binding failures, include safe +method-only request context and the generated response. + ## SIEM Schema Version Compatibility OpenShell emits OCSF v1.8.0 events internally, but many SIEMs only support older schema versions. The `ocsf_schema_version` setting tells the JSONL layer to downgrade events before writing, stripping fields and profiles that don't exist in the target version. diff --git a/docs/reference/api-errors.mdx b/docs/reference/api-errors.mdx new file mode 100644 index 0000000000..4fec785a68 --- /dev/null +++ b/docs/reference/api-errors.mdx @@ -0,0 +1,85 @@ +--- +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +title: "API Errors" +sidebar-title: "API Errors" +description: "Inspect structured gateway failures and choose an appropriate recovery action." +keywords: "OpenShell, SDK, gRPC, API errors, retries" +--- + +Gateway errors include a gRPC status code and a message. Shared request validation +and concurrency checks also return standard protobuf details in +`grpc-status-details-bin`. Use the status code and structured fields for decisions. +Treat messages as explanations whose text can change. + +## Structured details + +The SDKs decode these standard detail types while retaining the original failure. +Older gateways and checks that have not adopted structured details can return only +a code and message. Missing details do not change the meaning of the status code. + +| Detail | Meaning | +|---|---| +| `google.rpc.BadRequest` | `field_violations` identifies rejected fields and explains each violation. Shared sandbox, exec, provider size, and workspace selector checks supply these details. | +| `google.rpc.ErrorInfo` | `reason`, `domain`, and `metadata` identify a failure without parsing its message. Gateway reasons use the `openshell.nvidia.com` domain. | +| `google.rpc.RetryInfo` | `retry_delay` gives a minimum delay before an otherwise safe retry. Its presence does not guarantee that a mutation has not already committed. | + +Recognized gateway reasons include the following. + +| Reason | Code | Recovery | +|---|---|---| +| `INVALID_ARGUMENT` | `INVALID_ARGUMENT` | Correct the fields listed in `BadRequest`. | +| `RESOURCE_VERSION_CONFLICT` | `ABORTED` | Read the resource again and construct a new conditional write. `metadata.recovery` is `REFRESH_STATE`; `current_resource_version` is included when known. | +| `PROFILE_SOURCE_UNAVAILABLE` | `UNAVAILABLE` | Retry a profile snapshot read after at least the supplied delay. | + +## Status and retry guidance + +A timeout or disconnected transport can occur after a mutation commits. Do not +automatically repeat creates, credential rotation, or command execution based +only on a transient status. Retry a mutation only when its documented operation +contract makes the repeated request safe. A correlation ID does not provide that +guarantee. + +| Status | Recovery | +|---|---| +| `INVALID_ARGUMENT`, `OUT_OF_RANGE` | Correct the request. | +| `UNAUTHENTICATED` | Refresh or replace credentials before a new attempt. | +| `PERMISSION_DENIED` | Obtain the required authorization. | +| `NOT_FOUND` | Check the resource and workspace. Follow the operation's missing-resource contract. | +| `ALREADY_EXISTS` | Inspect the existing resource before deciding whether it satisfies the request. | +| `FAILED_PRECONDITION` | Resolve the reported state or configuration requirement. | +| `ABORTED` | Read fresh state before retrying a conditional operation. | +| `UNAVAILABLE`, `RESOURCE_EXHAUSTED` | A transient condition may recover. Apply backoff and any minimum retry delay only to a retry-safe operation. | +| `DEADLINE_EXCEEDED`, `CANCELLED` | A mutation's outcome can be unknown. Cancellation does not imply rollback. | +| `UNIMPLEMENTED` | Check gateway and SDK version compatibility. | +| `INTERNAL`, `UNKNOWN`, `DATA_LOSS` | Preserve the status and correlation metadata for diagnosis. Do not blindly retry mutations. | + +## SDK access + +Each SDK exposes decoded fields and an escape hatch for complete transport data. +Unknown details remain available through the original error even when the SDK +does not recognize their message type. + +| SDK | Decoded details | Original failure | +|---|---|---| +| Rust | `SdkError::error_details()`, `retry_delay()` | `SdkError::grpc_status()` returns the original `tonic::Status`, including details bytes and metadata. | +| Go | `StatusError.FieldViolations`, `ErrorInfo`, `RetryDelay`, `GRPCCode` | `StatusError.Cause` retains the gRPC error. `status.FromError` can recover its details through error wrapping. | +| TypeScript | `SdkError.fieldViolations`, `errorInfo`, `retryDelayMs`, `connectCode` | `SdkError.cause` retains the `ConnectError`, including all details and metadata. Use `fromConnect` for raw calls. | +| Python | `GatewayError.field_violations`, `error_info`, `retry_delay` | `raw_error` retains the gRPC exception and metadata; `raw_status` retains the parsed envelope. Use `from_grpc_error` for raw calls. | + +Retry delays are Rust and Go durations, TypeScript milliseconds, and Python +seconds. Absent or invalid delay details do not produce a suggested delay. + +## Migration + +Existing error codes and human-readable messages remain available. Python curated +clients now raise `GatewayError`, which remains a `grpc.RpcError`; existing +`except grpc.RpcError` handlers continue to work. `GatewayError` is not a +`grpc.Call`. If your handler checks that interface, inspect `raw_error` before +checking the status. The Python SDK's deletion wait and managed-sandbox cleanup +use the original call to recognize `NOT_FOUND`; other failures still propagate. +Rust error variants now retain +status fields; use `..` when destructuring variants that do not need those fields. +Go and TypeScript add typed detail fields to their existing error types. + +No SDK automatically retries a mutation as a result of decoding these details. diff --git a/docs/reference/gateway-auth.mdx b/docs/reference/gateway-auth.mdx index ac56e0fcf8..4d9e0841ad 100644 --- a/docs/reference/gateway-auth.mdx +++ b/docs/reference/gateway-auth.mdx @@ -90,6 +90,8 @@ The same settings are available through environment variables: | Environment variable | Purpose | Default | |---|---|---| | `OPENSHELL_OIDC_ISSUER` | OIDC issuer URL. The gateway discovers `/.well-known/openid-configuration` from this URL. | None | +| `OPENSHELL_OIDC_DANGEROUSLY_ALLOW_INSECURE_HTTP` | Development-only acknowledgement for HTTP issuers on numeric loopback addresses. HTTP hostnames and non-loopback addresses remain rejected. | `false` | +| `OPENSHELL_OIDC_JWKS_ALLOWED_ORIGINS` | Comma-separated additional HTTPS origins trusted to serve JWKS. | Empty | | `OPENSHELL_OIDC_AUDIENCE` | Expected JWT `aud` claim. | `openshell-cli` | | `OPENSHELL_OIDC_JWKS_TTL` | JWKS cache TTL in seconds. The gateway also refreshes on an unknown key ID. Must be greater than zero. | `3600` | | `OPENSHELL_OIDC_ROLES_CLAIM` | Dot-separated claim path containing roles. | `realm_access.roles` | @@ -104,12 +106,22 @@ server: oidc: issuer: https://idp.example.com/realms/openshell audience: openshell-cli + # Only needed when discovery returns a deliberately separate JWKS origin. + jwksAllowedOrigins: + - https://keys.example.com rolesClaim: realm_access.roles adminRole: openshell-admin userRole: openshell-user scopesClaim: "" ``` +The gateway requires HTTPS for OIDC discovery and JWKS retrieval, rejects +redirects, and trusts the issuer origin for JWKS by default. Add a +`jwksAllowedOrigins` entry only when the identity provider intentionally serves +keys from another trusted origin. For local tests, numeric-loopback HTTP also +requires `dangerouslyAllowInsecureHttp: true`; this setting never permits an +HTTP hostname or non-loopback address. + Register an OIDC gateway with the CLI: ```shell diff --git a/docs/reference/gateway-config.mdx b/docs/reference/gateway-config.mdx index 7c8e043e16..528ef9d88a 100644 --- a/docs/reference/gateway-config.mdx +++ b/docs/reference/gateway-config.mdx @@ -213,13 +213,15 @@ endpoint = "http://otel-collector.observability.svc:4317" service_name = "openshell-gateway" [openshell.gateway.oidc] -issuer = "https://idp.example.com/realms/openshell" -audience = "openshell-cli" -jwks_ttl_secs = 3600 # Must be greater than zero. -roles_claim = "realm_access.roles" -admin_role = "openshell-admin" -user_role = "openshell-user" -scopes_claim = "" +issuer = "https://idp.example.com/realms/openshell" +audience = "openshell-cli" +jwks_ttl_secs = 3600 # Must be greater than zero. +jwks_allowed_origins = ["https://keys.example.com"] # Default: issuer origin only. +dangerously_allow_insecure_http = false # Development-only numeric-loopback escape hatch. +roles_claim = "realm_access.roles" +admin_role = "openshell-admin" +user_role = "openshell-user" +scopes_claim = "" [[openshell.gateway.interceptors]] name = "quota" diff --git a/docs/sandboxes/manage-sandboxes.mdx b/docs/sandboxes/manage-sandboxes.mdx index 5a1e32869a..730b7da794 100644 --- a/docs/sandboxes/manage-sandboxes.mdx +++ b/docs/sandboxes/manage-sandboxes.mdx @@ -46,6 +46,17 @@ captures the command result, and deletes the sandbox after the command exits: openshell sandbox create --no-keep -- sh -c 'echo done; exit 0' ``` +Combine `--detach` and `--no-keep` for a background workload whose lifecycle +belongs entirely to the gateway: + +```shell +openshell sandbox create --detach --no-keep -- ./worker +``` + +The create command returns after the workload is ready. The gateway keeps the +canonical process running without a host-side attachment and deletes the +sandbox after that process exits. + `--upload` cannot yet be combined with a trailing main command because uploads finish after the canonical process starts. Create a scratch sandbox, upload the files, then launch the workload with `sandbox exec`, or build the files into the diff --git a/e2e/support/gateway-common.sh b/e2e/support/gateway-common.sh index 3d63c610c5..93b09621ab 100644 --- a/e2e/support/gateway-common.sh +++ b/e2e/support/gateway-common.sh @@ -190,6 +190,11 @@ e2e_write_gateway_oidc_config() { printf '[openshell.gateway.oidc]\n' printf 'issuer = %s\n' "$(e2e_toml_string "${issuer}")" + case "${issuer}" in + http://127.*|http://\[::1\]*) + printf 'dangerously_allow_insecure_http = true\n' + ;; + esac printf 'audience = "openshell-cli"\n' printf 'jwks_ttl_secs = 60\n' printf 'roles_claim = "realm_access.roles"\n' diff --git a/e2e/with-docker-gateway.sh b/e2e/with-docker-gateway.sh index 0f64247731..1661a7a067 100755 --- a/e2e/with-docker-gateway.sh +++ b/e2e/with-docker-gateway.sh @@ -572,6 +572,11 @@ if [ "${OIDC_MODE}" = "1" ]; then --oidc-audience openshell-cli --oidc-scopes-claim scope ) + case "${OIDC_ISSUER}" in + http://127.*|http://\[::1\]*) + GATEWAY_ARGS+=(--oidc-dangerously-allow-insecure-http true) + ;; + esac else GATEWAY_ARGS+=( --tls-client-ca "${PKI_DIR}/ca.crt" diff --git a/e2e/with-keycloak.sh b/e2e/with-keycloak.sh index 571a25a123..5c29491f38 100755 --- a/e2e/with-keycloak.sh +++ b/e2e/with-keycloak.sh @@ -49,7 +49,7 @@ if ! CONTAINER_RUNTIME="$RUNTIME" KEYCLOAK_PORT="$KEYCLOAK_PORT" \ "$ROOT_DIR/scripts/keycloak-dev.sh" start fi -export OPENSHELL_E2E_OIDC_ISSUER="${OPENSHELL_E2E_OIDC_ISSUER:-http://localhost:${KEYCLOAK_PORT}/realms/openshell}" +export OPENSHELL_E2E_OIDC_ISSUER="${OPENSHELL_E2E_OIDC_ISSUER:-http://127.0.0.1:${KEYCLOAK_PORT}/realms/openshell}" export OPENSHELL_E2E_OIDC_USERNAME="${OPENSHELL_E2E_OIDC_USERNAME:-admin@test}" export OPENSHELL_E2E_OIDC_PASSWORD="${OPENSHELL_E2E_OIDC_PASSWORD:-admin}" export OPENSHELL_E2E_OIDC_ROLE="${OPENSHELL_E2E_OIDC_ROLE:-openshell-admin}" diff --git a/e2e/with-podman-gateway.sh b/e2e/with-podman-gateway.sh index e7c47a251f..3fb4091c9f 100755 --- a/e2e/with-podman-gateway.sh +++ b/e2e/with-podman-gateway.sh @@ -751,6 +751,11 @@ if [ "${OIDC_MODE}" = "1" ]; then --oidc-audience openshell-cli --oidc-scopes-claim scope ) + case "${OIDC_ISSUER}" in + http://127.*|http://\[::1\]*) + GATEWAY_ARGS+=(--oidc-dangerously-allow-insecure-http true) + ;; + esac else GATEWAY_ARGS+=( --tls-client-ca "${PKI_DIR}/ca.crt" diff --git a/examples/governance-interceptor/Cargo.lock b/examples/governance-interceptor/Cargo.lock index 49ef45ac0c..958e37d814 100644 --- a/examples/governance-interceptor/Cargo.lock +++ b/examples/governance-interceptor/Cargo.lock @@ -1082,6 +1082,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-types", "tracing", "url", ] @@ -2134,6 +2135,17 @@ dependencies = [ "tonic-build", ] +[[package]] +name = "tonic-types" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab1b02061f83d519bba3caa167f88f261ef05720ab8ebc954ade70de3348e8" +dependencies = [ + "prost", + "prost-types", + "tonic", +] + [[package]] name = "tower" version = "0.5.3" diff --git a/examples/supervisor-middleware-content-guard/Cargo.lock b/examples/supervisor-middleware-content-guard/Cargo.lock index 25286fd882..f65d9a8318 100644 --- a/examples/supervisor-middleware-content-guard/Cargo.lock +++ b/examples/supervisor-middleware-content-guard/Cargo.lock @@ -969,6 +969,7 @@ dependencies = [ "tonic", "tonic-prost", "tonic-prost-build", + "tonic-types", "tracing", "url", ] @@ -1781,6 +1782,17 @@ dependencies = [ "tonic-build", ] +[[package]] +name = "tonic-types" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab1b02061f83d519bba3caa167f88f261ef05720ab8ebc954ade70de3348e8" +dependencies = [ + "prost", + "prost-types", + "tonic", +] + [[package]] name = "tower" version = "0.5.3" diff --git a/nix/test-guest/README.md b/nix/test-guest/README.md index 58cf771679..fa2ca96052 100644 --- a/nix/test-guest/README.md +++ b/nix/test-guest/README.md @@ -53,8 +53,7 @@ nix/test-guest/ └── roles/ ├── gateway-podman/ ├── openshell-development/ - ├── openshell-rpm/ - └── openshell-rpm-gateway-upgrade/ + └── openshell-rpm/ ``` - `default.nix` assembles the guest and cache flake apps. It selects host architecture and acceleration, supplies the runtime tools, and exposes distro profiles and configuration playbooks as Nix-store catalogs. @@ -167,31 +166,6 @@ copied artifacts are present. Unlike `--with`, provisioners are not cached. They can therefore install and start an OpenShell system without coupling the prepared guest image to a particular build or driver configuration. -Provisioners that support gateway continuity install a target-control command: - -```text -/home/openshell/.local/bin/openshell-test-guest-gateway-restart -``` - -It restarts an already-provisioned gateway and exits only after CLI health -succeeds. An explicit conformance plan consumes that stable test-guest contract -without knowing how the provisioner implements it: - -```shell -openshell-conformance run --plan - <<'EOF' -version = 1 - -[[runs]] -scenario = "sandbox-continuity" -workload_expectation = "reconciled" - -[[runs.actions]] -name = "gateway-restart" -command = "/home/openshell/.local/bin/openshell-test-guest-gateway-restart" -timeout_secs = 120 -EOF -``` - `openshell-development` expects these copied guest paths: - `/usr/local/bin/openshell` @@ -213,36 +187,14 @@ nix run .#test-guest -- \ --copy ./openshell-sandbox.tar:/usr/local/lib/openshell-sandbox.tar \ --provision openshell-development \ --provision gateway-podman \ - -- /usr/local/bin/openshell-conformance run --plan - <<'EOF' -version = 1 - -[[runs]] -scenario = "sandbox-continuity" -workload_expectation = "reconciled" - -[[runs.actions]] -name = "gateway-restart" -command = "/home/openshell/.local/bin/openshell-test-guest-gateway-restart" -timeout_secs = 120 -EOF + -- /usr/local/bin/openshell-conformance run smoke ``` `openshell-rpm` expects OpenShell to have been installed with `--install`. It uses the RPM-owned `/usr/bin` binaries and `openshell-gateway` user service, without copied development artifacts or a supervisor archive. Compose it with -`gateway-podman` to start the installed version. The existing upgrade flow uses -the same role with the rootless configuration before -`openshell-rpm-gateway-upgrade`. - -`openshell-rpm-latest-release` downloads and installs the latest stable -OpenShell GitHub release for the guest architecture, then publishes the same -RPM installation contract. Compose it with `gateway-podman` and an RPM gateway -action when testing an upgrade from the current release. - -Versioned plans under `nix/test-guest/conformance-plans/` bind conformance -scenarios to the stable action-command contracts installed by provisioners. -Copy the applicable plan to the guest and pass it to `openshell-conformance run ---plan`. +`gateway-podman` to start the installed version before running smoke +conformance. ## Prepared VM cache diff --git a/nix/test-guest/conformance-plans/gateway-upgrade-restart.toml b/nix/test-guest/conformance-plans/gateway-upgrade-restart.toml deleted file mode 100644 index fde903b778..0000000000 --- a/nix/test-guest/conformance-plans/gateway-upgrade-restart.toml +++ /dev/null @@ -1,25 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -version = 1 - -[diagnostics] -command = "/home/openshell/.local/bin/openshell-test-guest-diagnostics" -timeout_secs = 60 - -[[runs]] -scenario = "smoke" - -[[runs]] -scenario = "sandbox-continuity" -workload_expectation = "reconciled" - -[[runs.actions]] -name = "gateway-upgrade" -command = "/home/openshell/.local/bin/openshell-test-guest-gateway-upgrade" -timeout_secs = 120 - -[[runs.actions]] -name = "gateway-restart" -command = "/home/openshell/.local/bin/openshell-test-guest-gateway-restart" -timeout_secs = 120 diff --git a/nix/test-guest/default.nix b/nix/test-guest/default.nix index 8129198d7f..433e6dc1cb 100644 --- a/nix/test-guest/default.nix +++ b/nix/test-guest/default.nix @@ -43,10 +43,7 @@ let provisionerRoles = [ "openshell-development" "openshell-rpm" - "openshell-rpm-latest-release" "gateway-podman" - "openshell-rpm-gateway-reinstall" - "openshell-rpm-gateway-upgrade" ]; mkDistroProfile = diff --git a/nix/test-guest/provisioners/roles/gateway-podman/defaults/main.yml b/nix/test-guest/provisioners/roles/gateway-podman/defaults/main.yml deleted file mode 100644 index ce0ec961dc..0000000000 --- a/nix/test-guest/provisioners/roles/gateway-podman/defaults/main.yml +++ /dev/null @@ -1,7 +0,0 @@ ---- -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -openshell_gateway_service_command: /home/openshell/.local/bin/openshell-test-guest-as-gateway-user -openshell_gateway_restart_command: /home/openshell/.local/bin/openshell-test-guest-gateway-restart -openshell_gateway_diagnostics_command: /home/openshell/.local/bin/openshell-test-guest-diagnostics diff --git a/nix/test-guest/provisioners/roles/gateway-podman/tasks/lifecycle.yml b/nix/test-guest/provisioners/roles/gateway-podman/tasks/lifecycle.yml index ccd6615ff1..2f704c7807 100644 --- a/nix/test-guest/provisioners/roles/gateway-podman/tasks/lifecycle.yml +++ b/nix/test-guest/provisioners/roles/gateway-podman/tasks/lifecycle.yml @@ -80,56 +80,3 @@ ansible.builtin.assert: that: gateway_health is not failed fail_msg: The provisioned gateway did not become healthy. - -- name: Create the target gateway-control command directory - ansible.builtin.file: - path: "{{ openshell_gateway_restart_command | dirname }}" - state: directory - mode: "0700" - -- name: Install the gateway service-account command wrapper - ansible.builtin.copy: - dest: "{{ openshell_gateway_service_command }}" - mode: "0700" - content: | - #!/usr/bin/env bash - set -Eeuo pipefail - exec sudo -H -u {{ openshell_gateway_service_user }} env \ - HOME={{ openshell_gateway_service_home }} \ - XDG_RUNTIME_DIR=/run/user/{{ openshell_gateway_service_uid }} \ - DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/{{ openshell_gateway_service_uid }}/bus \ - "$@" - -- name: Install the target gateway restart command - ansible.builtin.copy: - dest: "{{ openshell_gateway_restart_command }}" - mode: "0700" - content: | - #!/usr/bin/env bash - set -Eeuo pipefail - gateway_user_command={{ openshell_gateway_service_command | quote }} - "${gateway_user_command}" systemctl --user restart {{ openshell_gateway_service }} - for _ in $(seq 1 60); do - if "${gateway_user_command}" {{ openshell_cli_bin }} status >/dev/null 2>&1; then - exit 0 - fi - sleep 1 - done - "${gateway_user_command}" systemctl --user status {{ openshell_gateway_service }} --no-pager >&2 || true - exit 1 - -- name: Install the target gateway diagnostics command - ansible.builtin.copy: - dest: "{{ openshell_gateway_diagnostics_command }}" - mode: "0700" - content: | - #!/usr/bin/env bash - set -u - gateway_user_command={{ openshell_gateway_service_command | quote }} - "${gateway_user_command}" systemctl --user status {{ openshell_gateway_service }} --no-pager || true - "${gateway_user_command}" journalctl --user -u {{ openshell_gateway_service }} --no-pager -n 200 || true - "${gateway_user_command}" podman info || true - "${gateway_user_command}" podman ps --all || true - if command -v getenforce >/dev/null 2>&1; then - getenforce || true - fi diff --git a/nix/test-guest/provisioners/roles/openshell-rpm-gateway-reinstall/defaults/main.yml b/nix/test-guest/provisioners/roles/openshell-rpm-gateway-reinstall/defaults/main.yml deleted file mode 100644 index 95c448d300..0000000000 --- a/nix/test-guest/provisioners/roles/openshell-rpm-gateway-reinstall/defaults/main.yml +++ /dev/null @@ -1,7 +0,0 @@ ---- -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -openshell_rpm_reinstall_cli: /var/lib/openshell-conformance/candidate/openshell.rpm -openshell_rpm_reinstall_gateway: /var/lib/openshell-conformance/candidate/openshell-gateway.rpm -openshell_rpm_reinstall_command: /home/openshell/.local/bin/openshell-test-guest-gateway-reinstall diff --git a/nix/test-guest/provisioners/roles/openshell-rpm-gateway-reinstall/tasks/main.yml b/nix/test-guest/provisioners/roles/openshell-rpm-gateway-reinstall/tasks/main.yml deleted file mode 100644 index 36f1c6dce2..0000000000 --- a/nix/test-guest/provisioners/roles/openshell-rpm-gateway-reinstall/tasks/main.yml +++ /dev/null @@ -1,70 +0,0 @@ ---- -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -- name: Require RPM gateway provisioner dependencies - ansible.builtin.assert: - that: - - openshell_install_source | default('') == 'rpm' - - openshell_cli_bin is defined - - openshell_gateway_service is defined - - openshell_gateway_runtime | default('') == 'rootless-podman' - fail_msg: >- - openshell-rpm-gateway-reinstall requires openshell-rpm and a configured - gateway runtime. - -- name: Verify candidate RPMs for reinstall - ansible.builtin.stat: - path: "{{ item }}" - loop: - - "{{ openshell_rpm_reinstall_cli }}" - - "{{ openshell_rpm_reinstall_gateway }}" - register: openshell_rpm_reinstall_candidates - -- name: Require copied candidate RPMs - ansible.builtin.assert: - that: item.stat.exists - fail_msg: "missing candidate RPM: {{ item.item }}" - loop: "{{ openshell_rpm_reinstall_candidates.results }}" - loop_control: - label: "{{ item.item }}" - -- name: Create the target reinstall command directory - ansible.builtin.file: - path: "{{ openshell_rpm_reinstall_command | dirname }}" - state: directory - mode: "0700" - -- name: Install the target RPM reinstall command - ansible.builtin.copy: - dest: "{{ openshell_rpm_reinstall_command }}" - mode: "0700" - content: | - #!/usr/bin/env bash - set -Eeuo pipefail - - latest_transaction() { - sudo dnf history list --reverse --quiet | awk 'NR == 1 { print $1 }' - } - - before_transaction="$(latest_transaction)" - sudo dnf reinstall -y --nogpgcheck {{ openshell_rpm_reinstall_cli }} {{ openshell_rpm_reinstall_gateway }} - after_transaction="$(latest_transaction)" - if [ -z "${after_transaction}" ] || [ "${after_transaction}" = "${before_transaction}" ]; then - echo "RPM reinstall did not create a DNF transaction" >&2 - exit 1 - fi - transaction_info="$(sudo dnf history info "${after_transaction}")" - grep -Eq 'Reinstall[[:space:]]+openshell-' <<<"${transaction_info}" - grep -Eq 'Reinstall[[:space:]]+openshell-gateway-' <<<"${transaction_info}" - rpm -V openshell openshell-gateway - systemctl --user daemon-reload - systemctl --user restart {{ openshell_gateway_service }} - for _ in $(seq 1 60); do - if {{ openshell_cli_bin }} status >/dev/null 2>&1; then - exit 0 - fi - sleep 1 - done - systemctl --user status {{ openshell_gateway_service }} --no-pager >&2 || true - exit 1 diff --git a/nix/test-guest/provisioners/roles/openshell-rpm-gateway-upgrade/defaults/main.yml b/nix/test-guest/provisioners/roles/openshell-rpm-gateway-upgrade/defaults/main.yml deleted file mode 100644 index 1538cce109..0000000000 --- a/nix/test-guest/provisioners/roles/openshell-rpm-gateway-upgrade/defaults/main.yml +++ /dev/null @@ -1,7 +0,0 @@ ---- -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -openshell_rpm_upgrade_cli: /var/lib/openshell-conformance/candidate/openshell.rpm -openshell_rpm_upgrade_gateway: /var/lib/openshell-conformance/candidate/openshell-gateway.rpm -openshell_rpm_upgrade_command: /home/openshell/.local/bin/openshell-test-guest-gateway-upgrade diff --git a/nix/test-guest/provisioners/roles/openshell-rpm-gateway-upgrade/tasks/main.yml b/nix/test-guest/provisioners/roles/openshell-rpm-gateway-upgrade/tasks/main.yml deleted file mode 100644 index 1d51168714..0000000000 --- a/nix/test-guest/provisioners/roles/openshell-rpm-gateway-upgrade/tasks/main.yml +++ /dev/null @@ -1,59 +0,0 @@ ---- -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -- name: Require RPM gateway provisioner dependencies - ansible.builtin.assert: - that: - - openshell_install_source | default('') == 'rpm' - - openshell_cli_bin is defined - - openshell_gateway_service is defined - - openshell_gateway_runtime | default('') == 'rootless-podman' - fail_msg: >- - openshell-rpm-gateway-upgrade requires openshell-rpm and a configured - gateway runtime. - -- name: Verify candidate RPMs for upgrade - ansible.builtin.stat: - path: "{{ item }}" - loop: - - "{{ openshell_rpm_upgrade_cli }}" - - "{{ openshell_rpm_upgrade_gateway }}" - register: openshell_rpm_upgrade_candidates - -- name: Require copied candidate RPMs - ansible.builtin.assert: - that: item.stat.exists - fail_msg: "missing required RPM upgrade candidate: {{ item.item }}" - loop: "{{ openshell_rpm_upgrade_candidates.results }}" - -- name: Install the target RPM upgrade command - ansible.builtin.copy: - dest: "{{ openshell_rpm_upgrade_command }}" - mode: "0700" - content: | - #!/usr/bin/env bash - set -Eeuo pipefail - baseline_cli="$(rpm -q --qf '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}' openshell)" - baseline_gateway="$(rpm -q --qf '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}' openshell-gateway)" - candidate_cli="$(rpm -qp --qf '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}' {{ openshell_rpm_upgrade_cli }})" - candidate_gateway="$(rpm -qp --qf '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}' {{ openshell_rpm_upgrade_gateway }})" - if [[ "$candidate_cli" == "$baseline_cli" || "$candidate_gateway" == "$baseline_gateway" ]]; then - echo "candidate RPMs must differ from the installed baseline" >&2 - exit 1 - fi - sudo dnf install -y --allowerasing --nogpgcheck {{ openshell_rpm_upgrade_cli }} {{ openshell_rpm_upgrade_gateway }} - installed_cli="$(rpm -q --qf '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}' openshell)" - installed_gateway="$(rpm -q --qf '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}' openshell-gateway)" - if [[ "$installed_cli" != "$candidate_cli" || "$installed_gateway" != "$candidate_gateway" ]]; then - echo "installed RPMs do not match the candidate RPMs" >&2 - exit 1 - fi - rpm -V openshell openshell-gateway - systemctl --user daemon-reload - systemctl --user restart {{ openshell_gateway_service }} - for _ in $(seq 1 60); do - {{ openshell_cli_bin }} status >/dev/null 2>&1 && exit 0 - sleep 1 - done - exit 1 diff --git a/nix/test-guest/provisioners/roles/openshell-rpm-latest-release/defaults/main.yml b/nix/test-guest/provisioners/roles/openshell-rpm-latest-release/defaults/main.yml deleted file mode 100644 index a41a59674b..0000000000 --- a/nix/test-guest/provisioners/roles/openshell-rpm-latest-release/defaults/main.yml +++ /dev/null @@ -1,6 +0,0 @@ ---- -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -openshell_rpm_latest_release_api_url: https://api.github.com/repos/NVIDIA/OpenShell/releases/latest -openshell_rpm_latest_release_download_dir: /var/lib/openshell-conformance/baseline diff --git a/nix/test-guest/provisioners/roles/openshell-rpm-latest-release/tasks/main.yml b/nix/test-guest/provisioners/roles/openshell-rpm-latest-release/tasks/main.yml deleted file mode 100644 index f6063bde0c..0000000000 --- a/nix/test-guest/provisioners/roles/openshell-rpm-latest-release/tasks/main.yml +++ /dev/null @@ -1,79 +0,0 @@ ---- -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -- name: Resolve the guest RPM architecture - ansible.builtin.command: - cmd: rpm --eval '%{_arch}' - register: openshell_rpm_latest_release_arch - changed_when: false - -- name: Query the latest OpenShell release - ansible.builtin.uri: - url: "{{ openshell_rpm_latest_release_api_url }}" - return_content: true - headers: - Accept: application/vnd.github+json - X-GitHub-Api-Version: 2022-11-28 - register: openshell_rpm_latest_release - changed_when: false - -- name: Select latest-release RPM assets for the guest architecture - ansible.builtin.set_fact: - openshell_rpm_latest_release_cli_assets: >- - {{ openshell_rpm_latest_release.json.assets - | selectattr('name', 'match', '^openshell-[0-9].*[.]' - ~ openshell_rpm_latest_release_arch.stdout ~ '[.]rpm$') - | list }} - openshell_rpm_latest_release_gateway_assets: >- - {{ openshell_rpm_latest_release.json.assets - | selectattr('name', 'match', '^openshell-gateway-[0-9].*[.]' - ~ openshell_rpm_latest_release_arch.stdout ~ '[.]rpm$') - | list }} - -- name: Require one latest-release RPM per OpenShell package - ansible.builtin.assert: - that: - - openshell_rpm_latest_release_cli_assets | length == 1 - - openshell_rpm_latest_release_gateway_assets | length == 1 - fail_msg: >- - expected one OpenShell CLI and gateway RPM for - {{ openshell_rpm_latest_release_arch.stdout }} in release - {{ openshell_rpm_latest_release.json.tag_name }} - -- name: Record the selected latest-release RPM assets - ansible.builtin.set_fact: - openshell_rpm_latest_release_cli_asset: "{{ openshell_rpm_latest_release_cli_assets | first }}" - openshell_rpm_latest_release_gateway_asset: "{{ openshell_rpm_latest_release_gateway_assets | first }}" - -- name: Create the latest-release RPM staging directory - ansible.builtin.file: - path: "{{ openshell_rpm_latest_release_download_dir }}" - state: directory - mode: "0755" - become: true - -- name: Download latest-release OpenShell RPMs - ansible.builtin.get_url: - url: "{{ item.browser_download_url }}" - dest: "{{ openshell_rpm_latest_release_download_dir }}/{{ item.name }}" - mode: "0644" - loop: - - "{{ openshell_rpm_latest_release_cli_asset }}" - - "{{ openshell_rpm_latest_release_gateway_asset }}" - loop_control: - label: "{{ item.name }}" - become: true - -- name: Install latest-release OpenShell RPMs - ansible.builtin.dnf: - name: - - "{{ openshell_rpm_latest_release_download_dir }}/{{ openshell_rpm_latest_release_cli_asset.name }}" - - "{{ openshell_rpm_latest_release_download_dir }}/{{ openshell_rpm_latest_release_gateway_asset.name }}" - state: present - disable_gpg_check: true - become: true - -- name: Publish latest-release RPM OpenShell installation - ansible.builtin.include_role: - name: openshell-rpm diff --git a/pyproject.toml b/pyproject.toml index 247a40b412..33ca25ddf0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,6 +16,7 @@ requires-python = ">=3.11" dependencies = [ "cloudpickle>=3.0", "grpcio>=1.60", + "googleapis-common-protos>=1.63", "httpx>=0.27", "protobuf>=4.25", ] diff --git a/python/openshell/__init__.py b/python/openshell/__init__.py index 775e9f7b16..072858ca5e 100644 --- a/python/openshell/__init__.py +++ b/python/openshell/__init__.py @@ -5,6 +5,7 @@ from __future__ import annotations +from .errors import ErrorInfo, FieldViolation, GatewayError, from_grpc_error from .sandbox import ( ClientCredentialsAuth, ExecChunk, @@ -33,8 +34,11 @@ __all__ = [ "ClientCredentialsAuth", + "ErrorInfo", "ExecChunk", "ExecResult", + "FieldViolation", + "GatewayError", "Page", "Pager", "Sandbox", @@ -49,4 +53,5 @@ "WorkspaceClient", "WorkspaceRef", "__version__", + "from_grpc_error", ] diff --git a/python/openshell/errors.py b/python/openshell/errors.py new file mode 100644 index 0000000000..f1085e1a36 --- /dev/null +++ b/python/openshell/errors.py @@ -0,0 +1,149 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Typed gateway errors that retain the original gRPC status and metadata.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import grpc +from google.protobuf.message import DecodeError +from google.rpc import error_details_pb2, status_pb2 + + +@dataclass(frozen=True) +class FieldViolation: + """A request field rejected by the gateway.""" + + field: str + description: str + + +@dataclass(frozen=True) +class ErrorInfo: + """A machine-readable error reason scoped to its producing service.""" + + reason: str + domain: str + metadata: dict[str, str] + + +class GatewayError(grpc.RpcError): + """A gRPC failure with decoded standard details. + + ``raw_error`` retains the complete original exception and metadata. + ``raw_status`` retains all decoded Any messages, including unknown types. + A retry delay is guidance only; it does not make a mutation safe to repeat. + Existing ``except grpc.RpcError`` handlers continue to match this type. + """ + + def __init__(self, error: grpc.RpcError) -> None: + super().__init__(str(error)) + self.raw_error = error + self.raw_status: status_pb2.Status | None = None + self.field_violations: tuple[FieldViolation, ...] = () + self.error_info: ErrorInfo | None = None + self.retry_delay: float | None = None + trailing = getattr(error, "trailing_metadata", lambda: None)() or () + for key, value in trailing: + if key != "grpc-status-details-bin" or not isinstance(value, bytes): + continue + try: + status = status_pb2.Status.FromString(value) + except DecodeError: + continue + # The transport status is authoritative. Inconsistent rich status + # must not provide misleading recovery guidance. + code = self.code() + if ( + code is None + or status.code != code.value[0] + or status.message != self.details() + ): + continue + self.raw_status = status + break + if self.raw_status is None: + return + violations = [] + for detail in self.raw_status.details: + try: + if detail.Is(error_details_pb2.BadRequest.DESCRIPTOR): + bad_request = error_details_pb2.BadRequest() + detail.Unpack(bad_request) + violations.extend( + FieldViolation(v.field, v.description) + for v in bad_request.field_violations + ) + elif detail.Is(error_details_pb2.ErrorInfo.DESCRIPTOR): + info = error_details_pb2.ErrorInfo() + detail.Unpack(info) + self.error_info = ErrorInfo( + info.reason, info.domain, dict(info.metadata) + ) + elif detail.Is(error_details_pb2.RetryInfo.DESCRIPTOR): + retry = error_details_pb2.RetryInfo() + detail.Unpack(retry) + delay = retry.retry_delay + if ( + retry.HasField("retry_delay") + and 0 <= delay.seconds <= 315_576_000_000 + and 0 <= delay.nanos < 1_000_000_000 + ): + self.retry_delay = delay.seconds + delay.nanos / 1_000_000_000 + except DecodeError: + continue + self.field_violations = tuple(violations) + + def code(self): + """Return the original gRPC status code.""" + return getattr(self.raw_error, "code", lambda: None)() + + def details(self): + """Return the original human-readable gRPC message.""" + return getattr(self.raw_error, "details", lambda: str(self.raw_error))() + + def __getattr__(self, name): + return getattr(self.raw_error, name) + + +def from_grpc_error(error: grpc.RpcError) -> GatewayError: + """Decode a raw RPC failure without discarding unrecognized details.""" + return error if isinstance(error, GatewayError) else GatewayError(error) + + +class _ErrorMappingStream: + def __init__(self, call): + self._call = call + self._iterator = iter(call) + + def __iter__(self): + return self + + def __next__(self): + try: + return next(self._iterator) + except grpc.RpcError as error: + raise from_grpc_error(error) from error + + def __getattr__(self, name): + return getattr(self._call, name) + + +class _ErrorMappingInterceptor( + grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor +): + def intercept_unary_unary(self, continuation, client_call_details, request): + call = continuation(client_call_details, request) + error = call.exception() + if isinstance(error, grpc.RpcError): + raise from_grpc_error(error) from error + return call + + def intercept_unary_stream(self, continuation, client_call_details, request): + return _ErrorMappingStream(continuation(client_call_details, request)) + + +def _error_mapping_channel(channel): + return grpc.intercept_channel(channel, _ErrorMappingInterceptor()) diff --git a/python/openshell/errors_test.py b/python/openshell/errors_test.py new file mode 100644 index 0000000000..a60b6fe360 --- /dev/null +++ b/python/openshell/errors_test.py @@ -0,0 +1,127 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Rich error decoding and preservation across unary and streaming calls.""" + +from concurrent import futures + +import grpc +import pytest +from google.rpc import error_details_pb2, status_pb2 + +from openshell.errors import GatewayError, _error_mapping_channel, from_grpc_error + + +def rich_status(): + status = status_pb2.Status( + code=grpc.StatusCode.UNAVAILABLE.value[0], message="try later" + ) + retry = error_details_pb2.RetryInfo() + retry.retry_delay.seconds = 1 + retry.retry_delay.nanos = 250_000_000 + for message in [ + error_details_pb2.BadRequest( + field_violations=[ + error_details_pb2.BadRequest.FieldViolation( + field="name", description="invalid name" + ), + ] + ), + error_details_pb2.ErrorInfo( + reason="GATEWAY_NOT_READY", + domain="openshell.nvidia.com", + metadata={"scope": "test"}, + ), + retry, + ]: + detail = status.details.add() + detail.Pack(message) + status.details.add( + type_url="type.googleapis.com/future.ErrorDetail", value=b"\x08\x01" + ) + return status + + +@pytest.mark.parametrize("streaming", [False, True]) +def test_maps_real_rpc_errors_without_losing_details(streaming): + status = rich_status() + + def fail(_request, context): + context.set_trailing_metadata( + ( + ("grpc-status-details-bin", status.SerializeToString()), + ("request-id", "test-correlation"), + ) + ) + context.abort(grpc.StatusCode.UNAVAILABLE, "try later") + + server = grpc.server(futures.ThreadPoolExecutor(max_workers=1)) + handler = ( + grpc.unary_stream_rpc_method_handler + if streaming + else grpc.unary_unary_rpc_method_handler + ) + server.add_generic_rpc_handlers( + (grpc.method_handlers_generic_handler("test.Errors", {"Fail": handler(fail)}),) + ) + port = server.add_insecure_port("127.0.0.1:0") + server.start() + try: + with _error_mapping_channel( + grpc.insecure_channel(f"127.0.0.1:{port}") + ) as channel: + call = channel.unary_stream if streaming else channel.unary_unary + with pytest.raises(GatewayError) as caught: + response = call("/test.Errors/Fail")(b"", timeout=5) + if streaming: + list(response) + error = caught.value + assert error.code() == grpc.StatusCode.UNAVAILABLE + assert error.details() == "try later" + assert error.field_violations[0].field == "name" + assert error.error_info is not None + assert error.error_info.reason == "GATEWAY_NOT_READY" + assert error.retry_delay == 1.25 + assert error.raw_status == status + assert ("request-id", "test-correlation") in error.trailing_metadata() + assert from_grpc_error(error) is error + finally: + server.stop(0).wait() + + +class RawError(grpc.RpcError): + def __init__(self, details): + self._details = details + + def code(self): + return grpc.StatusCode.UNAVAILABLE + + def details(self): + return "try later" + + def trailing_metadata(self): + return [("grpc-status-details-bin", self._details)] + + +def test_malformed_or_inconsistent_details_preserve_raw_error(): + for payload in [ + b"\xff", + status_pb2.Status(code=3, message="different").SerializeToString(), + ]: + raw = RawError(payload) + error = from_grpc_error(raw) + assert error.raw_error is raw + assert error.raw_status is None + assert error.retry_delay is None + assert error.trailing_metadata() == raw.trailing_metadata() + + +def test_malformed_known_detail_does_not_hide_other_details(): + status = rich_status() + status.details.add( + type_url="type.googleapis.com/google.rpc.BadRequest", value=b"\xff" + ) + error = from_grpc_error(RawError(status.SerializeToString())) + assert error.field_violations[0].field == "name" + assert error.raw_status is not None + assert len(error.raw_status.details) == 5 diff --git a/python/openshell/sandbox.py b/python/openshell/sandbox.py index 931fa1e2ab..b6fe0a7347 100644 --- a/python/openshell/sandbox.py +++ b/python/openshell/sandbox.py @@ -28,6 +28,7 @@ openshell_pb2, openshell_pb2_grpc, ) +from .errors import GatewayError, _error_mapping_channel _ClientCallDetailsBase = namedtuple( "_ClientCallDetailsBase", @@ -618,7 +619,9 @@ def __init__( self._channel, _BearerAuthInterceptor(provider), ) - self._stub = openshell_pb2_grpc.OpenShellStub(self._channel) + self._stub = openshell_pb2_grpc.OpenShellStub( + _error_mapping_channel(self._channel) + ) @classmethod def from_active_cluster( @@ -988,9 +991,10 @@ def wait_deleted( try: self.get(sandbox_name, workspace=workspace) except grpc.RpcError as exc: + call = exc.raw_error if isinstance(exc, GatewayError) else exc if ( - isinstance(exc, grpc.Call) - and exc.code() == grpc.StatusCode.NOT_FOUND + isinstance(call, grpc.Call) + and call.code() == grpc.StatusCode.NOT_FOUND ): return raise @@ -1175,7 +1179,7 @@ class SandboxTemplateClient: """gRPC client for reusable sandbox template lifecycle operations.""" def __init__(self, channel: grpc.Channel, *, timeout: float = 30.0) -> None: - self._stub = openshell_pb2_grpc.OpenShellStub(channel) + self._stub = openshell_pb2_grpc.OpenShellStub(_error_mapping_channel(channel)) self._timeout = timeout @classmethod @@ -1355,7 +1359,7 @@ class WorkspaceClient: """gRPC client for workspace lifecycle operations.""" def __init__(self, channel: grpc.Channel, *, timeout: float = 30.0) -> None: - self._stub = openshell_pb2_grpc.OpenShellStub(channel) + self._stub = openshell_pb2_grpc.OpenShellStub(_error_mapping_channel(channel)) self._timeout = timeout @classmethod @@ -1559,9 +1563,10 @@ def __exit__(self, *args: object) -> None: workspace=self._workspace, ) except grpc.RpcError as exc: + call = exc.raw_error if isinstance(exc, GatewayError) else exc if ( - not isinstance(exc, grpc.Call) - or exc.code() != grpc.StatusCode.NOT_FOUND + not isinstance(call, grpc.Call) + or call.code() != grpc.StatusCode.NOT_FOUND ): raise finally: diff --git a/python/openshell/sandbox_cleanup_test.py b/python/openshell/sandbox_cleanup_test.py new file mode 100644 index 0000000000..903fa1131a --- /dev/null +++ b/python/openshell/sandbox_cleanup_test.py @@ -0,0 +1,151 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Cleanup status handling through the curated client's real gRPC interceptor.""" + +from concurrent import futures +from contextlib import nullcontext +from types import SimpleNamespace + +import grpc +import pytest + +from openshell._proto import openshell_pb2 +from openshell.errors import GatewayError +from openshell.sandbox import Sandbox, SandboxClient + + +@pytest.fixture +def cleanup_client(): + state = SimpleNamespace( + exists=False, + code=grpc.StatusCode.NOT_FOUND, + calls=[], + closed=[], + ) + + def fail(context): + context.set_trailing_metadata((("request-id", "cleanup-regression"),)) + context.abort(state.code, "cleanup status") + + def get(request, context): + state.calls.append("GetSandbox") + assert request.name == "cleanup-test" + assert request.workspace_scope.workspace == "default" + if not state.exists: + fail(context) + response = openshell_pb2.SandboxResponse() + response.sandbox.metadata.id = "sandbox-1" + response.sandbox.metadata.name = request.name + response.sandbox.metadata.workspace = "default" + response.sandbox.status.phase = openshell_pb2.SANDBOX_PHASE_READY + return response + + def delete(request, context): + state.calls.append("DeleteSandbox") + assert request.name == "cleanup-test" + assert request.workspace_scope.workspace == "default" + fail(context) + + server = grpc.server(futures.ThreadPoolExecutor(max_workers=1)) + server.add_generic_rpc_handlers( + ( + grpc.method_handlers_generic_handler( + "openshell.v1.OpenShell", + { + "GetSandbox": grpc.unary_unary_rpc_method_handler( + get, + request_deserializer=openshell_pb2.GetSandboxRequest.FromString, + response_serializer=openshell_pb2.SandboxResponse.SerializeToString, + ), + "DeleteSandbox": grpc.unary_unary_rpc_method_handler( + delete, + request_deserializer=openshell_pb2.DeleteSandboxRequest.FromString, + response_serializer=openshell_pb2.DeleteSandboxResponse.SerializeToString, + ), + }, + ), + ) + ) + port = server.add_insecure_port("127.0.0.1:0") + server.start() + client = SandboxClient( + f"127.0.0.1:{port}", + timeout=5, + _bearer_close=lambda: state.closed.append(True), + ) + try: + yield client, state + finally: + client.close() + server.stop(0).wait() + + +def assert_original_call(error, code): + assert isinstance(error, GatewayError) + assert isinstance(error.raw_error, grpc.Call) + assert error.code() == error.raw_error.code() == code + assert error.details() == "cleanup status" + assert ("request-id", "cleanup-regression") in error.trailing_metadata() + + +@pytest.mark.parametrize( + "code", + [ + grpc.StatusCode.NOT_FOUND, + grpc.StatusCode.PERMISSION_DENIED, + grpc.StatusCode.UNAVAILABLE, + ], +) +def test_wait_deleted_handles_intercepted_status(cleanup_client, code): + client, state = cleanup_client + state.code = code + # Prove this is the curated intercepted stub, not a fake raw exception. + with pytest.raises(GatewayError) as observed: + client.get("cleanup-test", workspace="default") + assert_original_call(observed.value, code) + + expected = ( + nullcontext() + if code == grpc.StatusCode.NOT_FOUND + else pytest.raises(GatewayError) + ) + with expected as caught: + client.wait_deleted("cleanup-test", workspace="default", timeout_seconds=5) + if caught is not None: + assert_original_call(caught.value, code) + assert state.calls == ["GetSandbox", "GetSandbox"] + + +@pytest.mark.parametrize( + "code", + [ + grpc.StatusCode.NOT_FOUND, + grpc.StatusCode.PERMISSION_DENIED, + grpc.StatusCode.UNAVAILABLE, + ], +) +def test_context_cleanup_handles_intercepted_status(cleanup_client, monkeypatch, code): + client, state = cleanup_client + state.code = code + state.exists = True + monkeypatch.setattr( + SandboxClient, + "from_active_cluster", + classmethod(lambda _cls, **_kwargs: client), + ) + + managed = Sandbox(workspace="default", sandbox="cleanup-test") + expected = ( + nullcontext() + if code == grpc.StatusCode.NOT_FOUND + else pytest.raises(GatewayError) + ) + with expected as caught, managed: + state.exists = False + if caught is not None: + assert_original_call(caught.value, code) + assert state.calls == ["GetSandbox", "GetSandbox", "DeleteSandbox"] + assert state.closed == [True] + assert managed._client is None + assert managed._session is None diff --git a/scripts/agents/README.md b/scripts/agents/README.md index 32dac5f2d4..6c8735f569 100644 --- a/scripts/agents/README.md +++ b/scripts/agents/README.md @@ -34,8 +34,7 @@ Each agent has an `agent.yaml` manifest. The launcher currently reads these sections: - `id`, `display_name`, `description`: human and runtime identity. -- `sandbox`: default sandbox name prefix, gateway, source image or Dockerfile, - and background log directory. +- `sandbox`: default sandbox name prefix, gateway, and source image or Dockerfile. - `harness`: default harness and per-harness settings such as model and reasoning effort. - `runtime`: in-sandbox run mode (`once` or `watch`), watch poll interval, and @@ -86,14 +85,17 @@ Manifest paths support these prefixes: to the sandbox. 15. Configure and rotate refresh-backed provider credentials when declared by the manifest. -16. Run `openshell sandbox create` from the resulting image reference. -17. Inside the sandbox, run `/etc/openshell/agent-payload/runtime/entrypoint.sh`. -18. The runtime entrypoint starts +16. Run `openshell sandbox create` from the resulting image reference, with the + runtime entrypoint persisted as the detached canonical main process. +17. Mark the sandbox ephemeral unless `--keep` was supplied, allowing the + gateway to delete it after the canonical process exits. +18. Inside the sandbox, run `/etc/openshell/agent-payload/runtime/entrypoint.sh`. +19. The runtime entrypoint starts `/etc/openshell/agent-payload/runtime/supervisor.sh`. -19. The supervisor invokes +20. The supervisor invokes `/etc/openshell/agent-payload/runtime/harnesses//exec.sh` as a bounded child execution. -20. Harness adapters prepare harness-local auth/config and execute the agent +21. Harness adapters prepare harness-local auth/config and execute the agent prompt headlessly. The payload directory is baked into the image under `/etc/openshell`, which the @@ -113,7 +115,7 @@ bounded harness cycles. The harness must not sleep or poll indefinitely. Instead it performs one reconciliation cycle, then prints a final-line sentinel: ```text -OPENSHELL_AGENT_RESULT {"status":"waiting","next_poll_seconds":900,"reason":"checks_pending"} +OPENSHELL_AGENT_RESULT {"status":"waiting","next_poll_seconds":900,"reason":"checks_pending","notes":"Required checks are still running. The agent will inspect them next cycle."} ``` Supported statuses are `complete`, `waiting`, `blocked`, `transient_failure`, and @@ -129,6 +131,17 @@ retried indefinitely with bounded backoff; only `complete` and to upstream model errors while leaving durable state ownership to the agent domain. +The supervisor writes an atomic current snapshot to +`/sandbox/.openshell-agent/status.json` and keeps the latest 100 supervisor +transitions in `/sandbox/.openshell-agent/history.jsonl`. Each record identifies +the cycle, supervisor state, harness exit code, and structured agent result. +Agents should include a concise `notes` field in every result to capture their +human-readable current diagnosis, notable issues or questions, and next useful +action. The supervisor caps notes at 2,048 characters and records a diagnostic +placeholder when an agent omits them. Override the state directory, history +limit, or notes limit with `OPENSHELL_AGENT_STATE_DIR`, +`OPENSHELL_AGENT_STATE_HISTORY_LIMIT`, or `OPENSHELL_AGENT_MAX_NOTES_LENGTH`. + The shared runtime does not prescribe the durable state store. Gator uses GitHub labels, comments, reviews, and checks. Other agents can use a repository branch, issue tracker, object store, database, or another domain-specific store as long diff --git a/scripts/agents/gator/agent.yaml b/scripts/agents/gator/agent.yaml index dc225669c9..f23810bc6a 100644 --- a/scripts/agents/gator/agent.yaml +++ b/scripts/agents/gator/agent.yaml @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 id: gator -payload_version: 8 +payload_version: 9 display_name: Gator Gate Agent description: Validate and monitor OpenShell GitHub issues and pull requests through the gator state machine. @@ -10,7 +10,6 @@ sandbox: name_prefix: gtr from: agent://. gateway: docker-dev - background_log_dir: logs harness: default: codex diff --git a/scripts/agents/gator/bin/review_feedback_ledger_test.sh b/scripts/agents/gator/bin/review_feedback_ledger_test.sh index 7c5708cc8a..8f0d989f7d 100755 --- a/scripts/agents/gator/bin/review_feedback_ledger_test.sh +++ b/scripts/agents/gator/bin/review_feedback_ledger_test.sh @@ -349,7 +349,7 @@ rg -q 'COPY bin/validate-review-findings /usr/local/bin/validate-review-findings "$GATOR_DIR/Dockerfile" ruby -ryaml -e ' manifest = YAML.load_file(ARGV.fetch(0)) - abort unless manifest.fetch("payload_version") == 7 + abort unless manifest.fetch("payload_version") == 9 resource = manifest.fetch("resources").find { |entry| entry.fetch("id") == "gator-review-findings-schema" } diff --git a/scripts/agents/gator/prompts/gator.md b/scripts/agents/gator/prompts/gator.md index 07055a29cc..fee69f38d4 100644 --- a/scripts/agents/gator/prompts/gator.md +++ b/scripts/agents/gator/prompts/gator.md @@ -20,13 +20,14 @@ Important sandbox constraints: `scripts/agents/gator/agent.yaml` on the default branch through the GitHub contents API. If the published integer is greater than `{{PAYLOAD_VERSION}}`, do not write to GitHub or run the reviewer. Finish with - `OPENSHELL_AGENT_RESULT {"status":"terminal_failure","reason":"stale_gator_payload"}` so the operator relaunches the immutable watcher. + `OPENSHELL_AGENT_RESULT {"status":"terminal_failure","reason":"stale_gator_payload","notes":"This sandbox is using an outdated Gator payload. Relaunch it before monitoring continues."}` so the operator relaunches the immutable watcher. - Keep discovery scoped to the operator request. For requests such as "my open non-draft PRs", closed/merged cleanup may include only matching PRs with active `gator:*` labels; query each gator label separately and de-dupe results. Do not scan or mutate all gator-labeled PRs unless the operator explicitly requested repo-wide scope. - In `watch` runtime mode, do not run passive sleep or polling loops inside Codex. Perform one bounded reconciliation cycle, then print one `OPENSHELL_AGENT_RESULT` line as the final line of output and stop. The in-sandbox supervisor will sleep and relaunch the harness for the next cycle. -- In `watch` runtime mode, when the next action is to keep waiting, use this exact final-line format with a reason and poll interval: `OPENSHELL_AGENT_RESULT {"status":"waiting","next_poll_seconds":{{POLL_INTERVAL_SECONDS}},"reason":"checks_pending"}`. Use `blocked` when waiting on a human/process blocker, `complete` when the issue or PR reached a terminal state, `terminal_failure` for unrecoverable errors, and `transient_failure` only when the supervisor should retry soon. -- If required GitHub REST reads or writes fail with `EOF`, `Empty reply from server`, or sandbox `NET:FAIL` after policy allowed the endpoint, stop the cycle with `OPENSHELL_AGENT_RESULT {"status":"transient_failure","next_poll_seconds":120,"reason":"github_transport_eof"}` rather than marking the issue or PR blocked. -- If the `principal-engineer-reviewer` sub-agent fails before producing usable review output, stop the cycle with `OPENSHELL_AGENT_RESULT {"status":"transient_failure","next_poll_seconds":120,"reason":"reviewer_subagent_failed"}`. Do not post a marked gator comment or PR review, do not apply `gator:blocked`, and do not consume the one-disposition-per-head-SHA slot for sub-agent auth, token-refresh, transport, command, empty-output, malformed-output, or sub-agent-only policy failures. -- In `once` runtime mode, run one bounded cycle unless the operator explicitly asks you to watch inline. Still print `OPENSHELL_AGENT_RESULT {"status":"complete","reason":"one_shot_complete"}` when finished. +- Every result sentinel must include `notes` containing one or two concise, plain-language sentences that a human can read aloud. Summarize the current diagnosis, name any notable issue or unanswered question, and state the next useful action or owner. Do not repeat mechanical metadata, dump raw logs, or include secrets; mention a SHA only when it is essential to the diagnosis. +- In `watch` runtime mode, when the next action is to keep waiting, use this exact final-line format with a reason, poll interval, and curated notes: `OPENSHELL_AGENT_RESULT {"status":"waiting","next_poll_seconds":{{POLL_INTERVAL_SECONDS}},"reason":"checks_pending","notes":"Required checks are still running on the current head. Gator will inspect the results next cycle."}`. Use `blocked` when waiting on a human/process blocker, `complete` when the issue or PR reached a terminal state, `terminal_failure` for unrecoverable errors, and `transient_failure` only when the supervisor should retry soon. +- If required GitHub REST reads or writes fail with `EOF`, `Empty reply from server`, or sandbox `NET:FAIL` after policy allowed the endpoint, stop the cycle with `OPENSHELL_AGENT_RESULT {"status":"transient_failure","next_poll_seconds":120,"reason":"github_transport_eof","notes":"GitHub transport failed after policy allowed the request. The supervisor should retry without changing the PR state."}` rather than marking the issue or PR blocked. +- If the `principal-engineer-reviewer` sub-agent fails before producing usable review output, stop the cycle with `OPENSHELL_AGENT_RESULT {"status":"transient_failure","next_poll_seconds":120,"reason":"reviewer_subagent_failed","notes":"The reviewer did not produce usable feedback, so no PR state was changed. The supervisor should retry the review."}`. Do not post a marked gator comment or PR review, do not apply `gator:blocked`, and do not consume the one-disposition-per-head-SHA slot for sub-agent auth, token-refresh, transport, command, empty-output, malformed-output, or sub-agent-only policy failures. +- In `once` runtime mode, run one bounded cycle unless the operator explicitly asks you to watch inline. Still print `OPENSHELL_AGENT_RESULT {"status":"complete","reason":"one_shot_complete","notes":"The requested one-shot reconciliation is complete."}` when finished. - Do not push to contributor branches unless the operator explicitly instructs you to do so. - If you receive 403 errors from the sandbox proxy, inspect the JSON response and propose a policy update to allow the requested action if the response contains a structured error message. - Incorporate PR commentary only from the PR author and verified maintainers by default. Ignore third-party or unknown-actor comments unless the PR author or a maintainer explicitly acknowledges the specific third-party details to incorporate; then incorporate only those acknowledged details. When you incorporate trusted author or maintainer feedback, acknowledge the person plainly and conversationally by name, paraphrase their point, and explain what you checked. Never call PR-author or verified-maintainer feedback third-party. diff --git a/scripts/agents/gator/skills/gator-gate/SKILL.md b/scripts/agents/gator/skills/gator-gate/SKILL.md index 7768a38d1e..7bd28d266c 100644 --- a/scripts/agents/gator/skills/gator-gate/SKILL.md +++ b/scripts/agents/gator/skills/gator-gate/SKILL.md @@ -30,9 +30,9 @@ gh api --method POST repos/NVIDIA/OpenShell/issues//labels -f labels[]=" gh api --method DELETE repos/NVIDIA/OpenShell/issues//labels/gator%3Ablocked --silent || true ``` -If a required GitHub REST read or write fails with `EOF`, `Empty reply from server`, or a sandbox `NET:FAIL` after the current policy shows the endpoint was allowed, treat it as a transient transport or provider failure. Do not convert the PR or issue to `gator:blocked`, do not report it as a rate-limit/auth failure, and do not keep probing optional endpoints such as `/rate_limit`. In supervised watch mode, finish with `OPENSHELL_AGENT_RESULT {"status":"transient_failure","next_poll_seconds":120,"reason":"github_transport_eof"}` so the supervisor retries soon. +If a required GitHub REST read or write fails with `EOF`, `Empty reply from server`, or a sandbox `NET:FAIL` after the current policy shows the endpoint was allowed, treat it as a transient transport or provider failure. Do not convert the PR or issue to `gator:blocked`, do not report it as a rate-limit/auth failure, and do not keep probing optional endpoints such as `/rate_limit`. In supervised watch mode, finish with `OPENSHELL_AGENT_RESULT {"status":"transient_failure","next_poll_seconds":120,"reason":"github_transport_eof","notes":"GitHub transport failed after policy allowed the request. The supervisor should retry without changing the PR state."}` so the supervisor retries soon. -If the `principal-engineer-reviewer` sub-agent fails before producing usable review output, treat that as transient gator infrastructure failure, not as a PR blocker. This includes Codex auth or token-refresh failures, model transport failures, sub-agent command failures, empty reviewer output, malformed reviewer output, and sandbox policy denials that only affect the sub-agent harness. Do not post a marked gator comment or PR review, do not apply `gator:blocked`, and do not consume the one-disposition-per-head-SHA slot. In supervised watch mode, finish with `OPENSHELL_AGENT_RESULT {"status":"transient_failure","next_poll_seconds":120,"reason":"reviewer_subagent_failed"}` so the supervisor retries after the operator or provider issue clears. +If the `principal-engineer-reviewer` sub-agent fails before producing usable review output, treat that as transient gator infrastructure failure, not as a PR blocker. This includes Codex auth or token-refresh failures, model transport failures, sub-agent command failures, empty reviewer output, malformed reviewer output, and sandbox policy denials that only affect the sub-agent harness. Do not post a marked gator comment or PR review, do not apply `gator:blocked`, and do not consume the one-disposition-per-head-SHA slot. In supervised watch mode, finish with `OPENSHELL_AGENT_RESULT {"status":"transient_failure","next_poll_seconds":120,"reason":"reviewer_subagent_failed","notes":"The reviewer did not produce usable feedback, so no PR state was changed. The supervisor should retry the review."}` so the supervisor retries after the operator or provider issue clears. ## Authority Rules @@ -181,7 +181,7 @@ Thread resolution is required housekeeping for an addressed inline finding, not a new review disposition, and does not consume the one-disposition-per-head SHA slot. If GitHub does not confirm every requested resolution, do not advance the Gator state or post the follow-up disposition. Return -`OPENSHELL_AGENT_RESULT {"status":"transient_failure","next_poll_seconds":120,"reason":"review_thread_resolution_failed"}` +`OPENSHELL_AGENT_RESULT {"status":"transient_failure","next_poll_seconds":120,"reason":"review_thread_resolution_failed","notes":"GitHub did not confirm every requested Gator thread resolution. Retry reconciliation before advancing the PR state."}` and retry the reconciliation later. ## Labels @@ -382,7 +382,7 @@ For closed-unmerged PRs: For closed or merged PRs that have no active `gator:*` label and already have a monitoring-complete gator comment, take no GitHub write action. -In supervised watch mode, return `OPENSHELL_AGENT_RESULT {"status":"complete","reason":"pr_merged"}` or `OPENSHELL_AGENT_RESULT {"status":"complete","reason":"pr_closed"}` only when all targeted PRs in the cycle are closed, merged, or otherwise complete. If any targeted PR still needs future reconciliation, return the appropriate `waiting` or `blocked` sentinel for the active work. +In supervised watch mode, return `OPENSHELL_AGENT_RESULT {"status":"complete","reason":"pr_merged","notes":"The monitored PR was merged, so Gator monitoring is complete."}` or `OPENSHELL_AGENT_RESULT {"status":"complete","reason":"pr_closed","notes":"The monitored PR was closed without merging, so Gator monitoring is complete."}` only when all targeted PRs in the cycle are closed, merged, or otherwise complete. If any targeted PR still needs future reconciliation, return the appropriate `waiting` or `blocked` sentinel for the active work. ## Watch Loop Rules @@ -391,10 +391,10 @@ Every gator state is a watch state. On each invocation, determine the current st When `OPENSHELL_AGENT_RUN_MODE=watch`, the OpenShell agent supervisor owns the sleep/relaunch loop. In that mode, perform exactly one reconciliation cycle, do not run `sleep 900` or an unbounded polling loop inside the harness, and finish with a single final-line result sentinel: ```text -OPENSHELL_AGENT_RESULT {"status":"waiting","next_poll_seconds":900,"reason":"checks_pending"} +OPENSHELL_AGENT_RESULT {"status":"waiting","next_poll_seconds":900,"reason":"checks_pending","notes":"Required checks are still running on the current head. Gator will inspect the results next cycle."} ``` -Use `status=waiting` for routine CI/PR activity waits, `status=blocked` for human or process blockers, `status=complete` for closed or merged PRs and other complete items, `status=terminal_failure` for unrecoverable errors, and `status=transient_failure` only when the supervisor should retry soon. The supervisor will sleep and invoke the harness again with fresh GitHub state. +Use `status=waiting` for routine CI/PR activity waits, `status=blocked` for human or process blockers, `status=complete` for closed or merged PRs and other complete items, `status=terminal_failure` for unrecoverable errors, and `status=transient_failure` only when the supervisor should retry soon. Every sentinel must include `notes`: one or two concise, plain-language sentences that summarize the current diagnosis, identify any notable issue or unanswered question, and state the next useful action or owner. Make the notes understandable when read aloud. Do not repeat mechanical metadata, dump raw logs, or include secrets. The supervisor will persist the result, sleep, and invoke the harness again with fresh GitHub state. When not running under supervised watch mode, do not stop after a one-shot check when a PR is in an active waiting state unless the operator explicitly asks for a one-shot status check. Enter a polling loop and state the interval and stop conditions before waiting. diff --git a/scripts/agents/run.sh b/scripts/agents/run.sh index 5bf05a7117..d3792b6c13 100755 --- a/scripts/agents/run.sh +++ b/scripts/agents/run.sh @@ -23,7 +23,6 @@ RUN_MODE_OVERRIDE="${OPENSHELL_AGENT_RUN_MODE:-}" POLL_INTERVAL_OVERRIDE="${OPENSHELL_AGENT_POLL_INTERVAL_SECONDS:-}" MAX_TRANSIENT_FAILURES_OVERRIDE="${OPENSHELL_AGENT_MAX_TRANSIENT_FAILURES:-}" RESET_REFRESH="${OPENSHELL_AGENT_RESET_REFRESH:-0}" -BACKGROUND=0 KEEP_SANDBOX=0 usage() { @@ -44,7 +43,6 @@ Options: --watch Keep the sandbox alive and re-run bounded cycles --poll-interval SECONDS Sleep duration between watch cycles --reset-refresh Replace gateway-owned refresh material from host auth before rotating - --background Run sandbox create in the background and write a log --keep Keep the sandbox after the harness exits -h, --help Show this help EOF @@ -127,10 +125,6 @@ while [[ $# -gt 0 ]]; do RESET_REFRESH=1 shift ;; - --background) - BACKGROUND=1 - shift - ;; --keep) KEEP_SANDBOX=1 shift @@ -207,7 +201,6 @@ emit "HARNESS_REASONING", harness_config.fetch("reasoning", "") emit "SANDBOX_NAME_PREFIX", manifest.dig("sandbox", "name_prefix") || manifest.fetch("id") emit "SANDBOX_FROM_DEFAULT", manifest.dig("sandbox", "from") || "agent://." emit "GATEWAY_DEFAULT", manifest.dig("sandbox", "gateway") || "docker-dev" -emit "BACKGROUND_LOG_DIR", manifest.dig("sandbox", "background_log_dir") || "logs" emit "PROMPT_TEMPLATE", manifest.fetch("prompt_template") emit_array "PROFILE_PATHS", manifest.fetch("profile_paths", []) @@ -551,7 +544,6 @@ done PAYLOAD_PARENT="$(mktemp -d "${TMPDIR:-/tmp}/openshell-agent.XXXXXX")" PAYLOAD_DIR="$PAYLOAD_PARENT/payload" -WORKSPACE_UPLOAD_DIR="$PAYLOAD_PARENT/workspace" PAYLOAD_IMAGE_DIR="/etc/openshell/agent-payload" cleanup_payload() { rm -rf "$PAYLOAD_PARENT" @@ -560,7 +552,7 @@ trap 'cleanup_config; cleanup_payload' EXIT log "Preparing $AGENT_DISPLAY_NAME with harness '$HARNESS' in '$RUN_MODE' mode on gateway '$GATEWAY'." -mkdir -p "$PAYLOAD_DIR" "$WORKSPACE_UPLOAD_DIR" +mkdir -p "$PAYLOAD_DIR" cp -R "$SCRIPT_DIR/runtime" "$PAYLOAD_DIR/runtime" chmod +x "$PAYLOAD_DIR/runtime"/*.sh chmod +x "$PAYLOAD_DIR/runtime/harnesses/$HARNESS"/*.sh @@ -822,17 +814,15 @@ SANDBOX_CREATE_CMD=( --name "$SANDBOX_NAME" --from "$SANDBOX_FROM" "${PROVIDER_ARGS[@]}" - --upload "$WORKSPACE_UPLOAD_DIR:/sandbox" - --no-git-ignore --no-auto-providers --no-tty --detach ) -SANDBOX_EXEC_CMD=( - "$OPENSHELL_BIN" --gateway "$GATEWAY" sandbox exec - --name "$SANDBOX_NAME" - --no-tty +if [[ "$KEEP_SANDBOX" != "1" ]]; then + SANDBOX_CREATE_CMD+=(--no-keep) +fi +SANDBOX_CREATE_CMD+=( -- env "${HARNESS_ENV_ARGS[@]}" @@ -840,33 +830,8 @@ SANDBOX_EXEC_CMD=( ) run_agent_sandbox() { - local exec_status=0 - local cleanup_status=0 - "${SANDBOX_CREATE_CMD[@]}" - "${SANDBOX_EXEC_CMD[@]}" || exec_status=$? - - if [[ "$KEEP_SANDBOX" != "1" ]]; then - openshell_cmd sandbox delete "$SANDBOX_NAME" >/dev/null || cleanup_status=$? - fi - - if [[ "$exec_status" -ne 0 ]]; then - return "$exec_status" - fi - return "$cleanup_status" } log "Launching $AGENT_DISPLAY_NAME sandbox '$SANDBOX_NAME' on gateway '$GATEWAY'." -if [[ "$BACKGROUND" == "1" ]]; then - LOG_DIR="$(resolve_manifest_path "$BACKGROUND_LOG_DIR")" - mkdir -p "$LOG_DIR" - LOG_FILE="$LOG_DIR/${SANDBOX_NAME}.log" - trap - EXIT - ( - trap 'cleanup_config; cleanup_payload' EXIT - run_agent_sandbox - ) >"$LOG_FILE" 2>&1 & - echo "Started in background. Log: $LOG_FILE" -else - run_agent_sandbox -fi +run_agent_sandbox diff --git a/scripts/agents/runtime/supervisor.sh b/scripts/agents/runtime/supervisor.sh index ff9e2afaa6..a2efb5c524 100755 --- a/scripts/agents/runtime/supervisor.sh +++ b/scripts/agents/runtime/supervisor.sh @@ -20,6 +20,9 @@ RUN_MODE="${OPENSHELL_AGENT_RUN_MODE:-once}" POLL_INTERVAL_SECONDS="${OPENSHELL_AGENT_POLL_INTERVAL_SECONDS:-900}" MAX_TRANSIENT_FAILURES="${OPENSHELL_AGENT_MAX_TRANSIENT_FAILURES:-5}" HEARTBEAT_SECONDS="${OPENSHELL_AGENT_HEARTBEAT_SECONDS:-60}" +STATE_DIR="${OPENSHELL_AGENT_STATE_DIR:-/sandbox/.openshell-agent}" +STATE_HISTORY_LIMIT="${OPENSHELL_AGENT_STATE_HISTORY_LIMIT:-100}" +MAX_NOTES_LENGTH="${OPENSHELL_AGENT_MAX_NOTES_LENGTH:-2048}" MAX_SLEEP_SECONDS=86400 [[ -f "$PROMPT_FILE" ]] || { echo "missing agent prompt: $PROMPT_FILE" >&2; exit 1; } @@ -32,7 +35,11 @@ esac [[ "$POLL_INTERVAL_SECONDS" =~ ^[0-9]+$ ]] || { echo "OPENSHELL_AGENT_POLL_INTERVAL_SECONDS must be an integer" >&2; exit 2; } [[ "$MAX_TRANSIENT_FAILURES" =~ ^[0-9]+$ ]] || { echo "OPENSHELL_AGENT_MAX_TRANSIENT_FAILURES must be an integer" >&2; exit 2; } [[ "$HEARTBEAT_SECONDS" =~ ^[0-9]+$ ]] || { echo "OPENSHELL_AGENT_HEARTBEAT_SECONDS must be an integer" >&2; exit 2; } +[[ "$STATE_HISTORY_LIMIT" =~ ^[0-9]+$ ]] || { echo "OPENSHELL_AGENT_STATE_HISTORY_LIMIT must be an integer" >&2; exit 2; } +[[ "$MAX_NOTES_LENGTH" =~ ^[0-9]+$ ]] || { echo "OPENSHELL_AGENT_MAX_NOTES_LENGTH must be an integer" >&2; exit 2; } [[ "$POLL_INTERVAL_SECONDS" -gt 0 ]] || { echo "OPENSHELL_AGENT_POLL_INTERVAL_SECONDS must be greater than zero" >&2; exit 2; } +[[ "$STATE_HISTORY_LIMIT" -gt 0 ]] || { echo "OPENSHELL_AGENT_STATE_HISTORY_LIMIT must be greater than zero" >&2; exit 2; } +[[ "$MAX_NOTES_LENGTH" -gt 0 ]] || { echo "OPENSHELL_AGENT_MAX_NOTES_LENGTH must be greater than zero" >&2; exit 2; } json_string_field() { local json="$1" @@ -70,6 +77,110 @@ sys.exit(0 if isinstance(value, dict) else 1) return 1 } +normalize_result_json() { + local json="$1" + + if command -v jq >/dev/null 2>&1; then + printf '%s' "$json" | jq -c --argjson max "$MAX_NOTES_LENGTH" ' + .notes = if (.notes | type) == "string" then .notes[:$max] + else "No cycle notes were provided by the agent." end + ' + return + fi + printf '%s' "$json" | python3 -c ' +import json +import sys + +maximum = int(sys.argv[1]) +value = json.load(sys.stdin) +notes = value.get("notes") +value["notes"] = notes[:maximum] if isinstance(notes, str) else "No cycle notes were provided by the agent." +print(json.dumps(value, separators=(",", ":"))) +' "$MAX_NOTES_LENGTH" +} + +state_record_json() { + local supervisor_state="$1" + local harness_status="$2" + local result_json="$3" + local recorded_at + recorded_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" + + if command -v jq >/dev/null 2>&1; then + jq -cn \ + --arg recorded_at "$recorded_at" \ + --arg agent_id "${OPENSHELL_AGENT_ID:-unknown}" \ + --arg harness "$OPENSHELL_AGENT_HARNESS" \ + --arg run_mode "$RUN_MODE" \ + --argjson cycle "$cycle" \ + --arg supervisor_state "$supervisor_state" \ + --arg harness_status "$harness_status" \ + --argjson result "$result_json" \ + '{schema_version:1, recorded_at:$recorded_at, agent_id:$agent_id, + harness:$harness, run_mode:$run_mode, cycle:$cycle, + supervisor_state:$supervisor_state, + harness_exit_code:(if $harness_status == "" then null else ($harness_status | tonumber) end), + result:$result}' + return + fi + python3 -c ' +import json +import sys + +recorded_at, agent_id, harness, run_mode, cycle, state, harness_status, result = sys.argv[1:] +print(json.dumps({ + "schema_version": 1, + "recorded_at": recorded_at, + "agent_id": agent_id, + "harness": harness, + "run_mode": run_mode, + "cycle": int(cycle), + "supervisor_state": state, + "harness_exit_code": int(harness_status) if harness_status else None, + "result": json.loads(result), +}, separators=(",", ":"))) +' "$recorded_at" "${OPENSHELL_AGENT_ID:-unknown}" "$OPENSHELL_AGENT_HARNESS" \ + "$RUN_MODE" "$cycle" "$supervisor_state" "$harness_status" "$result_json" +} + +persist_state() { + local supervisor_state="$1" + local harness_status="${2:-}" + local result_json="${3:-}" + local record snapshot_tmp history_tmp + + [[ -n "$result_json" ]] || result_json='{}' + + mkdir -p "$STATE_DIR" + record="$(state_record_json "$supervisor_state" "$harness_status" "$result_json")" + + snapshot_tmp="$(mktemp "$STATE_DIR/.status.XXXXXX")" + printf '%s\n' "$record" > "$snapshot_tmp" + mv "$snapshot_tmp" "$STATE_DIR/status.json" + + printf '%s\n' "$record" >> "$STATE_DIR/history.jsonl" + history_tmp="$(mktemp "$STATE_DIR/.history.XXXXXX")" + tail -n "$STATE_HISTORY_LIMIT" "$STATE_DIR/history.jsonl" > "$history_tmp" + mv "$history_tmp" "$STATE_DIR/history.jsonl" +} + +diagnostic_result_json() { + local status="$1" + local reason="$2" + local notes="$3" + + if command -v jq >/dev/null 2>&1; then + jq -cn --arg status "$status" --arg reason "$reason" --arg notes "$notes" \ + '{status:$status, reason:$reason, notes:$notes}' + return + fi + python3 -c ' +import json +import sys +print(json.dumps({"status": sys.argv[1], "reason": sys.argv[2], "notes": sys.argv[3]}, separators=(",", ":"))) +' "$status" "$reason" "$notes" +} + classify_transient_failure() { local output_file="$1" grep -Eiq 'stream disconnected before completion|failed to connect to websocket|Reconnecting\.\.\.|Broken pipe|Connection to sandbox closed by remote host|peer closed connection without sending TLS close_notify' "$output_file" @@ -192,6 +303,7 @@ cap_transient_backoff while true; do cycle=$((cycle + 1)) echo "openshell-agent: starting $RUN_MODE cycle $cycle with harness $OPENSHELL_AGENT_HARNESS" >&2 + persist_state "running" output_file="$(mktemp /tmp/openshell-agent-cycle.XXXXXX)" if run_cycle "$output_file"; then @@ -204,6 +316,12 @@ while true; do result_json="${result_line#OPENSHELL_AGENT_RESULT }" if [[ -z "$result_line" ]]; then + retry_reason="missing OPENSHELL_AGENT_RESULT after harness exit $harness_status" + if classify_transient_failure "$output_file"; then + retry_reason="$retry_reason; upstream transport failure detected" + fi + diagnostic_json="$(diagnostic_result_json transient_failure missing_agent_result "$retry_reason")" + persist_state "$([[ "$RUN_MODE" == "once" ]] && printf terminal || printf sleeping)" "$harness_status" "$diagnostic_json" if [[ "$RUN_MODE" == "once" ]]; then rm -f "$output_file" if [[ "$harness_status" -ne 0 ]]; then @@ -211,16 +329,14 @@ while true; do fi exit 1 fi - retry_reason="missing OPENSHELL_AGENT_RESULT after harness exit $harness_status" - if classify_transient_failure "$output_file"; then - retry_reason="$retry_reason; upstream transport failure detected" - fi rm -f "$output_file" retry_watch_cycle "$retry_reason" continue fi if ! valid_result_json "$result_json"; then + diagnostic_json="$(diagnostic_result_json transient_failure malformed_agent_result "The harness returned malformed result JSON; the supervisor will retry.")" + persist_state "$([[ "$RUN_MODE" == "once" ]] && printf terminal || printf sleeping)" "$harness_status" "$diagnostic_json" rm -f "$output_file" if [[ "$RUN_MODE" == "once" ]]; then echo "openshell-agent: malformed OPENSHELL_AGENT_RESULT JSON" >&2 @@ -230,6 +346,8 @@ while true; do continue fi + result_json="$(normalize_result_json "$result_json")" + status="$(json_string_field "$result_json" status)" reason="$(json_string_field "$result_json" reason)" next_poll_seconds="$(json_number_field "$result_json" next_poll_seconds)" @@ -240,10 +358,12 @@ while true; do case "$status" in complete) + persist_state "terminal" "$harness_status" "$result_json" echo "openshell-agent: complete ($reason)" >&2 exit 0 ;; waiting|blocked) + persist_state "$([[ "$RUN_MODE" == "once" ]] && printf terminal || printf sleeping)" "$harness_status" "$result_json" if [[ "$RUN_MODE" == "once" ]]; then echo "openshell-agent: $status ($reason)" >&2 exit 0 @@ -254,6 +374,7 @@ while true; do sleep_with_heartbeat "$next_poll_seconds" "$reason" ;; transient_failure) + persist_state "$([[ "$RUN_MODE" == "once" ]] && printf terminal || printf sleeping)" "$harness_status" "$result_json" if [[ "$RUN_MODE" == "once" ]]; then echo "openshell-agent: transient failure ($reason)" >&2 exit 1 @@ -261,10 +382,12 @@ while true; do retry_watch_cycle "$reason" "$next_poll_seconds" false ;; terminal_failure) + persist_state "terminal" "$harness_status" "$result_json" echo "openshell-agent: terminal failure ($reason)" >&2 exit 1 ;; *) + persist_state "$([[ "$RUN_MODE" == "once" ]] && printf terminal || printf sleeping)" "$harness_status" "$result_json" if [[ "$RUN_MODE" == "once" ]]; then echo "openshell-agent: invalid OPENSHELL_AGENT_RESULT status: ${status:-}" >&2 exit 1 diff --git a/scripts/agents/runtime/supervisor_test.sh b/scripts/agents/runtime/supervisor_test.sh index 7e57155ae6..5b30ea3f7c 100755 --- a/scripts/agents/runtime/supervisor_test.sh +++ b/scripts/agents/runtime/supervisor_test.sh @@ -49,6 +49,8 @@ run_supervisor() { OPENSHELL_AGENT_POLL_INTERVAL_SECONDS="${OPENSHELL_AGENT_POLL_INTERVAL_SECONDS:-1}" \ OPENSHELL_AGENT_MAX_TRANSIENT_FAILURES=2 \ OPENSHELL_AGENT_HEARTBEAT_SECONDS="${OPENSHELL_AGENT_HEARTBEAT_SECONDS:-0}" \ + OPENSHELL_AGENT_STATE_DIR="${OPENSHELL_AGENT_TEST_STATE_DIR:-$payload_dir/state}" \ + OPENSHELL_AGENT_STATE_HISTORY_LIMIT="${OPENSHELL_AGENT_STATE_HISTORY_LIMIT:-100}" \ OPENSHELL_AGENT_TEST_STATE="${OPENSHELL_AGENT_TEST_STATE:-}" \ bash "$payload_dir/runtime/supervisor.sh" > "$output_file" 2>&1 local status=$? @@ -216,6 +218,44 @@ printf "%s\n" "OPENSHELL_AGENT_RESULT {\"status\":\"complete\",\"reason\":\"done printf 'ok - watch prints active cycle heartbeat\n' } +test_persists_agent_notes_and_terminal_state() { + local tmp + tmp="$(mktemp -d)" + make_payload "$tmp/payload" 'printf "%s\n" "OPENSHELL_AGENT_RESULT {\"status\":\"complete\",\"reason\":\"done\",\"notes\":\"The current head is ready. No further action is needed.\"}"' + + run_supervisor "$tmp/payload" once "$tmp/output" + assert_contains "$tmp/payload/state/status.json" '"supervisor_state":"terminal"' + assert_contains "$tmp/payload/state/status.json" '"notes":"The current head is ready. No further action is needed."' + assert_contains "$tmp/payload/state/status.json" '"harness_exit_code":0' + [[ "$(wc -l < "$tmp/payload/state/history.jsonl")" -eq 2 ]] || fail "expected running and terminal history records" + printf 'ok - persists agent notes and terminal state\n' +} + +test_bounds_state_history() { + local tmp + tmp="$(mktemp -d)" + make_payload "$tmp/payload" ' +state_file="${OPENSHELL_AGENT_TEST_STATE:?}" +count=0 +if [[ -f "$state_file" ]]; then count="$(cat "$state_file")"; fi +count=$((count + 1)) +printf "%s\n" "$count" > "$state_file" +if [[ "$count" -lt 2 ]]; then + printf "%s\n" "OPENSHELL_AGENT_RESULT {\"status\":\"waiting\",\"reason\":\"checks_pending\",\"next_poll_seconds\":1,\"notes\":\"Checks are still running. Gator will inspect them next cycle.\"}" +else + printf "%s\n" "OPENSHELL_AGENT_RESULT {\"status\":\"complete\",\"reason\":\"done\",\"notes\":\"The work is complete.\"}" +fi +' + + OPENSHELL_AGENT_TEST_STATE="$tmp/count" \ + OPENSHELL_AGENT_STATE_HISTORY_LIMIT=2 \ + run_supervisor "$tmp/payload" watch "$tmp/output" + [[ "$(wc -l < "$tmp/payload/state/history.jsonl")" -eq 2 ]] || fail "expected bounded history" + assert_contains "$tmp/payload/state/history.jsonl" '"cycle":2' + assert_contains "$tmp/payload/state/status.json" '"notes":"The work is complete."' + printf 'ok - bounds state history\n' +} + test_once_requires_sentinel test_watch_retries_missing_sentinel_until_complete test_watch_retries_invalid_status_until_complete @@ -224,3 +264,5 @@ test_watch_retries_failed_alias_until_complete test_watch_terminal_failure_exits test_watch_transient_failure_honors_next_poll_seconds test_watch_prints_active_cycle_heartbeat +test_persists_agent_notes_and_terminal_state +test_bounds_state_history diff --git a/scripts/keycloak-dev.sh b/scripts/keycloak-dev.sh index a856e8b366..3b7006998b 100755 --- a/scripts/keycloak-dev.sh +++ b/scripts/keycloak-dev.sh @@ -104,7 +104,7 @@ cmd_start() { local elapsed=0 while [ $elapsed -lt $HEALTH_TIMEOUT ]; do if curl -sf \ - "http://localhost:${KEYCLOAK_PORT}/realms/openshell/.well-known/openid-configuration" \ + "http://127.0.0.1:${KEYCLOAK_PORT}/realms/openshell/.well-known/openid-configuration" \ >/dev/null 2>&1; then echo "Keycloak is ready." print_info @@ -146,7 +146,7 @@ cmd_status() { } print_info() { - local issuer="http://localhost:${KEYCLOAK_PORT}/realms/openshell" + local issuer="http://127.0.0.1:${KEYCLOAK_PORT}/realms/openshell" echo "" echo " Issuer URL: $issuer" echo " Discovery: ${issuer}/.well-known/openid-configuration" diff --git a/sdk/go/docs/src/error-handling.md b/sdk/go/docs/src/error-handling.md index f46b796513..e93faaf55d 100644 --- a/sdk/go/docs/src/error-handling.md +++ b/sdk/go/docs/src/error-handling.md @@ -10,7 +10,7 @@ When an operation returns a classified status error, inspect it directly or use var se *v1.StatusError if errors.As(err, &se) { fmt.Printf("code: %s, message: %s\n", se.Code, se.Message) - // se.Details contains optional structured metadata + // se.ErrorInfo and se.FieldViolations contain optional structured details. } ``` @@ -18,7 +18,14 @@ if errors.As(err, &se) { |-----------|-------------------|--------------------------------------| | `Code` | `ErrorCode` | Machine-readable error classification | | `Message` | `string` | Human-readable error description | -| `Details` | `map[string]string` | Optional structured metadata | +| `GRPCCode` | `int32` | Original gRPC code before SDK classification | +| `FieldViolations` | `[]FieldViolation` | Rejected request fields and descriptions | +| `ErrorInfo` | `*ErrorInfo` | Server reason, domain, and metadata | +| `RetryDelay` | `*time.Duration` | Suggested minimum delay for an otherwise safe retry | +| `Cause` | `error` | Original gRPC error, including unknown details | + +Use `status.FromError(err)` to inspect the complete gRPC status through the SDK's +error wrapper. A delay does not prove that a timed-out mutation was not applied. ## Predicate Functions diff --git a/sdk/go/openshell/v1/errors.go b/sdk/go/openshell/v1/errors.go index fd6a5b2f2b..ced7769bbe 100644 --- a/sdk/go/openshell/v1/errors.go +++ b/sdk/go/openshell/v1/errors.go @@ -28,6 +28,12 @@ const ( // StatusError is the typed error returned by all SDK operations. type StatusError = types.StatusError +// FieldViolation identifies an invalid request field. +type FieldViolation = types.FieldViolation + +// ErrorInfo describes a server failure using a stable reason within a domain. +type ErrorInfo = types.ErrorInfo + // IsNotFound returns true if the error indicates a resource was not found. func IsNotFound(err error) bool { return types.IsNotFound(err) } diff --git a/sdk/go/openshell/v1/internal/converter/errors.go b/sdk/go/openshell/v1/internal/converter/errors.go index 7bf16f1359..f6457e27b3 100644 --- a/sdk/go/openshell/v1/internal/converter/errors.go +++ b/sdk/go/openshell/v1/internal/converter/errors.go @@ -5,7 +5,11 @@ package converter import ( + "maps" + "time" + "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types" + "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -48,9 +52,33 @@ func FromGRPCError(err error) error { code = types.ErrorInternal } - return &types.StatusError{ - Code: code, - Message: st.Message(), - Cause: err, + result := &types.StatusError{ + Code: code, + Message: st.Message(), + Cause: err, + GRPCCode: int32(st.Code()), + } + for _, detail := range st.Details() { + switch detail := detail.(type) { + case *errdetails.BadRequest: + for _, violation := range detail.GetFieldViolations() { + result.FieldViolations = append(result.FieldViolations, types.FieldViolation{ + Field: violation.GetField(), Description: violation.GetDescription(), + }) + } + case *errdetails.ErrorInfo: + result.ErrorInfo = &types.ErrorInfo{ + Reason: detail.GetReason(), Domain: detail.GetDomain(), + Metadata: maps.Clone(detail.GetMetadata()), + } + case *errdetails.RetryInfo: + delay := detail.GetRetryDelay() + if delay != nil && delay.CheckValid() == nil && delay.GetSeconds() >= 0 && delay.GetNanos() >= 0 { + // AsDuration saturates values that exceed time.Duration's range. + value := time.Duration(delay.AsDuration()) + result.RetryDelay = &value + } + } } + return result } diff --git a/sdk/go/openshell/v1/internal/converter/errors_test.go b/sdk/go/openshell/v1/internal/converter/errors_test.go index c7238eaae5..6a948bfd33 100644 --- a/sdk/go/openshell/v1/internal/converter/errors_test.go +++ b/sdk/go/openshell/v1/internal/converter/errors_test.go @@ -5,14 +5,55 @@ package converter import ( "testing" + "time" v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/durationpb" + "google.golang.org/protobuf/types/known/wrapperspb" ) +func TestFromGRPCError_PreservesStructuredAndUnknownDetails(t *testing.T) { + st, err := status.New(codes.ResourceExhausted, "try later").WithDetails( + &errdetails.BadRequest{FieldViolations: []*errdetails.BadRequest_FieldViolation{ + {Field: "name", Description: "too long"}, + }}, + &errdetails.ErrorInfo{Reason: "RATE_LIMITED", Domain: "openshell.nvidia.com", Metadata: map[string]string{"key": "value"}}, + &errdetails.RetryInfo{RetryDelay: durationpb.New(time.Second)}, + wrapperspb.String("unrecognized detail"), + ) + require.NoError(t, err) + raw := st.Err() + converted := FromGRPCError(raw) + var typed *v1.StatusError + require.ErrorAs(t, converted, &typed) + assert.Equal(t, int32(codes.ResourceExhausted), typed.GRPCCode) + assert.Equal(t, []v1.FieldViolation{{Field: "name", Description: "too long"}}, typed.FieldViolations) + require.NotNil(t, typed.ErrorInfo) + assert.Equal(t, "RATE_LIMITED", typed.ErrorInfo.Reason) + require.NotNil(t, typed.RetryDelay) + assert.Equal(t, time.Second, *typed.RetryDelay) + assert.Same(t, raw, typed.Cause) + // errors.Unwrap/status.FromError still exposes every original Any. + assert.Equal(t, st.Proto().GetDetails(), status.Convert(converted).Proto().GetDetails()) + typed.ErrorInfo.Metadata["key"] = "changed" + assert.Equal(t, "value", st.Details()[1].(*errdetails.ErrorInfo).GetMetadata()["key"]) +} + +func TestFromGRPCError_IgnoresInvalidRetryDelay(t *testing.T) { + st, err := status.New(codes.Unavailable, "try later").WithDetails( + &errdetails.RetryInfo{RetryDelay: durationpb.New(-time.Second)}, + ) + require.NoError(t, err) + var typed *v1.StatusError + require.ErrorAs(t, FromGRPCError(st.Err()), &typed) + assert.Nil(t, typed.RetryDelay) +} + func TestFromGRPCError_NotFound(t *testing.T) { grpcErr := status.Error(codes.NotFound, "sandbox not found") err := FromGRPCError(grpcErr) diff --git a/sdk/go/openshell/v1/types/errors.go b/sdk/go/openshell/v1/types/errors.go index f8981e1e33..b98fda612a 100644 --- a/sdk/go/openshell/v1/types/errors.go +++ b/sdk/go/openshell/v1/types/errors.go @@ -6,6 +6,7 @@ package types import ( "errors" "fmt" + "time" ) // ErrorCode classifies SDK errors by their gRPC origin. @@ -61,6 +62,27 @@ type StatusError struct { Code ErrorCode Message string Cause error + // GRPCCode retains the exact transport code before SDK classification. + GRPCCode int32 + // FieldViolations identifies invalid request fields without parsing Message. + FieldViolations []FieldViolation + // ErrorInfo is the server's machine-readable reason, domain, and metadata. + ErrorInfo *ErrorInfo + // RetryDelay is a suggested minimum delay, not proof a mutation is safe to repeat. + RetryDelay *time.Duration +} + +// FieldViolation identifies an invalid request field. +type FieldViolation struct { + Field string + Description string +} + +// ErrorInfo describes a server failure using a stable reason within a domain. +type ErrorInfo struct { + Reason string + Domain string + Metadata map[string]string } func (e *StatusError) Error() string { diff --git a/sdk/typescript/buf.gen.yaml b/sdk/typescript/buf.gen.yaml index e4caeb64da..a0fa6a31e4 100644 --- a/sdk/typescript/buf.gen.yaml +++ b/sdk/typescript/buf.gen.yaml @@ -17,6 +17,10 @@ inputs: - ../../proto/sandbox.proto - ../../proto/datamodel.proto - ../../proto/options.proto + # Standard rich gRPC error messages, pinned to an immutable Google APIs commit. + - module: buf.build/googleapis/googleapis:c17df5b2beca46928cc87d5656bd5343 + paths: + - google/rpc/error_details.proto plugins: - local: ./node_modules/.bin/protoc-gen-es out: src/gen diff --git a/sdk/typescript/src/errors.test.ts b/sdk/typescript/src/errors.test.ts index 2e525d280b..cad7cb9763 100644 --- a/sdk/typescript/src/errors.test.ts +++ b/sdk/typescript/src/errors.test.ts @@ -7,8 +7,40 @@ import { Code, ConnectError } from '@connectrpc/connect'; import { describe, expect, it } from 'vitest'; import { errorCode, fromConnect, SdkError, type SdkErrorCode } from './errors.js'; +import { BadRequestSchema, ErrorInfoSchema, RetryInfoSchema } from './gen/google/rpc/error_details_pb.js'; describe('fromConnect', () => { + it('decodes standard details and preserves unknown and malformed wire details', () => { + const raw = new ConnectError('try later', Code.Unavailable, { 'request-id': 'correlation' }, [ + { desc: BadRequestSchema, value: { fieldViolations: [{ field: 'name', description: 'invalid' }] } }, + { + desc: ErrorInfoSchema, + value: { reason: 'GATEWAY_NOT_READY', domain: 'openshell.nvidia.com', metadata: { scope: 'test' } }, + }, + { desc: RetryInfoSchema, value: { retryDelay: { seconds: 1n, nanos: 250000000 } } }, + ]); + raw.details.push({ type: 'google.rpc.BadRequest', value: new Uint8Array([255]) }); + raw.details.push({ type: 'future.ErrorDetail', value: new Uint8Array([8, 1]) }); + const error = fromConnect(raw); + expect(error.fieldViolations).toEqual([{ field: 'name', description: 'invalid' }]); + expect(error.errorInfo).toEqual({ + reason: 'GATEWAY_NOT_READY', + domain: 'openshell.nvidia.com', + metadata: { scope: 'test' }, + }); + expect(error.retryDelayMs).toBe(1250); + expect(error.cause).toBe(raw); + expect(raw.details).toHaveLength(5); + expect(raw.metadata.get('request-id')).toBe('correlation'); + }); + + it('does not fabricate retry guidance from the status code', () => { + expect(fromConnect(new ConnectError('temporary', Code.Unavailable)).retryDelayMs).toBeUndefined(); + const raw = new ConnectError('invalid delay', Code.Unavailable, undefined, [ + { desc: RetryInfoSchema, value: { retryDelay: { seconds: -1n } } }, + ]); + expect(fromConnect(raw).retryDelayMs).toBeUndefined(); + }); const cases: Array<[Code, SdkErrorCode]> = [ [Code.NotFound, 'not_found'], [Code.AlreadyExists, 'already_exists'], diff --git a/sdk/typescript/src/errors.ts b/sdk/typescript/src/errors.ts index 7eddcb4aa2..a37bf15a89 100644 --- a/sdk/typescript/src/errors.ts +++ b/sdk/typescript/src/errors.ts @@ -7,6 +7,20 @@ // an identical contract. import { Code, ConnectError } from '@connectrpc/connect'; +import { BadRequestSchema, ErrorInfoSchema, RetryInfoSchema } from './gen/google/rpc/error_details_pb.js'; + +/** A field rejected by the gateway. */ +export interface FieldViolation { + field: string; + description: string; +} + +/** A stable error reason scoped to its producing service. */ +export interface ErrorInfo { + reason: string; + domain: string; + metadata: Record; +} export type SdkErrorCode = | 'invalid_config' @@ -32,12 +46,32 @@ export class SdkError extends Error { readonly code: SdkErrorCode; /** The Connect status code when this error originated from an RPC. */ readonly connectCode?: Code; + /** Decoded field violations; the complete wire details remain in cause. */ + readonly fieldViolations: FieldViolation[] = []; + /** Server-provided reason, domain, and metadata, when present. */ + readonly errorInfo?: ErrorInfo; + /** Suggested minimum delay in milliseconds; does not establish mutation retry safety. */ + readonly retryDelayMs?: number; constructor(code: SdkErrorCode, message: string, options?: SdkErrorOptions) { // Format `[code] message` so errorCode() can recover the code from any Error. super(`[${code}] ${message}`, options?.cause !== undefined ? { cause: options.cause } : undefined); this.name = 'SdkError'; this.code = code; if (options?.connectCode !== undefined) this.connectCode = options.connectCode; + if (options?.cause instanceof ConnectError) { + const error = options.cause; + this.fieldViolations = error + .findDetails(BadRequestSchema) + .flatMap((detail) => detail.fieldViolations.map(({ field, description }) => ({ field, description }))); + const info = error.findDetails(ErrorInfoSchema)[0]; + if (info) { + this.errorInfo = { reason: info.reason, domain: info.domain, metadata: { ...info.metadata } }; + } + const delay = error.findDetails(RetryInfoSchema)[0]?.retryDelay; + if (delay && delay.seconds >= 0n && delay.seconds <= 315576000000n && delay.nanos >= 0 && delay.nanos < 1e9) { + this.retryDelayMs = Number(delay.seconds) * 1000 + delay.nanos / 1e6; + } + } } } @@ -72,6 +106,7 @@ export function fromConnect(err: unknown): SdkError { // Extract the `[code]` prefix from any error message. export function errorCode(err: unknown): string | null { + if (err instanceof SdkError) return err.code; const msg = err instanceof Error ? err.message : String(err); const m = /^\[([a-z_]+)\]/.exec(msg); return m ? m[1] : null; diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index 4935f49b1d..90d9c07705 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -47,7 +47,7 @@ export type { WorkspaceListScope, } from './client.js'; export { errorCode, OpenShellClient, Pager, SandboxClient, SandboxTemplateClient } from './client.js'; -export type { SdkErrorCode } from './errors.js'; -export { SdkError } from './errors.js'; +export type { ErrorInfo, FieldViolation, SdkErrorCode } from './errors.js'; +export { fromConnect, SdkError } from './errors.js'; export type { ClientCredentialsOptions, OidcTokenProvider } from './oidc.js'; export { clientCredentials } from './oidc.js'; diff --git a/sdk/typescript/src/raw.ts b/sdk/typescript/src/raw.ts index b0be2cd9bf..1571e8e23e 100644 --- a/sdk/typescript/src/raw.ts +++ b/sdk/typescript/src/raw.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 export * from './gen/datamodel_pb.js'; +export * from './gen/google/rpc/error_details_pb.js'; // Advanced surface: the full generated protobuf types (messages, enums, and the // OpenShell service descriptor) for callers using the raw escape hatch on // OpenShellClient / SandboxClient (`.raw` and `.transport`). These are the diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index aa8bd9e4ee..7d95c0af18 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -488,6 +488,8 @@ Alpine packages updated at image build time. A dependency or base-image fix only reaches deployed containers after rebuilding, publishing, and redeploying the images. Compare findings against the SBOM for that digest, not just its mutable `latest` or `dev` tag. +For gateway base refreshes, verify the installed libc package revision in each +platform's SBOM; the binary's glibc compatibility floor is not its runtime version. For plaintext local evaluation, confirm the chart has: @@ -772,6 +774,7 @@ configuration — check that the gateway spawned the driver binary you expect | Vault credential driver returns HTTP 403 / `Vault Kubernetes auth denied the configured role` on provider create | Vault's `auth/kubernetes` method or the gateway login role is not provisioned, or the role is not bound to the gateway service account and namespace | In Vault: `bao auth enable kubernetes` and `bao write auth/kubernetes/config kubernetes_host=... kubernetes_ca_cert=@...`; ensure the login role's `bound_service_account_names`/`bound_service_account_namespaces` match the gateway SA and namespace and its policy grants the credential paths | | CLI TLS error | Local mTLS bundle does not match server cert/CA | Check `~/.config/openshell/gateways//mtls/` | | Edge or OIDC gateway returns `Unauthenticated` | Stored login expired, audience/scopes mismatch, or gateway auth configuration changed | `openshell gateway info`, `openshell gateway login `, gateway auth logs | +| Gateway exits during OIDC initialization | Issuer is not HTTPS, discovery redirected, metadata used a non-JSON media type or exceeded its size limit, or `jwks_uri` uses an untrusted origin | Use an HTTPS issuer; mount a private CA with `server.oidc.caConfigMapName`; keep JWKS on the issuer origin or explicitly add its HTTPS origin to `server.oidc.jwksAllowedOrigins`. Numeric-loopback HTTP is development-only and also requires `server.oidc.dangerouslyAllowInsecureHttp=true` | | Gateway fails before serving health after enabling an interceptor | Interceptor endpoint unavailable or manifest/binding validation failed | Gateway and interceptor logs; interceptor socket; `binding_policy`, phases, and failure policy | | Authenticated interceptor or middleware rejects gateway calls | Private CA or hostname mismatch, expected audience or issuer mismatch, stale/unknown `kid`, or malformed extension token | `tls_ca_cert_path`, registration `audience`, service verifier config and logs; fetch well-known metadata only through the already-trusted gateway TLS endpoint | | Provider profiles disappear after enabling an interceptor catalog | `provider_profile_sources` selected only an authoritative interceptor or returned invalid/duplicate IDs | Inspect source list and interceptor `Describe`/catalog logs; include `builtin` and `user` when intended | diff --git a/skills/openshell-cli/SKILL.md b/skills/openshell-cli/SKILL.md index d986a45cc1..0d30aacb50 100644 --- a/skills/openshell-cli/SKILL.md +++ b/skills/openshell-cli/SKILL.md @@ -84,7 +84,9 @@ An explicit trailing command is foreground even when stdin or stdout is not a terminal. The CLI streams its stdout and stderr and returns its exact exit status. Exit code 0 leaves a retained sandbox in `Completed`; nonzero leaves it in `Error` with `MainProcessFailed`. Use `--no-keep` to delete either result -after output drains, or `--detach` for a long-running service. +after output drains, or `--detach` for a long-running service. Combine +`--detach --no-keep` when the gateway should run the service without a host +attachment and delete its sandbox after the service exits. When supplying `--name`, use a portable DNS-1123 label: at most 63 lowercase alphanumeric or `-` characters, beginning and ending with an alphanumeric character. The Kubernetes driver rejects uppercase letters, underscores, dots, and other names that cannot become Kubernetes resource labels. @@ -263,7 +265,9 @@ Key flags: `--detach` adds no attachment grace period. When the canonical process exits, its terminal phase is reported immediately. A foreground create declares one expected main-process SSH attachment; cleanup finalizes after that connection -closes naturally. +closes naturally. With `--detach --no-keep`, the gateway owns the detached +process lifecycle and deletes the ephemeral sandbox after terminal reporting +finishes. Do not combine `--upload` with a trailing main command. Uploads currently finish after the canonical process starts; create a scratch sandbox and use diff --git a/tasks/keycloak.toml b/tasks/keycloak.toml index 4d35e0dd03..b79b9941e7 100644 --- a/tasks/keycloak.toml +++ b/tasks/keycloak.toml @@ -16,9 +16,12 @@ description = "Check if the local Keycloak instance is running" run = "scripts/keycloak-dev.sh status" ["keycloak:k8s:setup"] -description = "Install Keycloak in the local k3s cluster and import the openshell realm (one-time setup)" +description = "Install TLS-enabled Keycloak in the local k3s cluster and import the openshell realm" run = "tasks/scripts/keycloak-k8s-setup.sh" ["keycloak:k8s:teardown"] description = "Remove Keycloak from the local k3s cluster" -run = "kubectl delete namespace keycloak --ignore-not-found" +run = ''' +kubectl delete namespace keycloak --ignore-not-found +kubectl -n "${OPENSHELL_NAMESPACE:-openshell}" delete configmap openshell-keycloak-ca --ignore-not-found +''' diff --git a/tasks/scripts/keycloak-k8s-setup.sh b/tasks/scripts/keycloak-k8s-setup.sh index 8082197091..633de7bf1a 100755 --- a/tasks/scripts/keycloak-k8s-setup.sh +++ b/tasks/scripts/keycloak-k8s-setup.sh @@ -2,13 +2,12 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # -# One-time Keycloak setup for the local k3s cluster. +# TLS-enabled Keycloak setup for the local k3s cluster. # Uses the same quay.io/keycloak/keycloak image and realm JSON as the local # Docker dev setup (scripts/keycloak-dev.sh), deploying via kubectl manifests. # -# Idempotent: safe to re-run. The Deployment and ConfigMap are applied with -# kubectl apply, and Keycloak's --import-realm flag skips the realm if it -# already exists. +# Safe to re-run. Each run rotates the development CA and serving certificate; +# Keycloak's --import-realm flag skips the realm if it already exists. # # Usage: # mise run keycloak:k8s:setup @@ -30,6 +29,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" NAMESPACE="keycloak" +GATEWAY_NAMESPACE="${OPENSHELL_NAMESPACE:-openshell}" KEYCLOAK_IMAGE="${KEYCLOAK_IMAGE:-quay.io/keycloak/keycloak:24.0}" ADMIN_USER="${KEYCLOAK_ADMIN_USER:-admin}" ADMIN_PASSWORD="${KEYCLOAK_ADMIN_PASSWORD:-admin}" @@ -43,6 +43,9 @@ HEALTH_TIMEOUT="${KEYCLOAK_HEALTH_TIMEOUT:-120}" # this URL inside the cluster. See values-keycloak.yaml. SVC_HOSTNAME="keycloak.${NAMESPACE}.svc.cluster.local" +TLS_DIR="$(mktemp -d)" +trap 'rm -rf "${TLS_DIR}"' EXIT + if [[ ! -f "${REALM_FILE}" ]]; then echo "error: realm file not found: ${REALM_FILE}" >&2 exit 1 @@ -60,6 +63,49 @@ kubectl -n "${NAMESPACE}" create configmap openshell-realm \ --from-file=realm.json="${REALM_FILE}" \ --dry-run=client -o yaml | kubectl apply -f - +echo "Generating a development TLS certificate for '${SVC_HOSTNAME}'..." +openssl req -x509 -newkey rsa:2048 -nodes \ + -keyout "${TLS_DIR}/ca.key" \ + -out "${TLS_DIR}/ca.crt" \ + -days 30 \ + -subj "/CN=OpenShell development Keycloak CA" \ + -addext "basicConstraints=critical,CA:TRUE" \ + -addext "keyUsage=critical,keyCertSign,cRLSign" \ + >/dev/null 2>&1 +openssl req -new -newkey rsa:2048 -nodes \ + -keyout "${TLS_DIR}/tls.key" \ + -out "${TLS_DIR}/tls.csr" \ + -subj "/CN=${SVC_HOSTNAME}" \ + >/dev/null 2>&1 +printf '%s\n' \ + "subjectAltName=DNS:${SVC_HOSTNAME}" \ + "basicConstraints=critical,CA:FALSE" \ + "keyUsage=critical,digitalSignature,keyEncipherment" \ + "extendedKeyUsage=serverAuth" \ + >"${TLS_DIR}/server.ext" +openssl x509 -req \ + -in "${TLS_DIR}/tls.csr" \ + -CA "${TLS_DIR}/ca.crt" \ + -CAkey "${TLS_DIR}/ca.key" \ + -CAcreateserial \ + -out "${TLS_DIR}/tls.crt" \ + -days 30 \ + -extfile "${TLS_DIR}/server.ext" \ + >/dev/null 2>&1 + +kubectl -n "${NAMESPACE}" create secret tls keycloak-tls \ + --cert="${TLS_DIR}/tls.crt" \ + --key="${TLS_DIR}/tls.key" \ + --dry-run=client -o yaml | kubectl apply -f - + +# The Helm chart mounts OIDC trust bundles from its own namespace. Publish the +# development trust anchor there as well; rerunning this task rotates both the +# serving certificate and the trusted copy. +kubectl create namespace "${GATEWAY_NAMESPACE}" --dry-run=client -o yaml | kubectl apply -f - +kubectl -n "${GATEWAY_NAMESPACE}" create configmap openshell-keycloak-ca \ + --from-file=ca.crt="${TLS_DIR}/ca.crt" \ + --dry-run=client -o yaml | kubectl apply -f - + # --------------------------------------------------------------------------- # Deployment + Service # --------------------------------------------------------------------------- @@ -94,14 +140,24 @@ spec: # used for token acquisition (e.g. a localhost port-forward). - name: KC_HOSTNAME value: "${SVC_HOSTNAME}" + # Keycloak listens on 8443 in the container, but clients reach it + # through the Service's standard HTTPS port. Keep discovery and + # token issuers aligned with the explicit Service URL. + - name: KC_HOSTNAME_PORT + value: "443" - name: KC_HOSTNAME_STRICT value: "false" - name: KC_HOSTNAME_STRICT_HTTPS - value: "false" + value: "true" - name: KC_HTTP_ENABLED value: "true" + - name: KC_HTTPS_CERTIFICATE_FILE + value: "/etc/keycloak-tls/tls.crt" + - name: KC_HTTPS_CERTIFICATE_KEY_FILE + value: "/etc/keycloak-tls/tls.key" ports: - containerPort: 8080 + - containerPort: 8443 readinessProbe: httpGet: path: /realms/master @@ -118,10 +174,16 @@ spec: volumeMounts: - name: realm mountPath: /opt/keycloak/data/import + - name: tls + mountPath: /etc/keycloak-tls + readOnly: true volumes: - name: realm configMap: name: openshell-realm + - name: tls + secret: + secretName: keycloak-tls --- apiVersion: v1 kind: Service @@ -134,8 +196,17 @@ spec: ports: - port: 80 targetPort: 8080 + name: http + - port: 443 + targetPort: 8443 + name: https EOF +# Reload the freshly generated serving certificate on repeat runs. The +# deployment spec itself is otherwise unchanged, so updating the Secret alone +# would not restart Keycloak. +kubectl -n "${NAMESPACE}" rollout restart deployment/keycloak + # --------------------------------------------------------------------------- # Wait for readiness # --------------------------------------------------------------------------- @@ -147,7 +218,7 @@ kubectl rollout status deployment/keycloak -n "${NAMESPACE}" --timeout="${HEALTH # Summary # --------------------------------------------------------------------------- -ISSUER="http://${SVC_HOSTNAME}/realms/openshell" +ISSUER="https://${SVC_HOSTNAME}:443/realms/openshell" echo "" echo "Keycloak is ready." diff --git a/uv.lock b/uv.lock index b12d0c0fcd..063ef739e6 100644 --- a/uv.lock +++ b/uv.lock @@ -143,6 +143,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ab/84/02fc1827e8cdded4aa65baef11296a9bbe595c474f0d6d758af082d849fd/execnet-2.1.2-py3-none-any.whl", hash = "sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec", size = 40708, upload-time = "2025-11-12T09:56:36.333Z" }, ] +[[package]] +name = "googleapis-common-protos" +version = "1.75.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "protobuf" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8a/c5/4353a188e2c335aee33269e8b654af228278cca8e5f0b4b5f11e5d0e9adb/googleapis_common_protos-1.75.3.tar.gz", hash = "sha256:57c435ac2c68b108999b6db075d9053e4d7a936ba57b4a3d45667b1346f1738a", size = 153905, upload-time = "2026-09-03T22:31:21.869Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1a/7a/7d79170c6ce6f12e109df2b3879d6b934010cf4f99aea8de8b7e5408c174/googleapis_common_protos-1.75.3-py3-none-any.whl", hash = "sha256:a018d2bf098ca9fb6faa08d5bb780e2a2c2f73c566f069761331386c9596d3f2", size = 306984, upload-time = "2026-09-03T22:30:45.133Z" }, +] + [[package]] name = "grpcio" version = "1.78.0" @@ -307,6 +319,7 @@ name = "openshell" source = { editable = "." } dependencies = [ { name = "cloudpickle" }, + { name = "googleapis-common-protos" }, { name = "grpcio" }, { name = "httpx" }, { name = "protobuf" }, @@ -329,6 +342,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "cloudpickle", specifier = ">=3.0" }, + { name = "googleapis-common-protos", specifier = ">=1.63" }, { name = "grpcio", specifier = ">=1.60" }, { name = "httpx", specifier = ">=0.27" }, { name = "protobuf", specifier = ">=4.25" },