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
36 changes: 36 additions & 0 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 @@ -286,6 +302,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;
96 changes: 96 additions & 0 deletions crates/openshell-driver-kubernetes/src/app_endpoint_index/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use super::*;

fn metadata(namespace: &str, name: &str, uid: &str, id: &str) -> ObjectMeta {
ObjectMeta {
namespace: Some(namespace.into()),
name: Some(name.into()),
uid: Some(uid.into()),
labels: Some(BTreeMap::from([
(LABEL_SANDBOX_ID.into(), id.into()),
(LABEL_GATEWAY_ID.into(), "gateway".into()),
(LABEL_MANAGED_BY.into(), LABEL_MANAGED_BY_VALUE.into()),
])),
..Default::default()
}
}

#[test]
fn partial_initialization_and_watch_reset_do_not_publish_locators() {
let index = AppEndpointIndex::default();
let object = metadata("ns", "sandbox", "uid", "id");
index.observe(Event::InitApply(object.clone()));
assert!(index.lookup("id").is_none());
index.observe(Event::InitDone);
assert!(index.lookup("id").is_some());
index.observe(Event::Init);
index.observe(Event::InitApply(object));
assert!(index.lookup("id").is_none());
index.observe(Event::InitDone);
assert!(index.lookup("id").is_some());
index.observe(Event::Init);
index.observe(Event::InitDone);
assert!(
index.lookup("id").is_none(),
"relisting removes absent resources"
);
}

#[test]
fn duplicate_ids_across_namespaces_are_ambiguous() {
let index = AppEndpointIndex::default();
let first = metadata("ns-a", "same-name", "uid-a", "id");
let second = metadata("ns-b", "same-name", "uid-b", "id");
index.observe(Event::InitApply(first));
index.observe(Event::InitApply(second.clone()));
index.observe(Event::InitDone);
assert!(index.lookup("id").is_none());
index.observe(Event::Delete(second));
assert_eq!(index.lookup("id").unwrap().namespace, "ns-a");
}

#[test]
fn delayed_deletion_cannot_remove_recreated_resource() {
let index = AppEndpointIndex::default();
let original = metadata("ns", "sandbox", "old", "id");
let replacement = metadata("ns", "sandbox", "new", "id");
index.observe(Event::InitApply(original.clone()));
index.observe(Event::InitDone);
let old = index.lookup("id").unwrap();
index.observe(Event::Apply(replacement.clone()));
index.observe(Event::Delete(original));
assert!(!old.matches(&replacement, "id", "gateway"));
assert!(
index
.lookup("id")
.unwrap()
.matches(&replacement, "id", "gateway")
);
}

#[test]
fn label_reassignment_replaces_old_id_and_get_must_match_all_identity_fields() {
let index = AppEndpointIndex::default();
let mut object = metadata("ns", "sandbox", "uid", "old");
index.observe(Event::InitApply(object.clone()));
index.observe(Event::InitDone);
object
.labels
.as_mut()
.unwrap()
.insert(LABEL_SANDBOX_ID.into(), "new".into());
index.observe(Event::Apply(object.clone()));
assert!(index.lookup("old").is_none());
let locator = index.lookup("new").unwrap();
assert!(locator.matches(&object, "new", "gateway"));
assert!(!locator.matches(&object, "old", "gateway"));
assert!(!locator.matches(&object, "new", "other-gateway"));
object
.labels
.as_mut()
.unwrap()
.insert(LABEL_MANAGED_BY.into(), "foreign".into());
assert!(!locator.matches(&object, "new", "gateway"));
}
Loading
Loading