Skip to content

Commit 0183288

Browse files
committed
feat(supervisor): rotate launch-scoped authentication
Signed-off-by: Drew Newberry <anewberry@nvidia.com>
1 parent d9e88fb commit 0183288

22 files changed

Lines changed: 1477 additions & 440 deletions

File tree

‎crates/openshell-core/src/grpc_client.rs‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,9 @@ static TOKEN_INIT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new((
7070
/// One-shot guard so the renewal loop spawns at most once per process.
7171
static REFRESH_SPAWNED: OnceLock<()> = OnceLock::new();
7272

73+
#[cfg(feature = "jwt")]
74+
static SANDBOX_BEARER_SLOT: OnceLock<crate::jwt::SessionBearerTokenSlot> = OnceLock::new();
75+
7376
#[derive(Clone, Debug)]
7477
enum RefreshMode {
7578
GatewayJwt(TokenSource),
@@ -94,6 +97,22 @@ fn install_token_slot(token: &str) -> Result<TokenSlot> {
9497
Ok(TOKEN_SLOT.get().cloned().unwrap_or(slot))
9598
}
9699

100+
/// Install the gateway-session credential supplied in trusted supervisor
101+
/// launch state before any gateway client is constructed.
102+
#[cfg(feature = "jwt")]
103+
pub fn install_supervisor_auth_bundle(
104+
bundle: &crate::jwt::SupervisorAuthBundle,
105+
) -> Result<crate::jwt::SessionBearerTokenSlot> {
106+
install_token_slot(bundle.gateway_token.expose_secret())?;
107+
let _ = TOKEN_REFRESH_MODE.set(RefreshMode::GatewayJwt(TokenSource::File));
108+
let slot = bundle
109+
.sandbox_bearer_slot()
110+
.into_diagnostic()
111+
.wrap_err("invalid Sandbox Protocol credential")?;
112+
let _ = SANDBOX_BEARER_SLOT.set(slot.clone());
113+
Ok(SANDBOX_BEARER_SLOT.get().cloned().unwrap_or(slot))
114+
}
115+
97116
/// gRPC interceptor that injects `authorization: Bearer <token>` on every
98117
/// outbound request. The token lives in a shared [`TokenSlot`] so the renewal
99118
/// task can replace it without rebuilding clients.
@@ -360,7 +379,8 @@ async fn refresh_token_loop(
360379
.await
361380
{
362381
Ok(resp) => {
363-
let new_token = resp.into_inner().token;
382+
let response = resp.into_inner();
383+
let new_token = response.token;
364384
match AsciiMetadataValue::try_from(format!("Bearer {new_token}")) {
365385
Ok(value) => {
366386
if let Ok(mut guard) = slot.write() {
@@ -370,6 +390,18 @@ async fn refresh_token_loop(
370390
}
371391
Err(e) => warn!(error = %e, "refreshed JWT contained invalid header bytes"),
372392
}
393+
#[cfg(feature = "jwt")]
394+
if let Some(sandbox_slot) = SANDBOX_BEARER_SLOT.get() {
395+
let update =
396+
crate::jwt::SecretJwt::parse(response.sandbox_token).and_then(|token| {
397+
let epoch =
398+
crate::jwt::CredentialEpoch::new(response.credential_epoch)?;
399+
sandbox_slot.update(token, response.sandbox_expires_at_ms / 1000, epoch)
400+
});
401+
if let Err(error) = update {
402+
warn!(%error, "gateway returned an invalid Sandbox Protocol credential");
403+
}
404+
}
373405
}
374406
Err(status) => {
375407
if status.code() == tonic::Code::Unauthenticated
@@ -467,6 +499,23 @@ async fn refresh_extension_credentials_with_client(
467499
// is a superset of what the dedicated renewal loop would do, so letting it
468500
// land early is harmless.
469501
install_token_slot(&response.token)?;
502+
#[cfg(feature = "jwt")]
503+
if let Some(sandbox_slot) = SANDBOX_BEARER_SLOT.get() {
504+
let token = crate::jwt::SecretJwt::parse(response.sandbox_token.clone())
505+
.into_diagnostic()
506+
.wrap_err("gateway returned an invalid Sandbox Protocol token")?;
507+
let epoch = crate::jwt::CredentialEpoch::new(response.credential_epoch)
508+
.into_diagnostic()
509+
.wrap_err("gateway returned an invalid Sandbox Protocol credential epoch")?;
510+
match sandbox_slot.update(token, response.sandbox_expires_at_ms / 1000, epoch) {
511+
Ok(()) | Err(crate::jwt::SessionJwtError::StaleCredentialEpoch) => {}
512+
Err(error) => {
513+
return Err(miette::miette!(
514+
"gateway returned an invalid Sandbox Protocol credential: {error}"
515+
));
516+
}
517+
}
518+
}
470519

471520
// Validate the whole response before mutating any slot, so a malformed or
472521
// partial reply cannot leave the store half-rotated.

‎crates/openshell-core/src/jwt.rs‎

Lines changed: 188 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,119 @@ mod session {
181181
}
182182
}
183183

184+
impl Serialize for SecretJwt {
185+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
186+
where
187+
S: serde::Serializer,
188+
{
189+
serializer.serialize_str(self.expose_secret())
190+
}
191+
}
192+
193+
impl<'de> Deserialize<'de> for SecretJwt {
194+
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
195+
where
196+
D: serde::Deserializer<'de>,
197+
{
198+
let value = String::deserialize(deserializer)?;
199+
Self::parse(value).map_err(serde::de::Error::custom)
200+
}
201+
}
202+
203+
/// Trusted launch input delivered only to `openshell-supervisor`.
204+
#[derive(Clone, Serialize, Deserialize)]
205+
#[serde(deny_unknown_fields)]
206+
pub struct SupervisorAuthBundle {
207+
pub session_id: SandboxSessionId,
208+
pub gateway_token: SecretJwt,
209+
pub gateway_expires_at: i64,
210+
pub sandbox_token: SecretJwt,
211+
pub sandbox_expires_at: i64,
212+
pub credential_epoch: CredentialEpoch,
213+
}
214+
215+
/// Gateway-created authentication input trusted by a compute driver.
216+
///
217+
/// Drivers split this structure: the supervisor receives `supervisor`,
218+
/// while the sandbox receives only the gateway identity and public keys.
219+
#[derive(Clone, Serialize, Deserialize)]
220+
#[serde(deny_unknown_fields)]
221+
pub struct SandboxLaunchAuthentication {
222+
pub supervisor: SupervisorAuthBundle,
223+
pub gateway_id: String,
224+
pub verification_keys: Vec<SessionVerificationKey>,
225+
}
226+
227+
impl SandboxLaunchAuthentication {
228+
pub fn validate(&self) -> Result<(), SessionJwtError> {
229+
self.supervisor.validate()?;
230+
validate_gateway_id(&self.gateway_id)?;
231+
if self.verification_keys.is_empty() {
232+
return Err(SessionJwtError::NoVerificationKeys);
233+
}
234+
let mut key_ids = std::collections::BTreeSet::new();
235+
for key in &self.verification_keys {
236+
validate_key_id(key.key_id.clone())?;
237+
if key.public_key_pem.is_empty() {
238+
return Err(SessionJwtError::InvalidVerificationKey);
239+
}
240+
if !key_ids.insert(key.key_id.as_str()) {
241+
return Err(SessionJwtError::DuplicateKeyId);
242+
}
243+
}
244+
Ok(())
245+
}
246+
}
247+
248+
impl fmt::Debug for SandboxLaunchAuthentication {
249+
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
250+
formatter
251+
.debug_struct("SandboxLaunchAuthentication")
252+
.field("supervisor", &self.supervisor)
253+
.field("gateway_id", &self.gateway_id)
254+
.field(
255+
"verification_key_ids",
256+
&self
257+
.verification_keys
258+
.iter()
259+
.map(|key| key.key_id.as_str())
260+
.collect::<Vec<_>>(),
261+
)
262+
.finish()
263+
}
264+
}
265+
266+
impl SupervisorAuthBundle {
267+
pub fn validate(&self) -> Result<(), SessionJwtError> {
268+
if self.gateway_expires_at <= 0 || self.sandbox_expires_at <= 0 {
269+
return Err(SessionJwtError::InvalidLifetime);
270+
}
271+
Ok(())
272+
}
273+
274+
pub fn sandbox_bearer_slot(&self) -> Result<SessionBearerTokenSlot, SessionJwtError> {
275+
SessionBearerTokenSlot::new(
276+
self.sandbox_token.clone(),
277+
self.sandbox_expires_at,
278+
self.credential_epoch,
279+
)
280+
}
281+
}
282+
283+
impl fmt::Debug for SupervisorAuthBundle {
284+
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
285+
formatter
286+
.debug_struct("SupervisorAuthBundle")
287+
.field("session_id", &self.session_id)
288+
.field("gateway_token", &"[REDACTED]")
289+
.field("gateway_expires_at", &self.gateway_expires_at)
290+
.field("sandbox_token", &"[REDACTED]")
291+
.field("sandbox_expires_at", &self.sandbox_expires_at)
292+
.field("credential_epoch", &self.credential_epoch)
293+
.finish()
294+
}
295+
}
296+
184297
#[derive(Clone, Debug)]
185298
pub struct MintedSessionToken {
186299
pub token: SecretJwt,
@@ -206,6 +319,7 @@ mod session {
206319
struct StoredBearer {
207320
token: SecretJwt,
208321
expires_at: i64,
322+
credential_epoch: CredentialEpoch,
209323
}
210324

211325
impl SessionBearerTokenSlot {
@@ -216,21 +330,40 @@ mod session {
216330
}
217331
}
218332

219-
pub fn new(token: SecretJwt, expires_at: i64) -> Result<Self, SessionJwtError> {
333+
pub fn new(
334+
token: SecretJwt,
335+
expires_at: i64,
336+
credential_epoch: CredentialEpoch,
337+
) -> Result<Self, SessionJwtError> {
220338
let slot = Self::empty();
221-
slot.update(token, expires_at)?;
339+
slot.update(token, expires_at, credential_epoch)?;
222340
Ok(slot)
223341
}
224342

225-
pub fn update(&self, token: SecretJwt, expires_at: i64) -> Result<(), SessionJwtError> {
343+
pub fn update(
344+
&self,
345+
token: SecretJwt,
346+
expires_at: i64,
347+
credential_epoch: CredentialEpoch,
348+
) -> Result<(), SessionJwtError> {
226349
if expires_at <= 0 {
227350
return Err(SessionJwtError::InvalidLifetime);
228351
}
229-
*self
352+
let mut stored = self
230353
.inner
231354
.write()
232-
.unwrap_or_else(std::sync::PoisonError::into_inner) =
233-
Some(StoredBearer { token, expires_at });
355+
.unwrap_or_else(std::sync::PoisonError::into_inner);
356+
if stored
357+
.as_ref()
358+
.is_some_and(|current| credential_epoch <= current.credential_epoch)
359+
{
360+
return Err(SessionJwtError::StaleCredentialEpoch);
361+
}
362+
*stored = Some(StoredBearer {
363+
token,
364+
expires_at,
365+
credential_epoch,
366+
});
234367
Ok(())
235368
}
236369

@@ -250,6 +383,15 @@ mod session {
250383
.map(|stored| stored.expires_at)
251384
}
252385

386+
#[must_use]
387+
pub fn credential_epoch(&self) -> Option<CredentialEpoch> {
388+
self.inner
389+
.read()
390+
.unwrap_or_else(std::sync::PoisonError::into_inner)
391+
.as_ref()
392+
.map(|stored| stored.credential_epoch)
393+
}
394+
253395
pub fn authorization_metadata(
254396
&self,
255397
) -> Result<tonic::metadata::AsciiMetadataValue, SessionJwtError> {
@@ -278,6 +420,7 @@ mod session {
278420
formatter
279421
.debug_struct("SessionBearerTokenSlot")
280422
.field("expires_at", &self.expires_at())
423+
.field("credential_epoch", &self.credential_epoch())
281424
.finish_non_exhaustive()
282425
}
283426
}
@@ -401,6 +544,8 @@ mod session {
401544
}
402545

403546
/// One accepted public key from the immutable sandbox verification bundle.
547+
#[derive(Clone, Serialize, Deserialize)]
548+
#[serde(deny_unknown_fields)]
404549
pub struct SessionVerificationKey {
405550
pub key_id: String,
406551
pub public_key_pem: Vec<u8>,
@@ -541,6 +686,8 @@ mod session {
541686
InvalidGatewayId,
542687
#[error("credential epoch must be positive")]
543688
InvalidCredentialEpoch,
689+
#[error("credential epoch does not advance the active credential")]
690+
StaleCredentialEpoch,
544691
#[error("key ID is invalid")]
545692
InvalidKeyId,
546693
#[error("verification key IDs must be unique")]
@@ -765,6 +912,41 @@ mod tests {
765912
assert!(!debug.contains(pair.sandbox.token.expose_secret()));
766913
}
767914

915+
#[test]
916+
fn supervisor_auth_bundle_round_trips_without_exposing_secrets_in_debug() {
917+
let (issuer, _gateway, _sandbox, identity) = fixture();
918+
let pair = issuer
919+
.mint_pair(&identity, CredentialEpoch::new(7).expect("epoch"))
920+
.expect("token pair");
921+
let bundle = SupervisorAuthBundle {
922+
session_id: identity.session_id,
923+
gateway_token: pair.gateway.token,
924+
gateway_expires_at: pair.gateway.expires_at,
925+
sandbox_token: pair.sandbox.token,
926+
sandbox_expires_at: pair.sandbox.expires_at,
927+
credential_epoch: pair.credential_epoch,
928+
};
929+
930+
let encoded = serde_json::to_vec(&bundle).expect("serialize auth bundle");
931+
let decoded: SupervisorAuthBundle =
932+
serde_json::from_slice(&encoded).expect("deserialize auth bundle");
933+
assert_eq!(decoded.session_id, bundle.session_id);
934+
assert_eq!(decoded.credential_epoch, bundle.credential_epoch);
935+
assert_eq!(
936+
decoded.gateway_token.expose_secret(),
937+
bundle.gateway_token.expose_secret()
938+
);
939+
assert_eq!(
940+
decoded.sandbox_token.expose_secret(),
941+
bundle.sandbox_token.expose_secret()
942+
);
943+
944+
let debug = format!("{bundle:?}");
945+
assert!(!debug.contains(bundle.gateway_token.expose_secret()));
946+
assert!(!debug.contains(bundle.sandbox_token.expose_secret()));
947+
assert_eq!(debug.matches("[REDACTED]").count(), 2);
948+
}
949+
768950
#[derive(Serialize)]
769951
struct AudienceArrayClaims<'a> {
770952
iss: &'a str,

‎crates/openshell-driver-docker/src/tests.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ fn test_sandbox() -> DriverSandbox {
5050
tty: false,
5151
await_main_process_attachment: false,
5252
workload_identity: None,
53+
launch_authentication: Vec::new(),
5354
}),
5455
status: None,
5556
workspace: String::new(),

0 commit comments

Comments
 (0)