Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
316 changes: 287 additions & 29 deletions Cargo.lock

Large diffs are not rendered by default.

19 changes: 19 additions & 0 deletions architecture/adr/0001-supervisor-terminated-appliance-tunnel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# 1. Supervisor-terminated customer appliance tunnel

Date: 2026-10-02

Status: Proposed

## Context

Customer private services require a route from a sandbox to a customer appliance. A tunnel inside the workload would let decrypted packets leave the supervisor's policy point. A shared cluster exit would also couple customer routes and keys across sandboxes. The supervisor already authorizes explicit proxy destinations, inspects supported application traffic, and rewrites endpoint-bound credentials.

## Decision

Each sandbox supervisor owns its own userspace WireGuard interface and TCP stack. Its policy names the appliance's exact UDP endpoint and an inner destination endpoint that references the tunnel. The appliance endpoint is a supervisor-only transport exception; workload TCP cannot use it. The inner host and port remain ordinary policy objects. Destination validation and applicable L7 and credential handling stay in the existing proxy path, with the tunnel replacing only the final upstream TCP transport. A failed tunnel has no direct or corporate-proxy fallback.

The policy carries a reference to a sandbox-scoped provider credential containing the private key. The supervisor suppresses that environment key before workload startup and resolves it only in its own credential state. Key bytes do not enter policy persistence, policy introspection, or the workload environment. The first implementation accepts one named tunnel, one IPv4 literal destination and port, and one route. A successful policy reload advances the accepted generation only when the validated tunnel configuration, full inner and outer endpoints, key reference, and current supervisor key material are unchanged. A changed or missing tunnel or key permanently revokes the route until sandbox restart. Every dial checks the current supervisor key, so an independent credential refresh also fails closed. A failed policy reload leaves the last accepted generation intact.

## Consequences

The supervisor remains the enforcement point for inner destinations. Tunnel keys and decrypted packets stay outside the workload. The appliance must expose a reachable WireGuard UDP listener and trust the supervisor peer key and tunnel source address. CONNECT establishes the upstream TCP stream after endpoint and address authorization, before its existing TLS and L7 request inspection; stricter pre-dial application authorization would require a separate CONNECT flow change. Tunnel DNS, tunnel configuration hot reload and key rotation, multiple routes, IPv6, and alternate TCP carriers remain future work.
14 changes: 14 additions & 0 deletions architecture/sandbox.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,20 @@ handled by the inference interception path:
External inference endpoints that do not use `inference.local` are treated like
ordinary network traffic and must be allowed by policy.

For an explicitly configured customer appliance, the supervisor owns one
userspace WireGuard interface. The workload receives neither its key nor a
tunnel network interface. A private IPv4 destination remains an ordinary
network endpoint: the explicit proxy authorizes its host and port, checks its
exact `allowed_ips` entry, then selects the named tunnel at the upstream dial
boundary. HTTP forward requests still pass L7 rules and credential rewriting
before the dial. CONNECT keeps its existing sequence: endpoint authorization
and address validation precede the TCP dial; TLS interception and request
inspection follow establishment. A `wireguard-udp` endpoint authorizes only
the supervisor's exact appliance socket and cannot authorize workload TCP.
The first implementation binds one tunnel and one inner endpoint. Policy
reloads retain tunnel traffic when that configuration and its key are unchanged;
changes revoke new tunnel dials until sandbox restart.

In proxy-required networks, the supervisor chains upstream TLS tunnels through
a corporate forward proxy with HTTP CONNECT instead of connecting directly,
once policy and SSRF checks pass. Only TLS (CONNECT) egress is chained:
Expand Down
3 changes: 3 additions & 0 deletions crates/openshell-core/src/gateway_channels.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Gateway connections whose supervisor session is currently established.
//!
//! A supervisor multi-connects to a subset of the gateway fleet and holds one
Expand Down
117 changes: 112 additions & 5 deletions crates/openshell-core/src/provider_credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ use std::fmt;
use std::sync::{Arc, RwLock};

const MAX_RETAINED_CREDENTIAL_GENERATIONS: usize = 8;
const SUPERVISOR_TUNNEL_ENV_PREFIX: &str = "OPENSHELL_WG_";

/// Reserved supervisor tunnel material remains in the resolver but never in
/// any workload-facing environment snapshot, including sidecar refreshes.
fn strip_supervisor_tunnel_keys(child_env: &mut HashMap<String, String>) {
child_env.retain(|key, _| !key.starts_with(SUPERVISOR_TUNNEL_ENV_PREFIX));
}

#[derive(Debug, Clone, Default)]
pub struct ProviderCredentialSnapshot {
Expand Down Expand Up @@ -80,12 +87,13 @@ impl ProviderCredentialState {
credential_expires_at_ms: HashMap<String, i64>,
dynamic_credentials: HashMap<String, crate::proto::ProviderProfileCredential>,
) -> Self {
let (child_env, generation_resolver, current_resolver) =
let (mut child_env, generation_resolver, current_resolver) =
SecretResolver::from_provider_env_for_current_revision(
env,
credential_expires_at_ms,
revision,
);
strip_supervisor_tunnel_keys(&mut child_env);
let snapshot = Arc::new(ProviderCredentialSnapshot {
revision,
child_env,
Expand Down Expand Up @@ -124,13 +132,14 @@ impl ProviderCredentialState {
&non_secret_environment_keys,
)?;
let stable_handles = static_credential_stable_handles(&static_credential_bindings);
let (child_env, generation_resolver, current_resolver) =
let (mut child_env, generation_resolver, current_resolver) =
SecretResolver::from_provider_env_for_current_revision_with_stable_handles(
env,
credential_expires_at_ms,
revision,
&stable_handles,
);
strip_supervisor_tunnel_keys(&mut child_env);
let snapshot = Arc::new(ProviderCredentialSnapshot {
revision,
child_env,
Expand Down Expand Up @@ -170,7 +179,8 @@ impl ProviderCredentialState {
/// workload-facing env map over a local control channel. The process leaf
/// must inject that map into child processes without re-placeholderizing it
/// or holding the gateway-side resolver material.
pub fn from_child_env_snapshot(revision: u64, child_env: HashMap<String, String>) -> Self {
pub fn from_child_env_snapshot(revision: u64, mut child_env: HashMap<String, String>) -> Self {
strip_supervisor_tunnel_keys(&mut child_env);
let snapshot = Arc::new(ProviderCredentialSnapshot {
revision,
child_env,
Expand Down Expand Up @@ -208,6 +218,7 @@ impl ProviderCredentialState {
.write()
.expect("provider credential state poisoned");

strip_supervisor_tunnel_keys(&mut child_env);
for key in &inner.suppressed_keys {
child_env.remove(key);
}
Expand Down Expand Up @@ -240,7 +251,26 @@ impl ProviderCredentialState {
.read()
.expect("provider credential state poisoned")
.combined_resolver
.clone()
.as_ref()
.map(|resolver| Arc::new(resolver.without_env_key_prefix(SUPERVISOR_TUNNEL_ENV_PREFIX)))
}

/// Resolve a reserved tunnel key for supervisor transport setup only.
/// Workload-facing resolver views never contain this value.
pub fn supervisor_tunnel_private_key(&self, key: &str) -> Option<String> {
if !key.starts_with(SUPERVISOR_TUNNEL_ENV_PREFIX)
|| key.len() == SUPERVISOR_TUNNEL_ENV_PREFIX.len()
{
return None;
}
self.inner
.read()
.expect("provider credential state poisoned")
.current_resolver
.as_ref()?
.resolve_current_env_key_checked(key, "supervisor tunnel")
.ok()?
.map(str::to_owned)
}

/// Resolve provider placeholders only for credentials bound to this
Expand Down Expand Up @@ -295,6 +325,7 @@ impl ProviderCredentialState {
.map(|(key, _)| key.clone())
.collect();
let resolver = inner.combined_resolver.as_ref().map(|resolver| {
let workload_resolver = resolver.without_env_key_prefix(SUPERVISOR_TUNNEL_ENV_PREFIX);
let revision_fallback_allowed_revisions = inner
.static_credential_identity_epochs
.iter()
Expand All @@ -307,7 +338,7 @@ impl ProviderCredentialState {
})
.map(|(key, epoch)| (key.clone(), epoch.revisions.clone()))
.collect();
Arc::new(resolver.scoped_to_env_keys(
Arc::new(workload_resolver.scoped_to_env_keys(
&inner.known_static_credential_keys,
&allowed,
revision_fallback_allowed_revisions,
Expand Down Expand Up @@ -474,6 +505,7 @@ impl ProviderCredentialState {
.write()
.expect("provider credential state poisoned");

strip_supervisor_tunnel_keys(&mut child_env);
for key in &inner.suppressed_keys {
child_env.remove(key);
}
Expand Down Expand Up @@ -537,6 +569,7 @@ impl ProviderCredentialState {
.write()
.expect("provider credential state poisoned");

strip_supervisor_tunnel_keys(&mut child_env);
for key in &inner.suppressed_keys {
child_env.remove(key);
}
Expand Down Expand Up @@ -2084,6 +2117,80 @@ mod tests {
);
}

#[test]
fn supervisor_tunnel_key_never_enters_workload_or_sidecar_environment() {
let key = "OPENSHELL_WG_PRIVATE_KEY";
let env = HashMap::from([
(key.to_string(), "supervisor-secret".to_string()),
("API_TOKEN".to_string(), "ordinary-secret".to_string()),
]);
let state = ProviderCredentialState::from_environment(
1,
env.clone(),
HashMap::new(),
HashMap::new(),
);
assert!(!state.snapshot().child_env.contains_key(key));
assert!(!state.child_env_with_gcp_resolved().contains_key(key));
assert!(state.snapshot().child_env.contains_key("API_TOKEN"));
assert_eq!(
state.supervisor_tunnel_private_key(key).as_deref(),
Some("supervisor-secret")
);
for token in [
"openshell:resolve:env:OPENSHELL_WG_PRIVATE_KEY",
"openshell:resolve:env:v1_OPENSHELL_WG_PRIVATE_KEY",
"xOPENSHELL-RESOLVE-ENV-OPENSHELL_WG_PRIVATE_KEY",
] {
assert!(
state
.resolver()
.unwrap()
.resolve_placeholder(token)
.is_none()
);
assert!(
state
.resolver_for_endpoint("api.example.test", 80, "/")
.unwrap()
.resolve_placeholder(token)
.is_none()
);
}
state.install_environment(2, env.clone(), HashMap::new(), HashMap::new());
assert!(!state.snapshot().child_env.contains_key(key));
assert_eq!(
state.supervisor_tunnel_private_key(key).as_deref(),
Some("supervisor-secret")
);
for token in [
"openshell:resolve:env:OPENSHELL_WG_PRIVATE_KEY",
"openshell:resolve:env:v1_OPENSHELL_WG_PRIVATE_KEY",
"openshell:resolve:env:v2_OPENSHELL_WG_PRIVATE_KEY",
] {
assert!(
state
.resolver()
.unwrap()
.resolve_placeholder(token)
.is_none()
);
assert!(
state
.resolver_for_endpoint("api.example.test", 80, "/")
.unwrap()
.resolve_placeholder(token)
.is_none()
);
}

let sidecar = ProviderCredentialState::from_child_env_snapshot(1, env.clone());
assert!(!sidecar.snapshot().child_env.contains_key(key));
sidecar.install_child_env_snapshot(2, env);
assert!(!sidecar.snapshot().child_env.contains_key(key));
assert!(sidecar.snapshot().child_env.contains_key("API_TOKEN"));
}

#[test]
fn child_env_snapshot_install_updates_env_without_resolver_material() {
let state = ProviderCredentialState::from_child_env_snapshot(
Expand Down
16 changes: 16 additions & 0 deletions crates/openshell-core/src/secrets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,22 @@ impl SecretResolver {
}
}

/// Remove supervisor-only environment keys from a workload resolver view.
/// This filters canonical, revisioned, stable, and provider-shaped aliases;
/// revision fallback cannot restore a removed canonical key.
pub(crate) fn without_env_key_prefix(&self, prefix: &str) -> Self {
let mut view = self.clone();
view.by_placeholder.retain(|placeholder, _| {
placeholder_env_key(placeholder).is_none_or(|key| !key.starts_with(prefix))
});
view.denied_env_keys.retain(|key| !key.starts_with(prefix));
view.identity_bound_env_keys
.retain(|key| !key.starts_with(prefix));
view.revision_fallback_allowed_revisions
.retain(|key, _| !key.starts_with(prefix));
view
}

/// Return a cheap endpoint-scoped resolver view.
///
/// Secret strings are shared through cloned resolver entries. Credential
Expand Down
99 changes: 79 additions & 20 deletions crates/openshell-driver-kubernetes/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1982,26 +1982,9 @@ impl KubernetesComputeDriver {
.supported_sandbox_api_for_lookup(self.client.clone())
.await
.map_err(KubernetesDriverError::Message)?;
let selector = self.sandbox_lookup_selector(sandbox_id);
let list = tokio::time::timeout(
KUBE_API_TIMEOUT,
lookup_api
.api
.list(&ListParams::default().labels(&selector)),
)
.await
.map_err(|_| {
KubernetesDriverError::Message(format!(
"timed out after {}s waiting for Kubernetes API",
KUBE_API_TIMEOUT.as_secs()
))
})?
.map_err(KubernetesDriverError::from_kube)?;
let object = list
.items
.into_iter()
.next()
.ok_or(KubernetesDriverError::NotFound)?;
let object = self
.resolve_operating_state_object(&lookup_api, sandbox_id)
.await?;
let namespace = object
.metadata
.namespace
Expand Down Expand Up @@ -2061,6 +2044,82 @@ impl KubernetesComputeDriver {
))
}

/// Resolve the Sandbox CR an operating-state patch (stop/start) must act
/// on. Direct-mode sandboxes carry the gateway labels, so the id-label
/// selector finds them. In claim mode the bound Sandbox is pool-generated
/// and carries no gateway labels — the id label lives on the SandboxClaim,
/// and `claim.status.sandbox.name` names the bound CR (the same resolution
/// get_sandbox and delete_sandbox already do for claims). Without this,
/// stop/start on a claimed sandbox always failed with NotFound.
async fn resolve_operating_state_object(
&self,
lookup_api: &AgentSandboxApi,
sandbox_id: &str,
) -> Result<DynamicObject, KubernetesDriverError> {
let selector = self.sandbox_lookup_selector(sandbox_id);
let list = tokio::time::timeout(
KUBE_API_TIMEOUT,
lookup_api.api.list(&ListParams::default().labels(&selector)),
)
.await
.map_err(|_| {
KubernetesDriverError::Message(format!(
"timed out after {}s waiting for Kubernetes API",
KUBE_API_TIMEOUT.as_secs()
))
})?
.map_err(KubernetesDriverError::from_kube)?;
if let Some(object) = list.items.into_iter().next() {
return Ok(object);
}
if !self.is_claim_mode() {
return Err(KubernetesDriverError::NotFound);
}
let claim_api = self.claim_api();
let claims = tokio::time::timeout(
KUBE_API_TIMEOUT,
claim_api.list(&ListParams::default().labels(&selector)),
)
.await
.map_err(|_| {
KubernetesDriverError::Message(format!(
"timed out after {}s waiting for Kubernetes API",
KUBE_API_TIMEOUT.as_secs()
))
})?
.map_err(KubernetesDriverError::from_kube)?;
let claim = claims
.items
.into_iter()
.next()
.ok_or(KubernetesDriverError::NotFound)?;
let bound_name = claim
.data
.get("status")
.and_then(|status| status.get("sandbox"))
.and_then(|sandbox| sandbox.get("name"))
.and_then(|name| name.as_str())
.map(str::to_string)
.ok_or_else(|| {
KubernetesDriverError::Message(
"sandbox claim is not bound to a sandbox yet".to_string(),
)
})?;
let object = tokio::time::timeout(
KUBE_API_TIMEOUT,
lookup_api.api.get(&bound_name),
)
.await
.map_err(|_| {
KubernetesDriverError::Message(format!(
"timed out after {}s waiting for Kubernetes API",
KUBE_API_TIMEOUT.as_secs()
))
})?
.map_err(KubernetesDriverError::from_kube)?;
Ok(object)
}

#[tracing::instrument(
name = "kubernetes.delete_sandbox",
skip(self),
Expand Down
2 changes: 2 additions & 0 deletions crates/openshell-policy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ license.workspace = true
repository.workspace = true

[dependencies]
base64 = { workspace = true }
ipnet = "2"
hickory-proto = { workspace = true }
openshell-core = { path = "../openshell-core", default-features = false }
serde = { workspace = true }
Expand Down
Loading
Loading