Skip to content

Commit 45a349e

Browse files
committed
fix(server): three sandbox-identity issues found during helm exercise
Three regressions / inefficiencies surfaced while bringing the per-sandbox identity series up end-to-end in the local helm cluster: 1. CLI returned Unauthenticated against a no-OIDC dev gateway. PR 3 removed the pre-refactor "no OIDC = pass through" behavior; with only sandbox-side authenticators in the chain, plain user CLI calls hit Unauthenticated. Add a PermissiveUserAuthenticator that installs as a final fallback when no OIDC is configured but sandbox JWT signing IS — produces a synthetic dev-anonymous user principal so the rest of the handler chain treats CLI calls as User and bypasses the IDOR guard. Production OIDC deployments are unaffected: when OIDC is configured the fallback is not installed and missing-Bearer still 401s. 2. Sandbox supervisor re-ran the K8s SA bootstrap exchange on every connect_channel() call. With multiple subsystems each building their own channels, IssueSandboxToken was firing every few seconds even though TOKEN_SLOT already had a fresh token. Change connect_channel to reuse TOKEN_SLOT when populated; only run acquire_sandbox_token on the first call per process. The refresh loop keeps the slot fresh thereafter. 3. K8s SA authenticator looked up sandbox pods in the gateway's own namespace (POD_NAMESPACE) instead of the K8s driver's configured sandbox namespace. Source from kubernetes_config_from_file() so the resolver targets the same namespace the driver creates pods in. Verified end-to-end against the helm-dev cluster: - Two sandboxes get distinct gateway JWTs with their own sandbox UUIDs. - Cross-sandbox GetSandboxConfig is rejected with PermissionDenied and the auth::guard audit log fires with both principal and requested IDs. - RefreshSandboxToken mints a new JWT and revokes the old jti; the old token is then rejected with Unauthenticated: revoked token.
1 parent 6391728 commit 45a349e

4 files changed

Lines changed: 84 additions & 20 deletions

File tree

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

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -159,23 +159,26 @@ async fn build_plain_channel(endpoint: &str) -> Result<Channel> {
159159

160160
/// Build a Bearer-authenticated channel to the gateway.
161161
///
162-
/// Resolves the sandbox JWT via the three-step lookup described at the
163-
/// module level (env → file → K8s SA bootstrap exchange), installs the
164-
/// token into the process-wide [`TOKEN_SLOT`], wraps the channel in an
165-
/// [`AuthInterceptor`] that reads from that slot, and spawns the refresh
166-
/// loop the first time the channel is built.
162+
/// First call per process resolves the sandbox JWT via the three-step
163+
/// lookup (env → file → K8s SA bootstrap exchange) and installs it into
164+
/// the process-wide [`TOKEN_SLOT`]. Subsequent calls reuse the cached
165+
/// slot — the refresh loop keeps the value fresh, so re-running the
166+
/// bootstrap is both unnecessary and (on the K8s SA path) expensive
167+
/// (one apiserver round-trip per call). The refresh loop itself is
168+
/// spawned once per process via [`REFRESH_SPAWNED`].
167169
async fn connect_channel(endpoint: &str) -> Result<AuthedChannel> {
168170
let channel = build_plain_channel(endpoint).await?;
169-
let token = acquire_sandbox_token(endpoint, &channel).await?;
170-
let slot = install_token_slot(&token)?;
171+
let slot = if let Some(existing) = TOKEN_SLOT.get() {
172+
existing.clone()
173+
} else {
174+
let token = acquire_sandbox_token(endpoint, &channel).await?;
175+
install_token_slot(&token)?
176+
};
171177
let intercepted = InterceptedService::new(channel, AuthInterceptor::new(slot.clone()));
172-
// Spawn the refresh loop once per process. It uses the same authed
173-
// channel, so its outbound calls always carry the current token.
174178
if REFRESH_SPAWNED.set(()).is_ok() {
175179
let refresh_channel = intercepted.clone();
176-
let refresh_slot = slot;
177180
tokio::spawn(async move {
178-
refresh_token_loop(refresh_channel, refresh_slot).await;
181+
refresh_token_loop(refresh_channel, slot).await;
179182
});
180183
}
181184
Ok(intercepted)

‎crates/openshell-server/src/auth/authenticator.rs‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,13 @@
1717
//! - [`super::k8s_sa::K8sServiceAccountAuthenticator`] — K8s projected SA
1818
//! tokens (path-scoped to `IssueSandboxToken`)
1919
//! - [`super::oidc::OidcAuthenticator`] — user OIDC Bearer tokens
20+
//! - [`PermissiveUserAuthenticator`] — final-fallback dev-mode catch-all
21+
//! that produces a synthetic user principal when no OIDC is
22+
//! configured. Preserves the pre-PR-1 "no OIDC = open" posture for
23+
//! singleplayer / helm-dev deployments.
2024
21-
use super::principal::Principal;
25+
use super::identity::{Identity, IdentityProvider};
26+
use super::principal::{Principal, UserPrincipal};
2227
use async_trait::async_trait;
2328
use std::sync::Arc;
2429
use tonic::Status;
@@ -91,6 +96,48 @@ impl std::fmt::Debug for AuthenticatorChain {
9196
}
9297
}
9398

99+
/// Final-fallback authenticator that produces a synthetic user principal
100+
/// for any request the earlier authenticators didn't claim. Used only
101+
/// when no user-side authentication is configured (no OIDC, no fronting
102+
/// proxy contract) — the pre-PR-1 gateway accepted such requests with
103+
/// no auth at all; this preserves that posture in a principal-aware
104+
/// way so handlers always see *some* principal in extensions.
105+
///
106+
/// Producing a User principal (rather than Anonymous) means dev-mode
107+
/// requests pass the per-handler IDOR guard via the User-bypass
108+
/// branch — equivalent to "RBAC was the user's gate" with the dev
109+
/// default of "every caller is a user."
110+
pub struct PermissiveUserAuthenticator {
111+
subject: String,
112+
}
113+
114+
impl PermissiveUserAuthenticator {
115+
pub fn new(subject: impl Into<String>) -> Self {
116+
Self {
117+
subject: subject.into(),
118+
}
119+
}
120+
}
121+
122+
#[async_trait]
123+
impl Authenticator for PermissiveUserAuthenticator {
124+
async fn authenticate(
125+
&self,
126+
_headers: &http::HeaderMap,
127+
_path: &str,
128+
) -> Result<Option<Principal>, Status> {
129+
Ok(Some(Principal::User(UserPrincipal {
130+
identity: Identity {
131+
subject: self.subject.clone(),
132+
display_name: None,
133+
roles: vec![],
134+
scopes: vec![],
135+
provider: IdentityProvider::Internal,
136+
},
137+
})))
138+
}
139+
}
140+
94141
#[cfg(test)]
95142
pub mod test_support {
96143
use super::*;

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

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -302,21 +302,24 @@ pub async fn run_server(
302302
// and without the issuer there's nothing to exchange the SA token
303303
// for.
304304
if state.sandbox_jwt_issuer.is_some() && std::env::var_os("KUBERNETES_SERVICE_HOST").is_some() {
305+
// Pod lookups must target the sandbox namespace (where the K8s
306+
// driver places sandbox pods), not the gateway's own pod
307+
// namespace. Sourced from the merged
308+
// `[openshell.drivers.kubernetes].namespace` config, falling
309+
// back to "default" only if the driver config can't be parsed.
310+
let sandbox_namespace = kubernetes_config_from_file(config_file.as_ref())
311+
.map_or_else(|_| "default".to_string(), |cfg| cfg.namespace);
305312
match kube::Client::try_default().await {
306313
Ok(client) => {
307-
let namespace = std::env::var("POD_NAMESPACE")
308-
.ok()
309-
.filter(|s| !s.is_empty())
310-
.unwrap_or_else(|| "default".to_string());
311314
let resolver = Arc::new(auth::k8s_sa::LiveK8sResolver::new(
312315
client,
313-
&namespace,
316+
&sandbox_namespace,
314317
"openshell-gateway".to_string(),
315318
));
316319
let authenticator = auth::k8s_sa::K8sServiceAccountAuthenticator::new(resolver);
317320
state.k8s_sa_authenticator = Some(Arc::new(authenticator));
318321
info!(
319-
namespace = %namespace,
322+
namespace = %sandbox_namespace,
320323
"K8s ServiceAccount bootstrap authenticator enabled"
321324
);
322325
}

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

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ use tracing::Span;
3232

3333
use crate::{
3434
OpenShellService, ServerState,
35-
auth::authenticator::AuthenticatorChain,
35+
auth::authenticator::{AuthenticatorChain, PermissiveUserAuthenticator},
3636
auth::authz::AuthzPolicy,
3737
auth::oidc::{self, OidcAuthenticator},
3838
auth::principal::Principal,
@@ -260,7 +260,12 @@ where
260260
/// 2. `SandboxJwtAuthenticator` — validates gateway-minted JWTs. Recognized
261261
/// via a distinctive `kid` so non-matching Bearer tokens fall through.
262262
/// 3. `OidcAuthenticator` — validates user Bearer tokens against the
263-
/// configured OIDC issuer.
263+
/// configured OIDC issuer. Returns `Unauthenticated` for missing
264+
/// Bearer headers so non-OIDC clients can't sneak through.
265+
/// 4. `PermissiveUserAuthenticator` — installed only when no OIDC is
266+
/// configured (singleplayer / helm-dev). Catches anything the
267+
/// sandbox authenticators didn't claim and produces a synthetic
268+
/// user principal, preserving the pre-PR-1 "no OIDC = open" posture.
264269
///
265270
/// When neither OIDC nor gateway-minted JWTs are configured (a barebones
266271
/// dev gateway), the chain is left as `None` so the router short-circuits
@@ -275,6 +280,12 @@ fn build_authenticator_chain(state: &ServerState) -> Option<AuthenticatorChain>
275280
}
276281
if let Some(cache) = state.oidc_cache.clone() {
277282
authenticators.push(Arc::new(OidcAuthenticator::new(cache)));
283+
} else if !authenticators.is_empty() {
284+
// No OIDC, but sandbox-side authentication IS configured —
285+
// user CLI calls must still pass through, so install a
286+
// permissive final fallback. Production deployments configure
287+
// OIDC and this branch is unused.
288+
authenticators.push(Arc::new(PermissiveUserAuthenticator::new("dev-anonymous")));
278289
}
279290
if authenticators.is_empty() {
280291
return None;

0 commit comments

Comments
 (0)