diff --git a/architecture/gateway.md b/architecture/gateway.md index cca6599281..ec2e8d8882 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -29,6 +29,11 @@ gateway maps the verified certificate subject to a user principal. Kubernetes deployments use mTLS for transport only and require OIDC or a trusted access proxy for user authentication unless the explicit unsafe local-development `allow_unauthenticated_users` switch is enabled. +OIDC deployments normally enforce RBAC roles for user and admin APIs. Shared +gateways reject OIDC authentication-only mode unless +`allow_oidc_auth_only` is set explicitly, and authenticated gRPC methods fail +closed when no user, sandbox, mTLS, or explicit local-dev principal can be +derived. When that service port is bound to loopback, the listener can also accept plaintext HTTP on the same port for sandbox service subdomains only. That local browser path is enabled by default and disabled with diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index b200eded64..c1d358052f 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -572,6 +572,12 @@ pub struct GatewayAuthConfig { /// gateway-minted sandbox JWTs. #[serde(default)] pub allow_unauthenticated_users: bool, + + /// When true, an OIDC issuer may authenticate users without requiring + /// configured RBAC roles. Configured scope checks still apply, so shared + /// deployments must opt in explicitly. + #[serde(default)] + pub allow_oidc_auth_only: bool, } /// One configured gateway interceptor service. @@ -895,6 +901,109 @@ impl Config { self.service_routing.enable_loopback_service_http = enabled; self } + + /// Validate auth settings that depend on the deployment posture. + /// + /// Local loopback gateways can rely on developer-oriented auth shortcuts, + /// but Kubernetes and externally-bound gateways must fail closed unless + /// the operator chose an explicit weak mode. + pub fn validate_gateway_auth_posture(&self) -> Result<(), String> { + self.validate_gateway_auth_posture_with_extra_bind_addresses(&[]) + } + + /// Validate auth settings against the configured listener set plus + /// runtime-provided gateway listeners from compute drivers. + pub fn validate_gateway_auth_posture_with_extra_bind_addresses( + &self, + extra_bind_addresses: &[SocketAddr], + ) -> Result<(), String> { + let shared = + self.is_shared_gateway_deployment_with_extra_bind_addresses(extra_bind_addresses); + + if self.auth.allow_oidc_auth_only && self.oidc.is_none() { + return Err( + "auth.allow_oidc_auth_only=true requires OIDC to be configured".to_string(), + ); + } + + if let Some(oidc) = &self.oidc { + let admin_set = !oidc.admin_role.is_empty(); + let user_set = !oidc.user_role.is_empty(); + + if admin_set != user_set { + return Err(format!( + "OIDC RBAC misconfiguration: admin_role={:?}, user_role={:?}. \ + Either set both roles (RBAC mode) or leave both empty (authentication-only mode).", + oidc.admin_role, oidc.user_role, + )); + } + + if admin_set && self.auth.allow_oidc_auth_only { + return Err( + "auth.allow_oidc_auth_only=true is only valid when OIDC admin_role and user_role are both empty" + .to_string(), + ); + } + + if shared && !admin_set && !self.auth.allow_oidc_auth_only { + return Err( + "OIDC authentication-only mode is disabled for shared gateway deployments; \ + configure admin_role and user_role for RBAC, or set \ + auth.allow_oidc_auth_only=true to skip role checks while retaining configured scope checks" + .to_string(), + ); + } + } + + if self.is_kubernetes_gateway_deployment() && self.mtls_auth.enabled { + return Err( + "mTLS user authentication is not supported with the Kubernetes compute driver; \ + configure OIDC or a trusted fronting proxy for user authentication" + .to_string(), + ); + } + + let has_user_authenticator = self.oidc.is_some(); + if shared + && !has_user_authenticator + && !self.mtls_auth.enabled + && !self.auth.allow_unauthenticated_users + { + return Err( + "shared gateway deployments require an explicit auth path; configure OIDC, \ + mTLS user auth, or set auth.allow_unauthenticated_users=true \ + only behind a trusted local-dev/fronting-proxy boundary" + .to_string(), + ); + } + + Ok(()) + } + + /// Whether this gateway serves a shared or remotely reachable gRPC API. + #[must_use] + pub fn is_shared_gateway_deployment(&self) -> bool { + self.is_shared_gateway_deployment_with_extra_bind_addresses(&[]) + } + + #[must_use] + fn is_shared_gateway_deployment_with_extra_bind_addresses( + &self, + extra_bind_addresses: &[SocketAddr], + ) -> bool { + self.is_kubernetes_gateway_deployment() + || !self.bind_address.ip().is_loopback() + || extra_bind_addresses + .iter() + .any(|addr| !addr.ip().is_loopback()) + } + + #[must_use] + fn is_kubernetes_gateway_deployment(&self) -> bool { + self.compute_drivers + .iter() + .any(|driver| driver == ComputeDriverKind::Kubernetes.as_str()) + } } impl Default for ServiceRoutingConfig { @@ -981,10 +1090,10 @@ mod tests { use super::{ ComputeDriverKind, Config, DEFAULT_SERVICE_ROUTING_DOMAIN, GatewayInterceptorBindingPolicy, GatewayInterceptorConfig, GatewayInterceptorFailurePolicy, GatewayJwtConfig, - GatewayProviderProfileSourceConfig, detect_docker_socket_from_candidates, detect_driver, - detect_podman_socket_from_candidates, docker_host_unix_socket_path, docker_socket_responds, - is_unix_socket, normalize_compute_driver_name, podman_socket_candidates_from_env, - podman_socket_responds, + GatewayProviderProfileSourceConfig, OidcConfig, detect_docker_socket_from_candidates, + detect_driver, detect_podman_socket_from_candidates, docker_host_unix_socket_path, + docker_socket_responds, is_unix_socket, normalize_compute_driver_name, + podman_socket_candidates_from_env, podman_socket_responds, }; #[cfg(unix)] use std::io::{Read as _, Write as _}; @@ -1050,6 +1159,125 @@ mod tests { assert!(!cfg.auth.allow_unauthenticated_users); } + fn oidc_config(admin_role: &str, user_role: &str) -> OidcConfig { + OidcConfig { + issuer: "https://issuer.example.com".to_string(), + audience: "openshell-cli".to_string(), + jwks_ttl_secs: 3600, + roles_claim: "realm_access.roles".to_string(), + admin_role: admin_role.to_string(), + user_role: user_role.to_string(), + scopes_claim: String::new(), + } + } + + #[test] + fn gateway_auth_posture_allows_loopback_oidc_auth_only_without_override() { + let cfg = Config::new(None).with_oidc(oidc_config("", "")); + + assert!(cfg.validate_gateway_auth_posture().is_ok()); + } + + #[test] + fn gateway_auth_posture_rejects_shared_oidc_auth_only_without_override() { + let cfg = Config::new(None) + .with_compute_drivers([ComputeDriverKind::Kubernetes]) + .with_oidc(oidc_config("", "")); + + let err = cfg.validate_gateway_auth_posture().unwrap_err(); + assert!(err.contains("OIDC authentication-only mode")); + } + + #[test] + fn gateway_auth_posture_allows_shared_oidc_auth_only_with_override() { + let mut cfg = Config::new(None) + .with_compute_drivers([ComputeDriverKind::Kubernetes]) + .with_oidc(oidc_config("", "")); + cfg.auth.allow_oidc_auth_only = true; + + assert!(cfg.validate_gateway_auth_posture().is_ok()); + } + + #[test] + fn gateway_auth_posture_rejects_oidc_auth_only_override_without_oidc() { + let mut cfg = Config::new(None); + cfg.auth.allow_oidc_auth_only = true; + + let err = cfg.validate_gateway_auth_posture().unwrap_err(); + assert!(err.contains("requires OIDC to be configured")); + } + + #[test] + fn gateway_auth_posture_rejects_oidc_auth_only_override_with_rbac() { + let mut cfg = Config::new(None).with_oidc(oidc_config("openshell-admin", "openshell-user")); + cfg.auth.allow_oidc_auth_only = true; + + let err = cfg.validate_gateway_auth_posture().unwrap_err(); + assert!(err.contains("only valid when OIDC admin_role and user_role are both empty")); + } + + #[test] + fn gateway_auth_posture_allows_shared_oidc_rbac() { + let cfg = Config::new(None) + .with_compute_drivers([ComputeDriverKind::Kubernetes]) + .with_oidc(oidc_config("openshell-admin", "openshell-user")); + + assert!(cfg.validate_gateway_auth_posture().is_ok()); + } + + #[test] + fn gateway_auth_posture_rejects_partial_oidc_roles() { + let cfg = Config::new(None).with_oidc(oidc_config("openshell-admin", "")); + + let err = cfg.validate_gateway_auth_posture().unwrap_err(); + assert!(err.contains("OIDC RBAC misconfiguration")); + } + + #[test] + fn gateway_auth_posture_rejects_shared_gateway_without_auth_path() { + let cfg = Config::new(None).with_compute_drivers([ComputeDriverKind::Kubernetes]); + + let err = cfg.validate_gateway_auth_posture().unwrap_err(); + assert!(err.contains("require an explicit auth path")); + } + + #[test] + fn gateway_auth_posture_rejects_shared_gateway_with_only_sandbox_jwt() { + let mut cfg = Config::new(None).with_compute_drivers([ComputeDriverKind::Kubernetes]); + cfg.gateway_jwt = Some(GatewayJwtConfig { + signing_key_path: "/tmp/signing.pem".into(), + public_key_path: "/tmp/public.pem".into(), + kid_path: "/tmp/kid".into(), + gateway_id: "openshell".to_string(), + ttl_secs: 3600, + }); + + let err = cfg.validate_gateway_auth_posture().unwrap_err(); + assert!(err.contains("require an explicit auth path")); + } + + #[test] + fn gateway_auth_posture_rejects_runtime_non_loopback_listener_without_auth_path() { + let cfg = Config::new(None); + let driver_bind: SocketAddr = "172.18.0.1:17670".parse().expect("valid address"); + + let err = cfg + .validate_gateway_auth_posture_with_extra_bind_addresses(&[driver_bind]) + .unwrap_err(); + assert!(err.contains("require an explicit auth path")); + } + + #[test] + fn gateway_auth_posture_rejects_kubernetes_mtls_user_auth() { + let mut cfg = Config::new(None) + .with_compute_drivers([ComputeDriverKind::Kubernetes]) + .with_oidc(oidc_config("openshell-admin", "openshell-user")); + cfg.mtls_auth.enabled = true; + + let err = cfg.validate_gateway_auth_posture().unwrap_err(); + assert!(err.contains("mTLS user authentication is not supported")); + } + #[test] fn config_defaults_to_builtin_and_user_provider_profile_sources() { let cfg = Config::new(None); diff --git a/crates/openshell-server/src/auth/authz.rs b/crates/openshell-server/src/auth/authz.rs index 1c04b09766..37ec3501f2 100644 --- a/crates/openshell-server/src/auth/authz.rs +++ b/crates/openshell-server/src/auth/authz.rs @@ -23,7 +23,9 @@ const SCOPE_ALL: &str = "openshell:all"; /// /// Supports two modes: /// - **RBAC mode**: both `admin_role` and `user_role` are non-empty. -/// - **Authentication-only mode**: both are empty (any valid token is authorized). +/// - **Authentication-only mode**: both are empty (role checks are skipped). +/// +/// Configured scope checks apply in both modes. /// /// Partial configuration (one empty, one set) is rejected at construction /// to prevent accidentally leaving admin endpoints unprotected. @@ -60,8 +62,8 @@ impl AuthzPolicy { /// Check whether the identity is authorized to call the given method. /// /// Returns `Ok(())` if authorized, `Err(PERMISSION_DENIED)` if not. - /// When both role names are empty, all authenticated callers are authorized - /// (authentication-only mode for providers like GitHub). + /// When both role names are empty, role checks are skipped. Configured + /// scope checks still apply. #[allow(clippy::result_large_err)] pub fn check(&self, identity: &Identity, method: &str) -> Result<(), Status> { let required = match method_authz::required_role(method) { diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index 269b9f40e9..0e5882fd01 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -480,8 +480,7 @@ async fn run_from_args(mut args: RunArgs, matches: ArgMatches) -> Result<()> { && prepared.config.gateway_jwt.is_none() { warn!( - "Neither mTLS user auth nor OIDC nor sandbox JWT auth is configured — \ - the gateway has no authentication mechanism" + "No gateway authentication path is configured; non-loopback or shared deployments will fail startup" ); } diff --git a/crates/openshell-server/src/config_file.rs b/crates/openshell-server/src/config_file.rs index c4e0cbc959..8a120ffe00 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -441,11 +441,13 @@ grpc_endpoint = "https://openshell-gateway.agents.svc:8080" let toml = r" [openshell.gateway.auth] allow_unauthenticated_users = true +allow_oidc_auth_only = true "; let tmp = write_tmp(toml); let file = load(tmp.path()).expect("valid auth config parses"); let auth = file.openshell.gateway.auth.expect("auth config"); assert!(auth.allow_unauthenticated_users); + assert!(auth.allow_oidc_auth_only); } #[test] diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index a75534d397..6d0ef8566e 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -240,6 +240,9 @@ pub(crate) async fn run_server( if database_url.is_empty() { return Err(Error::config("database_url is required")); } + config + .validate_gateway_auth_posture() + .map_err(Error::config)?; let middleware_registrations = config_file .as_ref() @@ -263,24 +266,6 @@ pub(crate) async fn run_server( let store = Arc::new(Store::connect(database_url).await?); - let oidc_cache = if let Some(ref oidc) = config.oidc { - // Validate RBAC configuration before starting. - let policy = auth::authz::AuthzPolicy { - admin_role: oidc.admin_role.clone(), - user_role: oidc.user_role.clone(), - scopes_enabled: !oidc.scopes_claim.is_empty(), - }; - policy.validate().map_err(Error::config)?; - - let cache = auth::oidc::JwksCache::new(oidc) - .await - .map_err(|e| Error::config(format!("OIDC initialization failed: {e}")))?; - info!("OIDC JWT validation enabled (issuer: {})", oidc.issuer); - Some(Arc::new(cache)) - } else { - None - }; - let sandbox_index = SandboxIndex::new(); let sandbox_watch_bus = SandboxWatchBus::new(); let supervisor_sessions = Arc::new(supervisor_session::SupervisorSessionRegistry::new()); @@ -301,6 +286,29 @@ pub(crate) async fn run_server( supervisor_sessions.clone(), ) .await?; + config + .validate_gateway_auth_posture_with_extra_bind_addresses(compute.gateway_bind_addresses()) + .map_err(Error::config)?; + + let oidc_cache = if let Some(ref oidc) = config.oidc { + // Validate RBAC configuration before starting. + let policy = auth::authz::AuthzPolicy { + admin_role: oidc.admin_role.clone(), + user_role: oidc.user_role.clone(), + scopes_enabled: !oidc.scopes_claim.is_empty(), + }; + policy.validate().map_err(Error::config)?; + + let cache = auth::oidc::JwksCache::new(oidc) + .await + .map_err(|e| Error::config(format!("OIDC initialization failed: {e}")))?; + info!("OIDC JWT validation enabled (issuer: {})", oidc.issuer); + warn_if_oidc_auth_only_enabled(&config); + Some(Arc::new(cache)) + } else { + None + }; + let gateway_interceptors = openshell_gateway_interceptors::initialize(config.gateway_interceptors.clone()) .await @@ -942,6 +950,22 @@ fn builtin_compute_driver(name: &str) -> Option { name.parse().ok() } +fn oidc_auth_only_enabled(config: &Config) -> bool { + config.auth.allow_oidc_auth_only + && config + .oidc + .as_ref() + .is_some_and(|oidc| oidc.admin_role.is_empty() && oidc.user_role.is_empty()) +} + +fn warn_if_oidc_auth_only_enabled(config: &Config) { + if oidc_auth_only_enabled(config) { + warn!( + "OIDC authentication-only mode enabled; RBAC role checks are disabled and configured scope checks still apply" + ); + } +} + fn kubernetes_sandbox_jwt_expiry_disabled(config: &Config) -> bool { config .gateway_jwt @@ -1022,7 +1046,7 @@ mod tests { ConfiguredComputeDriver, ConnectionProtocol, MultiplexService, ServerState, TlsAcceptor, allow_plaintext_service_http, classify_initial_bytes, configured_compute_driver, gateway_listener_addresses, is_benign_tls_handshake_failure, - kubernetes_sandbox_jwt_expiry_disabled, serve_gateway_listener, + kubernetes_sandbox_jwt_expiry_disabled, oidc_auth_only_enabled, serve_gateway_listener, }; use openshell_core::{ ComputeDriverKind, Config, @@ -1492,6 +1516,29 @@ mod tests { assert!(!kubernetes_sandbox_jwt_expiry_disabled(&Config::new(None))); } + #[test] + fn oidc_auth_only_enabled_requires_explicit_active_mode() { + let mut config = Config::new(None).with_oidc(openshell_core::OidcConfig { + issuer: "https://issuer.example.com".to_string(), + audience: "openshell-cli".to_string(), + jwks_ttl_secs: 3600, + roles_claim: "realm_access.roles".to_string(), + admin_role: String::new(), + user_role: String::new(), + scopes_claim: String::new(), + }); + + assert!(!oidc_auth_only_enabled(&config)); + + config.auth.allow_oidc_auth_only = true; + assert!(oidc_auth_only_enabled(&config)); + + let oidc = config.oidc.as_mut().expect("OIDC configured"); + oidc.admin_role = "openshell-admin".to_string(); + oidc.user_role = "openshell-user".to_string(); + assert!(!oidc_auth_only_enabled(&config)); + } + #[test] fn gateway_listener_addresses_skip_driver_address_covered_by_wildcard() { let primary: SocketAddr = "0.0.0.0:8080".parse().unwrap(); diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 83e27d27cb..e601b0e833 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -710,9 +710,9 @@ where /// for local single-user gateways, or to an unsafe local developer user when /// `auth.allow_unauthenticated_users` is explicitly enabled. /// -/// When neither OIDC nor sandbox credentials are configured (a barebones -/// dev gateway), the chain is left as `None` so the router short-circuits -/// to pass-through unless mTLS or local unauthenticated users are enabled. +/// When neither OIDC nor sandbox credentials are configured, the chain is left +/// as `None`; authenticated methods still fail closed unless mTLS or local +/// unauthenticated users are enabled explicitly. fn build_authenticator_chain(state: &ServerState) -> Option { let mut authenticators: Vec> = Vec::new(); if let Some(k8s) = state.k8s_sa_authenticator.clone() { @@ -737,8 +737,8 @@ fn build_authenticator_chain(state: &ServerState) -> Option /// - Strip any external `x-openshell-auth-source` marker first (so callers /// cannot spoof a sandbox identity). /// - Health probes / reflection bypass the chain entirely. -/// - When no chain is configured (OIDC not configured), forward without -/// authentication — preserves today's pass-through behavior. +/// - When no chain is configured, authenticated methods fail closed unless +/// mTLS user auth or the explicit local unauthenticated user mode applies. /// - Otherwise, run the chain. The first match produces a `Principal`. /// `Principal::User` is gated by the RBAC `AuthzPolicy`. /// `Principal::Sandbox` is gated by a supervisor-method allowlist, then @@ -856,9 +856,9 @@ where } else if allow_unauthenticated_users { unauthenticated_dev_user_principal() } else { - // No auth configured — pass through for dev / - // fronting-proxy deployments. - return inner.ready().await?.call(req).await; + return Ok(status_response(tonic::Status::unauthenticated( + "gateway authentication is not configured", + ))); }; match principal { @@ -2018,6 +2018,21 @@ mod tests { )); } + #[tokio::test] + async fn missing_chain_without_explicit_auth_fails_closed() { + let (recorder, seen) = PrincipalRecorder::new(); + let mut router = + AuthGrpcRouter::with_peer_identity(recorder, None, None, None, false, false); + + let res = router + .call(empty_request("/openshell.v1.OpenShell/ListSandboxes")) + .await + .unwrap(); + + assert!(seen.lock().unwrap().is_none()); + assert_eq!(grpc_status(&res).as_deref(), Some("16")); + } + #[tokio::test] async fn user_principal_lands_in_request_extensions() { let mock = Arc::new(MockAuthenticator::returning(Ok(Some(user_principal( diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index 8723535d1a..64a22fe778 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -194,6 +194,7 @@ add `ci/values-spire.yaml` to the OpenShell release values files. | securityContext.runAsNonRoot | bool | `true` | Require the gateway container to run as a non-root user. | | securityContext.runAsUser | int | `1000` | UID assigned to the gateway container. | | server.appArmorProfile | string | `"Unconfined"` | Kubernetes AppArmor profile requested for sandbox agent containers. Default Unconfined avoids runtime/default AppArmor blocking the supervisor's network namespace mount setup on AppArmor-enabled nodes. Set to "" to omit the field, "RuntimeDefault" to force the runtime default profile, or "Localhost/profile-name" for an operator-managed localhost profile. | +| server.auth.allowOidcAuthOnly | bool | `false` | UNSAFE: allow OIDC authentication-only mode when adminRole and userRole are both empty. This skips role checks while retaining configured scope checks. This setting requires OIDC with both roles empty. Leave false for shared or production clusters. | | server.auth.allowUnauthenticatedUsers | bool | `false` | UNSAFE: accept unauthenticated CLI/user requests as a local developer principal. Intended only for trusted local Skaffold/k3d development or a fully trusted fronting proxy. Leave false for shared or production clusters. | | server.dbUrl | string | `"sqlite:/var/openshell/openshell.db"` | Gateway database URL (used for the default SQLite backend). | | server.defaultRuntimeClassName | string | `""` | Default Kubernetes runtimeClassName for sandbox pods. Applied when a CreateSandbox request does not specify one. Empty (default) = omit the field, using the cluster's default RuntimeClass. Set to a RuntimeClass name (e.g. "kata-containers", "nvidia") to apply it to all sandboxes that don't explicitly override it. | @@ -206,14 +207,14 @@ add `ci/values-spire.yaml` to the OpenShell release values files. | server.grpcRateLimit.windowSeconds | int | `0` | gRPC rate-limit window length in seconds. Must be positive (alongside requests) to enable rate limiting; 0 (default) disables it. | | server.hostGatewayIP | string | `""` | Host gateway IP for sandbox pod hostAliases. When set, sandbox pods get hostAliases entries mapping host.docker.internal and host.openshell.internal to this IP, allowing them to reach services running on the Docker host. Auto-detected by the cluster entrypoint script. | | server.logLevel | string | `"info"` | Gateway log level. | -| server.oidc.adminRole | string | `""` | Role name for admin access. Leave empty (with userRole also empty) for authentication-only mode. Both must be set or both empty. | +| server.oidc.adminRole | string | `""` | Role name for admin access. Set with userRole for RBAC mode. Leaving both empty enables authentication-only mode only when server.auth.allowOidcAuthOnly=true. | | server.oidc.audience | string | `"openshell-cli"` | Expected audience claim for the API resource server. This should match the server's --oidc-audience, NOT the CLI client ID. | | server.oidc.caConfigMapName | string | `""` | Name of a ConfigMap containing a CA certificate bundle (key: ca.crt) for verifying the OIDC issuer's TLS certificate. Required when the issuer uses a non-public CA (e.g. OpenShift ingress, private PKI). | | server.oidc.issuer | string | `""` | OIDC issuer URL (e.g. https://keycloak.example.com/realms/openshell). | | server.oidc.jwksTtl | int | `3600` | JWKS key cache TTL in seconds. | | server.oidc.rolesClaim | string | `""` | Dot-separated path to the roles array in the JWT claims. Keycloak: "realm_access.roles", Entra ID: "roles", Okta: "groups". | | server.oidc.scopesClaim | string | `""` | Dot-separated path to the scopes array in the JWT claims. | -| server.oidc.userRole | string | `""` | Role name for standard user access. | +| server.oidc.userRole | string | `""` | Role name for standard user access. Set with adminRole for RBAC mode. | | server.providerTokenGrants.spiffe.enabled | bool | `false` | Mount the SPIFFE Workload API socket into sandbox pods for dynamic provider token grants. | | server.providerTokenGrants.spiffe.workloadApiSocketPath | string | `"/spiffe-workload-api/spire-agent.sock"` | Path to the SPIFFE Workload API socket mounted into sandbox pods. | | server.sandboxImage | string | `"ghcr.io/nvidia/openshell-community/sandboxes/base:latest"` | Default sandbox image used when requests do not specify one. | diff --git a/deploy/helm/openshell/ci/values-keycloak.yaml b/deploy/helm/openshell/ci/values-keycloak.yaml index cc6ca658bf..7afd87e88f 100644 --- a/deploy/helm/openshell/ci/values-keycloak.yaml +++ b/deploy/helm/openshell/ci/values-keycloak.yaml @@ -31,6 +31,7 @@ server: jwksTtl: 60 # Keycloak puts realm roles at realm_access.roles in the JWT. rolesClaim: "realm_access.roles" - # Leave both empty for authentication-only mode (any valid token is accepted). + # RBAC mode: both roles must be set. Leave both empty only with + # server.auth.allowOidcAuthOnly=true for authentication-only mode. adminRole: "openshell-admin" userRole: "openshell-user" diff --git a/deploy/helm/openshell/templates/_helpers.tpl b/deploy/helm/openshell/templates/_helpers.tpl index 1b4598088f..e671991a7e 100644 --- a/deploy/helm/openshell/templates/_helpers.tpl +++ b/deploy/helm/openshell/templates/_helpers.tpl @@ -198,9 +198,26 @@ Validate chart values that Helm would otherwise accept silently. {{- $workloadKind := include "openshell.workloadKind" . -}} {{- $workload := .Values.workload | default dict -}} {{- $replicaCount := int (default 1 .Values.replicaCount) -}} +{{- $oidcIssuer := default "" .Values.server.oidc.issuer -}} +{{- $oidcAdminRole := default "" .Values.server.oidc.adminRole -}} +{{- $oidcUserRole := default "" .Values.server.oidc.userRole -}} +{{- $oidcAdminRoleSet := ne $oidcAdminRole "" -}} +{{- $oidcUserRoleSet := ne $oidcUserRole "" -}} {{- if and (hasKey .Values "postgres") (kindIs "map" .Values.postgres) (hasKey .Values.postgres "enabled") -}} {{- fail "postgres.enabled was removed; the OpenShell chart no longer deploys PostgreSQL. Provision PostgreSQL separately and set server.externalDbSecret to a Secret containing a PostgreSQL URI." -}} {{- end -}} +{{- if and .Values.server.auth.allowOidcAuthOnly (not $oidcIssuer) -}} +{{- fail "server.auth.allowOidcAuthOnly=true requires server.oidc.issuer to be configured." -}} +{{- end -}} +{{- if and $oidcIssuer (ne $oidcAdminRoleSet $oidcUserRoleSet) -}} +{{- fail "server.oidc.adminRole and server.oidc.userRole must either both be set for OIDC RBAC or both be empty for authentication-only mode." -}} +{{- end -}} +{{- if and .Values.server.auth.allowOidcAuthOnly $oidcAdminRoleSet $oidcUserRoleSet -}} +{{- fail "server.auth.allowOidcAuthOnly=true is only valid when server.oidc.adminRole and server.oidc.userRole are both empty." -}} +{{- end -}} +{{- if and $oidcIssuer (not $oidcAdminRoleSet) (not .Values.server.auth.allowOidcAuthOnly) -}} +{{- fail "OIDC authentication-only mode skips role checks while retaining configured scope checks. Set server.oidc.adminRole and server.oidc.userRole for RBAC, or set server.auth.allowOidcAuthOnly=true to opt in explicitly." -}} +{{- end -}} {{- if not (or (eq $workloadKind "statefulset") (eq $workloadKind "deployment")) -}} {{- fail "workload.kind must be one of: statefulset, deployment." -}} {{- end -}} diff --git a/deploy/helm/openshell/templates/gateway-config.yaml b/deploy/helm/openshell/templates/gateway-config.yaml index 36a579250b..94541ac4a5 100644 --- a/deploy/helm/openshell/templates/gateway-config.yaml +++ b/deploy/helm/openshell/templates/gateway-config.yaml @@ -78,11 +78,16 @@ data: client_ca_path = "/etc/openshell-tls/client-ca/ca.crt" {{- end }} - {{- if .Values.server.auth.allowUnauthenticatedUsers }} + {{- if or .Values.server.auth.allowUnauthenticatedUsers .Values.server.auth.allowOidcAuthOnly }} [openshell.gateway.auth] + {{- if .Values.server.auth.allowUnauthenticatedUsers }} allow_unauthenticated_users = true {{- end }} + {{- if .Values.server.auth.allowOidcAuthOnly }} + allow_oidc_auth_only = true + {{- end }} + {{- end }} [openshell.gateway.gateway_jwt] signing_key_path = "/etc/openshell-jwt/signing.pem" @@ -100,10 +105,10 @@ data: {{- if .Values.server.oidc.rolesClaim }} roles_claim = {{ .Values.server.oidc.rolesClaim | quote }} {{- end }} - {{- if .Values.server.oidc.adminRole }} + {{- if or .Values.server.oidc.adminRole .Values.server.auth.allowOidcAuthOnly }} admin_role = {{ .Values.server.oidc.adminRole | quote }} {{- end }} - {{- if .Values.server.oidc.userRole }} + {{- if or .Values.server.oidc.userRole .Values.server.auth.allowOidcAuthOnly }} user_role = {{ .Values.server.oidc.userRole | quote }} {{- end }} {{- if .Values.server.oidc.scopesClaim }} diff --git a/deploy/helm/openshell/tests/gateway_config_test.yaml b/deploy/helm/openshell/tests/gateway_config_test.yaml index aee396c38f..82d4deec1b 100644 --- a/deploy/helm/openshell/tests/gateway_config_test.yaml +++ b/deploy/helm/openshell/tests/gateway_config_test.yaml @@ -47,6 +47,8 @@ tests: set: server.disableTls: true server.oidc.issuer: https://issuer.example.com + server.oidc.adminRole: openshell-admin + server.oidc.userRole: openshell-user server.oidc.caConfigMapName: openshell-oidc-ca asserts: - equal: @@ -277,6 +279,67 @@ tests: - failedTemplate: errorMessage: "server.grpcRateLimit.requests and server.grpcRateLimit.windowSeconds must not be negative; they map to unsigned gateway settings" + - it: fails OIDC authentication-only mode without explicit opt-in + template: templates/statefulset.yaml + set: + server.oidc.issuer: https://issuer.example.com + asserts: + - failedTemplate: + errorPattern: "OIDC authentication-only mode skips role checks while retaining configured scope checks" + + - it: fails OIDC authentication-only opt-in without OIDC + template: templates/statefulset.yaml + set: + server.auth.allowOidcAuthOnly: true + asserts: + - failedTemplate: + errorPattern: "server.auth.allowOidcAuthOnly=true requires server.oidc.issuer" + + - it: fails OIDC authentication-only opt-in with RBAC roles + template: templates/statefulset.yaml + set: + server.auth.allowOidcAuthOnly: true + server.oidc.issuer: https://issuer.example.com + server.oidc.adminRole: openshell-admin + server.oidc.userRole: openshell-user + asserts: + - failedTemplate: + errorPattern: "server.auth.allowOidcAuthOnly=true is only valid when server.oidc.adminRole and server.oidc.userRole are both empty" + + - it: fails OIDC configuration with only one role set + template: templates/statefulset.yaml + set: + server.oidc.issuer: https://issuer.example.com + server.oidc.adminRole: openshell-admin + asserts: + - failedTemplate: + errorPattern: "server.oidc.adminRole and server.oidc.userRole must either both be set" + + - it: renders OIDC RBAC roles when configured + template: templates/gateway-config.yaml + set: + server.oidc.issuer: https://issuer.example.com + server.oidc.rolesClaim: realm_access.roles + server.oidc.adminRole: openshell-admin + server.oidc.userRole: openshell-user + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: '(?ms)\[openshell\.gateway\.oidc\].*?roles_claim\s*=\s*"realm_access\.roles".*?admin_role\s*=\s*"openshell-admin".*?user_role\s*=\s*"openshell-user"' + + - it: renders explicit OIDC authentication-only mode when opted in + template: templates/gateway-config.yaml + set: + server.auth.allowOidcAuthOnly: true + server.oidc.issuer: https://issuer.example.com + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: '(?ms)\[openshell\.gateway\.auth\].*?allow_oidc_auth_only\s*=\s*true' + - matchRegex: + path: data["gateway.toml"] + pattern: '(?ms)\[openshell\.gateway\.oidc\].*?admin_role\s*=\s*"".*?user_role\s*=\s*""' + - it: uses the configured existing sandbox service account name template: templates/gateway-config.yaml set: diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index e89a234912..44220b7047 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -240,6 +240,11 @@ server: # principal. Intended only for trusted local Skaffold/k3d development or a # fully trusted fronting proxy. Leave false for shared or production clusters. allowUnauthenticatedUsers: false + # -- UNSAFE: allow OIDC authentication-only mode when adminRole and userRole + # are both empty. This skips role checks while retaining configured scope + # checks. This setting requires OIDC with both roles empty. Leave false for + # shared or production clusters. + allowOidcAuthOnly: false tls: # -- K8s secret (type kubernetes.io/tls) with tls.crt and tls.key for the server. certSecretName: openshell-server-tls @@ -295,10 +300,11 @@ server: # -- Dot-separated path to the roles array in the JWT claims. # Keycloak: "realm_access.roles", Entra ID: "roles", Okta: "groups". rolesClaim: "" - # -- Role name for admin access. Leave empty (with userRole also empty) for - # authentication-only mode. Both must be set or both empty. + # -- Role name for admin access. Set with userRole for RBAC mode. Leaving + # both empty enables authentication-only mode only when + # server.auth.allowOidcAuthOnly=true. adminRole: "" - # -- Role name for standard user access. + # -- Role name for standard user access. Set with adminRole for RBAC mode. userRole: "" # -- Dot-separated path to the scopes array in the JWT claims. scopesClaim: "" diff --git a/docs/kubernetes/access-control.mdx b/docs/kubernetes/access-control.mdx index 5409a4b11d..3e0eac8775 100644 --- a/docs/kubernetes/access-control.mdx +++ b/docs/kubernetes/access-control.mdx @@ -37,7 +37,10 @@ helm upgrade openshell \ --version \ --namespace openshell \ --set server.oidc.issuer=https://your-idp.example.com/realms/openshell \ - --set server.oidc.audience=openshell-cli + --set server.oidc.audience=openshell-cli \ + --set server.oidc.rolesClaim=realm_access.roles \ + --set server.oidc.adminRole=openshell-admin \ + --set server.oidc.userRole=openshell-user ``` The `audience` value must match the client ID configured in your identity provider for the OpenShell resource server. @@ -53,12 +56,11 @@ The `audience` value must match the client ID configured in your identity provid | `server.oidc.adminRole` | `""` | Role name that grants admin access. | | `server.oidc.userRole` | `""` | Role name that grants standard user access. | | `server.oidc.scopesClaim` | `""` | Dot-separated path to the scopes array in JWT claims. | +| `server.auth.allowOidcAuthOnly` | `false` | Explicit opt-in for OIDC authentication-only mode when both role values are empty. | ### Auth-only mode vs. RBAC mode -Leave both `adminRole` and `userRole` empty to use auth-only mode: any request with a valid JWT from the configured issuer is accepted, but no role distinction is enforced. - -Set both values to enable RBAC mode, where the gateway checks the role claim and enforces access based on the assigned role: +Set both role values to enable RBAC mode, where the gateway checks the role claim and enforces access based on the assigned role. This is the recommended mode for shared Kubernetes deployments: ```shell helm upgrade openshell \ @@ -72,7 +74,23 @@ helm upgrade openshell \ --set server.oidc.userRole=openshell-user ``` -Both `adminRole` and `userRole` must be set, or both must be empty. Setting only one is not supported. +Authentication-only mode skips the admin/user role distinction for tokens validated by the configured issuer. Configured scope checks still apply. To use it, leave both `adminRole` and `userRole` empty and explicitly opt in: + +```shell +helm upgrade openshell \ + oci://ghcr.io/nvidia/openshell/helm-chart \ + --version \ + --namespace openshell \ + --set server.oidc.issuer=https://your-idp.example.com/realms/openshell \ + --set server.oidc.audience=openshell-cli \ + --set server.auth.allowOidcAuthOnly=true +``` + +Both `adminRole` and `userRole` must be set, or both must be empty. Setting only one is not supported. Helm rejects authentication-only mode unless `server.auth.allowOidcAuthOnly=true` is set. It also rejects this opt-in when OIDC is disabled or RBAC roles are configured. + + + Before upgrading an existing OIDC deployment with both role values empty, configure both roles or set `server.auth.allowOidcAuthOnly=true`. Otherwise, Helm rejects the upgrade or the shared gateway fails to start. + ### Provider-specific rolesClaim paths diff --git a/docs/kubernetes/setup.mdx b/docs/kubernetes/setup.mdx index c2fca827f1..134d0b088b 100644 --- a/docs/kubernetes/setup.mdx +++ b/docs/kubernetes/setup.mdx @@ -157,6 +157,7 @@ The most commonly changed values are: | `server.appArmorProfile` | AppArmor profile requested for sandbox agent containers. Defaults to `Unconfined`. | | `server.disableTls` | Run the gateway over plaintext HTTP. Use only behind a trusted transport. | | `server.auth.allowUnauthenticatedUsers` | Accept user-facing calls without OIDC or mTLS credentials. Use only for trusted local development or a fully trusted access proxy. | +| `server.auth.allowOidcAuthOnly` | Allow OIDC authentication without RBAC role checks. Configured scope checks still apply. | | `server.enableLoopbackServiceHttp` | Enable local plaintext HTTP for loopback sandbox service URLs. Defaults to `true`. | | `pkiInitJob.serverDnsNames` / `certManager.serverDnsNames` | Additional gateway server DNS SANs. Wildcard SANs also enable sandbox service URLs under that domain. | | `supervisor.sideloadMethod` | How the supervisor binary is delivered into sandbox pods. Leave empty to auto-detect based on cluster version: clusters running Kubernetes 1.35 or later use `image-volume` (ImageVolume GA in 1.36); older clusters use `init-container`. Set explicitly to `image-volume` on Kubernetes 1.33 or 1.34 with the ImageVolume feature gate enabled, or to `init-container` to force the legacy path on any version. | diff --git a/docs/reference/gateway-auth.mdx b/docs/reference/gateway-auth.mdx index 94aca659ee..d4cf9fe99c 100644 --- a/docs/reference/gateway-auth.mdx +++ b/docs/reference/gateway-auth.mdx @@ -104,6 +104,8 @@ server: scopesClaim: "" ``` +For Kubernetes and other shared gateways, set both `adminRole` and `userRole` for RBAC. Authentication-only mode leaves both roles empty and skips role checks for tokens validated by the issuer. Configured scope checks still apply. This mode requires an explicit opt-in with `server.auth.allowOidcAuthOnly=true` in Helm or `allow_oidc_auth_only = true` under `[openshell.gateway.auth]` in TOML. + Register an OIDC gateway with the CLI: ```shell @@ -123,7 +125,7 @@ The connection flow: 3. The CLI connects to the gateway and attaches `authorization: Bearer ` metadata to each gRPC request. 4. The gateway validates the JWT signature, issuer, audience, expiration, and key ID against the issuer's JWKS. 5. The gateway extracts roles and optional scopes from the configured claim paths. -6. The gateway authorizes the gRPC method. Admin methods require the admin role, other authenticated methods require the user role. Admin role holders also satisfy user-role checks. +6. The gateway authorizes the gRPC method. In RBAC mode, admin methods require the admin role, other authenticated methods require the user role, and admin role holders also satisfy user-role checks. In authentication-only mode, role checks are skipped only after the deployment explicitly opts in. If `OPENSHELL_OIDC_SCOPES_CLAIM` is set, the gateway also enforces scopes. It accepts space-delimited scope strings such as `scope: "openid sandbox:read"` and JSON arrays such as `scp: ["sandbox:read"]`. Standard OIDC scopes such as `openid`, `profile`, `email`, and `offline_access` are ignored for authorization. `openshell:all` grants access to all scoped methods. diff --git a/docs/reference/gateway-config.mdx b/docs/reference/gateway-config.mdx index 56f5d15348..52223b0d69 100644 --- a/docs/reference/gateway-config.mdx +++ b/docs/reference/gateway-config.mdx @@ -136,6 +136,7 @@ ttl_secs = 3600 [openshell.gateway.auth] allow_unauthenticated_users = false +allow_oidc_auth_only = false [openshell.gateway.mtls_auth] enabled = false @@ -175,6 +176,8 @@ Local Docker, Podman, and VM gateways can also set `[openshell.gateway.mtls_auth `[openshell.gateway.auth] allow_unauthenticated_users = true` is an unsafe local-development and trusted-proxy escape hatch. It accepts user-facing CLI/API calls without OIDC or mTLS credentials while sandbox supervisors still authenticate with gateway-minted sandbox JWTs. Leave it false for shared and production gateways. +`[openshell.gateway.auth] allow_oidc_auth_only = true` permits OIDC authentication-only mode when `admin_role` and `user_role` are both empty. This skips role checks for tokens validated by the configured issuer while retaining configured scope checks. The gateway rejects this setting when OIDC is absent or RBAC roles are configured, and logs a startup warning when the mode is active. Shared gateways fail startup unless OIDC RBAC roles are configured or this flag is set explicitly. + ## Supervisor Middleware Services Register operator-run supervisor middleware services with one or more `[[openshell.supervisor.middleware]]` entries. Registration is static and operator-owned; changing it requires restarting the gateway. diff --git a/docs/security/best-practices.mdx b/docs/security/best-practices.mdx index b63883c2b8..7c484340d4 100644 --- a/docs/security/best-practices.mdx +++ b/docs/security/best-practices.mdx @@ -261,9 +261,9 @@ Gateway transport uses TLS, with client certificate checks available where the d | Aspect | Detail | |---|---| | Default | Local TLS bundles enable mTLS user authentication for single-user local gateways. Helm deployments generate mTLS certificates for transport, while sandbox supervisors authenticate API calls with gateway-minted sandbox JWTs. TLS-enabled loopback gateways also accept plaintext HTTP for sandbox service hostnames by default. | -| What you can change | Configure OIDC or a trusted access proxy for multi-user gateways, set `OPENSHELL_ENABLE_MTLS_AUTH=true` for local single-user gateways, enable `server.auth.allowUnauthenticatedUsers=true` only for trusted local Kubernetes development or a fully trusted proxy, disable TLS only for trusted reverse-proxy setups, or disable loopback service HTTP with `--enable-loopback-service-http=false`. | -| Risk if relaxed | Disabling TLS removes transport-level protection entirely. Allowing unauthenticated users removes the gateway user-auth boundary and must not be exposed to shared or public networks. Treating transport certificates as shared user identity in Kubernetes would collapse user and sandbox trust boundaries. Loopback service HTTP is local-only and rejects cross-origin browser requests, but any local process can still reach exposed service URLs directly. | -| Recommendation | Use local mTLS user authentication only for single-user Docker, Podman, and VM gateways. Use OIDC or a trusted access proxy for Kubernetes and shared deployments. | +| What you can change | Configure OIDC or a trusted access proxy for multi-user gateways, set `OPENSHELL_ENABLE_MTLS_AUTH=true` for local single-user gateways, enable `server.auth.allowUnauthenticatedUsers=true` only for trusted local Kubernetes development or a fully trusted proxy, set `server.auth.allowOidcAuthOnly=true` only when issuer-validated tokens should bypass RBAC role checks, disable TLS only for trusted reverse-proxy setups, or disable loopback service HTTP with `--enable-loopback-service-http=false`. | +| Risk if relaxed | Disabling TLS removes transport-level protection entirely. Allowing unauthenticated users removes the gateway user-auth boundary and must not be exposed to shared or public networks. OIDC authentication-only mode validates tokens but skips RBAC role checks; configured scope checks still apply. Treating transport certificates as shared user identity in Kubernetes would collapse user and sandbox trust boundaries. Loopback service HTTP is local-only and rejects cross-origin browser requests, but any local process can still reach exposed service URLs directly. | +| Recommendation | Use local mTLS user authentication only for single-user Docker, Podman, and VM gateways. Use OIDC RBAC or a trusted access proxy for Kubernetes and shared deployments. | ### SSH Tunnel Authentication