diff --git a/.agents/skills/debug-openshell-cluster/SKILL.md b/.agents/skills/debug-openshell-cluster/SKILL.md index 0de85fb0a4..286f014ff9 100644 --- a/.agents/skills/debug-openshell-cluster/SKILL.md +++ b/.agents/skills/debug-openshell-cluster/SKILL.md @@ -176,6 +176,18 @@ Common findings: - Sandbox image missing or pull denied: verify image reference and registry credentials. - Sandbox fails before readiness with an identity-resolution error: inspect the image's OCI `USER` and matching `/etc/passwd` and `/etc/group` entries, or explicitly set both process identity fields in policy. Root and missing identities are rejected. - Supervisor cannot call back: check callback endpoint and gateway logs. +- Gateway exits before becoming healthy with a callback-listener discovery + error: inspect `podman info --debug`, the configured Podman network, and the + host's IPv4 default route. Rootless pasta uses the private source address + selected by that route; rootful Podman uses the bridge gateway address. +- Callback discovery reports that the requested address equals the primary + listener: configure a distinct primary address. For Podman Machine, keep the + IPv4 loopback callback separate by using an IPv6-loopback primary such as + `[::1]:17670`. +- Rootless slirp4netns, another named helper, or missing helper metadata + requires an explicitly remote `grpc_endpoint`. An explicit `host_gateway_ip` + cannot bypass slirp4netns host-loopback isolation. Do not work around + discovery failures by broadening the primary gateway listener to `0.0.0.0`. ### Step 6: Check Kubernetes Helm Gateways @@ -392,6 +404,8 @@ openshell logs |---|---|---| | `openshell status` fails | Gateway endpoint unreachable or auth mismatch | `openshell gateway info`, gateway logs | | Gateway starts but sandbox create fails | Compute driver cannot reach runtime | Docker/Podman/Kubernetes/VM driver logs | +| Gateway exits while resolving compute-driver listener requirements | Callback alias topology is unsupported, the Podman network cannot be inspected, or the selected address is not private/authorized | Gateway startup error, `podman info --debug`, Podman network inspection, host IPv4 default route | +| Admin, health, reflection, or HTTP request is denied on a Docker/Podman callback address | Negotiated callback listeners intentionally expose only sandbox-callable gRPC methods | Retry through the gateway's primary endpoint; inspect the listener-purpose startup log if the address was unexpected | | Docker or Podman sandbox never registers | Wrong callback endpoint or supervisor startup failure | Gateway logs and sandbox container logs | | Docker GPU e2e fails before GPU sandbox comparison | NVIDIA CDI specs are missing or Docker has not discovered them | `docker info --format '{{json .DiscoveredDevices}}'`, `/etc/cdi`, `/var/run/cdi`, `nvidia-cdi-refresh.service` | | Kubernetes gateway pod pending | PVC unbound, taint, selector, or insufficient resources | `kubectl -n openshell describe pod ` | diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml index d671149999..ebe89d1ca8 100644 --- a/.github/workflows/e2e-test.yml +++ b/.github/workflows/e2e-test.yml @@ -131,20 +131,17 @@ jobs: # Run directly on the Ubuntu host so the test observes the host's AppArmor # and unprivileged-user-namespace policy. A privileged job container masks # the restrictions that production rootless Podman installations enforce. + # Ubuntu 26.04 provides the supported Podman 5.x and pasta combination. + # Re-add older/slirp4netns environments when direct callbacks through a + # rootless-network namespace relay are supported. runs-on: ${{ matrix.runner }} timeout-minutes: 30 strategy: fail-fast: false matrix: include: - # Ubuntu 24.04 matches the environment reported in #2069 and ships - # Podman 4.x. The probe records whether AppArmor blocks the drop. - - runner: ubuntu-24.04 - podman_major: "4" - podman_package_version: "4.9.3+ds1-1ubuntu0.2" - conmon_package_version: "2.1.10+ds1-1build2" - # Ubuntu 26.04 provides the supported Podman 5.x coverage for - # comparison with the Ubuntu 24.04 environment. + # Keep package versions explicit so hosted-runner tool overrides + # cannot silently change the supported test environment. - runner: ubuntu-26.04 podman_major: "5" podman_package_version: "5.7.0+ds2-3build1" @@ -199,7 +196,6 @@ jobs: pkg-config \ "conmon=${{ matrix.conmon_package_version }}" \ "podman=${{ matrix.podman_package_version }}" \ - slirp4netns \ uidmap # Hosted runners can place newer Podman and conmon binaries under # /usr/local ahead of Ubuntu's packages. Select the distro CLI and @@ -238,6 +234,7 @@ jobs: test "$(command -v podman)" = "/usr/bin/podman" test "$(podman info --format '{{.Host.Conmon.Path}}')" = "/usr/bin/conmon" test "$(podman info --format '{{.Host.Security.Rootless}}')" = "true" + test "$(podman info --format '{{.Host.RootlessNetworkCmd}}')" = "pasta" test "$(sudo sysctl -n kernel.apparmor_restrict_unprivileged_userns)" = "1" echo "=== host ===" uname -a diff --git a/.github/workflows/release-dev.yml b/.github/workflows/release-dev.yml index 2eb503a507..70f458d384 100644 --- a/.github/workflows/release-dev.yml +++ b/.github/workflows/release-dev.yml @@ -920,7 +920,7 @@ jobs: cat release/openshell.rb - name: Attest VM driver artifacts - uses: actions/attest@f7c74d28b9d84cb8768d0b8ca14a4bac6ef463e6 # v4.2.0 + uses: actions/attest@508db95dd578ae2727ebd6217d5ba78e4fbda05d # v4.2.1 with: subject-path: | release/openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz diff --git a/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml index 61594f528a..8d43e390cf 100644 --- a/.github/workflows/release-tag.yml +++ b/.github/workflows/release-tag.yml @@ -978,7 +978,7 @@ jobs: cat release/openshell.rb - name: Attest VM driver artifacts - uses: actions/attest@f7c74d28b9d84cb8768d0b8ca14a4bac6ef463e6 # v4.2.0 + uses: actions/attest@508db95dd578ae2727ebd6217d5ba78e4fbda05d # v4.2.1 with: subject-path: | release/*.tar.gz diff --git a/.github/workflows/release-vm-kernel.yml b/.github/workflows/release-vm-kernel.yml index 0d7bd31f33..76f00cb784 100644 --- a/.github/workflows/release-vm-kernel.yml +++ b/.github/workflows/release-vm-kernel.yml @@ -186,7 +186,7 @@ jobs: merge-multiple: true - name: Attest VM runtime artifacts - uses: actions/attest@f7c74d28b9d84cb8768d0b8ca14a4bac6ef463e6 # v4.2.0 + uses: actions/attest@508db95dd578ae2727ebd6217d5ba78e4fbda05d # v4.2.1 with: subject-path: | release/vm-runtime-linux-aarch64.tar.zst diff --git a/AGENTS.md b/AGENTS.md index ce7fc7cd63..540a8d9207 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,6 +37,7 @@ These pipelines connect skills into end-to-end workflows. Individual skill files | `crates/openshell-bootstrap/` | Gateway metadata | Gateway registration metadata, auth token storage, mTLS bundle storage | | `crates/openshell-gateway-interceptors/` | Gateway interceptors | Intercepts and transforms configured gRPC requests at the gateway routing boundary | | `crates/openshell-ocsf/` | OCSF logging | OCSF v1.7.0 event types, builders, shorthand/JSONL formatters, tracing layers | +| `crates/openshell-otel/` | OpenTelemetry support | Shared OTLP trace provider, resource, and tracing-layer construction | | `crates/openshell-core/` | Shared core | Common types, configuration, error handling | | `crates/openshell-sdk/` | Shared client SDK | Async Rust gateway client (gRPC transport, TLS, OIDC refresh, edge tunnel); consumed by CLI, TUI, and `@openshell/sdk` | | `crates/openshell-providers/` | Provider management | Credential provider backends | diff --git a/Cargo.lock b/Cargo.lock index 89a0dc6eda..528309a970 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3957,6 +3957,7 @@ dependencies = [ "tonic", "tracing", "tracing-subscriber", + "url", ] [[package]] @@ -4026,6 +4027,21 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "openshell-otel" +version = "0.0.0" +dependencies = [ + "http 1.4.0", + "opentelemetry", + "opentelemetry-otlp", + "opentelemetry_sdk", + "thiserror 2.0.18", + "tokio", + "tracing", + "tracing-opentelemetry", + "tracing-subscriber", +] + [[package]] name = "openshell-policy" version = "0.0.0" @@ -4177,6 +4193,7 @@ dependencies = [ "openshell-driver-podman", "openshell-gateway-interceptors", "openshell-ocsf", + "openshell-otel", "openshell-policy", "openshell-prover", "openshell-providers", @@ -4184,8 +4201,6 @@ dependencies = [ "openshell-supervisor-middleware", "openshell-supervisor-middleware-builtins", "opentelemetry", - "opentelemetry-otlp", - "opentelemetry-proto", "opentelemetry_sdk", "petname", "pin-project-lite", @@ -4202,6 +4217,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.10.9", + "socket2 0.6.3", "sqlx", "tempfile", "thiserror 2.0.18", diff --git a/Cargo.toml b/Cargo.toml index 4078c0feb5..e3043dc322 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -74,6 +74,7 @@ metrics-exporter-prometheus = { version = "0.18", default-features = false, feat # Unix/Process nix = { version = "0.29", features = ["signal", "process", "user", "fs", "term"] } rustix = { version = "1.1", features = ["process"] } +socket2 = "0.6" # Serialization serde = { version = "1", features = ["derive"] } diff --git a/architecture/gateway.md b/architecture/gateway.md index 9469161477..c7569c3d5b 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -37,6 +37,27 @@ health, metrics, or tunnel routes. The plaintext service router also rejects browser requests whose Fetch Metadata, Origin, or Referer headers indicate a cross-origin or sibling-subdomain request. +Docker and Podman may negotiate additional listeners that make the gateway +reachable from their local sandbox network topology. Those listeners accept +only gRPC methods classified as sandbox-callable by the gateway's generated +authorization metadata. They reject user and administrator APIs, health, +reflection, non-callback inference APIs, and HTTP routes before normal request +authentication. The operator-configured primary listener retains the full +multiplexed API surface. + +The gateway rejects a callback requirement that resolves to the exact primary +listener address because one socket cannot preserve two authorization scopes. +A wildcard primary listener may cover a callback address because the accepted +connection's concrete local address still selects the callback-only scope. + +The `rpc_auth` classification is also the source of truth for negotiated +listener exposure: marking an RPC as `sandbox` or `dual` makes it callable on +these listeners. Review such changes as both authorization and network-surface +changes. Listener requirements are currently authorized only for the built-in +Docker and Podman drivers. Operator-granted listener capabilities for external +drivers are tracked in +[#2539](https://github.com/NVIDIA/OpenShell/issues/2539). + Operators can configure a gateway-wide gRPC request rate limit. The limit is applied only to gRPC API traffic after protocol multiplexing; health, metrics, and local sandbox-service HTTP routes are not rate limited by this control. @@ -615,7 +636,8 @@ replace the existing logging paths. export: the table's presence is the on-switch, and `OTEL_EXPORTER_OTLP_ENDPOINT` is ignored so enablement has a single source. TOML decides whether and where to export; the SDK's `OTEL_*` variables tune how. Transport is OTLP over gRPC -only. +only. Shared provider, resource, and tracing-layer construction lives in +`openshell-otel`. Span emission requires no per-handler instrumentation. The `tower_http` `TraceLayer` in `multiplex.rs` opens a span per inbound request, and that span @@ -660,7 +682,12 @@ system entry instead of pretending to delete package-manager owned state. - Podman-backed macOS gateways use gvproxy's host-loopback IP for sandbox host aliases by default so stale Podman machine images do not need Podman's `host-gateway` resolver. Linux Podman keeps the resolver unless - `host_gateway_ip` is configured. + `host_gateway_ip` is configured. Rootful Podman can request its exact bridge + gateway listener. Rootless Podman explicitly reporting pasta requests the + private IPv4 source selected by the host default route rather than an + arbitrary private interface. Slirp4netns, other helpers, and missing helper + metadata fail closed for local callbacks until a rootless-network namespace + relay is available. - Gateway restarts recover persisted objects from storage, but live relay streams must be re-established by supervisors. - User-facing behavior changes must update published docs in `docs/`; this file diff --git a/crates/openshell-bootstrap/src/pki.rs b/crates/openshell-bootstrap/src/pki.rs index adc2c48f12..ed6e839bf6 100644 --- a/crates/openshell-bootstrap/src/pki.rs +++ b/crates/openshell-bootstrap/src/pki.rs @@ -39,6 +39,7 @@ pub const DEFAULT_SERVER_SANS: &[&str] = &[ "host.docker.internal", "host.containers.internal", "127.0.0.1", + "::1", ]; /// Generate a complete PKI bundle: CA, server cert, and client cert. @@ -190,5 +191,7 @@ mod tests { fn default_server_sans_include_local_container_hostnames() { assert!(DEFAULT_SERVER_SANS.contains(&"host.docker.internal")); assert!(DEFAULT_SERVER_SANS.contains(&"host.containers.internal")); + assert!(DEFAULT_SERVER_SANS.contains(&"127.0.0.1")); + assert!(DEFAULT_SERVER_SANS.contains(&"::1")); } } diff --git a/crates/openshell-driver-docker/src/lib.rs b/crates/openshell-driver-docker/src/lib.rs index a196ba6ad9..502f4ae8fe 100644 --- a/crates/openshell-driver-docker/src/lib.rs +++ b/crates/openshell-driver-docker/src/lib.rs @@ -39,12 +39,14 @@ use openshell_core::progress::{ use openshell_core::proto::compute::v1::{ CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse, DriverCondition, DriverPlatformEvent, DriverSandbox, DriverSandboxStatus, - DriverSandboxTemplate, GetCapabilitiesRequest, GetCapabilitiesResponse, GetSandboxRequest, - GetSandboxResponse, GpuResourceRequirements, ListSandboxesRequest, ListSandboxesResponse, - StopSandboxRequest, StopSandboxResponse, ValidateSandboxCreateRequest, - ValidateSandboxCreateResponse, WatchSandboxesDeletedEvent, WatchSandboxesEvent, - WatchSandboxesPlatformEvent, WatchSandboxesRequest, WatchSandboxesSandboxEvent, - compute_driver_server::ComputeDriver, watch_sandboxes_event, + DriverSandboxTemplate, GatewayListenerRequirement, GetCapabilitiesRequest, + GetCapabilitiesResponse, GetGatewayListenerRequirementsRequest, + GetGatewayListenerRequirementsResponse, GetSandboxRequest, GetSandboxResponse, + GpuResourceRequirements, ListSandboxesRequest, ListSandboxesResponse, StopSandboxRequest, + StopSandboxResponse, ValidateSandboxCreateRequest, ValidateSandboxCreateResponse, + WatchSandboxesDeletedEvent, WatchSandboxesEvent, WatchSandboxesPlatformEvent, + WatchSandboxesRequest, WatchSandboxesSandboxEvent, compute_driver_server::ComputeDriver, + gateway_listener_requirement::Selector, watch_sandboxes_event, }; use openshell_core::proto_struct::{ deserialize_optional_non_empty_string_list, struct_to_json_value, @@ -399,14 +401,6 @@ impl DockerComputeDriver { Ok(driver) } - #[must_use] - pub fn gateway_bind_addresses(&self) -> Vec { - match self.config.gateway_route { - DockerGatewayRoute::Bridge { bind_address, .. } => vec![bind_address], - DockerGatewayRoute::HostGateway => Vec::new(), - } - } - fn capabilities(&self) -> GetCapabilitiesResponse { openshell_core::driver_utils::build_capabilities_response( "docker", @@ -1386,6 +1380,24 @@ impl ComputeDriver for DockerComputeDriver { Ok(Response::new(self.capabilities())) } + async fn get_gateway_listener_requirements( + &self, + _request: Request, + ) -> Result, Status> { + let requirements = match self.config.gateway_route { + DockerGatewayRoute::Bridge { bind_address, .. } => { + vec![GatewayListenerRequirement { + reason: "docker managed bridge gateway".to_string(), + selector: Some(Selector::ExactBindAddress(bind_address.to_string())), + }] + } + DockerGatewayRoute::HostGateway => Vec::new(), + }; + Ok(Response::new(GetGatewayListenerRequirementsResponse { + requirements, + })) + } + async fn validate_sandbox_create( &self, request: Request, diff --git a/crates/openshell-driver-docker/src/tests.rs b/crates/openshell-driver-docker/src/tests.rs index a86a9936f5..fdf850dc6a 100644 --- a/crates/openshell-driver-docker/src/tests.rs +++ b/crates/openshell-driver-docker/src/tests.rs @@ -13,8 +13,9 @@ use openshell_core::progress::{ PROGRESS_STEP_STARTING_SANDBOX, }; use openshell_core::proto::compute::v1::{ - DriverResourceRequirements, DriverSandboxSpec, DriverSandboxTemplate, GpuResourceRequirements, - ResourceRequirements, + DriverResourceRequirements, DriverSandboxSpec, DriverSandboxTemplate, + GetGatewayListenerRequirementsRequest, GpuResourceRequirements, ResourceRequirements, + gateway_listener_requirement::Selector, }; use std::fs; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; @@ -158,6 +159,43 @@ fn test_driver_with_config(config: DockerDriverRuntimeConfig) -> DockerComputeDr } } +#[tokio::test] +async fn gateway_listener_requirements_report_managed_bridge_address() { + let config = runtime_config(); + let expected_address = match config.gateway_route { + DockerGatewayRoute::Bridge { bind_address, .. } => bind_address, + DockerGatewayRoute::HostGateway => panic!("test config must use a managed bridge"), + }; + let driver = test_driver_with_config(config); + + let response = driver + .get_gateway_listener_requirements(Request::new(GetGatewayListenerRequirementsRequest {})) + .await + .unwrap() + .into_inner(); + + assert_eq!(response.requirements.len(), 1); + assert_eq!( + response.requirements[0].selector, + Some(Selector::ExactBindAddress(expected_address.to_string())) + ); +} + +#[tokio::test] +async fn gateway_listener_requirements_are_empty_for_host_gateway_route() { + let mut config = runtime_config(); + config.gateway_route = DockerGatewayRoute::HostGateway; + let driver = test_driver_with_config(config); + + let response = driver + .get_gateway_listener_requirements(Request::new(GetGatewayListenerRequirementsRequest {})) + .await + .unwrap() + .into_inner(); + + assert!(response.requirements.is_empty()); +} + #[test] fn container_visible_endpoint_rewrites_loopback_hosts() { assert_eq!( diff --git a/crates/openshell-driver-kubernetes/src/grpc.rs b/crates/openshell-driver-kubernetes/src/grpc.rs index fccfa9464b..6eeb51cd73 100644 --- a/crates/openshell-driver-kubernetes/src/grpc.rs +++ b/crates/openshell-driver-kubernetes/src/grpc.rs @@ -6,7 +6,8 @@ use futures::{Stream, StreamExt}; use openshell_core::proto::compute::v1::{ CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse, - GetCapabilitiesRequest, GetCapabilitiesResponse, GetSandboxRequest, GetSandboxResponse, + GetCapabilitiesRequest, GetCapabilitiesResponse, GetGatewayListenerRequirementsRequest, + GetGatewayListenerRequirementsResponse, GetSandboxRequest, GetSandboxResponse, ListSandboxesRequest, ListSandboxesResponse, StopSandboxRequest, StopSandboxResponse, ValidateSandboxCreateRequest, ValidateSandboxCreateResponse, WatchSandboxesEvent, WatchSandboxesRequest, compute_driver_server::ComputeDriver, @@ -40,6 +41,15 @@ impl ComputeDriver for ComputeDriverService { .map_err(Status::internal) } + async fn get_gateway_listener_requirements( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(GetGatewayListenerRequirementsResponse { + requirements: Vec::new(), + })) + } + async fn validate_sandbox_create( &self, request: Request, diff --git a/crates/openshell-driver-podman/Cargo.toml b/crates/openshell-driver-podman/Cargo.toml index ed798c0ab2..5f108fd9cc 100644 --- a/crates/openshell-driver-podman/Cargo.toml +++ b/crates/openshell-driver-podman/Cargo.toml @@ -34,6 +34,7 @@ tracing = { workspace = true } tracing-subscriber = { workspace = true } thiserror = { workspace = true } miette = { workspace = true } +url = { workspace = true } [dev-dependencies] prost-types = { workspace = true } diff --git a/crates/openshell-driver-podman/NETWORKING.md b/crates/openshell-driver-podman/NETWORKING.md index 93c5ba0964..4b2ae7ff29 100644 --- a/crates/openshell-driver-podman/NETWORKING.md +++ b/crates/openshell-driver-podman/NETWORKING.md @@ -255,6 +255,34 @@ if config.grpc_endpoint.is_empty() { The bridge gateway IP is not a stable substitute in rootless mode because it can live inside the user namespace rather than on the host. +Before the gateway binds its serving sockets, the driver reports the callback +listener required by the selected topology: + +- Rootful Linux Podman reports the configured bridge's gateway address exactly. +- Rootless Linux Podman explicitly reporting pasta requests the private IPv4 + source address selected by the host's default route. This avoids guessing + among private interfaces on a multihomed host. +- Rootless Linux Podman reporting slirp4netns, another named helper, or no + helper cannot use a direct local callback listener. The driver fails startup + unless `grpc_endpoint` names an explicitly remote endpoint. Supporting + slirp4netns requires a relay inside Podman's rootless network namespace. +- Podman Machine requests IPv4 loopback because gvproxy terminates the host + forwarding path there. +- An explicitly remote callback endpoint requests no additional local listener. + +On Linux, an explicit `host_gateway_ip` is reported exactly for rootful Podman +and rootless pasta because the driver maps both local callback aliases to that +literal. Other rootless helpers still fail closed. Podman Machine requests +gateway loopback because its configured address is guest-visible and gvproxy +terminates that route on host loopback. The gateway validates and binds every +accepted callback listener. A callback address cannot equal the exact primary +listener address because the gateway could not distinguish their authorization +scopes. In particular, a Podman Machine gateway using the IPv4 loopback +callback must place its primary listener on another address, such as IPv6 +loopback (`[::1]:17670`). Negotiated callback listeners expose only the +gateway's sandbox-callable gRPC methods. Operator, health, reflection, and HTTP +requests must use the primary listener. + ### Layer 3 Inner Sandbox Network Namespace Inside the container, the supervisor creates another network namespace for the diff --git a/crates/openshell-driver-podman/src/client.rs b/crates/openshell-driver-podman/src/client.rs index 952938d47a..5291f09eac 100644 --- a/crates/openshell-driver-podman/src/client.rs +++ b/crates/openshell-driver-podman/src/client.rs @@ -262,6 +262,8 @@ pub struct HostInfo { #[serde(default)] pub network_backend: String, #[serde(default)] + pub rootless_network_cmd: String, + #[serde(default)] pub security: SecurityInfo, } @@ -902,6 +904,24 @@ mod tests { assert!(validate_name(&exact_name).is_ok()); } + #[test] + fn system_info_parses_rootless_network_helper() { + let info: SystemInfo = serde_json::from_str( + r#"{ + "host": { + "cgroupVersion": "v2", + "networkBackend": "netavark", + "rootlessNetworkCmd": "pasta", + "security": {"rootless": true} + } + }"#, + ) + .unwrap(); + + assert!(info.host.security.rootless); + assert_eq!(info.host.rootless_network_cmd, "pasta"); + } + #[tokio::test] async fn inspect_volume_parses_driver_options() { let (socket_path, request_log, handle) = spawn_podman_stub( diff --git a/crates/openshell-driver-podman/src/driver.rs b/crates/openshell-driver-podman/src/driver.rs index aa3df9cbd7..f871caf7b6 100644 --- a/crates/openshell-driver-podman/src/driver.rs +++ b/crates/openshell-driver-podman/src/driver.rs @@ -16,13 +16,21 @@ use openshell_core::gpu::{ CdiGpuDefaultSelector, CdiGpuInventory, CdiGpuSelectionError, driver_gpu_requirements, effective_driver_gpu_count, validate_specific_gpu_device_request, }; +#[cfg(target_os = "linux")] +use openshell_core::proto::compute::v1::GatewayDefaultRouteInterfaceRequirement; +#[cfg(target_os = "macos")] +use openshell_core::proto::compute::v1::GatewayLoopbackInterfaceRequirement; use openshell_core::proto::compute::v1::{ - DriverSandbox, GetCapabilitiesResponse, GpuResourceRequirements, + DriverSandbox, GatewayListenerRequirement, GetCapabilitiesResponse, GpuResourceRequirements, + gateway_listener_requirement::Selector, }; +#[cfg(target_os = "linux")] +use std::net::{IpAddr, SocketAddr}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; use tracing::{debug, info, warn}; +use url::Url; impl From for ComputeDriverError { fn from(value: PodmanApiError) -> Self { @@ -39,9 +47,13 @@ impl From for ComputeDriverError { pub struct PodmanComputeDriver { client: PodmanClient, config: PodmanComputeConfig, - /// The host's IP on the bridge network. Sandbox containers use this to - /// reach the gateway server when no explicit gRPC endpoint is configured. + /// The host's IP on the bridge network, when that bridge exists in the + /// gateway's network namespace (notably rootful Podman). network_gateway_ip: Option, + /// Whether Podman's service is running without root privileges. + rootless: bool, + /// Rootless network helper reported by Podman, such as `pasta`. + rootless_network_cmd: String, gpu_selector: Arc, gpu_inventory_refresh: Arc (CdiGpuInventory, bool) + Send + Sync>, } @@ -52,6 +64,8 @@ impl std::fmt::Debug for PodmanComputeDriver { .field("socket_path", &self.config.socket_path) .field("default_image", &self.config.default_image) .field("network_name", &self.config.network_name) + .field("rootless", &self.rootless) + .field("rootless_network_cmd", &self.rootless_network_cmd) .field("gpu_inventory", &self.gpu_selector.device_ids()) .finish() } @@ -289,7 +303,7 @@ impl PodmanComputeDriver { } // Verify cgroups v2, detect rootless mode, and log system info. - match client.system_info().await { + let (rootless, rootless_network_cmd) = match client.system_info().await { Ok(info) => { if info.host.cgroup_version != "v2" { return Err(PodmanApiError::Connection(format!( @@ -303,15 +317,17 @@ impl PodmanComputeDriver { cgroup_version = %info.host.cgroup_version, network_backend = %info.host.network_backend, rootless = info.host.security.rootless, + rootless_network_cmd = %info.host.rootless_network_cmd, "Connected to Podman" ); + (info.host.security.rootless, info.host.rootless_network_cmd) } Err(e) => { return Err(PodmanApiError::Connection(format!( "failed to query Podman system info: {e}" ))); } - } + }; // Rootless pre-flight: warn if subuid/subgid ranges look missing. // Not a hard error because some systems configure these via LDAP or @@ -320,33 +336,8 @@ impl PodmanComputeDriver { check_subuid_range(); } - // Ensure the bridge network exists. - client.ensure_network(&config.network_name).await?; - let network_gateway_ip = client - .network_gateway_ip(&config.network_name) - .await - .unwrap_or(None); - info!( - network = %config.network_name, - gateway_ip = ?network_gateway_ip, - "Bridge network ready" - ); - - let (gpu_inventory, allow_all_default_gpu) = local_podman_gpu_selector_state(); - if !gpu_inventory.is_empty() { - info!( - device_count = gpu_inventory.as_slice().len(), - "Discovered local Podman NVIDIA CDI GPU devices" - ); - } - - // Auto-detect the gRPC callback endpoint when not explicitly - // configured. Sandbox containers use host.containers.internal - // (injected via hostadd with host-gateway in the container spec) - // to reach the gateway server on the host. The scheme is - // determined by whether TLS client certs are configured: when - // all three TLS paths are set, the endpoint uses https so the - // supervisor connects with mTLS. + // Auto-detect the gRPC callback endpoint before deciding whether this + // topology needs the Podman bridge gateway address. if config.grpc_endpoint.is_empty() { let scheme = if config.tls_enabled() { "https" @@ -364,10 +355,42 @@ impl PodmanComputeDriver { ); } + // Ensure the bridge network exists. Inspect its gateway only when the + // selected Linux callback topology will bind that exact address. + client.ensure_network(&config.network_name).await?; + let uses_local_callback_alias = Url::parse(&config.grpc_endpoint) + .ok() + .as_ref() + .is_some_and(callback_endpoint_uses_local_alias); + let needs_network_gateway_ip = cfg!(target_os = "linux") + && uses_local_callback_alias + && !rootless + && config.host_gateway_ip.trim().is_empty(); + let network_gateway_ip = if needs_network_gateway_ip { + client.network_gateway_ip(&config.network_name).await? + } else { + None + }; + info!( + network = %config.network_name, + gateway_ip = ?network_gateway_ip, + "Bridge network ready" + ); + + let (gpu_inventory, allow_all_default_gpu) = local_podman_gpu_selector_state(); + if !gpu_inventory.is_empty() { + info!( + device_count = gpu_inventory.as_slice().len(), + "Discovered local Podman NVIDIA CDI GPU devices" + ); + } + Ok(Self { client, config, network_gateway_ip, + rootless, + rootless_network_cmd, gpu_selector: Arc::new(CdiGpuDefaultSelector::new( gpu_inventory, allow_all_default_gpu, @@ -378,8 +401,8 @@ impl PodmanComputeDriver { /// The host's IP on the bridge network, if available. /// - /// Used by the server to auto-detect the gRPC callback endpoint when - /// no explicit `--grpc-endpoint` is configured. + /// Used to request the exact rootful gateway callback listener when no + /// explicit host-gateway override is configured. #[must_use] pub fn network_gateway_ip(&self) -> Option<&str> { self.network_gateway_ip.as_deref() @@ -394,6 +417,94 @@ impl PodmanComputeDriver { )) } + /// Report the gateway exposure needed by Podman's standard local callback aliases. + /// + /// Rootful Podman binds the exact bridge address behind the sandbox alias. + /// Rootless pasta follows the host's default-route interface, while Podman + /// Machine forwards the alias to gateway loopback. Other rootless helpers + /// cannot use a direct host listener. + pub fn gateway_listener_requirements( + &self, + ) -> Result, ComputeDriverError> { + let endpoint = Url::parse(&self.config.grpc_endpoint).map_err(|err| { + ComputeDriverError::Precondition(format!( + "invalid Podman gateway callback endpoint '{}': {err}", + self.config.grpc_endpoint + )) + })?; + let uses_local_callback_alias = callback_endpoint_uses_local_alias(&endpoint); + if !uses_local_callback_alias { + return Ok(Vec::new()); + } + let callback_port = endpoint.port_or_known_default().ok_or_else(|| { + ComputeDriverError::Precondition(format!( + "Podman gateway callback endpoint '{}' has no port", + self.config.grpc_endpoint + )) + })?; + if callback_port != self.config.gateway_port { + return Err(ComputeDriverError::Precondition(format!( + "Podman local callback endpoint '{}' uses port {callback_port}, but the gateway primary listener uses port {}; configure grpc_endpoint with the gateway primary listener port", + self.config.grpc_endpoint, self.config.gateway_port + ))); + } + + #[cfg(target_os = "linux")] + { + if self.rootless { + validate_rootless_local_callback_helper(&self.rootless_network_cmd)?; + + if self.config.host_gateway_ip.trim().is_empty() { + return Ok(vec![GatewayListenerRequirement { + reason: + "Podman rootless pasta callback uses the host default-route interface" + .to_string(), + selector: Some(Selector::DefaultRouteInterface( + GatewayDefaultRouteInterfaceRequirement {}, + )), + }]); + } + } + + let gateway_ip = if self.config.host_gateway_ip.trim().is_empty() { + self.network_gateway_ip.as_deref().ok_or_else(|| { + ComputeDriverError::Precondition(format!( + "Podman network '{}' did not report a host bridge gateway address for local callback alias '{}'", + self.config.network_name, + endpoint.host_str().unwrap_or_default() + )) + })? + } else { + self.config.host_gateway_ip.trim() + }; + let gateway_ip = gateway_ip.parse::().map_err(|err| { + ComputeDriverError::Precondition(format!( + "Podman callback gateway address '{gateway_ip}' is invalid: {err}" + )) + })?; + Ok(vec![GatewayListenerRequirement { + reason: format!("Podman network '{}' host gateway", self.config.network_name), + selector: Some(Selector::ExactBindAddress( + SocketAddr::new(gateway_ip, callback_port).to_string(), + )), + }]) + } + #[cfg(target_os = "macos")] + { + Ok(vec![GatewayListenerRequirement { + reason: "Podman machine callback forwarding terminates on gateway loopback" + .to_string(), + selector: Some(Selector::LoopbackInterface( + GatewayLoopbackInterfaceRequirement {}, + )), + }]) + } + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + { + Ok(Vec::new()) + } + } + #[must_use] pub fn default_image(&self) -> &str { &self.config.default_image @@ -892,6 +1003,8 @@ impl PodmanComputeDriver { client, config, network_gateway_ip: None, + rootless: false, + rootless_network_cmd: String::new(), gpu_selector: Arc::new(CdiGpuDefaultSelector::new( gpu_inventory, allow_all_default_gpu, @@ -950,6 +1063,31 @@ fn check_subuid_range() { } } +fn callback_endpoint_uses_local_alias(endpoint: &Url) -> bool { + endpoint + .host_str() + .is_some_and(|host| matches!(host, "host.containers.internal" | "host.openshell.internal")) +} + +#[cfg(any(target_os = "linux", test))] +fn validate_rootless_local_callback_helper( + rootless_network_cmd: &str, +) -> Result<(), ComputeDriverError> { + let rootless_network_cmd = rootless_network_cmd.trim(); + if rootless_network_cmd == "pasta" { + return Ok(()); + } + + let reported = if rootless_network_cmd.is_empty() { + "" + } else { + rootless_network_cmd + }; + Err(ComputeDriverError::Precondition(format!( + "Podman rootless network helper '{reported}' does not support direct local gateway callbacks; configure pasta or use an explicitly remote grpc_endpoint" + ))) +} + #[cfg(test)] mod tests { use super::*; @@ -1168,6 +1306,272 @@ mod tests { assert_eq!(cfg.grpc_endpoint, "https://gateway.internal:9000"); } + #[test] + fn rootless_slirp_allows_remote_callback_endpoint() { + let mut driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { + grpc_endpoint: "https://gateway.internal:9000".to_string(), + ..PodmanComputeConfig::default() + }); + driver.rootless = true; + driver.rootless_network_cmd = "slirp4netns".to_string(); + + let requirements = driver.gateway_listener_requirements().unwrap(); + + assert!(requirements.is_empty()); + } + + #[test] + #[cfg(target_os = "linux")] + fn rootful_local_callback_alias_requests_discovered_network_gateway() { + let mut driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { + grpc_endpoint: "http://host.openshell.internal:17670".to_string(), + ..PodmanComputeConfig::default() + }); + driver.network_gateway_ip = Some("10.89.1.1".to_string()); + + let requirements = driver.gateway_listener_requirements().unwrap(); + + assert_eq!(requirements.len(), 1); + assert_eq!( + requirements[0].selector, + Some(Selector::ExactBindAddress("10.89.1.1:17670".to_string())) + ); + } + + #[test] + #[cfg(target_os = "linux")] + fn configured_host_gateway_overrides_discovered_network_gateway() { + let mut driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { + grpc_endpoint: "http://host.containers.internal:17670".to_string(), + host_gateway_ip: "10.90.1.1".to_string(), + ..PodmanComputeConfig::default() + }); + driver.network_gateway_ip = Some("10.89.1.1".to_string()); + driver.rootless = true; + driver.rootless_network_cmd = "pasta".to_string(); + + let requirements = driver.gateway_listener_requirements().unwrap(); + + assert_eq!( + requirements[0].selector, + Some(Selector::ExactBindAddress("10.90.1.1:17670".to_string())) + ); + } + + #[test] + #[cfg(target_os = "linux")] + fn rootless_pasta_requests_default_route_interface() { + let mut driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { + grpc_endpoint: "http://host.openshell.internal:17670".to_string(), + ..PodmanComputeConfig::default() + }); + driver.rootless = true; + driver.rootless_network_cmd = "pasta".to_string(); + + let requirements = driver.gateway_listener_requirements().unwrap(); + + assert!(matches!( + requirements[0].selector, + Some(Selector::DefaultRouteInterface(_)) + )); + } + + #[test] + fn rootless_non_pasta_helpers_are_rejected() { + for (rootless_network_cmd, reported) in [ + ("slirp4netns", "slirp4netns"), + ("", ""), + ("unknown-helper", "unknown-helper"), + ] { + let err = validate_rootless_local_callback_helper(rootless_network_cmd).unwrap_err(); + + assert!(matches!(err, ComputeDriverError::Precondition(_))); + assert!(err.to_string().contains(reported)); + assert!(err.to_string().contains("configure pasta")); + assert!(err.to_string().contains("remote grpc_endpoint")); + } + } + + #[test] + fn rootless_pasta_is_accepted_for_local_callbacks() { + validate_rootless_local_callback_helper("pasta").unwrap(); + } + + #[test] + #[cfg(target_os = "linux")] + fn rootless_slirp_rejects_explicit_host_gateway_override() { + let mut driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { + grpc_endpoint: "http://host.openshell.internal:17670".to_string(), + host_gateway_ip: "10.90.1.1".to_string(), + ..PodmanComputeConfig::default() + }); + driver.rootless = true; + driver.rootless_network_cmd = "slirp4netns".to_string(); + + let err = driver.gateway_listener_requirements().unwrap_err(); + + assert!(matches!(err, ComputeDriverError::Precondition(_))); + assert!(err.to_string().contains("slirp4netns")); + } + + #[tokio::test] + async fn constructor_preserves_required_network_gateway_discovery_error() { + let (socket_path, _request_log, handle) = spawn_podman_stub( + "network-gateway-error", + vec![ + StubResponse::new(StatusCode::OK, ""), + StubResponse::new( + StatusCode::OK, + r#"{ + "host": { + "cgroupVersion": "v2", + "networkBackend": "netavark", + "security": {"rootless": false}, + "remoteSocket": {"path": "/run/podman/podman.sock"} + }, + "version": {"Version": "5.0.0"} + }"#, + ), + StubResponse::new(StatusCode::CREATED, "{}"), + StubResponse::new( + StatusCode::INTERNAL_SERVER_ERROR, + r#"{"message":"network gateway inspection failed"}"#, + ), + ], + ); + let config = PodmanComputeConfig { + socket_path: Some(socket_path.clone()), + grpc_endpoint: "http://host.containers.internal:8080".to_string(), + ..PodmanComputeConfig::default() + }; + + let Err(err) = PodmanComputeDriver::new(config).await else { + panic!("required network gateway discovery failure should prevent startup"); + }; + + assert!( + err.to_string() + .contains("network gateway inspection failed"), + "unexpected startup error: {err}" + ); + handle.await.expect("stub task should finish"); + } + + #[tokio::test] + async fn constructor_skips_network_gateway_discovery_for_remote_callback() { + let (socket_path, request_log, handle) = spawn_podman_stub( + "remote-callback-no-network-gateway", + vec![ + StubResponse::new(StatusCode::OK, ""), + StubResponse::new( + StatusCode::OK, + r#"{ + "host": { + "cgroupVersion": "v2", + "networkBackend": "netavark", + "security": {"rootless": false} + } + }"#, + ), + StubResponse::new(StatusCode::CREATED, "{}"), + ], + ); + let config = PodmanComputeConfig { + socket_path: Some(socket_path.clone()), + grpc_endpoint: "https://gateway.example.test:9443".to_string(), + ..PodmanComputeConfig::default() + }; + + let driver = PodmanComputeDriver::new(config) + .await + .expect("remote callbacks must not require bridge gateway inspection"); + + assert!(driver.network_gateway_ip().is_none()); + assert!(driver.gateway_listener_requirements().unwrap().is_empty()); + handle.await.expect("stub task should finish"); + assert_eq!( + request_log + .lock() + .expect("request log lock should not be poisoned") + .as_slice(), + [ + "GET /_ping".to_string(), + format!("GET {}", api_path("/libpod/info")), + format!("POST {}", api_path("/libpod/networks/create")), + ] + ); + } + + #[test] + #[cfg(target_os = "linux")] + fn rootful_local_callback_alias_requires_concrete_gateway_address() { + let driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { + grpc_endpoint: "http://host.openshell.internal:17670".to_string(), + ..PodmanComputeConfig::default() + }); + + let err = driver.gateway_listener_requirements().unwrap_err(); + + assert!( + err.to_string() + .contains("did not report a host bridge gateway address") + ); + } + + #[test] + #[cfg(target_os = "macos")] + fn podman_machine_callback_alias_requests_loopback_listener() { + let driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { + grpc_endpoint: "http://host.openshell.internal:17670".to_string(), + ..PodmanComputeConfig::default() + }); + + let requirements = driver.gateway_listener_requirements().unwrap(); + + assert_eq!(requirements.len(), 1); + assert!(matches!( + requirements[0].selector, + Some(Selector::LoopbackInterface(_)) + )); + } + + #[test] + fn explicit_remote_callback_does_not_request_gateway_listener() { + let driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { + grpc_endpoint: "https://gateway.example.test:9443".to_string(), + gateway_port: 17670, + ..PodmanComputeConfig::default() + }); + + assert!(driver.gateway_listener_requirements().unwrap().is_empty()); + } + + #[test] + fn local_callback_alias_requires_primary_listener_port() { + for grpc_endpoint in [ + "http://host.openshell.internal:17671", + "http://host.containers.internal", + ] { + let driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { + grpc_endpoint: grpc_endpoint.to_string(), + gateway_port: 17670, + ..PodmanComputeConfig::default() + }); + + let err = driver.gateway_listener_requirements().unwrap_err(); + + assert!( + matches!(err, ComputeDriverError::Precondition(_)), + "mismatched local callback port should fail precondition: {err}" + ); + assert!( + err.to_string() + .contains("gateway primary listener uses port 17670"), + "unexpected error for {grpc_endpoint}: {err}" + ); + } + } + #[test] fn local_podman_cdi_gpu_inventory_maps_nvidia_device_nodes() { let root = std::env::temp_dir().join(format!( diff --git a/crates/openshell-driver-podman/src/grpc.rs b/crates/openshell-driver-podman/src/grpc.rs index 8e68a91e72..2d0792d447 100644 --- a/crates/openshell-driver-podman/src/grpc.rs +++ b/crates/openshell-driver-podman/src/grpc.rs @@ -6,7 +6,8 @@ use futures::{Stream, StreamExt}; use openshell_core::proto::compute::v1::{ CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse, - GetCapabilitiesRequest, GetCapabilitiesResponse, GetSandboxRequest, GetSandboxResponse, + GetCapabilitiesRequest, GetCapabilitiesResponse, GetGatewayListenerRequirementsRequest, + GetGatewayListenerRequirementsResponse, GetSandboxRequest, GetSandboxResponse, ListSandboxesRequest, ListSandboxesResponse, StopSandboxRequest, StopSandboxResponse, ValidateSandboxCreateRequest, ValidateSandboxCreateResponse, WatchSandboxesEvent, WatchSandboxesRequest, compute_driver_server::ComputeDriver, @@ -40,6 +41,18 @@ impl ComputeDriver for ComputeDriverService { .map_err(Status::from) } + async fn get_gateway_listener_requirements( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(GetGatewayListenerRequirementsResponse { + requirements: self + .driver + .gateway_listener_requirements() + .map_err(Status::from)?, + })) + } + async fn validate_sandbox_create( &self, request: Request, diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 7af0ddc389..841457f38c 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -41,6 +41,7 @@ use openshell_core::proto::compute::v1::{ DriverCondition as SandboxCondition, DriverPlatformEvent as PlatformEvent, DriverSandbox as Sandbox, DriverSandboxStatus as SandboxStatus, DriverSandboxTemplate as SandboxTemplate, GetCapabilitiesRequest, GetCapabilitiesResponse, + GetGatewayListenerRequirementsRequest, GetGatewayListenerRequirementsResponse, GetSandboxRequest, GetSandboxResponse, ListSandboxesRequest, ListSandboxesResponse, StopSandboxRequest, StopSandboxResponse, ValidateSandboxCreateRequest, ValidateSandboxCreateResponse, WatchSandboxesDeletedEvent, WatchSandboxesEvent, @@ -2989,6 +2990,15 @@ impl ComputeDriver for VmDriver { Ok(Response::new(self.capabilities())) } + async fn get_gateway_listener_requirements( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(GetGatewayListenerRequirementsResponse { + requirements: Vec::new(), + })) + } + async fn validate_sandbox_create( &self, request: Request, diff --git a/crates/openshell-otel/Cargo.toml b/crates/openshell-otel/Cargo.toml new file mode 100644 index 0000000000..bdf42630af --- /dev/null +++ b/crates/openshell-otel/Cargo.toml @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "openshell-otel" +description = "Shared OpenTelemetry trace export support for OpenShell services" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +http = { workspace = true } +opentelemetry = { workspace = true } +opentelemetry_sdk = { workspace = true } +opentelemetry-otlp = { workspace = true } +thiserror = { workspace = true } +tracing = { workspace = true } +tracing-opentelemetry = { workspace = true } +tracing-subscriber = { workspace = true } + +[dev-dependencies] +tokio = { workspace = true } + +[lints] +workspace = true diff --git a/crates/openshell-otel/src/lib.rs b/crates/openshell-otel/src/lib.rs new file mode 100644 index 0000000000..ae6f503ad7 --- /dev/null +++ b/crates/openshell-otel/src/lib.rs @@ -0,0 +1,198 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Shared OpenTelemetry trace export support for `OpenShell` services. + +use opentelemetry::KeyValue; +use opentelemetry::trace::TracerProvider as _; +use opentelemetry_otlp::{SpanExporter, WithExportConfig}; +use opentelemetry_sdk::Resource; +use opentelemetry_sdk::trace::SdkTracer; +pub use opentelemetry_sdk::trace::SdkTracerProvider; +use tracing::Subscriber; +use tracing_opentelemetry::OpenTelemetryLayer; +use tracing_subscriber::Layer as _; +use tracing_subscriber::registry::LookupSpan; + +const SDK_UNKNOWN_SERVICE_PREFIX: &str = "unknown_service"; + +/// How a process chooses its OpenTelemetry `service.name`. +#[derive(Debug, Clone, Copy)] +pub enum ServiceName<'a> { + /// Always use this name, overriding `OTEL_SERVICE_NAME`. + Fixed(&'a str), + /// Use `OTEL_SERVICE_NAME` when set, otherwise use this default. + EnvironmentOr(&'a str), +} + +/// Inputs for an OTLP/gRPC trace provider. +#[derive(Debug, Clone)] +pub struct OtlpTraceConfig<'a> { + pub endpoint: &'a str, + pub service_name: ServiceName<'a>, + pub service_version: Option<&'a str>, + pub resource_attributes: Vec, +} + +/// Failure to construct an OTLP trace provider. +#[derive(Debug, thiserror::Error)] +pub enum SetupError { + #[error("OTLP endpoint is empty")] + EmptyEndpoint, + + #[error("invalid OTLP endpoint {endpoint:?}: {source}")] + InvalidEndpoint { + endpoint: String, + source: http::uri::InvalidUri, + }, + + #[error("failed to build the OTLP span exporter: {0}")] + Exporter(#[from] opentelemetry_otlp::ExporterBuildError), +} + +fn resource_attributes(config: &OtlpTraceConfig<'_>) -> Vec { + let mut attributes = config.resource_attributes.clone(); + if let Some(version) = config + .service_version + .map(str::trim) + .filter(|version| !version.is_empty()) + { + attributes.push(KeyValue::new("service.version", version.to_string())); + } + attributes +} + +/// Build the OpenTelemetry resource for a trace provider configuration. +#[must_use] +pub fn resource_for(config: &OtlpTraceConfig<'_>) -> Resource { + let attributes = resource_attributes(config); + match config.service_name { + ServiceName::Fixed(name) => Resource::builder() + .with_service_name(name.trim().to_string()) + .with_attributes(attributes) + .build(), + ServiceName::EnvironmentOr(default) => { + let detected = Resource::builder() + .with_attributes(attributes.clone()) + .build(); + if detected + .get(&opentelemetry::Key::from_static_str("service.name")) + .is_some_and(|value| !value.to_string().starts_with(SDK_UNKNOWN_SERVICE_PREFIX)) + { + detected + } else { + Resource::builder() + .with_service_name(default.trim().to_string()) + .with_attributes(attributes) + .build() + } + } + } +} + +/// Build an OTLP/gRPC trace provider. +pub fn build_provider(config: &OtlpTraceConfig<'_>) -> Result { + let endpoint = config.endpoint.trim(); + if endpoint.is_empty() { + return Err(SetupError::EmptyEndpoint); + } + endpoint + .parse::() + .map_err(|source| SetupError::InvalidEndpoint { + endpoint: endpoint.to_string(), + source, + })?; + + let exporter = SpanExporter::builder() + .with_tonic() + .with_endpoint(endpoint) + .build()?; + + Ok(SdkTracerProvider::builder() + .with_batch_exporter(exporter) + .with_resource(resource_for(config)) + .build()) +} + +/// Build the provider for an optional OTLP configuration. +/// +/// Telemetry setup failures disable export and remain available for the caller +/// to report after its tracing subscriber is installed. +#[must_use] +pub fn provider_for( + config: Option>, +) -> (Option, Option) { + match config.as_ref().map(build_provider) { + None => (None, None), + Some(Ok(provider)) => (Some(provider), None), + Some(Err(error)) => (None, Some(error)), + } +} + +/// Filtered OpenTelemetry layer returned by [`layer`]. +pub type OtlpLayer = tracing_subscriber::filter::Filtered< + OpenTelemetryLayer, + tracing_subscriber::filter::FilterFn, + S, +>; + +/// Build a tracing layer that exports spans and excludes exporter callsites. +pub fn layer(provider: &SdkTracerProvider, instrumentation_scope: &'static str) -> OtlpLayer +where + S: Subscriber + for<'span> LookupSpan<'span>, +{ + tracing_opentelemetry::layer() + .with_tracer(provider.tracer(instrumentation_scope)) + .with_filter(tracing_subscriber::filter::filter_fn(|metadata| { + metadata.is_span() && !metadata.target().starts_with("opentelemetry") + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn resource_uses_fixed_service_identity_and_custom_attributes() { + let resource = resource_for(&OtlpTraceConfig { + endpoint: "http://127.0.0.1:4317", + service_name: ServiceName::Fixed("openshell-driver-vm"), + service_version: Some("1.2.3"), + resource_attributes: vec![KeyValue::new("openshell.gateway.name", "vm-dev")], + }); + + assert_eq!( + resource + .get(&opentelemetry::Key::from_static_str("service.name")) + .map(|value| value.to_string()), + Some("openshell-driver-vm".to_string()) + ); + assert_eq!( + resource + .get(&opentelemetry::Key::from_static_str("service.version")) + .map(|value| value.to_string()), + Some("1.2.3".to_string()) + ); + assert_eq!( + resource + .get(&opentelemetry::Key::from_static_str( + "openshell.gateway.name", + )) + .map(|value| value.to_string()), + Some("vm-dev".to_string()) + ); + } + + #[tokio::test] + async fn malformed_endpoint_disables_export_with_a_reportable_error() { + let (provider, error) = provider_for(Some(OtlpTraceConfig { + endpoint: "definitely not a url", + service_name: ServiceName::Fixed("test-service"), + service_version: None, + resource_attributes: Vec::new(), + })); + + assert!(provider.is_none()); + assert!(matches!(error, Some(SetupError::InvalidEndpoint { .. }))); + } +} diff --git a/crates/openshell-server/Cargo.toml b/crates/openshell-server/Cargo.toml index 56afd55ff8..8f4dbeb859 100644 --- a/crates/openshell-server/Cargo.toml +++ b/crates/openshell-server/Cargo.toml @@ -22,6 +22,7 @@ openshell-driver-kubernetes = { path = "../openshell-driver-kubernetes" } openshell-driver-podman = { path = "../openshell-driver-podman" } openshell-gateway-interceptors = { path = "../openshell-gateway-interceptors" } openshell-ocsf = { path = "../openshell-ocsf" } +openshell-otel = { path = "../openshell-otel" } openshell-policy = { path = "../openshell-policy" } openshell-prover = { path = "../openshell-prover" } openshell-providers = { path = "../openshell-providers" } @@ -35,6 +36,7 @@ k8s-openapi = { workspace = true } # Async runtime tokio = { workspace = true } +socket2 = { workspace = true } # gRPC tonic = { workspace = true, features = ["channel", "tls-native-roots"] } @@ -72,7 +74,6 @@ tracing-subscriber = { workspace = true } # OpenTelemetry (OTLP trace export, opt-in via [openshell.gateway.otlp]) opentelemetry = { workspace = true } opentelemetry_sdk = { workspace = true } -opentelemetry-otlp = { workspace = true } tracing-opentelemetry = { workspace = true } # Metrics @@ -127,8 +128,5 @@ wiremock = "0.6" # `testing` provides InMemorySpanExporter, so span assertions do not need a # collector, a network hop, or a flush barrier. opentelemetry_sdk = { workspace = true, features = ["testing"] } -# Supports asserting that the gateway sends spans over OTLP. -opentelemetry-proto = { version = "0.32", default-features = false, features = ["gen-tonic", "trace"] } - [lints] workspace = true diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 69bc390b46..25a2655a74 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -27,11 +27,14 @@ use openshell_core::ComputeDriverKind; use openshell_core::proto::compute::v1::{ CreateSandboxRequest, DeleteSandboxRequest, DriverCondition, DriverPlatformEvent, DriverResourceRequirements, DriverSandbox, DriverSandboxSpec, DriverSandboxStatus, - DriverSandboxTemplate, GetCapabilitiesRequest, GetSandboxRequest, + DriverSandboxTemplate, GatewayListenerRequirement as ProtoGatewayListenerRequirement, + GetCapabilitiesRequest, GetGatewayListenerRequirementsRequest, + GetGatewayListenerRequirementsResponse, GetSandboxRequest, GpuResourceRequirements as DriverGpuResourceRequirements, ListSandboxesRequest, ResourceRequirements as DriverSandboxResourceRequirements, ValidateSandboxCreateRequest, WatchSandboxesEvent, WatchSandboxesRequest, compute_driver_client::ComputeDriverClient, - compute_driver_server::ComputeDriver, watch_sandboxes_event, + compute_driver_server::ComputeDriver, gateway_listener_requirement::Selector, + watch_sandboxes_event, }; use openshell_core::proto::{ PlatformEvent, Sandbox, SandboxCondition, SandboxPhase, SandboxSpec, SandboxStatus, @@ -129,6 +132,41 @@ mod traced_driver { const DELETE_PHASE_CAS_RETRY_LIMIT: usize = 3; +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum GatewayListenerRequirement { + Exact { + address: SocketAddr, + driver_name: String, + reason: String, + }, + DefaultRouteInterface { + driver_name: String, + reason: String, + }, + LoopbackInterface { + driver_name: String, + reason: String, + }, +} + +impl GatewayListenerRequirement { + pub fn driver_name(&self) -> &str { + match self { + Self::Exact { driver_name, .. } + | Self::DefaultRouteInterface { driver_name, .. } + | Self::LoopbackInterface { driver_name, .. } => driver_name, + } + } + + pub fn reason(&self) -> &str { + match self { + Self::Exact { reason, .. } + | Self::DefaultRouteInterface { reason, .. } + | Self::LoopbackInterface { reason, .. } => reason, + } + } +} + /// Serializes request-side deletes for the same stable sandbox ID. /// /// Watch events deliberately do not use these gates, so a slow driver delete @@ -352,6 +390,14 @@ impl ComputeDriver for RemoteComputeDriver { client.get_capabilities(request).await } + async fn get_gateway_listener_requirements( + &self, + request: Request, + ) -> Result, Status> { + let mut client = self.client(); + client.get_gateway_listener_requirements(request).await + } + async fn validate_sandbox_create( &self, request: Request, @@ -434,7 +480,7 @@ pub struct ComputeRuntime { supervisor_sessions: Arc, sync_lock: Arc>, delete_gates: Arc, - gateway_bind_addresses: Vec, + gateway_listener_requirements: Vec, replica_id: String, } @@ -466,7 +512,6 @@ impl ComputeRuntime { sandbox_watch_bus: SandboxWatchBus, tracing_log_bus: TracingLogBus, supervisor_sessions: Arc, - gateway_bind_addresses: Vec, ) -> Result { let capabilities = driver .get_capabilities(Request::new(GetCapabilitiesRequest {})) @@ -489,6 +534,59 @@ impl ComputeRuntime { driver_version: capabilities.driver_version, }; let default_image = capabilities.default_image; + let gateway_listener_requirements = match driver + .get_gateway_listener_requirements(Request::new( + GetGatewayListenerRequirementsRequest {}, + )) + .await + { + Ok(response) => response + .into_inner() + .requirements + .into_iter() + .map(|requirement: ProtoGatewayListenerRequirement| { + let Some(selector) = requirement.selector else { + return Err(ComputeError::Message(format!( + "compute driver '{driver_name}' returned a gateway listener requirement without a selector" + ))); + }; + match selector { + Selector::ExactBindAddress(bind_address) => { + let address = bind_address.parse::().map_err(|err| { + ComputeError::Message(format!( + "compute driver '{driver_name}' returned invalid gateway listener address '{bind_address}': {err}" + )) + })?; + Ok(GatewayListenerRequirement::Exact { + address, + driver_name: driver_name.clone(), + reason: requirement.reason, + }) + } + Selector::DefaultRouteInterface(_) => { + Ok(GatewayListenerRequirement::DefaultRouteInterface { + driver_name: driver_name.clone(), + reason: requirement.reason, + }) + } + Selector::LoopbackInterface(_) => { + Ok(GatewayListenerRequirement::LoopbackInterface { + driver_name: driver_name.clone(), + reason: requirement.reason, + }) + } + } + }) + .collect::, ComputeError>>()?, + Err(status) if status.code() == Code::Unimplemented => { + debug!( + driver = %driver_name, + "Compute driver does not implement gateway listener requirements" + ); + Vec::new() + } + Err(status) => return Err(compute_error_from_status(status)), + }; Ok(Self { driver: TracedDriver::new(driver, driver_name), driver_info, @@ -503,7 +601,7 @@ impl ComputeRuntime { supervisor_sessions, sync_lock: Arc::new(Mutex::new(())), delete_gates: Arc::new(DeleteGateRegistry::default()), - gateway_bind_addresses, + gateway_listener_requirements, replica_id: lease::replica_id(), }) } @@ -547,7 +645,6 @@ impl ComputeRuntime { .await .map_err(|err| ComputeError::Message(err.to_string()))?, ); - let gateway_bind_addresses = driver.gateway_bind_addresses(); let shutdown_cleanup: Arc = driver.clone(); let startup_resume: Arc = driver.clone(); let driver: SharedComputeDriver = driver; @@ -562,7 +659,6 @@ impl ComputeRuntime { sandbox_watch_bus, tracing_log_bus, supervisor_sessions, - gateway_bind_addresses, ) .await } @@ -590,7 +686,6 @@ impl ComputeRuntime { sandbox_watch_bus, tracing_log_bus, supervisor_sessions, - Vec::new(), ) .await } @@ -615,7 +710,6 @@ impl ComputeRuntime { sandbox_watch_bus, tracing_log_bus, supervisor_sessions, - Vec::new(), ) .await } @@ -643,7 +737,6 @@ impl ComputeRuntime { sandbox_watch_bus, tracing_log_bus, supervisor_sessions, - Vec::new(), ) .await } @@ -664,8 +757,8 @@ impl ComputeRuntime { } #[must_use] - pub fn gateway_bind_addresses(&self) -> &[SocketAddr] { - &self.gateway_bind_addresses + pub(crate) fn gateway_listener_requirements(&self) -> &[GatewayListenerRequirement] { + &self.gateway_listener_requirements } pub async fn validate_sandbox_create(&self, sandbox: &Sandbox) -> Result<(), Status> { @@ -2932,6 +3025,15 @@ impl ComputeDriver for NoopTestDriver { )) } + async fn get_gateway_listener_requirements( + &self, + _request: Request, + ) -> Result, Status> { + Ok(tonic::Response::new( + GetGatewayListenerRequirementsResponse::default(), + )) + } + async fn validate_sandbox_create( &self, _request: Request, @@ -3027,7 +3129,7 @@ pub async fn new_test_runtime_for_driver(store: Arc, driver_name: &str) - supervisor_sessions: Arc::new(SupervisorSessionRegistry::new()), sync_lock: Arc::new(Mutex::new(())), delete_gates: Arc::new(DeleteGateRegistry::default()), - gateway_bind_addresses: Vec::new(), + gateway_listener_requirements: Vec::new(), replica_id: "test-replica".to_string(), } } @@ -3181,6 +3283,15 @@ mod tests { })) } + async fn get_gateway_listener_requirements( + &self, + _request: Request, + ) -> Result, Status> { + Ok(tonic::Response::new( + GetGatewayListenerRequirementsResponse::default(), + )) + } + async fn validate_sandbox_create( &self, _request: Request, @@ -3363,6 +3474,15 @@ mod tests { })) } + async fn get_gateway_listener_requirements( + &self, + _request: Request, + ) -> Result, Status> { + Ok(tonic::Response::new( + GetGatewayListenerRequirementsResponse::default(), + )) + } + async fn validate_sandbox_create( &self, _request: Request, @@ -3496,7 +3616,7 @@ mod tests { supervisor_sessions: Arc::new(SupervisorSessionRegistry::new()), sync_lock: Arc::new(Mutex::new(())), delete_gates: Arc::new(DeleteGateRegistry::default()), - gateway_bind_addresses: Vec::new(), + gateway_listener_requirements: Vec::new(), replica_id: "test-replica".to_string(), } } @@ -4102,12 +4222,12 @@ mod tests { async fn driver_calls_export_spans_with_parents() { use tracing::Instrument as _; - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; let runtime = test_runtime(Arc::new(TestDriver::default())).await; let sandbox = sandbox_record("sb-trace", "sandbox-trace", SandboxPhase::Provisioning); - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); async { runtime .create_sandbox(sandbox, None) @@ -4118,14 +4238,14 @@ mod tests { .await; let driver_span = traced.span_with("driver.create_sandbox", "sandbox.id", "sb-trace"); - test_collector::assert_has_parent(&driver_span); + test_exporter::assert_has_parent(&driver_span); assert_eq!( - test_collector::attribute(&driver_span, "driver.name").as_deref(), + test_exporter::attribute(&driver_span, "driver.name").as_deref(), Some("test-driver"), "the span names which driver was called" ); assert_eq!( - test_collector::attribute(&driver_span, "sandbox.id").as_deref(), + test_exporter::attribute(&driver_span, "sandbox.id").as_deref(), Some("sb-trace"), ); assert_eq!( @@ -4149,7 +4269,7 @@ mod tests { async fn failed_driver_calls_are_marked_on_the_span() { use tracing::Instrument as _; - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; /// A driver that behaves normally except that creates fail, so the /// test exercises only the failure attribute. @@ -4174,6 +4294,14 @@ mod tests { self.0.get_capabilities(request).await } + async fn get_gateway_listener_requirements( + &self, + request: Request, + ) -> Result, Status> + { + self.0.get_gateway_listener_requirements(request).await + } + async fn validate_sandbox_create( &self, request: Request, @@ -4223,7 +4351,7 @@ mod tests { let runtime = test_runtime(Arc::new(FailingDriver::default())).await; let sandbox = sandbox_record("sb-fail", "sandbox-fail", SandboxPhase::Provisioning); - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); async { runtime .create_sandbox(sandbox, None) @@ -4244,7 +4372,7 @@ mod tests { driver_span.status ); assert_eq!( - test_collector::attribute(&driver_span, "grpc.code").as_deref(), + test_exporter::attribute(&driver_span, "grpc.code").as_deref(), Some("14"), "the gRPC code names the cause without reading the message" ); @@ -6007,14 +6135,14 @@ mod tests { /// they trigger land outside the request that caused them. #[tokio::test] async fn driver_watch_events_are_roots_and_store_operations_have_parents() { - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; let runtime = test_runtime(Arc::new(TestDriver::default())).await; let sandbox = sandbox_record("sb-1", "sandbox-a", SandboxPhase::Ready); runtime.store.put_message(&sandbox).await.unwrap(); runtime.sandbox_index.update_from_sandbox(&sandbox); - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); runtime .apply_watch_event(deleted_watch_event("sb-1")) .await @@ -6031,9 +6159,9 @@ mod tests { ) }); - test_collector::assert_is_root(root); + test_exporter::assert_is_root(root); assert_eq!( - test_collector::attribute(root, "sandbox.id").as_deref(), + test_exporter::attribute(root, "sandbox.id").as_deref(), Some("sb-1"), "the span names which sandbox the driver reported on" ); @@ -6045,21 +6173,21 @@ mod tests { && span.span_context.trace_id() == root.span_context.trace_id() }) .expect("the event records its store operation"); - test_collector::assert_has_parent(store_span); + test_exporter::assert_has_parent(store_span); } /// The reconciler runs on a timer with no inbound request, so without a /// span of its own each store call becomes its own anonymous trace. #[tokio::test] async fn reconcile_sweeps_are_roots_and_operations_have_parents() { - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; let runtime = test_runtime(Arc::new(TestDriver::default())).await; let sandbox = sandbox_record("sb-1", "sandbox-a", SandboxPhase::Provisioning); runtime.store.put_message(&sandbox).await.unwrap(); runtime.sandbox_index.update_from_sandbox(&sandbox); - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); runtime .reconcile_store_with_backend(Duration::ZERO) .await @@ -6087,7 +6215,7 @@ mod tests { }) }) .expect("the sweep records its driver and store operations"); - test_collector::assert_is_root(root); + test_exporter::assert_is_root(root); let driver_span = spans .iter() @@ -6096,7 +6224,7 @@ mod tests { && span.span_context.trace_id() == root.span_context.trace_id() }) .expect("the sweep records its driver call"); - test_collector::assert_has_parent(driver_span); + test_exporter::assert_has_parent(driver_span); let store_span = spans .iter() .find(|span| { @@ -6104,7 +6232,7 @@ mod tests { && span.span_context.trace_id() == root.span_context.trace_id() }) .expect("the sweep records its store operation"); - test_collector::assert_has_parent(store_span); + test_exporter::assert_has_parent(store_span); } #[tokio::test] @@ -6516,10 +6644,10 @@ mod tests { #[tokio::test] async fn compute_driver_initialization_records_an_operation_span() { - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; let store = Arc::new(Store::connect("sqlite::memory:").await.unwrap()); - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); ComputeRuntime::from_driver( "test-driver".to_string(), Arc::new(TestDriver::default()), @@ -6531,13 +6659,12 @@ mod tests { SandboxWatchBus::new(), TracingLogBus::new(), Arc::new(SupervisorSessionRegistry::new()), - Vec::new(), ) .await .unwrap(); let initialization = traced.span_with("driver.initialize", "driver.name", "test-driver"); - test_collector::assert_is_root(&initialization); + test_exporter::assert_is_root(&initialization); } #[tokio::test] @@ -6549,7 +6676,11 @@ mod tests { let socket_path = dir.path().join("compute-driver.sock"); let driver = FakeComputeDriver::new() .with_driver_name("fake-remote-driver") - .with_default_image("openshell/sandbox:remote"); + .with_default_image("openshell/sandbox:remote") + .with_gateway_listener_requirement( + "172.19.0.1:17670", + "external driver managed bridge", + ); let _server = driver.serve_uds(&socket_path).unwrap(); let endpoint = connect_remote_compute_driver("external-test", &socket_path) @@ -6566,6 +6697,14 @@ mod tests { ) .await .unwrap(); + assert_eq!( + runtime.gateway_listener_requirements(), + &[GatewayListenerRequirement::Exact { + address: "172.19.0.1:17670".parse().unwrap(), + driver_name: "external-test".to_string(), + reason: "external driver managed bridge".to_string(), + }] + ); let mut sandbox = sandbox_record("sb-uds", "uds-sandbox", SandboxPhase::Provisioning); sandbox.spec = Some(SandboxSpec { @@ -6602,10 +6741,14 @@ mod tests { ); let calls = driver.calls(); - assert_eq!(calls.len(), 4, "unexpected calls: {calls:?}"); + assert_eq!(calls.len(), 5, "unexpected calls: {calls:?}"); assert!(matches!(calls[0], FakeComputeDriverCall::GetCapabilities)); + assert!(matches!( + calls[1], + FakeComputeDriverCall::GetGatewayListenerRequirements + )); - let validated = match &calls[1] { + let validated = match &calls[2] { FakeComputeDriverCall::ValidateSandboxCreate { sandbox: Some(sandbox), } => sandbox, @@ -6622,7 +6765,7 @@ mod tests { assert!(driver_config.fields.contains_key("pool")); assert!(!driver_config.fields.contains_key("network_mode")); - let created = match &calls[2] { + let created = match &calls[3] { FakeComputeDriverCall::CreateSandbox { sandbox: Some(sandbox), } => sandbox, @@ -6631,7 +6774,7 @@ mod tests { assert_eq!(created.id, "sb-uds"); assert_eq!(created.name, "uds-sandbox"); - match &calls[3] { + match &calls[4] { FakeComputeDriverCall::DeleteSandbox { sandbox_id, sandbox_name, @@ -6643,6 +6786,43 @@ mod tests { } } + #[tokio::test] + #[cfg(unix)] + async fn remote_compute_driver_accepts_unimplemented_listener_requirements_api() { + use crate::test_support::{FakeComputeDriver, FakeComputeDriverCall}; + + let dir = tempfile::tempdir().unwrap(); + let socket_path = dir.path().join("compute-driver.sock"); + let driver = FakeComputeDriver::new() + .with_driver_name("legacy-remote-driver") + .without_gateway_listener_requirements_api(); + let _server = driver.serve_uds(&socket_path).unwrap(); + + let endpoint = connect_remote_compute_driver("external-test", &socket_path) + .await + .unwrap(); + let store = Arc::new(Store::connect("sqlite::memory:").await.unwrap()); + let runtime = ComputeRuntime::new_remote_driver( + endpoint, + store, + SandboxIndex::new(), + SandboxWatchBus::new(), + TracingLogBus::new(), + Arc::new(SupervisorSessionRegistry::new()), + ) + .await + .unwrap(); + + assert!(runtime.gateway_listener_requirements().is_empty()); + assert_eq!( + driver.calls(), + vec![ + FakeComputeDriverCall::GetCapabilities, + FakeComputeDriverCall::GetGatewayListenerRequirements, + ] + ); + } + #[tokio::test] async fn create_sandbox_returns_resource_version_one() { let runtime = test_runtime(Arc::new(TestDriver::default())).await; diff --git a/crates/openshell-server/src/config_file.rs b/crates/openshell-server/src/config_file.rs index c29fd21657..72fcefaf9a 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -797,7 +797,8 @@ version = 2 /// `load()` path that the gateway uses at runtime, catching: /// - template corruption or unknown fields (`deny_unknown_fields`) /// - schema drift (version bump or field renames) - /// - accidental changes to the bind address or compute driver list + /// - accidental addition of a wildcard bind-address override + /// - accidental changes to the compute driver list #[test] fn rpm_default_config_parses_and_has_podman_defaults() { let path = @@ -806,20 +807,12 @@ version = 2 load(&path).expect("deploy/rpm/gateway.toml.default must parse against current schema"); let gw = &config.openshell.gateway; - let addr = gw - .bind_address - .expect("bind_address must be explicitly set in the RPM default config"); - assert!( - addr.ip().is_unspecified(), - "RPM default bind_address must be 0.0.0.0 so Podman sandbox containers \ - can reach the gateway over the host network bridge, got {addr}" - ); - assert_eq!( - addr.port(), - openshell_core::config::DEFAULT_SERVER_PORT, - "RPM default port must match DEFAULT_SERVER_PORT ({})", - openshell_core::config::DEFAULT_SERVER_PORT - ); + if let Some(addr) = gw.bind_address { + assert!( + !addr.ip().is_unspecified(), + "RPM default config must not expose the primary listener on every interface" + ); + } let drivers = gw .compute_drivers diff --git a/crates/openshell-server/src/gateway_listener.rs b/crates/openshell-server/src/gateway_listener.rs index 0957c4ebee..1db4c6cbca 100644 --- a/crates/openshell-server/src/gateway_listener.rs +++ b/crates/openshell-server/src/gateway_listener.rs @@ -1,8 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use openshell_core::{Error, Result}; -use std::net::SocketAddr; +use crate::compute::GatewayListenerRequirement; +use openshell_core::{ComputeDriverKind, Error, Result}; +use socket2::{Domain, Protocol, Socket, Type}; +use std::net::{IpAddr, SocketAddr}; use tokio::net::TcpListener; use tracing::info; @@ -24,6 +26,14 @@ pub struct GatewayListenerSpec { pub address: SocketAddr, pub scope: GatewayListenerScope, covered_addresses: Vec, + provenance: Option, +} + +/// Diagnostic source of a driver-requested listener. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct GatewayListenerProvenance { + pub driver_name: String, + pub reason: String, } /// A gateway listener together with the context needed to serve it. @@ -38,6 +48,7 @@ impl GatewayListenerSpec { address, scope, covered_addresses: Vec::new(), + provenance: None, } } @@ -59,52 +70,257 @@ impl GatewayListenerSpec { fn gateway_listener_specs( bind_address: SocketAddr, - extra_addresses: &[SocketAddr], -) -> Vec { + requirements: &[GatewayListenerRequirement], +) -> Result> { + let needs_default_route_resolution = requirements.iter().any(|requirement| { + matches!( + requirement, + GatewayListenerRequirement::DefaultRouteInterface { .. } + ) + }); + let default_route_ip = if needs_default_route_resolution { + Some(gateway_default_route_ip()?) + } else { + None + }; + gateway_listener_specs_with_default_route_ip(bind_address, requirements, default_route_ip) +} + +fn gateway_listener_specs_with_default_route_ip( + bind_address: SocketAddr, + requirements: &[GatewayListenerRequirement], + default_route_ip: Option, +) -> Result> { let mut specs = vec![GatewayListenerSpec::new( bind_address, GatewayListenerScope::Primary, )]; - for address in extra_addresses { - let scope = GatewayListenerScope::ComputeDriverCallback; - if let Some(existing) = specs + + // Resolve exact requirements first so they can satisfy a later semantic + // requirement regardless of driver response ordering. + for requirement in requirements { + let GatewayListenerRequirement::Exact { address, .. } = requirement else { + continue; + }; + validate_gateway_listener_requirement(bind_address, requirement)?; + add_callback_listener_spec(&mut specs, *address, requirement)?; + } + + for requirement in requirements { + let GatewayListenerRequirement::DefaultRouteInterface { .. } = requirement else { + continue; + }; + validate_gateway_listener_requirement(bind_address, requirement)?; + let Some(ip) = default_route_ip else { + return Err(Error::config(format!( + "compute driver '{}' requested the gateway default-route interface, but no IPv4 source address was resolved (reason: {})", + requirement.driver_name(), + requirement.reason() + ))); + }; + if !gateway_default_route_ip_is_usable(ip) { + return Err(Error::config(format!( + "compute driver '{}' requested the gateway default-route interface, but its resolved address {ip} is not a private IPv4 address (reason: {})", + requirement.driver_name(), + requirement.reason() + ))); + } + let address = SocketAddr::new(ip, bind_address.port()); + validate_resolved_gateway_listener(bind_address, address)?; + add_callback_listener_spec(&mut specs, address, requirement)?; + } + + for requirement in requirements { + let GatewayListenerRequirement::LoopbackInterface { .. } = requirement else { + continue; + }; + validate_gateway_listener_requirement(bind_address, requirement)?; + let address = SocketAddr::from(([127, 0, 0, 1], bind_address.port())); + validate_resolved_gateway_listener(bind_address, address)?; + add_callback_listener_spec(&mut specs, address, requirement)?; + } + + Ok(specs) +} + +fn add_callback_listener_spec( + specs: &mut Vec, + address: SocketAddr, + requirement: &GatewayListenerRequirement, +) -> Result<()> { + let scope = GatewayListenerScope::ComputeDriverCallback; + if let Some(existing) = specs + .iter_mut() + .find(|existing| listener_covers(existing.address, address)) + { + if existing.address == address { + if existing.scope == GatewayListenerScope::Primary { + return Err(Error::config(format!( + "compute driver '{}' requested gateway callback listener {address}, but it is the same address as the primary listener; callback-only authorization cannot be preserved", + requirement.driver_name() + ))); + } + return Ok(()); + } + if !existing + .covered_addresses .iter() - .position(|existing| listener_covers(existing.address, *address)) + .any(|covered| covered.address == address) { - let existing = &mut specs[existing]; - if existing.address != *address - && !existing - .covered_addresses - .iter() - .any(|covered| covered.address == *address) - { - existing.covered_addresses.push(CoveredGatewayAddress { - address: *address, - scope, - }); - } - } else { - specs.push(GatewayListenerSpec::new(*address, scope)); + existing + .covered_addresses + .push(CoveredGatewayAddress { address, scope }); } + return Ok(()); } - specs + specs.push(callback_listener_spec(address, requirement)); + Ok(()) +} + +fn callback_listener_spec( + address: SocketAddr, + requirement: &GatewayListenerRequirement, +) -> GatewayListenerSpec { + GatewayListenerSpec { + address, + scope: GatewayListenerScope::ComputeDriverCallback, + covered_addresses: Vec::new(), + provenance: Some(GatewayListenerProvenance { + driver_name: requirement.driver_name().to_string(), + reason: requirement.reason().to_string(), + }), + } +} + +fn validate_gateway_listener_requirement( + primary_listener: SocketAddr, + requirement: &GatewayListenerRequirement, +) -> Result<()> { + match requirement { + GatewayListenerRequirement::Exact { + address, + driver_name, + .. + } if driver_name == ComputeDriverKind::Docker.as_str() + || driver_name == ComputeDriverKind::Podman.as_str() => + { + validate_resolved_gateway_listener(primary_listener, *address) + } + GatewayListenerRequirement::DefaultRouteInterface { driver_name, .. } + | GatewayListenerRequirement::LoopbackInterface { driver_name, .. } + if driver_name == ComputeDriverKind::Podman.as_str() => + { + Ok(()) + } + _ => Err(Error::config(format!( + "compute driver '{}' is not authorized to request this gateway listener selector", + requirement.driver_name() + ))), + } +} + +fn validate_resolved_gateway_listener( + primary_listener: SocketAddr, + requested_listener: SocketAddr, +) -> Result<()> { + if requested_listener.ip().is_unspecified() { + return Err(Error::config(format!( + "compute driver requested wildcard gateway listener {requested_listener}" + ))); + } + if requested_listener.ip().is_multicast() { + return Err(Error::config(format!( + "compute driver requested multicast gateway listener {requested_listener}" + ))); + } + if requested_listener.port() == 0 { + return Err(Error::config(format!( + "compute driver requested zero-port gateway listener {requested_listener}" + ))); + } + if requested_listener.port() != primary_listener.port() { + return Err(Error::config(format!( + "compute driver requested gateway listener {requested_listener} with port {}, but the primary listener uses port {}", + requested_listener.port(), + primary_listener.port() + ))); + } + Ok(()) +} + +fn gateway_default_route_ip_is_usable(address: IpAddr) -> bool { + matches!(address, IpAddr::V4(address) if address.is_private()) +} + +#[cfg(target_os = "linux")] +fn gateway_default_route_ip() -> Result { + // UDP connect performs a local route lookup without sending a packet. The + // selected source address follows the IPv4 default route, matching pasta's + // default upstream-interface selection. + let socket = + std::net::UdpSocket::bind((std::net::Ipv4Addr::UNSPECIFIED, 0)).map_err(|err| { + Error::config(format!("failed to open default-route probe socket: {err}")) + })?; + socket + .connect((std::net::Ipv4Addr::new(192, 0, 2, 1), 9)) + .map_err(|err| Error::config(format!("failed to resolve IPv4 default route: {err}")))?; + socket + .local_addr() + .map(|address| address.ip()) + .map_err(|err| Error::config(format!("failed to read IPv4 default-route address: {err}"))) +} + +#[cfg(not(target_os = "linux"))] +fn gateway_default_route_ip() -> Result { + Err(Error::config( + "default-route gateway listener requirements are supported only on Linux", + )) } pub async fn bind_gateway_listeners( bind_address: SocketAddr, - extra_addresses: &[SocketAddr], + requirements: &[GatewayListenerRequirement], ) -> Result> { - let specs = gateway_listener_specs(bind_address, extra_addresses); + let specs = gateway_listener_specs(bind_address, requirements)?; let mut listeners = Vec::with_capacity(specs.len()); - for spec in specs { - let listener = TcpListener::bind(spec.address) + for spec in &specs { + let ipv6_only = matches!( + spec.address.ip(), + IpAddr::V6(address) if address.is_unspecified() + ) && specs.iter().any(|candidate| { + candidate.address.port() == spec.address.port() && candidate.address.is_ipv4() + }); + let listener = bind_gateway_listener(spec.address, ipv6_only) .await .map_err(|e| Error::transport(format!("failed to bind to {}: {e}", spec.address)))?; let local_addr = listener.local_addr().unwrap_or(spec.address); - info!(address = %local_addr, "Server listening"); + match spec.scope { + GatewayListenerScope::Primary => { + info!( + address = %local_addr, + listener_purpose = "primary", + authorization_scope = "full-multiplexed-api", + "Gateway listener bound" + ); + } + GatewayListenerScope::ComputeDriverCallback => { + let provenance = spec + .provenance + .as_ref() + .expect("callback listener spec must include provenance"); + info!( + address = %local_addr, + listener_purpose = "compute-driver-callback", + driver = %provenance.driver_name, + reason = %provenance.reason, + authorization_scope = "sandbox-callable-grpc-only", + "Gateway listener bound" + ); + } + } listeners.push(BoundGatewayListener { listener, - spec: spec.bind_to(local_addr), + spec: spec.clone().bind_to(local_addr), }); } Ok(listeners) @@ -140,6 +356,24 @@ fn resolve_ephemeral_port( } } +async fn bind_gateway_listener( + address: SocketAddr, + ipv6_only: bool, +) -> std::io::Result { + if ipv6_only { + let socket = Socket::new(Domain::IPV6, Type::STREAM, Some(Protocol::TCP))?; + socket.set_reuse_address(true)?; + socket.set_only_v6(true)?; + socket.set_nonblocking(true)?; + socket.bind(&address.into())?; + socket.listen(1024)?; + let listener: std::net::TcpListener = socket.into(); + return TcpListener::from_std(listener); + } + + TcpListener::bind(address).await +} + fn listener_covers(existing: SocketAddr, requested: SocketAddr) -> bool { if existing == requested { return true; @@ -149,8 +383,8 @@ fn listener_covers(existing: SocketAddr, requested: SocketAddr) -> bool { } match (existing.ip(), requested.ip()) { - (std::net::IpAddr::V4(existing), std::net::IpAddr::V4(_)) => existing.is_unspecified(), - (std::net::IpAddr::V6(existing), std::net::IpAddr::V6(_)) => existing.is_unspecified(), + (IpAddr::V4(existing), IpAddr::V4(_)) => existing.is_unspecified(), + (IpAddr::V6(existing), IpAddr::V6(_)) => existing.is_unspecified(), _ => false, } } @@ -158,9 +392,11 @@ fn listener_covers(existing: SocketAddr, requested: SocketAddr) -> bool { #[cfg(test)] mod tests { use super::{ - CoveredGatewayAddress, GatewayListenerScope, GatewayListenerSpec, bind_gateway_listeners, - gateway_listener_specs, + CoveredGatewayAddress, GatewayListenerProvenance, GatewayListenerScope, + GatewayListenerSpec, bind_gateway_listeners, gateway_listener_specs, + gateway_listener_specs_with_default_route_ip, }; + use crate::compute::GatewayListenerRequirement; use std::net::SocketAddr; use std::sync::atomic::{AtomicBool, Ordering}; use tokio::net::TcpListener; @@ -169,9 +405,13 @@ mod tests { fn gateway_listener_specs_track_driver_address_covered_by_wildcard() { let primary: SocketAddr = "0.0.0.0:8080".parse().unwrap(); let docker: SocketAddr = "172.18.0.1:8080".parse().unwrap(); + let requirements = [ + docker_listener_requirement(docker), + docker_listener_requirement(docker), + ]; assert_eq!( - gateway_listener_specs(primary, &[docker, docker]), + gateway_listener_specs(primary, &requirements).unwrap(), vec![GatewayListenerSpec { address: primary, scope: GatewayListenerScope::Primary, @@ -179,6 +419,7 @@ mod tests { address: docker, scope: GatewayListenerScope::ComputeDriverCallback, }], + provenance: None, }] ); } @@ -188,7 +429,8 @@ mod tests { let primary: SocketAddr = "0.0.0.0:8080".parse().unwrap(); let docker: SocketAddr = "172.18.0.1:8080".parse().unwrap(); let loopback: SocketAddr = "127.0.0.1:8080".parse().unwrap(); - let [spec] = gateway_listener_specs(primary, &[docker]) + let [spec] = gateway_listener_specs(primary, &[docker_listener_requirement(docker)]) + .unwrap() .try_into() .unwrap(); @@ -206,24 +448,210 @@ mod tests { fn gateway_listener_specs_preserve_driver_callback_scope() { let primary: SocketAddr = "127.0.0.1:8080".parse().unwrap(); let docker: SocketAddr = "172.18.0.1:8080".parse().unwrap(); + let requirements = [ + docker_listener_requirement(docker), + docker_listener_requirement(docker), + ]; assert_eq!( - gateway_listener_specs(primary, &[docker, docker]), + gateway_listener_specs(primary, &requirements).unwrap(), vec![ GatewayListenerSpec { address: primary, scope: GatewayListenerScope::Primary, covered_addresses: Vec::new(), + provenance: None, }, GatewayListenerSpec { address: docker, scope: GatewayListenerScope::ComputeDriverCallback, covered_addresses: Vec::new(), + provenance: Some(GatewayListenerProvenance { + driver_name: "docker".to_string(), + reason: "managed bridge".to_string(), + }), }, ] ); } + #[test] + fn gateway_listener_specs_reject_unauthorized_external_driver() { + let primary: SocketAddr = "127.0.0.1:8080".parse().unwrap(); + let requirement = GatewayListenerRequirement::Exact { + address: "172.18.0.1:8080".parse().unwrap(), + driver_name: "external-test".to_string(), + reason: "external bridge".to_string(), + }; + + let err = gateway_listener_specs(primary, &[requirement]).unwrap_err(); + assert!(err.to_string().contains("not authorized")); + } + + #[test] + fn gateway_listener_specs_reject_invalid_exact_addresses() { + let primary: SocketAddr = "127.0.0.1:8080".parse().unwrap(); + for address in [ + "0.0.0.0:8080", + "224.0.0.1:8080", + "172.18.0.1:0", + "172.18.0.1:9090", + ] { + let requirement = docker_listener_requirement(address.parse().unwrap()); + assert!( + gateway_listener_specs(primary, &[requirement]).is_err(), + "{address} should be rejected" + ); + } + } + + #[test] + fn gateway_listener_specs_use_exact_podman_network_gateway() { + let primary: SocketAddr = "127.0.0.1:8080".parse().unwrap(); + let podman_gateway: SocketAddr = "10.89.1.1:8080".parse().unwrap(); + + assert_eq!( + gateway_listener_specs(primary, &[podman_listener_requirement(podman_gateway)]) + .unwrap(), + vec![ + primary_listener_spec(primary), + callback_listener_spec(podman_gateway, "podman", "Podman managed bridge",), + ] + ); + } + + #[test] + fn gateway_listener_specs_track_podman_exact_when_primary_covers_it() { + let primary: SocketAddr = "0.0.0.0:8080".parse().unwrap(); + let podman_gateway: SocketAddr = "10.89.1.1:8080".parse().unwrap(); + + assert_eq!( + gateway_listener_specs(primary, &[podman_listener_requirement(podman_gateway)],) + .unwrap(), + vec![primary_listener_spec_with_covered(primary, podman_gateway,)] + ); + } + + #[test] + fn gateway_listener_specs_resolve_podman_default_route_source() { + let primary: SocketAddr = "127.0.0.1:8080".parse().unwrap(); + let default_route_ip = "192.168.20.20".parse().unwrap(); + + assert_eq!( + gateway_listener_specs_with_default_route_ip( + primary, + &[podman_default_route_listener_requirement()], + Some(default_route_ip), + ) + .unwrap(), + vec![ + primary_listener_spec(primary), + callback_listener_spec( + "192.168.20.20:8080".parse().unwrap(), + "podman", + "rootless pasta upstream interface", + ), + ] + ); + } + + #[test] + fn gateway_listener_specs_reject_public_default_route_source() { + let primary: SocketAddr = "127.0.0.1:8080".parse().unwrap(); + + let err = gateway_listener_specs_with_default_route_ip( + primary, + &[podman_default_route_listener_requirement()], + Some("203.0.113.20".parse().unwrap()), + ) + .unwrap_err(); + + assert!(err.to_string().contains("not a private IPv4 address")); + } + + #[test] + fn gateway_listener_specs_track_default_route_when_primary_is_ipv4_wildcard() { + let primary: SocketAddr = "0.0.0.0:8080".parse().unwrap(); + let default_route_ip = "192.168.20.20".parse().unwrap(); + let callback = "192.168.20.20:8080".parse().unwrap(); + + assert_eq!( + gateway_listener_specs_with_default_route_ip( + primary, + &[podman_default_route_listener_requirement()], + Some(default_route_ip), + ) + .unwrap(), + vec![primary_listener_spec_with_covered(primary, callback)] + ); + } + + #[test] + fn gateway_listener_specs_resolve_podman_loopback_separately() { + let primary: SocketAddr = "192.168.20.20:8080".parse().unwrap(); + + assert_eq!( + gateway_listener_specs(primary, &[podman_loopback_listener_requirement()]).unwrap(), + vec![ + primary_listener_spec(primary), + callback_listener_spec( + "127.0.0.1:8080".parse().unwrap(), + "podman", + "Podman machine host forwarder", + ), + ] + ); + } + + #[test] + fn gateway_listener_specs_track_podman_loopback_when_wildcard_primary_covers_it() { + let primary = "0.0.0.0:8080".parse().unwrap(); + let loopback = "127.0.0.1:8080".parse().unwrap(); + + assert_eq!( + gateway_listener_specs(primary, &[podman_loopback_listener_requirement()]).unwrap(), + vec![primary_listener_spec_with_covered(primary, loopback)] + ); + } + + #[test] + fn gateway_listener_specs_reject_callback_matching_primary_address() { + let primary = "127.0.0.1:8080".parse().unwrap(); + + let err = + gateway_listener_specs(primary, &[podman_loopback_listener_requirement()]).unwrap_err(); + + assert!( + err.to_string() + .contains("same address as the primary listener") + ); + assert!(err.to_string().contains("callback-only authorization")); + } + + #[test] + fn gateway_listener_specs_do_not_use_ipv6_listener_for_ipv4_loopback_requirement() { + for primary in ["[::1]:8080", "[::]:8080"] { + let primary = primary.parse().unwrap(); + let specs = + gateway_listener_specs(primary, &[podman_loopback_listener_requirement()]).unwrap(); + + assert_eq!(specs.len(), 2); + assert_eq!(specs[1].address, SocketAddr::from(([127, 0, 0, 1], 8080))); + } + } + + #[test] + fn gateway_listener_specs_reject_cross_driver_selector_authority() { + let primary: SocketAddr = "127.0.0.1:8080".parse().unwrap(); + let requirement = GatewayListenerRequirement::LoopbackInterface { + driver_name: "docker".to_string(), + reason: "wrong selector".to_string(), + }; + + let err = gateway_listener_specs(primary, &[requirement]).unwrap_err(); + assert!(err.to_string().contains("not authorized")); + } + #[tokio::test] async fn failed_bind_does_not_return_partially_bound_listeners() { let occupied_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -232,7 +660,11 @@ mod tests { let primary_address: SocketAddr = "127.0.0.1:0".parse().unwrap(); let result: openshell_core::Result<()> = async { - let _listeners = bind_gateway_listeners(primary_address, &[occupied_address]).await?; + let _listeners = bind_gateway_listeners( + primary_address, + &[docker_listener_requirement(occupied_address)], + ) + .await?; continuation_reached.store(true, Ordering::SeqCst); Ok(()) } @@ -247,4 +679,96 @@ mod tests { "binding must fail before returning a partial listener set" ); } + + #[tokio::test] + #[cfg(target_os = "linux")] + async fn gateway_listeners_bind_ipv6_wildcard_and_ipv4_callback_on_same_port() { + let probe = TcpListener::bind("[::1]:0") + .await + .expect("IPv6 loopback probe should bind"); + let port = probe.local_addr().unwrap().port(); + drop(probe); + + let primary = format!("[::]:{port}").parse().unwrap(); + let listeners = bind_gateway_listeners(primary, &[podman_loopback_listener_requirement()]) + .await + .expect("IPv6 wildcard and IPv4 callback listeners should both bind"); + + assert_eq!(listeners.len(), 2); + assert_eq!(listeners[0].spec.address, primary); + assert_eq!( + listeners[1].spec.address, + SocketAddr::from(([127, 0, 0, 1], port)) + ); + } + + fn docker_listener_requirement(address: SocketAddr) -> GatewayListenerRequirement { + GatewayListenerRequirement::Exact { + address, + driver_name: "docker".to_string(), + reason: "managed bridge".to_string(), + } + } + + fn podman_listener_requirement(address: SocketAddr) -> GatewayListenerRequirement { + GatewayListenerRequirement::Exact { + address, + driver_name: "podman".to_string(), + reason: "Podman managed bridge".to_string(), + } + } + + fn podman_default_route_listener_requirement() -> GatewayListenerRequirement { + GatewayListenerRequirement::DefaultRouteInterface { + driver_name: "podman".to_string(), + reason: "rootless pasta upstream interface".to_string(), + } + } + + fn podman_loopback_listener_requirement() -> GatewayListenerRequirement { + GatewayListenerRequirement::LoopbackInterface { + driver_name: "podman".to_string(), + reason: "Podman machine host forwarder".to_string(), + } + } + + fn primary_listener_spec(address: SocketAddr) -> GatewayListenerSpec { + GatewayListenerSpec { + address, + scope: GatewayListenerScope::Primary, + covered_addresses: Vec::new(), + provenance: None, + } + } + + fn primary_listener_spec_with_covered( + address: SocketAddr, + covered_address: SocketAddr, + ) -> GatewayListenerSpec { + GatewayListenerSpec { + address, + scope: GatewayListenerScope::Primary, + covered_addresses: vec![CoveredGatewayAddress { + address: covered_address, + scope: GatewayListenerScope::ComputeDriverCallback, + }], + provenance: None, + } + } + + fn callback_listener_spec( + address: SocketAddr, + driver_name: &str, + reason: &str, + ) -> GatewayListenerSpec { + GatewayListenerSpec { + address, + scope: GatewayListenerScope::ComputeDriverCallback, + covered_addresses: Vec::new(), + provenance: Some(GatewayListenerProvenance { + driver_name: driver_name.to_string(), + reason: reason.to_string(), + }), + } + } } diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 405932f037..8dc385e889 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -2570,7 +2570,7 @@ mod tests { #[tokio::test] async fn watch_producer_releases_request_span_when_client_disconnects() { - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; use tokio_stream::StreamExt as _; use tracing::Instrument as _; @@ -2578,7 +2578,7 @@ mod tests { let sandbox = test_sandbox("watched", Vec::new()); state.store.put_message(&sandbox).await.unwrap(); - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); let request_span = tracing::info_span!("disconnected_watch_request"); let response = handle_watch_sandbox( &state, diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 288b491662..1ab9e1ada1 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -78,8 +78,6 @@ pub(crate) static TEST_ENV_LOCK: LazyLock> = LazyLock::new(|| Mutex::n pub(crate) static TEST_TRACING_LOCK: LazyLock> = LazyLock::new(|| Mutex::new(())); use compute::ComputeRuntime; -#[cfg(test)] -use gateway_listener::GatewayListenerSpec; use gateway_listener::{BoundGatewayListener, GatewayListenerScope, bind_gateway_listeners}; pub use grpc::OpenShellService; pub use http::{health_router, http_router, metrics_router, service_http_router}; @@ -449,8 +447,11 @@ pub(crate) async fn run_server( // snapshot on its first poll. ensure_default_workspace(&store).await?; - let gateway_listeners = - bind_gateway_listeners(config.bind_address, state.compute.gateway_bind_addresses()).await?; + let gateway_listeners = bind_gateway_listeners( + config.bind_address, + state.compute.gateway_listener_requirements(), + ) + .await?; if let Err(err) = state.compute.resume_persisted_sandboxes().await { warn!(error = %err, "Failed to resume persisted sandboxes during startup"); @@ -662,8 +663,12 @@ fn allow_plaintext_service_http( enabled: bool, listen_addr: SocketAddr, peer_addr: SocketAddr, + listener_scope: GatewayListenerScope, ) -> bool { - enabled && listen_addr.ip().is_loopback() && peer_addr.ip().is_loopback() + enabled + && matches!(listener_scope, GatewayListenerScope::Primary) + && listen_addr.ip().is_loopback() + && peer_addr.ip().is_loopback() } fn spawn_gateway_connection( @@ -683,6 +688,7 @@ fn spawn_gateway_connection( enable_loopback_service_http, listen_addr, addr, + listener_scope, ) => { if let Err(e) = service @@ -697,7 +703,12 @@ fn spawn_gateway_connection( } } Ok(ConnectionProtocol::PlainHttp) => { - warn!(client = %addr, listen = %listen_addr, "Rejected plaintext HTTP on non-loopback gateway listener"); + warn!( + client = %addr, + listen = %listen_addr, + scope = ?listener_scope, + "Rejected plaintext HTTP on gateway listener" + ); } Ok(ConnectionProtocol::Tls | ConnectionProtocol::Unknown) => { // acceptor.acceptor() snapshots the current TLS config; @@ -1015,10 +1026,10 @@ pub(crate) async fn ensure_default_workspace(store: &Store) -> Result<()> { mod tests { use super::{ BoundGatewayListener, ConfiguredComputeDriver, ConnectionProtocol, GatewayListenerScope, - GatewayListenerSpec, MultiplexService, ServerState, TlsAcceptor, - allow_plaintext_service_http, bind_gateway_listeners, classify_initial_bytes, - configured_compute_driver, is_benign_tls_handshake_failure, - kubernetes_sandbox_jwt_expiry_disabled, serve_gateway_listener, + MultiplexService, ServerState, TlsAcceptor, allow_plaintext_service_http, + bind_gateway_listeners, classify_initial_bytes, configured_compute_driver, + is_benign_tls_handshake_failure, kubernetes_sandbox_jwt_expiry_disabled, + serve_gateway_listener, }; use openshell_core::{ ComputeDriverKind, Config, @@ -1036,7 +1047,11 @@ mod tests { use tokio::net::{TcpListener, TcpStream}; use tokio::sync::watch; - use crate::tls_test_utils::{generate_test_certs_with_ca, install_rustls_provider}; + use crate::{ + compute::GatewayListenerRequirement, + gateway_listener::GatewayListenerSpec, + tls_test_utils::{generate_test_certs_with_ca, install_rustls_provider}, + }; fn test_driver_startup<'a>( config: &'a Config, @@ -1212,11 +1227,23 @@ mod tests { let peer: SocketAddr = "127.0.0.1:54000".parse().unwrap(); let wildcard: SocketAddr = "0.0.0.0:8080".parse().unwrap(); let remote_peer: SocketAddr = "192.0.2.10:54000".parse().unwrap(); + let primary = GatewayListenerScope::Primary; + let callback = GatewayListenerScope::ComputeDriverCallback; - assert!(allow_plaintext_service_http(true, loopback, peer)); - assert!(!allow_plaintext_service_http(false, loopback, peer)); - assert!(!allow_plaintext_service_http(true, wildcard, peer)); - assert!(!allow_plaintext_service_http(true, loopback, remote_peer)); + assert!(allow_plaintext_service_http(true, loopback, peer, primary)); + assert!(!allow_plaintext_service_http( + false, loopback, peer, primary + )); + assert!(!allow_plaintext_service_http(true, wildcard, peer, primary)); + assert!(!allow_plaintext_service_http( + true, + loopback, + remote_peer, + primary + )); + assert!(!allow_plaintext_service_http( + true, loopback, peer, callback + )); } #[tokio::test] @@ -1501,7 +1528,11 @@ mod tests { let primary_address: SocketAddr = "127.0.0.1:0".parse().unwrap(); let result: openshell_core::Result<()> = async { - let _listeners = bind_gateway_listeners(primary_address, &[occupied_address]).await?; + let _listeners = bind_gateway_listeners( + primary_address, + &[docker_listener_requirement(occupied_address)], + ) + .await?; resume_attempted.store(true, Ordering::SeqCst); Ok(()) } @@ -1516,4 +1547,12 @@ mod tests { "persisted sandbox resume must not run before every gateway listener is bound" ); } + + fn docker_listener_requirement(address: SocketAddr) -> GatewayListenerRequirement { + GatewayListenerRequirement::Exact { + address, + driver_name: "docker".to_string(), + reason: "managed bridge".to_string(), + } + } } diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index b8c0d77439..bf06d2c537 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -7,7 +7,7 @@ //! to either the gRPC service or HTTP endpoints based on the request headers. use bytes::{Bytes, BytesMut}; -use http::{Extensions, HeaderValue, Request, Response}; +use http::{Extensions, HeaderValue, Request, Response, StatusCode}; use http_body::Body; use http_body_util::{BodyExt, Full, LengthLimitError, Limited, StreamBody}; use hyper::body::Incoming; @@ -234,7 +234,7 @@ impl MultiplexService { .await } - /// Serve a connection and preserve its listener purpose in request + /// Serve a connection and preserve its listener scope in request /// extensions for downstream routing and policy decisions. pub(crate) async fn serve_on_listener( &self, @@ -265,7 +265,7 @@ impl MultiplexService { .await } - /// Serve a TLS connection and preserve its listener purpose in request + /// Serve a TLS connection and preserve its listener scope in request /// extensions for downstream routing and policy decisions. pub(crate) async fn serve_with_peer_identity_on_listener( &self, @@ -345,7 +345,7 @@ impl MultiplexService { } /// Serve a plaintext service HTTP connection and preserve its listener - /// purpose in request extensions. + /// scope in request extensions. pub(crate) async fn serve_service_http_on_listener( &self, stream: S, @@ -1080,6 +1080,38 @@ impl MultiplexedService { } } +fn listener_allows_request( + listener_scope: Option<&GatewayListenerScope>, + is_grpc: bool, + path: &str, +) -> bool { + match listener_scope { + Some(GatewayListenerScope::ComputeDriverCallback) => { + is_grpc && crate::auth::sandbox_methods::is_sandbox_callable(path) + } + Some(GatewayListenerScope::Primary) | None => true, + } +} + +fn callback_listener_rejection(is_grpc: bool) -> Response { + if is_grpc { + let response: Response = tonic::Status::permission_denied( + "compute-driver callback listeners accept sandbox callback RPCs only", + ) + .into_http(); + let (parts, body) = response.into_parts(); + let body = body.map_err(Into::into).boxed_unsync(); + Response::from_parts(parts, BoxBody(body)) + } else { + Response::builder() + .status(StatusCode::FORBIDDEN) + .body(boxed_body_from_bytes(Bytes::from_static( + b"compute-driver callback listeners accept gRPC callbacks only", + ))) + .expect("static callback listener rejection response must be valid") + } +} + impl hyper::service::Service> for MultiplexedService where G: tower::Service, Response = Response> + Clone + Send + 'static, @@ -1103,6 +1135,15 @@ where .get("content-type") .is_some_and(|v| v.as_bytes().starts_with(b"application/grpc")); + if !listener_allows_request( + req.extensions().get::(), + is_grpc, + req.uri().path(), + ) { + let response = callback_listener_rejection(is_grpc); + return Box::pin(async move { Ok(response) }); + } + if is_grpc { let method = grpc_method_from_path(req.uri().path()); let start = Instant::now(); @@ -1321,6 +1362,98 @@ mod tests { ); } + fn callback_listener_scope() -> GatewayListenerScope { + GatewayListenerScope::ComputeDriverCallback + } + + #[test] + fn callback_listener_allows_sandbox_callback_rpcs() { + let scope = callback_listener_scope(); + let callback_paths = [ + "/openshell.v1.OpenShell/ConnectSupervisor", + "/openshell.v1.OpenShell/RelayStream", + "/openshell.v1.OpenShell/GetSandboxConfig", + "/openshell.v1.OpenShell/ReportPolicyStatus", + "/openshell.v1.OpenShell/PushSandboxLogs", + "/openshell.v1.OpenShell/GetSandboxProviderEnvironment", + "/openshell.v1.OpenShell/SubmitPolicyAnalysis", + "/openshell.v1.OpenShell/RefreshSandboxToken", + "/openshell.inference.v1.Inference/GetInferenceBundle", + ]; + + for path in callback_paths { + assert!( + listener_allows_request(Some(&scope), true, path), + "callback listener should allow {path}" + ); + } + } + + #[test] + fn callback_listener_surface_matches_rpc_auth_metadata() { + let scope = callback_listener_scope(); + + for path in crate::auth::method_authz::all_paths() { + assert_eq!( + listener_allows_request(Some(&scope), true, path), + crate::auth::method_authz::is_sandbox_callable(path), + "callback listener exposure must follow rpc_auth metadata for {path}" + ); + } + } + + #[test] + fn callback_listener_rejects_non_callback_routes() { + let scope = callback_listener_scope(); + let rejected_grpc_paths = [ + "/grpc.health.v1.Health/Check", + "/grpc.reflection.v1.ServerReflection/ServerReflectionInfo", + "/openshell.v1.OpenShell/ListSandboxes", + "/openshell.v1.OpenShell/DeleteSandbox", + "/openshell.v1.OpenShell/CreateProvider", + "/openshell.inference.v1.Inference/GetInferenceRoute", + "/openshell.inference.v1.Inference/SetInferenceRoute", + ]; + + for path in rejected_grpc_paths { + assert!( + !listener_allows_request(Some(&scope), true, path), + "callback listener should reject {path}" + ); + } + assert!(!listener_allows_request(Some(&scope), false, "/health")); + assert!(!listener_allows_request(Some(&scope), false, "/service")); + } + + #[test] + fn primary_listener_routing_is_unchanged() { + let primary = GatewayListenerScope::Primary; + let paths = [ + "/grpc.health.v1.Health/Check", + "/openshell.v1.OpenShell/ListSandboxes", + "/openshell.inference.v1.Inference/GetInferenceRoute", + "/health", + "/service", + ]; + + for path in paths { + assert!(listener_allows_request(Some(&primary), true, path)); + assert!(listener_allows_request(Some(&primary), false, path)); + assert!(listener_allows_request(None, true, path)); + assert!(listener_allows_request(None, false, path)); + } + } + + #[test] + fn callback_listener_rejections_use_protocol_appropriate_statuses() { + let grpc = callback_listener_rejection(true); + assert_eq!(grpc.status(), StatusCode::OK); + assert_eq!(grpc.headers().get("grpc-status").unwrap(), "7"); + + let http = callback_listener_rejection(false); + assert_eq!(http.status(), StatusCode::FORBIDDEN); + } + #[derive(Clone)] struct PostCommitTestInterceptor; @@ -1422,6 +1555,12 @@ mod tests { } async fn start_http_server_with_middleware() -> std::net::SocketAddr { + start_http_server_with_middleware_on_listener(GatewayListenerScope::Primary).await + } + + async fn start_http_server_with_middleware_on_listener( + listener_scope: GatewayListenerScope, + ) -> std::net::SocketAddr { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); @@ -1429,6 +1568,7 @@ mod tests { let http_service = request_id_middleware!(http_service); let service = MultiplexedService::new(http_service.clone(), http_service); + let service = GatewayListenerContextService::new(service, listener_scope); tokio::spawn(async move { loop { @@ -1447,8 +1587,9 @@ mod tests { addr } - async fn http1_get( + async fn http1_request( addr: std::net::SocketAddr, + method: &str, path: &str, headers: &[(&str, &str)], ) -> Response { @@ -1462,7 +1603,7 @@ mod tests { }); let mut builder = Request::builder() - .method("GET") + .method(method) .uri(format!("http://{addr}{path}")); for (k, v) in headers { builder = builder.header(*k, *v); @@ -1471,6 +1612,47 @@ mod tests { sender.send_request(req).await.unwrap() } + async fn http1_get( + addr: std::net::SocketAddr, + path: &str, + headers: &[(&str, &str)], + ) -> Response { + http1_request(addr, "GET", path, headers).await + } + + #[tokio::test] + async fn callback_listener_filter_is_applied_before_route_dispatch() { + let addr = start_http_server_with_middleware_on_listener(callback_listener_scope()).await; + + let health = http1_get(addr, "/healthz", &[]).await; + assert_eq!(health.status(), StatusCode::FORBIDDEN); + + let admin = http1_request( + addr, + "POST", + "/openshell.v1.OpenShell/ListSandboxes", + &[("content-type", "application/grpc")], + ) + .await; + assert_eq!(admin.status(), StatusCode::OK); + assert_eq!(admin.headers().get("grpc-status").unwrap(), "7"); + + let callback = http1_request( + addr, + "POST", + "/openshell.v1.OpenShell/ConnectSupervisor", + &[("content-type", "application/grpc")], + ) + .await; + assert_ne!( + callback + .headers() + .get("grpc-status") + .and_then(|value| value.to_str().ok()), + Some("7") + ); + } + #[tokio::test] async fn intercepted_grpc_body_collection_rejects_oversized_body() { let oversized = Bytes::from(vec![0_u8; MAX_INTERCEPTED_GRPC_BODY_SIZE + 1]); @@ -1948,7 +2130,7 @@ mod tests { tracing_subscriber::registry().with(fmt_layer) }; { - let _traced = crate::otel_tracing::test_collector::install_scoped(subscriber); + let _traced = crate::otel_tracing::test_exporter::install_scoped(subscriber); let req = Request::builder() .uri("/test-path") @@ -1972,9 +2154,9 @@ mod tests { /// correlated with the gateway's logs. #[tokio::test] async fn request_span_exports_over_otlp_with_request_id() { - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); let req = Request::builder() .uri("/openshell.v1.OpenShell/CreateSandbox") .header("x-request-id", "otlp-req-id-9876") @@ -1995,11 +2177,11 @@ mod tests { ) }); assert_eq!( - test_collector::attribute(span, "request_id").as_deref(), + test_exporter::attribute(span, "request_id").as_deref(), Some("otlp-req-id-9876"), ); assert_eq!( - test_collector::attribute(span, "path").as_deref(), + test_exporter::attribute(span, "path").as_deref(), Some("/openshell.v1.OpenShell/CreateSandbox"), ); assert_eq!( @@ -2007,26 +2189,26 @@ mod tests { opentelemetry::trace::SpanKind::Server, "trace UIs lay this out as a served call, not an internal operation" ); - test_collector::assert_is_root(span); + test_exporter::assert_is_root(span); assert_eq!( - test_collector::attribute(span, "rpc.system").as_deref(), + test_exporter::attribute(span, "rpc.system").as_deref(), Some("grpc"), ); assert_eq!( - test_collector::attribute(span, "rpc.service").as_deref(), + test_exporter::attribute(span, "rpc.service").as_deref(), Some("openshell.v1.OpenShell"), ); assert_eq!( - test_collector::attribute(span, "rpc.method").as_deref(), + test_exporter::attribute(span, "rpc.method").as_deref(), Some("CreateSandbox"), ); } #[tokio::test] async fn request_span_continues_the_incoming_trace() { - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); let req = Request::builder() .uri("/openshell.v1.OpenShell/CreateSandbox") .header( @@ -2059,9 +2241,9 @@ mod tests { /// trace UI, which keys off span status rather than a logged field. #[tokio::test] async fn request_spans_record_the_response_outcome() { - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); for (path, status) in [ ("/openshell.v1.OpenShell/CreateSandbox", 500), ("/openshell.v1.OpenShell/ListSandboxes", 200), @@ -2092,7 +2274,7 @@ mod tests { .expect("successful request span recorded"); assert_eq!( - test_collector::attribute(failed, "http.response.status_code").as_deref(), + test_exporter::attribute(failed, "http.response.status_code").as_deref(), Some("500"), "the response status is an attribute, not only a log field" ); @@ -2110,9 +2292,9 @@ mod tests { #[tokio::test] async fn request_span_records_grpc_status_from_trailers() { - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); let req = Request::builder() .uri("/openshell.v1.OpenShell/CreateSandbox") .body(Empty::::new()) @@ -2129,7 +2311,7 @@ mod tests { "CreateSandbox", ); assert_eq!( - test_collector::attribute(&span, "rpc.grpc.status_code").as_deref(), + test_exporter::attribute(&span, "rpc.grpc.status_code").as_deref(), Some("13") ); assert!( @@ -2142,7 +2324,7 @@ mod tests { /// named for its RPC or HTTP method. #[tokio::test] async fn each_entrypoint_gets_its_own_root_span() { - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; let paths = [ "/openshell.v1.OpenShell/CreateSandbox", @@ -2152,7 +2334,7 @@ mod tests { "/metrics", ]; - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); for path in paths { let req = Request::builder() .uri(path) diff --git a/crates/openshell-server/src/otel_tracing.rs b/crates/openshell-server/src/otel_tracing.rs index b22f7a8dc8..58b4cdf804 100644 --- a/crates/openshell-server/src/otel_tracing.rs +++ b/crates/openshell-server/src/otel_tracing.rs @@ -21,14 +21,12 @@ //! Only traces are exported. Logs and metrics have their own surfaces (OCSF //! JSONL and the Prometheus `/metrics` endpoint). -use opentelemetry::KeyValue; -use opentelemetry::trace::TracerProvider as _; -use opentelemetry_otlp::{SpanExporter, WithExportConfig}; +pub use openshell_otel::SetupError; +use openshell_otel::{OtlpTraceConfig, ServiceName}; +#[cfg(test)] use opentelemetry_sdk::Resource; -use opentelemetry_sdk::trace::{SdkTracer, SdkTracerProvider}; +use opentelemetry_sdk::trace::SdkTracerProvider; use tracing::Subscriber; -use tracing_opentelemetry::OpenTelemetryLayer; -use tracing_subscriber::Layer as _; use tracing_subscriber::registry::LookupSpan; use crate::config_file::OtlpConfig; @@ -39,67 +37,28 @@ const DEFAULT_SERVICE_NAME: &str = "openshell-gateway"; /// Instrumentation scope recorded on spans this gateway emits. const INSTRUMENTATION_SCOPE: &str = "openshell-gateway"; -/// Prefix of the placeholder `service.name` the SDK's own detector supplies -/// when nothing else set one. The full value is `unknown_service:`. -/// Used to tell "operator configured nothing" apart from "operator set -/// `OTEL_SERVICE_NAME`". -const SDK_UNKNOWN_SERVICE_PREFIX: &str = "unknown_service"; - -/// Failure to construct the OTLP export pipeline from gateway config. -/// -/// Every variant is a configuration error, surfaced at startup. Collector -/// *reachability* is deliberately not an error here — the batch exporter -/// connects lazily so a down collector never blocks the gateway from serving. -#[derive(Debug, thiserror::Error)] -pub enum SetupError { - #[error("otlp endpoint is empty; set [openshell.gateway.otlp].endpoint")] - EmptyEndpoint, - - #[error("invalid otlp endpoint {endpoint:?}: {source}")] - InvalidEndpoint { - endpoint: String, - source: http::uri::InvalidUri, - }, - - #[error("failed to build the otlp span exporter: {0}")] - Exporter(#[from] opentelemetry_otlp::ExporterBuildError), -} - -/// Build the `OTel` resource describing this gateway process. -/// -/// `Resource::builder` also runs the SDK's env detector, so -/// `OTEL_RESOURCE_ATTRIBUTES` and `OTEL_SERVICE_NAME` are merged in on top of -/// these defaults. -fn build_resource(cfg: &OtlpConfig) -> Resource { - let version = KeyValue::new("service.version", openshell_core::VERSION); - - if let Some(name) = cfg +fn trace_config(cfg: &OtlpConfig) -> OtlpTraceConfig<'_> { + let service_name = cfg .service_name .as_deref() .map(str::trim) .filter(|s| !s.is_empty()) - { - return Resource::builder() - .with_service_name(name.to_string()) - .with_attribute(version) - .build(); - } + .map_or( + ServiceName::EnvironmentOr(DEFAULT_SERVICE_NAME), + ServiceName::Fixed, + ); - // No name configured: prefer whatever the env detector found, and fall - // back to our own default only if it found nothing. Setting the default - // unconditionally would mask `OTEL_SERVICE_NAME`. - let detected = Resource::builder().with_attribute(version.clone()).build(); - if detected - .get(&opentelemetry::Key::from_static_str("service.name")) - .is_some_and(|v| !v.to_string().starts_with(SDK_UNKNOWN_SERVICE_PREFIX)) - { - return detected; + OtlpTraceConfig { + endpoint: &cfg.endpoint, + service_name, + service_version: Some(openshell_core::VERSION), + resource_attributes: Vec::new(), } +} - Resource::builder() - .with_service_name(DEFAULT_SERVICE_NAME) - .with_attribute(version) - .build() +#[cfg(test)] +fn build_resource(cfg: &OtlpConfig) -> Resource { + openshell_otel::resource_for(&trace_config(cfg)) } /// Build a tracer provider exporting over OTLP/gRPC to the configured endpoint. @@ -110,29 +69,9 @@ fn build_resource(cfg: &OtlpConfig) -> Resource { /// /// The sampler and span limits are left at the SDK's defaults, which are /// themselves resolved from `OTEL_*` env vars (see the module docs). +#[cfg(test)] fn build_provider(cfg: &OtlpConfig) -> Result { - let endpoint = cfg.endpoint.trim(); - if endpoint.is_empty() { - return Err(SetupError::EmptyEndpoint); - } - // Validate up front: the exporter defers connection, so without this a - // typo'd endpoint would surface only as export failures at runtime. - endpoint - .parse::() - .map_err(|source| SetupError::InvalidEndpoint { - endpoint: endpoint.to_string(), - source, - })?; - - let exporter = SpanExporter::builder() - .with_tonic() - .with_endpoint(endpoint) - .build()?; - - Ok(SdkTracerProvider::builder() - .with_batch_exporter(exporter) - .with_resource(build_resource(cfg)) - .build()) + openshell_otel::build_provider(&trace_config(cfg)) } /// Resolve the tracer provider for a gateway config file's optional @@ -144,32 +83,18 @@ fn build_provider(cfg: &OtlpConfig) -> Result { /// The error is returned rather than logged because the provider is built /// before the subscriber it attaches to, so logging here would go nowhere. pub fn provider_for(cfg: Option<&OtlpConfig>) -> (Option, Option) { - match cfg.map(build_provider) { - None => (None, None), - Some(Ok(provider)) => (Some(provider), None), - Some(Err(err)) => (None, Some(err)), - } + openshell_otel::provider_for(cfg.map(trace_config)) } /// Build the `tracing` layer that forwards spans to `provider`. /// /// Events stay on the gateway's logging layers. Spans emitted by the /// OpenTelemetry crates are excluded to prevent recursive export traffic. -pub fn layer( - provider: &SdkTracerProvider, -) -> tracing_subscriber::filter::Filtered< - OpenTelemetryLayer, - tracing_subscriber::filter::FilterFn, - S, -> +pub fn layer(provider: &SdkTracerProvider) -> openshell_otel::OtlpLayer where S: Subscriber + for<'span> LookupSpan<'span>, { - tracing_opentelemetry::layer() - .with_tracer(provider.tracer(INSTRUMENTATION_SCOPE)) - .with_filter(tracing_subscriber::filter::filter_fn(|meta| { - meta.is_span() && !is_opentelemetry_target(meta.target()) - })) + openshell_otel::layer(provider, INSTRUMENTATION_SCOPE) } /// Mark `span` as failed. @@ -180,74 +105,48 @@ pub fn mark_error(span: &tracing::Span) { span.record("otel.status_code", "ERROR"); } -/// Whether `target` belongs to the OpenTelemetry crates themselves. -/// -/// OpenTelemetry crates use their crate name as the target (`opentelemetry`, -/// `opentelemetry_sdk`, `opentelemetry-otlp`), so a prefix match covers them. -fn is_opentelemetry_target(target: &str) -> bool { - target.starts_with("opentelemetry") -} - -/// In-process OTLP/gRPC trace collector, for tests that need to assert what -/// the gateway actually put on the wire. +/// Isolated in-memory span exporters for tracing tests. #[cfg(test)] -pub mod test_collector { - use std::net::SocketAddr; - use std::sync::{Arc, Mutex}; - - use opentelemetry_proto::tonic::collector::trace::v1::{ - ExportTraceServiceRequest, ExportTraceServiceResponse, - trace_service_server::{TraceService, TraceServiceServer}, - }; - use opentelemetry_proto::tonic::trace::v1::Span; - - /// Spans received by a running [`start`] collector. - pub type Received = Arc>>; - - /// The one exporter every traced test reads, installed for the whole test - /// binary and never swapped. +pub mod test_exporter { + /// Installs a process-wide registry before any scoped test subscriber is + /// used. /// - /// A per-test subscriber cannot work here: `tracing` caches callsite - /// interest process-wide, so a callsite first hit by an untraced test - /// stays dark for every later one. - static EXPORTER: std::sync::LazyLock = - std::sync::LazyLock::new(|| { - use tracing_subscriber::layer::SubscriberExt as _; - - let exporter = opentelemetry_sdk::trace::InMemorySpanExporterBuilder::new().build(); - let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = tracing_subscriber::registry().with(super::layer(&provider)); - tracing::subscriber::set_global_default(subscriber) - .expect("test subscriber installs once"); - // Leaked so the provider outlives every span the binary records; - // dropping it would shut the exporter down mid-suite. - std::mem::forget(provider); - exporter - }); - - /// Captures spans until the returned guard is dropped. + /// `tracing` caches callsite interest process-wide. The registry keeps + /// callsites enabled without exporting spans from unrelated tests. + static INITIALIZED: std::sync::LazyLock<()> = std::sync::LazyLock::new(|| { + tracing::subscriber::set_global_default(tracing_subscriber::registry()) + .expect("test subscriber installs once"); + }); + + /// Captures spans from the current test thread until the guard is dropped. /// - /// Serialized on [`crate::TEST_TRACING_LOCK`] because the exporter it - /// clears is shared by the whole binary. + /// Subscriber changes remain serialized because `tracing` caches callsite + /// interest process-wide. The exporter itself is private to this guard, so + /// concurrent non-tracing tests cannot contaminate or reset its spans. #[must_use] pub fn install_traced() -> TracingTestGuard { + use tracing_subscriber::layer::SubscriberExt as _; + let lock = crate::TEST_TRACING_LOCK .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - EXPORTER.reset(); + std::sync::LazyLock::force(&INITIALIZED); + let exporter = opentelemetry_sdk::trace::InMemorySpanExporterBuilder::new().build(); + let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder() + .with_simple_exporter(exporter.clone()) + .build(); + let subscriber = tracing_subscriber::registry().with(super::layer(&provider)); + let dispatch = tracing::Dispatch::new(subscriber); TracingTestGuard { + _default: tracing::dispatcher::set_default(&dispatch), + _provider: provider, + exporter, _lock: lock, - exporter: &EXPORTER, } } impl TracingTestGuard { - /// Every span recorded since [`install_traced`], including any written - /// concurrently by other callers. - /// - /// Prefer [`Self::spans_named`] or [`Self::span_with`] to select spans. + /// Every span recorded by this test's in-memory exporter. pub fn finished_spans(&self) -> Vec { self.exporter.get_finished_spans().expect("in-memory spans") } @@ -309,7 +208,7 @@ pub mod test_collector { let lock = crate::TEST_TRACING_LOCK .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - std::sync::LazyLock::force(&EXPORTER); + std::sync::LazyLock::force(&INITIALIZED); ScopedTracingTestGuard { _default: tracing::dispatcher::set_default(&subscriber.into()), _lock: lock, @@ -323,72 +222,10 @@ pub mod test_collector { } pub struct TracingTestGuard { + _default: tracing::dispatcher::DefaultGuard, + _provider: opentelemetry_sdk::trace::SdkTracerProvider, + exporter: opentelemetry_sdk::trace::InMemorySpanExporter, _lock: std::sync::MutexGuard<'static, ()>, - exporter: &'static opentelemetry_sdk::trace::InMemorySpanExporter, - } - - #[derive(Clone)] - struct Collector { - spans: Received, - } - - #[tonic::async_trait] - impl TraceService for Collector { - async fn export( - &self, - request: tonic::Request, - ) -> Result, tonic::Status> { - let mut spans = self.spans.lock().expect("collector lock"); - for resource_span in request.into_inner().resource_spans { - for scope_span in resource_span.scope_spans { - spans.extend(scope_span.spans); - } - } - Ok(tonic::Response::new(ExportTraceServiceResponse::default())) - } - } - - /// Start a collector on an ephemeral port. Returns its address and a - /// handle to the spans it receives. - pub async fn start() -> (SocketAddr, Received) { - let spans: Received = Arc::new(Mutex::new(Vec::new())); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind collector"); - let addr = listener.local_addr().expect("collector addr"); - - let service = Collector { - spans: Arc::clone(&spans), - }; - tokio::spawn(async move { - tonic::transport::Server::builder() - .add_service(TraceServiceServer::new(service)) - .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)) - .await - .ok(); - }); - - (addr, spans) - } - - /// Wait for spans named `expected` to arrive, returning everything - /// received. - /// - /// `SdkTracerProvider::force_flush` is not a delivery barrier — it reports - /// `Ok` even when the collector is unreachable — so asserting on the - /// collector's contents immediately after it is a race. - pub async fn wait_for_spans(received: &Received, expected: &[&str]) -> Vec { - for _ in 0..200 { - let spans = received.lock().expect("collector lock").clone(); - if expected - .iter() - .all(|name| spans.iter().any(|s| s.name == *name)) - { - return spans; - } - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - received.lock().expect("collector lock").clone() } /// Value of `key` on an in-memory span, if present. @@ -398,21 +235,6 @@ pub mod test_collector { .find(|kv| kv.key.as_str() == key) .map(|kv| kv.value.to_string()) } - - /// Value of `key` on `span`, if present as a string attribute. - pub fn string_attribute(span: &Span, key: &str) -> Option { - use opentelemetry_proto::tonic::common::v1::any_value::Value; - - span.attributes - .iter() - .find(|kv| kv.key == key) - .and_then(|kv| kv.value.as_ref()) - .and_then(|v| v.value.as_ref()) - .map(|v| match v { - Value::StringValue(s) => s.clone(), - other => format!("{other:?}"), - }) - } } #[cfg(test)] @@ -613,7 +435,7 @@ mod tests { #[tokio::test] async fn tracing_events_are_not_exported() { - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); let span = tracing::info_span!("outer"); let entered = span.enter(); tracing::warn!(target: "opentelemetry-otlp", "export failed"); @@ -632,45 +454,4 @@ mod tests { "structured log events stay on the logging paths" ); } - - #[tokio::test(flavor = "multi_thread")] - async fn tracing_spans_reach_the_collector_over_otlp() { - let (addr, received) = test_collector::start().await; - - let cfg = OtlpConfig { - endpoint: format!("http://{addr}"), - service_name: None, - }; - let provider = build_provider(&cfg).expect("provider builds"); - - { - // Its own subscriber, not the shared in-memory one: this test - // asserts on what reaches a real collector over the wire. - use tracing_subscriber::layer::SubscriberExt as _; - let subscriber = tracing_subscriber::registry().with(layer(&provider)); - let _traced = test_collector::install_scoped(subscriber); - let span = tracing::info_span!("create_sandbox", sandbox_id = "sb-otlp"); - let _entered = span.enter(); - } - - provider.force_flush().expect("flush spans"); - - let spans = test_collector::wait_for_spans(&received, &["create_sandbox"]).await; - let span = spans - .iter() - .find(|s| s.name == "create_sandbox") - .unwrap_or_else(|| { - panic!( - "collector received the exported span, got {:?}", - spans.iter().map(|s| &s.name).collect::>() - ) - }); - assert_eq!( - test_collector::string_attribute(span, "sandbox_id").as_deref(), - Some("sb-otlp"), - "tracing fields are exported as span attributes" - ); - - provider.shutdown().ok(); - } } diff --git a/crates/openshell-server/src/persistence/mod.rs b/crates/openshell-server/src/persistence/mod.rs index 5ab1d8bd61..3ad20e1082 100644 --- a/crates/openshell-server/src/persistence/mod.rs +++ b/crates/openshell-server/src/persistence/mod.rs @@ -358,7 +358,7 @@ impl Store { name = "store", skip_all, fields( - otel.name = "store.get_by_name", otel.status_code = tracing::field::Empty, + otel.name = "store.get_by_name", otel.status_code = tracing::field::Empty, object_type = %object_type, workspace = %workspace, object.name = %name @@ -492,7 +492,7 @@ impl Store { name = "store", skip_all, fields( - otel.name = "store.list_with_selector", otel.status_code = tracing::field::Empty, + otel.name = "store.list_with_selector", otel.status_code = tracing::field::Empty, object_type = %object_type, workspace = %workspace, label_selector = %label_selector diff --git a/crates/openshell-server/src/persistence/tests.rs b/crates/openshell-server/src/persistence/tests.rs index 539dd2c6ff..ebf15b0d21 100644 --- a/crates/openshell-server/src/persistence/tests.rs +++ b/crates/openshell-server/src/persistence/tests.rs @@ -12,10 +12,10 @@ use std::collections::HashMap as StdHashMap; /// span that merely happened to return nothing. #[tokio::test] async fn failed_store_calls_are_marked_on_the_span() { - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; let store = test_store().await; - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); store.close_for_test().await; store .get("sandbox", "failed-store-call") @@ -36,26 +36,32 @@ async fn failed_store_calls_are_marked_on_the_span() { /// every gateway restart, exports as a failure. #[tokio::test] async fn expected_conflicts_leave_the_span_unmarked() { - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; let store = test_store().await; - let traced = test_collector::install_traced(); - let put = async |id: &str| { - store - .put_if( - "workspace", - id, - "expected-conflict", - "", - b"payload", - None, - super::WriteCondition::MustCreate, - ) - .await - }; + store + .put( + "workspace", + "expected-conflict-first", + "expected-conflict", + "", + b"payload", + None, + ) + .await + .expect("seed conflicting record"); - put("expected-conflict-first").await.expect("first write"); - put("expected-conflict-second") + let traced = test_exporter::install_traced(); + store + .put_if( + "workspace", + "expected-conflict-second", + "expected-conflict", + "", + b"payload", + None, + super::WriteCondition::MustCreate, + ) .await .expect_err("the name is already taken"); @@ -73,7 +79,7 @@ async fn expected_conflicts_leave_the_span_unmarked() { /// each call touched is carried as attributes. #[tokio::test] async fn store_spans_record_what_they_touched_as_attributes() { - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; let store = test_store().await; store @@ -81,7 +87,7 @@ async fn store_spans_record_what_they_touched_as_attributes() { .await .unwrap(); - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); store.get("sandbox", "abc").await.unwrap(); store .get_by_name("sandbox", "default", "my-sandbox") @@ -91,7 +97,7 @@ async fn store_spans_record_what_they_touched_as_attributes() { let by_name = traced.span_with("store.get_by_name", "object.name", "my-sandbox"); assert_eq!( - test_collector::attribute(&by_name, "object_type").as_deref(), + test_exporter::attribute(&by_name, "object_type").as_deref(), Some("sandbox"), "the span records which type it queried" ); @@ -2179,11 +2185,11 @@ async fn membership_selector_escapes_adversarial_label_key() { async fn store_operations_export_spans_with_parents() { use tracing::Instrument as _; - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; let store = test_store().await; - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); async { store .list("sandbox", "default", 10, 0) @@ -2211,9 +2217,9 @@ async fn store_operations_export_spans_with_parents() { ) }); - test_collector::assert_has_parent(child); + test_exporter::assert_has_parent(child); assert_eq!( - test_collector::attribute(child, "object_type").as_deref(), + test_exporter::attribute(child, "object_type").as_deref(), Some("sandbox"), "the store span records what it queried" ); diff --git a/crates/openshell-server/src/provider_refresh.rs b/crates/openshell-server/src/provider_refresh.rs index f70801221d..a03fdb0b17 100644 --- a/crates/openshell-server/src/provider_refresh.rs +++ b/crates/openshell-server/src/provider_refresh.rs @@ -1527,11 +1527,11 @@ mod tests { /// of its own its store reads export as anonymous single-span traces. #[tokio::test] async fn refresh_worker_ticks_are_roots_and_store_operations_have_parents() { - use crate::otel_tracing::test_collector; + use crate::otel_tracing::test_exporter; let store = test_store().await; - let traced = test_collector::install_traced(); + let traced = test_exporter::install_traced(); run_refresh_worker_tick(&store).await.unwrap(); let spans = traced.finished_spans(); @@ -1545,7 +1545,7 @@ mod tests { ) }); - test_collector::assert_is_root(root); + test_exporter::assert_is_root(root); let store_span = spans .iter() .find(|span| { @@ -1553,7 +1553,7 @@ mod tests { && span.span_context.trace_id() == root.span_context.trace_id() }) .expect("the tick records its store operation"); - test_collector::assert_has_parent(store_span); + test_exporter::assert_has_parent(store_span); } #[test] diff --git a/crates/openshell-server/src/test_support.rs b/crates/openshell-server/src/test_support.rs index 9cd80d6ed8..2bfa9998a2 100644 --- a/crates/openshell-server/src/test_support.rs +++ b/crates/openshell-server/src/test_support.rs @@ -8,10 +8,12 @@ use futures::{Stream, stream}; use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; use openshell_core::proto::compute::v1::{ CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse, - DriverSandbox, GetCapabilitiesRequest, GetCapabilitiesResponse, GetSandboxRequest, - GetSandboxResponse, ListSandboxesRequest, ListSandboxesResponse, StopSandboxRequest, - StopSandboxResponse, ValidateSandboxCreateRequest, ValidateSandboxCreateResponse, - WatchSandboxesEvent, WatchSandboxesRequest, compute_driver_server::ComputeDriver, + DriverSandbox, GatewayListenerRequirement, GetCapabilitiesRequest, GetCapabilitiesResponse, + GetGatewayListenerRequirementsRequest, GetGatewayListenerRequirementsResponse, + GetSandboxRequest, GetSandboxResponse, ListSandboxesRequest, ListSandboxesResponse, + StopSandboxRequest, StopSandboxResponse, ValidateSandboxCreateRequest, + ValidateSandboxCreateResponse, WatchSandboxesEvent, WatchSandboxesRequest, + compute_driver_server::ComputeDriver, gateway_listener_requirement::Selector, }; use std::collections::HashMap; #[cfg(unix)] @@ -33,6 +35,7 @@ type WatchStream = Pin #[derive(Debug, Clone, PartialEq)] pub enum FakeComputeDriverCall { GetCapabilities, + GetGatewayListenerRequirements, ValidateSandboxCreate { sandbox: Option, }, @@ -65,6 +68,8 @@ struct FakeComputeDriverState { driver_name: String, driver_version: String, default_image: String, + gateway_listener_requirements: Vec, + gateway_listener_requirements_supported: bool, sandboxes: HashMap, calls: Vec, } @@ -83,6 +88,8 @@ impl FakeComputeDriver { driver_name: "fake-compute-driver".to_string(), driver_version: "test".to_string(), default_image: "openshell/sandbox:test".to_string(), + gateway_listener_requirements: Vec::new(), + gateway_listener_requirements_supported: true, sandboxes: HashMap::new(), calls: Vec::new(), })), @@ -107,6 +114,29 @@ impl FakeComputeDriver { self } + #[must_use] + pub fn with_gateway_listener_requirement( + self, + bind_address: impl Into, + reason: impl Into, + ) -> Self { + self.with_state(|state| { + state + .gateway_listener_requirements + .push(GatewayListenerRequirement { + reason: reason.into(), + selector: Some(Selector::ExactBindAddress(bind_address.into())), + }); + }); + self + } + + #[must_use] + pub fn without_gateway_listener_requirements_api(self) -> Self { + self.with_state(|state| state.gateway_listener_requirements_supported = false); + self + } + #[must_use] pub fn calls(&self) -> Vec { self.with_state(|state| state.calls.clone()) @@ -194,6 +224,24 @@ impl ComputeDriver for FakeComputeDriver { Ok(Response::new(response)) } + async fn get_gateway_listener_requirements( + &self, + _request: Request, + ) -> Result, Status> { + self.with_state(|state| { + state + .calls + .push(FakeComputeDriverCall::GetGatewayListenerRequirements); + state + .gateway_listener_requirements_supported + .then(|| GetGatewayListenerRequirementsResponse { + requirements: state.gateway_listener_requirements.clone(), + }) + .map(Response::new) + .ok_or_else(|| Status::unimplemented("listener requirements unsupported")) + }) + } + async fn validate_sandbox_create( &self, request: Request, diff --git a/deploy/rpm/CONFIGURATION.md b/deploy/rpm/CONFIGURATION.md index a144cac8ed..4fc18e6215 100644 --- a/deploy/rpm/CONFIGURATION.md +++ b/deploy/rpm/CONFIGURATION.md @@ -20,14 +20,13 @@ The defaults are tuned for rootless Podman use: version = 1 [openshell.gateway] -bind_address = "0.0.0.0:17670" compute_drivers = ["podman"] ``` -`bind_address = "0.0.0.0:17670"` is required because Podman sandbox -containers reach the gateway over the host network bridge and cannot -connect to `127.0.0.1` inside the gateway's network namespace. mTLS is -enabled by default and protects all connections. +The RPM does not override `bind_address`. The primary listener uses the +built-in `127.0.0.1:17670` default. The Podman driver reports the callback +interface it needs, and the gateway adds a separate listener scoped to that +interface. This keeps the general API off unrelated host interfaces. `compute_drivers = ["podman"]` pins the compute driver to Podman. Without this, the gateway auto-detects in order: Kubernetes, Podman, Docker. Pinning @@ -43,8 +42,8 @@ To apply environment variable overrides that persist across upgrades without editing the TOML file, add them to `~/.config/openshell/gateway.env`: ```shell -# Example: restrict to loopback only -OPENSHELL_BIND_ADDRESS=127.0.0.1 +# Example: explicitly expose the primary listener on one host interface +OPENSHELL_BIND_ADDRESS=192.168.1.10 ``` To override the path to the TOML config file entirely: @@ -63,8 +62,9 @@ systemctl --user edit openshell-gateway ## TLS (mTLS) The RPM enables mutual TLS by default. The gateway requires a valid -client certificate for all API connections and listens on -`0.0.0.0:17670` by default (see "Default configuration" above). +client certificate for all API connections. Its primary listener uses +`127.0.0.1:17670`; Podman callback traffic uses the additional listener +described in "Default configuration" above. ### Auto-generated certificates @@ -214,7 +214,7 @@ overrides that persist across package upgrades. | TOML option | Default | Description | |-------------|---------|-------------| -| `bind_address` | `0.0.0.0:17670` (RPM default) | Address for the gRPC/HTTP API. | +| `bind_address` | `127.0.0.1:17670` (gateway default) | Address for the primary gRPC/HTTP API listener. | | `compute_drivers` | `["podman"]` (RPM default) | When unset, the gateway auto-detects Kubernetes, then Podman, then Docker. The RPM default pins to Podman. | | `default_image` | `ghcr.io/nvidia/openshell-community/sandboxes/base:latest` | Default sandbox image. | | `supervisor_image` | `ghcr.io/nvidia/openshell/supervisor:latest` | Supervisor image mounted into Podman sandboxes. | @@ -235,7 +235,6 @@ settings: version = 1 [openshell.gateway] -bind_address = "0.0.0.0:17670" compute_drivers = ["podman"] default_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" diff --git a/deploy/rpm/QUICKSTART.md b/deploy/rpm/QUICKSTART.md index c6634ced95..442458d09d 100644 --- a/deploy/rpm/QUICKSTART.md +++ b/deploy/rpm/QUICKSTART.md @@ -65,11 +65,11 @@ On first start, the gateway automatically generates: - A self-signed PKI bundle (CA, server cert, client cert) for mTLS -> **Note:** The RPM default configuration binds to `0.0.0.0:17670` so -> Podman sandbox containers can reach the gateway over the host network -> bridge. Mutual TLS (mTLS) is enabled automatically on first start, -> requiring a valid client certificate for every connection. See -> CONFIGURATION.md for details. +> **Note:** The primary gateway listener uses the loopback default, +> `127.0.0.1:17670`. The Podman driver requests a separate callback listener +> scoped to the interface its sandboxes can reach. Mutual TLS (mTLS) is +> enabled automatically on first start, requiring a valid client certificate +> for every connection. See CONFIGURATION.md for details. Verify the service is running: diff --git a/deploy/rpm/TROUBLESHOOTING.md b/deploy/rpm/TROUBLESHOOTING.md index 68a1f49464..103ce3bf9d 100644 --- a/deploy/rpm/TROUBLESHOOTING.md +++ b/deploy/rpm/TROUBLESHOOTING.md @@ -85,7 +85,7 @@ Generate certificates that include the server's hostname or IP in the SANs. See "Using externally-managed certificates" in CONFIGURATION.md. Then change `bind_address` in `~/.config/openshell/gateway.toml` to the interface the remote CLI -can reach, for example `0.0.0.0:17670`, and restart the gateway. +can reach, for example `192.168.1.10:17670`, and restart the gateway. After placing the server and client certs, register from the remote CLI: @@ -274,11 +274,12 @@ Other breaking changes in this release: - **Default bind address changed from `0.0.0.0` to `127.0.0.1`.** If you relied on network-accessible access without an explicit bind - address, add the following to `~/.config/openshell/gateway.toml`: + address, bind the specific reachable interface in + `~/.config/openshell/gateway.toml`: ```toml [openshell.gateway] - bind_address = "0.0.0.0:17670" + bind_address = "192.168.1.10:17670" ``` Also update your firewall rule if applicable: diff --git a/deploy/rpm/gateway.toml.default b/deploy/rpm/gateway.toml.default index d853799640..cd7e0d99c3 100644 --- a/deploy/rpm/gateway.toml.default +++ b/deploy/rpm/gateway.toml.default @@ -18,11 +18,9 @@ version = 1 [openshell.gateway] -# Podman sandbox containers reach the gateway over the host network bridge, -# which requires binding to all interfaces. Override to 127.0.0.1:17670 if -# you don't use Podman or want loopback-only access (e.g. behind a reverse -# proxy). mTLS is enabled by default and protects all connections. -bind_address = "0.0.0.0:17670" +# Keep the primary listener on the built-in 127.0.0.1:17670 default. The +# Podman driver reports the callback interface it needs, and the gateway +# adds a separate listener scoped to that interface. # Pin to the Podman compute driver. Without this, the gateway auto-detects # in order: Kubernetes, Podman, Docker. Pinning prevents unexpected driver diff --git a/docs/about/installation.mdx b/docs/about/installation.mdx index 2ac077e7b9..58cec98f37 100644 --- a/docs/about/installation.mdx +++ b/docs/about/installation.mdx @@ -38,7 +38,7 @@ For detailed driver behavior, refer to [Sandbox Compute Drivers](/reference/sand On macOS, the install script uses Homebrew. The Homebrew package installs the `openshell` CLI, the gateway binary, and a Homebrew-managed gateway service. -The Homebrew service listens on `https://127.0.0.1:17670` and generates a local mTLS bundle on install. The gateway starts from built-in defaults and reads `~/.config/openshell/gateway.toml` when that file exists. If that file is absent, the Homebrew service also falls back to a Homebrew prefix config when present, such as `/opt/homebrew/var/openshell/gateway.toml`. +The Homebrew service listens on `https://[::1]:17670` and generates a local mTLS bundle on install. The formula creates a Homebrew prefix config, such as `/opt/homebrew/var/openshell/gateway.toml`, with this IPv6 loopback default so Podman can use its separate IPv4 loopback callback listener. The gateway reads `~/.config/openshell/gateway.toml` instead when that file exists. Homebrew preserves existing prefix and user configs during upgrades. The CLI reads the client bundle from `~/.config/openshell/gateways/openshell/mtls/`. diff --git a/docs/reference/gateway-auth.mdx b/docs/reference/gateway-auth.mdx index 062a708131..2ef54de70c 100644 --- a/docs/reference/gateway-auth.mdx +++ b/docs/reference/gateway-auth.mdx @@ -45,10 +45,10 @@ Set these environment variables before starting the gateway: | `OPENSHELL_TLS_CLIENT_CA` | Path to the CA certificate that verifies CLI client certificates. | | `OPENSHELL_ENABLE_MTLS_AUTH` | Set to `true` to authenticate CLI callers from verified client certificates. Defaults on for local Docker, Podman, and VM gateways with no OIDC issuer. | -For local access, the server certificate must be valid for the endpoint the CLI uses. Include `localhost` and `127.0.0.1` in the certificate SANs when users connect to a local gateway through loopback. +For local access, the server certificate must be valid for the endpoint the CLI uses. Include `localhost`, `127.0.0.1`, and `::1` in the certificate SANs when users connect to a local gateway through loopback. -Package-managed local gateways on Homebrew, Debian, and RPM generate this bundle automatically for the `openshell` gateway name and use `https://127.0.0.1:17670` by default. -When you register a package-managed local gateway with `openshell gateway add https://127.0.0.1:17670 --local --name openshell`, the CLI refreshes its mTLS bundle from the package-managed TLS directory. +Package-managed local gateways generate this bundle automatically for the `openshell` gateway name. Homebrew uses `https://[::1]:17670` by default; Debian and RPM use `https://127.0.0.1:17670`. +When you register a package-managed local gateway with `openshell gateway add --local --name openshell`, the CLI refreshes its mTLS bundle from the package-managed TLS directory. On Homebrew, the gateway service also mirrors the Docker sandbox client bundle into `$HOME/.local/state/openshell/homebrew/tls` before startup so Docker Desktop can bind-mount the files into sandbox containers. The CLI loads its mTLS bundle from `~/.config/openshell/gateways//mtls/`: diff --git a/docs/reference/gateway-config.mdx b/docs/reference/gateway-config.mdx index d81aaa95f6..e46bc7c41c 100644 --- a/docs/reference/gateway-config.mdx +++ b/docs/reference/gateway-config.mdx @@ -24,11 +24,15 @@ Package-managed gateways do not require a TOML file. Create one at the package's | Package | Optional Gateway TOML location | |---|---| -| Homebrew | `$XDG_CONFIG_HOME/openshell/gateway.toml` when it exists, otherwise an existing Homebrew prefix config such as `/opt/homebrew/var/openshell/gateway.toml`. | +| Homebrew | `$XDG_CONFIG_HOME/openshell/gateway.toml` when it exists, otherwise the Homebrew prefix config such as `/opt/homebrew/var/openshell/gateway.toml`. | | Debian/Ubuntu | `$XDG_CONFIG_HOME/openshell/gateway.toml`, usually `~/.config/openshell/gateway.toml` for the systemd user service. | | Fedora/RHEL RPM | `$XDG_CONFIG_HOME/openshell/gateway.toml`, usually `~/.config/openshell/gateway.toml` for the systemd user service. | | Snap | `$SNAP_COMMON/gateway.toml`, usually `/var/snap/openshell/common/gateway.toml`. | +The Fedora/RHEL RPM template leaves `[openshell.gateway].bind_address` unset. The gateway therefore uses its built-in `127.0.0.1:17670` primary listener. The Podman driver negotiates separate, restricted listeners for sandbox callbacks, so the primary listener does not need a wildcard address. Set `bind_address` explicitly only when clients must reach the primary multiplexed API through another interface. + +The Homebrew formula creates its prefix config once with `bind_address = "[::1]:17670"`. Keeping the primary API on IPv6 loopback leaves IPv4 loopback available for Podman Machine's sandbox callback listener. A user config takes precedence, and upgrades do not overwrite either config. + ## Layout The file is rooted at `[openshell]`. Gateway-wide settings live under `[openshell.gateway]`. Each compute driver owns its own `[openshell.drivers.]` table. Shared keys set at gateway scope are inherited into driver tables when not overridden. diff --git a/docs/reference/sandbox-compute-drivers.mdx b/docs/reference/sandbox-compute-drivers.mdx index 6700a22c9f..675ffaff6a 100644 --- a/docs/reference/sandbox-compute-drivers.mdx +++ b/docs/reference/sandbox-compute-drivers.mdx @@ -107,6 +107,16 @@ It overrides the gateway's configured default runtime class for that sandbox, while a typed `SandboxTemplate.runtime_class_name` value from the API still takes precedence. +Docker and Podman callback listeners accept only supervisor callback gRPC +methods. Use the gateway's primary endpoint for CLI, administrator, health, +reflection, inference-route management, and HTTP requests. A +`PermissionDenied` response from one of the sandbox-visible callback addresses +is expected for those requests. The gateway fails startup if a callback +requirement resolves to the exact primary listener address because one socket +cannot preserve both authorization scopes. For the IPv4-loopback callback used +by Podman Machine, bind the primary listener to a distinct address such as +`[::1]:17670`. + ## Docker Driver [Docker](https://www.docker.com/get-started/)-backed sandboxes run as containers on the gateway host. Use Docker for local development, single-machine gateways, and hosts that already use Docker Desktop or Docker Engine. @@ -186,7 +196,7 @@ Podman sandboxes default to a 45-second graceful stop window before Podman escal For proxy-required networks, the Podman driver also accepts the corporate egress proxy keys `https_proxy`, `no_proxy`, `proxy_auth_file`, `proxy_auth_allow_insecure`, and `proxy_connect_by_hostname`. The supervisor chains policy-approved TLS tunnels through the proxy with HTTP CONNECT instead of dialing destinations directly. See the [Gateway Configuration File](./gateway-config) reference for the full contract, including the cleartext-credential acknowledgement and the validated-IP CONNECT behavior. -On macOS with `podman machine`, the driver uses gvproxy's host-loopback IP, `192.168.127.254`, for sandbox host aliases by default. Set `host_gateway_ip` only when your Podman machine uses a non-standard host-loopback address. On Linux, an empty `host_gateway_ip` keeps Podman's `host-gateway` resolver behavior. +On macOS with `podman machine`, the driver uses gvproxy's host-loopback IP, `192.168.127.254`, for sandbox host aliases by default. Set `host_gateway_ip` only when your Podman machine uses a non-standard host-loopback address. On Linux, an empty `host_gateway_ip` keeps Podman's `host-gateway` resolver behavior. Direct local callbacks from rootless Podman require Podman to report the pasta network helper. Slirp4netns, other helpers, and Podman versions that do not report their helper require an explicitly remote `grpc_endpoint`; otherwise the gateway fails startup rather than leaving sandbox callbacks unreachable. Rootful Podman continues to use the configured network's bridge gateway address. ### Podman Driver Config Mounts diff --git a/e2e/configs/gateway/podman.toml b/e2e/configs/gateway/podman.toml index 2ad86099fb..c1549cd933 100644 --- a/e2e/configs/gateway/podman.toml +++ b/e2e/configs/gateway/podman.toml @@ -24,6 +24,5 @@ ttl_secs = 0 default_image = "ghcr.io/nvidia/openshell-community/sandboxes/base:latest" image_pull_policy = "missing" network_name = "openshell-e2e" -grpc_endpoint = "http://10.89.0.1:8080" -host_gateway_ip = "10.89.0.1" +grpc_endpoint = "http://host.containers.internal:8080" supervisor_image = "localhost/openshell/supervisor:e2e-vm" diff --git a/e2e/python/test_security_tls.py b/e2e/python/test_security_tls.py index fa9059fa49..529404a6e4 100644 --- a/e2e/python/test_security_tls.py +++ b/e2e/python/test_security_tls.py @@ -234,11 +234,14 @@ def test_plaintext_connection_rejected( stub = openshell_pb2_grpc.OpenShellStub(channel) with pytest.raises(grpc.RpcError) as exc_info: stub.Health(openshell_pb2.HealthRequest(), timeout=10) - # Plaintext to a TLS port will fail at the transport level. + # The loopback listener may intentionally accept plaintext service + # HTTP. A gRPC request is still rejected, either at the transport + # boundary or as an unimplemented HTTP route. assert exc_info.value.code() in ( grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.UNKNOWN, grpc.StatusCode.INTERNAL, - ), f"expected transport failure, got {exc_info.value.code()}" + grpc.StatusCode.UNIMPLEMENTED, + ), f"expected plaintext gRPC rejection, got {exc_info.value.code()}" finally: channel.close() diff --git a/e2e/run.sh b/e2e/run.sh index 967f240c23..0505730f05 100755 --- a/e2e/run.sh +++ b/e2e/run.sh @@ -31,7 +31,8 @@ Options: -h, --help Show this help Omit --vm and --with to run the gateway on the host. Supplying --with without ---vm selects the Ubuntu test guest. Set OPENSHELL_E2E_KEEP=1 to retain state. +--vm selects Fedora for the Podman driver and Ubuntu otherwise. Set +OPENSHELL_E2E_KEEP=1 to retain state. EOF } @@ -154,7 +155,11 @@ mode=host if [ -n "${vm}" ] || [ "${#with_configurations[@]}" -gt 0 ]; then mode=vm if [ -z "${vm}" ]; then - vm=ubuntu + if [ "${gateway_driver}" = podman ]; then + vm=fedora + else + vm=ubuntu + fi fi fi if [ "${mode}" = vm ]; then @@ -166,6 +171,9 @@ if [ "${mode}" = vm ]; then die "invalid VM configuration name: ${configuration}" fi done + if [ "${gateway_driver}" = podman ] && [ "${vm}" = ubuntu ]; then + die "the Ubuntu 24.04 guest lacks the Podman 5 pasta helper required for sandbox callbacks; use --vm fedora --with podman" + fi if ! command -v nix >/dev/null 2>&1; then die "Nix is required for VM mode" fi @@ -466,33 +474,6 @@ podman) ;; esac report_timing "${gateway_driver} supervisor import" "\${phase_started_at}" -if [ '${gateway_driver}' = podman ]; then - phase_started_at=\${SECONDS} - # Keep the primary gateway listener on loopback and bridge the rootless - # container callback path temporarily. Remove this relay when #2492 lands. - relay_socket=\${state_root}/podman-gateway.sock - rm -f "\${relay_socket}" - socat "UNIX-LISTEN:\${relay_socket},fork" TCP:127.0.0.1:8080 & - host_relay_pid=\$! - for _ in \$(seq 1 50); do - [ -S "\${relay_socket}" ] && break - sleep 0.1 - done - if [ ! -S "\${relay_socket}" ] || ! kill -0 "\${host_relay_pid}" 2>/dev/null; then - echo "ERROR: failed to start the host-side Podman gateway relay" >&2 - exit 1 - fi - env -u XDG_CONFIG_HOME -u XDG_DATA_HOME -u XDG_STATE_HOME \ - podman unshare --rootless-netns \ - socat TCP-LISTEN:8080,bind=0.0.0.0,reuseaddr,fork "UNIX-CONNECT:\${relay_socket}" & - network_relay_pid=\$! - sleep 1 - if ! kill -0 "\${network_relay_pid}" 2>/dev/null; then - echo "ERROR: failed to start the rootless-network Podman gateway relay" >&2 - exit 1 - fi - report_timing "Podman network relays" "\${phase_started_at}" -fi cd /home/openshell exec /usr/local/bin/openshell-gateway \ --config "\${config_path}" \ diff --git a/e2e/with-docker-gateway.sh b/e2e/with-docker-gateway.sh index f6d01cb88f..15e9d3466e 100755 --- a/e2e/with-docker-gateway.sh +++ b/e2e/with-docker-gateway.sh @@ -512,7 +512,6 @@ GATEWAY_CONFIG="${STATE_DIR}/gateway.toml" GATEWAY_ARGS=( --config "${GATEWAY_CONFIG}" - --bind-address 0.0.0.0 --port "${HOST_PORT}" --health-port "${HEALTH_PORT}" --drivers docker diff --git a/e2e/with-podman-gateway.sh b/e2e/with-podman-gateway.sh index ba04d63b3e..8c598c88f8 100755 --- a/e2e/with-podman-gateway.sh +++ b/e2e/with-podman-gateway.sh @@ -416,10 +416,10 @@ toml_string() { GATEWAY_CONFIG="${STATE_DIR}/gateway.toml" # Start from the RPM default template so this e2e test exercises the same -# TOML config path that RPM users get on first start. The template sets -# bind_address = "0.0.0.0:17670" and compute_drivers = ["podman"]; those -# values must be correct for Podman e2e to pass, which means a regression -# to the template (wrong bind address, wrong driver) will surface here. +# TOML config path that RPM users get on first start. The template leaves +# bind_address unset and sets compute_drivers = ["podman"], so this test +# exercises the built-in loopback listener plus the callback listener +# requested by the Podman driver. # # We append the driver-specific table and override the port via CLI flag # (CLI > TOML in the merge precedence) so the test can use an ephemeral port. @@ -458,8 +458,8 @@ cp "${ROOT}/deploy/rpm/gateway.toml.default" "${GATEWAY_CONFIG}" GATEWAY_ARGS=( --config "${GATEWAY_CONFIG}" - # bind_address and compute_drivers come from the RPM template; no CLI flags - # needed. Port is overridden via CLI (CLI > TOML) for ephemeral port selection. + # compute_drivers comes from the RPM template, while bind_address uses the + # built-in loopback default. Override only the port for ephemeral selection. --port "${HOST_PORT}" --health-port "${HEALTH_PORT}" --tls-cert "${PKI_DIR}/server/tls.crt" diff --git a/install.sh b/install.sh index 6cda59f8bc..a623cd14b4 100755 --- a/install.sh +++ b/install.sh @@ -467,6 +467,17 @@ detect_platform() { esac } +local_gateway_endpoint() { + case "${PLATFORM:-$(detect_platform)}" in + darwin) + printf 'https://[::1]:%s\n' "$LOCAL_GATEWAY_PORT" + ;; + *) + printf 'https://127.0.0.1:%s\n' "$LOCAL_GATEWAY_PORT" + ;; + esac +} + linux_package_method() { if has_cmd dpkg; then echo "deb" @@ -764,7 +775,7 @@ wait_for_local_gateway_listener() { _timeout="${OPENSHELL_INSTALL_GATEWAY_TIMEOUT:-30}" _elapsed=0 _last_output="" - _probe_url="https://127.0.0.1:${LOCAL_GATEWAY_PORT}/" + _probe_url="$(local_gateway_endpoint)/" _mtls_dir="${TARGET_HOME}/.config/openshell/gateways/openshell/mtls" info "waiting for local gateway listener to become reachable..." @@ -835,8 +846,9 @@ remove_local_gateway_registration() { register_local_gateway() { _register_bin="${OPENSHELL_REGISTER_BIN:-openshell}" + _endpoint="$(local_gateway_endpoint)" - if _add_output="$(as_target_user "$_register_bin" gateway add "https://127.0.0.1:${LOCAL_GATEWAY_PORT}" --local --name openshell 2>&1)"; then + if _add_output="$(as_target_user "$_register_bin" gateway add "$_endpoint" --local --name openshell 2>&1)"; then [ -z "$_add_output" ] || print_gateway_add_output "$_add_output" return 0 else @@ -847,7 +859,7 @@ register_local_gateway() { *"already exists"*) info "local gateway already exists; removing and re-adding it..." remove_local_gateway_registration - as_target_user "$_register_bin" gateway add "https://127.0.0.1:${LOCAL_GATEWAY_PORT}" --local --name openshell + as_target_user "$_register_bin" gateway add "$_endpoint" --local --name openshell ;; *) printf '%s\n' "$_add_output" >&2 @@ -857,9 +869,10 @@ register_local_gateway() { } print_gateway_add_output() { + _endpoint="$(local_gateway_endpoint)" printf '%s\n' "$1" | while IFS= read -r _line; do case "$_line" in - *"Gateway is not reachable at https://127.0.0.1:${LOCAL_GATEWAY_PORT}"*) ;; + *"Gateway is not reachable at ${_endpoint}"*) ;; *"Verify the gateway is running and the endpoint is correct."*) ;; *) printf '%s\n' "$_line" >&2 ;; esac @@ -992,7 +1005,7 @@ install_macos_homebrew() { if ! as_target_user brew services restart "$_formula_ref"; then warn "could not restart the OpenShell Homebrew service" info "restart it later with: brew services restart ${_formula_ref}" - info "then register it with: openshell gateway add https://127.0.0.1:${LOCAL_GATEWAY_PORT} --local --name openshell" + info "then register it with: openshell gateway add $(local_gateway_endpoint) --local --name openshell" return 0 fi diff --git a/nix/test-guest/README.md b/nix/test-guest/README.md index 1400bb21a8..ae28452056 100644 --- a/nix/test-guest/README.md +++ b/nix/test-guest/README.md @@ -57,6 +57,11 @@ The root [`flake.nix`](../../flake.nix) exposes this directory as the `test-gues | Fedora 44 | No | Yes | Yes | `.rpm` | | Rocky Linux 9 | Yes | Yes | Yes | `.rpm` | +The Ubuntu 24.04 Podman configuration is available for runtime and packaging +checks, but its Podman 4 release does not provide the `pasta` rootless network +helper required by OpenShell sandbox callbacks. OpenShell Podman E2E runs use +the Fedora guest, which provides Podman 5 and `pasta`. + List the available distros and configurations: ```shell diff --git a/nix/test-guest/configuration/podman.yml b/nix/test-guest/configuration/podman.yml index a1139b4f6d..1c79199074 100644 --- a/nix/test-guest/configuration/podman.yml +++ b/nix/test-guest/configuration/podman.yml @@ -24,9 +24,7 @@ - name: Install Podman dependencies ansible.builtin.package: - name: - - podman - - socat + name: podman state: present - name: Enable the rootless Podman API socket diff --git a/proto/compute_driver.proto b/proto/compute_driver.proto index c99b7756b0..e3f18af19f 100644 --- a/proto/compute_driver.proto +++ b/proto/compute_driver.proto @@ -20,6 +20,13 @@ service ComputeDriver { // Report driver capabilities and defaults. rpc GetCapabilities(GetCapabilitiesRequest) returns (GetCapabilitiesResponse); + // Report additional gateway listeners required by this driver instance. + // + // A requirement is not authorization to expose the gateway. The gateway + // owns validation, authorization, and the authoritative bind. + rpc GetGatewayListenerRequirements(GetGatewayListenerRequirementsRequest) + returns (GetGatewayListenerRequirementsResponse); + // Validate a sandbox before create-time provisioning. rpc ValidateSandboxCreate(ValidateSandboxCreateRequest) returns (ValidateSandboxCreateResponse); @@ -57,6 +64,32 @@ message GetCapabilitiesResponse { string default_image = 3; } +message GetGatewayListenerRequirementsRequest {} + +message GatewayListenerRequirement { + // Untrusted human-readable driver rationale for diagnostics. + string reason = 1; + + oneof selector { + // Concrete IP:port address requested by the driver. The port must match + // the gateway's configured primary listener port. + string exact_bind_address = 2; + // Ask the gateway to bind the IPv4 address selected by its default route. + // This matches rootless pasta's default upstream-interface selection. + GatewayDefaultRouteInterfaceRequirement default_route_interface = 3; + // Ask the gateway to ensure an IPv4 loopback listener is present. This + // covers runtimes whose host forwarder terminates on gateway loopback. + GatewayLoopbackInterfaceRequirement loopback_interface = 4; + } +} + +message GatewayDefaultRouteInterfaceRequirement {} +message GatewayLoopbackInterfaceRequirement {} + +message GetGatewayListenerRequirementsResponse { + repeated GatewayListenerRequirement requirements = 1; +} + // Driver-owned sandbox model used for create requests and platform observations. // // This intentionally omits gateway-owned lifecycle fields such as the public diff --git a/python/openshell/release_formula_test.py b/python/openshell/release_formula_test.py index b3ab871ae4..d22705afa3 100644 --- a/python/openshell/release_formula_test.py +++ b/python/openshell/release_formula_test.py @@ -55,7 +55,13 @@ def test_generate_homebrew_formula_uses_tagged_macos_driver_asset_without_defaul assert 'OPENSHELL_GATEWAY_CONFIG: "#{var}/openshell/gateway.toml"' not in formula assert "init-gateway-config.sh" not in formula assert 'bind_address = "127.0.0.1:17670"' not in formula + assert 'gateway_config = var/"openshell/gateway.toml"' in formula + assert "unless gateway_config.exist?" in formula + assert 'bind_address = "[::1]:17670"' in formula assert '# compute_drivers = ["vm"]' not in formula + assert ( + "openshell gateway add https://[::1]:17670 --local --name openshell" in formula + ) assert 'run opt_libexec/"openshell-gateway-homebrew-service"' in formula assert 'xdg_config_home="${XDG_CONFIG_HOME:-${HOME}/.config}"' in formula assert 'xdg_gateway_config="${xdg_config_home}/openshell/gateway.toml"' in formula diff --git a/tasks/scripts/gateway.sh b/tasks/scripts/gateway.sh index 3e94afe108..5d3adae2a8 100644 --- a/tasks/scripts/gateway.sh +++ b/tasks/scripts/gateway.sh @@ -306,15 +306,6 @@ if [[ "${DRIVER}" == "podman" ]]; then SUPERVISOR_IMAGE="${OPENSHELL_SUPERVISOR_IMAGE:-openshell/supervisor:dev}" ensure_podman_supervisor_image "${SUPERVISOR_IMAGE}" export OPENSHELL_SUPERVISOR_IMAGE="${SUPERVISOR_IMAGE}" - - # Rootless Podman containers reach the host via pasta's local connection - # bypass, which translates to host L4 sockets. The gateway must listen on - # 0.0.0.0 so pasta can reach it — 127.0.0.1 is not routable through pasta. - if [[ -z "${OPENSHELL_BIND_ADDRESS:-}" ]]; then - if podman info --format '{{.Host.Security.Rootless}}' 2>/dev/null | grep -q true; then - export OPENSHELL_BIND_ADDRESS="0.0.0.0" - fi - fi fi if [[ ! "${GATEWAY_NAME}" =~ ^[A-Za-z0-9._-]+$ ]]; then diff --git a/tasks/scripts/release.py b/tasks/scripts/release.py index f00bd19d34..1996cf6f84 100644 --- a/tasks/scripts/release.py +++ b/tasks/scripts/release.py @@ -329,6 +329,17 @@ def post_install (var/"log/openshell").mkpath system bin/"openshell-gateway", "generate-certs", "--output-dir", var/"openshell/tls", "--server-san", "host.openshell.internal" + gateway_config = var/"openshell/gateway.toml" + unless gateway_config.exist? + gateway_config.write <<~TOML + [openshell] + version = 1 + + [openshell.gateway] + bind_address = "[::1]:{LOCAL_GATEWAY_PORT}" + TOML + end + entitlements = var/"openshell/openshell-driver-vm.entitlements.plist" entitlements.atomic_write <<~XML @@ -357,7 +368,7 @@ def caveats brew services restart openshell Register it with the OpenShell CLI: - openshell gateway add https://127.0.0.1:{LOCAL_GATEWAY_PORT} --local --name openshell + openshell gateway add https://[::1]:{LOCAL_GATEWAY_PORT} --local --name openshell EOS end diff --git a/tasks/scripts/test-install-sh.sh b/tasks/scripts/test-install-sh.sh index a1259cf0bc..88e08dfed1 100755 --- a/tasks/scripts/test-install-sh.sh +++ b/tasks/scripts/test-install-sh.sh @@ -100,4 +100,14 @@ assert_glibc_preflight_fails \ "OpenShell Linux packages require glibc >= 2.28; detected musl or unsupported libc." \ setup_ldd_musl -echo "install.sh libc preflight tests passed" +if [ "$(PLATFORM=darwin local_gateway_endpoint)" != "https://[::1]:17670" ]; then + echo "FAIL: macOS local gateway endpoint must use IPv6 loopback" >&2 + exit 1 +fi + +if [ "$(PLATFORM=linux local_gateway_endpoint)" != "https://127.0.0.1:17670" ]; then + echo "FAIL: Linux local gateway endpoint must use IPv4 loopback" >&2 + exit 1 +fi + +echo "install.sh focused tests passed"