Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
9 changes: 5 additions & 4 deletions .agents/skills/helm-dev-environment/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,9 +259,10 @@ Discovery returns the acknowledged owner's Pod IP and app port; no headless app
Service is needed. Exercise HTTP/WebSocket reconnection through graceful downscale
and abrupt loss, preserving workload generation/PID/in-memory state and the public
hostname. Verify stale-owner rejection independently of the replacement's success.
Shared serving leases expire within fifteen seconds of issuance and do not renew
from configuration alone. Do not claim seamless socket migration or infer external
ingress readiness from an advertisement.
Installed routes and application streams survive gateway outages. Verify explicit
withdrawal and sandbox-attachment ownership changes independently of control-session
liveness. Do not claim seamless socket migration or infer external ingress readiness
from an advertisement.

### 2. Deploy OpenShell

Expand Down Expand Up @@ -531,7 +532,7 @@ For the opt-in application listener, build/import matching branch images and run
`mise run e2e:kubernetes:app-listener`; see `e2e/kubernetes/app-listener/README.md`
for image, topology, delivery-mode and takeover inputs. The task owns an isolated
Helm release/namespace, temporary TLS material, in-cluster clients, teardown and
evidence under `results/app-listener/`. It checks policy denial, Pod-IP ingress without app Services, shared-owner takeover, gateway-outage expiry and disabled-listener
evidence under `results/app-listener/`. It checks policy denial, Pod-IP ingress without app Services, shared-owner takeover, gateway-outage route retention and disabled-listener
gateway compatibility, without discovery or a proxy. CI runs four cases under
`test:e2e` and includes them in `Core E2E result`. Its reusable kind setup installs
pinned Calico only for this lane; other jobs retain kindnet. Local k3s already
Expand Down
67 changes: 62 additions & 5 deletions crates/openshell-core/src/app_listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

pub const DEFAULT_APP_MAX_CONNECTIONS: usize = 1024;
pub const DEFAULT_APP_MAX_CONNECTIONS_PER_SANDBOX: usize = 64;

/// Gateway browser credentials are reserved on both application access paths.
pub fn is_gateway_service_auth_cookie(name: &[u8]) -> bool {
name.eq_ignore_ascii_case(b"__Host-openshell-service-session")
Expand All @@ -21,6 +24,10 @@ pub struct AppListenerConfig {
pub port: u16,
/// Public HTTPS origin used to derive service hostnames and URLs.
pub base_url: Option<String>,
/// Concurrent accepted TLS connections per supervisor listener.
pub max_connections: usize,
/// Concurrent connections and backend relays for each sandbox.
pub max_connections_per_sandbox: usize,
}

impl Default for AppListenerConfig {
Expand All @@ -29,6 +36,8 @@ impl Default for AppListenerConfig {
enabled: false,
port: 8443,
base_url: None,
max_connections: DEFAULT_APP_MAX_CONNECTIONS,
max_connections_per_sandbox: DEFAULT_APP_MAX_CONNECTIONS_PER_SANDBOX,
}
}
}
Expand Down Expand Up @@ -59,6 +68,13 @@ impl AppListenerConfig {
if !self.enabled {
return Ok(());
}
if self.max_connections == 0
|| self.max_connections > tokio::sync::Semaphore::MAX_PERMITS
|| self.max_connections_per_sandbox == 0
|| self.max_connections_per_sandbox > self.max_connections
{
return Err("app listener requires 1 <= max_connections_per_sandbox <= max_connections <= Semaphore::MAX_PERMITS".into());
}
let origin = self.parsed_base_url()?;
validate_listener_endpoint(self.port, origin.host_str().unwrap_or_default())
}
Expand Down Expand Up @@ -199,11 +215,32 @@ fn base32_lower_no_padding(bytes: &[u8]) -> String {
output
}

/// A synchronous view of installed ingress, evaluated on the sandbox instance
/// runtime. The requested lease must fit entirely within serving freshness.
pub type InstallationSource = std::sync::Arc<
dyn Fn(std::time::Duration) -> crate::proto::SupervisorServiceAdvertisement + Send + Sync,
>;
/// Installed ingress on one sandbox attachment, with change notifications.
#[derive(Clone)]
pub struct InstallationSource {
snapshot:
std::sync::Arc<dyn Fn() -> crate::proto::SupervisorServiceAdvertisement + Send + Sync>,
updates: tokio::sync::watch::Receiver<()>,
}

impl InstallationSource {
pub fn new(
snapshot: std::sync::Arc<
dyn Fn() -> crate::proto::SupervisorServiceAdvertisement + Send + Sync,
>,
updates: tokio::sync::watch::Receiver<()>,
) -> Self {
Self { snapshot, updates }
}

pub fn snapshot(&self) -> crate::proto::SupervisorServiceAdvertisement {
(self.snapshot)()
}

pub async fn changed(&mut self) -> Result<(), tokio::sync::watch::error::RecvError> {
self.updates.changed().await
}
}

#[cfg(test)]
mod tests {
Expand Down Expand Up @@ -286,6 +323,26 @@ mod tests {
assert!(config.service_url("default", "demo", "web", None).is_none());
}

#[test]
fn listener_connection_budgets_preserve_defaults_and_reject_invalid_bounds() {
let mut config = AppListenerConfig {
enabled: true,
base_url: Some("https://services.example.com".into()),
..Default::default()
};
assert_eq!(config.max_connections, 1024);
assert_eq!(config.max_connections_per_sandbox, 64);
assert!(config.validate().is_ok());
for (total, per_sandbox) in [(0, 1), (64, 0), (64, 65), (usize::MAX, 1)] {
config.max_connections = total;
config.max_connections_per_sandbox = per_sandbox;
assert!(config.validate().is_err());
}
config.max_connections = 16384;
config.max_connections_per_sandbox = 256;
assert!(config.validate().is_ok());
}

#[test]
fn base_url_is_the_only_authored_service_domain() {
let config: AppListenerConfig = serde_json::from_str(
Expand Down
8 changes: 8 additions & 0 deletions crates/openshell-driver-kubernetes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

Kubernetes-backed compute driver for OpenShell cluster deployments.

Application endpoint resolution uses a metadata-only Sandbox watch to map each
sandbox ID to its Kubernetes resource. Every resolution still fetches that
resource by name and checks its UID, gateway labels, and deletion state before
validating supervisor placement. The watch must finish its initial list;
ambiguous IDs and watch errors make resolution unavailable until a fresh list
completes. Renewals use point reads to avoid repeated label-selected Sandbox
LISTs exhausting Kubernetes API flow-control capacity.

Caller driver config is disabled by default. External resource references need
administrator-controlled approval labels in every workspace mode, including
before restart and scheduling-gate release. GPU devices are temporarily exempt.
Expand Down
179 changes: 179 additions & 0 deletions crates/openshell-driver-kubernetes/src/app_endpoint_index.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Watch-maintained resource locators, never cached endpoint authority.

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use futures::StreamExt as _;
use kube::Api;
use kube::core::{DynamicObject, ObjectMeta, PartialObjectMeta};
use kube::runtime::watcher::{self, Event};
use openshell_core::driver_utils::{
LABEL_GATEWAY_ID, LABEL_MANAGED_BY, LABEL_MANAGED_BY_VALUE, LABEL_SANDBOX_ID,
};

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Locator {
pub namespace: String,
pub name: String,
uid: String,
}

impl Locator {
pub fn matches(&self, metadata: &ObjectMeta, sandbox_id: &str, gateway_id: &str) -> bool {
let label = |key| metadata.labels.as_ref().and_then(|labels| labels.get(key));
metadata.namespace.as_ref() == Some(&self.namespace)
&& metadata.name.as_ref() == Some(&self.name)
&& metadata.uid.as_ref() == Some(&self.uid)
&& metadata.deletion_timestamp.is_none()
&& label(LABEL_SANDBOX_ID).is_some_and(|id| id == sandbox_id)
&& label(LABEL_GATEWAY_ID).is_some_and(|id| id == gateway_id)
&& label(LABEL_MANAGED_BY).is_some_and(|value| value == LABEL_MANAGED_BY_VALUE)
}
}

#[derive(Default)]
struct State {
ready: bool,
// Key by resource name so label changes replace the previous association.
objects: BTreeMap<(String, String), (String, Locator)>,
by_id: BTreeMap<String, BTreeMap<(String, String), Locator>>,
}

impl State {
fn remove(&mut self, key: &(String, String)) {
if let Some((id, _)) = self.objects.remove(key)
&& let Some(locators) = self.by_id.get_mut(&id)
{
locators.remove(key);
if locators.is_empty() {
self.by_id.remove(&id);
}
}
}

fn apply(&mut self, metadata: ObjectMeta) {
let (Some(namespace), Some(name)) = (&metadata.namespace, &metadata.name) else {
return;
};
let key = (namespace.clone(), name.clone());
self.remove(&key);
let Some(uid) = metadata.uid.clone() else {
return;
};
let Some(id) = metadata
.labels
.as_ref()
.and_then(|labels| labels.get(LABEL_SANDBOX_ID))
.cloned()
else {
return;
};
if metadata.deletion_timestamp.is_some() {
return;
}
let locator = Locator {
namespace: namespace.clone(),
name: name.clone(),
uid,
};
self.by_id
.entry(id.clone())
.or_default()
.insert(key.clone(), locator.clone());
self.objects.insert(key, (id, locator));
}

fn delete(&mut self, metadata: &ObjectMeta) {
let (Some(namespace), Some(name)) = (&metadata.namespace, &metadata.name) else {
return;
};
let key = (namespace.clone(), name.clone());
if self
.objects
.get(&key)
.is_some_and(|(_, locator)| metadata.uid.as_ref() == Some(&locator.uid))
{
self.remove(&key);
}
}
}

#[derive(Clone, Default)]
pub struct AppEndpointIndex(Arc<Mutex<State>>);

impl AppEndpointIndex {
pub fn lookup(&self, sandbox_id: &str) -> Option<Locator> {
let state = self.0.lock().ok()?;
if !state.ready {
return None;
}
let locators = state.by_id.get(sandbox_id)?;
if locators.len() != 1 {
return None;
}
locators.values().next().cloned()
}

pub fn observe(&self, event: Event<ObjectMeta>) {
let Ok(mut state) = self.0.lock() else { return };
match event {
Event::Init => *state = State::default(),
Event::InitApply(metadata) | Event::Apply(metadata) => state.apply(metadata),
Event::InitDone => state.ready = true,
Event::Delete(metadata) => state.delete(&metadata),
}
}

pub fn start(
&self,
api: Api<PartialObjectMeta<DynamicObject>>,
selector: String,
mut shutdown: tokio::sync::watch::Receiver<bool>,
) {
let index = self.clone();
tokio::spawn(async move {
loop {
if *shutdown.borrow() {
break;
}
let stream =
watcher::watcher(api.clone(), watcher::Config::default().labels(&selector));
tokio::pin!(stream);
loop {
tokio::select! {
_ = shutdown.changed() => { index.observe(Event::Init); return; }
event = stream.next() => match event {
Some(Ok(event)) => index.observe(match event {
Event::Init => Event::Init,
Event::InitDone => Event::InitDone,
Event::Apply(object) => Event::Apply(object.metadata),
Event::InitApply(object) => Event::InitApply(object.metadata),
Event::Delete(object) => Event::Delete(object.metadata),
}),
Some(Err(error)) => {
tracing::warn!(%error, "application endpoint locator watch failed; relisting");
break;
}
None => break,
}
}
}
// Recreate the watcher after errors so recovery must complete
// a fresh list; incremental events cannot revive a partial index.
index.observe(Event::Init);
tokio::select! {
_ = shutdown.changed() => return,
() = tokio::time::sleep(Duration::from_secs(1)) => {}
}
}
index.observe(Event::Init);
});
}
}

#[cfg(test)]
mod tests;
Loading
Loading