From d0dfb22baf32449dc565196fe55ac87769e83231 Mon Sep 17 00:00:00 2001 From: krishicks Date: Wed, 26 Aug 2026 21:22:51 +0000 Subject: [PATCH 1/3] feat(kubernetes): export driver traces over OTLP (#2958) Mirror the VM, Podman, and Docker driver tracing setup for Kubernetes. Export standalone driver spans through OTLP/gRPC as the distinct openshell-driver-kubernetes service, preserve gateway trace context, record lifecycle operations and gRPC failures, and flush spans on shutdown. Kubernetes currently runs in-process when selected as a built-in gateway driver. Use the temporary server-boundary shim shared with Podman and Docker so traces retain the shape they will have when Kubernetes moves to a separate process. Move the common ComputeDriver RPC tracing layer into openshell-otel to keep all drivers aligned. Propagate the active W3C context through the controller-reserved Sandbox annotation and enable Agent Sandbox OTLP export in the local k3s workflow. This connects asynchronous controller reconciliation spans to the originating OpenShell create trace. Expose gateway OTLP configuration through Helm and add an Aspire collector to the local k3s workflow. Extend helm:k3s:forward with OTLP ingest and trace UI forwarding for Kubernetes and local container gateway development. Signed-off-by: Kris Hicks --- .../skills/debug-openshell-cluster/SKILL.md | 8 +- .agents/skills/helm-dev-environment/SKILL.md | 44 +- Cargo.lock | 8 + crates/openshell-driver-kubernetes/Cargo.toml | 8 + crates/openshell-driver-kubernetes/README.md | 11 + .../openshell-driver-kubernetes/src/driver.rs | 159 ++++- .../openshell-driver-kubernetes/src/grpc.rs | 567 ++++++++++++++---- crates/openshell-driver-kubernetes/src/lib.rs | 1 + .../openshell-driver-kubernetes/src/main.rs | 52 +- .../src/otel_tracing.rs | 108 ++++ .../src/otel_tracing.rs | 87 +-- .../openshell-driver-vm/src/otel_tracing.rs | 83 +-- crates/openshell-otel/src/grpc.rs | 133 +++- crates/openshell-otel/src/lib.rs | 9 +- crates/openshell-otel/src/propagation.rs | 23 + crates/openshell-server/src/compute/mod.rs | 2 +- crates/openshell-server/src/tracing_setup.rs | 19 +- deploy/helm/openshell/README.md | 2 + deploy/helm/openshell/ci/values-skaffold.yaml | 2 + .../openshell/templates/gateway-config.yaml | 10 + .../openshell/tests/gateway_config_test.yaml | 26 + deploy/helm/openshell/values.yaml | 6 + docs/reference/gateway-config.mdx | 16 + tasks/helm.toml | 4 +- tasks/scripts/gateway-docker.sh | 3 + tasks/scripts/gateway-podman.sh | 3 + tasks/scripts/gateway-vm.sh | 3 + tasks/scripts/gateway.sh | 3 + tasks/scripts/helm-k3s-local.sh | 187 +++++- 29 files changed, 1280 insertions(+), 307 deletions(-) create mode 100644 crates/openshell-driver-kubernetes/src/otel_tracing.rs diff --git a/.agents/skills/debug-openshell-cluster/SKILL.md b/.agents/skills/debug-openshell-cluster/SKILL.md index 9db860995c..80d5057b17 100644 --- a/.agents/skills/debug-openshell-cluster/SKILL.md +++ b/.agents/skills/debug-openshell-cluster/SKILL.md @@ -440,8 +440,12 @@ openshell gateway list openshell status ``` -A successful plaintext `helm:skaffold:run` registers and selects the local -gateway; the forwarding task does not modify gateway metadata. +The forwarding task always exposes the collector on ports `4317` and `18888`. +It exposes the gateway on port `8090` only when the `openshell` Service exists, +so collector-only Docker or Podman development remains valid before a Skaffold +deployment. A successful plaintext `helm:skaffold:run` registers the local +gateway and selects it as active; the forwarding task does not modify gateway +metadata. If the gateway is healthy but sandbox creation fails: diff --git a/.agents/skills/helm-dev-environment/SKILL.md b/.agents/skills/helm-dev-environment/SKILL.md index 0c6afb8162..ebd9a01595 100644 --- a/.agents/skills/helm-dev-environment/SKILL.md +++ b/.agents/skills/helm-dev-environment/SKILL.md @@ -28,8 +28,10 @@ mise run helm:k3s:create Creates a k3d cluster and merges its kubeconfig into the worktree-local `kubeconfig` file. Also applies the upstream agent-sandbox CRDs/controller (pinned via `AGENT_SANDBOX_VERSION` in `tasks/scripts/helm-k3s-local.sh`, fetched from `github.com/kubernetes-sigs/agent-sandbox` -releases) and preloads the default community sandbox image into k3d so the first sandbox -create does not wait on a large registry pull. Traefik is disabled at cluster creation time. +releases), enables its OTLP tracing on v0.5 and later, installs an OTLP trace +collector and UI in the `observability` namespace, +and preloads the default community sandbox image into k3d so the first sandbox create +does not wait on a large registry pull. Traefik is disabled at cluster creation time. **Multi-worktree support:** the cluster name is derived from the last component of the current git branch (e.g. branch `kube-support/local-dev/tmutch` → cluster @@ -47,6 +49,9 @@ Override with env vars before running `helm:k3s:create`: - `HELM_K3S_LB_HOST_PORT` (default: `8080`) - `HELM_K3S_PRELOAD_SANDBOX_IMAGE` (default: `ghcr.io/nvidia/openshell-community/sandboxes/base:latest`; set to an empty value to skip) +- `HELM_K3S_COLLECTOR_IMAGE` (default: + `mcr.microsoft.com/dotnet/aspire-dashboard:latest`) +- `HELM_K3S_COLLECTOR_HEALTH_TIMEOUT` (default: `120` seconds) ### 2. Deploy OpenShell @@ -79,19 +84,42 @@ must be at least `1000` and distinct from the workload UID. The sidecar-mTLS profile reuses `ci/values-sidecar.yaml` and restores `server.disableTls=false` inline for Skaffold. The `pkiInitJob` hook (a pre-install Job that runs `openshell-gateway generate-certs`) generates mTLS secrets on first -install. Envoy Gateway opt-in; see the Optional Add-ons section below. +install. The default Skaffold values export gateway and Kubernetes-driver traces to +the collector service installed by `helm:k3s:create`. Envoy Gateway opt-in; see the +Optional Add-ons section below. The gateway Service uses ClusterIP. Access is via Envoy Gateway (port `8080`) or -the local forwarding task: +the unified local forwarding task: ```bash mise run helm:k3s:forward ``` -The task forwards the Kubernetes gateway to `http://127.0.0.1:8090`. A -successful plaintext `helm:skaffold:run` or `helm:skaffold:run:sidecar` -registers and selects the gateway under the worktree-specific k3d cluster name. -Keep the forwarding task running while using the endpoint. +The task forwards OTLP/gRPC to `http://127.0.0.1:4317` and the trace UI to +`http://127.0.0.1:18888`. When Skaffold has deployed a Kubernetes gateway, it +also forwards the gateway to `http://127.0.0.1:8090`; otherwise it continues +with the collector ports only. A successful plaintext `helm:skaffold:run` or +`helm:skaffold:run:sidecar` registers the gateway under the worktree-specific +k3d cluster name and selects it as the active gateway. Keep the forwarding +task running while using those endpoints. + +### Viewing local traces + +The gateway exports OTLP/gRPC to +`http://openshell-collector.observability.svc.cluster.local:4317` through the +default Skaffold values. Forward OTLP/gRPC and the trace UI to the host: + +```bash +mise run helm:k3s:forward +``` + +Open `http://127.0.0.1:18888` and exercise the gateway to inspect gateway and +Kubernetes compute-driver spans under their distinct service names, along with +Agent Sandbox controller reconciliation spans linked through the Sandbox +trace-context annotation. The same command exposes OTLP/gRPC on +`http://127.0.0.1:4317` and, when deployed, the Kubernetes gateway on +`http://127.0.0.1:8090`; the local `gateway`, `gateway:docker`, and `gateway:vm` +tasks export to the collector endpoint automatically. **HA test deploy** (two gateway replicas + external PostgreSQL Secret): uncomment `#- ci/values-high-availability.yaml` in `deploy/helm/openshell/skaffold.yaml`, diff --git a/Cargo.lock b/Cargo.lock index 65a50f0f39..afe6c33c7b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3974,15 +3974,22 @@ dependencies = [ name = "openshell-driver-kubernetes" version = "0.0.0" dependencies = [ + "bytes", "clap", "futures", + "http 1.4.0", + "http-body-util", "k8s-openapi", "kube", "kube-runtime", "miette", "notify", "openshell-core", + "openshell-otel", + "openshell-otel-test-support", "openshell-policy", + "opentelemetry", + "opentelemetry_sdk", "prost", "prost-types", "serde", @@ -3993,6 +4000,7 @@ dependencies = [ "tokio-stream", "toml", "tonic", + "tower 0.5.3", "tracing", "tracing-subscriber", ] diff --git a/crates/openshell-driver-kubernetes/Cargo.toml b/crates/openshell-driver-kubernetes/Cargo.toml index 714b7d05c9..d7fcf19a17 100644 --- a/crates/openshell-driver-kubernetes/Cargo.toml +++ b/crates/openshell-driver-kubernetes/Cargo.toml @@ -16,6 +16,7 @@ path = "src/main.rs" [dependencies] openshell-core = { path = "../openshell-core", default-features = false } +openshell-otel = { path = "../openshell-otel" } openshell-policy = { path = "../openshell-policy" } tokio = { workspace = true } @@ -37,8 +38,15 @@ miette = { workspace = true } notify = "8" [dev-dependencies] +openshell-otel-test-support = { path = "../openshell-otel-test-support" } +opentelemetry = { workspace = true } +opentelemetry_sdk = { workspace = true, features = ["testing"] } +bytes = { workspace = true } +http = { workspace = true } +http-body-util = { workspace = true } temp-env = "0.3" toml = { workspace = true } +tower = { workspace = true } [lints] workspace = true diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index fac220c83b..b352f6efe9 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -19,6 +19,17 @@ workspace namespace modes via `workspace_mode`: gateway state; it never deletes or otherwise accesses the operator-managed Kubernetes namespace. +When the gateway configures `[openshell.gateway.otlp]`, Kubernetes +compute-driver spans export to the same OTLP/gRPC collector with the service +name `openshell-driver-kubernetes`. The driver preserves the gateway trace +context and uses the same compute-driver RPC span names in its in-process and +standalone forms. + +When it creates an Agent Sandbox resource, the driver serializes the active W3C +trace context into the controller-reserved `opentelemetry.io/trace-context` +annotation. An OTLP-enabled Agent Sandbox controller can therefore attach its +asynchronous reconciliation spans to the originating OpenShell create trace. + Workspace namespace modes assume exclusive control of the sandbox identity resource chain. In shared and managed modes, only the gateway and its trusted Agent Sandbox controller may administer the sandbox namespace, Sandbox CRs, diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 84d7029de4..c1885870e8 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -62,6 +62,7 @@ pub type WatchStream = Pin> + Send>>; const MANAGED_SSH_NETWORK_POLICY_NAME: &str = "openshell-sandbox-ssh"; +const AGENT_SANDBOX_TRACE_CONTEXT_ANNOTATION: &str = "opentelemetry.io/trace-context"; #[derive(Debug, thiserror::Error)] pub enum KubernetesDriverError { @@ -467,6 +468,23 @@ impl std::fmt::Debug for KubernetesComputeDriver { } impl KubernetesComputeDriver { + #[cfg(test)] + pub(crate) fn new_for_test(config: KubernetesComputeConfig) -> Self { + let service = tower::service_fn(|_request: http::Request| async { + Ok::<_, std::convert::Infallible>(http::Response::new(http_body_util::Empty::< + bytes::Bytes, + >::new())) + }); + let client = Client::new(service, "default"); + Self { + client: client.clone(), + watch_client: client, + sandbox_api_version: Arc::new(OnceCell::new()), + config, + operator_allowlist: None, + } + } + pub async fn new( config: KubernetesComputeConfig, shutdown_rx: tokio::sync::watch::Receiver, @@ -1339,7 +1357,24 @@ impl KubernetesComputeDriver { } #[allow(clippy::similar_names)] + #[tracing::instrument( + name = "kubernetes.create_sandbox", + skip(self, sandbox), + fields( + otel.name = "kubernetes.create_sandbox", + otel.status_code = tracing::field::Empty, + sandbox.id = %sandbox.id, + sandbox.name = %sandbox.name, + ) + )] pub async fn create_sandbox(&self, sandbox: &Sandbox) -> Result<(), KubernetesDriverError> { + let span_status = openshell_otel::ErrorStatusGuard::current(); + let result = self.create_sandbox_inner(sandbox).await; + span_status.finish(result) + } + + #[allow(clippy::similar_names)] + async fn create_sandbox_inner(&self, sandbox: &Sandbox) -> Result<(), KubernetesDriverError> { let gpu_requirements = sandbox .spec .as_ref() @@ -1444,6 +1479,7 @@ impl KubernetesComputeDriver { let kube_name = self.config.kube_resource_name(workspace, name); let mut obj = DynamicObject::new(&kube_name, &agent_sandbox_api.resource); let mut annotations = sandbox_annotations(sandbox); + add_trace_context_annotation(&mut annotations); for key in [ crate::config::ANNOTATION_SCC_UID_RANGE, crate::config::ANNOTATION_SCC_SUPPLEMENTAL_GROUPS, @@ -1499,7 +1535,22 @@ impl KubernetesComputeDriver { } } + #[tracing::instrument( + name = "kubernetes.stop_sandbox", + skip(self), + fields( + otel.name = "kubernetes.stop_sandbox", + otel.status_code = tracing::field::Empty, + sandbox.id = %sandbox_id, + ) + )] pub async fn stop_sandbox(&self, sandbox_id: &str) -> Result<(), KubernetesDriverError> { + let span_status = openshell_otel::ErrorStatusGuard::current(); + let result = self.stop_sandbox_inner(sandbox_id).await; + span_status.finish(result) + } + + async fn stop_sandbox_inner(&self, sandbox_id: &str) -> Result<(), KubernetesDriverError> { let (agent_sandbox_api, kube_name, pod_name, namespace, stop_timeout) = self .patch_sandbox_operating_state(sandbox_id, false) .await?; @@ -1554,10 +1605,22 @@ impl KubernetesComputeDriver { } } + #[tracing::instrument( + name = "kubernetes.start_sandbox", + skip(self), + fields( + otel.name = "kubernetes.start_sandbox", + otel.status_code = tracing::field::Empty, + sandbox.id = %sandbox_id, + ) + )] pub async fn start_sandbox(&self, sandbox_id: &str) -> Result<(), KubernetesDriverError> { - self.patch_sandbox_operating_state(sandbox_id, true) + let span_status = openshell_otel::ErrorStatusGuard::current(); + let result = self + .patch_sandbox_operating_state(sandbox_id, true) .await - .map(|_| ()) + .map(|_| ()); + span_status.finish(result) } async fn patch_sandbox_operating_state( @@ -1648,7 +1711,22 @@ impl KubernetesComputeDriver { )) } + #[tracing::instrument( + name = "kubernetes.delete_sandbox", + skip(self), + fields( + otel.name = "kubernetes.delete_sandbox", + otel.status_code = tracing::field::Empty, + sandbox.id = %sandbox_id, + ) + )] pub async fn delete_sandbox(&self, sandbox_id: &str) -> Result { + let span_status = openshell_otel::ErrorStatusGuard::current(); + let result = self.delete_sandbox_inner(sandbox_id).await; + span_status.finish(result) + } + + async fn delete_sandbox_inner(&self, sandbox_id: &str) -> Result { info!( sandbox_id = %sandbox_id, workspace_mode = %self.config.workspace_mode, @@ -1968,6 +2046,15 @@ impl KubernetesComputeDriver { } } +fn add_trace_context_annotation(annotations: &mut BTreeMap) { + let Some(carrier) = openshell_otel::current_trace_context_carrier() else { + return; + }; + if let Ok(value) = serde_json::to_string(&carrier) { + annotations.insert(AGENT_SANDBOX_TRACE_CONTEXT_ANNOTATION.to_string(), value); + } +} + fn should_try_next_sandbox_api_version(err: &KubeError) -> bool { // Kubernetes returns a structured 404 for some missing API resources and a // raw "404 page not found" body for others. Both mean the probed @@ -4561,6 +4648,74 @@ mod tests { static ENV_LOCK: std::sync::LazyLock> = std::sync::LazyLock::new(|| std::sync::Mutex::new(())); + #[tokio::test] + async fn tracing_create_sandbox_failure_exports_a_kubernetes_operation_span() { + use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; + use tracing::instrument::WithSubscriber as _; + use tracing_subscriber::layer::SubscriberExt as _; + + let _tracing_lock = crate::otel_tracing::test_lock().await; + let exporter = InMemorySpanExporterBuilder::new().build(); + let provider = SdkTracerProvider::builder() + .with_simple_exporter(exporter.clone()) + .build(); + let subscriber = tracing_subscriber::registry().with(crate::otel_tracing::layer(&provider)); + let driver = KubernetesComputeDriver::new_for_test(KubernetesComputeConfig::default()); + + driver + .create_sandbox(&Sandbox::default()) + .with_subscriber(subscriber) + .await + .expect_err("missing sandbox name should fail"); + provider.force_flush().unwrap(); + + let spans = exporter.get_finished_spans().unwrap(); + let span = spans + .iter() + .find(|span| span.name == "kubernetes.create_sandbox") + .expect("create operation span"); + assert!(matches!( + span.status, + opentelemetry::trace::Status::Error { .. } + )); + provider.shutdown().unwrap(); + } + + #[tokio::test] + async fn sandbox_annotation_propagates_the_active_w3c_trace_context() { + use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; + use tracing_subscriber::layer::SubscriberExt as _; + + let _tracing_lock = crate::otel_tracing::test_lock().await; + let exporter = InMemorySpanExporterBuilder::new().build(); + let provider = SdkTracerProvider::builder() + .with_simple_exporter(exporter) + .build(); + let subscriber = tracing_subscriber::registry().with(crate::otel_tracing::layer(&provider)); + + let annotations = tracing::subscriber::with_default(subscriber, || { + let span = tracing::info_span!("kubernetes.create_sandbox"); + let _entered = span.enter(); + let mut annotations = BTreeMap::new(); + add_trace_context_annotation(&mut annotations); + annotations + }); + + let carrier: serde_json::Value = serde_json::from_str( + annotations + .get("opentelemetry.io/trace-context") + .expect("agent-sandbox trace-context annotation"), + ) + .expect("annotation should contain a JSON propagation carrier"); + let traceparent = carrier["traceparent"] + .as_str() + .expect("carrier should contain traceparent"); + assert!(traceparent.starts_with("00-")); + assert_eq!(traceparent.len(), 55); + + provider.shutdown().unwrap(); + } + fn json_struct(value: serde_json::Value) -> Struct { let serde_json::Value::Object(object) = value else { panic!("expected JSON object"); diff --git a/crates/openshell-driver-kubernetes/src/grpc.rs b/crates/openshell-driver-kubernetes/src/grpc.rs index ce23cf0189..383ddebe0c 100644 --- a/crates/openshell-driver-kubernetes/src/grpc.rs +++ b/crates/openshell-driver-kubernetes/src/grpc.rs @@ -14,21 +14,109 @@ use openshell_core::proto::compute::v1::{ ValidateSandboxCreateRequest, ValidateSandboxCreateResponse, WatchSandboxesEvent, WatchSandboxesRequest, compute_driver_server::ComputeDriver, }; +use std::future::Future; use std::pin::Pin; +use std::task::{Context, Poll}; use tonic::{Request, Response, Status}; +use tracing::Instrument as _; use crate::KubernetesComputeDriver; use crate::WorkspaceMode; +type ComputeDriverWatchStream = + Pin> + Send + 'static>>; + +struct TracedWatchStream { + inner: ComputeDriverWatchStream, + span: tracing::Span, +} + +impl Stream for TracedWatchStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let span = self.span.clone(); + let _entered = span.enter(); + let result = self.inner.as_mut().poll_next(cx); + match &result { + Poll::Ready(Some(Err(status))) => { + openshell_otel::mark_error(&self.span); + self.span + .record("rpc.grpc.status_code", status.code() as i32); + } + Poll::Ready(None) => { + self.span + .record("rpc.grpc.status_code", tonic::Code::Ok as i32); + } + Poll::Pending | Poll::Ready(Some(Ok(_))) => {} + } + result + } +} + #[derive(Debug, Clone)] pub struct ComputeDriverService { driver: KubernetesComputeDriver, + trace_in_process_rpc: bool, } impl ComputeDriverService { #[must_use] pub fn new(driver: KubernetesComputeDriver) -> Self { - Self { driver } + Self { + driver, + trace_in_process_rpc: false, + } + } + + #[must_use] + pub fn new_in_process(driver: KubernetesComputeDriver) -> Self { + Self { + driver, + trace_in_process_rpc: true, + } + } + + fn in_process_rpc_span( + &self, + operation: &'static str, + method: &'static str, + ) -> Option { + self.trace_in_process_rpc.then(|| { + tracing::info_span!( + target: "openshell_driver_kubernetes::otel_tracing", + "driver_rpc", + otel.name = operation, + otel.kind = "server", + otel.status_code = tracing::field::Empty, + rpc.system = "grpc", + rpc.service = "openshell.compute.v1.ComputeDriver", + rpc.method = method, + rpc.grpc.status_code = tracing::field::Empty, + ) + }) + } + + async fn trace_rpc( + &self, + operation: &'static str, + method: &'static str, + future: impl Future>, + ) -> Result { + let Some(span) = self.in_process_rpc_span(operation, method) else { + return future.await; + }; + let result = future.instrument(span.clone()).await; + match &result { + Ok(_) => { + span.record("rpc.grpc.status_code", tonic::Code::Ok as i32); + } + Err(status) => { + openshell_otel::mark_error(&span); + span.record("rpc.grpc.status_code", status.code() as i32); + } + } + result } } @@ -38,193 +126,250 @@ impl ComputeDriver for ComputeDriverService { &self, _request: Request, ) -> Result, Status> { - self.driver - .capabilities() - .map(Response::new) - .map_err(Status::internal) + self.trace_rpc("driver.get_capabilities", "get_capabilities", async { + self.driver + .capabilities() + .map(Response::new) + .map_err(Status::internal) + }) + .await } async fn get_gateway_listener_requirements( &self, _request: Request, ) -> Result, Status> { - Ok(Response::new(GetGatewayListenerRequirementsResponse { - requirements: Vec::new(), - })) + self.trace_rpc( + "driver.get_gateway_listener_requirements", + "get_gateway_listener_requirements", + async { + Ok(Response::new(GetGatewayListenerRequirementsResponse { + requirements: Vec::new(), + })) + }, + ) + .await } async fn validate_sandbox_create( &self, request: Request, ) -> Result, Status> { - let sandbox = request - .into_inner() - .sandbox - .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; - self.driver.validate_sandbox_create(&sandbox).await?; - Ok(Response::new(ValidateSandboxCreateResponse {})) + self.trace_rpc( + "driver.validate_sandbox_create", + "validate_sandbox_create", + async { + let sandbox = request + .into_inner() + .sandbox + .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; + self.driver.validate_sandbox_create(&sandbox).await?; + Ok(Response::new(ValidateSandboxCreateResponse {})) + }, + ) + .await } async fn get_sandbox( &self, request: Request, ) -> Result, Status> { - let request = request.into_inner(); - if request.sandbox_id.is_empty() { - return Err(Status::invalid_argument("sandbox_id is required")); - } - - let sandbox = self - .driver - .get_sandbox(&request.sandbox_id) - .await - .map_err(Status::internal)? - .ok_or_else(|| Status::not_found("sandbox not found"))?; - - Ok(Response::new(GetSandboxResponse { - sandbox: Some(sandbox), - })) + self.trace_rpc("driver.get_sandbox", "get_sandbox", async { + let request = request.into_inner(); + if request.sandbox_id.is_empty() { + return Err(Status::invalid_argument("sandbox_id is required")); + } + let sandbox = self + .driver + .get_sandbox(&request.sandbox_id) + .await + .map_err(Status::internal)? + .ok_or_else(|| Status::not_found("sandbox not found"))?; + Ok(Response::new(GetSandboxResponse { + sandbox: Some(sandbox), + })) + }) + .await } async fn list_sandboxes( &self, _request: Request, ) -> Result, Status> { - let sandboxes = self - .driver - .list_sandboxes() - .await - .map_err(Status::internal)?; - Ok(Response::new(ListSandboxesResponse { sandboxes })) + self.trace_rpc("driver.list_sandboxes", "list_sandboxes", async { + let sandboxes = self + .driver + .list_sandboxes() + .await + .map_err(Status::internal)?; + Ok(Response::new(ListSandboxesResponse { sandboxes })) + }) + .await } async fn create_sandbox( &self, request: Request, ) -> Result, Status> { - let sandbox = request - .into_inner() - .sandbox - .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; - self.driver - .create_sandbox(&sandbox) - .await - .map_err(|e| Status::from(openshell_core::ComputeDriverError::from(e)))?; - Ok(Response::new(CreateSandboxResponse {})) + self.trace_rpc("driver.create_sandbox", "create_sandbox", async { + let sandbox = request + .into_inner() + .sandbox + .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; + self.driver + .create_sandbox(&sandbox) + .await + .map_err(|e| Status::from(openshell_core::ComputeDriverError::from(e)))?; + Ok(Response::new(CreateSandboxResponse {})) + }) + .await } async fn stop_sandbox( &self, request: Request, ) -> Result, Status> { - let request = request.into_inner(); - if request.sandbox_id.is_empty() { - return Err(Status::invalid_argument("sandbox_id is required")); - } - self.driver - .stop_sandbox(&request.sandbox_id) - .await - .map_err(|error| Status::from(openshell_core::ComputeDriverError::from(error)))?; - Ok(Response::new(StopSandboxResponse {})) + self.trace_rpc("driver.stop_sandbox", "stop_sandbox", async { + let request = request.into_inner(); + if request.sandbox_id.is_empty() { + return Err(Status::invalid_argument("sandbox_id is required")); + } + self.driver + .stop_sandbox(&request.sandbox_id) + .await + .map_err(|error| Status::from(openshell_core::ComputeDriverError::from(error)))?; + Ok(Response::new(StopSandboxResponse {})) + }) + .await } async fn start_sandbox( &self, request: Request, ) -> Result, Status> { - let request = request.into_inner(); - if request.sandbox_id.is_empty() { - return Err(Status::invalid_argument("sandbox_id is required")); - } - self.driver - .start_sandbox(&request.sandbox_id) - .await - .map_err(|error| Status::from(openshell_core::ComputeDriverError::from(error)))?; - Ok(Response::new(StartSandboxResponse {})) + self.trace_rpc("driver.start_sandbox", "start_sandbox", async { + let request = request.into_inner(); + if request.sandbox_id.is_empty() { + return Err(Status::invalid_argument("sandbox_id is required")); + } + self.driver + .start_sandbox(&request.sandbox_id) + .await + .map_err(|error| Status::from(openshell_core::ComputeDriverError::from(error)))?; + Ok(Response::new(StartSandboxResponse {})) + }) + .await } async fn delete_sandbox( &self, request: Request, ) -> Result, Status> { - let request = request.into_inner(); - if request.sandbox_id.is_empty() { - return Err(Status::invalid_argument("sandbox_id is required")); - } - let deleted = self - .driver - .delete_sandbox(&request.sandbox_id) - .await - .map_err(Status::internal)?; - Ok(Response::new(DeleteSandboxResponse { deleted })) + self.trace_rpc("driver.delete_sandbox", "delete_sandbox", async { + let request = request.into_inner(); + if request.sandbox_id.is_empty() { + return Err(Status::invalid_argument("sandbox_id is required")); + } + let deleted = self + .driver + .delete_sandbox(&request.sandbox_id) + .await + .map_err(Status::internal)?; + Ok(Response::new(DeleteSandboxResponse { deleted })) + }) + .await } - type WatchSandboxesStream = - Pin> + Send + 'static>>; + type WatchSandboxesStream = ComputeDriverWatchStream; async fn watch_sandboxes( &self, _request: Request, ) -> Result, Status> { - let stream = self - .driver - .watch_sandboxes() - .await - .map_err(Status::internal)?; - let stream = stream.map(|item| item.map_err(|err| Status::internal(err.to_string()))); - Ok(Response::new(Box::pin(stream))) + let create_stream = async { + let stream = self + .driver + .watch_sandboxes() + .await + .map_err(Status::internal)?; + let stream = stream.map(|item| item.map_err(|err| Status::internal(err.to_string()))); + Ok::(Box::pin(stream)) + }; + let Some(span) = self.in_process_rpc_span("driver.watch_sandboxes", "watch_sandboxes") + else { + return create_stream.await.map(Response::new); + }; + match create_stream.instrument(span.clone()).await { + Ok(stream) => Ok(Response::new(Box::pin(TracedWatchStream { + inner: stream, + span, + }))), + Err(status) => { + openshell_otel::mark_error(&span); + span.record("rpc.grpc.status_code", status.code() as i32); + Err(status) + } + } } async fn ensure_workspace( &self, request: Request, ) -> Result, Status> { - let workspace = request.into_inner().workspace; - if workspace.is_empty() { - return Err(Status::invalid_argument("workspace is required")); - } - self.driver - .validate_workspace_namespace(&workspace) - .map_err(|error| Status::from(openshell_core::ComputeDriverError::from(error)))?; - match self.driver.workspace_mode() { - WorkspaceMode::Managed => { - self.driver - .ensure_namespace(&workspace) - .await - .map_err(|e| Status::internal(e.to_string()))?; + self.trace_rpc("driver.ensure_workspace", "ensure_workspace", async { + let workspace = request.into_inner().workspace; + if workspace.is_empty() { + return Err(Status::invalid_argument("workspace is required")); } - WorkspaceMode::Operator => { - if let Some(allowlist) = self.driver.operator_allowlist() - && !allowlist.contains(&workspace) - { - return Err(Status::permission_denied(format!( - "workspace '{workspace}' is not in the operator namespace allowlist" - ))); + self.driver + .validate_workspace_namespace(&workspace) + .map_err(|error| Status::from(openshell_core::ComputeDriverError::from(error)))?; + match self.driver.workspace_mode() { + WorkspaceMode::Managed => { + self.driver + .ensure_namespace(&workspace) + .await + .map_err(|e| Status::internal(e.to_string()))?; + } + WorkspaceMode::Operator => { + if let Some(allowlist) = self.driver.operator_allowlist() + && !allowlist.contains(&workspace) + { + return Err(Status::permission_denied(format!( + "workspace '{workspace}' is not in the operator namespace allowlist" + ))); + } } + WorkspaceMode::Shared => {} } - WorkspaceMode::Shared => {} - } - Ok(Response::new(EnsureWorkspaceResponse {})) + Ok(Response::new(EnsureWorkspaceResponse {})) + }) + .await } async fn delete_workspace( &self, request: Request, ) -> Result, Status> { - let workspace = request.into_inner().workspace; - if workspace.is_empty() { - return Err(Status::invalid_argument("workspace is required")); - } - if workspace_delete_requires_namespace_access(self.driver.workspace_mode()) { - self.driver - .validate_workspace_namespace(&workspace) - .map_err(|error| Status::from(openshell_core::ComputeDriverError::from(error)))?; - self.driver - .delete_namespace(&workspace) - .await - .map_err(|e| Status::internal(e.to_string()))?; - } - Ok(Response::new(DeleteWorkspaceResponse {})) + self.trace_rpc("driver.delete_workspace", "delete_workspace", async { + let workspace = request.into_inner().workspace; + if workspace.is_empty() { + return Err(Status::invalid_argument("workspace is required")); + } + if workspace_delete_requires_namespace_access(self.driver.workspace_mode()) { + self.driver + .validate_workspace_namespace(&workspace) + .map_err(|error| { + Status::from(openshell_core::ComputeDriverError::from(error)) + })?; + self.driver + .delete_namespace(&workspace) + .await + .map_err(|e| Status::internal(e.to_string()))?; + } + Ok(Response::new(DeleteWorkspaceResponse {})) + }) + .await } } @@ -239,6 +384,192 @@ mod tests { use openshell_core::ComputeDriverError; use tonic::Status; + #[tokio::test] + async fn tracing_in_process_service_preserves_the_driver_rpc_server_boundary() { + use super::*; + use crate::KubernetesComputeConfig; + use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; + use tracing::instrument::WithSubscriber as _; + use tracing_subscriber::layer::SubscriberExt as _; + + let _tracing_lock = crate::otel_tracing::test_lock().await; + let gateway_exporter = InMemorySpanExporterBuilder::new().build(); + let gateway_provider = SdkTracerProvider::builder() + .with_simple_exporter(gateway_exporter.clone()) + .build(); + let driver_exporter = InMemorySpanExporterBuilder::new().build(); + let driver_provider = SdkTracerProvider::builder() + .with_simple_exporter(driver_exporter.clone()) + .build(); + let subscriber = tracing_subscriber::registry() + .with(openshell_otel::layer_excluding_target_prefix( + &gateway_provider, + "gateway-test", + Some(crate::otel_tracing::IN_PROCESS_TARGET_PREFIX), + )) + .with(crate::otel_tracing::in_process_layer(&driver_provider)); + let service = ComputeDriverService::new_in_process(KubernetesComputeDriver::new_for_test( + KubernetesComputeConfig::default(), + )); + + async { + let gateway_span = tracing::info_span!( + target: "openshell_server::compute", + "driver", + otel.name = "driver.get_capabilities", + otel.kind = "client" + ); + ComputeDriver::get_capabilities(&service, Request::new(GetCapabilitiesRequest {})) + .instrument(gateway_span) + .await?; + + ComputeDriver::validate_sandbox_create( + &service, + Request::new(ValidateSandboxCreateRequest { sandbox: None }), + ) + .await + } + .with_subscriber(subscriber) + .await + .expect_err("missing sandbox should fail"); + gateway_provider.force_flush().unwrap(); + driver_provider.force_flush().unwrap(); + + let gateway_spans = gateway_exporter.get_finished_spans().unwrap(); + let driver_spans = driver_exporter.get_finished_spans().unwrap(); + let client = gateway_spans + .iter() + .find(|span| span.name == "driver.get_capabilities") + .expect("gateway client span"); + let server = driver_spans + .iter() + .find(|span| span.name == "driver.get_capabilities") + .expect("in-process server span"); + assert_eq!( + server.span_context.trace_id(), + client.span_context.trace_id() + ); + assert_eq!(server.parent_span_id, client.span_context.span_id()); + assert_eq!(server.span_kind, opentelemetry::trace::SpanKind::Server); + assert!(server.attributes.iter().any(|attribute| { + attribute.key.as_str() == "rpc.grpc.status_code" + && attribute.value.to_string() == (tonic::Code::Ok as i32).to_string() + })); + let failed = driver_spans + .iter() + .find(|span| span.name == "driver.validate_sandbox_create") + .expect("failed in-process server span"); + assert!(matches!( + failed.status, + opentelemetry::trace::Status::Error { .. } + )); + gateway_provider.shutdown().unwrap(); + driver_provider.shutdown().unwrap(); + } + + #[tokio::test] + async fn tracing_in_process_stream_span_lives_until_stream_failure() { + use super::*; + use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; + use tracing::instrument::WithSubscriber as _; + use tracing_subscriber::layer::SubscriberExt as _; + + let _tracing_lock = crate::otel_tracing::test_lock().await; + let exporter = InMemorySpanExporterBuilder::new().build(); + let provider = SdkTracerProvider::builder() + .with_simple_exporter(exporter.clone()) + .build(); + let subscriber = + tracing_subscriber::registry().with(crate::otel_tracing::in_process_layer(&provider)); + + async { + let span = tracing::info_span!( + target: "openshell_driver_kubernetes::otel_tracing", + "driver_rpc", + otel.name = "driver.watch_sandboxes", + otel.kind = "server", + otel.status_code = tracing::field::Empty, + rpc.grpc.status_code = tracing::field::Empty, + ); + let inner: ComputeDriverWatchStream = Box::pin(futures::stream::iter([Err( + Status::internal("watch failed"), + )])); + let mut stream = TracedWatchStream { inner, span }; + + provider.force_flush().unwrap(); + assert!( + exporter.get_finished_spans().unwrap().is_empty(), + "server span must remain open while the response stream is alive" + ); + stream + .next() + .await + .expect("stream item") + .expect_err("stream should fail"); + drop(stream); + } + .with_subscriber(subscriber) + .await; + provider.force_flush().unwrap(); + + let spans = exporter.get_finished_spans().unwrap(); + let span = spans + .iter() + .find(|span| span.name == "driver.watch_sandboxes") + .expect("watch server span should be exported when the stream ends"); + assert!(matches!( + span.status, + opentelemetry::trace::Status::Error { .. } + )); + provider.shutdown().unwrap(); + } + + #[tokio::test] + async fn tracing_in_process_stream_records_ok_when_stream_completes() { + use super::*; + use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; + use tracing::instrument::WithSubscriber as _; + use tracing_subscriber::layer::SubscriberExt as _; + + let _tracing_lock = crate::otel_tracing::test_lock().await; + let exporter = InMemorySpanExporterBuilder::new().build(); + let provider = SdkTracerProvider::builder() + .with_simple_exporter(exporter.clone()) + .build(); + let subscriber = + tracing_subscriber::registry().with(crate::otel_tracing::in_process_layer(&provider)); + + async { + let span = tracing::info_span!( + target: "openshell_driver_kubernetes::otel_tracing", + "driver_rpc", + otel.name = "driver.watch_sandboxes", + otel.kind = "server", + otel.status_code = tracing::field::Empty, + rpc.grpc.status_code = tracing::field::Empty, + ); + let inner: ComputeDriverWatchStream = Box::pin(futures::stream::empty()); + let mut stream = TracedWatchStream { inner, span }; + + assert!(stream.next().await.is_none()); + drop(stream); + } + .with_subscriber(subscriber) + .await; + provider.force_flush().unwrap(); + + let spans = exporter.get_finished_spans().unwrap(); + let span = spans + .iter() + .find(|span| span.name == "driver.watch_sandboxes") + .expect("watch server span should be exported when the stream completes"); + assert!(span.attributes.iter().any(|attribute| { + attribute.key.as_str() == "rpc.grpc.status_code" + && attribute.value.to_string() == (tonic::Code::Ok as i32).to_string() + })); + provider.shutdown().unwrap(); + } + #[test] fn precondition_driver_errors_map_to_failed_precondition_status() { let status: Status = ComputeDriverError::from(KubernetesDriverError::Precondition( diff --git a/crates/openshell-driver-kubernetes/src/lib.rs b/crates/openshell-driver-kubernetes/src/lib.rs index d69f9749a1..edc0a3e97e 100644 --- a/crates/openshell-driver-kubernetes/src/lib.rs +++ b/crates/openshell-driver-kubernetes/src/lib.rs @@ -4,6 +4,7 @@ pub mod config; pub mod driver; pub mod grpc; +pub mod otel_tracing; pub use config::{ AppArmorProfile, DEFAULT_GATEWAY_ID, DEFAULT_PROXY_UID, DEFAULT_SANDBOX_SERVICE_ACCOUNT_NAME, diff --git a/crates/openshell-driver-kubernetes/src/main.rs b/crates/openshell-driver-kubernetes/src/main.rs index 3a805c8685..712cc1cbda 100644 --- a/crates/openshell-driver-kubernetes/src/main.rs +++ b/crates/openshell-driver-kubernetes/src/main.rs @@ -8,9 +8,11 @@ use std::net::SocketAddr; use std::path::PathBuf; use tracing::info; use tracing_subscriber::EnvFilter; +use tracing_subscriber::prelude::*; use openshell_core::VERSION; use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; +use openshell_driver_kubernetes::otel_tracing::compute_driver_rpc_layer; use openshell_driver_kubernetes::{ AppArmorProfile, ComputeDriverService, DEFAULT_GATEWAY_ID, DEFAULT_PROXY_UID, DEFAULT_SANDBOX_SERVICE_ACCOUNT_NAME, KubernetesComputeConfig, KubernetesComputeDriver, @@ -37,6 +39,9 @@ struct Args { #[arg(long, env = "OPENSHELL_LOG_LEVEL", default_value = "info")] log_level: String, + #[arg(long, env = "OPENSHELL_OTLP_ENDPOINT")] + otlp_endpoint: Option, + #[arg(long, env = "OPENSHELL_WORKSPACE_MODE", default_value = "shared")] workspace_mode: WorkspaceMode, @@ -210,11 +215,22 @@ async fn shutdown_signal() { #[tokio::main] async fn main() -> Result<()> { let args = Args::parse(); - tracing_subscriber::fmt() - .with_env_filter( - EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&args.log_level)), + let (tracer_provider, setup_error) = + openshell_driver_kubernetes::otel_tracing::provider_for(args.otlp_endpoint.as_deref()); + tracing_subscriber::registry() + .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&args.log_level))) + .with(tracing_subscriber::fmt::layer()) + .with( + tracer_provider + .as_ref() + .map(openshell_driver_kubernetes::otel_tracing::layer), ) .init(); + if let Some(error) = setup_error { + tracing::error!(%error, "OTLP exporting could not be started"); + } else if let Some(endpoint) = &args.otlp_endpoint { + info!(endpoint, "OTLP exporting enabled"); + } let managed_ssh_gateway_pod_selector = args .managed_ssh_gateway_pod_selector @@ -296,13 +312,14 @@ async fn main() -> Result<()> { shutdown_signal().await; let _ = shutdown_tx.send(true); }; - if let Some(socket_path) = args.bind_socket { + let result = if let Some(socket_path) = args.bind_socket { let listener = openshell_core::external_driver_socket::bind_private(&socket_path) .map_err(|err| miette::miette!("{err}"))?; let _cleanup = openshell_core::external_driver_socket::SocketCleanup::new(socket_path.clone()); info!(socket = %socket_path.display(), "Starting Kubernetes compute driver"); tonic::transport::Server::builder() + .layer(compute_driver_rpc_layer()) .add_service(service) .serve_with_incoming_shutdown( openshell_core::external_driver_socket::SameUidUnixIncoming::new(listener), @@ -313,9 +330,36 @@ async fn main() -> Result<()> { } else { info!(address = %args.bind_address, "Starting Kubernetes compute driver"); tonic::transport::Server::builder() + .layer(compute_driver_rpc_layer()) .add_service(service) .serve_with_shutdown(args.bind_address, shutdown) .await .into_diagnostic() + }; + if let Some(provider) = &tracer_provider + && let Err(error) = provider.shutdown() + { + tracing::warn!(%error, "OTLP tracer provider shutdown failed"); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accepts_gateway_otlp_endpoint() { + let args = Args::try_parse_from([ + "openshell-driver-kubernetes", + "--otlp-endpoint", + "http://collector.example:4317", + ]) + .expect("OTLP endpoint should parse"); + + assert_eq!( + args.otlp_endpoint.as_deref(), + Some("http://collector.example:4317") + ); } } diff --git a/crates/openshell-driver-kubernetes/src/otel_tracing.rs b/crates/openshell-driver-kubernetes/src/otel_tracing.rs new file mode 100644 index 0000000000..1a8d40071d --- /dev/null +++ b/crates/openshell-driver-kubernetes/src/otel_tracing.rs @@ -0,0 +1,108 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! OpenTelemetry trace exporting for the Kubernetes compute driver. + +use openshell_otel::{OtlpTraceConfig, SdkTracerProvider, ServiceName, SetupError}; +pub use openshell_otel::{compute_driver_rpc_layer, compute_driver_rpc_operation}; +use tracing::Subscriber; +use tracing_subscriber::registry::LookupSpan; + +const SERVICE_NAME: &str = "openshell-driver-kubernetes"; +const INSTRUMENTATION_SCOPE: &str = "openshell-driver-kubernetes"; +pub const IN_PROCESS_TARGET_PREFIX: &str = "openshell_driver_kubernetes"; + +#[must_use] +pub fn provider_for(endpoint: Option<&str>) -> (Option, Option) { + openshell_otel::provider_for(endpoint.map(|endpoint| OtlpTraceConfig { + endpoint, + service_name: ServiceName::Fixed(SERVICE_NAME), + service_version: Some(openshell_core::VERSION), + resource_attributes: Vec::new(), + })) +} + +pub fn layer(provider: &SdkTracerProvider) -> openshell_otel::OtlpLayer +where + S: Subscriber + for<'span> LookupSpan<'span>, +{ + openshell_otel::layer(provider, INSTRUMENTATION_SCOPE) +} + +pub fn in_process_layer(provider: &SdkTracerProvider) -> openshell_otel::TargetOtlpLayer +where + S: Subscriber + for<'span> LookupSpan<'span>, +{ + openshell_otel::layer_for_target_prefix( + provider, + INSTRUMENTATION_SCOPE, + IN_PROCESS_TARGET_PREFIX, + ) +} + +#[cfg(test)] +pub(crate) async fn test_lock() -> tokio::sync::MutexGuard<'static, ()> { + static LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + static INITIALIZED: std::sync::LazyLock<()> = std::sync::LazyLock::new(|| { + tracing::subscriber::set_global_default(tracing_subscriber::registry()) + .expect("test tracing subscriber installs once"); + }); + + let guard = LOCK.lock().await; + std::sync::LazyLock::force(&INITIALIZED); + guard +} + +#[cfg(test)] +mod tests { + use openshell_otel_test_support::OtlpTestServer; + use tracing_subscriber::layer::SubscriberExt as _; + + #[test] + fn compute_driver_rpc_names_are_explicitly_mapped_and_schema_bounded() { + assert_eq!( + super::compute_driver_rpc_operation( + "/openshell.compute.v1.ComputeDriver/GetCapabilities" + ), + ("driver.get_capabilities", "get_capabilities") + ); + assert_eq!( + super::compute_driver_rpc_operation( + "/openshell.compute.v1.ComputeDriver/AttackerControlled12345" + ), + ("driver.unknown", "unknown") + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn tracing_kubernetes_driver_spans_reach_otlp_collector_with_distinct_service_name() { + let _tracing_lock = super::test_lock().await; + let collector = OtlpTestServer::start().await; + let (provider, error) = super::provider_for(Some(collector.endpoint())); + assert!(error.is_none()); + let provider = provider.expect("provider"); + let subscriber = tracing_subscriber::registry().with(super::layer(&provider)); + tracing::subscriber::with_default(subscriber, || { + let span = tracing::info_span!("kubernetes.create_sandbox", sandbox.id = "sb-otlp"); + drop(span.enter()); + drop(span); + }); + provider.force_flush().unwrap(); + collector.wait_for_export().await; + provider.shutdown().unwrap(); + let received = collector.shutdown().await; + + assert!( + received + .spans + .iter() + .any(|span| span.name == "kubernetes.create_sandbox") + ); + assert!( + received + .service_names + .iter() + .any(|name| name == super::SERVICE_NAME) + ); + } +} diff --git a/crates/openshell-driver-podman/src/otel_tracing.rs b/crates/openshell-driver-podman/src/otel_tracing.rs index 51d42a88fe..00163c206e 100644 --- a/crates/openshell-driver-podman/src/otel_tracing.rs +++ b/crates/openshell-driver-podman/src/otel_tracing.rs @@ -3,92 +3,15 @@ //! OpenTelemetry trace exporting for the Podman compute driver. -use http::Request; -use openshell_otel::{ - HeaderMapExtractor, OtlpTraceConfig, RecordGrpcFailure, RecordGrpcStatus, SdkTracerProvider, - ServiceName, SetupError, -}; -use opentelemetry::propagation::TextMapPropagator as _; -use opentelemetry::trace::TraceContextExt as _; -use opentelemetry_sdk::propagation::TraceContextPropagator; -use tower_http::trace::{GrpcMakeClassifier, MakeSpan, TraceLayer}; -use tracing::{Span, Subscriber}; -use tracing_opentelemetry::OpenTelemetrySpanExt as _; +use openshell_otel::{OtlpTraceConfig, SdkTracerProvider, ServiceName, SetupError}; +pub use openshell_otel::{compute_driver_rpc_layer, compute_driver_rpc_operation}; +use tracing::Subscriber; use tracing_subscriber::registry::LookupSpan; const SERVICE_NAME: &str = "openshell-driver-podman"; const INSTRUMENTATION_SCOPE: &str = "openshell-driver-podman"; -const COMPUTE_DRIVER_SERVICE: &str = "openshell.compute.v1.ComputeDriver"; pub const IN_PROCESS_TARGET_PREFIX: &str = "openshell_driver_podman"; -pub fn compute_driver_rpc_layer() -> TraceLayer< - GrpcMakeClassifier, - ComputeDriverRpcSpan, - (), - RecordGrpcStatus, - (), - RecordGrpcStatus, - RecordGrpcFailure, -> { - TraceLayer::new_for_grpc() - .make_span_with(ComputeDriverRpcSpan) - .on_request(()) - .on_response(RecordGrpcStatus) - .on_body_chunk(()) - .on_eos(RecordGrpcStatus) - .on_failure(RecordGrpcFailure) -} - -#[derive(Debug, Clone, Copy)] -pub struct ComputeDriverRpcSpan; - -impl MakeSpan for ComputeDriverRpcSpan { - fn make_span(&mut self, request: &Request) -> Span { - let (operation, method) = compute_driver_rpc_operation(request.uri().path()); - let span = tracing::info_span!( - "driver_rpc", - otel.name = operation, - otel.kind = "server", - otel.status_code = tracing::field::Empty, - rpc.system = "grpc", - rpc.service = COMPUTE_DRIVER_SERVICE, - rpc.method = method, - rpc.grpc.status_code = tracing::field::Empty, - ); - let parent = TraceContextPropagator::new().extract_with_context( - &opentelemetry::Context::new(), - &HeaderMapExtractor::new(request.headers()), - ); - if parent.span().span_context().is_valid() { - let _ = span.set_parent(parent); - } - span - } -} - -pub(crate) fn compute_driver_rpc_operation(path: &str) -> (&'static str, &'static str) { - match path.rsplit('/').next() { - Some("GetCapabilities") => ("driver.get_capabilities", "get_capabilities"), - Some("GetGatewayListenerRequirements") => ( - "driver.get_gateway_listener_requirements", - "get_gateway_listener_requirements", - ), - Some("ValidateSandboxCreate") => { - ("driver.validate_sandbox_create", "validate_sandbox_create") - } - Some("CreateSandbox") => ("driver.create_sandbox", "create_sandbox"), - Some("GetSandbox") => ("driver.get_sandbox", "get_sandbox"), - Some("ListSandboxes") => ("driver.list_sandboxes", "list_sandboxes"), - Some("StopSandbox") => ("driver.stop_sandbox", "stop_sandbox"), - Some("StartSandbox") => ("driver.start_sandbox", "start_sandbox"), - Some("DeleteSandbox") => ("driver.delete_sandbox", "delete_sandbox"), - Some("WatchSandboxes") => ("driver.watch_sandboxes", "watch_sandboxes"), - Some("EnsureWorkspace") => ("driver.ensure_workspace", "ensure_workspace"), - Some("DeleteWorkspace") => ("driver.delete_workspace", "delete_workspace"), - _ => ("driver.unknown", "unknown"), - } -} - #[must_use] pub fn provider_for(endpoint: Option<&str>) -> (Option, Option) { openshell_otel::provider_for(endpoint.map(|endpoint| OtlpTraceConfig { @@ -200,7 +123,7 @@ mod tests { let provider = provider.expect("provider"); let subscriber = tracing_subscriber::registry().with(super::layer(&provider)); tracing::subscriber::with_default(subscriber, || { - let span = tracing::info_span!("podman.create_sandbox", sandbox.id = "sb-otlp"); + let span = tracing::info_span!("podman.create", sandbox.id = "sb-otlp"); drop(span.enter()); drop(span); }); @@ -213,7 +136,7 @@ mod tests { received .spans .iter() - .any(|span| span.name == "podman.create_sandbox") + .any(|span| span.name == "podman.create") ); assert!( received diff --git a/crates/openshell-driver-vm/src/otel_tracing.rs b/crates/openshell-driver-vm/src/otel_tracing.rs index e956e8310d..f63066bb88 100644 --- a/crates/openshell-driver-vm/src/otel_tracing.rs +++ b/crates/openshell-driver-vm/src/otel_tracing.rs @@ -3,90 +3,13 @@ //! OpenTelemetry trace exporting. -use http::Request; -use openshell_otel::{ - HeaderMapExtractor, OtlpTraceConfig, RecordGrpcFailure, RecordGrpcStatus, SdkTracerProvider, - ServiceName, SetupError, -}; -use opentelemetry::propagation::TextMapPropagator; -use opentelemetry::trace::TraceContextExt as _; -use opentelemetry_sdk::propagation::TraceContextPropagator; -use tower_http::trace::{GrpcMakeClassifier, MakeSpan, TraceLayer}; -use tracing::{Span, Subscriber}; -use tracing_opentelemetry::OpenTelemetrySpanExt as _; +use openshell_otel::{OtlpTraceConfig, SdkTracerProvider, ServiceName, SetupError}; +pub use openshell_otel::{compute_driver_rpc_layer, compute_driver_rpc_operation}; +use tracing::Subscriber; use tracing_subscriber::registry::LookupSpan; const SERVICE_NAME: &str = "openshell-driver-vm"; const INSTRUMENTATION_SCOPE: &str = "openshell-driver-vm"; -const COMPUTE_DRIVER_SERVICE: &str = "openshell.compute.v1.ComputeDriver"; - -/// Trace every inbound compute-driver RPC at the tonic service boundary. -pub fn compute_driver_rpc_layer() -> TraceLayer< - GrpcMakeClassifier, - ComputeDriverRpcSpan, - (), - RecordGrpcStatus, - (), - RecordGrpcStatus, - RecordGrpcFailure, -> { - TraceLayer::new_for_grpc() - .make_span_with(ComputeDriverRpcSpan) - .on_request(()) - .on_response(RecordGrpcStatus) - .on_body_chunk(()) - .on_eos(RecordGrpcStatus) - .on_failure(RecordGrpcFailure) -} - -/// Creates the server span for an inbound compute-driver request. -#[derive(Debug, Clone, Copy)] -pub struct ComputeDriverRpcSpan; - -impl MakeSpan for ComputeDriverRpcSpan { - fn make_span(&mut self, request: &Request) -> Span { - let (operation, method) = compute_driver_rpc_operation(request.uri().path()); - let span = tracing::info_span!( - "driver_rpc", - otel.name = operation, - otel.kind = "server", - otel.status_code = tracing::field::Empty, - rpc.system = "grpc", - rpc.service = COMPUTE_DRIVER_SERVICE, - rpc.method = method, - rpc.grpc.status_code = tracing::field::Empty, - ); - let parent = TraceContextPropagator::new().extract_with_context( - &opentelemetry::Context::new(), - &HeaderMapExtractor::new(request.headers()), - ); - if parent.span().span_context().is_valid() { - let _ = span.set_parent(parent); - } - span - } -} - -fn compute_driver_rpc_operation(path: &str) -> (&'static str, &'static str) { - match path.rsplit('/').next() { - Some("GetCapabilities") => ("driver.get_capabilities", "get_capabilities"), - Some("GetGatewayListenerRequirements") => ( - "driver.get_gateway_listener_requirements", - "get_gateway_listener_requirements", - ), - Some("ValidateSandboxCreate") => { - ("driver.validate_sandbox_create", "validate_sandbox_create") - } - Some("CreateSandbox") => ("driver.create_sandbox", "create_sandbox"), - Some("GetSandbox") => ("driver.get_sandbox", "get_sandbox"), - Some("ListSandboxes") => ("driver.list_sandboxes", "list_sandboxes"), - Some("StopSandbox") => ("driver.stop_sandbox", "stop_sandbox"), - Some("StartSandbox") => ("driver.start_sandbox", "start_sandbox"), - Some("DeleteSandbox") => ("driver.delete_sandbox", "delete_sandbox"), - Some("WatchSandboxes") => ("driver.watch_sandboxes", "watch_sandboxes"), - _ => ("driver.unknown", "unknown"), - } -} /// Build a tracer provider for the configured OTLP/gRPC endpoint. #[must_use] diff --git a/crates/openshell-otel/src/grpc.rs b/crates/openshell-otel/src/grpc.rs index 564f889aeb..3c38ddd74a 100644 --- a/crates/openshell-otel/src/grpc.rs +++ b/crates/openshell-otel/src/grpc.rs @@ -3,9 +3,87 @@ //! Shared gRPC tracing adapters. +use http::Request; +use opentelemetry::propagation::TextMapPropagator as _; +use opentelemetry::trace::TraceContextExt as _; +use opentelemetry_sdk::propagation::TraceContextPropagator; use tower_http::classify::GrpcFailureClass; -use tower_http::trace::{OnEos, OnFailure, OnResponse}; +use tower_http::trace::{GrpcMakeClassifier, MakeSpan, OnEos, OnFailure, OnResponse, TraceLayer}; use tracing::Span; +use tracing_opentelemetry::OpenTelemetrySpanExt as _; + +const COMPUTE_DRIVER_SERVICE: &str = "openshell.compute.v1.ComputeDriver"; + +/// Trace every inbound compute-driver RPC at the tonic service boundary. +pub fn compute_driver_rpc_layer() -> TraceLayer< + GrpcMakeClassifier, + ComputeDriverRpcSpan, + (), + RecordGrpcStatus, + (), + RecordGrpcStatus, + RecordGrpcFailure, +> { + TraceLayer::new_for_grpc() + .make_span_with(ComputeDriverRpcSpan) + .on_request(()) + .on_response(RecordGrpcStatus) + .on_body_chunk(()) + .on_eos(RecordGrpcStatus) + .on_failure(RecordGrpcFailure) +} + +/// Creates a bounded server span for an inbound compute-driver request. +#[derive(Debug, Clone, Copy)] +pub struct ComputeDriverRpcSpan; + +impl MakeSpan for ComputeDriverRpcSpan { + fn make_span(&mut self, request: &Request) -> Span { + let (operation, method) = compute_driver_rpc_operation(request.uri().path()); + let span = tracing::info_span!( + "driver_rpc", + otel.name = operation, + otel.kind = "server", + otel.status_code = tracing::field::Empty, + rpc.system = "grpc", + rpc.service = COMPUTE_DRIVER_SERVICE, + rpc.method = method, + rpc.grpc.status_code = tracing::field::Empty, + ); + let parent = TraceContextPropagator::new().extract_with_context( + &opentelemetry::Context::new(), + &crate::HeaderMapExtractor::new(request.headers()), + ); + if parent.span().span_context().is_valid() { + let _ = span.set_parent(parent); + } + span + } +} + +/// Maps the generated compute-driver RPC schema to low-cardinality span names. +pub fn compute_driver_rpc_operation(path: &str) -> (&'static str, &'static str) { + match path.rsplit('/').next() { + Some("GetCapabilities") => ("driver.get_capabilities", "get_capabilities"), + Some("GetGatewayListenerRequirements") => ( + "driver.get_gateway_listener_requirements", + "get_gateway_listener_requirements", + ), + Some("ValidateSandboxCreate") => { + ("driver.validate_sandbox_create", "validate_sandbox_create") + } + Some("CreateSandbox") => ("driver.create_sandbox", "create_sandbox"), + Some("GetSandbox") => ("driver.get_sandbox", "get_sandbox"), + Some("ListSandboxes") => ("driver.list_sandboxes", "list_sandboxes"), + Some("StopSandbox") => ("driver.stop_sandbox", "stop_sandbox"), + Some("StartSandbox") => ("driver.start_sandbox", "start_sandbox"), + Some("DeleteSandbox") => ("driver.delete_sandbox", "delete_sandbox"), + Some("WatchSandboxes") => ("driver.watch_sandboxes", "watch_sandboxes"), + Some("EnsureWorkspace") => ("driver.ensure_workspace", "ensure_workspace"), + Some("DeleteWorkspace") => ("driver.delete_workspace", "delete_workspace"), + _ => ("driver.unknown", "unknown"), + } +} /// Records a non-OK gRPC outcome on the request span. #[derive(Debug, Clone, Copy)] @@ -70,6 +148,59 @@ mod tests { use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; use tracing_subscriber::layer::SubscriberExt as _; + #[test] + fn compute_driver_rpc_names_are_explicitly_mapped_and_schema_bounded() { + for (rpc, operation, method) in [ + ( + "GetCapabilities", + "driver.get_capabilities", + "get_capabilities", + ), + ( + "GetGatewayListenerRequirements", + "driver.get_gateway_listener_requirements", + "get_gateway_listener_requirements", + ), + ( + "ValidateSandboxCreate", + "driver.validate_sandbox_create", + "validate_sandbox_create", + ), + ("CreateSandbox", "driver.create_sandbox", "create_sandbox"), + ("GetSandbox", "driver.get_sandbox", "get_sandbox"), + ("ListSandboxes", "driver.list_sandboxes", "list_sandboxes"), + ("StopSandbox", "driver.stop_sandbox", "stop_sandbox"), + ("StartSandbox", "driver.start_sandbox", "start_sandbox"), + ("DeleteSandbox", "driver.delete_sandbox", "delete_sandbox"), + ( + "WatchSandboxes", + "driver.watch_sandboxes", + "watch_sandboxes", + ), + ( + "EnsureWorkspace", + "driver.ensure_workspace", + "ensure_workspace", + ), + ( + "DeleteWorkspace", + "driver.delete_workspace", + "delete_workspace", + ), + ] { + assert_eq!( + compute_driver_rpc_operation(&format!("/openshell.compute.v1.ComputeDriver/{rpc}")), + (operation, method) + ); + } + assert_eq!( + compute_driver_rpc_operation( + "/openshell.compute.v1.ComputeDriver/AttackerControlled12345" + ), + ("driver.unknown", "unknown") + ); + } + #[test] fn grpc_status_records_and_marks_non_ok_trailer_status() { let _tracing_lock = crate::test_lock(); diff --git a/crates/openshell-otel/src/lib.rs b/crates/openshell-otel/src/lib.rs index 81d9f7bf01..30a9d29730 100644 --- a/crates/openshell-otel/src/lib.rs +++ b/crates/openshell-otel/src/lib.rs @@ -6,8 +6,13 @@ mod grpc; mod propagation; -pub use grpc::{RecordGrpcFailure, RecordGrpcStatus}; -pub use propagation::{HeaderMapExtractor, MetadataMapInjector, TraceContextInterceptor}; +pub use grpc::{ + ComputeDriverRpcSpan, RecordGrpcFailure, RecordGrpcStatus, compute_driver_rpc_layer, + compute_driver_rpc_operation, +}; +pub use propagation::{ + HeaderMapExtractor, MetadataMapInjector, TraceContextInterceptor, current_trace_context_carrier, +}; use opentelemetry::KeyValue; use opentelemetry::trace::TracerProvider as _; diff --git a/crates/openshell-otel/src/propagation.rs b/crates/openshell-otel/src/propagation.rs index 8deb2ffe20..c6e51a0a6b 100644 --- a/crates/openshell-otel/src/propagation.rs +++ b/crates/openshell-otel/src/propagation.rs @@ -3,6 +3,8 @@ //! W3C trace-context propagation for HTTP and tonic transports. +use std::collections::BTreeMap; + use http::HeaderMap; use opentelemetry::propagation::{Extractor, Injector, TextMapPropagator}; use opentelemetry_sdk::propagation::TraceContextPropagator; @@ -52,6 +54,27 @@ impl Injector for MetadataMapInjector<'_> { } } +#[derive(Debug)] +struct TraceContextMapInjector<'a>(&'a mut BTreeMap); + +impl Injector for TraceContextMapInjector<'_> { + fn set(&mut self, key: &str, value: String) { + self.0.insert(key.to_string(), value); + } +} + +/// Serialize the active span's W3C propagation fields into a string map. +/// +/// Returns `None` when the current span has no valid OpenTelemetry context. +#[must_use] +pub fn current_trace_context_carrier() -> Option> { + let context = tracing::Span::current().context(); + let mut carrier = BTreeMap::new(); + TraceContextPropagator::new() + .inject_context(&context, &mut TraceContextMapInjector(&mut carrier)); + carrier.contains_key("traceparent").then_some(carrier) +} + /// Injects the active W3C trace context into an outbound tonic request. #[derive(Debug, Clone, Copy)] pub struct TraceContextInterceptor; diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 51f05a395c..65411d28f1 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -755,7 +755,7 @@ impl ComputeRuntime { .await .map_err(|err| ComputeError::Message(err.to_string()))?; let operator_allowlist_arc = driver.operator_allowlist().cloned(); - let driver: SharedComputeDriver = Arc::new(KubernetesDriverService::new(driver)); + let driver: SharedComputeDriver = Arc::new(KubernetesDriverService::new_in_process(driver)); let runtime = Self::from_driver( ComputeDriverKind::Kubernetes.as_str().to_string(), driver, diff --git a/crates/openshell-server/src/tracing_setup.rs b/crates/openshell-server/src/tracing_setup.rs index bbd98f16c6..c5b8d9f4a3 100644 --- a/crates/openshell-server/src/tracing_setup.rs +++ b/crates/openshell-server/src/tracing_setup.rs @@ -41,6 +41,8 @@ enum InProcessDriverTracing { #[cfg(feature = "in-tree-compute-drivers")] Docker, #[cfg(feature = "in-tree-compute-drivers")] + Kubernetes, + #[cfg(feature = "in-tree-compute-drivers")] Podman, } @@ -49,6 +51,7 @@ impl InProcessDriverTracing { fn target_prefix(self) -> &'static str { match self { Self::Docker => openshell_driver_docker::otel_tracing::IN_PROCESS_TARGET_PREFIX, + Self::Kubernetes => openshell_driver_kubernetes::otel_tracing::IN_PROCESS_TARGET_PREFIX, Self::Podman => openshell_driver_podman::otel_tracing::IN_PROCESS_TARGET_PREFIX, } } @@ -63,6 +66,9 @@ fn in_process_driver_tracing(driver: &ConfiguredComputeDriver) -> Option { Some(InProcessDriverTracing::Podman) } + ConfiguredComputeDriver::Registered(registration) if registration.name == "kubernetes" => { + Some(InProcessDriverTracing::Kubernetes) + } _ => None, } #[cfg(not(feature = "in-tree-compute-drivers"))] @@ -93,6 +99,9 @@ fn in_process_driver_provider( Some(InProcessDriverTracing::Docker) => { openshell_driver_docker::otel_tracing::provider_for(endpoint) } + Some(InProcessDriverTracing::Kubernetes) => { + openshell_driver_kubernetes::otel_tracing::provider_for(endpoint) + } Some(InProcessDriverTracing::Podman) => { openshell_driver_podman::otel_tracing::provider_for(endpoint) } @@ -120,6 +129,9 @@ where Some(InProcessDriverTracing::Docker) => { openshell_driver_docker::otel_tracing::in_process_layer(provider) } + Some(InProcessDriverTracing::Kubernetes) => { + openshell_driver_kubernetes::otel_tracing::in_process_layer(provider) + } Some(InProcessDriverTracing::Podman) => { openshell_driver_podman::otel_tracing::in_process_layer(provider) } @@ -185,7 +197,7 @@ mod tests { #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] #[test] - fn in_process_driver_tracing_selects_docker_and_podman() { + fn in_process_driver_tracing_selects_registered_compute_drivers() { let registry = crate::install_default_compute_drivers(); let registered = |name| { ConfiguredComputeDriver::Registered( @@ -203,7 +215,10 @@ mod tests { in_process_driver_tracing(®istered("docker")), Some(InProcessDriverTracing::Docker) ); - assert_eq!(in_process_driver_tracing(®istered("kubernetes")), None); + assert_eq!( + in_process_driver_tracing(®istered("kubernetes")), + Some(InProcessDriverTracing::Kubernetes) + ); assert_eq!( in_process_driver_tracing(&ConfiguredComputeDriver::Remote { name: "custom".to_string(), diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index 5879d617ff..25550f3cab 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -261,6 +261,8 @@ discovery endpoint or its TLS CA. | server.oidc.rolesClaim | string | `""` | Dot-separated path to the roles array in the JWT claims. Keycloak: "realm_access.roles", Entra ID: "roles", Okta: "groups". | | server.oidc.scopesClaim | string | `""` | Dot-separated path to the scopes array in the JWT claims. | | server.oidc.userRole | string | `""` | Role name for standard user access. | +| server.otlp.endpoint | string | `""` | OTLP/gRPC collector endpoint, conventionally using port 4317. | +| server.otlp.serviceName | string | `""` | Gateway OpenTelemetry service name. Empty uses openshell-gateway. | | server.policyValidationFailureMode | string | `"fail_closed"` | Posture when a candidate sandbox policy fails validation. `fail_closed` deactivates the previous policy; `retain_last_valid` keeps it active. | | server.providerTokenGrants.spiffe.enabled | bool | `false` | Mount the SPIFFE Workload API socket into gateway and sandbox pods for dynamic provider token grants. | | server.providerTokenGrants.spiffe.workloadApiSocketPath | string | `"/spiffe-workload-api/spire-agent.sock"` | Path to the SPIFFE Workload API socket mounted into gateway and sandbox pods. | diff --git a/deploy/helm/openshell/ci/values-skaffold.yaml b/deploy/helm/openshell/ci/values-skaffold.yaml index 795c056f68..15ff87554e 100644 --- a/deploy/helm/openshell/ci/values-skaffold.yaml +++ b/deploy/helm/openshell/ci/values-skaffold.yaml @@ -4,6 +4,8 @@ # Merge with values.yaml for Skaffold-driven local image builds (see skaffold.yaml). server: sandboxImagePullPolicy: IfNotPresent + otlp: + endpoint: http://openshell-collector.observability.svc.cluster.local:4317 # Comment out to enforce mTLS (uses PKI secrets generated by pkiInitJob). disableTls: true auth: diff --git a/deploy/helm/openshell/templates/gateway-config.yaml b/deploy/helm/openshell/templates/gateway-config.yaml index 9d24dbd917..60420cc535 100644 --- a/deploy/helm/openshell/templates/gateway-config.yaml +++ b/deploy/helm/openshell/templates/gateway-config.yaml @@ -13,6 +13,7 @@ One value is intentionally NOT rendered here: --db-url arg for SQLite */}} {{- $credentialDrivers := list -}} +{{- $otlp := .Values.server.otlp | default dict -}} {{- if .Values.server.credentialDrivers.kubernetesSecrets.enabled -}} {{- $credentialDrivers = append $credentialDrivers "kubernetes-secrets" -}} {{- end -}} @@ -88,6 +89,15 @@ data: {{- fail "server.grpcRateLimit requires both requests and windowSeconds to be positive to enable rate limiting, or both 0/unset to disable it" }} {{- end }} + {{- if $otlp.endpoint }} + + [openshell.gateway.otlp] + endpoint = {{ $otlp.endpoint | quote }} + {{- if $otlp.serviceName }} + service_name = {{ $otlp.serviceName | quote }} + {{- end }} + {{- end }} + {{- if not .Values.server.disableTls }} [openshell.gateway.tls] diff --git a/deploy/helm/openshell/tests/gateway_config_test.yaml b/deploy/helm/openshell/tests/gateway_config_test.yaml index eaa2140862..10e14d6554 100644 --- a/deploy/helm/openshell/tests/gateway_config_test.yaml +++ b/deploy/helm/openshell/tests/gateway_config_test.yaml @@ -62,6 +62,32 @@ tests: name: OPENSHELL_TELEMETRY_ENABLED value: "false" + - it: renders OTLP tracing configuration when configured + template: templates/gateway-config.yaml + set: + server.otlp.endpoint: http://otel-collector.observability.svc:4317 + server.otlp.serviceName: production-gateway + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: '(?ms)\[openshell\.gateway\.otlp\].*?endpoint\s*=\s*"http://otel-collector\.observability\.svc:4317".*?service_name\s*=\s*"production-gateway"' + + - it: omits OTLP tracing configuration by default + template: templates/gateway-config.yaml + asserts: + - notMatchRegex: + path: data["gateway.toml"] + pattern: '\[openshell\.gateway\.otlp\]' + + - it: treats a null OTLP map as disabled + template: templates/gateway-config.yaml + set: + server.otlp: null + asserts: + - notMatchRegex: + path: data["gateway.toml"] + pattern: '\[openshell\.gateway\.otlp\]' + - it: mounts the OIDC CA bundle when TLS is disabled template: templates/statefulset.yaml set: diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index f2c3c28dd8..6c0889773c 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -191,6 +191,12 @@ affinity: {} server: # -- Gateway log level. logLevel: info + # OpenTelemetry trace export over OTLP/gRPC. Leave endpoint empty to disable. + otlp: + # -- OTLP/gRPC collector endpoint, conventionally using port 4317. + endpoint: "" + # -- Gateway OpenTelemetry service name. Empty uses openshell-gateway. + serviceName: "" # -- Enable anonymous OpenShell telemetry from the gateway and the sandbox # supervisors it launches. telemetryEnabled: true diff --git a/docs/reference/gateway-config.mdx b/docs/reference/gateway-config.mdx index d1fed9ae44..a066b14f01 100644 --- a/docs/reference/gateway-config.mdx +++ b/docs/reference/gateway-config.mdx @@ -234,6 +234,22 @@ Only OpenTelemetry traces are exported. Inbound gRPC and HTTP requests produce s The gateway forwards the OTLP configuration and W3C trace context to managed external drivers. Built-in Docker and Podman drivers also export their spans to the same collector through dedicated in-process providers. Driver spans retain the gateway trace context and use a distinct service name such as `openshell-driver-docker` or `openshell-driver-podman`. +For Helm deployments, set `server.otlp.endpoint` to render this table. The +optional `server.otlp.serviceName` value overrides the gateway service name; +driver service names remain fixed. + +The local `mise run helm:k3s:create` workflow installs a trace collector and UI, +enables Agent Sandbox controller tracing on supported releases, and configures +both the controller and the existing Skaffold deployment to export traces to it +automatically. +Run `mise run helm:k3s:forward` to forward OTLP/gRPC to local port `4317` and +the trace UI to local port `18888`. When Skaffold has deployed a Kubernetes +gateway, the task also forwards it to local port `8090`; otherwise it continues +with the collector ports only. The Skaffold run task registers the forwarded +gateway under the worktree-specific k3d cluster name; select it with +`openshell gateway select `. The local Podman, Docker, and VM gateway +tasks export to the forwarded receiver automatically. + ### Tuning This table decides whether and where to export. How the SDK exports is controlled by the standard OpenTelemetry environment variables, which the gateway reads through the SDK rather than mirroring as TOML keys: diff --git a/tasks/helm.toml b/tasks/helm.toml index 7f78ce4a8f..f7db8f9c57 100644 --- a/tasks/helm.toml +++ b/tasks/helm.toml @@ -108,7 +108,7 @@ hide = true # should install k3d explicitly or point workflows at an existing/kind cluster. ["helm:k3s:create"] -description = "Create a local k3s cluster with k3d and merge kubeconfig (macOS via mise; Linux requires explicit k3d install; use with helm:skaffold:dev)" +description = "Create a local k3s cluster with agent-sandbox and an OTLP trace collector, then merge kubeconfig" run = "tasks/scripts/helm-k3s-local.sh create" ["helm:k3s:delete"] @@ -131,7 +131,7 @@ run = "tasks/scripts/helm-k3s-local.sh status" hide = true ["helm:k3s:forward"] -description = "Forward the local Kubernetes gateway to port 8090" +description = "Forward collector OTLP ingest (4317), trace UI (18888), and the local gateway (8090) when deployed" run = "tasks/scripts/helm-k3s-local.sh forward" # Install Envoy Gateway's GatewayClass into the cluster diff --git a/tasks/scripts/gateway-docker.sh b/tasks/scripts/gateway-docker.sh index ef51f37182..6e7b85634a 100644 --- a/tasks/scripts/gateway-docker.sh +++ b/tasks/scripts/gateway-docker.sh @@ -202,6 +202,9 @@ version = 1 compute_drivers = ["docker"] disable_tls = true +[openshell.gateway.otlp] +endpoint = "http://127.0.0.1:4317" + [openshell.gateway.auth] allow_unauthenticated_users = true diff --git a/tasks/scripts/gateway-podman.sh b/tasks/scripts/gateway-podman.sh index 2b70e3a85b..8b6d98ca0c 100644 --- a/tasks/scripts/gateway-podman.sh +++ b/tasks/scripts/gateway-podman.sh @@ -207,6 +207,9 @@ compute_drivers = ["podman"] default_image = "${SANDBOX_IMAGE}" disable_tls = true +[openshell.gateway.otlp] +endpoint = "http://127.0.0.1:4317" + [openshell.gateway.auth] allow_unauthenticated_users = true diff --git a/tasks/scripts/gateway-vm.sh b/tasks/scripts/gateway-vm.sh index 22ba1b039f..c4aac270da 100755 --- a/tasks/scripts/gateway-vm.sh +++ b/tasks/scripts/gateway-vm.sh @@ -327,6 +327,9 @@ version = 1 compute_drivers = ["vm"] disable_tls = ${DISABLE_TLS} +[openshell.gateway.otlp] +endpoint = "http://127.0.0.1:4317" + [openshell.gateway.auth] allow_unauthenticated_users = true diff --git a/tasks/scripts/gateway.sh b/tasks/scripts/gateway.sh index 604476a4b6..895e545862 100644 --- a/tasks/scripts/gateway.sh +++ b/tasks/scripts/gateway.sh @@ -251,6 +251,9 @@ compute_drivers = ["${DRIVER}"] default_image = "${SANDBOX_IMAGE}" disable_tls = true +[openshell.gateway.otlp] +endpoint = "http://127.0.0.1:4317" + [openshell.gateway.auth] allow_unauthenticated_users = true diff --git a/tasks/scripts/helm-k3s-local.sh b/tasks/scripts/helm-k3s-local.sh index 2234497b44..39fed2f4b4 100755 --- a/tasks/scripts/helm-k3s-local.sh +++ b/tasks/scripts/helm-k3s-local.sh @@ -38,12 +38,18 @@ PRELOAD_SANDBOX_IMAGE="${HELM_K3S_PRELOAD_SANDBOX_IMAGE-${DEFAULT_SANDBOX_PRELOA # exercise the v1alpha1 controller release. AGENT_SANDBOX_VERSION="${AGENT_SANDBOX_VERSION:-v0.5.0}" +# Local OTLP receiver and trace UI. The current Aspire implementation accepts +# OTLP/gRPC directly, so the development cluster needs only one deployment. +OBSERVABILITY_NAMESPACE="observability" +COLLECTOR_IMAGE="${HELM_K3S_COLLECTOR_IMAGE:-mcr.microsoft.com/dotnet/aspire-dashboard:latest}" +COLLECTOR_HEALTH_TIMEOUT="${HELM_K3S_COLLECTOR_HEALTH_TIMEOUT:-120}" # Host endpoint registered for the Skaffold-deployed gateway. Derive the # gateway name from the worktree-specific cluster name so concurrent local # clusters do not overwrite each other's CLI metadata. GATEWAY_NAMESPACE="openshell" GATEWAY_HOST_PORT="${HELM_K3S_GATEWAY_HOST_PORT:-8090}" GATEWAY_NAME="${HELM_K3S_GATEWAY_NAME:-${CLUSTER_NAME}}" +FORWARD_PIDS=() default_kubeconfig="${ROOT}/kubeconfig" if [[ -n "${HELM_K3S_KUBECONFIG:-}" ]]; then @@ -72,6 +78,10 @@ Environment: HELM_K3S_PRELOAD_SANDBOX_IMAGE Sandbox image to docker pull and import into k3d (default: ${DEFAULT_SANDBOX_PRELOAD_IMAGE}; set empty to skip) + HELM_K3S_COLLECTOR_IMAGE Image used for the local OTLP receiver and trace UI + (default: mcr.microsoft.com/dotnet/aspire-dashboard:latest) + HELM_K3S_COLLECTOR_HEALTH_TIMEOUT + Seconds to wait for collector readiness (default: 120) HELM_K3S_GATEWAY_HOST_PORT Host port forwarded to the gateway (default: 8090) HELM_K3S_GATEWAY_NAME CLI gateway registration name (default: worktree-specific k3d cluster name) @@ -156,6 +166,116 @@ apply_base_manifests() { kubectl --kubeconfig="${KUBECONFIG_TARGET}" apply -f "${base}/manifest.yaml" } +install_trace_collector() { + require_kubectl + + echo "Installing local trace collector in namespace '${OBSERVABILITY_NAMESPACE}'..." + kubectl --kubeconfig="${KUBECONFIG_TARGET}" \ + create namespace "${OBSERVABILITY_NAMESPACE}" --dry-run=client -o yaml \ + | kubectl --kubeconfig="${KUBECONFIG_TARGET}" apply -f - + + kubectl --kubeconfig="${KUBECONFIG_TARGET}" apply -f - </dev/null || true + done + for pid in "${FORWARD_PIDS[@]}"; do + wait "${pid}" 2>/dev/null || true + done +} + cmd_forward() { require_supported_os require_kubectl - echo "Forwarding gateway to http://127.0.0.1:${GATEWAY_HOST_PORT}" - echo "Press Ctrl-C to stop." kubectl \ + --kubeconfig="${KUBECONFIG_TARGET}" \ + --context="$(k3d_context_name)" \ + --namespace="${OBSERVABILITY_NAMESPACE}" \ + get service/openshell-collector >/dev/null + + echo "Forwarding collector OTLP/gRPC to http://127.0.0.1:4317" + echo "Forwarding trace UI to http://127.0.0.1:18888" + + trap cleanup_forwards EXIT + trap 'exit 130' INT + trap 'exit 143' TERM + + if kubectl \ --kubeconfig="${KUBECONFIG_TARGET}" \ --context="$(k3d_context_name)" \ --namespace="${GATEWAY_NAMESPACE}" \ - port-forward service/openshell "${GATEWAY_HOST_PORT}:8080" + get service/openshell >/dev/null 2>&1; then + echo "Forwarding gateway to http://127.0.0.1:${GATEWAY_HOST_PORT}" + kubectl \ + --kubeconfig="${KUBECONFIG_TARGET}" \ + --context="$(k3d_context_name)" \ + --namespace="${GATEWAY_NAMESPACE}" \ + port-forward service/openshell "${GATEWAY_HOST_PORT}:8080" & + FORWARD_PIDS+=("$!") + else + echo "No Kubernetes gateway service found; forwarding collector ports only." + fi + + kubectl \ + --kubeconfig="${KUBECONFIG_TARGET}" \ + --context="$(k3d_context_name)" \ + --namespace="${OBSERVABILITY_NAMESPACE}" \ + port-forward service/openshell-collector 4317:4317 18888:18888 & + FORWARD_PIDS+=("$!") + + echo "Press Ctrl-C to stop." + + local pid status + while true; do + for pid in "${FORWARD_PIDS[@]}"; do + if ! kill -0 "${pid}" 2>/dev/null; then + status=0 + wait "${pid}" || status=$? + if [[ ${status} -eq 0 ]]; then + status=1 + fi + echo "error: a port-forward process exited; stopping the remaining forwards" >&2 + return "${status}" + fi + done + sleep 1 + done } main() { From 0618ab0465680a569b2f99a869ae04f468ca3290 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?William=20Tr=C3=A9panier?= <39393794+wtrep@users.noreply.github.com> Date: Wed, 26 Aug 2026 21:29:56 +0000 Subject: [PATCH 2/3] fix(supervisor): log unmatched L7 route denials (#2916) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Requests denied by relay_with_route_selection because no L7 endpoint path matched returned a 403 without emitting an OCSF event or recording policy activity, leaving the deny invisible to operators and telemetry. Every other early-return deny in that loop already logs. Emit an HTTP Activity deny event and an l7_policy activity record before writing the denial. Split event construction out of emit_l7_request_log so the event shape is directly testable, and narrow both helpers to take the request action rather than the full L7RequestInfo, which they only used for that field. Signed-off-by: William Trépanier --- .../src/l7/relay.rs | 154 +++++++++++++++--- 1 file changed, 134 insertions(+), 20 deletions(-) diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 44f3f8023a..2697fedb3c 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -559,11 +559,13 @@ where } }; let Some(config) = select_l7_config_for_path(configs, &route_target) else { + let reason = "no L7 endpoint path matched request"; + emit_l7_request_log(ctx, &req.action, &route_target, "deny", "l7", reason, None); crate::l7::rest::RestProvider::default() .deny_with_redacted_target( &req, &ctx.policy_name, - "no L7 endpoint path matched request", + reason, client, None, Some(crate::l7::rest::DenyResponseContext::from_l7_context(ctx)), @@ -724,12 +726,12 @@ where l7_protocol_log_summary(graphql_info.as_ref(), jsonrpc_info.as_ref()); emit_l7_request_log( ctx, - &request_info, + &request_info.action, &redacted_target, decision_str, engine_type, &reason, - &protocol_summary, + protocol_summary.as_deref(), ); if allowed || (config.enforcement == EnforcementMode::Audit && !force_deny) { @@ -935,13 +937,35 @@ fn select_l7_config_for_path<'a>( fn emit_l7_request_log( ctx: &L7EvalContext, - request_info: &L7RequestInfo, + action: &str, redacted_target: &str, decision_str: &str, engine_type: &str, reason: &str, - protocol_summary: &str, + protocol_summary: Option<&str>, ) { + let event = build_l7_request_event( + ctx, + action, + redacted_target, + decision_str, + engine_type, + reason, + protocol_summary, + ); + ocsf_emit!(event); + emit_activity(ctx, decision_str == "deny", "l7_policy"); +} + +fn build_l7_request_event( + ctx: &L7EvalContext, + action: &str, + redacted_target: &str, + decision_str: &str, + engine_type: &str, + reason: &str, + protocol_summary: Option<&str>, +) -> openshell_ocsf::OcsfEvent { let (action_id, disposition_id, severity) = match decision_str { "deny" => (ActionId::Denied, DispositionId::Blocked, SeverityId::Medium), "allow" | "audit" => ( @@ -955,43 +979,44 @@ fn emit_l7_request_log( SeverityId::Informational, ), }; - let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + let protocol_suffix = + protocol_summary.map_or_else(String::new, |summary| format!(" {summary}")); + let message = format!( + "L7_REQUEST {decision_str} {action} {}:{}{}{protocol_suffix} reason={reason}", + ctx.host, ctx.port, redacted_target, + ); + HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Other) .action(action_id) .disposition(disposition_id) .severity(severity) .http_request(HttpRequest::new( - &request_info.action, + action, OcsfUrl::new("http", &ctx.host, redacted_target, ctx.port), )) .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) .firewall_rule(&ctx.policy_name, engine_type) - .message(format!( - "L7_REQUEST {decision_str} {} {}:{}{}{} reason={}", - request_info.action, ctx.host, ctx.port, redacted_target, protocol_summary, reason, - )) - .build(); - ocsf_emit!(event); - emit_activity(ctx, decision_str == "deny", "l7_policy"); + .message(message) + .build() } fn l7_protocol_log_summary( graphql_info: Option<&crate::l7::graphql::GraphqlRequestInfo>, jsonrpc_info: Option<&crate::l7::jsonrpc::JsonRpcRequestInfo>, -) -> String { +) -> Option { if let Some(info) = graphql_info { - return format!(" {}", crate::l7::graphql::log_summary(info)); + return Some(crate::l7::graphql::log_summary(info)); } if let Some(info) = jsonrpc_info { - return format!( - " rule_methods={} tools={}", + return Some(format!( + "rule_methods={} tools={}", rule_method_names_for_log(info), tool_names_for_log(info) - ); + )); } - String::new() + None } fn emit_activity(ctx: &L7EvalContext, denied: bool, deny_group: &'static str) { @@ -7360,6 +7385,95 @@ network_policies: } } + #[test] + fn unmatched_route_path_builds_denied_http_activity_event() { + let ctx = L7EvalContext { + host: "gateway.example.test".into(), + port: 443, + policy_name: "route_api".into(), + ..Default::default() + }; + + let event = build_l7_request_event( + &ctx, + "GET", + "/other", + "deny", + "l7", + "no L7 endpoint path matched request", + None, + ); + + assert_eq!(event.class_uid(), 4002); + assert_eq!(event.base().severity, SeverityId::Medium); + assert_eq!( + event.format_shorthand(), + "HTTP:GET [MED] DENIED GET http://gateway.example.test:443/other [policy:route_api engine:l7] [reason:L7_REQUEST deny GET gateway.example.test:443/other reason=no L7 endpoint path matched request]" + ); + } + + #[tokio::test] + async fn route_selected_unmatched_path_emits_denied_policy_activity() { + let engine = OpaEngine::from_strings(TEST_POLICY, ENCODED_SLASH_SCOPING_POLICY).unwrap(); + let tunnel_engine = engine + .clone_engine_for_tunnel(engine.current_generation()) + .unwrap(); + let configs = encoded_slash_scoping_configs(); + let (activity_tx, mut activity_rx) = tokio::sync::mpsc::channel(1); + let ctx = L7EvalContext { + activity_tx: Some(activity_tx), + ..encoded_slash_scoping_ctx() + }; + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_with_route_selection( + &configs, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + app.write_all( + b"GET /other HTTP/1.1\r\nHost: gateway.example.test\r\nConnection: close\r\n\r\n", + ) + .await + .unwrap(); + + let mut response = [0u8; 1024]; + let n = tokio::time::timeout(std::time::Duration::from_secs(1), app.read(&mut response)) + .await + .expect("denial should reach client") + .unwrap(); + assert!(String::from_utf8_lossy(&response[..n]).contains("403 Forbidden")); + + let mut upstream_bytes = [0u8; 16]; + assert!(matches!( + tokio::time::timeout( + std::time::Duration::from_millis(100), + upstream.read(&mut upstream_bytes) + ) + .await, + Err(_) | Ok(Ok(0)) + )); + let activity = tokio::time::timeout(std::time::Duration::from_secs(1), activity_rx.recv()) + .await + .expect("policy activity should be emitted") + .expect("activity channel should remain open"); + assert!(activity.denied); + assert_eq!(activity.deny_group, "l7_policy"); + + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should finish") + .unwrap() + .unwrap(); + } + /// Canonicalization runs before the matching config is known, so /// `allow_encoded_slash` is taken permissively across the whole /// host:port. The endpoint that did *not* opt in must still reject a From 56088d0811f35d01e5af8f975335c9d0e30524be Mon Sep 17 00:00:00 2001 From: Artem Lytvyn Date: Wed, 26 Aug 2026 23:26:25 +0000 Subject: [PATCH 3/3] fix(supervisor-network): distinguish absent policy binary from filesystem-access failure (#2948) * fix(supervisor-network): distinguish absent policy binary from filesystem-access failure Signed-off-by: Artem Lytvyn * fix(supervisor-network): resolve symlink chains at the SYMLOOP_MAX limit Signed-off-by: Artem Lytvyn --------- Signed-off-by: Artem Lytvyn --- .../openshell-supervisor-network/src/opa.rs | 513 +++++++++++++++--- 1 file changed, 438 insertions(+), 75 deletions(-) diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index 35cef601d8..63aa2c2c70 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -1624,19 +1624,6 @@ fn normalize_l7_rule_aliases( } } -/// Resolve a policy binary path through the container's root filesystem. -/// -/// On Linux, `/proc//root/` provides access to the container's mount -/// namespace. If the policy path is a symlink inside the container -/// (e.g., `/usr/bin/python3` → `/usr/bin/python3.11`), returns the -/// canonical target path. Returns `None` if: -/// - Not on Linux -/// - `entrypoint_pid` is 0 (container not yet started) -/// - Path contains glob characters -/// - Path is not a symlink -/// - Resolution fails (binary doesn't exist in container) -/// - Resolved path equals the original -/// /// Normalize a path by resolving `.` and `..` components without touching /// the filesystem. Only works correctly for absolute paths. #[cfg(any(target_os = "linux", test))] @@ -1654,10 +1641,72 @@ fn normalize_path(path: &Path) -> PathBuf { result } +// Only the Linux resolver constructs the non-`Literal` variants; on other +// platforms the stub returns `Literal`, so the rest look dead there. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +#[derive(Debug, PartialEq, Eq)] +enum BinaryResolution { + /// Symlink resolved to a different canonical target — add it to policy. + Resolved(String), + /// Nothing to add: glob, pid 0, not a symlink, or already canonical. + Literal, + /// Candidate absent under an accessible process root — expected, quiet. + Absent, + /// The process root `/proc//root` itself is unreachable (pid gone or + /// denied) — actionable, and `CAP_SYS_PTRACE` guidance is relevant. + Inaccessible(std::io::ErrorKind), + /// The process root is reachable but the candidate path itself failed for a + /// non-NotFound reason (a parent component is permission-denied, or the path + /// forms a symlink loop) — actionable, but a target-path problem rather than + /// a process-root one, so `CAP_SYS_PTRACE` guidance does not apply. + CandidateInaccessible(std::io::ErrorKind), + /// A component mid symlink-chain failed to resolve. + ChainBroken(std::io::ErrorKind), +} + +impl BinaryResolution { + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] + const fn classify_first_probe_error(kind: std::io::ErrorKind) -> Self { + // Callers reach this only after confirming the process root is + // reachable, so a non-NotFound failure here is specific to the + // candidate path, not the process root. + match kind { + std::io::ErrorKind::NotFound => Self::Absent, + _ => Self::CandidateInaccessible(kind), + } + } +} + +/// Resolve a policy binary path through the container's root filesystem. +/// +/// On Linux, `/proc//root/` provides access to the container's mount +/// namespace. If the policy path is a symlink inside the container +/// (e.g., `/usr/bin/python3` → `/usr/bin/python3.11`), the canonical target is +/// returned as [`BinaryResolution::Resolved`]. The outcome is classified as: +/// - [`BinaryResolution::Literal`] — not on Linux, `entrypoint_pid` is 0 +/// (container not yet started), the path contains glob characters, it is not +/// a symlink, or the resolved path equals the original. +/// - [`BinaryResolution::Absent`] — the candidate does not exist under an +/// otherwise reachable process root (expected; the caller logs it quietly). +/// - [`BinaryResolution::Inaccessible`] — `/proc//root` itself is +/// unreachable (pid gone or access denied). +/// - [`BinaryResolution::CandidateInaccessible`] — the process root is +/// reachable but the candidate path failed for a non-NotFound reason. +/// - [`BinaryResolution::ChainBroken`] — a component mid symlink-chain failed, +/// or the chain forms a cycle / exceeds the kernel symlink limit. #[cfg(target_os = "linux")] -fn resolve_binary_in_container(policy_path: &str, entrypoint_pid: u32) -> Option { +fn resolve_binary_in_container(policy_path: &str, entrypoint_pid: u32) -> BinaryResolution { if policy_path.contains('*') || entrypoint_pid == 0 { - return None; + return BinaryResolution::Literal; + } + + // Confirm the process root itself is reachable before probing candidates. + // A leaf `ENOENT` (absent candidate) and an unreachable process root + // (pid gone -> `ENOENT`, or denied -> `EACCES`) are indistinguishable at + // the leaf path, so check the root first. Any failure here is an access + // problem, not an absent candidate, and must stay actionable. + if let Err(e) = std::fs::metadata(format!("/proc/{entrypoint_pid}/root")) { + return BinaryResolution::Inaccessible(e.kind()); } // Walk the symlink chain inside the container filesystem using @@ -1667,6 +1716,11 @@ fn resolve_binary_in_container(policy_path: &str, entrypoint_pid: u32) -> Option // the specified symlink, keeping us in the container's namespace. let mut resolved = PathBuf::from(policy_path); + // Set once the walk reaches a real (non-symlink) target or a terminal + // dead end. If the iteration cap is hit while every component is still a + // symlink, this stays false and the chain is treated as broken. + let mut reached_target = false; + // Linux SYMLOOP_MAX is 40; stop before infinite loops for _ in 0..40 { let container_path = format!("/proc/{entrypoint_pid}/root{}", resolved.display()); @@ -1678,76 +1732,93 @@ fn resolve_binary_in_container(policy_path: &str, entrypoint_pid: u32) -> Option let meta = match std::fs::symlink_metadata(&container_path) { Ok(m) => m, Err(e) => { - // Only warn on the first iteration (the original policy path). - // On subsequent iterations, the intermediate target may - // legitimately not exist (broken symlink chain). + // First iteration is the original policy path: an absent + // candidate (NotFound) is expected, any other error means the + // process root itself is unreachable. Later iterations are + // chain components, so a failure there is a broken symlink + // chain. Classify without logging; the caller emits the log at + // the appropriate level. if resolved.as_os_str() == policy_path { - tracing::warn!( - "Cannot access container filesystem for symlink resolution: \ - path={policy_path} container_path={container_path} pid={entrypoint_pid} \ - error={e}. Binary paths in policy will be matched literally. \ - If this binary is a symlink (e.g., /usr/bin/python3 -> python3.11), \ - use the canonical path instead, or run with CAP_SYS_PTRACE." - ); - } else { - tracing::warn!( - "Symlink chain broken during resolution: \ - original={policy_path} current={} pid={entrypoint_pid} error={e}. \ - Binary will be matched by original path only.", - resolved.display() - ); + // The up-front root check and this probe are separate + // syscalls; if the process exited in between, the whole + // `/proc/` tree is gone and the leaf probe also + // reports NotFound. Re-check the root so a vanished process + // stays classified as Inaccessible (actionable) rather than + // being masked as an absent candidate (quiet). + if e.kind() == std::io::ErrorKind::NotFound + && let Err(root_error) = + std::fs::metadata(format!("/proc/{entrypoint_pid}/root")) + { + return BinaryResolution::Inaccessible(root_error.kind()); + } + return BinaryResolution::classify_first_probe_error(e.kind()); } - return None; + return BinaryResolution::ChainBroken(e.kind()); } }; if !meta.file_type().is_symlink() { // Reached a non-symlink — this is the final resolved target + reached_target = true; break; } let target = match std::fs::read_link(&container_path) { Ok(t) => t, - Err(e) => { - tracing::warn!( - "Symlink detected but read_link failed: \ - path={policy_path} current={} pid={entrypoint_pid} error={e}. \ - Binary will be matched by original path only.", - resolved.display() - ); - return None; - } + // A symlink whose target can't be read is a broken chain; the + // caller logs it. + Err(e) => return BinaryResolution::ChainBroken(e.kind()), }; if target.is_absolute() { resolved = target; - } else { + } else if let Some(parent) = resolved.parent() { // Relative symlink: resolve against the containing directory // e.g., /usr/bin/python3 -> python3.11 becomes /usr/bin/python3.11 - if let Some(parent) = resolved.parent() { - resolved = normalize_path(&parent.join(&target)); - } else { - break; + resolved = normalize_path(&parent.join(&target)); + } else { + // No parent to resolve a relative target against — terminal. + reached_target = true; + break; + } + } + + if !reached_target { + // The cap was exhausted while following symlinks. Linux SYMLOOP_MAX is + // 40, so a chain of exactly 40 symlinks ending at a real file is still + // valid — after the 40th hop `resolved` may already point at that file. + // Inspect it once more without following another link: a non-symlink is + // the valid final target (fall through to the Literal/Resolved logic + // below), while another symlink (or an error) is a genuine cycle + // (a -> b -> a) or a chain deeper than the kernel allows. read_link + // resolves one hop at a time, so the kernel never surfaces ELOOP; treat + // those as a broken chain so the caller logs it and matches literally. + let container_path = format!("/proc/{entrypoint_pid}/root{}", resolved.display()); + + match std::fs::symlink_metadata(&container_path) { + Ok(meta) if !meta.file_type().is_symlink() => {} + Ok(_) => { + return BinaryResolution::ChainBroken( + std::io::Error::from_raw_os_error(libc::ELOOP).kind(), + ); } + Err(e) => return BinaryResolution::ChainBroken(e.kind()), } } let resolved_str = resolved.to_string_lossy().into_owned(); if resolved_str == policy_path { - None + BinaryResolution::Literal } else { - tracing::info!( - "Resolved policy binary symlink via container filesystem: \ - original={policy_path} resolved={resolved_str} pid={entrypoint_pid}" - ); - Some(resolved_str) + // The caller logs the resolution at info level. + BinaryResolution::Resolved(resolved_str) } } #[cfg(not(target_os = "linux"))] -fn resolve_binary_in_container(_policy_path: &str, _entrypoint_pid: u32) -> Option { - None +fn resolve_binary_in_container(_policy_path: &str, _entrypoint_pid: u32) -> BinaryResolution { + BinaryResolution::Literal } fn l7_matchers_to_json( @@ -2015,8 +2086,46 @@ fn proto_to_opa_data_json(proto: &ProtoSandboxPolicy, entrypoint_pid: u32) -> St entry }; let mut entries = vec![binary_entry(&b.path)]; - if let Some(resolved) = resolve_binary_in_container(&b.path, entrypoint_pid) { - entries.push(binary_entry(&resolved)); + match resolve_binary_in_container(&b.path, entrypoint_pid) { + BinaryResolution::Resolved(resolved) => { + tracing::info!( + "Resolved policy binary symlink: original={} resolved={resolved} pid={entrypoint_pid}", + b.path + ); + entries.push(binary_entry(&resolved)); + } + BinaryResolution::Absent => { + tracing::debug!( + "Policy binary candidate not present in container: path={} pid={entrypoint_pid}. Matched literally.", + b.path + ); + } + BinaryResolution::Inaccessible(kind) => { + tracing::warn!( + "Cannot access container filesystem for symlink resolution: path={} pid={entrypoint_pid} \ + error_kind={kind:?}. Binary paths in policy will be matched literally. \ + If this binary is a symlink (e.g., /usr/bin/python3 -> python3.11), \ + use the canonical path instead, or run with CAP_SYS_PTRACE.", + b.path + ); + } + BinaryResolution::CandidateInaccessible(kind) => { + tracing::warn!( + "Cannot access policy binary candidate path: path={} pid={entrypoint_pid} \ + error_kind={kind:?}. Binary path will be matched literally. \ + A parent component is permission-denied or the path forms a symlink loop; \ + the process root itself is reachable.", + b.path + ); + } + BinaryResolution::ChainBroken(kind) => { + tracing::warn!( + "Symlink chain broken during resolution: path={} pid={entrypoint_pid} error_kind={kind:?}. \ + Matched by original path only.", + b.path + ); + } + BinaryResolution::Literal => {}, } entries }) @@ -7189,22 +7298,36 @@ process: #[test] fn resolve_binary_skips_glob_paths() { // Glob patterns should never be resolved — they're matched differently - assert!(resolve_binary_in_container("/usr/bin/*", 1).is_none()); - assert!(resolve_binary_in_container("/usr/local/bin/**", 1).is_none()); + assert_eq!( + resolve_binary_in_container("/usr/bin/*", 1), + BinaryResolution::Literal + ); + assert_eq!( + resolve_binary_in_container("/usr/local/bin/**", 1), + BinaryResolution::Literal + ); } #[test] fn resolve_binary_skips_pid_zero() { // pid=0 means the container hasn't started yet - assert!(resolve_binary_in_container("/usr/bin/python3", 0).is_none()); + assert_eq!( + resolve_binary_in_container("/usr/bin/python3", 0), + BinaryResolution::Literal + ); } #[test] - fn resolve_binary_returns_none_for_nonexistent_path() { - // A path that doesn't exist in any container should gracefully return None + fn resolve_binary_does_not_resolve_nonexistent_path() { + // A path that doesn't exist should never yield a Resolved target. The + // exact non-Resolved variant depends on platform/privilege (Absent when + // the process root is readable, Inaccessible when it is not, Literal on + // the non-Linux stub), so assert only that nothing is resolved. + let result = + resolve_binary_in_container("/nonexistent/binary/path/that/will/never/exist", 1); assert!( - resolve_binary_in_container("/nonexistent/binary/path/that/will/never/exist", 1) - .is_none() + !matches!(result, BinaryResolution::Resolved(_)), + "nonexistent path must not resolve, got: {result:?}" ); } @@ -7412,6 +7535,243 @@ network_policies: ); } + #[test] + fn classify_not_found_is_absent() { + // A missing candidate under an accessible root is expected, not an error. + assert_eq!( + BinaryResolution::classify_first_probe_error(std::io::ErrorKind::NotFound), + BinaryResolution::Absent + ); + } + + #[test] + fn classify_permission_denied_is_candidate_inaccessible() { + // A non-NotFound failure at the candidate probe (root already confirmed + // reachable) is a target-path problem, not a process-root one, so it + // must not emit the CAP_SYS_PTRACE process-root guidance. + assert_eq!( + BinaryResolution::classify_first_probe_error(std::io::ErrorKind::PermissionDenied), + BinaryResolution::CandidateInaccessible(std::io::ErrorKind::PermissionDenied) + ); + } + + #[test] + #[cfg(target_os = "linux")] + fn absent_candidate_resolves_to_absent() { + // Regression for #2883: a candidate path that does not exist under an + // accessible /proc//root must classify as Absent (quiet), not as a + // container-filesystem-access failure. + if !procfs_root_accessible() { + eprintln!("Skipping: /proc//root/ not accessible in this environment"); + return; + } + + // Use a path guaranteed absent: a real temp dir with an uncreated + // child. A hard-coded path like /app/.venv/bin/python could exist in a + // valid environment and make the resolver return Resolved/Literal. + let dir = tempfile::tempdir().unwrap(); + let missing = dir.path().join("missing-python"); + let pid = std::process::id(); // our own live, accessible root + assert_eq!( + resolve_binary_in_container(missing.to_str().unwrap(), pid), + BinaryResolution::Absent + ); + } + + #[test] + #[cfg(target_os = "linux")] + fn unreachable_process_root_is_inaccessible() { + // A pid whose /proc//root does not exist (process gone) must be + // reported as an access failure, not silently treated as an absent + // candidate — even though both surface as ENOENT at the leaf path. + // u32::MAX is far above /proc/sys/kernel/pid_max, so it never exists. + let dead_pid = u32::MAX; + assert!( + matches!( + resolve_binary_in_container("/usr/bin/python3", dead_pid), + BinaryResolution::Inaccessible(_) + ), + "an unreachable process root must classify as Inaccessible" + ); + } + + #[test] + #[cfg(target_os = "linux")] + fn symlink_cycle_exhausts_limit_as_chain_broken() { + // A symlink cycle (a -> b -> a) never resolves to a real target. The + // manual read_link walk resolves one hop at a time, so the kernel never + // raises ELOOP; exhausting the iteration cap must classify as + // ChainBroken, not silently pass as Resolved/Literal. + use std::os::unix::fs::symlink; + + if !procfs_root_accessible() { + eprintln!("Skipping: /proc//root/ not accessible in this environment"); + return; + } + + let dir = tempfile::tempdir().unwrap(); + let a = dir.path().join("a"); + let b = dir.path().join("b"); + symlink(&b, &a).unwrap(); // a -> b + symlink(&a, &b).unwrap(); // b -> a + let pid = std::process::id(); + assert!( + matches!( + resolve_binary_in_container(a.to_str().unwrap(), pid), + BinaryResolution::ChainBroken(_) + ), + "a symlink cycle must classify as ChainBroken" + ); + } + + #[test] + #[cfg(target_os = "linux")] + fn symlink_chain_at_limit_resolves_to_target() { + // Linux SYMLOOP_MAX is 40: a chain of exactly 40 symlinks ending at a + // real file resolves successfully in the kernel. The manual walk must + // follow all 40 hops and accept the final target rather than exhausting + // the cap and reporting ChainBroken (off-by-one regression). + use std::os::unix::fs::symlink; + + if !procfs_root_accessible() { + eprintln!("Skipping: /proc//root/ not accessible in this environment"); + return; + } + + let dir = tempfile::tempdir().unwrap(); + let target = dir.path().join("real"); + std::fs::write(&target, b"").unwrap(); + + // link0 -> link1 -> ... -> link39 -> real (40 symlinks, absolute + // targets so the resolver takes the is_absolute() branch). + let link = |i: usize| dir.path().join(format!("link{i}")); + symlink(&target, link(39)).unwrap(); + for i in (0..39).rev() { + symlink(link(i + 1), link(i)).unwrap(); + } + + let pid = std::process::id(); + let result = resolve_binary_in_container(link(0).to_str().unwrap(), pid); + assert!( + matches!(result, BinaryResolution::Resolved(_)), + "a 40-link chain ending at a real file must resolve, got {result:?}" + ); + } + + #[test] + #[cfg(target_os = "linux")] + fn symlink_chain_over_limit_is_chain_broken() { + // A chain of 41 symlinks exceeds SYMLOOP_MAX: the walk must give up and + // classify as ChainBroken, proving the 40-hop budget stays enforced. + use std::os::unix::fs::symlink; + + if !procfs_root_accessible() { + eprintln!("Skipping: /proc//root/ not accessible in this environment"); + return; + } + + let dir = tempfile::tempdir().unwrap(); + let target = dir.path().join("real"); + std::fs::write(&target, b"").unwrap(); + + // link0 -> ... -> link40 -> real (41 symlinks). + let link = |i: usize| dir.path().join(format!("link{i}")); + symlink(&target, link(40)).unwrap(); + for i in (0..40).rev() { + symlink(link(i + 1), link(i)).unwrap(); + } + + let pid = std::process::id(); + let result = resolve_binary_in_container(link(0).to_str().unwrap(), pid); + assert!( + matches!(result, BinaryResolution::ChainBroken(_)), + "a 41-link chain must classify as ChainBroken, got {result:?}" + ); + } + + #[test] + #[cfg(target_os = "linux")] + fn absent_candidates_emit_no_warnings() { + // Regression for #2883: several expected-but-absent compatibility + // candidates under an accessible process root must not produce a burst + // of WARN-level noise. Logging now lives at the caller, so drive the + // real caller (proto_to_opa_data_json) and count WARN events. + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + use tracing::Subscriber; + use tracing_subscriber::layer::{Context, Layer, SubscriberExt}; + use tracing_subscriber::registry::LookupSpan; + + #[derive(Clone)] + struct WarnCounter(Arc); + impl LookupSpan<'a>> Layer for WarnCounter { + fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) { + if *event.metadata().level() == tracing::Level::WARN { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + } + + if !procfs_root_accessible() { + eprintln!("Skipping: /proc//root/ not accessible in this environment"); + return; + } + + let warns = Arc::new(AtomicUsize::new(0)); + let subscriber = tracing_subscriber::registry().with(WarnCounter(Arc::clone(&warns))); + + // Candidates that do not exist under our accessible /proc//root. + // Historically each absent candidate emitted its own WARN. Use uncreated + // children of a real temp dir so the paths are guaranteed absent (not + // merely conventional): a hard-coded path could exist on a runner and + // stop exercising the Absent branch, or be inaccessible and emit a + // legitimate warning that fails this test. + let dir = tempfile::tempdir().unwrap(); + let candidates = [ + dir.path().join("app-python"), + dir.path().join("sandbox-python"), + dir.path().join("opt-python"), + ]; + let mut network_policies = std::collections::HashMap::new(); + network_policies.insert( + "pypi".to_string(), + NetworkPolicyRule { + name: "pypi".to_string(), + endpoints: vec![NetworkEndpoint { + host: "pypi.org".to_string(), + port: 443, + ..Default::default() + }], + binaries: candidates + .iter() + .map(|p| NetworkBinary { + path: p.to_str().unwrap().to_string(), + ..Default::default() + }) + .collect(), + }, + ); + let proto = ProtoSandboxPolicy { + version: 1, + filesystem: None, + landlock: None, + process: None, + network_policies, + network_middlewares: std::collections::HashMap::default(), + }; + + let pid = std::process::id(); // accessible root, leaf paths absent + tracing::subscriber::with_default(subscriber, || { + let _ = proto_to_opa_data_json(&proto, pid); + }); + + assert_eq!( + warns.load(Ordering::SeqCst), + 0, + "absent compatibility candidates must not emit warnings" + ); + } + #[test] fn hot_reload_preserves_symlink_expansion_behavior() { // Simulates the hot-reload path: initial load at pid=0, then reload @@ -7886,7 +8246,10 @@ network_policies: let pid = std::process::id(); let link_path = link.to_string_lossy().to_string(); // Actually attempt the same resolution our production code uses - resolve_binary_in_container(&link_path, pid).is_some() + matches!( + resolve_binary_in_container(&link_path, pid), + BinaryResolution::Resolved(_) + ) } #[cfg(target_os = "linux")] @@ -7915,11 +8278,9 @@ network_policies: let link_path = link.to_string_lossy().to_string(); let result = resolve_binary_in_container(&link_path, our_pid); - assert!( - result.is_some(), - "Should resolve symlink via /proc//root/" - ); - let resolved = result.unwrap(); + let BinaryResolution::Resolved(resolved) = result else { + panic!("Should resolve symlink via /proc//root/, got: {result:?}"); + }; assert!( resolved.ends_with("python3.11"), "Resolved path should point to target: {resolved}" @@ -7945,9 +8306,10 @@ network_policies: let path = tmp.path().to_string_lossy().to_string(); let result = resolve_binary_in_container(&path, our_pid); - assert!( - result.is_none(), - "Non-symlink file should return None, got: {result:?}" + assert_eq!( + result, + BinaryResolution::Literal, + "Non-symlink file should not expand, got: {result:?}" ); } @@ -7975,8 +8337,9 @@ network_policies: let link_path = top_link.to_string_lossy().to_string(); let result = resolve_binary_in_container(&link_path, our_pid); - assert!(result.is_some(), "Should resolve multi-level symlink chain"); - let resolved = result.unwrap(); + let BinaryResolution::Resolved(resolved) = result else { + panic!("Should resolve multi-level symlink chain, got: {result:?}"); + }; assert!( resolved.ends_with("cpython3.11"), "Should resolve to final target: {resolved}"