Skip to content

Commit d390efc

Browse files
committed
feat(sandbox): derive warm-path identity from the gateway-minted JWT
A pooled pod boots before it is claimed, so it cannot be handed a per-sandbox identity at create time. Let the supervisor boot identity-less on the image baseline policy and have the gateway derive the sandbox id from the gateway-minted JWT principal when the supervisor hello carries none, with a fast bootstrap retry while the claim binds. Landlock is applied once at process start, so a warm pod enforces the pool baseline policy; custom-policy requests stay on the cold path. Signed-off-by: Roshni Malani <rmalani@nvidia.com>
1 parent a7ee7bc commit d390efc

4 files changed

Lines changed: 90 additions & 25 deletions

File tree

‎crates/openshell-sandbox/src/lib.rs‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1223,7 +1223,22 @@ async fn load_policy(
12231223
}
12241224

12251225
// gRPC mode: fetch typed proto policy, construct OPA engine from baked rules + proto data
1226-
if let (Some(id), Some(endpoint)) = (&sandbox_id, &openshell_endpoint) {
1226+
if let Some(endpoint) = &openshell_endpoint {
1227+
// Warm-pool path: a pooled pod boots before its claim assigns an
1228+
// identity, so there is no per-sandbox policy to fetch yet. Boot on the
1229+
// image's baseline policy (default-deny) and enforce it; the per-sandbox
1230+
// policy is NOT applied on the warm path because Landlock is applied
1231+
// once at process start and cannot be loosened afterwards. Requests that
1232+
// carry a custom policy fall back to the cold path (see the driver's
1233+
// warm-pool eligibility check), so there is no silent policy downgrade.
1234+
let Some(id) = sandbox_id.as_deref().filter(|id| !id.is_empty()) else {
1235+
info!("Warm-pool sandbox: loading baseline policy (no boot-time identity)");
1236+
let mut proto_policy = discover_policy_from_disk_or_default();
1237+
enrich_proto_baseline_paths(&mut proto_policy);
1238+
let opa_engine = Some(Arc::new(OpaEngine::from_proto(&proto_policy)?));
1239+
let policy = SandboxPolicy::try_from(proto_policy.clone())?;
1240+
return Ok((policy, opa_engine, Some(proto_policy)));
1241+
};
12271242
info!(
12281243
sandbox_id = %id,
12291244
endpoint = %endpoint,

‎crates/openshell-server/src/supervisor_session.rs‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -591,13 +591,27 @@ pub async fn handle_connect_supervisor(
591591
None => return Err(Status::invalid_argument("stream closed before hello")),
592592
};
593593

594-
let sandbox_id = hello.sandbox_id.clone();
595-
if sandbox_id.is_empty() {
596-
return Err(Status::invalid_argument("sandbox_id is required"));
597-
}
598-
if let Some(principal) = principal.as_ref() {
599-
crate::auth::guard::ensure_sandbox_principal_scope(principal, &sandbox_id)?;
600-
}
594+
// Resolve the session's sandbox identity. A warm-pooled supervisor boots
595+
// without an identity and sends an empty `sandbox_id`; in that case the
596+
// identity is taken from the authenticated (gateway-minted) JWT principal,
597+
// which the K8s SA bootstrap re-anchor already resolved server-side from
598+
// the pod annotation + the durable claim mapping. A supervisor that does
599+
// assert an id must match its principal (unchanged cross-check).
600+
let sandbox_id = if hello.sandbox_id.is_empty() {
601+
match principal.as_ref() {
602+
Some(Principal::Sandbox(p)) if !p.sandbox_id.is_empty() => p.sandbox_id.clone(),
603+
_ => {
604+
return Err(Status::unauthenticated(
605+
"supervisor hello has no sandbox_id and no authenticated sandbox identity",
606+
));
607+
}
608+
}
609+
} else {
610+
if let Some(principal) = principal.as_ref() {
611+
crate::auth::guard::ensure_sandbox_principal_scope(principal, &hello.sandbox_id)?;
612+
}
613+
hello.sandbox_id.clone()
614+
};
601615
require_persisted_sandbox(&state.store, &sandbox_id).await?;
602616

603617
let session_id = Uuid::new_v4().to_string();

‎crates/openshell-supervisor-process/src/run.rs‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -296,14 +296,19 @@ pub async fn run_process(
296296
}
297297

298298
// Spawn the persistent supervisor session if we have a gateway endpoint
299-
// and sandbox identity. The session provides relay channels for SSH
300-
// connect and ExecSandbox through the gateway.
301-
if let (Some(endpoint), Some(id), Some(socket)) =
302-
(openshell_endpoint, sandbox_id, ssh_socket_path.as_ref())
303-
{
299+
// and a relay socket. The session provides relay channels for SSH connect
300+
// and ExecSandbox through the gateway.
301+
//
302+
// A boot-time sandbox identity is NOT required: warm-pooled pods boot
303+
// before a claim assigns their `openshell.io/sandbox-id`, so the session
304+
// sends an empty id in its hello and the gateway derives the sandbox
305+
// identity from the gateway-minted JWT (resolved server-side from the pod
306+
// annotation during `IssueSandboxToken`). Cold sandboxes pass their known
307+
// id through unchanged.
308+
if let (Some(endpoint), Some(socket)) = (openshell_endpoint, ssh_socket_path.as_ref()) {
304309
crate::supervisor_session::spawn(
305310
endpoint.to_string(),
306-
id.to_string(),
311+
sandbox_id.map(str::to_string),
307312
socket.clone(),
308313
ssh_netns_fd,
309314
);

‎crates/openshell-supervisor-process/src/supervisor_session.rs‎

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ use openshell_core::grpc_client;
3434

3535
const INITIAL_BACKOFF: Duration = Duration::from_secs(1);
3636
const MAX_BACKOFF: Duration = Duration::from_secs(30);
37+
/// Fixed, short retry cadence used while the supervisor has not yet established
38+
/// its first session — e.g. a warm-pooled pod whose identity is not assigned
39+
/// until its pool claim binds. A steady poll (rather than exponential backoff)
40+
/// keeps the session coming up promptly once the gateway can mint a JWT.
41+
const BOOTSTRAP_RETRY: Duration = Duration::from_secs(2);
3742

3843
/// Parse a gRPC endpoint URI into an OCSF `Endpoint` (host + port). Falls back
3944
/// to treating the whole string as a domain if parsing fails.
@@ -232,7 +237,7 @@ fn map_stream_message<T>(
232237
/// exponential backoff on failures.
233238
pub fn spawn(
234239
endpoint: String,
235-
sandbox_id: String,
240+
sandbox_id: Option<String>,
236241
ssh_socket_path: std::path::PathBuf,
237242
netns_fd: Option<i32>,
238243
) -> tokio::task::JoinHandle<()> {
@@ -246,20 +251,33 @@ pub fn spawn(
246251

247252
async fn run_session_loop(
248253
endpoint: String,
249-
sandbox_id: String,
254+
sandbox_id: Option<String>,
250255
ssh_socket_path: std::path::PathBuf,
251256
netns_fd: Option<i32>,
252257
) {
253258
let mut backoff = INITIAL_BACKOFF;
254259
let mut attempt: u64 = 0;
260+
// Tracks whether we have established a session at least once. Until then
261+
// (e.g. a warm pod still waiting to be claimed) we retry at a steady short
262+
// cadence rather than backing off exponentially, so the session comes up
263+
// promptly once the gateway can resolve the pod's identity.
264+
let ever_connected = std::sync::atomic::AtomicBool::new(false);
265+
let log_id = sandbox_id.as_deref().unwrap_or_default();
255266

256267
loop {
257268
attempt += 1;
258269

259-
match run_single_session(&endpoint, &sandbox_id, &ssh_socket_path, netns_fd).await {
270+
match run_single_session(
271+
&endpoint,
272+
sandbox_id.as_deref(),
273+
&ssh_socket_path,
274+
netns_fd,
275+
&ever_connected,
276+
)
277+
.await
278+
{
260279
Ok(()) => {
261-
let event =
262-
session_closed_event(openshell_ocsf::ctx::ctx(), &endpoint, &sandbox_id);
280+
let event = session_closed_event(openshell_ocsf::ctx::ctx(), &endpoint, log_id);
263281
ocsf_emit!(event);
264282
break;
265283
}
@@ -271,18 +289,23 @@ async fn run_session_loop(
271289
&e.to_string(),
272290
);
273291
ocsf_emit!(event);
274-
tokio::time::sleep(backoff).await;
275-
backoff = (backoff * 2).min(MAX_BACKOFF);
292+
if ever_connected.load(std::sync::atomic::Ordering::Relaxed) {
293+
tokio::time::sleep(backoff).await;
294+
backoff = (backoff * 2).min(MAX_BACKOFF);
295+
} else {
296+
tokio::time::sleep(BOOTSTRAP_RETRY).await;
297+
}
276298
}
277299
}
278300
}
279301
}
280302

281303
async fn run_single_session(
282304
endpoint: &str,
283-
sandbox_id: &str,
305+
sandbox_id: Option<&str>,
284306
ssh_socket_path: &std::path::Path,
285307
netns_fd: Option<i32>,
308+
ever_connected: &std::sync::atomic::AtomicBool,
286309
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
287310
// Connect to the gateway. The same `Channel` is used for both the
288311
// long-lived control stream and all data-plane `RelayStream` calls, so
@@ -297,11 +320,14 @@ async fn run_single_session(
297320
let (tx, rx) = mpsc::channel::<SupervisorMessage>(64);
298321
let outbound = tokio_stream::wrappers::ReceiverStream::new(rx);
299322

300-
// Send hello as the first message.
323+
// Send hello as the first message. On the warm path the supervisor has no
324+
// boot-time identity, so it sends an empty `sandbox_id` and the gateway
325+
// derives identity from the authenticated (gateway-minted) JWT. Cold
326+
// sandboxes assert their known id, which the gateway cross-checks.
301327
let instance_id = uuid::Uuid::new_v4().to_string();
302328
tx.send(SupervisorMessage {
303329
payload: Some(supervisor_message::Payload::Hello(SupervisorHello {
304-
sandbox_id: sandbox_id.to_string(),
330+
sandbox_id: sandbox_id.unwrap_or_default().to_string(),
305331
instance_id: instance_id.clone(),
306332
})),
307333
})
@@ -329,6 +355,11 @@ async fn run_single_session(
329355
_ => return Err("expected SessionAccepted or SessionRejected".into()),
330356
};
331357

358+
// We have a live, gateway-accepted session; subsequent reconnects (after a
359+
// clean close or transient error) use exponential backoff rather than the
360+
// bootstrap poll cadence.
361+
ever_connected.store(true, std::sync::atomic::Ordering::Relaxed);
362+
332363
let heartbeat_secs = accepted.heartbeat_interval_secs.max(5);
333364
let event = session_established_event(
334365
openshell_ocsf::ctx::ctx(),
@@ -349,7 +380,7 @@ async fn run_single_session(
349380
let msg = map_stream_message(msg, "gateway closed stream")?;
350381
handle_gateway_message(
351382
&msg,
352-
sandbox_id,
383+
sandbox_id.unwrap_or_default(),
353384
ssh_socket_path,
354385
netns_fd,
355386
&channel,

0 commit comments

Comments
 (0)