From 5dff6def6d1151967a7890b5981df78d3f8e7062 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Mon, 26 Oct 2026 21:07:09 -0700 Subject: [PATCH 01/15] feat(auth): authenticate gateway-mediated application requests Require configured gateway authentication for application HTTP requests and WebSocket upgrades, with or without the independent app listener. Add browser sessions, application credential separation, shared revocation, request authorization, documentation, and browser coverage. Closes #4722 Signed-off-by: Taylor Mutch --- crates/openshell-credential-issuer/README.md | 3 +- .../openshell-credential-issuer/src/owner.rs | 20 + crates/openshell-server/README.md | 33 + crates/openshell-server/src/auth/http.rs | 14 + crates/openshell-server/src/auth/mod.rs | 2 + crates/openshell-server/src/auth/oidc.rs | 8 +- .../src/auth/service_access.rs | 466 ++++++ .../src/auth/service_session.rs | 1372 +++++++++++++++++ crates/openshell-server/src/credentials.rs | 68 + crates/openshell-server/src/lib.rs | 110 +- crates/openshell-server/src/multiplex.rs | 17 +- .../openshell-server/src/service_routing.rs | 522 ++++++- .../tests/browser-service-auth.cjs | 82 + .../openshell-supervisor/src/app_listener.rs | 28 +- docs/how-it-works/gateways/authentication.mdx | 105 +- docs/how-it-works/gateways/configuration.mdx | 11 + docs/how-it-works/sandboxes/overview.mdx | 12 +- rfc/0017-sandbox-service-exposure/README.md | 6 +- skills/debug-openshell-cluster/SKILL.md | 17 + 19 files changed, 2867 insertions(+), 29 deletions(-) create mode 100644 crates/openshell-server/src/auth/service_access.rs create mode 100644 crates/openshell-server/src/auth/service_session.rs create mode 100644 crates/openshell-server/tests/browser-service-auth.cjs diff --git a/crates/openshell-credential-issuer/README.md b/crates/openshell-credential-issuer/README.md index 9e5b972085..580952c60f 100644 --- a/crates/openshell-credential-issuer/README.md +++ b/crates/openshell-credential-issuer/README.md @@ -24,9 +24,10 @@ This is the internal-refactoring increment of RFC phase 2, not remote readiness. ## Owners and compatibility -`SecretOwner` scopes each operation to a workspace and one of three kinds: +`SecretOwner` scopes each operation to a workspace and one of four kinds: - `Provider`: the existing provider UUID and name. +- `ApplicationSession`: the gateway browser session storage identity (`service-session-`), using the existing `gateway-service-session` driver scope. - `Sandbox`: the sandbox UUID for its SSH host identity. - `SupervisorInstance`: the sandbox UUID owning a launch-material assignment, not the shared supervisor route or host. diff --git a/crates/openshell-credential-issuer/src/owner.rs b/crates/openshell-credential-issuer/src/owner.rs index 259d105f7a..164ab880b8 100644 --- a/crates/openshell-credential-issuer/src/owner.rs +++ b/crates/openshell-credential-issuer/src/owner.rs @@ -20,6 +20,10 @@ pub enum SecretOwnerKind<'a> { Sandbox { id: &'a str, }, + /// Gateway-owned browser application session storage identity. + ApplicationSession { + id: &'a str, + }, /// Launch material is owned by a sandbox assignment, not the host/route. SupervisorInstance { sandbox_id: &'a str, @@ -65,9 +69,20 @@ impl<'a> SecretOwner<'a> { } } + /// `id` is the existing `service-session-` storage identity. + pub fn application_session(workspace: &'a str, id: &'a str) -> Self { + Self { + workspace, + kind: SecretOwnerKind::ApplicationSession { id }, + } + } + pub(crate) fn legacy_scope(self) -> LegacyScope<'a> { let (provider, id) = match self.kind { SecretOwnerKind::Provider { id, name } => (Cow::Borrowed(name), id), + SecretOwnerKind::ApplicationSession { id } => { + (Cow::Borrowed("gateway-service-session"), id) + } SecretOwnerKind::Sandbox { id } => (Cow::Owned(format!("sandbox-ssh-{id}")), id), SecretOwnerKind::SupervisorInstance { sandbox_id } => ( Cow::Owned(format!("sandbox-instance-{sandbox_id}")), @@ -97,6 +112,11 @@ mod tests { "provider-name", "provider-id", ), + ( + SecretOwner::application_session("workspace-a", "service-session-session-id"), + "gateway-service-session", + "service-session-session-id", + ), ( SecretOwner::sandbox("workspace-a", "sandbox-id"), "sandbox-ssh-sandbox-id", diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index 7789a767ae..3561a234f5 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -474,6 +474,39 @@ must independently honor the advertised lease expiry. Reconnect and relist on stream termination; revisions are opaque equality tokens, not resumable cursors or an ordering across gateway replicas. +## Gateway application authentication + +Gateway-mediated application HTTP requests and WebSocket upgrades authenticate +through the gateway chain or verified TLS client identity before endpoint lookup, +independently of app-listener enablement. User access requires TCP-forwarding +role/scope policy (`sandbox:write` when enforced) and current workspace membership; +operators retain their platform grant. Internal principals are rejected. Only +explicit local-development unauthenticated access bypasses this gate. + +`/auth/services` hosts browser login on the control-plane origin. The application +origin receives a single-use bootstrap code bound to a browser login nonce, then +a distinct host-only, Secure/HttpOnly session cookie. Shared metadata contains +only credential-driver handles and hashes; the configured credential driver +stores the access token. Login codes expire after two minutes, sessions after +at most ten minutes or token expiry. Every request revalidates the token and +workspace authorization. Session deletion, credential revocation, and redemption +CAS use the shared database. Expired metadata cleanup and admission are bounded. +The application path consumes standard gateway bearer headers, or authenticates +through a separate `X-OpenShell-Authorization`, browser session, or mTLS identity +while preserving application bearer passthrough and cookies. Gateway headers and +reserved cookies never reach the workload, and workloads cannot set reserved +browser auth cookies. Browser ambient credentials require origin checks for +unsafe methods and WebSocket upgrades. Direct supervisor ingress delegates +application authentication to its ingress provider. + +The optional real-Chrome login test uses an isolated profile and local test +credentials. Run it with `OPENSHELL_BROWSER_E2E_CHROME` pointing to Chrome: + +```shell +OPENSHELL_BROWSER_E2E_CHROME='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' \ + cargo test -p openshell-server --lib gateway_service_auth_real_browser_cross_site_login -- --ignored +``` + ## Application URL publication See [Supervisor application listener](../../docs/how-it-works/gateways/configuration.mdx#supervisor-application-listener) diff --git a/crates/openshell-server/src/auth/http.rs b/crates/openshell-server/src/auth/http.rs index 90dae5046f..1ec91db2ae 100644 --- a/crates/openshell-server/src/auth/http.rs +++ b/crates/openshell-server/src/auth/http.rs @@ -91,6 +91,10 @@ fn sanitize_callback_host(raw: &Option) -> (String, String) { /// Create the auth router. pub fn router(state: Arc) -> Router { Router::new() + .route( + "/auth/services", + get(service_browser_login).post(service_browser_login), + ) .route("/auth/connect", get(auth_connect)) .route("/auth/oidc-config", get(oidc_config_handler)) .route("/.well-known/jwks.json", get(gateway_jwks_handler)) @@ -101,6 +105,16 @@ pub fn router(state: Arc) -> Router { .with_state(state) } +async fn service_browser_login( + State(state): State>, + req: axum::extract::Request, +) -> axum::response::Response { + match super::service_session::control(&state, req).await { + Ok(response) => response, + Err(error) => super::service_session::error(&error), + } +} + /// Publish OIDC-shaped discovery metadata for extension services. /// /// This lets an extension be configured with only the trusted gateway URL: diff --git a/crates/openshell-server/src/auth/mod.rs b/crates/openshell-server/src/auth/mod.rs index f1800d5044..f4ae2d08a9 100644 --- a/crates/openshell-server/src/auth/mod.rs +++ b/crates/openshell-server/src/auth/mod.rs @@ -25,6 +25,8 @@ pub mod principal; pub mod sandbox_jwt; pub mod sandbox_methods; pub mod sandbox_session; +pub mod service_access; +pub mod service_session; pub mod supervisor_token; pub mod workspace_authz; diff --git a/crates/openshell-server/src/auth/oidc.rs b/crates/openshell-server/src/auth/oidc.rs index c1b10a6255..92fa899c97 100644 --- a/crates/openshell-server/src/auth/oidc.rs +++ b/crates/openshell-server/src/auth/oidc.rs @@ -1002,7 +1002,7 @@ impl Authenticator for OidcAuthenticator { } #[cfg(test)] -mod tests { +pub mod tests { use super::*; fn transport_test_config(issuer: impl Into) -> OidcConfig { @@ -1583,7 +1583,7 @@ mod tests { } /// Sign `claims` with the test key, tagging the header with `kid`. - fn mint_rs256(claims: &serde_json::Value, kid: &str) -> String { + pub fn mint_rs256(claims: &serde_json::Value, kid: &str) -> String { crate::install_jsonwebtoken_crypto_provider(); let mut header = jsonwebtoken::Header::new(Algorithm::RS256); @@ -1593,7 +1593,7 @@ mod tests { openshell_crypto::jwt::encode(&header, claims, &key).expect("sign RS256 token") } - fn claims_for(issuer: &str, audience: &str, exp: i64) -> serde_json::Value { + pub fn claims_for(issuer: &str, audience: &str, exp: i64) -> serde_json::Value { serde_json::json!({ "sub": "user-42", "preferred_username": "ada", @@ -1607,7 +1607,7 @@ mod tests { /// Serve an OIDC discovery document and a JWKS carrying the test key, then /// build a cache against them the same way production does. - async fn cache_with_mock_issuer(server: &wiremock::MockServer) -> JwksCache { + pub async fn cache_with_mock_issuer(server: &wiremock::MockServer) -> JwksCache { use wiremock::matchers::{method, path}; use wiremock::{Mock, ResponseTemplate}; diff --git a/crates/openshell-server/src/auth/service_access.rs b/crates/openshell-server/src/auth/service_access.rs new file mode 100644 index 0000000000..76236d8c1e --- /dev/null +++ b/crates/openshell-server/src/auth/service_access.rs @@ -0,0 +1,466 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Authentication for gateway-mediated application traffic. Direct supervisor +//! ingress has its own ingress-provider authentication contract. + +use super::{ + audit::{self, AuthzDenial, ConnectionSource, RequestOrigin}, + authenticator::{AuthFailureReason, AuthMechanism, Authentication, AuthenticatorChain}, + authz::AuthzPolicy, + identity::{Identity, IdentityProvider}, + principal::{OperatorPrincipal, Principal, UserPrincipal}, + workspace_authz::{MinWorkspaceRole, authorize_workspace}, +}; +use crate::ServerState; +use http::{HeaderMap, header}; +use tonic::Status; + +const APPLICATION_PATH: &str = "/openshell/application"; +// Application requests can perform arbitrary operations, just like a TCP +// forward. Reuse that operation's global role and sandbox:write scope policy. +const ACCESS_POLICY: &str = "/openshell.v1.OpenShell/ForwardTcp"; + +/// Only populated from a verified TLS connection, never forwarded HTTP headers. +#[derive(Clone, Default)] +pub struct ServicePeer { + pub secure: bool, + pub identity: Option, + pub certificate_sha256: Option, + pub source: Option, +} + +pub async fn authorize( + state: &ServerState, + headers: &HeaderMap, + peer: &ServicePeer, + workspace: &str, +) -> Result { + audit::with_request( + APPLICATION_PATH.to_string(), + RequestOrigin::new(peer.source, headers), + authorize_with_chain( + state, + headers, + peer, + workspace, + crate::multiplex::build_authenticator_chain(state), + ), + ) + .await +} + +async fn authorize_with_chain( + state: &ServerState, + headers: &HeaderMap, + peer: &ServicePeer, + workspace: &str, + chain: Option, +) -> Result { + let origin = RequestOrigin::new(peer.source, headers); + let principal = authenticate(state, headers, peer, chain).await.map_err( + |(status, mechanism, reason)| { + audit::emit_authentication_failure(APPLICATION_PATH, &origin, mechanism, reason); + status + }, + )?; + if (state.config.mtls_auth.enabled || state.config.mtls_auth.operator_enabled) + && let Some(fingerprint) = &peer.certificate_sha256 + { + super::service_session::check_certificate(state, fingerprint).await?; + } + if let Some(token) = super::authenticator::bearer_credential(headers) { + super::service_session::check_token(state, token).await?; + } + audit::emit_logon( + &state.logons, + APPLICATION_PATH, + &origin, + &principal, + headers, + peer.certificate_sha256.as_deref(), + ); + match &principal { + Principal::User(user) => { + if let Some(oidc) = &state.config.oidc { + let policy = AuthzPolicy { + admin_role: oidc.admin_role.clone(), + user_role: oidc.user_role.clone(), + scopes_enabled: !oidc.scopes_claim.is_empty(), + }; + if let Err(denial) = policy.check(&user.identity, ACCESS_POLICY) { + audit::emit_authorization_denial(&principal, denial.denial); + return Err(denial.status); + } + } + } + Principal::Operator(_) => {} + _ => { + return Err(audit::deny( + &principal, + AuthzDenial::MethodNotPermitted, + "application access requires a user identity", + )); + } + } + authorize_workspace( + &state.store, + &state.admin_role, + &principal, + workspace, + MinWorkspaceRole::User, + ) + .await?; + Ok(principal) +} + +type AuthenticationError = (Status, Option, AuthFailureReason); + +async fn authenticate( + state: &ServerState, + headers: &HeaderMap, + peer: &ServicePeer, + chain: Option, +) -> Result { + let reject = |message, reason| (Status::unauthenticated(message), None, reason); + let has_authorization = headers.contains_key(header::AUTHORIZATION); + if headers + .get_all(header::AUTHORIZATION) + .iter() + .any(|value| value.as_bytes().len() > 16384) + { + return Err(reject( + "authorization header exceeds limit", + AuthFailureReason::MalformedCredential, + )); + } + // Reject ambiguous credentials before any authenticator can select one. + if headers.get_all(header::AUTHORIZATION).iter().count() > 1 { + return Err(reject( + "ambiguous authorization headers", + AuthFailureReason::ConflictingCredentials, + )); + } + if state.config.mtls_auth.operator_enabled + && let Some(identity) = peer.identity.as_ref().filter(|identity| { + identity.provider == IdentityProvider::Mtls + && identity.roles.iter().any(|role| role == "operator") + }) + && let Some(certificate_sha256) = &peer.certificate_sha256 + { + if has_authorization { + return Err(reject( + "operator certificates must not be combined with authorization headers", + AuthFailureReason::ConflictingCredentials, + )); + } + return Ok(Principal::Operator(OperatorPrincipal { + identity: identity.clone(), + certificate_sha256: certificate_sha256.clone(), + })); + } + if let Some(chain) = chain { + match chain.authenticate(headers, APPLICATION_PATH).await { + Ok(Authentication::Accepted(principal)) => return Ok(principal), + Err(rejection) => { + return Err(( + rejection.status, + Some(rejection.mechanism), + rejection.reason, + )); + } + Ok(Authentication::Declined(decline)) => { + return Err(( + Status::unauthenticated("invalid application access credential"), + Some(decline.mechanism), + decline.reason, + )); + } + Ok(Authentication::NotApplicable) => {} + } + } + if has_authorization { + return Err(reject( + "invalid authorization header", + AuthFailureReason::MalformedCredential, + )); + } + if state.config.mtls_auth.enabled { + if let Some(identity) = &peer.identity { + return Ok(Principal::User(UserPrincipal { + identity: identity.clone(), + })); + } + // Match the configured gateway's explicit local-development bypass. + if !state.config.auth.allow_unauthenticated_users { + return Err(reject( + "missing client certificate", + AuthFailureReason::MissingCredential, + )); + } + } + if state.config.auth.allow_unauthenticated_users { + return Ok(crate::multiplex::unauthenticated_dev_user_principal()); + } + Err(reject( + "authentication required", + AuthFailureReason::MissingCredential, + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::auth::authenticator::{AuthRejection, Authenticator}; + use crate::grpc::test_support::test_server_state; + use async_trait::async_trait; + use openshell_core::proto::{WorkspaceMember, WorkspaceRole, datamodel::v1::ObjectMeta}; + use std::sync::Arc; + + #[derive(Clone)] + struct TestAuth(Result); + + #[async_trait] + impl Authenticator for TestAuth { + async fn authenticate( + &self, + _headers: &HeaderMap, + path: &str, + ) -> Result { + assert_eq!(path, APPLICATION_PATH); + self.0.clone() + } + } + + fn chain(outcome: Result) -> AuthenticatorChain { + AuthenticatorChain::new(vec![Arc::new(TestAuth(outcome))]) + } + + fn identity() -> Identity { + Identity { + subject: "alice".into(), + display_name: None, + roles: vec!["openshell-user".into()], + scopes: vec!["sandbox:write".into()], + provider: IdentityProvider::Oidc, + } + } + + async fn state() -> Arc { + let mut state = test_server_state().await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.auth.allow_unauthenticated_users = false; + inner.admin_role = "openshell-admin".into(); + inner.config.oidc = Some(serde_json::from_value(serde_json::json!({ + "issuer": "https://issuer.example.com", "audience": "openshell", "scopes_claim": "scope" + })).unwrap()); + state + } + + async fn member(state: &ServerState) { + state + .store + .put_message(&WorkspaceMember { + metadata: Some(ObjectMeta { + id: uuid::Uuid::new_v4().to_string(), + name: "alice".into(), + workspace: "default".into(), + ..Default::default() + }), + principal_subject: "alice".into(), + role: WorkspaceRole::User.into(), + }) + .await + .unwrap(); + } + + async fn access( + state: &ServerState, + identity: Identity, + workspace: &str, + ) -> Result { + authorize_with_chain( + state, + &HeaderMap::new(), + &ServicePeer::default(), + workspace, + Some(chain(Ok(Authentication::Accepted(Principal::User( + UserPrincipal { identity }, + ))))), + ) + .await + } + + #[tokio::test] + async fn service_access_enforces_workspace_role_and_scope() { + let state = state().await; + assert_eq!( + access(&state, identity(), "default") + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + member(&state).await; + access(&state, identity(), "default").await.unwrap(); + assert_eq!( + access(&state, identity(), "other") + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + let mut user = identity(); + user.scopes = vec!["sandbox:read".into()]; + assert_eq!( + access(&state, user, "default").await.unwrap_err().code(), + tonic::Code::PermissionDenied + ); + let mut user = identity(); + user.roles.clear(); + assert_eq!( + access(&state, user, "default").await.unwrap_err().code(), + tonic::Code::PermissionDenied + ); + } + + #[tokio::test] + async fn service_access_rejects_internal_principals_even_with_workspace_access() { + let state = state().await; + for principal in [ + crate::auth::principal::test_support::sandbox("sandbox-id"), + Principal::Peer(crate::auth::principal::PeerPrincipal { + replica_id: "peer".into(), + pod_uid: "uid".into(), + }), + Principal::Anonymous, + ] { + let error = authorize_with_chain( + &state, + &HeaderMap::new(), + &ServicePeer::default(), + "default", + Some(chain(Ok(Authentication::Accepted(principal)))), + ) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + } + } + + #[tokio::test] + async fn service_access_rejects_missing_invalid_expired_and_duplicate_credentials() { + let mut state = state().await; + let peer = ServicePeer::default(); + assert_eq!( + authorize_with_chain( + &state, + &HeaderMap::new(), + &peer, + "default", + Some(chain(Ok(Authentication::NotApplicable))) + ) + .await + .unwrap_err() + .code(), + tonic::Code::Unauthenticated + ); + // Invalid credentials never become a local-development identity. + Arc::get_mut(&mut state) + .unwrap() + .config + .auth + .allow_unauthenticated_users = true; + for reason in [ + AuthFailureReason::InvalidCredential, + AuthFailureReason::ExpiredCredential, + ] { + assert_eq!( + authorize_with_chain( + &state, + &HeaderMap::new(), + &peer, + "default", + Some(chain(Err(AuthRejection::new( + AuthMechanism::Oidc, + reason, + Status::unauthenticated("rejected") + )))) + ) + .await + .unwrap_err() + .code(), + tonic::Code::Unauthenticated + ); + } + let mut headers = HeaderMap::new(); + headers.append(header::AUTHORIZATION, "Bearer first".parse().unwrap()); + headers.append(header::AUTHORIZATION, "Bearer second".parse().unwrap()); + assert_eq!( + authorize_with_chain( + &state, + &headers, + &peer, + "default", + Some(chain(Ok(Authentication::Accepted(Principal::User( + UserPrincipal { + identity: identity() + } + ))))) + ) + .await + .unwrap_err() + .code(), + tonic::Code::Unauthenticated + ); + } + + #[tokio::test] + async fn service_access_uses_only_verified_mtls_identity_and_operator_fingerprint() { + let mut state = state().await; + Arc::get_mut(&mut state).unwrap().config.mtls_auth.enabled = true; + member(&state).await; + let mut user = identity(); + user.provider = IdentityProvider::Mtls; + let mut headers = HeaderMap::new(); + headers.insert("x-forwarded-client-cert", "alice".parse().unwrap()); + assert!( + authorize_with_chain(&state, &headers, &ServicePeer::default(), "default", None) + .await + .is_err() + ); + let peer = ServicePeer { + identity: Some(user.clone()), + ..Default::default() + }; + authorize_with_chain(&state, &headers, &peer, "default", None) + .await + .unwrap(); + user.roles = vec!["operator".into()]; + Arc::get_mut(&mut state) + .unwrap() + .config + .mtls_auth + .operator_enabled = true; + let peer = ServicePeer { + identity: Some(user), + certificate_sha256: Some("verified-fingerprint".into()), + source: None, + secure: true, + }; + assert!(matches!( + authorize_with_chain(&state, &HeaderMap::new(), &peer, "other", None) + .await + .unwrap(), + Principal::Operator(_) + )); + headers.insert(header::AUTHORIZATION, "Bearer user".parse().unwrap()); + assert_eq!( + authorize_with_chain(&state, &headers, &peer, "other", None) + .await + .unwrap_err() + .code(), + tonic::Code::Unauthenticated + ); + } +} diff --git a/crates/openshell-server/src/auth/service_session.rs b/crates/openshell-server/src/auth/service_session.rs new file mode 100644 index 0000000000..5785a0db8e --- /dev/null +++ b/crates/openshell-server/src/auth/service_session.rs @@ -0,0 +1,1372 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Browser login happens on the control-plane origin. Only a single-use, +//! host-bound code reaches the application origin. Session secrets live in the +//! configured credential driver; the shared store contains non-secret metadata. + +use super::{ + principal::Principal, + service_access::{self, ServicePeer}, +}; +use crate::{ + ServerState, + persistence::{ObjectRecord, WriteCondition}, +}; +use axum::{ + body::{Body, to_bytes}, + response::{IntoResponse, Response}, +}; +use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; +use http::{HeaderMap, HeaderValue, Method, Request, StatusCode, header}; +use openshell_core::proto::CredentialHandle; +use prost::Message; +use serde::{Deserialize, Serialize}; +use tonic::Status; + +pub const PREFIX: &str = "/.openshell/service-auth"; +pub const CONTROL: &str = "/auth/services"; +pub const COOKIE: &str = "__Host-openshell-service-session"; +pub const GATEWAY_AUTH: &str = "x-openshell-authorization"; +const LOGIN_COOKIE: &str = "__Host-openshell-service-login"; +const SESSION: &str = "gateway_application_session"; +const REVOKED: &str = "gateway_application_revocation"; +const REVOCATION_SCOPE: &str = "__gateway_application_auth"; + +#[derive(Serialize, Deserialize)] +struct Session { + host: String, + expires: u64, + pending_until: u64, + login_state: String, + handle: String, + credential_id: String, + cookie_key: String, + redeemed: bool, + revoked: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Login { + service_origin: String, + state: String, +} + +fn now() -> u64 { + openshell_core::time::now_ms().max(0).cast_unsigned() / 1000 +} +fn internal() -> Status { + Status::unavailable("application authentication unavailable") +} +fn digest(value: &str) -> Result { + openshell_crypto::sha256(value.as_bytes()) + .map(|hash| URL_SAFE_NO_PAD.encode(hash)) + .map_err(|_| internal()) +} +fn random() -> Result { + openshell_crypto::random_bytes::<32>() + .map(|bytes| URL_SAFE_NO_PAD.encode(bytes)) + .map_err(|_| internal()) +} +fn session(record: &ObjectRecord) -> Result { + serde_json::from_slice(&record.payload).map_err(|_| internal()) +} +fn credential_handle(value: &Session) -> Result { + CredentialHandle::decode( + URL_SAFE_NO_PAD + .decode(&value.handle) + .map_err(|_| internal())? + .as_slice(), + ) + .map_err(|_| internal()) +} + +// Parsing only, after the configured authenticator verifies the credential. +// Expiration is also checked here without the JWT library's clock-skew leeway. +fn token_expiry(token: &str) -> Result { + let payload = token + .split('.') + .nth(1) + .ok_or_else(|| Status::unauthenticated("invalid token"))?; + let bytes = URL_SAFE_NO_PAD + .decode(payload) + .map_err(|_| Status::unauthenticated("invalid token"))?; + let value: serde_json::Value = + serde_json::from_slice(&bytes).map_err(|_| Status::unauthenticated("invalid token"))?; + value + .get("exp") + .and_then(serde_json::Value::as_u64) + .ok_or_else(|| Status::unauthenticated("token expiration required")) +} + +pub async fn check_token(state: &ServerState, token: &str) -> Result<(), Status> { + if token.len() > 16384 || token_expiry(token)? <= now() { + return Err(Status::unauthenticated("expired or invalid credential")); + } + if state + .store + .get(REVOKED, &digest(token)?) + .await + .map_err(|_| internal())? + .is_some() + { + return Err(Status::unauthenticated( + "revoked application access credential", + )); + } + Ok(()) +} + +pub async fn check_certificate(state: &ServerState, fingerprint: &str) -> Result<(), Status> { + if state + .store + .get(REVOKED, &format!("mtls-{fingerprint}")) + .await + .map_err(|_| internal())? + .is_some() + { + return Err(Status::unauthenticated( + "revoked application client certificate", + )); + } + Ok(()) +} + +fn cookie(headers: &HeaderMap, wanted: &str) -> Result, Status> { + let mut found = None; + for value in headers.get_all(header::COOKIE) { + for item in value + .to_str() + .map_err(|_| Status::unauthenticated("invalid cookie"))? + .split(';') + { + if let Some((name, value)) = item.trim().split_once('=') + && name == wanted + { + if found.is_some() || value.len() != 43 { + return Err(Status::unauthenticated( + "ambiguous or invalid session cookie", + )); + } + found = Some(value.to_string()); + } + } + } + Ok(found) +} + +fn origin(value: &str) -> Result { + let url = url::Url::parse(value).map_err(|_| Status::invalid_argument("invalid origin"))?; + if url.scheme() != "https" + || url.host_str().is_none() + || !url.username().is_empty() + || url.password().is_some() + || url.path() != "/" + || url.query().is_some() + || url.fragment().is_some() + { + return Err(Status::invalid_argument("HTTPS origin required")); + } + Ok(url) +} +fn request_origin(req: &Request) -> Result { + origin(&format!( + "https://{}", + crate::service_routing::request_host(req) + .ok_or_else(|| Status::invalid_argument("missing host"))? + )) +} +fn secure(req: &Request) -> Result<(), Status> { + if req + .extensions() + .get::() + .is_some_and(|p| p.secure) + { + Ok(()) + } else { + Err(Status::permission_denied( + "browser authentication requires gateway HTTPS", + )) + } +} +fn browser_origin(req: &Request, required: bool) -> Result<(), Status> { + if req + .headers() + .get("sec-fetch-site") + .is_some_and(|v| v != "same-origin" && v != "none") + { + return Err(Status::permission_denied( + "cross-origin application request", + )); + } + match req.headers().get(header::ORIGIN) { + Some(value) + if value + .to_str() + .ok() + .and_then(|s| origin(s).ok()) + .is_some_and(|u| { + request_origin(req).is_ok_and(|ours| ours.origin() == u.origin()) + }) => + { + Ok(()) + } + None if !required => Ok(()), + _ => Err(Status::permission_denied("same-origin request required")), + } +} +fn ambient_request(req: &Request) -> Result<(), Status> { + browser_origin( + req, + !matches!(*req.method(), Method::GET | Method::HEAD) + || req.headers().contains_key(header::UPGRADE), + ) +} + +async fn active_token( + state: &ServerState, + host: &str, + workspace: &str, + value: &str, +) -> Result { + let key = digest(value)?; + let record = state + .store + .get(SESSION, &key) + .await + .map_err(|_| internal())? + .ok_or_else(|| Status::unauthenticated("session expired or revoked"))?; + let session = session(&record)?; + if !session.redeemed + || session.cookie_key != key + || session.revoked + || session.host != host + || record.workspace != workspace + || session.expires <= now() + { + return Err(Status::unauthenticated("session expired or wrong host")); + } + state + .credentials + .resolve_application_token( + workspace, + &session.credential_id, + credential_handle(&session)?, + ) + .await +} + +pub async fn authorize_request( + state: &ServerState, + req: &mut Request, + workspace: &str, +) -> Result, Status> { + let peer = req + .extensions() + .get::() + .cloned() + .unwrap_or_default(); + let session = cookie(req.headers(), COOKIE)?; + let explicit = req.headers().get(GATEWAY_AUTH).cloned(); + if req.headers().get_all(GATEWAY_AUTH).iter().count() > 1 + || (explicit.is_some() && session.is_some()) + { + return Err(Status::unauthenticated("ambiguous gateway credentials")); + } + let mut headers = req.headers().clone(); + let mut consumed = false; + let token = if let Some(value) = session { + secure(req)?; + ambient_request(req)?; + let host = request_origin(req)?.origin().ascii_serialization(); + let token = active_token(state, &host, workspace, &value).await?; + headers.insert( + header::AUTHORIZATION, + HeaderValue::from_str(&format!("Bearer {token}")).map_err(|_| internal())?, + ); + Some(token) + } else if let Some(value) = explicit { + headers.insert(header::AUTHORIZATION, value); + super::authenticator::bearer_credential(&headers).map(str::to_string) + } else if peer.identity.is_some() + && (state.config.mtls_auth.enabled || state.config.mtls_auth.operator_enabled) + { + ambient_request(req)?; + headers.remove(header::AUTHORIZATION); + None + } else if state.config.auth.allow_unauthenticated_users + && state.config.oidc.is_none() + && !state.config.mtls_auth.enabled + { + // Explicit local development has no gateway user bearer in this header. + headers.remove(header::AUTHORIZATION); + None + } else { + consumed = true; + super::authenticator::bearer_credential(&headers).map(str::to_string) + }; + service_access::authorize(state, &headers, &peer, workspace).await?; + if consumed + || token.as_deref().is_some_and(|gateway| { + super::authenticator::bearer_credential(req.headers()) == Some(gateway) + }) + { + req.headers_mut().remove(header::AUTHORIZATION); + } + Ok(token) +} + +async fn cleanup(state: &ServerState, workspace: &str) -> Result<(), Status> { + for record in state + .store + .list(SESSION, workspace, 1024, 0) + .await + .map_err(|_| internal())? + { + let value = session(&record)?; + if value.revoked + || value.expires <= now() + || !value.redeemed && value.pending_until <= now() + { + state + .credentials + .delete_application_token( + workspace, + &value.credential_id, + credential_handle(&value)?, + ) + .await?; + state + .store + .delete(SESSION, &record.id) + .await + .map_err(|_| internal())?; + } + } + for record in state + .store + .list(REVOKED, REVOCATION_SCOPE, 1024, 0) + .await + .map_err(|_| internal())? + { + if serde_json::from_slice::(&record.payload).map_err(|_| internal())? <= now() { + state + .store + .delete(REVOKED, &record.id) + .await + .map_err(|_| internal())?; + } + } + Ok(()) +} + +async fn service_origin(state: &ServerState, value: &str) -> Result<(url::Url, String), Status> { + let origin = origin(value)?; + let target = + crate::service_routing::resolve_service_host(state, origin.host_str().unwrap_or_default()) + .await + .ok_or_else(|| Status::invalid_argument("unknown service origin"))?; + Ok((origin, target.workspace)) +} +fn parameters(req: &Request) -> Result, Status> { + let mut params = std::collections::HashMap::new(); + for (key, value) in + url::form_urlencoded::parse(req.uri().query().unwrap_or_default().as_bytes()) + { + if params + .insert(key.into_owned(), value.into_owned()) + .is_some() + { + return Err(Status::invalid_argument("duplicate parameter")); + } + } + Ok(params) +} +fn redirect(url: &url::Url) -> Result { + let mut response = StatusCode::SEE_OTHER.into_response(); + response.headers_mut().insert( + header::LOCATION, + HeaderValue::from_str(url.as_str()).map_err(|_| internal())?, + ); + Ok(no_cache(response)) +} + +pub async fn control(state: &ServerState, mut req: Request) -> Result { + secure(&req)?; + let control_origin = request_origin(&req)?; + if req.method() == Method::GET { + let params = parameters(&req)?; + let (mut target, _) = service_origin( + state, + params.get("service_origin").map_or("", String::as_str), + ) + .await?; + let Some(login_state) = params.get("state") else { + target.set_path(&format!("{PREFIX}/start")); + target.query_pairs_mut().append_pair( + "login_origin", + &control_origin.origin().ascii_serialization(), + ); + return redirect(&target); + }; + if login_state.len() != 43 { + return Err(Status::invalid_argument("invalid login state")); + } + let nonce = random()?; + let body = serde_json::to_string(&LoginBody { + service_origin: target.origin().ascii_serialization(), + state: login_state.clone(), + }) + .map_err(|_| internal())? + .replace('<', "\\u003c"); + let html = format!( + r#"OpenShell service sign in

Sign in to a sandbox service

Use a gateway access token from your configured identity provider. The service receives only a host-bound browser session.

"# + ); + let mut response = html.into_response(); + response.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/html; charset=utf-8"), + ); + response.headers_mut().insert(header::CONTENT_SECURITY_POLICY, HeaderValue::from_str(&format!("default-src 'none'; script-src 'nonce-{nonce}'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'")).map_err(|_| internal())?); + return Ok(no_cache(response)); + } + browser_origin(&req, true)?; + let peer = req + .extensions() + .get::() + .cloned() + .unwrap_or_default(); + let bytes = to_bytes(std::mem::replace(req.body_mut(), Body::empty()), 4096) + .await + .map_err(|_| Status::invalid_argument("invalid login request"))?; + let login: Login = serde_json::from_slice(&bytes) + .map_err(|_| Status::invalid_argument("invalid login request"))?; + let (mut target, workspace) = service_origin(state, &login.service_origin).await?; + if login.state.len() != 43 { + return Err(Status::invalid_argument("invalid login state")); + } + let principal = service_access::authorize(state, req.headers(), &peer, &workspace).await?; + if !matches!(principal, Principal::User(ref user) if user.identity.provider == super::identity::IdentityProvider::Oidc) + { + return Err(Status::permission_denied( + "browser token sessions require an OIDC user", + )); + } + let token = super::authenticator::bearer_credential(req.headers()) + .ok_or_else(|| Status::unauthenticated("gateway token required"))?; + cleanup(state, &workspace).await?; + let value = random()?; + let key = digest(&value)?; + let credential = state + .credentials + .store_application_token(&workspace, &key, token) + .await?; + let record = Session { + host: target.origin().ascii_serialization(), + expires: token_expiry(token)?.min(now() + 600), + pending_until: now() + 120, + login_state: digest(&login.state)?, + handle: URL_SAFE_NO_PAD.encode(credential.encode_to_vec()), + credential_id: key.clone(), + cookie_key: String::new(), + redeemed: false, + revoked: false, + }; + let payload = serde_json::to_vec(&record).map_err(|_| internal())?; + let result = state + .store + .create_if_workspace_count_below(SESSION, &key, &key, &workspace, &payload, None, 1024) + .await; + if !matches!(result, Ok(Some(_))) { + state + .credentials + .delete_application_token(&workspace, &key, credential) + .await?; + return Err(Status::resource_exhausted("browser session unavailable")); + } + target.set_path(&format!("{PREFIX}/redeem")); + target.query_pairs_mut().append_pair("code", &value); + Ok(no_cache( + axum::Json(serde_json::json!({"redirect": target.as_str()})).into_response(), + )) +} + +#[derive(Serialize)] +struct LoginBody { + service_origin: String, + state: String, +} + +pub async fn handle( + state: &ServerState, + req: &mut Request, + workspace: &str, +) -> Result { + secure(req)?; + let path = req.uri().path().to_string(); + if path == format!("{PREFIX}/start") && req.method() == Method::GET { + let params = parameters(req)?; + let mut login = origin(params.get("login_origin").map_or("", String::as_str))?; + if crate::service_routing::resolve_service_host(state, login.host_str().unwrap_or_default()) + .await + .is_some() + { + return Err(Status::invalid_argument( + "login must use the control-plane origin", + )); + } + login.set_path(CONTROL); + let nonce = random()?; + login + .query_pairs_mut() + .append_pair( + "service_origin", + &request_origin(req)?.origin().ascii_serialization(), + ) + .append_pair("state", &nonce); + return with_cookie(redirect(&login)?, LOGIN_COOKIE, &nonce, 120, "Lax"); + } + if path == format!("{PREFIX}/redeem") && req.method() == Method::GET { + let params = parameters(req)?; + let code = params + .get("code") + .filter(|c| c.len() == 43) + .ok_or_else(|| Status::unauthenticated("invalid login code"))?; + let key = digest(code)?; + let record = state + .store + .get(SESSION, &key) + .await + .map_err(|_| internal())? + .ok_or_else(|| Status::unauthenticated("expired login code"))?; + let mut value = session(&record)?; + let nonce = cookie(req.headers(), LOGIN_COOKIE)? + .ok_or_else(|| Status::unauthenticated("missing login state"))?; + if record.workspace != workspace + || value.host != request_origin(req)?.origin().ascii_serialization() + || value.redeemed + || value.revoked + || value.pending_until <= now() + || value.expires <= now() + || value.login_state != digest(&nonce)? + { + return Err(Status::unauthenticated("invalid login code or state")); + } + let token = state + .credentials + .resolve_application_token(workspace, &value.credential_id, credential_handle(&value)?) + .await?; + let mut headers = HeaderMap::new(); + headers.insert( + header::AUTHORIZATION, + HeaderValue::from_str(&format!("Bearer {token}")).map_err(|_| internal())?, + ); + service_access::authorize(state, &headers, &ServicePeer::default(), workspace).await?; + value.redeemed = true; + let session_cookie = random()?; + let session_key = digest(&session_cookie)?; + value.cookie_key.clone_from(&session_key); + let payload = serde_json::to_vec(&value).map_err(|_| internal())?; + state + .store + .put_if( + SESSION, + &key, + &key, + workspace, + &payload, + None, + WriteCondition::MatchResourceVersion(record.resource_version), + ) + .await + .map_err(|_| Status::unauthenticated("login code already consumed"))?; + if state + .store + .create_if_workspace_count_below( + SESSION, + &session_key, + &session_key, + workspace, + &payload, + None, + 1024, + ) + .await + .map_err(|_| internal())? + .is_none() + { + return Err(Status::resource_exhausted("browser session limit reached")); + } + state + .store + .delete(SESSION, &key) + .await + .map_err(|_| internal())?; + let response = with_cookie( + browser_complete()?, + COOKIE, + &session_cookie, + value.expires.saturating_sub(now()), + "Strict", + )?; + return with_cookie(response, LOGIN_COOKIE, "", 0, "Lax"); + } + browser_origin(req, true)?; + if path == format!("{PREFIX}/session") && req.method() == Method::DELETE { + if let Some(cookie) = cookie(req.headers(), COOKIE)? { + let key = digest(&cookie)?; + if let Some(record) = state + .store + .get(SESSION, &key) + .await + .map_err(|_| internal())? + { + let mut value = session(&record)?; + if record.workspace != workspace + || value.host != request_origin(req)?.origin().ascii_serialization() + { + return Err(Status::permission_denied("wrong session host")); + } + value.revoked = true; + state + .store + .put_if( + SESSION, + &key, + &key, + workspace, + &serde_json::to_vec(&value).map_err(|_| internal())?, + None, + WriteCondition::MatchResourceVersion(record.resource_version), + ) + .await + .map_err(|_| internal())?; + state + .credentials + .delete_application_token( + workspace, + &value.credential_id, + credential_handle(&value)?, + ) + .await?; + state + .store + .delete(SESSION, &key) + .await + .map_err(|_| internal())?; + } + } + return with_cookie( + StatusCode::NO_CONTENT.into_response(), + COOKIE, + "", + 0, + "Strict", + ); + } + if path == format!("{PREFIX}/credential") && req.method() == Method::DELETE { + // A service-scoped browser session must not administer the underlying + // gateway credential's access to other services. + if cookie(req.headers(), COOKIE)?.is_some() { + return Err(Status::permission_denied( + "explicit gateway credential required for credential revocation", + )); + } + let token = authorize_request(state, req, workspace).await?; + let (key, expires) = if let Some(token) = token { + (digest(&token)?, token_expiry(&token)?) + } else { + let fingerprint = req + .extensions() + .get::() + .and_then(|p| p.certificate_sha256.as_ref()) + .ok_or_else(|| Status::invalid_argument("gateway credential required"))?; + (format!("mtls-{fingerprint}"), u64::MAX) + }; + cleanup(state, workspace).await?; + if state + .store + .create_if_workspace_count_below( + REVOKED, + &key, + &key, + REVOCATION_SCOPE, + &serde_json::to_vec(&expires).map_err(|_| internal())?, + None, + 1024, + ) + .await + .map_err(|_| internal())? + .is_none() + { + return Err(Status::resource_exhausted("revocation limit reached")); + } + return with_cookie( + StatusCode::NO_CONTENT.into_response(), + COOKIE, + "", + 0, + "Strict", + ); + } + Ok(StatusCode::NOT_FOUND.into_response()) +} + +fn no_cache(mut response: Response) -> Response { + response + .headers_mut() + .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + response.headers_mut().insert( + header::REFERRER_POLICY, + HeaderValue::from_static("no-referrer"), + ); + response.headers_mut().insert( + header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); + response +} + +fn browser_complete() -> Result { + // A document on the service origin starts a fresh navigation, so Strict + // cookies are sent even when login began on a different site. A chain of + // HTTP redirects would retain the original cross-site navigation context. + let nonce = random()?; + let mut response = format!("OpenShell sign in complete

Signed in.

Open service").into_response(); + response.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/html; charset=utf-8"), + ); + response.headers_mut().insert(header::CONTENT_SECURITY_POLICY, HeaderValue::from_str(&format!("default-src 'none'; script-src 'nonce-{nonce}'; frame-ancestors 'none'; base-uri 'none'")).map_err(|_| internal())?); + Ok(no_cache(response)) +} +fn with_cookie( + mut response: Response, + name: &str, + value: &str, + seconds: u64, + same_site: &str, +) -> Result { + response.headers_mut().append( + header::SET_COOKIE, + HeaderValue::from_str(&format!( + "{name}={value}; Path=/; Secure; HttpOnly; SameSite={same_site}; Max-Age={seconds}" + )) + .map_err(|_| internal())?, + ); + Ok(no_cache(response)) +} +pub fn strip_response_cookies(headers: &mut HeaderMap) { + let allowed: Vec<_> = headers + .get_all(header::SET_COOKIE) + .iter() + .filter(|value| { + value + .to_str() + .ok() + .and_then(|v| v.split_once('=')) + .is_some_and(|(name, _)| !name.trim().starts_with("__Host-openshell-")) + }) + .cloned() + .collect(); + headers.remove(header::SET_COOKIE); + for value in allowed { + headers.append(header::SET_COOKIE, value); + } +} + +pub fn error(status: &Status) -> Response { + let code = match status.code() { + tonic::Code::Unauthenticated => StatusCode::UNAUTHORIZED, + tonic::Code::PermissionDenied => StatusCode::FORBIDDEN, + tonic::Code::InvalidArgument => StatusCode::BAD_REQUEST, + tonic::Code::ResourceExhausted => StatusCode::TOO_MANY_REQUESTS, + _ => StatusCode::SERVICE_UNAVAILABLE, + }; + let mut response = + crate::service_routing::service_error_response(code, "Application authentication failed"); + if code == StatusCode::UNAUTHORIZED { + response + .headers_mut() + .insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); + } + no_cache(response) +} + +#[cfg(test)] +pub mod tests { + use super::*; + use crate::auth::oidc::tests::{cache_with_mock_issuer, claims_for, mint_rs256}; + use crate::grpc::test_support::test_server_state; + use http_body_util::BodyExt; + use openshell_core::proto::{WorkspaceMember, WorkspaceRole, datamodel::v1::ObjectMeta}; + use std::sync::Arc; + use tower::ServiceExt; + + const APP: &str = "https://default--demo--web.services.example.com"; + const GATEWAY: &str = "https://gateway.example.com"; + + pub async fn fixture() -> (wiremock::MockServer, Arc, String) { + let server = wiremock::MockServer::start().await; + let cache = Arc::new(cache_with_mock_issuer(&server).await); + let mut state = test_server_state().await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.auth.allow_unauthenticated_users = false; + inner.config.service_routing.base_domains = vec!["services.example.com".into()]; + inner.config.oidc = Some(serde_json::from_value(serde_json::json!({"issuer":server.uri(),"audience":"openshell-cli","scopes_claim":"scope"})).unwrap()); + inner.admin_role = "openshell-admin".into(); + inner.oidc_cache = Some(cache); + state + .store + .put_message(&WorkspaceMember { + metadata: Some(ObjectMeta { + id: "member-user-42".into(), + name: "user-42".into(), + workspace: "default".into(), + ..Default::default() + }), + principal_subject: "user-42".into(), + role: WorkspaceRole::User.into(), + }) + .await + .unwrap(); + let token = mint_rs256( + &claims_for( + &server.uri(), + "openshell-cli", + i64::try_from(now() + 3600).unwrap(), + ), + "test-signing-key", + ); + (server, state, token) + } + + fn request(method: Method, url: &str) -> Request { + let url = url::Url::parse(url).unwrap(); + let mut request = Request::builder() + .method(method) + .uri(url.as_str()) + .header(header::HOST, url.authority()) + .body(Body::empty()) + .unwrap(); + request.extensions_mut().insert(ServicePeer { + secure: true, + ..Default::default() + }); + request + } + async fn send(state: &Arc, request: Request) -> Response { + crate::http::http_router(state.clone()) + .oneshot(request) + .await + .unwrap() + } + fn location(response: &Response) -> String { + response.headers()[header::LOCATION] + .to_str() + .unwrap() + .to_string() + } + fn response_cookie(response: &Response, name: &str) -> String { + response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .find(|v| v.starts_with(&format!("{name}="))) + .unwrap() + .split(';') + .next() + .unwrap() + .to_string() + } + pub async fn browser_login(state: &Arc, token: &str) -> String { + browser_login_for(state, token, APP).await + } + + async fn browser_login_for(state: &Arc, token: &str, app_origin: &str) -> String { + let mut url = url::Url::parse(&format!("{GATEWAY}{CONTROL}")).unwrap(); + url.query_pairs_mut() + .append_pair("service_origin", app_origin); + let redirect = send(state, request(Method::GET, url.as_str())).await; + assert_eq!(redirect.status(), StatusCode::SEE_OTHER); + let start = send(state, request(Method::GET, &location(&redirect))).await; + let nonce_cookie = response_cookie(&start, LOGIN_COOKIE); + let login_url = location(&start); + let login_url = url::Url::parse(&login_url).unwrap(); + let params: std::collections::HashMap<_, _> = + login_url.query_pairs().into_owned().collect(); + let page = send(state, request(Method::GET, login_url.as_str())).await; + assert_eq!(page.status(), StatusCode::OK); + assert!( + page.headers()[header::CONTENT_SECURITY_POLICY] + .to_str() + .unwrap() + .contains("frame-ancestors 'none'") + ); + let mut login = request(Method::POST, &format!("{GATEWAY}{CONTROL}")); + login + .headers_mut() + .insert(header::ORIGIN, GATEWAY.parse().unwrap()); + login.headers_mut().insert( + header::AUTHORIZATION, + format!("Bearer {token}").parse().unwrap(), + ); + *login.body_mut() = Body::from( + serde_json::to_vec( + &serde_json::json!({"service_origin":app_origin,"state":params["state"]}), + ) + .unwrap(), + ); + let response = send(state, login).await; + assert_eq!(response.status(), StatusCode::OK); + let json: serde_json::Value = + serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes()) + .unwrap(); + let redeem_url = json["redirect"].as_str().unwrap(); + assert!(!redeem_url.contains(token)); + let missing = send(state, request(Method::GET, redeem_url)).await; + assert_eq!(missing.status(), StatusCode::UNAUTHORIZED); + let mut redeem = request(Method::GET, redeem_url); + redeem + .headers_mut() + .insert(header::COOKIE, nonce_cookie.parse().unwrap()); + let mut racing = request(Method::GET, redeem_url); + racing + .headers_mut() + .insert(header::COOKIE, nonce_cookie.parse().unwrap()); + let (left, right) = tokio::join!(send(state, redeem), send(state, racing)); + let response = if left.status() == StatusCode::OK { + assert_eq!(right.status(), StatusCode::UNAUTHORIZED); + left + } else { + assert_eq!(left.status(), StatusCode::UNAUTHORIZED); + assert_eq!(right.status(), StatusCode::OK); + right + }; + assert_eq!(response.status(), StatusCode::OK); + let cookie = response_cookie(&response, COOKIE); + let flags = response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .next() + .unwrap() + .to_str() + .unwrap(); + assert!(flags.contains("Secure; HttpOnly; SameSite=Strict")); + let mut replay = request(Method::GET, redeem_url); + replay + .headers_mut() + .insert(header::COOKIE, nonce_cookie.parse().unwrap()); + assert_eq!(send(state, replay).await.status(), StatusCode::UNAUTHORIZED); + let code = url::Url::parse(redeem_url) + .unwrap() + .query_pairs() + .find(|(k, _)| k == "code") + .unwrap() + .1 + .into_owned(); + let mut leaked_code = request(Method::GET, &format!("{app_origin}/")); + leaked_code + .headers_mut() + .insert(header::COOKIE, format!("{COOKIE}={code}").parse().unwrap()); + assert_eq!( + send(state, leaked_code).await.status(), + StatusCode::UNAUTHORIZED, + "bootstrap code is never an active cookie" + ); + let records = state.store.list(SESSION, "default", 1024, 0).await.unwrap(); + assert_eq!(records.len(), 1); + assert!(!String::from_utf8_lossy(&records[0].payload).contains(token)); + cookie + } + + #[tokio::test] + async fn hashed_service_browser_login_preserves_origin_and_authentication() { + use openshell_core::config::ServiceHostnameFormat; + let (_issuer, mut state, token) = fixture().await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.name = "gateway-a".into(); + inner.config.service_routing.service_hostname_format = ServiceHostnameFormat::Hashed; + inner.service_route_index = Arc::new(crate::service_routing::ServiceRouteIndex::new(Some( + "gateway-a".into(), + ))); + inner + .service_route_index + .register("default", "demo", "web") + .unwrap(); + state + .store + .put_message(&openshell_core::proto::ServiceEndpoint { + metadata: Some(ObjectMeta { + id: "hashed-web".into(), + name: "demo--web".into(), + workspace: "default".into(), + ..Default::default() + }), + sandbox_id: "sandbox-demo".into(), + sandbox: "demo".into(), + name: "web".into(), + target_port: 8080, + domain: true, + ..Default::default() + }) + .await + .unwrap(); + let label = crate::service_routing::service_route_hash_label( + "gateway-a", + "default", + "demo", + Some("web"), + ); + let app_origin = format!("https://{label}.services.example.com"); + assert_eq!( + service_origin(&state, &app_origin).await.unwrap().1, + "default" + ); + // Hashes from another installation must not resolve on this gateway. + let other = crate::service_routing::service_route_hash_label( + "gateway-b", + "default", + "demo", + Some("web"), + ); + assert!( + service_origin(&state, &format!("https://{other}.services.example.com")) + .await + .is_err() + ); + let mut start = request( + Method::GET, + &format!("{app_origin}{PREFIX}/start?login_origin={app_origin}"), + ); + assert_eq!( + handle(&state, &mut start, "default") + .await + .unwrap_err() + .code(), + tonic::Code::InvalidArgument + ); + let cookie = browser_login_for(&state, &token, &app_origin).await; + let mut application = request(Method::GET, &format!("{app_origin}/")); + application + .headers_mut() + .insert(header::COOKIE, cookie.parse().unwrap()); + authorize_request(&state, &mut application, "default") + .await + .unwrap(); + let anonymous = send(&state, request(Method::GET, &format!("{app_origin}/"))).await; + assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED); + } + + #[tokio::test] + async fn browser_login_separates_gateway_and_application_credentials_and_checks_csrf() { + let (_issuer, state, token) = fixture().await; + let cookie = browser_login(&state, &token).await; + let mut app = request(Method::GET, &format!("{APP}/")); + app.headers_mut().insert( + header::COOKIE, + format!("{cookie}; application_session=app-secret") + .parse() + .unwrap(), + ); + app.headers_mut().insert( + header::AUTHORIZATION, + "Bearer application-token".parse().unwrap(), + ); + authorize_request(&state, &mut app, "default") + .await + .unwrap(); + assert_eq!( + app.headers()[header::AUTHORIZATION], + "Bearer application-token" + ); + // Authenticated request reaches endpoint lookup; no such endpoint exists. + assert_eq!(send(&state, app).await.status(), StatusCode::NOT_FOUND); + for (method, upgrade) in [(Method::POST, false), (Method::GET, true)] { + for origin in [None, Some("https://evil.example.com"), Some("null")] { + let mut req = request(method.clone(), &format!("{APP}/")); + req.headers_mut() + .insert(header::COOKIE, cookie.parse().unwrap()); + if upgrade { + req.headers_mut() + .insert(header::UPGRADE, "websocket".parse().unwrap()); + } + if let Some(origin) = origin { + req.headers_mut() + .insert(header::ORIGIN, origin.parse().unwrap()); + } + assert_eq!(send(&state, req).await.status(), StatusCode::FORBIDDEN); + } + let mut req = request(method, &format!("{APP}/")); + req.headers_mut() + .insert(header::COOKIE, cookie.parse().unwrap()); + req.headers_mut() + .insert(header::ORIGIN, APP.parse().unwrap()); + if upgrade { + req.headers_mut() + .insert(header::UPGRADE, "websocket".parse().unwrap()); + } + assert_eq!(send(&state, req).await.status(), StatusCode::NOT_FOUND); + } + } + + #[tokio::test] + async fn gateway_headers_authenticate_without_forwarding_tokens_and_discovery_scope_is_rejected() + { + let (issuer, state, token) = fixture().await; + let mut direct = request(Method::GET, &format!("{APP}/")); + direct.headers_mut().insert( + header::AUTHORIZATION, + format!("Bearer {token}").parse().unwrap(), + ); + authorize_request(&state, &mut direct, "default") + .await + .unwrap(); + assert!(!direct.headers().contains_key(header::AUTHORIZATION)); + let mut separate = request(Method::GET, &format!("{APP}/")); + separate + .headers_mut() + .insert(GATEWAY_AUTH, format!("Bearer {token}").parse().unwrap()); + separate.headers_mut().insert( + header::AUTHORIZATION, + "Bearer application-token".parse().unwrap(), + ); + authorize_request(&state, &mut separate, "default") + .await + .unwrap(); + assert_eq!( + separate.headers()[header::AUTHORIZATION], + "Bearer application-token" + ); + let mut claims = claims_for( + &issuer.uri(), + "openshell-cli", + i64::try_from(now() + 3600).unwrap(), + ); + claims["scope"] = serde_json::json!("sandbox:read"); + let discovery = mint_rs256(&claims, "test-signing-key"); + separate + .headers_mut() + .insert(GATEWAY_AUTH, format!("Bearer {discovery}").parse().unwrap()); + assert_eq!(send(&state, separate).await.status(), StatusCode::FORBIDDEN); + for invalid in [ + "not-a-token".to_string(), + mint_rs256( + &claims_for( + &issuer.uri(), + "openshell-cli", + i64::try_from(now()).unwrap() - 1, + ), + "test-signing-key", + ), + ] { + let mut req = request(Method::GET, &format!("{APP}/")); + req.headers_mut().insert( + header::AUTHORIZATION, + format!("Bearer {invalid}").parse().unwrap(), + ); + assert_eq!(send(&state, req).await.status(), StatusCode::UNAUTHORIZED); + } + } + + async fn replica(state: &Arc) -> Arc { + Arc::new(ServerState::new_with_credentials( + state.config.clone(), + state.store.clone(), + crate::compute::new_test_runtime(state.store.clone()).await, + crate::sandbox_index::SandboxIndex::new(), + crate::sandbox_watch::SandboxWatchBus::new(), + crate::tracing_bus::TracingLogBus::new(), + Arc::new(crate::supervisor_session::SupervisorSessionRegistry::new()), + state.oidc_cache.clone(), + state.credentials.clone(), + )) + } + fn application(cookie: &str) -> Request { + let mut req = request(Method::GET, &format!("{APP}/")); + req.headers_mut() + .insert(header::COOKIE, cookie.parse().unwrap()); + req + } + + #[tokio::test] + async fn sessions_recheck_workspace_and_logout_and_token_revocation_across_replicas() { + let (_issuer, state, token) = fixture().await; + let cookie = browser_login(&state, &token).await; + let other = replica(&state).await; + assert_eq!( + send(&other, application(&cookie)).await.status(), + StatusCode::NOT_FOUND + ); + let mut logout = request(Method::DELETE, &format!("{APP}{PREFIX}/session")); + logout + .headers_mut() + .insert(header::COOKIE, cookie.parse().unwrap()); + logout + .headers_mut() + .insert(header::ORIGIN, APP.parse().unwrap()); + assert_eq!(send(&state, logout).await.status(), StatusCode::NO_CONTENT); + assert_eq!( + send(&other, application(&cookie)).await.status(), + StatusCode::UNAUTHORIZED + ); + let cookie = browser_login(&state, &token).await; + let mut revoke = request(Method::DELETE, &format!("{APP}{PREFIX}/credential")); + revoke.headers_mut().insert( + header::AUTHORIZATION, + format!("Bearer {token}").parse().unwrap(), + ); + revoke + .headers_mut() + .insert(header::ORIGIN, APP.parse().unwrap()); + assert_eq!(send(&state, revoke).await.status(), StatusCode::NO_CONTENT); + assert_eq!( + send(&other, application(&cookie)).await.status(), + StatusCode::UNAUTHORIZED + ); + let mut replay = request(Method::GET, &format!("{APP}/")); + replay.headers_mut().insert( + header::AUTHORIZATION, + format!("Bearer {token}").parse().unwrap(), + ); + assert_eq!( + send(&other, replay).await.status(), + StatusCode::UNAUTHORIZED + ); + } + + #[tokio::test] + async fn sessions_reject_wrong_hosts_expiry_removed_membership_and_spoofed_headers() { + let (_issuer, state, token) = fixture().await; + let cookie = browser_login(&state, &token).await; + let mut wrong = application(&cookie); + wrong.headers_mut().insert( + header::HOST, + "default--other--web.services.example.com".parse().unwrap(), + ); + assert_eq!(send(&state, wrong).await.status(), StatusCode::UNAUTHORIZED); + state + .store + .delete("workspace_member", "member-user-42") + .await + .unwrap(); + assert_eq!( + send(&state, application(&cookie)).await.status(), + StatusCode::FORBIDDEN + ); + let record = state + .store + .list(SESSION, "default", 1, 0) + .await + .unwrap() + .remove(0); + let mut value = session(&record).unwrap(); + value.expires = now(); + state + .store + .put_if( + SESSION, + &record.id, + &record.name, + "default", + &serde_json::to_vec(&value).unwrap(), + None, + WriteCondition::Unconditional, + ) + .await + .unwrap(); + assert_eq!( + send(&state, application(&cookie)).await.status(), + StatusCode::UNAUTHORIZED + ); + let mut spoof = request(Method::GET, &format!("{APP}/")); + spoof + .headers_mut() + .insert("x-forwarded-client-cert", "forged".parse().unwrap()); + spoof + .headers_mut() + .insert("x-openshell-auth-source", "oidc".parse().unwrap()); + assert_eq!(send(&state, spoof).await.status(), StatusCode::UNAUTHORIZED); + } + + #[tokio::test] + async fn mtls_revocation_and_explicit_development_auth_work_with_either_listener_mode() { + use crate::auth::identity::{Identity, IdentityProvider}; + let mut state = test_server_state().await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.service_routing.base_domains = vec!["services.example.com".into()]; + inner.config.auth.allow_unauthenticated_users = false; + inner.config.mtls_auth.enabled = true; + let peer = ServicePeer { + secure: true, + identity: Some(Identity { + subject: "mtls-user".into(), + display_name: None, + roles: vec![], + scopes: vec![], + provider: IdentityProvider::Mtls, + }), + certificate_sha256: Some("verified-certificate-digest".into()), + source: None, + }; + for enabled in [false, true] { + Arc::get_mut(&mut state) + .unwrap() + .config + .supervisor_app_listener + .enabled = enabled; + let mut req = request(Method::GET, &format!("{APP}/")); + req.extensions_mut().insert(peer.clone()); + assert_eq!(send(&state, req).await.status(), StatusCode::NOT_FOUND); + assert_eq!( + send(&state, request(Method::GET, &format!("{APP}/"))) + .await + .status(), + StatusCode::UNAUTHORIZED + ); + } + let other = replica(&state).await; + let mut revoke = request(Method::DELETE, &format!("{APP}{PREFIX}/credential")); + revoke.extensions_mut().insert(peer.clone()); + revoke + .headers_mut() + .insert(header::ORIGIN, APP.parse().unwrap()); + assert_eq!(send(&state, revoke).await.status(), StatusCode::NO_CONTENT); + let mut req = request(Method::GET, &format!("{APP}/")); + req.extensions_mut().insert(peer); + assert_eq!(send(&other, req).await.status(), StatusCode::UNAUTHORIZED); + drop(other); + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.mtls_auth.enabled = false; + inner.config.auth.allow_unauthenticated_users = true; + assert_eq!( + send(&state, request(Method::GET, &format!("{APP}/"))) + .await + .status(), + StatusCode::NOT_FOUND + ); + let mut invalid = request(Method::GET, &format!("{APP}/")); + invalid + .headers_mut() + .insert(GATEWAY_AUTH, "Bearer invalid".parse().unwrap()); + assert_eq!( + send(&state, invalid).await.status(), + StatusCode::UNAUTHORIZED + ); + let mut application = request(Method::GET, &format!("{APP}/")); + application.headers_mut().insert( + header::AUTHORIZATION, + "Bearer application-token".parse().unwrap(), + ); + authorize_request(&state, &mut application, "default") + .await + .unwrap(); + assert_eq!( + application.headers()[header::AUTHORIZATION], + "Bearer application-token" + ); + } +} diff --git a/crates/openshell-server/src/credentials.rs b/crates/openshell-server/src/credentials.rs index 333e7b412f..7d2e93fd75 100644 --- a/crates/openshell-server/src/credentials.rs +++ b/crates/openshell-server/src/credentials.rs @@ -48,6 +48,74 @@ impl CredentialRuntime { } } + /// Browser session tokens stay behind the configured credential issuer; + /// session metadata stores only their opaque credential handles. + pub async fn store_application_token( + &self, + workspace: &str, + id: &str, + token: &str, + ) -> Result { + let storage_id = format!("service-session-{id}"); + let mut handles = self + .store_secrets_with_object_id( + SecretOwner::application_session(workspace, &storage_id), + &storage_id, + &HashMap::from([("gateway-access-token".into(), token.into())]), + &Handles::new(), + ) + .await?; + handles + .remove("gateway-access-token") + .ok_or_else(|| Status::internal("application credential handle missing")) + } + + pub async fn resolve_application_token( + &self, + workspace: &str, + id: &str, + handle: CredentialHandle, + ) -> Result { + let storage_id = format!("service-session-{id}"); + let values = self + .issuer + .resolve( + SecretOwner::application_session(workspace, &storage_id), + &Handles::from([("gateway-access-token".into(), handle)]), + ) + .await?; + if values.len() != 1 + || values[0].credential_key != "gateway-access-token" + || values[0].value.is_empty() + { + return Err(Status::unauthenticated( + "application credential unavailable", + )); + } + if let Some(expires) = &values[0].expiration_time + && openshell_core::time::timestamp_to_millis(expires) + .map_err(|_| Status::unavailable("invalid application credential expiration"))? + <= openshell_core::time::now_ms() + { + return Err(Status::unauthenticated("expired application credential")); + } + Ok(values.into_iter().next().unwrap().value) + } + + pub async fn delete_application_token( + &self, + workspace: &str, + id: &str, + handle: CredentialHandle, + ) -> Result<(), Status> { + let storage_id = format!("service-session-{id}"); + self.delete_secrets( + SecretOwner::application_session(workspace, &storage_id), + &Handles::from([("gateway-access-token".into(), handle)]), + ) + .await + } + pub fn from_config(config: &Config) -> CoreResult { Ok(Self::from_embedded(EmbeddedCredentialIssuer::from_config( &IssuerConfig::from(config), diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index dd0ef762cc..2b886c5644 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -3446,13 +3446,15 @@ mod tests { .expect("failed to create test store"), ); let compute = crate::compute::new_test_runtime(store.clone()).await; + let mut config = Config::new(None) + .with_database_url("sqlite::memory:?cache=shared") + .with_bind_address(bind_addr) + .with_server_sans(["*.dev.openshell.localhost"]) + .with_loopback_service_http(enable_loopback_service_http) + .with_credential_drivers(["test-static"]); + config.auth.allow_unauthenticated_users = true; Arc::new(ServerState::new( - Config::new(None) - .with_database_url("sqlite::memory:?cache=shared") - .with_bind_address(bind_addr) - .with_server_sans(["*.dev.openshell.localhost"]) - .with_loopback_service_http(enable_loopback_service_http) - .with_credential_drivers(["test-static"]), + config, store, compute, crate::sandbox_index::SandboxIndex::new(), @@ -4159,6 +4161,102 @@ mod tests { stop_listener(shutdown, handle).await; } + #[tokio::test] + async fn service_auth_uses_real_tls_client_identity_with_listener_disabled_or_enabled() { + use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, pem::PemObject}; + let dir = tempdir().unwrap(); + let (ca, ca_key) = generate_test_certs_with_ca(dir.path()); + let mut params = rcgen::CertificateParams::new(Vec::::new()).unwrap(); + params + .distinguished_name + .push(rcgen::DnType::CommonName, "application-user"); + params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ClientAuth]; + let client_key = openshell_crypto::pki::generate_keypair().unwrap(); + let client = openshell_crypto::pki::signed_by(params, &client_key, &ca, &ca_key).unwrap(); + let client_cert = CertificateDer::from(client.der().to_vec()); + let key_pem = client_key.serialize_pem().unwrap(); + let client_key = PrivateKeyDer::from_pem_slice(key_pem.as_bytes()).unwrap(); + for enabled in [false, true] { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let mut state = test_state(addr, false).await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.auth.allow_unauthenticated_users = false; + inner.config.mtls_auth.enabled = true; + inner.config.supervisor_app_listener.enabled = enabled; + inner.config.tls = Some(openshell_core::TlsConfig { + cert_path: dir.path().join("server-cert.pem"), + key_path: dir.path().join("server-key.pem"), + client_ca_path: Some(dir.path().join("ca.pem")), + require_client_auth: false, + external_cert_path: None, + external_key_path: None, + external_server_names: vec![], + }); + let acceptor = TlsAcceptor::from_files( + &dir.path().join("server-cert.pem"), + &dir.path().join("server-key.pem"), + Some(&dir.path().join("ca.pem")), + false, + None, + None, + vec![], + ) + .unwrap(); + let (shutdown, rx) = watch::channel(false); + let handle = tokio::spawn(serve_gateway_listener( + BoundGatewayListener { + listener, + address: addr, + }, + MultiplexService::new(state), + Some(acceptor), + false, + rx, + )); + for authenticated in [false, true] { + let mut roots = rustls::RootCertStore::empty(); + roots.add(CertificateDer::from(ca.der().to_vec())).unwrap(); + let builder = openshell_crypto::tls::client_builder().with_root_certificates(roots); + let config = if authenticated { + builder + .with_client_auth_cert(vec![client_cert.clone()], client_key.clone_key()) + .unwrap() + } else { + builder.with_no_client_auth() + }; + let stream = openshell_core::net::connect_tcp_nodelay_best_effort(addr) + .await + .unwrap(); + let mut stream = tokio_rustls::TlsConnector::from(Arc::new(config)) + .connect(ServerName::try_from("localhost").unwrap(), stream) + .await + .unwrap(); + stream + .write_all( + service_request(addr, &[("X-Forwarded-Client-Cert", "forged")]).as_bytes(), + ) + .await + .unwrap(); + let mut response = vec![]; + tokio::time::timeout(Duration::from_secs(5), stream.read_to_end(&mut response)) + .await + .unwrap() + .unwrap(); + let response = String::from_utf8_lossy(&response); + assert!( + response.starts_with(if authenticated { + "HTTP/1.1 404" + } else { + "HTTP/1.1 401" + }), + "listener={enabled}, authenticated={authenticated}: {response}" + ); + } + stop_listener(shutdown, handle).await; + } + } + #[tokio::test] async fn plaintext_service_http_does_not_expose_grpc_gateway() { let (addr, shutdown, handle, _tls_dir) = diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 557c070996..6e045d97aa 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -340,19 +340,26 @@ impl MultiplexService { .config .mtls_auth .enabled - .then_some(peer_identity) + .then_some(peer_identity.clone()) .flatten(), self.state.config.mtls_auth.enabled, self.state.config.auth.allow_unauthenticated_users, ) - .with_peer_certificate(certificate_sha256) + .with_peer_certificate(certificate_sha256.clone()) .with_operator(operator) .with_connection_source(source) .with_logons(self.state.logons.clone()); let mut grpc_service = GrpcRateLimitService::new(grpc_service, self.state.grpc_rate_limiter.clone()); grpc_service.provider_token_limiter = self.state.provider_token_rate_limiter.clone(); - let http_service = http_router(self.state.clone()); + let http_service = http_router(self.state.clone()).layer(axum::Extension( + crate::auth::service_access::ServicePeer { + secure: self.state.config.tls.is_some(), + identity: peer_identity, + certificate_sha256, + source: Some(source), + }, + )); let grpc_service = request_id_middleware!(grpc_service); let http_service = request_id_middleware!(http_service); @@ -1148,7 +1155,7 @@ where /// /// When no bearer authenticators are configured, the chain is left as `None`. /// The router still requires an mTLS principal or the explicit development opt-in. -fn build_authenticator_chain(state: &ServerState) -> Option { +pub fn build_authenticator_chain(state: &ServerState) -> Option { let mut authenticators: Vec> = Vec::new(); if let Some(peer) = state.peer_authenticator.clone() { authenticators.push(peer); @@ -1260,7 +1267,7 @@ impl AuthGrpcRouter { } } -fn unauthenticated_dev_user_principal() -> Principal { +pub fn unauthenticated_dev_user_principal() -> Principal { Principal::User(UserPrincipal { identity: Identity { subject: "unauthenticated-local-dev".to_string(), diff --git a/crates/openshell-server/src/service_routing.rs b/crates/openshell-server/src/service_routing.rs index dfd84ff9d6..fba3d093eb 100644 --- a/crates/openshell-server/src/service_routing.rs +++ b/crates/openshell-server/src/service_routing.rs @@ -187,7 +187,11 @@ pub fn endpoint_url( fn endpoint_scheme(config: &openshell_core::Config) -> &'static str { if config.tls.is_none() || (config.bind_address.ip().is_loopback() - && config.service_routing.enable_loopback_service_http) + && config.service_routing.enable_loopback_service_http + && !config.mtls_auth.enabled + && !config.mtls_auth.operator_enabled + && config.oidc.is_none() + && !config.supervisor_app_listener.enabled) { "http" } else { @@ -512,7 +516,7 @@ pub async fn is_sandbox_service_request_with_state( pub async fn proxy_sandbox_service_request( state: Arc, - req: Request, + mut req: Request, ) -> impl IntoResponse { if !state.config.service_routing.enabled { return service_error_response( @@ -533,6 +537,22 @@ pub async fn proxy_sandbox_service_request( } = target; let service_name = service.unwrap_or_default(); + if req + .uri() + .path() + .starts_with(crate::auth::service_session::PREFIX) + { + return match crate::auth::service_session::handle(&state, &mut req, &workspace).await { + Ok(response) => response, + Err(error) => crate::auth::service_session::error(&error), + }; + } + if let Err(error) = + crate::auth::service_session::authorize_request(&state, &mut req, &workspace).await + { + return crate::auth::service_session::error(&error); + } + match proxy_to_endpoint(state, req, &workspace, sandbox_name, service_name).await { Ok(response) => response.into_response(), Err(err) => err.into_response(), @@ -813,11 +833,13 @@ async fn proxy_to_endpoint( } }); - let (parts, _) = response.into_parts(); + let (mut parts, _) = response.into_parts(); + crate::auth::service_session::strip_response_cookies(&mut parts.headers); return Ok(Response::from_parts(parts, Body::empty())); } - let (parts, body) = response.into_parts(); + let (mut parts, body) = response.into_parts(); + crate::auth::service_session::strip_response_cookies(&mut parts.headers); Ok(Response::from_parts(parts, Body::new(body))) } @@ -1096,7 +1118,13 @@ fn is_gateway_auth_header( ) -> bool { match name.as_str() { "authorization" => authorization_mode != ServiceAuthorizationMode::BearerPassthrough, - "cf-access-jwt-assertion" + "x-openshell-authorization" + | "x-openshell-auth-source" + | "x-openshell-principal" + | "x-openshell-user" + | "x-openshell-roles" + | "cf-access-authenticated-user-email" + | "cf-access-jwt-assertion" | "x-forwarded-client-cert" | "x-ssl-client-cert" | "x-client-cert" => true, @@ -1123,7 +1151,8 @@ fn sanitize_cookie_header(value: &HeaderValue) -> Option { } fn is_gateway_auth_cookie(name: &str) -> bool { - name.eq_ignore_ascii_case("CF_Authorization") || name.eq_ignore_ascii_case("cf-authorization") + name.eq_ignore_ascii_case("CF_Authorization") + || name.to_ascii_lowercase().starts_with("__host-openshell-") } pub fn emit_service_endpoint_config_event(endpoint: &ServiceEndpoint, url: &str, created: bool) { @@ -1470,6 +1499,475 @@ mod tests { } } + #[tokio::test] + async fn gateway_application_auth_gates_http_and_websocket_on_both_routers() { + use crate::auth::{ + identity::{Identity, IdentityProvider}, + service_access::ServicePeer, + }; + use crate::grpc::test_support::test_server_state; + use tower::ServiceExt; + + let mut state = test_server_state().await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.supervisor_app_listener.enabled = true; + inner.config.mtls_auth.enabled = true; + inner.config.auth.allow_unauthenticated_users = false; + inner.config.service_routing = config(); + let peer = ServicePeer { + identity: Some(Identity { + subject: "verified-user".into(), + display_name: None, + roles: vec![], + scopes: vec![], + provider: IdentityProvider::Mtls, + }), + ..Default::default() + }; + for router in [ + crate::http::http_router(state.clone()), + crate::http::service_http_router(state.clone()), + ] { + for path in ["/", "/auth/login", "/grpc.health.v1.Health/Check"] { + for websocket in [false, true] { + let mut request = Request::builder() + .uri(path) + .header(header::HOST, "default--unknown.dev.openshell.localhost") + .header("x-forwarded-client-cert", "forged-user"); + if websocket { + request = request + .header(header::CONNECTION, "upgrade") + .header(header::UPGRADE, "websocket"); + } + let response = router + .clone() + .oneshot(request.body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert_eq!(response.headers()[header::WWW_AUTHENTICATE], "Bearer"); + } + } + let request = || { + Request::builder() + .uri("/") + .header(header::HOST, "default--unknown.dev.openshell.localhost") + .body(Body::empty()) + .unwrap() + }; + // A verified peer passes the auth gate and reaches endpoint lookup. + let response = router + .clone() + .layer(axum::Extension(peer.clone())) + .oneshot(request()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + } + Arc::get_mut(&mut state).unwrap().admin_role = "openshell-admin".into(); + let response = crate::http::http_router(state.clone()) + .layer(axum::Extension(peer)) + .oneshot( + Request::builder() + .uri("/") + .header(header::HOST, "default--unknown.dev.openshell.localhost") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + response.status(), + StatusCode::FORBIDDEN, + "workspace authorization precedes endpoint lookup" + ); + Arc::get_mut(&mut state) + .unwrap() + .config + .supervisor_app_listener + .enabled = false; + let response = crate::http::http_router(state) + .oneshot( + Request::builder() + .uri("/") + .header(header::HOST, "default--unknown.dev.openshell.localhost") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + response.status(), + StatusCode::UNAUTHORIZED, + "listener-disabled gateways enforce configured authentication" + ); + } + + #[test] + fn authenticated_gateway_never_forwards_gateway_credentials() { + let request = || { + Request::builder() + .uri("/") + .header(header::AUTHORIZATION, "Bearer gateway-secret") + .header("cf-access-jwt-assertion", "edge-secret") + .body(Body::empty()) + .unwrap() + }; + let mode = effective_authorization_mode(ServiceAuthorizationMode::Strip as i32); + let upstream = build_upstream_request(request(), 8080, false, mode).unwrap(); + assert!(!upstream.headers().contains_key(header::AUTHORIZATION)); + assert!(!upstream.headers().contains_key("cf-access-jwt-assertion")); + let mode = effective_authorization_mode(ServiceAuthorizationMode::BearerPassthrough as i32); + let upstream = build_upstream_request(request(), 8080, false, mode).unwrap(); + assert_eq!( + upstream.headers()[header::AUTHORIZATION], + "Bearer gateway-secret" + ); + } + + #[tokio::test] + async fn authenticated_gateway_forwards_application_request_without_gateway_identity() { + use crate::auth::{ + identity::{Identity, IdentityProvider}, + service_access::ServicePeer, + }; + use crate::grpc::test_support::test_server_state; + use http_body_util::BodyExt; + use hyper::service::service_fn; + use tower::ServiceExt; + + let mut state = test_server_state().await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.supervisor_app_listener.enabled = true; + inner.config.mtls_auth.enabled = true; + inner.config.auth.allow_unauthenticated_users = false; + inner.config.service_routing = config(); + let mut endpoint = endpoint(); + endpoint.authorization_mode = ServiceAuthorizationMode::BearerPassthrough as i32; + state.store.put_message(&endpoint).await.unwrap(); + let mut sandbox = Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "sandbox-id".into(), + name: "my-sandbox".into(), + workspace: "default".into(), + ..Default::default() + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Ready as i32); + state.store.put_message(&sandbox).await.unwrap(); + + let (client_io, server_io) = tokio::io::duplex(4096); + let server = tokio::spawn(async move { + hyper::server::conn::http1::Builder::new() + .serve_connection( + TokioIo::new(server_io), + service_fn(|request: Request| async move { + assert_eq!(request.method(), Method::POST); + assert_eq!(request.uri().path(), "/app"); + assert!(!request.headers().contains_key(header::AUTHORIZATION)); + assert!(!request.headers().contains_key("x-forwarded-client-cert")); + assert!(!request.headers().contains_key("cf-access-jwt-assertion")); + let body = request.into_body().collect().await.unwrap().to_bytes(); + Ok::<_, std::convert::Infallible>(Response::new(Body::from(body))) + }), + ) + .await + .unwrap(); + }); + let (mut sender, connection) = + hyper::client::conn::http1::handshake(TokioIo::new(client_io)) + .await + .unwrap(); + let connection = tokio::spawn(connection); + sender.ready().await.unwrap(); + state + .service_upstreams + .put(&upstream_pool_key("endpoint-id", 8080), sender); + let peer = ServicePeer { + identity: Some(Identity { + subject: "verified-user".into(), + display_name: None, + roles: vec![], + scopes: vec![], + provider: IdentityProvider::Mtls, + }), + ..Default::default() + }; + let response = crate::http::http_router(state) + .layer(axum::Extension(peer)) + .oneshot( + Request::builder() + .method(Method::POST) + .uri("/app") + .header( + header::ORIGIN, + "https://default--my-sandbox--web.dev.openshell.localhost", + ) + .header( + header::HOST, + "default--my-sandbox--web.dev.openshell.localhost", + ) + .header("x-forwarded-client-cert", "forged-user") + .header("cf-access-jwt-assertion", "edge-token") + .body(Body::from("application-payload")) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.into_body().collect().await.unwrap().to_bytes(), + "application-payload" + ); + connection.abort(); + server.abort(); + } + + #[tokio::test] + async fn gateway_bearer_and_browser_sessions_forward_only_application_credentials() { + use crate::auth::service_session::{ + COOKIE, GATEWAY_AUTH, + tests::{browser_login, fixture}, + }; + use http_body_util::BodyExt; + use hyper::service::service_fn; + use tower::ServiceExt; + let (_issuer, state, token) = fixture().await; + let cookie = browser_login(&state, &token).await; + let mut endpoint = endpoint(); + endpoint.sandbox = "demo".into(); + endpoint.metadata.as_mut().unwrap().name = "demo--web".into(); + endpoint.authorization_mode = ServiceAuthorizationMode::BearerPassthrough.into(); + state.store.put_message(&endpoint).await.unwrap(); + let mut sandbox = Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "sandbox-id".into(), + name: "demo".into(), + workspace: "default".into(), + ..Default::default() + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Ready.into()); + state.store.put_message(&sandbox).await.unwrap(); + let (client_io, server_io) = tokio::io::duplex(8192); + let server = tokio::spawn(async move { + hyper::server::conn::http1::Builder::new() + .serve_connection( + TokioIo::new(server_io), + service_fn(|request: Request| async move { + assert_eq!(request.method(), Method::POST); + assert_eq!( + request.headers()[header::COOKIE], + "application_session=app-cookie" + ); + assert!(!request.headers().contains_key(GATEWAY_AUTH)); + assert!(!request.headers().contains_key("x-openshell-auth-source")); + assert!( + request + .headers() + .get(header::AUTHORIZATION) + .is_none_or(|v| v == "Bearer application-token") + ); + let body = request.into_body().collect().await.unwrap().to_bytes(); + let mut response = Response::new(Body::from(body)); + response.headers_mut().append( + header::SET_COOKIE, + "application_session=updated; HttpOnly".parse().unwrap(), + ); + response.headers_mut().append( + header::SET_COOKIE, + format!("{COOKIE}=forged; Secure; HttpOnly; Path=/") + .parse() + .unwrap(), + ); + Ok::<_, std::convert::Infallible>(response) + }), + ) + .await + .unwrap(); + }); + let (mut sender, connection) = + hyper::client::conn::http1::handshake(TokioIo::new(client_io)) + .await + .unwrap(); + let connection = tokio::spawn(connection); + sender.ready().await.unwrap(); + state + .service_upstreams + .put(&upstream_pool_key("endpoint-id", 8080), sender); + for method in ["session", "separate-header", "authorization"] { + let mut request = Request::builder() + .method(Method::POST) + .uri("/application") + .header(header::HOST, "default--demo--web.services.example.com") + .header( + header::ORIGIN, + "https://default--demo--web.services.example.com", + ) + .header("x-openshell-auth-source", "forged"); + if method == "session" { + request = request + .header( + header::COOKIE, + format!("{cookie}; application_session=app-cookie"), + ) + .header(header::AUTHORIZATION, "Bearer application-token"); + } else { + request = request.header(header::COOKIE, "application_session=app-cookie"); + request = if method == "separate-header" { + request + .header(GATEWAY_AUTH, format!("Bearer {token}")) + .header(header::AUTHORIZATION, "Bearer application-token") + } else { + request.header(header::AUTHORIZATION, format!("Bearer {token}")) + }; + } + let mut request = request.body(Body::from("payload")).unwrap(); + request + .extensions_mut() + .insert(crate::auth::service_access::ServicePeer { + secure: true, + ..Default::default() + }); + let response = crate::http::http_router(state.clone()) + .oneshot(request) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK, "{method}"); + assert_eq!( + response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .count(), + 1 + ); + assert!( + response.headers()[header::SET_COOKIE] + .to_str() + .unwrap() + .starts_with("application_session=") + ); + assert_eq!( + response.into_body().collect().await.unwrap().to_bytes(), + "payload" + ); + } + connection.abort(); + server.abort(); + } + + #[tokio::test] + #[ignore = "requires OPENSHELL_BROWSER_E2E_CHROME and Node.js"] + async fn gateway_service_auth_real_browser_cross_site_login() { + use crate::auth::service_session::tests::fixture; + use http_body_util::BodyExt; + use hyper::service::service_fn; + let (_issuer, mut state, token) = fixture().await; + let dir = tempfile::tempdir().unwrap(); + crate::tls_test_utils::generate_test_certs_with_ca(dir.path()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.bind_address = addr; + inner.config.tls = Some(openshell_core::TlsConfig { + cert_path: dir.path().join("server-cert.pem"), + key_path: dir.path().join("server-key.pem"), + client_ca_path: None, + require_client_auth: false, + external_cert_path: None, + external_key_path: None, + external_server_names: vec![], + }); + let mut endpoint = endpoint(); + endpoint.sandbox = "demo".into(); + endpoint.metadata.as_mut().unwrap().name = "demo--web".into(); + state.store.put_message(&endpoint).await.unwrap(); + let mut sandbox = Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "sandbox-id".into(), + name: "demo".into(), + workspace: "default".into(), + ..Default::default() + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Ready.into()); + state.store.put_message(&sandbox).await.unwrap(); + let (client_io, server_io) = tokio::io::duplex(8192); + let application = tokio::spawn(async move { + hyper::server::conn::http1::Builder::new().serve_connection(TokioIo::new(server_io),service_fn(|request:Request|async move { + assert!(!request.headers().contains_key(header::AUTHORIZATION)); + assert!(request.headers().get(header::COOKIE).is_none_or(|v|!v.to_str().unwrap().contains("__Host-openshell-"))); + let _=request.into_body().collect().await.unwrap(); + let mut response=Response::new(Body::from("Sandbox application

Application reached

")); + response.headers_mut().insert(header::CONTENT_TYPE,"text/html".parse().unwrap()); + response.headers_mut().insert(header::SET_COOKIE,"application_session=app-cookie; Secure; HttpOnly; SameSite=Strict".parse().unwrap()); + Ok::<_,std::convert::Infallible>(response) + })).await.unwrap(); + }); + let (mut sender, connection) = + hyper::client::conn::http1::handshake(TokioIo::new(client_io)) + .await + .unwrap(); + let connection = tokio::spawn(connection); + sender.ready().await.unwrap(); + state + .service_upstreams + .put(&upstream_pool_key("endpoint-id", 8080), sender); + let acceptor = crate::TlsAcceptor::from_files( + &dir.path().join("server-cert.pem"), + &dir.path().join("server-key.pem"), + None, + false, + None, + None, + vec![], + ) + .unwrap(); + let (shutdown, rx) = tokio::sync::watch::channel(false); + let server = tokio::spawn(crate::serve_gateway_listener( + crate::BoundGatewayListener { + listener, + address: addr, + }, + crate::multiplex::MultiplexService::new(state), + Some(acceptor), + false, + rx, + )); + let mut child = tokio::process::Command::new("node") + .arg(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/browser-service-auth.cjs" + )) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let mut stdin = child.stdin.take().unwrap(); + stdin.write_all(&serde_json::to_vec(&serde_json::json!({"gateway":format!("https://gateway.example.test:{}",addr.port()),"application":format!("https://default--demo--web.services.example.com:{}",addr.port()),"token":token})).unwrap()).await.unwrap(); + drop(stdin); + let output = tokio::time::timeout(Duration::from_secs(75), child.wait_with_output()) + .await + .unwrap() + .unwrap(); + let _ = shutdown.send(true); + server.await.unwrap(); + connection.abort(); + application.abort(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(String::from_utf8_lossy(&output.stdout).contains("PASS browser cross-site login")); + } + fn endpoint() -> ServiceEndpoint { ServiceEndpoint { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { @@ -1526,6 +2024,18 @@ mod tests { ); } + #[test] + fn authenticated_gateway_url_preserves_tls_on_loopback() { + let mut cfg = openshell_core::Config::new(Some(tls_config())) + .with_bind_address("127.0.0.1:8080".parse().unwrap()) + .with_server_sans(["*.dev.openshell.localhost"]); + cfg.supervisor_app_listener.enabled = true; + assert_eq!( + endpoint_url(&cfg, "default", "my-sandbox", "web").as_deref(), + Some("https://default--my-sandbox--web.dev.openshell.localhost:8080/") + ); + } + #[test] fn endpoint_url_omits_service_label_for_empty_service_name() { let cfg = openshell_core::Config::new(Some(tls_config())) diff --git a/crates/openshell-server/tests/browser-service-auth.cjs b/crates/openshell-server/tests/browser-service-auth.cjs new file mode 100644 index 0000000000..d2739d2319 --- /dev/null +++ b/crates/openshell-server/tests/browser-service-auth.cjs @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Optional real-browser fixture. CDP uses anonymous pipes, a disposable profile, +// loopback-only hostname resolution, and a disposable test issuer credential. +const { spawn } = require('node:child_process'); +const { mkdtempSync, rmSync } = require('node:fs'); +const { tmpdir } = require('node:os'); +const { join } = require('node:path'); + +async function main() { + let input = ''; + for await (const chunk of process.stdin) input += chunk; + const { gateway, application, token } = JSON.parse(input); + const profile = mkdtempSync(join(tmpdir(), 'openshell-auth-browser-')); + const chrome = spawn(process.env.OPENSHELL_BROWSER_E2E_CHROME, [ + '--headless=new', '--remote-debugging-pipe', '--no-first-run', + '--no-default-browser-check', '--disable-background-networking', + '--ignore-certificate-errors', '--no-proxy-server', + '--host-resolver-rules=MAP gateway.example.test 127.0.0.1, MAP *.services.example.com 127.0.0.1', + `--user-data-dir=${profile}`, + ], { stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'] }); + const pending = new Map(); + let next = 0; + let buffered = ''; + chrome.stdio[4].on('data', chunk => { + buffered += chunk.toString(); + for (let end; (end = buffered.indexOf('\0')) >= 0;) { + const message = JSON.parse(buffered.slice(0, end)); + buffered = buffered.slice(end + 1); + const waiter = pending.get(message.id); + if (waiter) { + pending.delete(message.id); + if (message.error) waiter.reject(new Error(message.error.message)); + else waiter.resolve(message.result); + } + } + }); + const call = (method, params = {}, sessionId) => new Promise((resolve, reject) => { + const id = ++next; + const timeout = setTimeout(() => { pending.delete(id); reject(new Error(`CDP timeout: ${method}`)); }, 10000); + pending.set(id, { resolve: result => { clearTimeout(timeout); resolve(result); }, reject: error => { clearTimeout(timeout); reject(error); } }); + chrome.stdio[3].write(JSON.stringify({ id, method, params, sessionId }) + '\0'); + }); + try { + const { targetId } = await call('Target.createTarget', { url: 'about:blank' }); + const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true }); + await call('Page.enable', {}, sessionId); + const evaluate = async expression => { + const result = await call('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, sessionId); + if (result.exceptionDetails) throw new Error('Browser evaluation failed'); + return result.result.value; + }; + const waitFor = async expression => { + const until = Date.now() + 15000; + while (Date.now() < until) { + try { if (await evaluate(expression)) return; } catch { /* Navigation can replace the execution context. */ } + await new Promise(resolve => setTimeout(resolve, 100)); + } + throw new Error(`Browser flow did not converge: ${await evaluate('location.origin + " " + document.title')}`); + }; + await call('Page.navigate', { url: `${gateway}/auth/services?service_origin=${encodeURIComponent(application)}` }, sessionId); + await waitFor(`location.origin === ${JSON.stringify(gateway)} && !!document.getElementById('token')`); + await evaluate(`document.getElementById('token').value=${JSON.stringify(token)};document.getElementById('login').requestSubmit();true`); + await waitFor(`location.origin === ${JSON.stringify(application)} && !!document.getElementById('application')`); + const { cookies } = await call('Network.getCookies', { urls: [application] }, sessionId); + const session = cookies.find(cookie => cookie.name === '__Host-openshell-service-session'); + if (!session || !session.secure || !session.httpOnly || session.sameSite !== 'Strict') throw new Error('Missing protected session cookie'); + if ((await evaluate('document.cookie')).includes('__Host-openshell-')) throw new Error('Gateway cookie exposed to application JavaScript'); + if (await evaluate(`fetch('/echo',{method:'POST',body:'application request'}).then(r=>r.status)`) !== 200) throw new Error('Authenticated application POST failed'); + if (await evaluate(`fetch('/.openshell/service-auth/session',{method:'DELETE'}).then(r=>r.status)`) !== 204) throw new Error('Logout failed'); + if (await evaluate(`fetch('/').then(r=>r.status)`) !== 401) throw new Error('Logged-out browser retained access'); + process.stdout.write('PASS browser cross-site login, Strict/HttpOnly cookies, authenticated POST, and logout\n'); + } finally { + if (chrome.exitCode === null && chrome.signalCode === null) { + chrome.kill('SIGKILL'); + await new Promise(resolve => chrome.once('exit', resolve)); + } + rmSync(profile, { recursive: true, force: true }); + } +} +main().catch(error => { process.stderr.write(error.message + '\n'); process.exitCode = 1; }); diff --git a/crates/openshell-supervisor/src/app_listener.rs b/crates/openshell-supervisor/src/app_listener.rs index 455e0c810e..55bdfbe7d5 100644 --- a/crates/openshell-supervisor/src/app_listener.rs +++ b/crates/openshell-supervisor/src/app_listener.rs @@ -922,6 +922,8 @@ fn gateway_header(name: &str) -> bool { matches!( name, "proxy-authorization" + | "x-openshell-authorization" + | "x-openshell-auth-source" | "cf-access-jwt-assertion" | "cf-access-authenticated-user-email" | "x-openshell-principal" @@ -1015,6 +1017,10 @@ fn sanitize_headers(headers: &mut http::HeaderMap, passthrough: bool, websocket: cookie.split_once('=').is_some_and(|(name, _)| { !name.trim().eq_ignore_ascii_case("CF_Authorization") && !name.trim().eq_ignore_ascii_case("cf-authorization") + && !name + .trim() + .to_ascii_lowercase() + .starts_with("__host-openshell-") }) }) .map(str::trim) @@ -2131,14 +2137,34 @@ mod tests { let mut headers = http::HeaderMap::new(); headers.insert( header::COOKIE, - "app=session; CF_Authorization=secret".parse().unwrap(), + "app=session; CF_Authorization=secret; __Host-openshell-service-session=secret; __Host-openshell-service-login=secret".parse().unwrap(), ); headers.insert("x-forwarded-client-cert", "secret".parse().unwrap()); + headers.insert( + "x-openshell-authorization", + "Bearer secret".parse().unwrap(), + ); + headers.insert("x-openshell-auth-source", "forged".parse().unwrap()); headers.insert(header::CONNECTION, "x-internal".parse().unwrap()); headers.insert("x-internal", "secret".parse().unwrap()); + headers.insert( + header::AUTHORIZATION, + "Bearer application-token".parse().unwrap(), + ); + let mut passthrough = headers.clone(); + assert!(sanitize_headers(&mut passthrough, true, false)); + assert_eq!( + passthrough[header::AUTHORIZATION], + "Bearer application-token" + ); + assert_eq!(passthrough[header::COOKIE], "app=session"); + assert!(!passthrough.contains_key("x-openshell-authorization")); assert!(sanitize_headers(&mut headers, false, false)); + assert!(!headers.contains_key(header::AUTHORIZATION)); assert_eq!(headers[header::COOKIE], "app=session"); assert!(!headers.contains_key("x-forwarded-client-cert")); + assert!(!headers.contains_key("x-openshell-authorization")); + assert!(!headers.contains_key("x-openshell-auth-source")); assert!(!headers.contains_key("x-internal")); } #[tokio::test] diff --git a/docs/how-it-works/gateways/authentication.mdx b/docs/how-it-works/gateways/authentication.mdx index 9c05a5bf5d..83cc71d137 100644 --- a/docs/how-it-works/gateways/authentication.mdx +++ b/docs/how-it-works/gateways/authentication.mdx @@ -8,7 +8,110 @@ keywords: "Generative AI, Cybersecurity, Gateway, Authentication, mTLS, OIDC, Op position: 1 --- -This page describes how the CLI resolves a gateway, authenticates with it, and where credentials are stored. For how to deploy or register gateways, refer to [Gateways](/how-it-works/gateways/overview). +This page describes gateway authentication for CLI clients and sandbox service requests. For how to deploy or register gateways, refer to [Gateways](/how-it-works/gateways/overview). + +## Sandbox service requests + +Gateway-mediated HTTP requests and WebSocket upgrades authenticate with the +configured gateway identity and require workspace user access. OIDC users need +the configured user or admin role and, when scope enforcement is enabled, +`sandbox:write` or `openshell:all`, matching TCP forwarding. Discovery-only access +does not grant application access. This applies with the supervisor app listener +enabled or disabled. Only explicitly enabled unauthenticated local development +bypasses the gate. Existing unauthenticated service clients must supply gateway +credentials in authenticated deployments. + +For a request that uses only gateway bearer authentication: + +```shell +curl --header "Authorization: Bearer ${GATEWAY_ACCESS_TOKEN}" \ + https://default--my-sandbox--web.gateway.example.com/ +``` + +The gateway consumes that header. When an application also needs its own bearer +token, enable the service's `bearer-passthrough` mode and separate the credentials: + +```shell +curl --header "X-OpenShell-Authorization: Bearer ${GATEWAY_ACCESS_TOKEN}" \ + --header "Authorization: Bearer ${APPLICATION_ACCESS_TOKEN}" \ + https://default--my-sandbox--web.gateway.example.com/ +``` + +A verified mTLS identity or browser session can also supply gateway authentication +while `Authorization` carries the application's token. The gateway strips its +own headers and reserved cookies before forwarding. Application cookies retain +their normal behavior; applications cannot overwrite reserved gateway cookies. +Missing, invalid, expired, or gateway-revoked credentials return 401 before any +application connection. Role, scope, membership, and origin denials return 403. + +### Browser sessions + +Open the control-plane gateway's sign-in page with the gateway-mediated service +origin as `service_origin`, for example: + +```text +https://gateway.example.com/auth/services?service_origin=https%3A%2F%2Fdefault--my-sandbox--web.gateway.example.com +``` + +The browser first visits the service to establish login state, then returns to +the control-plane sign-in page. Verify that page's gateway origin and target +service, and supply an access token obtained through your configured identity +provider. The gateway sends a single-use code to the service origin and installs +a host-only, Secure, HttpOnly, SameSite=Strict session cookie. Application +JavaScript never receives the gateway token. Configured mTLS browser users can +instead access the service directly with their client certificate. + +Browser login requires HTTPS to the gateway itself; forwarded scheme or identity +headers cannot enable it. The gateway stores token material through its configured +credential driver, which must support storing session secrets. Replicas must +share the database and credential backend/key. Direct bearer and mTLS requests +do not require browser session storage. +Login codes expire after two minutes. Sessions expire after ten minutes or the +token's expiration, whichever comes first; sign in again rather than silently +refreshing the token. Every request revalidates the token and current workspace +membership. Each workspace admits at most 1,024 pending and active sessions; +expired sessions are cleaned up during login. + +Cookie and mTLS requests require a matching Origin for unsafe HTTP methods and +WebSocket upgrades. Cross-origin browser requests are rejected. Headless mTLS +clients making unsafe requests must also provide the matching Origin. Explicit +bearer headers avoid ambient browser credentials. WebSockets authenticate at +upgrade; an established connection is not continuously reauthenticated. + +### Logout and credential revocation + +From application-origin JavaScript, log out with: + +```javascript +await fetch('/.openshell/service-auth/session', { method: 'DELETE' }); +``` + +The gateway deletes the session in the shared store and expires its cookie, so +replaying that cookie against another replica fails. To revoke application access +for the current gateway bearer token or verified client certificate, use +`DELETE /.openshell/service-auth/credential` on the service origin. Include the +matching Origin and an explicit gateway bearer header or verified mTLS identity. +A service-scoped browser cookie can revoke only its own session. For example: + +```shell +curl --request DELETE \ + --header "Origin: https://default--my-sandbox--web.gateway.example.com" \ + --header "Authorization: Bearer ${GATEWAY_ACCESS_TOKEN}" \ + https://default--my-sandbox--web.gateway.example.com/.openshell/service-auth/credential +``` + +Revocation is durable across gateway replicas and rejects subsequent application +requests, including browser sessions using that token. Obtain a new token or +rotate the client certificate to regain access. Revocation targets gateway +application access; it does not revoke the identity provider's token or alter +control-plane RPC credentials. Offline OIDC JWT validation cannot discover an +identity provider's individual-token revocations before token expiry or key +changes; use this gateway revocation endpoint for immediate application cutoff. +The gateway retains certificate revocations and removes expired token revocations; +it admits at most 1,024 outstanding application credential revocations. + +Direct supervisor app-listener access delegates authentication to the ingress +provider. Gateway browser sessions and credentials do not authorize that path. ## Gateway Resolution diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index c42bfd01e5..5f4ede62f1 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2654,3 +2654,14 @@ that a supervisor installed the route or ingress is ready. Upgrade the CLI alongside the gateway when enabling `base_url`. Older CLI versions can replace the public application port with the gateway connection's port. + +Gateway-mediated service URLs use configured gateway authentication and workspace +access controls with the app listener enabled or disabled. See +[application request authentication](/how-it-works/gateways/authentication#sandbox-service-requests) +for browser sessions, application credential passthrough, and revocation. +Direct app-listener authentication belongs to the ingress provider. + +TLS gateways advertise HTTPS for authenticated gateway service access, including +on loopback, so clients can present an mTLS identity. The separate plaintext +loopback service listener cannot accept a client-certificate identity or browser +sessions; use an explicit gateway bearer credential there. diff --git a/docs/how-it-works/sandboxes/overview.mdx b/docs/how-it-works/sandboxes/overview.mdx index 123678e9fe..856cdcbd0d 100644 --- a/docs/how-it-works/sandboxes/overview.mdx +++ b/docs/how-it-works/sandboxes/overview.mdx @@ -595,9 +595,15 @@ openshell service expose demo 50051 agent --backend-http-version 2 Use the printed HTTPS URL with an HTTP/2 client. The sandbox server must accept cleartext HTTP/2 with prior knowledge on the declared loopback port. -OpenShell strips the incoming `Authorization` header by default. Opt a service -into forwarding one valid bearer credential unchanged when the application -performs its own authentication: +Gateway-mediated requests require configured gateway authentication and workspace +access whether the app listener is enabled or disabled. Gateway credentials are +consumed before forwarding. Use a browser session, mTLS identity, or separate +`X-OpenShell-Authorization` gateway header when the application also needs an +`Authorization` header. See [sandbox service authentication](/how-it-works/gateways/authentication#sandbox-service-requests). +Direct app-listener authentication belongs to the ingress provider. + +OpenShell strips application `Authorization` headers by default. Opt a service +into forwarding one valid application bearer credential unchanged: ```shell openshell service expose my-sandbox 4500 \ diff --git a/rfc/0017-sandbox-service-exposure/README.md b/rfc/0017-sandbox-service-exposure/README.md index 310273018d..4da7ee6b2e 100644 --- a/rfc/0017-sandbox-service-exposure/README.md +++ b/rfc/0017-sandbox-service-exposure/README.md @@ -152,13 +152,15 @@ The ingress policy schema needs definition. Existing egress rules must not impli Application TLS is configured separately from gateway TLS. Operators provide DNS and certificates; `svc.openshell.internal` is an example domain. Certificate provisioning and rotation remain open questions. -SNI selects a route; it does not authenticate a user. Applications can handle authentication, or operators can apply an edge access policy. Preserve existing header handling: strip `Authorization` by default, allow explicit `bearer-passthrough`, and strip gateway/edge identity headers and edge authentication cookies. Native OpenShell user/workspace authorization is not the proposed default for application requests. +SNI selects a route; it does not authenticate a user. Direct app-listener access delegates authentication to the ingress provider; implementing that authentication is outside this proposal. Preserve existing listener header handling: strip `Authorization` by default, allow explicit `bearer-passthrough`, and strip gateway/edge identity headers and edge authentication cookies. + +Gateway-mediated application HTTP requests and WebSocket upgrades use configured gateway authentication and workspace authorization independently of app-listener enablement, as tracked by #4722. Use the TCP-forwarding access policy, including `sandbox:write` when scopes are enforced. Keep gateway credentials separate from application bearer passthrough and cookies; consume and strip gateway material before forwarding. Browser sessions require a control-plane login flow, origin/CSRF protections, and revocation. Missing, invalid, expired, or revoked credentials fail before application dial; insufficient permissions return 403. WebSockets authenticate at upgrade. Explicit unauthenticated local-development configurations retain their documented behavior. A passthrough proxy cannot inspect HTTP credentials. An edge that terminates TLS must reconnect with the correct service SNI and authority. Restrict supervisor listener access to prevent bypassing required edge authentication; use authenticated backend transport where network restrictions are insufficient. ### Deployment and compatibility -Enable the new path explicitly and retain existing gateway-mode behavior. CLI/SDK URLs must use the application ingress domain and public port independently of the gateway endpoint. Status should distinguish configured, advertised, and unavailable routes. Domain migrations require coordinated DNS, TLS, and client changes. +Enable the app-listener path explicitly. Gateway-mediated service clients independently require configured gateway credentials and workspace access; TLS gateway URLs retain HTTPS on loopback to support client certificates. CLI/SDK URLs must use the application ingress domain and public port independently of the gateway endpoint. Status should distinguish configured, advertised, and unavailable routes. Domain migrations require coordinated DNS, TLS, and client changes. ## Implementation plan diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 663494e929..9613cc8306 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1994,6 +1994,23 @@ an app domain need distinct gateway names; replicas of one installation share its name. Changing the mode or installation name requires fresh route installation before discovery can advertise the replacement. +Gateway-mediated service HTTP requests and WebSocket upgrades require configured +gateway authentication and workspace user access with the app listener disabled +or enabled. OIDC scope enforcement requires `sandbox:write` (or `openshell:all`), +as for TCP forwarding. Check HTTP 401 for missing/invalid/expired/revoked +credentials and 403 for role/scope/membership/origin denial. Browser login starts +at the control-plane `/auth/services?service_origin=...`; the app host receives +only a single-use code and a Secure/HttpOnly cookie. Check shared database and +credential-driver availability across replicas. Browser sessions expire within +ten minutes and reauthorize on every request. DELETE the same-origin app paths +`/.openshell/service-auth/session` to log out or +`/.openshell/service-auth/credential` to revoke the current application-access +credential. `X-OpenShell-Authorization` separates gateway bearer auth from an +application Authorization header. Gateway headers and reserved cookies are +stripped; application cookies and explicit bearer passthrough remain available. +Only explicit local-development unauthenticated access bypasses gateway auth. +Direct listener authentication belongs to the ingress provider. + ## Azure PostgreSQL workload identity When `database_auth = "azure-workload-identity"` is configured, verify the gateway From f468c34962c91abaf042f0fcce01c97461e37355 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Wed, 4 Nov 2026 10:38:47 -0800 Subject: [PATCH 02/15] test(auth): use shared TLS test imports after rebase Signed-off-by: Taylor Mutch --- crates/openshell-server/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 2b886c5644..1d2e4e70fc 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -4166,7 +4166,7 @@ mod tests { use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, pem::PemObject}; let dir = tempdir().unwrap(); let (ca, ca_key) = generate_test_certs_with_ca(dir.path()); - let mut params = rcgen::CertificateParams::new(Vec::::new()).unwrap(); + let mut params = CertificateParams::new(Vec::::new()).unwrap(); params .distinguished_name .push(rcgen::DnType::CommonName, "application-user"); @@ -4228,7 +4228,7 @@ mod tests { let stream = openshell_core::net::connect_tcp_nodelay_best_effort(addr) .await .unwrap(); - let mut stream = tokio_rustls::TlsConnector::from(Arc::new(config)) + let mut stream = TlsConnector::from(Arc::new(config)) .connect(ServerName::try_from("localhost").unwrap(), stream) .await .unwrap(); From 70deeb097a82f12100c2199dad3d0ade4f9239f5 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Fri, 6 Nov 2026 09:16:10 -0800 Subject: [PATCH 03/15] test(auth): cover issuer-backed application session credentials Signed-off-by: Taylor Mutch --- crates/openshell-server/src/credentials.rs | 73 +++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/crates/openshell-server/src/credentials.rs b/crates/openshell-server/src/credentials.rs index 7d2e93fd75..61e0f6a2bd 100644 --- a/crates/openshell-server/src/credentials.rs +++ b/crates/openshell-server/src/credentials.rs @@ -67,7 +67,8 @@ impl CredentialRuntime { .await?; handles .remove("gateway-access-token") - .ok_or_else(|| Status::internal("application credential handle missing")) + .filter(|handle| !handle.handle.is_empty()) + .ok_or_else(|| Status::internal("empty or missing application credential handle")) } pub async fn resolve_application_token( @@ -452,6 +453,76 @@ mod tests { } } + #[tokio::test] + async fn application_tokens_preserve_issuer_scope_and_backend_ownership() { + let storage = tempfile::tempdir().unwrap(); + let key_path = storage.path().join("key-encryption-key.bin"); + let store = Arc::new(crate::persistence::test_store().await); + let file = config_file(&format!( + "[openshell.gateway.credential_storage]\nkey_encryption_key_path = {}\n", + toml_path(&key_path), + )); + let runtime = + CredentialRuntime::from_config_file_with_store(&Config::new(None), Some(&file), store) + .await + .unwrap(); + let handle = runtime + .store_application_token("workspace-a", "session-a", "session-secret") + .await + .unwrap(); + assert_eq!( + runtime + .resolve_application_token("workspace-a", "session-a", handle.clone()) + .await + .unwrap(), + "session-secret" + ); + // Storage validates provider/key ownership; the gateway retains + // workspace/session authorization before resolving its private handle. + for (provider, key) in [ + ("another-provider", "gateway-access-token"), + ("gateway-service-session", "another-key"), + ] { + assert!( + runtime + .resolve_secrets( + SecretOwner::provider("workspace-a", "service-session-session-a", provider), + &Handles::from([(key.into(), handle.clone())]), + openshell_core::time::now_ms(), + ) + .await + .is_err() + ); + } + // The explicit owner kind must preserve the already deployed driver scope. + let resolved = runtime + .resolve_secrets( + SecretOwner::provider( + "workspace-a", + "service-session-session-a", + "gateway-service-session", + ), + &Handles::from([("gateway-access-token".into(), handle.clone())]), + openshell_core::time::now_ms(), + ) + .await + .unwrap(); + assert_eq!( + resolved.values.get("gateway-access-token").unwrap(), + "session-secret" + ); + runtime + .delete_application_token("workspace-a", "session-a", handle.clone()) + .await + .unwrap(); + assert!( + runtime + .resolve_application_token("workspace-a", "session-a", handle) + .await + .is_err() + ); + } + #[tokio::test] async fn embedded_test_hooks_share_the_trait_backed_issuer_across_clones() { let runtime = CredentialRuntime::from_config( From ff79fdccfeb1b88015dccf5395d8729293299927 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Fri, 6 Nov 2026 10:37:15 -0800 Subject: [PATCH 04/15] feat(auth): make gateway service authentication opt-in Signed-off-by: Taylor Mutch --- crates/openshell-core/src/config.rs | 14 + crates/openshell-server/README.md | 8 +- crates/openshell-server/src/auth/http.rs | 9 +- .../src/auth/service_session.rs | 2 + crates/openshell-server/src/cli.rs | 44 ++ .../openshell-server/src/config_file/mod.rs | 3 + crates/openshell-server/src/lib.rs | 8 +- .../openshell-server/src/service_routing.rs | 385 ++++++++++++------ deploy/helm/openshell/README.md | 1 + deploy/helm/openshell/templates/_toml.tpl | 2 +- .../openshell/tests/gateway_config_test.yaml | 25 ++ deploy/helm/openshell/values.yaml | 3 + deploy/man/openshell-gateway.8.md | 5 + docs/how-it-works/gateways/authentication.mdx | 10 +- docs/how-it-works/gateways/configuration.mdx | 19 +- skills/debug-openshell-cluster/SKILL.md | 18 +- 16 files changed, 416 insertions(+), 140 deletions(-) diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index 2d3f37c7eb..32fd08ce57 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -517,6 +517,10 @@ pub struct Config { pub struct ServiceRoutingConfig { /// Publish gateway URLs and forward application requests through the gateway. pub enabled: bool, + /// Opt in to gateway authentication for proxied application requests. + /// Independent of the supervisor application listener. + pub auth_enabled: bool, + /// Base domains accepted for `sandbox--service.` routes. /// The first domain is used when the gateway prints endpoint URLs. pub base_domains: Vec, @@ -1583,6 +1587,13 @@ impl Config { self } + /// Opt in to configured gateway authentication on application requests. + #[must_use] + pub const fn with_service_auth(mut self, enabled: bool) -> Self { + self.service_routing.auth_enabled = enabled; + self + } + /// Enable or disable plaintext HTTP routing for loopback sandbox service /// hostnames on TLS-enabled gateway listeners. #[must_use] @@ -1603,6 +1614,7 @@ impl Default for ServiceRoutingConfig { fn default() -> Self { Self { enabled: true, + auth_enabled: false, base_domains: default_service_routing_domains(), enable_loopback_service_http: default_enable_loopback_service_http(), service_hostname_format: ServiceHostnameFormat::default(), @@ -2182,6 +2194,8 @@ mod tests { vec![DEFAULT_SERVICE_ROUTING_DOMAIN.to_string()] ); assert!(cfg.service_routing.enable_loopback_service_http); + assert!(!cfg.service_routing.auth_enabled); + assert!(cfg.with_service_auth(true).service_routing.auth_enabled); } #[test] diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index 3561a234f5..394fbd115c 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -476,7 +476,13 @@ equality tokens, not resumable cursors or an ordering across gateway replicas. ## Gateway application authentication -Gateway-mediated application HTTP requests and WebSocket upgrades authenticate +Gateway service authentication defaults to disabled, independently of the app +listener. Disabled mode preserves application routing, reserved-looking paths, +and the pre-existing header/cookie policy. CLI `--service-auth-enabled` and +`OPENSHELL_SERVICE_AUTH_ENABLED` override the TOML setting. + +With `[openshell.gateway].service_auth_enabled = true`, gateway-mediated +application HTTP requests and WebSocket upgrades authenticate through the gateway chain or verified TLS client identity before endpoint lookup, independently of app-listener enablement. User access requires TCP-forwarding role/scope policy (`sandbox:write` when enforced) and current workspace membership; diff --git a/crates/openshell-server/src/auth/http.rs b/crates/openshell-server/src/auth/http.rs index 1ec91db2ae..03f8f3ce65 100644 --- a/crates/openshell-server/src/auth/http.rs +++ b/crates/openshell-server/src/auth/http.rs @@ -90,11 +90,14 @@ fn sanitize_callback_host(raw: &Option) -> (String, String) { /// Create the auth router. pub fn router(state: Arc) -> Router { - Router::new() - .route( + let mut router = Router::new(); + if state.config.service_routing.auth_enabled { + router = router.route( "/auth/services", get(service_browser_login).post(service_browser_login), - ) + ); + } + router .route("/auth/connect", get(auth_connect)) .route("/auth/oidc-config", get(oidc_config_handler)) .route("/.well-known/jwks.json", get(gateway_jwks_handler)) diff --git a/crates/openshell-server/src/auth/service_session.rs b/crates/openshell-server/src/auth/service_session.rs index 5785a0db8e..14b5954db6 100644 --- a/crates/openshell-server/src/auth/service_session.rs +++ b/crates/openshell-server/src/auth/service_session.rs @@ -813,6 +813,7 @@ pub mod tests { let mut state = test_server_state().await; let inner = Arc::get_mut(&mut state).unwrap(); inner.config.auth.allow_unauthenticated_users = false; + inner.config.service_routing.auth_enabled = true; inner.config.service_routing.base_domains = vec!["services.example.com".into()]; inner.config.oidc = Some(serde_json::from_value(serde_json::json!({"issuer":server.uri(),"audience":"openshell-cli","scopes_claim":"scope"})).unwrap()); inner.admin_role = "openshell-admin".into(); @@ -1299,6 +1300,7 @@ pub mod tests { let inner = Arc::get_mut(&mut state).unwrap(); inner.config.service_routing.base_domains = vec!["services.example.com".into()]; inner.config.auth.allow_unauthenticated_users = false; + inner.config.service_routing.auth_enabled = true; inner.config.mtls_auth.enabled = true; let peer = ServicePeer { secure: true, diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index c2aedba17d..e4939dc37f 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -351,6 +351,10 @@ struct RunArgs { )] server_sans: Vec, + /// Authenticate sandbox application requests using configured gateway auth. + #[arg(long, env = "OPENSHELL_SERVICE_AUTH_ENABLED", default_value_t = false, action = ArgAction::Set)] + service_auth_enabled: bool, + /// Hostname format for exposed sandbox services: `readable` (default) /// keeps `--[--]` hostnames; `hashed` mints /// opaque one-label hostnames discriminated by the gateway installation @@ -759,6 +763,7 @@ fn assemble_server_config( .with_server_sans(args.server_sans.clone()) .with_service_hostname_format(args.service_hostname_format.unwrap_or_default()) .with_service_routing(args.enable_gateway_service_routing) + .with_service_auth(args.service_auth_enabled) .with_loopback_service_http(args.enable_loopback_service_http) .with_websocket_tunnel(args.enable_websocket_tunnel); config @@ -1896,6 +1901,11 @@ fn merge_file_into_args(args: &mut RunArgs, file: &GatewayFileSection, matches: { args.enable_gateway_service_routing = enabled; } + if let Some(enabled) = file.service_auth_enabled + && arg_defaulted(matches, "service_auth_enabled") + { + args.service_auth_enabled = enabled; + } if let Some(enabled) = file.enable_loopback_service_http && arg_defaulted(matches, "enable_loopback_service_http") { @@ -4853,6 +4863,40 @@ enabled = false }); } + #[test] + fn service_auth_is_opt_in_with_explicit_cli_environment_and_file_precedence() { + Environment::new() + .remove("OPENSHELL_SERVICE_AUTH_ENABLED") + .run(|| { + let file = toml::from_str::( + "[openshell.gateway]\nservice_auth_enabled = true\n", + ) + .unwrap(); + let (mut args, matches) = parse_with_args(&["openshell-gateway"]); + assert!(!args.service_auth_enabled); + merge_file_into_args(&mut args, &file.openshell.gateway, &matches); + assert!(args.service_auth_enabled); + let (mut args, matches) = + parse_with_args(&["openshell-gateway", "--service-auth-enabled", "false"]); + merge_file_into_args(&mut args, &file.openshell.gateway, &matches); + assert!(!args.service_auth_enabled); + }); + Environment::new() + .set("OPENSHELL_SERVICE_AUTH_ENABLED", "false") + .run(|| { + let file = toml::from_str::( + "[openshell.gateway]\nservice_auth_enabled = true\n", + ) + .unwrap(); + let (mut args, matches) = parse_with_args(&["openshell-gateway"]); + merge_file_into_args(&mut args, &file.openshell.gateway, &matches); + assert!(!args.service_auth_enabled); + let (args, _) = + parse_with_args(&["openshell-gateway", "--service-auth-enabled", "true"]); + assert!(args.service_auth_enabled); + }); + } + #[test] fn operator_auth_is_opt_in_and_file_flag_precedence_is_explicit() { Environment::new() diff --git a/crates/openshell-server/src/config_file/mod.rs b/crates/openshell-server/src/config_file/mod.rs index 5c2bdf606e..f98caef54f 100644 --- a/crates/openshell-server/src/config_file/mod.rs +++ b/crates/openshell-server/src/config_file/mod.rs @@ -196,6 +196,9 @@ pub struct GatewayFileSection { /// Publish gateway URLs and forward application requests. Defaults to true. #[serde(default)] pub enable_gateway_service_routing: Option, + /// Opt in to gateway authentication for sandbox application requests. + #[serde(default)] + pub service_auth_enabled: Option, /// Subject Alternative Names configured on the gateway server certificate. /// Wildcard DNS SANs also enable sandbox service URLs under that domain. #[serde(default)] diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 1d2e4e70fc..2d8aa3e714 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -4176,12 +4176,14 @@ mod tests { let client_cert = CertificateDer::from(client.der().to_vec()); let key_pem = client_key.serialize_pem().unwrap(); let client_key = PrivateKeyDer::from_pem_slice(key_pem.as_bytes()).unwrap(); - for enabled in [false, true] { + for (enabled, auth_enabled) in [(false, false), (false, true), (true, false), (true, true)] + { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); let mut state = test_state(addr, false).await; let inner = Arc::get_mut(&mut state).unwrap(); inner.config.auth.allow_unauthenticated_users = false; + inner.config.service_routing.auth_enabled = auth_enabled; inner.config.mtls_auth.enabled = true; inner.config.supervisor_app_listener.enabled = enabled; inner.config.tls = Some(openshell_core::TlsConfig { @@ -4245,12 +4247,12 @@ mod tests { .unwrap(); let response = String::from_utf8_lossy(&response); assert!( - response.starts_with(if authenticated { + response.starts_with(if authenticated || !auth_enabled { "HTTP/1.1 404" } else { "HTTP/1.1 401" }), - "listener={enabled}, authenticated={authenticated}: {response}" + "listener={enabled}, auth={auth_enabled}, authenticated={authenticated}: {response}" ); } stop_listener(shutdown, handle).await; diff --git a/crates/openshell-server/src/service_routing.rs b/crates/openshell-server/src/service_routing.rs index fba3d093eb..c62cbeec04 100644 --- a/crates/openshell-server/src/service_routing.rs +++ b/crates/openshell-server/src/service_routing.rs @@ -191,7 +191,7 @@ fn endpoint_scheme(config: &openshell_core::Config) -> &'static str { && !config.mtls_auth.enabled && !config.mtls_auth.operator_enabled && config.oidc.is_none() - && !config.supervisor_app_listener.enabled) + && !config.service_routing.auth_enabled) { "http" } else { @@ -518,12 +518,6 @@ pub async fn proxy_sandbox_service_request( state: Arc, mut req: Request, ) -> impl IntoResponse { - if !state.config.service_routing.enabled { - return service_error_response( - StatusCode::NOT_FOUND, - "Gateway service routing is disabled", - ); - } let Some(host) = request_host(&req).map(str::to_string) else { return StatusCode::NOT_FOUND.into_response(); }; @@ -537,20 +531,29 @@ pub async fn proxy_sandbox_service_request( } = target; let service_name = service.unwrap_or_default(); - if req - .uri() - .path() - .starts_with(crate::auth::service_session::PREFIX) - { - return match crate::auth::service_session::handle(&state, &mut req, &workspace).await { - Ok(response) => response, - Err(error) => crate::auth::service_session::error(&error), - }; + if !state.config.service_routing.enabled { + return service_error_response( + StatusCode::NOT_FOUND, + "Gateway service routing is disabled", + ); } - if let Err(error) = - crate::auth::service_session::authorize_request(&state, &mut req, &workspace).await - { - return crate::auth::service_session::error(&error); + + if state.config.service_routing.auth_enabled { + if req + .uri() + .path() + .starts_with(crate::auth::service_session::PREFIX) + { + return match crate::auth::service_session::handle(&state, &mut req, &workspace).await { + Ok(response) => response, + Err(error) => crate::auth::service_session::error(&error), + }; + } + if let Err(error) = + crate::auth::service_session::authorize_request(&state, &mut req, &workspace).await + { + return crate::auth::service_session::error(&error); + } } match proxy_to_endpoint(state, req, &workspace, sandbox_name, service_name).await { @@ -770,7 +773,13 @@ async fn proxy_to_endpoint( None => open_upstream(&state, &sandbox, &endpoint, target_port, websocket_upgrade).await?, }; - let upstream = build_upstream_request(req, target_port, websocket_upgrade, authorization_mode)?; + let upstream = build_upstream_request( + req, + target_port, + websocket_upgrade, + authorization_mode, + state.config.service_routing.auth_enabled, + )?; let replay = reused.then(|| replayable_request(&upstream)).flatten(); let first_attempt = if reused { sender.try_send_request(upstream).await.map_err(|mut err| { @@ -834,12 +843,16 @@ async fn proxy_to_endpoint( }); let (mut parts, _) = response.into_parts(); - crate::auth::service_session::strip_response_cookies(&mut parts.headers); + if state.config.service_routing.auth_enabled { + crate::auth::service_session::strip_response_cookies(&mut parts.headers); + } return Ok(Response::from_parts(parts, Body::empty())); } let (mut parts, body) = response.into_parts(); - crate::auth::service_session::strip_response_cookies(&mut parts.headers); + if state.config.service_routing.auth_enabled { + crate::auth::service_session::strip_response_cookies(&mut parts.headers); + } Ok(Response::from_parts(parts, Body::new(body))) } @@ -953,6 +966,7 @@ fn build_upstream_request( target_port: u16, preserve_upgrade_headers: bool, authorization_mode: ServiceAuthorizationMode, + service_auth_enabled: bool, ) -> Result, ServiceRouteError> { let (parts, body) = req.into_parts(); let path = parts.uri.path_and_query().map_or("/", |path| path.as_str()); @@ -971,12 +985,12 @@ fn build_upstream_request( for (name, value) in &parts.headers { if (is_hop_by_hop_header(name) && !(preserve_upgrade_headers && is_websocket_hop_by_hop_header(name))) - || is_gateway_auth_header(name, authorization_mode) + || is_gateway_auth_header(name, authorization_mode, service_auth_enabled) { continue; } if name == header::COOKIE { - if let Some(cookie) = sanitize_cookie_header(value) { + if let Some(cookie) = sanitize_cookie_header(value, service_auth_enabled) { headers.append(name, cookie); } continue; @@ -1115,6 +1129,7 @@ fn is_bearer_token68(value: &str) -> bool { fn is_gateway_auth_header( name: &header::HeaderName, authorization_mode: ServiceAuthorizationMode, + service_auth_enabled: bool, ) -> bool { match name.as_str() { "authorization" => authorization_mode != ServiceAuthorizationMode::BearerPassthrough, @@ -1123,8 +1138,8 @@ fn is_gateway_auth_header( | "x-openshell-principal" | "x-openshell-user" | "x-openshell-roles" - | "cf-access-authenticated-user-email" - | "cf-access-jwt-assertion" + | "cf-access-authenticated-user-email" => service_auth_enabled, + "cf-access-jwt-assertion" | "x-forwarded-client-cert" | "x-ssl-client-cert" | "x-client-cert" => true, @@ -1132,14 +1147,14 @@ fn is_gateway_auth_header( } } -fn sanitize_cookie_header(value: &HeaderValue) -> Option { +fn sanitize_cookie_header(value: &HeaderValue, service_auth_enabled: bool) -> Option { let value = value.to_str().ok()?; let cookies = value .split(';') .filter_map(|cookie| { let cookie = cookie.trim(); let (name, _) = cookie.split_once('=')?; - (!is_gateway_auth_cookie(name.trim())).then_some(cookie) + (!is_gateway_auth_cookie(name.trim(), service_auth_enabled)).then_some(cookie) }) .collect::>(); @@ -1150,9 +1165,10 @@ fn sanitize_cookie_header(value: &HeaderValue) -> Option { HeaderValue::from_str(&cookies.join("; ")).ok() } -fn is_gateway_auth_cookie(name: &str) -> bool { +fn is_gateway_auth_cookie(name: &str, service_auth_enabled: bool) -> bool { name.eq_ignore_ascii_case("CF_Authorization") - || name.to_ascii_lowercase().starts_with("__host-openshell-") + || name.eq_ignore_ascii_case("cf-authorization") + || (service_auth_enabled && name.to_ascii_lowercase().starts_with("__host-openshell-")) } pub fn emit_service_endpoint_config_event(endpoint: &ServiceEndpoint, url: &str, created: bool) { @@ -1499,6 +1515,102 @@ mod tests { } } + #[tokio::test] + async fn disabled_service_auth_leaves_application_paths_unreserved_with_either_listener_mode() { + use tower::ServiceExt; + for enabled in [false, true] { + let mut state = crate::grpc::test_support::test_server_state().await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.service_routing = config(); + inner.config.supervisor_app_listener.enabled = enabled; + inner.config.mtls_auth.enabled = true; + inner.config.auth.allow_unauthenticated_users = false; + assert!(!inner.config.service_routing.auth_enabled); + for router in [ + crate::http::http_router(state.clone()), + crate::http::service_http_router(state.clone()), + ] { + for path in ["/", "/.openshell/service-auth/start"] { + for websocket in [false, true] { + let mut req = Request::builder() + .uri(path) + .header(header::HOST, "default--unknown.dev.openshell.localhost") + .header("X-OpenShell-Authorization", "not-a-gateway-token") + .header(header::COOKIE, "__Host-openshell-app=application-cookie"); + if websocket { + req = req + .header(header::CONNECTION, "upgrade") + .header(header::UPGRADE, "websocket"); + } + let response = router + .clone() + .oneshot(req.body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!( + response.status(), + StatusCode::NOT_FOUND, + "auth must be skipped and endpoint lookup reached" + ); + } + } + } + let response = crate::http::http_router(state) + .oneshot( + Request::builder() + .uri("/auth/services") + .header(header::HOST, "gateway.example.com") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + response.status(), + StatusCode::NOT_FOUND, + "browser login is disabled" + ); + } + } + + #[test] + fn disabled_service_auth_preserves_application_owned_headers_and_cookies() { + for enabled in [false, true] { + let req = Request::builder().uri("/.openshell/service-auth/start") + .header(header::AUTHORIZATION, "Bearer application-token") + .header("x-openshell-authorization", "application-header") + .header("cf-access-authenticated-user-email", "application-value") + .header(header::COOKIE, "__Host-openshell-app=app-value; ordinary=retained; cf-authorization=edge-value") + .body(Body::empty()).unwrap(); + let upstream = build_upstream_request( + req, + 8080, + false, + ServiceAuthorizationMode::BearerPassthrough, + enabled, + ) + .unwrap(); + assert_eq!( + upstream.headers()[header::AUTHORIZATION], + "Bearer application-token" + ); + assert_eq!( + upstream.headers().contains_key("x-openshell-authorization"), + !enabled + ); + assert_eq!( + upstream + .headers() + .contains_key("cf-access-authenticated-user-email"), + !enabled + ); + let cookies = upstream.headers()[header::COOKIE].to_str().unwrap(); + assert_eq!(cookies.contains("__Host-openshell-app"), !enabled); + assert!(cookies.contains("ordinary=retained")); + assert!(!cookies.contains("cf-authorization")); + } + } + #[tokio::test] async fn gateway_application_auth_gates_http_and_websocket_on_both_routers() { use crate::auth::{ @@ -1514,6 +1626,7 @@ mod tests { inner.config.mtls_auth.enabled = true; inner.config.auth.allow_unauthenticated_users = false; inner.config.service_routing = config(); + inner.config.service_routing.auth_enabled = true; let peer = ServicePeer { identity: Some(Identity { subject: "verified-user".into(), @@ -1614,11 +1727,11 @@ mod tests { .unwrap() }; let mode = effective_authorization_mode(ServiceAuthorizationMode::Strip as i32); - let upstream = build_upstream_request(request(), 8080, false, mode).unwrap(); + let upstream = build_upstream_request(request(), 8080, false, mode, true).unwrap(); assert!(!upstream.headers().contains_key(header::AUTHORIZATION)); assert!(!upstream.headers().contains_key("cf-access-jwt-assertion")); let mode = effective_authorization_mode(ServiceAuthorizationMode::BearerPassthrough as i32); - let upstream = build_upstream_request(request(), 8080, false, mode).unwrap(); + let upstream = build_upstream_request(request(), 8080, false, mode, true).unwrap(); assert_eq!( upstream.headers()[header::AUTHORIZATION], "Bearer gateway-secret" @@ -1626,7 +1739,7 @@ mod tests { } #[tokio::test] - async fn authenticated_gateway_forwards_application_request_without_gateway_identity() { + async fn gateway_service_auth_opt_in_preserves_forwarding_in_all_listener_modes() { use crate::auth::{ identity::{Identity, IdentityProvider}, service_access::ServicePeer, @@ -1636,92 +1749,114 @@ mod tests { use hyper::service::service_fn; use tower::ServiceExt; - let mut state = test_server_state().await; - let inner = Arc::get_mut(&mut state).unwrap(); - inner.config.supervisor_app_listener.enabled = true; - inner.config.mtls_auth.enabled = true; - inner.config.auth.allow_unauthenticated_users = false; - inner.config.service_routing = config(); - let mut endpoint = endpoint(); - endpoint.authorization_mode = ServiceAuthorizationMode::BearerPassthrough as i32; - state.store.put_message(&endpoint).await.unwrap(); - let mut sandbox = Sandbox { - metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { - id: "sandbox-id".into(), - name: "my-sandbox".into(), - workspace: "default".into(), + for (auth_enabled, listener_enabled) in + [(false, false), (false, true), (true, false), (true, true)] + { + let mut state = test_server_state().await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.supervisor_app_listener.enabled = listener_enabled; + inner.config.mtls_auth.enabled = true; + inner.config.auth.allow_unauthenticated_users = false; + inner.config.service_routing = config(); + inner.config.service_routing.auth_enabled = auth_enabled; + let mut endpoint = endpoint(); + endpoint.authorization_mode = ServiceAuthorizationMode::BearerPassthrough as i32; + state.store.put_message(&endpoint).await.unwrap(); + let mut sandbox = Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "sandbox-id".into(), + name: "my-sandbox".into(), + workspace: "default".into(), + ..Default::default() + }), ..Default::default() - }), - ..Default::default() - }; - sandbox.set_phase(SandboxPhase::Ready as i32); - state.store.put_message(&sandbox).await.unwrap(); - - let (client_io, server_io) = tokio::io::duplex(4096); - let server = tokio::spawn(async move { - hyper::server::conn::http1::Builder::new() - .serve_connection( - TokioIo::new(server_io), - service_fn(|request: Request| async move { - assert_eq!(request.method(), Method::POST); - assert_eq!(request.uri().path(), "/app"); - assert!(!request.headers().contains_key(header::AUTHORIZATION)); - assert!(!request.headers().contains_key("x-forwarded-client-cert")); - assert!(!request.headers().contains_key("cf-access-jwt-assertion")); - let body = request.into_body().collect().await.unwrap().to_bytes(); - Ok::<_, std::convert::Infallible>(Response::new(Body::from(body))) - }), + }; + sandbox.set_phase(SandboxPhase::Ready as i32); + state.store.put_message(&sandbox).await.unwrap(); + + let (client_io, server_io) = tokio::io::duplex(4096); + let server = tokio::spawn(async move { + hyper::server::conn::http1::Builder::new() + .serve_connection( + TokioIo::new(server_io), + service_fn(move |request: Request| async move { + assert_eq!(request.method(), Method::POST); + assert_eq!(request.uri().path(), "/app"); + assert!(!request.headers().contains_key(header::AUTHORIZATION)); + assert!(!request.headers().contains_key("x-forwarded-client-cert")); + assert!(!request.headers().contains_key("cf-access-jwt-assertion")); + assert_eq!( + request.headers().contains_key(header::COOKIE), + !auth_enabled + ); + let body = request.into_body().collect().await.unwrap().to_bytes(); + let mut response = Response::new(Body::from(body)); + response.headers_mut().insert( + header::SET_COOKIE, + "__Host-openshell-owned=application-cookie; Secure; Path=/" + .parse() + .unwrap(), + ); + Ok::<_, std::convert::Infallible>(response) + }), + ) + .await + .unwrap(); + }); + let (mut sender, connection) = + hyper::client::conn::http1::handshake(TokioIo::new(client_io)) + .await + .unwrap(); + let connection = tokio::spawn(connection); + sender.ready().await.unwrap(); + state + .service_upstreams + .put(&upstream_pool_key("endpoint-id", 8080), sender); + let peer = ServicePeer { + identity: Some(Identity { + subject: "verified-user".into(), + display_name: None, + roles: vec![], + scopes: vec![], + provider: IdentityProvider::Mtls, + }), + ..Default::default() + }; + let mut request = Request::builder() + .method(Method::POST) + .uri("/app") + .header( + header::ORIGIN, + "https://default--my-sandbox--web.dev.openshell.localhost", ) - .await + .header( + header::HOST, + "default--my-sandbox--web.dev.openshell.localhost", + ) + .header(header::COOKIE, "__Host-openshell-owned=application-cookie") + .header("x-forwarded-client-cert", "forged-user") + .header("cf-access-jwt-assertion", "edge-token") + .body(Body::from("application-payload")) .unwrap(); - }); - let (mut sender, connection) = - hyper::client::conn::http1::handshake(TokioIo::new(client_io)) + if auth_enabled { + request.extensions_mut().insert(peer); + } + let response = crate::http::http_router(state) + .oneshot(request) .await .unwrap(); - let connection = tokio::spawn(connection); - sender.ready().await.unwrap(); - state - .service_upstreams - .put(&upstream_pool_key("endpoint-id", 8080), sender); - let peer = ServicePeer { - identity: Some(Identity { - subject: "verified-user".into(), - display_name: None, - roles: vec![], - scopes: vec![], - provider: IdentityProvider::Mtls, - }), - ..Default::default() - }; - let response = crate::http::http_router(state) - .layer(axum::Extension(peer)) - .oneshot( - Request::builder() - .method(Method::POST) - .uri("/app") - .header( - header::ORIGIN, - "https://default--my-sandbox--web.dev.openshell.localhost", - ) - .header( - header::HOST, - "default--my-sandbox--web.dev.openshell.localhost", - ) - .header("x-forwarded-client-cert", "forged-user") - .header("cf-access-jwt-assertion", "edge-token") - .body(Body::from("application-payload")) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::OK); - assert_eq!( - response.into_body().collect().await.unwrap().to_bytes(), - "application-payload" - ); - connection.abort(); - server.abort(); + assert_eq!( + response.headers().contains_key(header::SET_COOKIE), + !auth_enabled + ); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.into_body().collect().await.unwrap().to_bytes(), + "application-payload" + ); + connection.abort(); + server.abort(); + } } #[tokio::test] @@ -2026,10 +2161,10 @@ mod tests { #[test] fn authenticated_gateway_url_preserves_tls_on_loopback() { - let mut cfg = openshell_core::Config::new(Some(tls_config())) + let cfg = openshell_core::Config::new(Some(tls_config())) .with_bind_address("127.0.0.1:8080".parse().unwrap()) - .with_server_sans(["*.dev.openshell.localhost"]); - cfg.supervisor_app_listener.enabled = true; + .with_server_sans(["*.dev.openshell.localhost"]) + .with_service_auth(true); assert_eq!( endpoint_url(&cfg, "default", "my-sandbox", "web").as_deref(), Some("https://default--my-sandbox--web.dev.openshell.localhost:8080/") @@ -2659,7 +2794,8 @@ mod tests { .unwrap(); let upstream = - build_upstream_request(request, 8080, false, ServiceAuthorizationMode::Strip).unwrap(); + build_upstream_request(request, 8080, false, ServiceAuthorizationMode::Strip, true) + .unwrap(); assert_eq!(upstream.uri(), "/path"); assert!(!upstream.headers().contains_key(header::AUTHORIZATION)); @@ -2682,7 +2818,7 @@ mod tests { let mode = effective_authorization_mode(ServiceAuthorizationMode::Unspecified as i32); validate_application_authorization(&request, mode).unwrap(); - let upstream = build_upstream_request(request, 8080, false, mode).unwrap(); + let upstream = build_upstream_request(request, 8080, false, mode, true).unwrap(); assert_eq!(mode, ServiceAuthorizationMode::Strip); assert!(!upstream.headers().contains_key(header::AUTHORIZATION)); @@ -2705,7 +2841,7 @@ mod tests { let mode = ServiceAuthorizationMode::BearerPassthrough; validate_application_authorization(&request, mode).unwrap(); - let upstream = build_upstream_request(request, 8080, false, mode).unwrap(); + let upstream = build_upstream_request(request, 8080, false, mode, true).unwrap(); assert_eq!( upstream.headers()[header::AUTHORIZATION], @@ -2726,7 +2862,7 @@ mod tests { let mode = ServiceAuthorizationMode::BearerPassthrough; validate_application_authorization(&request, mode).unwrap(); - let upstream = build_upstream_request(request, 8080, false, mode).unwrap(); + let upstream = build_upstream_request(request, 8080, false, mode, true).unwrap(); assert!(!upstream.headers().contains_key(header::AUTHORIZATION)); } @@ -2836,7 +2972,8 @@ mod tests { .unwrap(); let upstream = - build_upstream_request(request, 8080, true, ServiceAuthorizationMode::Strip).unwrap(); + build_upstream_request(request, 8080, true, ServiceAuthorizationMode::Strip, true) + .unwrap(); assert_eq!(upstream.uri(), "/chat?session=main"); assert_eq!(upstream.headers()[header::CONNECTION], "Upgrade"); @@ -2859,7 +2996,7 @@ mod tests { let mode = ServiceAuthorizationMode::BearerPassthrough; validate_application_authorization(&request, mode).unwrap(); - let upstream = build_upstream_request(request, 8080, true, mode).unwrap(); + let upstream = build_upstream_request(request, 8080, true, mode, true).unwrap(); assert_eq!( upstream.headers()[header::AUTHORIZATION], diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index c441cb63e4..91b3c0721b 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -814,6 +814,7 @@ for peer identity policies, multi-node registrations, and authorization. | server.sandboxJwt.ttlSecs | int | `3600` | Token TTL in seconds. Defaults to 3600 (1h). | | server.sandboxNamespace | string | `""` | Namespace where sandbox pods are created. Defaults to the Helm release namespace (.Release.Namespace) when left empty. | | server.sandboxUid | string | `""` | UID for sandbox pods (`sandbox_uid`). Empty (default) = use the OpenShift SCC namespace annotation if present, otherwise the driver default. Must be an integer between 1 and 4294967294. | +| server.serviceAuthEnabled | bool | `false` | Opt in to gateway authentication for proxied application requests. Independent of the supervisor app listener; disabled preserves existing routing. | | server.serviceHostnameFormat | string | `""` | Hostname format for exposed sandbox services. Empty or "readable" keeps readable `--[--]` hostnames; "hashed" mints opaque one-label hostnames discriminated by the gateway installation name (server.name, defaulting to the release name). The name must be unique among all gateways sharing the service base domain, and renaming the installation changes every minted hostname. | | server.telemetryEnabled | bool | `true` | Enable anonymous OpenShell telemetry from the gateway and the sandbox supervisors it launches. | | server.tls.certSecretName | string | `"openshell-server-tls"` | K8s secret (type kubernetes.io/tls) with tls.crt and tls.key for the server. | diff --git a/deploy/helm/openshell/templates/_toml.tpl b/deploy/helm/openshell/templates/_toml.tpl index 8d94dc7442..65cff196f9 100644 --- a/deploy/helm/openshell/templates/_toml.tpl +++ b/deploy/helm/openshell/templates/_toml.tpl @@ -113,7 +113,7 @@ Keep this default in sync with gatewayConfig."openshell.gateway".enable_gateway_ {{- $_ := set $gateway "bind_address" (printf "%s:%v" $listenHost .Values.service.port) -}} {{- if .Values.service.healthPort -}}{{- $_ := set $gateway "health_bind_address" (printf "%s:%v" $listenHost .Values.service.healthPort) -}}{{- else -}}{{- $_ := unset $gateway "health_bind_address" -}}{{- end -}} {{- if include "openshell.metricsEnabled" . -}}{{- $_ := set $gateway "metrics_bind_address" (printf "%s:%v" $listenHost .Values.service.metricsPort) -}}{{- else -}}{{- $_ := unset $gateway "metrics_bind_address" -}}{{- end -}} -{{- range $legacyKey, $runtimeKey := dict "logLevel" "log_level" "enableLoopbackServiceHttp" "enable_loopback_service_http" "enableWebsocketTunnel" "enable_websocket_tunnel" "policyValidationFailureMode" "policy_validation_failure_mode" -}} +{{- range $legacyKey, $runtimeKey := dict "logLevel" "log_level" "enableLoopbackServiceHttp" "enable_loopback_service_http" "serviceAuthEnabled" "service_auth_enabled" "enableWebsocketTunnel" "enable_websocket_tunnel" "policyValidationFailureMode" "policy_validation_failure_mode" -}} {{- if not (hasKey $gateway $runtimeKey) -}}{{- $_ := set $gateway $runtimeKey (get $legacyServer $legacyKey) -}}{{- end -}} {{- end -}} {{/* An empty hostname format means "unset"; only translate it when set. The diff --git a/deploy/helm/openshell/tests/gateway_config_test.yaml b/deploy/helm/openshell/tests/gateway_config_test.yaml index 99538a7ffb..a046da6e9f 100644 --- a/deploy/helm/openshell/tests/gateway_config_test.yaml +++ b/deploy/helm/openshell/tests/gateway_config_test.yaml @@ -51,6 +51,31 @@ tests: - matchRegex: path: data["gateway.toml"] pattern: '(?m)^enable_gateway_service_routing\s*=\s*false$' + - it: leaves gateway application auth disabled by default + template: templates/gateway-config.yaml + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: '(?m)^service_auth_enabled\s*=\s*false$' + + - it: enables application auth without enabling the app listener + template: templates/gateway-config.yaml + set: + server.serviceAuthEnabled: true + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: '(?m)^service_auth_enabled\s*=\s*true$' + + - it: honors canonical auth false over legacy true + template: templates/gateway-config.yaml + set: + server.serviceAuthEnabled: true + gatewayConfig.gateway.service_auth_enabled: false + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: '(?m)^service_auth_enabled\s*=\s*false$' - it: disables the WebSocket tunnel unless explicitly enabled for an edge proxy template: templates/gateway-config.yaml diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index e5ae3b736b..ea3079ce1f 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -591,6 +591,9 @@ server: # -- Enable plaintext HTTP routing for loopback sandbox service URLs on # TLS-enabled gateways. enableLoopbackServiceHttp: true + # -- Opt in to gateway authentication for proxied application requests. + # Independent of the supervisor app listener; disabled preserves existing routing. + serviceAuthEnabled: false # -- Hostname format for exposed sandbox services. Empty or "readable" # keeps readable `--[--]` hostnames; "hashed" # mints opaque one-label hostnames discriminated by the gateway diff --git a/deploy/man/openshell-gateway.8.md b/deploy/man/openshell-gateway.8.md index a9bf03771f..eccd3efb05 100644 --- a/deploy/man/openshell-gateway.8.md +++ b/deploy/man/openshell-gateway.8.md @@ -35,6 +35,11 @@ TLS. # OPTIONS +**--service-auth-enabled** *BOOL* +: Opt in to configured gateway authentication for sandbox application HTTP + requests and WebSocket upgrades. Default: **false**. Independent of the + supervisor application listener. Environment: **OPENSHELL_SERVICE_AUTH_ENABLED**. + **--bind-address** *IP* : IP address to bind all listeners to. Default: **127.0.0.1**. Environment: **OPENSHELL_BIND_ADDRESS**. diff --git a/docs/how-it-works/gateways/authentication.mdx b/docs/how-it-works/gateways/authentication.mdx index 83cc71d137..8c8345c9f2 100644 --- a/docs/how-it-works/gateways/authentication.mdx +++ b/docs/how-it-works/gateways/authentication.mdx @@ -12,13 +12,19 @@ This page describes gateway authentication for CLI clients and sandbox service r ## Sandbox service requests -Gateway-mediated HTTP requests and WebSocket upgrades authenticate with the +Gateway application authentication is opt-in. Set +`service_auth_enabled = true` in `[openshell.gateway]` to enable it. The default +is `false`, which preserves existing service routing and its header, cookie, +and path handling. The supervisor app-listener setting does not enable +this authentication gate. + +When enabled, gateway-mediated HTTP requests and WebSocket upgrades authenticate with the configured gateway identity and require workspace user access. OIDC users need the configured user or admin role and, when scope enforcement is enabled, `sandbox:write` or `openshell:all`, matching TCP forwarding. Discovery-only access does not grant application access. This applies with the supervisor app listener enabled or disabled. Only explicitly enabled unauthenticated local development -bypasses the gate. Existing unauthenticated service clients must supply gateway +bypasses the gate. After enabling this flag, existing unauthenticated service clients must supply gateway credentials in authenticated deployments. For a request that uses only gateway bearer authentication: diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 5f4ede62f1..4f83e56c40 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2655,13 +2655,26 @@ Upgrade the CLI alongside the gateway when enabling `base_url`. Older CLI versions can replace the public application port with the gateway connection's port. -Gateway-mediated service URLs use configured gateway authentication and workspace -access controls with the app listener enabled or disabled. See +Gateway-mediated service authentication is independently opt-in: + +```toml +[openshell.gateway] +service_auth_enabled = true +``` + +The default is `false`, preserving existing service routing. Enable it with +`--service-auth-enabled true`, `OPENSHELL_SERVICE_AUTH_ENABLED=true`, or Helm +`server.serviceAuthEnabled: true`. The canonical Helm setting is +`gatewayConfig.gateway.service_auth_enabled`. Precedence is CLI > environment > +TOML > default, including explicit `false` values. This setting works with the +app listener enabled or disabled and with any compute driver supporting gateway +service forwarding. It uses the gateway's configured authentication and workspace +access controls. See [application request authentication](/how-it-works/gateways/authentication#sandbox-service-requests) for browser sessions, application credential passthrough, and revocation. Direct app-listener authentication belongs to the ingress provider. -TLS gateways advertise HTTPS for authenticated gateway service access, including +When service authentication is enabled, TLS gateways advertise HTTPS for gateway service access, including on loopback, so clients can present an mTLS identity. The separate plaintext loopback service listener cannot accept a client-certificate identity or browser sessions; use an explicit gateway bearer credential there. diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 9613cc8306..3ea4bb4d6d 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1994,9 +1994,9 @@ an app domain need distinct gateway names; replicas of one installation share its name. Changing the mode or installation name requires fresh route installation before discovery can advertise the replacement. -Gateway-mediated service HTTP requests and WebSocket upgrades require configured -gateway authentication and workspace user access with the app listener disabled -or enabled. OIDC scope enforcement requires `sandbox:write` (or `openshell:all`), +When `service_auth_enabled` is true, gateway-mediated service HTTP requests and +WebSocket upgrades require configured gateway authentication and workspace user +access with the app listener disabled or enabled. OIDC scope enforcement requires `sandbox:write` (or `openshell:all`), as for TCP forwarding. Check HTTP 401 for missing/invalid/expired/revoked credentials and 403 for role/scope/membership/origin denial. Browser login starts at the control-plane `/auth/services?service_origin=...`; the app host receives @@ -2011,6 +2011,18 @@ stripped; application cookies and explicit bearer passthrough remain available. Only explicit local-development unauthenticated access bypasses gateway auth. Direct listener authentication belongs to the ingress provider. +### Gateway-mediated application authentication + +Gateway service auth is opt-in with `[openshell.gateway].service_auth_enabled = true`, +`--service-auth-enabled true`, or `OPENSHELL_SERVICE_AUTH_ENABLED=true`. Helm uses +`server.serviceAuthEnabled` or canonical `gatewayConfig.gateway.service_auth_enabled`. +It defaults to false and is independent of `supervisor_app_listener.enabled`. +When debugging unexpected application 401/403 responses or browser login, check +this flag before inspecting the configured gateway authentication and workspace +membership. Direct app-listener authentication remains the ingress provider's +responsibility. Disabling service auth retains gateway application routing; it +does not disable the gateway data path. + ## Azure PostgreSQL workload identity When `database_auth = "azure-workload-identity"` is configured, verify the gateway From 93560304abd5a7c8b88eb7dcb125eee7720219ca Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Mon, 16 Nov 2026 11:39:12 -0800 Subject: [PATCH 05/15] fix(auth): preserve disabled service routing behavior Signed-off-by: Taylor Mutch --- .../openshell-server/src/service_routing.rs | 35 +++++++++++++++++-- .../openshell-supervisor/src/app_listener.rs | 18 +++++++--- docs/how-it-works/gateways/authentication.mdx | 8 +++++ 3 files changed, 53 insertions(+), 8 deletions(-) diff --git a/crates/openshell-server/src/service_routing.rs b/crates/openshell-server/src/service_routing.rs index c62cbeec04..4934bf1ae3 100644 --- a/crates/openshell-server/src/service_routing.rs +++ b/crates/openshell-server/src/service_routing.rs @@ -188,9 +188,6 @@ fn endpoint_scheme(config: &openshell_core::Config) -> &'static str { if config.tls.is_none() || (config.bind_address.ip().is_loopback() && config.service_routing.enable_loopback_service_http - && !config.mtls_auth.enabled - && !config.mtls_auth.operator_enabled - && config.oidc.is_none() && !config.service_routing.auth_enabled) { "http" @@ -2171,6 +2168,38 @@ mod tests { ); } + #[test] + fn configured_gateway_auth_does_not_change_the_disabled_service_auth_scheme() { + for mode in ["mtls", "operator", "oidc"] { + let mut cfg = openshell_core::Config::new(Some(tls_config())) + .with_bind_address("127.0.0.1:8080".parse().unwrap()) + .with_server_sans(["*.dev.openshell.localhost"]); + match mode { + "mtls" => cfg.mtls_auth.enabled = true, + "operator" => cfg.mtls_auth.operator_enabled = true, + "oidc" => { + cfg.oidc = Some( + serde_json::from_value(serde_json::json!({ + "issuer": "https://issuer.example.com", + "audience": "openshell" + })) + .unwrap(), + ); + } + _ => unreachable!(), + } + assert_eq!( + endpoint_url(&cfg, "default", "my-sandbox", "web").as_deref(), + Some("http://default--my-sandbox--web.dev.openshell.localhost:8080/") + ); + cfg.service_routing.auth_enabled = true; + assert_eq!( + endpoint_url(&cfg, "default", "my-sandbox", "web").as_deref(), + Some("https://default--my-sandbox--web.dev.openshell.localhost:8080/") + ); + } + } + #[test] fn endpoint_url_omits_service_label_for_empty_service_name() { let cfg = openshell_core::Config::new(Some(tls_config())) diff --git a/crates/openshell-supervisor/src/app_listener.rs b/crates/openshell-supervisor/src/app_listener.rs index 55bdfbe7d5..7178561b1d 100644 --- a/crates/openshell-supervisor/src/app_listener.rs +++ b/crates/openshell-supervisor/src/app_listener.rs @@ -1019,8 +1019,10 @@ fn sanitize_headers(headers: &mut http::HeaderMap, passthrough: bool, websocket: && !name.trim().eq_ignore_ascii_case("cf-authorization") && !name .trim() - .to_ascii_lowercase() - .starts_with("__host-openshell-") + .eq_ignore_ascii_case("__Host-openshell-service-session") + && !name + .trim() + .eq_ignore_ascii_case("__Host-openshell-service-login") }) }) .map(str::trim) @@ -2137,7 +2139,7 @@ mod tests { let mut headers = http::HeaderMap::new(); headers.insert( header::COOKIE, - "app=session; CF_Authorization=secret; __Host-openshell-service-session=secret; __Host-openshell-service-login=secret".parse().unwrap(), + "app=session; __Host-openshell-app=retained; CF_Authorization=secret; __Host-openshell-service-session=secret; __Host-openshell-service-login=secret".parse().unwrap(), ); headers.insert("x-forwarded-client-cert", "secret".parse().unwrap()); headers.insert( @@ -2157,11 +2159,17 @@ mod tests { passthrough[header::AUTHORIZATION], "Bearer application-token" ); - assert_eq!(passthrough[header::COOKIE], "app=session"); + assert_eq!( + passthrough[header::COOKIE], + "app=session; __Host-openshell-app=retained" + ); assert!(!passthrough.contains_key("x-openshell-authorization")); assert!(sanitize_headers(&mut headers, false, false)); assert!(!headers.contains_key(header::AUTHORIZATION)); - assert_eq!(headers[header::COOKIE], "app=session"); + assert_eq!( + headers[header::COOKIE], + "app=session; __Host-openshell-app=retained" + ); assert!(!headers.contains_key("x-forwarded-client-cert")); assert!(!headers.contains_key("x-openshell-authorization")); assert!(!headers.contains_key("x-openshell-auth-source")); diff --git a/docs/how-it-works/gateways/authentication.mdx b/docs/how-it-works/gateways/authentication.mdx index 8c8345c9f2..f73ca879ef 100644 --- a/docs/how-it-works/gateways/authentication.mdx +++ b/docs/how-it-works/gateways/authentication.mdx @@ -18,6 +18,11 @@ is `false`, which preserves existing service routing and its header, cookie, and path handling. The supervisor app-listener setting does not enable this authentication gate. +With gateway TLS configured, enabling service authentication advertises HTTPS +service URLs on loopback too. Clients must trust the gateway certificate. With +the flag disabled, configured mTLS or OIDC does not change the existing +loopback HTTP URL behavior. + When enabled, gateway-mediated HTTP requests and WebSocket upgrades authenticate with the configured gateway identity and require workspace user access. OIDC users need the configured user or admin role and, when scope enforcement is enabled, @@ -118,6 +123,9 @@ it admits at most 1,024 outstanding application credential revocations. Direct supervisor app-listener access delegates authentication to the ingress provider. Gateway browser sessions and credentials do not authorize that path. +The listener strips the gateway's `__Host-openshell-service-session` and +`__Host-openshell-service-login` cookies, while preserving other application +cookies, including names such as `__Host-openshell-app`. ## Gateway Resolution From db4317e2639a37778f1714ef0a6bf543cd000a95 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Mon, 16 Nov 2026 16:41:44 -0800 Subject: [PATCH 06/15] fix(auth): disable application login with gateway service routing Signed-off-by: Taylor Mutch --- crates/openshell-server/src/auth/http.rs | 2 +- .../openshell-server/src/service_routing.rs | 126 +++++++++++------- docs/how-it-works/gateways/configuration.mdx | 3 + 3 files changed, 83 insertions(+), 48 deletions(-) diff --git a/crates/openshell-server/src/auth/http.rs b/crates/openshell-server/src/auth/http.rs index 03f8f3ce65..725e119d77 100644 --- a/crates/openshell-server/src/auth/http.rs +++ b/crates/openshell-server/src/auth/http.rs @@ -91,7 +91,7 @@ fn sanitize_callback_host(raw: &Option) -> (String, String) { /// Create the auth router. pub fn router(state: Arc) -> Router { let mut router = Router::new(); - if state.config.service_routing.auth_enabled { + if state.config.service_routing.enabled && state.config.service_routing.auth_enabled { router = router.route( "/auth/services", get(service_browser_login).post(service_browser_login), diff --git a/crates/openshell-server/src/service_routing.rs b/crates/openshell-server/src/service_routing.rs index 4934bf1ae3..8bf4b6eaff 100644 --- a/crates/openshell-server/src/service_routing.rs +++ b/crates/openshell-server/src/service_routing.rs @@ -515,6 +515,12 @@ pub async fn proxy_sandbox_service_request( state: Arc, mut req: Request, ) -> impl IntoResponse { + if !state.config.service_routing.enabled { + return service_error_response( + StatusCode::NOT_FOUND, + "Gateway service routing is disabled", + ); + } let Some(host) = request_host(&req).map(str::to_string) else { return StatusCode::NOT_FOUND.into_response(); }; @@ -528,13 +534,6 @@ pub async fn proxy_sandbox_service_request( } = target; let service_name = service.unwrap_or_default(); - if !state.config.service_routing.enabled { - return service_error_response( - StatusCode::NOT_FOUND, - "Gateway service routing is disabled", - ); - } - if state.config.service_routing.auth_enabled { if req .uri() @@ -1460,52 +1459,85 @@ mod tests { } #[tokio::test] - async fn disabled_gateway_routing_rejects_http_and_websocket_on_both_routers() { + async fn application_login_requires_gateway_routing_and_auth() { use tower::ServiceExt as _; - for hashed in [false, true] { - for listener_enabled in [false, true] { + for routing_enabled in [false, true] { + for auth_enabled in [false, true] { let mut state = crate::grpc::test_support::test_server_state().await; - let inner = Arc::get_mut(&mut state).unwrap(); - inner.config.service_routing.enabled = false; - inner.config.supervisor_app_listener.enabled = listener_enabled; - inner.config.name = "gateway-a".into(); - inner.config.service_routing.service_hostname_format = if hashed { - ServiceHostnameFormat::Hashed - } else { - ServiceHostnameFormat::Readable - }; - inner.service_route_index = - Arc::new(ServiceRouteIndex::new(Some("gateway-a".into()))); - inner - .service_route_index - .register("default", "my-sandbox", "web") + let config = &mut Arc::get_mut(&mut state).unwrap().config; + config.service_routing.enabled = routing_enabled; + config.service_routing.auth_enabled = auth_enabled; + let response = crate::http_router(state) + .oneshot( + Request::builder() + .uri("/auth/services") + .header(header::HOST, "gateway.example.com") + .body(Body::empty()) + .unwrap(), + ) + .await .unwrap(); - let host = if hashed { - "enh47uqyj7bpyttz.openshell.localhost" + if routing_enabled && auth_enabled { + assert_ne!(response.status(), StatusCode::NOT_FOUND); } else { - "default--my-sandbox--web.openshell.localhost" - }; - for service_only in [false, true] { - for websocket in [false, true] { - let router = if service_only { - crate::service_http_router(state.clone()) - } else { - crate::http_router(state.clone()) - }; - let mut request = Request::builder().uri("/app").header(header::HOST, host); - if websocket { - request = request - .header(header::CONNECTION, "upgrade") - .header(header::UPGRADE, "websocket") - .header("sec-websocket-version", "13") - .header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ=="); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + } + } + } + } + + #[tokio::test] + async fn disabled_gateway_routing_rejects_http_and_websocket_on_both_routers() { + use tower::ServiceExt as _; + + for auth_enabled in [false, true] { + for hashed in [false, true] { + for listener_enabled in [false, true] { + let mut state = crate::grpc::test_support::test_server_state().await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.config.service_routing.enabled = false; + inner.config.service_routing.auth_enabled = auth_enabled; + inner.config.supervisor_app_listener.enabled = listener_enabled; + inner.config.name = "gateway-a".into(); + inner.config.service_routing.service_hostname_format = if hashed { + ServiceHostnameFormat::Hashed + } else { + ServiceHostnameFormat::Readable + }; + inner.service_route_index = + Arc::new(ServiceRouteIndex::new(Some("gateway-a".into()))); + inner + .service_route_index + .register("default", "my-sandbox", "web") + .unwrap(); + let host = if hashed { + "enh47uqyj7bpyttz.openshell.localhost" + } else { + "default--my-sandbox--web.openshell.localhost" + }; + for service_only in [false, true] { + for websocket in [false, true] { + let router = if service_only { + crate::service_http_router(state.clone()) + } else { + crate::http_router(state.clone()) + }; + let mut request = + Request::builder().uri("/app").header(header::HOST, host); + if websocket { + request = request + .header(header::CONNECTION, "upgrade") + .header(header::UPGRADE, "websocket") + .header("sec-websocket-version", "13") + .header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ=="); + } + let response = router + .oneshot(request.body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); } - let response = router - .oneshot(request.body(Body::empty()).unwrap()) - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::NOT_FOUND); } } } diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 4f83e56c40..7a5d32ee26 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2662,6 +2662,9 @@ Gateway-mediated service authentication is independently opt-in: service_auth_enabled = true ``` +This setting applies only when `enable_gateway_service_routing` is `true`. Disabling +gateway service routing also disables the application login endpoint. + The default is `false`, preserving existing service routing. Enable it with `--service-auth-enabled true`, `OPENSHELL_SERVICE_AUTH_ENABLED=true`, or Helm `server.serviceAuthEnabled: true`. The canonical Helm setting is From 746d753e5e85f674a5ffbe83656c830305a0251f Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Tue, 17 Nov 2026 14:41:46 -0800 Subject: [PATCH 07/15] chore(auth): log gateway service authentication separately Signed-off-by: Taylor Mutch --- crates/openshell-server/src/cli.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index e4939dc37f..6957474905 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -1157,6 +1157,11 @@ async fn run_from_args( if prepared.config.service_routing.enabled { info!("Gateway-based service routing enabled"); + if prepared.config.service_routing.auth_enabled { + info!("Gateway-mediated service authentication enabled"); + } else { + info!("Gateway-mediated service authentication disabled"); + } } info!(bind = %prepared.config.bind_address, "Starting OpenShell server"); From 7bb2856062744ae7bd65ddae0667cae3150e3f11 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Tue, 17 Nov 2026 15:07:25 -0800 Subject: [PATCH 08/15] fix(helm): use canonical service authentication configuration Signed-off-by: Taylor Mutch --- deploy/helm/openshell/tests/gateway_config_test.yaml | 4 +++- docs/how-it-works/gateways/configuration.mdx | 2 +- skills/debug-openshell-cluster/SKILL.md | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/deploy/helm/openshell/tests/gateway_config_test.yaml b/deploy/helm/openshell/tests/gateway_config_test.yaml index a046da6e9f..b15d00506f 100644 --- a/deploy/helm/openshell/tests/gateway_config_test.yaml +++ b/deploy/helm/openshell/tests/gateway_config_test.yaml @@ -71,7 +71,9 @@ tests: template: templates/gateway-config.yaml set: server.serviceAuthEnabled: true - gatewayConfig.gateway.service_auth_enabled: false + gatewayConfig: + openshell.gateway: + service_auth_enabled: false asserts: - matchRegex: path: data["gateway.toml"] diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 7a5d32ee26..2aa9ce81eb 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2668,7 +2668,7 @@ gateway service routing also disables the application login endpoint. The default is `false`, preserving existing service routing. Enable it with `--service-auth-enabled true`, `OPENSHELL_SERVICE_AUTH_ENABLED=true`, or Helm `server.serviceAuthEnabled: true`. The canonical Helm setting is -`gatewayConfig.gateway.service_auth_enabled`. Precedence is CLI > environment > +`gatewayConfig."openshell.gateway".service_auth_enabled`. Precedence is CLI > environment > TOML > default, including explicit `false` values. This setting works with the app listener enabled or disabled and with any compute driver supporting gateway service forwarding. It uses the gateway's configured authentication and workspace diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 3ea4bb4d6d..af099f10bf 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -2015,7 +2015,7 @@ Direct listener authentication belongs to the ingress provider. Gateway service auth is opt-in with `[openshell.gateway].service_auth_enabled = true`, `--service-auth-enabled true`, or `OPENSHELL_SERVICE_AUTH_ENABLED=true`. Helm uses -`server.serviceAuthEnabled` or canonical `gatewayConfig.gateway.service_auth_enabled`. +`server.serviceAuthEnabled` or canonical `gatewayConfig."openshell.gateway".service_auth_enabled`. It defaults to false and is independent of `supervisor_app_listener.enabled`. When debugging unexpected application 401/403 responses or browser login, check this flag before inspecting the configured gateway authentication and workspace From f64ec96d940db313518b9c2a86d182d0eae6ea40 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Wed, 18 Nov 2026 15:41:49 -0800 Subject: [PATCH 09/15] test(auth): handle fallible server construction after rebase Signed-off-by: Taylor Mutch --- .../src/auth/service_session.rs | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/crates/openshell-server/src/auth/service_session.rs b/crates/openshell-server/src/auth/service_session.rs index 14b5954db6..33aa181643 100644 --- a/crates/openshell-server/src/auth/service_session.rs +++ b/crates/openshell-server/src/auth/service_session.rs @@ -1174,17 +1174,20 @@ pub mod tests { } async fn replica(state: &Arc) -> Arc { - Arc::new(ServerState::new_with_credentials( - state.config.clone(), - state.store.clone(), - crate::compute::new_test_runtime(state.store.clone()).await, - crate::sandbox_index::SandboxIndex::new(), - crate::sandbox_watch::SandboxWatchBus::new(), - crate::tracing_bus::TracingLogBus::new(), - Arc::new(crate::supervisor_session::SupervisorSessionRegistry::new()), - state.oidc_cache.clone(), - state.credentials.clone(), - )) + Arc::new( + ServerState::new_with_credentials( + state.config.clone(), + state.store.clone(), + crate::compute::new_test_runtime(state.store.clone()).await, + crate::sandbox_index::SandboxIndex::new(), + crate::sandbox_watch::SandboxWatchBus::new(), + crate::tracing_bus::TracingLogBus::new(), + Arc::new(crate::supervisor_session::SupervisorSessionRegistry::new()), + state.oidc_cache.clone(), + state.credentials.clone(), + ) + .expect("valid replica configuration"), + ) } fn application(cookie: &str) -> Request { let mut req = request(Method::GET, &format!("{APP}/")); From f4a864ec2661f9f736a0e8d64fb0bd83a41b6aa2 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Wed, 18 Nov 2026 16:19:43 -0800 Subject: [PATCH 10/15] refactor(auth): rename gateway service auth toggle Signed-off-by: Taylor Mutch --- crates/openshell-server/README.md | 6 +-- crates/openshell-server/src/cli.rs | 44 +++++++++++-------- .../openshell-server/src/config_file/mod.rs | 2 +- .../openshell-server/src/service_routing.rs | 22 ++++++---- deploy/helm/openshell/README.md | 1 - deploy/helm/openshell/templates/_toml.tpl | 2 +- .../openshell/tests/gateway_config_test.yaml | 19 ++++---- deploy/helm/openshell/values.yaml | 3 -- deploy/man/openshell-gateway.8.md | 4 +- docs/how-it-works/gateways/authentication.mdx | 2 +- docs/how-it-works/gateways/configuration.mdx | 7 ++- skills/debug-openshell-cluster/SKILL.md | 8 ++-- 12 files changed, 63 insertions(+), 57 deletions(-) diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index 394fbd115c..6284c4214c 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -478,10 +478,10 @@ equality tokens, not resumable cursors or an ordering across gateway replicas. Gateway service authentication defaults to disabled, independently of the app listener. Disabled mode preserves application routing, reserved-looking paths, -and the pre-existing header/cookie policy. CLI `--service-auth-enabled` and -`OPENSHELL_SERVICE_AUTH_ENABLED` override the TOML setting. +and the pre-existing header/cookie policy. CLI `--enable-gateway-service-auth` and +`OPENSHELL_ENABLE_GATEWAY_SERVICE_AUTH` override the TOML setting. -With `[openshell.gateway].service_auth_enabled = true`, gateway-mediated +With `[openshell.gateway].enable_gateway_service_auth = true`, gateway-mediated application HTTP requests and WebSocket upgrades authenticate through the gateway chain or verified TLS client identity before endpoint lookup, independently of app-listener enablement. User access requires TCP-forwarding diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index 6957474905..224a1c5bf3 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -352,8 +352,8 @@ struct RunArgs { server_sans: Vec, /// Authenticate sandbox application requests using configured gateway auth. - #[arg(long, env = "OPENSHELL_SERVICE_AUTH_ENABLED", default_value_t = false, action = ArgAction::Set)] - service_auth_enabled: bool, + #[arg(long, env = "OPENSHELL_ENABLE_GATEWAY_SERVICE_AUTH", default_value_t = false, action = ArgAction::Set)] + enable_gateway_service_auth: bool, /// Hostname format for exposed sandbox services: `readable` (default) /// keeps `--[--]` hostnames; `hashed` mints @@ -763,7 +763,7 @@ fn assemble_server_config( .with_server_sans(args.server_sans.clone()) .with_service_hostname_format(args.service_hostname_format.unwrap_or_default()) .with_service_routing(args.enable_gateway_service_routing) - .with_service_auth(args.service_auth_enabled) + .with_service_auth(args.enable_gateway_service_auth) .with_loopback_service_http(args.enable_loopback_service_http) .with_websocket_tunnel(args.enable_websocket_tunnel); config @@ -1906,10 +1906,10 @@ fn merge_file_into_args(args: &mut RunArgs, file: &GatewayFileSection, matches: { args.enable_gateway_service_routing = enabled; } - if let Some(enabled) = file.service_auth_enabled - && arg_defaulted(matches, "service_auth_enabled") + if let Some(enabled) = file.enable_gateway_service_auth + && arg_defaulted(matches, "enable_gateway_service_auth") { - args.service_auth_enabled = enabled; + args.enable_gateway_service_auth = enabled; } if let Some(enabled) = file.enable_loopback_service_http && arg_defaulted(matches, "enable_loopback_service_http") @@ -4871,34 +4871,40 @@ enabled = false #[test] fn service_auth_is_opt_in_with_explicit_cli_environment_and_file_precedence() { Environment::new() - .remove("OPENSHELL_SERVICE_AUTH_ENABLED") + .remove("OPENSHELL_ENABLE_GATEWAY_SERVICE_AUTH") .run(|| { let file = toml::from_str::( - "[openshell.gateway]\nservice_auth_enabled = true\n", + "[openshell.gateway]\nenable_gateway_service_auth = true\n", ) .unwrap(); let (mut args, matches) = parse_with_args(&["openshell-gateway"]); - assert!(!args.service_auth_enabled); + assert!(!args.enable_gateway_service_auth); merge_file_into_args(&mut args, &file.openshell.gateway, &matches); - assert!(args.service_auth_enabled); - let (mut args, matches) = - parse_with_args(&["openshell-gateway", "--service-auth-enabled", "false"]); + assert!(args.enable_gateway_service_auth); + let (mut args, matches) = parse_with_args(&[ + "openshell-gateway", + "--enable-gateway-service-auth", + "false", + ]); merge_file_into_args(&mut args, &file.openshell.gateway, &matches); - assert!(!args.service_auth_enabled); + assert!(!args.enable_gateway_service_auth); }); Environment::new() - .set("OPENSHELL_SERVICE_AUTH_ENABLED", "false") + .set("OPENSHELL_ENABLE_GATEWAY_SERVICE_AUTH", "false") .run(|| { let file = toml::from_str::( - "[openshell.gateway]\nservice_auth_enabled = true\n", + "[openshell.gateway]\nenable_gateway_service_auth = true\n", ) .unwrap(); let (mut args, matches) = parse_with_args(&["openshell-gateway"]); merge_file_into_args(&mut args, &file.openshell.gateway, &matches); - assert!(!args.service_auth_enabled); - let (args, _) = - parse_with_args(&["openshell-gateway", "--service-auth-enabled", "true"]); - assert!(args.service_auth_enabled); + assert!(!args.enable_gateway_service_auth); + let (args, _) = parse_with_args(&[ + "openshell-gateway", + "--enable-gateway-service-auth", + "true", + ]); + assert!(args.enable_gateway_service_auth); }); } diff --git a/crates/openshell-server/src/config_file/mod.rs b/crates/openshell-server/src/config_file/mod.rs index f98caef54f..c96f7be8c5 100644 --- a/crates/openshell-server/src/config_file/mod.rs +++ b/crates/openshell-server/src/config_file/mod.rs @@ -198,7 +198,7 @@ pub struct GatewayFileSection { pub enable_gateway_service_routing: Option, /// Opt in to gateway authentication for sandbox application requests. #[serde(default)] - pub service_auth_enabled: Option, + pub enable_gateway_service_auth: Option, /// Subject Alternative Names configured on the gateway server certificate. /// Wildcard DNS SANs also enable sandbox service URLs under that domain. #[serde(default)] diff --git a/crates/openshell-server/src/service_routing.rs b/crates/openshell-server/src/service_routing.rs index 8bf4b6eaff..7df113c272 100644 --- a/crates/openshell-server/src/service_routing.rs +++ b/crates/openshell-server/src/service_routing.rs @@ -962,7 +962,7 @@ fn build_upstream_request( target_port: u16, preserve_upgrade_headers: bool, authorization_mode: ServiceAuthorizationMode, - service_auth_enabled: bool, + enable_gateway_service_auth: bool, ) -> Result, ServiceRouteError> { let (parts, body) = req.into_parts(); let path = parts.uri.path_and_query().map_or("/", |path| path.as_str()); @@ -981,12 +981,12 @@ fn build_upstream_request( for (name, value) in &parts.headers { if (is_hop_by_hop_header(name) && !(preserve_upgrade_headers && is_websocket_hop_by_hop_header(name))) - || is_gateway_auth_header(name, authorization_mode, service_auth_enabled) + || is_gateway_auth_header(name, authorization_mode, enable_gateway_service_auth) { continue; } if name == header::COOKIE { - if let Some(cookie) = sanitize_cookie_header(value, service_auth_enabled) { + if let Some(cookie) = sanitize_cookie_header(value, enable_gateway_service_auth) { headers.append(name, cookie); } continue; @@ -1125,7 +1125,7 @@ fn is_bearer_token68(value: &str) -> bool { fn is_gateway_auth_header( name: &header::HeaderName, authorization_mode: ServiceAuthorizationMode, - service_auth_enabled: bool, + enable_gateway_service_auth: bool, ) -> bool { match name.as_str() { "authorization" => authorization_mode != ServiceAuthorizationMode::BearerPassthrough, @@ -1134,7 +1134,7 @@ fn is_gateway_auth_header( | "x-openshell-principal" | "x-openshell-user" | "x-openshell-roles" - | "cf-access-authenticated-user-email" => service_auth_enabled, + | "cf-access-authenticated-user-email" => enable_gateway_service_auth, "cf-access-jwt-assertion" | "x-forwarded-client-cert" | "x-ssl-client-cert" @@ -1143,14 +1143,17 @@ fn is_gateway_auth_header( } } -fn sanitize_cookie_header(value: &HeaderValue, service_auth_enabled: bool) -> Option { +fn sanitize_cookie_header( + value: &HeaderValue, + enable_gateway_service_auth: bool, +) -> Option { let value = value.to_str().ok()?; let cookies = value .split(';') .filter_map(|cookie| { let cookie = cookie.trim(); let (name, _) = cookie.split_once('=')?; - (!is_gateway_auth_cookie(name.trim(), service_auth_enabled)).then_some(cookie) + (!is_gateway_auth_cookie(name.trim(), enable_gateway_service_auth)).then_some(cookie) }) .collect::>(); @@ -1161,10 +1164,11 @@ fn sanitize_cookie_header(value: &HeaderValue, service_auth_enabled: bool) -> Op HeaderValue::from_str(&cookies.join("; ")).ok() } -fn is_gateway_auth_cookie(name: &str, service_auth_enabled: bool) -> bool { +fn is_gateway_auth_cookie(name: &str, enable_gateway_service_auth: bool) -> bool { name.eq_ignore_ascii_case("CF_Authorization") || name.eq_ignore_ascii_case("cf-authorization") - || (service_auth_enabled && name.to_ascii_lowercase().starts_with("__host-openshell-")) + || (enable_gateway_service_auth + && name.to_ascii_lowercase().starts_with("__host-openshell-")) } pub fn emit_service_endpoint_config_event(endpoint: &ServiceEndpoint, url: &str, created: bool) { diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index 91b3c0721b..c441cb63e4 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -814,7 +814,6 @@ for peer identity policies, multi-node registrations, and authorization. | server.sandboxJwt.ttlSecs | int | `3600` | Token TTL in seconds. Defaults to 3600 (1h). | | server.sandboxNamespace | string | `""` | Namespace where sandbox pods are created. Defaults to the Helm release namespace (.Release.Namespace) when left empty. | | server.sandboxUid | string | `""` | UID for sandbox pods (`sandbox_uid`). Empty (default) = use the OpenShift SCC namespace annotation if present, otherwise the driver default. Must be an integer between 1 and 4294967294. | -| server.serviceAuthEnabled | bool | `false` | Opt in to gateway authentication for proxied application requests. Independent of the supervisor app listener; disabled preserves existing routing. | | server.serviceHostnameFormat | string | `""` | Hostname format for exposed sandbox services. Empty or "readable" keeps readable `--[--]` hostnames; "hashed" mints opaque one-label hostnames discriminated by the gateway installation name (server.name, defaulting to the release name). The name must be unique among all gateways sharing the service base domain, and renaming the installation changes every minted hostname. | | server.telemetryEnabled | bool | `true` | Enable anonymous OpenShell telemetry from the gateway and the sandbox supervisors it launches. | | server.tls.certSecretName | string | `"openshell-server-tls"` | K8s secret (type kubernetes.io/tls) with tls.crt and tls.key for the server. | diff --git a/deploy/helm/openshell/templates/_toml.tpl b/deploy/helm/openshell/templates/_toml.tpl index 65cff196f9..8d94dc7442 100644 --- a/deploy/helm/openshell/templates/_toml.tpl +++ b/deploy/helm/openshell/templates/_toml.tpl @@ -113,7 +113,7 @@ Keep this default in sync with gatewayConfig."openshell.gateway".enable_gateway_ {{- $_ := set $gateway "bind_address" (printf "%s:%v" $listenHost .Values.service.port) -}} {{- if .Values.service.healthPort -}}{{- $_ := set $gateway "health_bind_address" (printf "%s:%v" $listenHost .Values.service.healthPort) -}}{{- else -}}{{- $_ := unset $gateway "health_bind_address" -}}{{- end -}} {{- if include "openshell.metricsEnabled" . -}}{{- $_ := set $gateway "metrics_bind_address" (printf "%s:%v" $listenHost .Values.service.metricsPort) -}}{{- else -}}{{- $_ := unset $gateway "metrics_bind_address" -}}{{- end -}} -{{- range $legacyKey, $runtimeKey := dict "logLevel" "log_level" "enableLoopbackServiceHttp" "enable_loopback_service_http" "serviceAuthEnabled" "service_auth_enabled" "enableWebsocketTunnel" "enable_websocket_tunnel" "policyValidationFailureMode" "policy_validation_failure_mode" -}} +{{- range $legacyKey, $runtimeKey := dict "logLevel" "log_level" "enableLoopbackServiceHttp" "enable_loopback_service_http" "enableWebsocketTunnel" "enable_websocket_tunnel" "policyValidationFailureMode" "policy_validation_failure_mode" -}} {{- if not (hasKey $gateway $runtimeKey) -}}{{- $_ := set $gateway $runtimeKey (get $legacyServer $legacyKey) -}}{{- end -}} {{- end -}} {{/* An empty hostname format means "unset"; only translate it when set. The diff --git a/deploy/helm/openshell/tests/gateway_config_test.yaml b/deploy/helm/openshell/tests/gateway_config_test.yaml index b15d00506f..5bb2d985ce 100644 --- a/deploy/helm/openshell/tests/gateway_config_test.yaml +++ b/deploy/helm/openshell/tests/gateway_config_test.yaml @@ -51,33 +51,34 @@ tests: - matchRegex: path: data["gateway.toml"] pattern: '(?m)^enable_gateway_service_routing\s*=\s*false$' - - it: leaves gateway application auth disabled by default + - it: leaves gateway application auth disabled by the runtime default when omitted template: templates/gateway-config.yaml asserts: - - matchRegex: + - notMatchRegex: path: data["gateway.toml"] - pattern: '(?m)^service_auth_enabled\s*=\s*false$' + pattern: 'enable_gateway_service_auth\s*=' - it: enables application auth without enabling the app listener template: templates/gateway-config.yaml set: - server.serviceAuthEnabled: true + gatewayConfig: + openshell.gateway: + enable_gateway_service_auth: true asserts: - matchRegex: path: data["gateway.toml"] - pattern: '(?m)^service_auth_enabled\s*=\s*true$' + pattern: '(?m)^enable_gateway_service_auth\s*=\s*true$' - - it: honors canonical auth false over legacy true + - it: disables application auth through canonical configuration template: templates/gateway-config.yaml set: - server.serviceAuthEnabled: true gatewayConfig: openshell.gateway: - service_auth_enabled: false + enable_gateway_service_auth: false asserts: - matchRegex: path: data["gateway.toml"] - pattern: '(?m)^service_auth_enabled\s*=\s*false$' + pattern: '(?m)^enable_gateway_service_auth\s*=\s*false$' - it: disables the WebSocket tunnel unless explicitly enabled for an edge proxy template: templates/gateway-config.yaml diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index ea3079ce1f..e5ae3b736b 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -591,9 +591,6 @@ server: # -- Enable plaintext HTTP routing for loopback sandbox service URLs on # TLS-enabled gateways. enableLoopbackServiceHttp: true - # -- Opt in to gateway authentication for proxied application requests. - # Independent of the supervisor app listener; disabled preserves existing routing. - serviceAuthEnabled: false # -- Hostname format for exposed sandbox services. Empty or "readable" # keeps readable `--[--]` hostnames; "hashed" # mints opaque one-label hostnames discriminated by the gateway diff --git a/deploy/man/openshell-gateway.8.md b/deploy/man/openshell-gateway.8.md index eccd3efb05..7f0dd32ca0 100644 --- a/deploy/man/openshell-gateway.8.md +++ b/deploy/man/openshell-gateway.8.md @@ -35,10 +35,10 @@ TLS. # OPTIONS -**--service-auth-enabled** *BOOL* +**--enable-gateway-service-auth** *BOOL* : Opt in to configured gateway authentication for sandbox application HTTP requests and WebSocket upgrades. Default: **false**. Independent of the - supervisor application listener. Environment: **OPENSHELL_SERVICE_AUTH_ENABLED**. + supervisor application listener. Environment: **OPENSHELL_ENABLE_GATEWAY_SERVICE_AUTH**. **--bind-address** *IP* : IP address to bind all listeners to. Default: **127.0.0.1**. diff --git a/docs/how-it-works/gateways/authentication.mdx b/docs/how-it-works/gateways/authentication.mdx index f73ca879ef..319f0e7930 100644 --- a/docs/how-it-works/gateways/authentication.mdx +++ b/docs/how-it-works/gateways/authentication.mdx @@ -13,7 +13,7 @@ This page describes gateway authentication for CLI clients and sandbox service r ## Sandbox service requests Gateway application authentication is opt-in. Set -`service_auth_enabled = true` in `[openshell.gateway]` to enable it. The default +`enable_gateway_service_auth = true` in `[openshell.gateway]` to enable it. The default is `false`, which preserves existing service routing and its header, cookie, and path handling. The supervisor app-listener setting does not enable this authentication gate. diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 2aa9ce81eb..444f85cd72 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2659,16 +2659,15 @@ Gateway-mediated service authentication is independently opt-in: ```toml [openshell.gateway] -service_auth_enabled = true +enable_gateway_service_auth = true ``` This setting applies only when `enable_gateway_service_routing` is `true`. Disabling gateway service routing also disables the application login endpoint. The default is `false`, preserving existing service routing. Enable it with -`--service-auth-enabled true`, `OPENSHELL_SERVICE_AUTH_ENABLED=true`, or Helm -`server.serviceAuthEnabled: true`. The canonical Helm setting is -`gatewayConfig."openshell.gateway".service_auth_enabled`. Precedence is CLI > environment > +`--enable-gateway-service-auth true`, `OPENSHELL_ENABLE_GATEWAY_SERVICE_AUTH=true`, or Helm +`gatewayConfig."openshell.gateway".enable_gateway_service_auth`. Precedence is CLI > environment > TOML > default, including explicit `false` values. This setting works with the app listener enabled or disabled and with any compute driver supporting gateway service forwarding. It uses the gateway's configured authentication and workspace diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index af099f10bf..d109447f8f 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1994,7 +1994,7 @@ an app domain need distinct gateway names; replicas of one installation share its name. Changing the mode or installation name requires fresh route installation before discovery can advertise the replacement. -When `service_auth_enabled` is true, gateway-mediated service HTTP requests and +When `enable_gateway_service_auth` is true, gateway-mediated service HTTP requests and WebSocket upgrades require configured gateway authentication and workspace user access with the app listener disabled or enabled. OIDC scope enforcement requires `sandbox:write` (or `openshell:all`), as for TCP forwarding. Check HTTP 401 for missing/invalid/expired/revoked @@ -2013,9 +2013,9 @@ Direct listener authentication belongs to the ingress provider. ### Gateway-mediated application authentication -Gateway service auth is opt-in with `[openshell.gateway].service_auth_enabled = true`, -`--service-auth-enabled true`, or `OPENSHELL_SERVICE_AUTH_ENABLED=true`. Helm uses -`server.serviceAuthEnabled` or canonical `gatewayConfig."openshell.gateway".service_auth_enabled`. +Gateway service auth is opt-in with `[openshell.gateway].enable_gateway_service_auth = true`, +`--enable-gateway-service-auth true`, or `OPENSHELL_ENABLE_GATEWAY_SERVICE_AUTH=true`. Helm uses +`gatewayConfig."openshell.gateway".enable_gateway_service_auth`. It defaults to false and is independent of `supervisor_app_listener.enabled`. When debugging unexpected application 401/403 responses or browser login, check this flag before inspecting the configured gateway authentication and workspace From a4900e6e8dd88f95249f7b50c1e475811f862d3a Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Thu, 19 Nov 2026 15:28:50 -0800 Subject: [PATCH 11/15] fix(auth): bind browser origins and atomically promote sessions Signed-off-by: Taylor Mutch --- crates/openshell-core/src/config.rs | 45 +++ crates/openshell-server/README.md | 7 +- .../src/auth/service_session.rs | 321 +++++++++++++++--- crates/openshell-server/src/cli.rs | 37 ++ .../openshell-server/src/config_file/mod.rs | 3 + .../openshell-server/src/service_routing.rs | 2 + .../openshell/tests/gateway_config_test.yaml | 12 + docs/how-it-works/gateways/authentication.mdx | 14 + docs/how-it-works/gateways/configuration.mdx | 7 + docs/how-it-works/sandboxes/overview.mdx | 6 +- rfc/0017-sandbox-service-exposure/README.md | 4 +- skills/debug-openshell-cluster/SKILL.md | 4 +- 12 files changed, 407 insertions(+), 55 deletions(-) diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index 32fd08ce57..0c38cd311e 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -520,6 +520,9 @@ pub struct ServiceRoutingConfig { /// Opt in to gateway authentication for proxied application requests. /// Independent of the supervisor application listener. pub auth_enabled: bool, + /// Exact trusted HTTPS control-plane origins for browser service login. + /// Empty disables browser login without affecting bearer or mTLS access. + pub auth_login_origins: Vec, /// Base domains accepted for `sandbox--service.` routes. /// The first domain is used when the gateway prints endpoint URLs. @@ -577,6 +580,23 @@ impl ServiceRoutingConfig { /// deploying platform is responsible for, since a single gateway cannot /// observe its siblings. pub fn validate(&self, installation_name: &str) -> crate::error::Result<()> { + for value in &self.auth_login_origins { + let valid = url::Url::parse(value).is_ok_and(|origin| { + origin.scheme() == "https" + && origin.host_str().is_some_and(|host| !host.contains('*')) + && origin.username().is_empty() + && origin.password().is_none() + && origin.path() == "/" + && origin.query().is_none() + && origin.fragment().is_none() + && origin.port() != Some(0) + }); + if !valid { + return Err(crate::error::Error::Config { + message: "service_auth_login_origins must contain HTTPS origins without credentials, paths, queries, or fragments".into(), + }); + } + } if self.service_hostname_format == ServiceHostnameFormat::Hashed && !is_dns_label(installation_name) { @@ -1615,6 +1635,7 @@ impl Default for ServiceRoutingConfig { Self { enabled: true, auth_enabled: false, + auth_login_origins: Vec::new(), base_domains: default_service_routing_domains(), enable_loopback_service_http: default_enable_loopback_service_http(), service_hostname_format: ServiceHostnameFormat::default(), @@ -2186,6 +2207,30 @@ mod tests { ); } + #[test] + fn browser_service_login_requires_exact_https_origins() { + let mut config = super::ServiceRoutingConfig::default(); + assert!(config.auth_login_origins.is_empty()); + for invalid in [ + "http://gateway.example.com", + "https://*.example.com", + "https://user:password@gateway.example.com", + "https://gateway.example.com/login", + "https://gateway.example.com?query=1", + "https://gateway.example.com#fragment", + "https://gateway.example.com:0", + "not-an-origin", + ] { + config.auth_login_origins = vec![invalid.into()]; + assert!(config.validate("gateway").is_err()); + } + config.auth_login_origins = vec![ + "https://gateway.example.com".into(), + "https://127.0.0.1:8443".into(), + ]; + config.validate("gateway").unwrap(); + } + #[test] fn service_routing_allows_loopback_plaintext_http_by_default() { let cfg = Config::new(None); diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index 6284c4214c..2ba41e821a 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -489,14 +489,17 @@ role/scope policy (`sandbox:write` when enforced) and current workspace membersh operators retain their platform grant. Internal principals are rejected. Only explicit local-development unauthenticated access bypasses this gate. -`/auth/services` hosts browser login on the control-plane origin. The application +`/auth/services` hosts browser login on an exact control-plane origin allowed by +`[openshell.gateway].service_auth_login_origins`. The empty default disables +browser login without affecting bearer or mTLS application access. The application origin receives a single-use bootstrap code bound to a browser login nonce, then a distinct host-only, Secure/HttpOnly session cookie. Shared metadata contains only credential-driver handles and hashes; the configured credential driver stores the access token. Login codes expire after two minutes, sessions after at most ten minutes or token expiry. Every request revalidates the token and workspace authorization. Session deletion, credential revocation, and redemption -CAS use the shared database. Expired metadata cleanup and admission are bounded. +CAS use the shared database. Redemption atomically replaces the pending record +without consuming another session slot. Expired metadata cleanup and admission are bounded. The application path consumes standard gateway bearer headers, or authenticates through a separate `X-OpenShell-Authorization`, browser session, or mTLS identity while preserving application bearer passthrough and cookies. Gateway headers and diff --git a/crates/openshell-server/src/auth/service_session.rs b/crates/openshell-server/src/auth/service_session.rs index 33aa181643..c06be08217 100644 --- a/crates/openshell-server/src/auth/service_session.rs +++ b/crates/openshell-server/src/auth/service_session.rs @@ -11,7 +11,7 @@ use super::{ }; use crate::{ ServerState, - persistence::{ObjectRecord, WriteCondition}, + persistence::{AtomicWrite, ObjectRecord, PersistenceError, WriteCondition}, }; use axum::{ body::{Body, to_bytes}, @@ -165,11 +165,26 @@ fn origin(value: &str) -> Result { || url.path() != "/" || url.query().is_some() || url.fragment().is_some() + || url.port() == Some(0) { return Err(Status::invalid_argument("HTTPS origin required")); } Ok(url) } + +fn trusted_login_origin(state: &ServerState, value: &str) -> Result { + let candidate = origin(value)?; + if !state + .config + .service_routing + .auth_login_origins + .iter() + .any(|allowed| origin(allowed).is_ok_and(|allowed| allowed.origin() == candidate.origin())) + { + return Err(Status::permission_denied("untrusted browser login origin")); + } + Ok(candidate) +} fn request_origin(req: &Request) -> Result { origin(&format!( "https://{}", @@ -329,19 +344,7 @@ async fn cleanup(state: &ServerState, workspace: &str) -> Result<(), Status> { || value.expires <= now() || !value.redeemed && value.pending_until <= now() { - state - .credentials - .delete_application_token( - workspace, - &value.credential_id, - credential_handle(&value)?, - ) - .await?; - state - .store - .delete(SESSION, &record.id) - .await - .map_err(|_| internal())?; + retire_session(state, &record, value).await?; } } for record in state @@ -361,6 +364,49 @@ async fn cleanup(state: &ServerState, workspace: &str) -> Result<(), Status> { Ok(()) } +async fn retire_session( + state: &ServerState, + record: &ObjectRecord, + mut value: Session, +) -> Result<(), Status> { + // Claim the exact record before touching the credential shared with a + // possible replacement. Leave a retryable tombstone if secret deletion fails. + value.revoked = true; + let claim = match state + .store + .put_if( + SESSION, + &record.id, + &record.name, + &record.workspace, + &serde_json::to_vec(&value).map_err(|_| internal())?, + None, + WriteCondition::MatchResourceVersion(record.resource_version), + ) + .await + { + Ok(claim) => claim, + Err(PersistenceError::Conflict { .. }) => return Ok(()), + Err(_) => return Err(internal()), + }; + state + .credentials + .delete_application_token( + &record.workspace, + &value.credential_id, + credential_handle(&value)?, + ) + .await?; + match state + .store + .delete_if(SESSION, &record.id, claim.resource_version) + .await + { + Ok(_) | Err(PersistenceError::Conflict { .. }) => Ok(()), + Err(_) => Err(internal()), + } +} + async fn service_origin(state: &ServerState, value: &str) -> Result<(url::Url, String), Status> { let origin = origin(value)?; let target = @@ -395,6 +441,7 @@ fn redirect(url: &url::Url) -> Result { pub async fn control(state: &ServerState, mut req: Request) -> Result { secure(&req)?; let control_origin = request_origin(&req)?; + trusted_login_origin(state, control_origin.as_str())?; if req.method() == Method::GET { let params = parameters(&req)?; let (mut target, _) = service_origin( @@ -507,7 +554,8 @@ pub async fn handle( let path = req.uri().path().to_string(); if path == format!("{PREFIX}/start") && req.method() == Method::GET { let params = parameters(req)?; - let mut login = origin(params.get("login_origin").map_or("", String::as_str))?; + let mut login = + trusted_login_origin(state, params.get("login_origin").map_or("", String::as_str))?; if crate::service_routing::resolve_service_host(state, login.host_str().unwrap_or_default()) .await .is_some() @@ -570,39 +618,27 @@ pub async fn handle( let payload = serde_json::to_vec(&value).map_err(|_| internal())?; state .store - .put_if( - SESSION, - &key, - &key, - workspace, - &payload, - None, - WriteCondition::MatchResourceVersion(record.resource_version), - ) - .await - .map_err(|_| Status::unauthenticated("login code already consumed"))?; - if state - .store - .create_if_workspace_count_below( - SESSION, - &session_key, - &session_key, - workspace, - &payload, - None, - 1024, - ) - .await - .map_err(|_| internal())? - .is_none() - { - return Err(Status::resource_exhausted("browser session limit reached")); - } - state - .store - .delete(SESSION, &key) + .write_atomically(&[ + AtomicWrite::Delete { + object_type: SESSION.into(), + id: key, + expected_version: record.resource_version, + }, + AtomicWrite::Create { + object_type: SESSION.into(), + id: session_key.clone(), + name: session_key, + workspace: workspace.into(), + payload, + }, + ]) .await - .map_err(|_| internal())?; + .map_err(|error| match error { + PersistenceError::Conflict { .. } => { + Status::unauthenticated("login code already consumed") + } + _ => internal(), + })?; let response = with_cookie( browser_complete()?, COOKIE, @@ -814,6 +850,7 @@ pub mod tests { let inner = Arc::get_mut(&mut state).unwrap(); inner.config.auth.allow_unauthenticated_users = false; inner.config.service_routing.auth_enabled = true; + inner.config.service_routing.auth_login_origins = vec![GATEWAY.into()]; inner.config.service_routing.base_domains = vec!["services.example.com".into()]; inner.config.oidc = Some(serde_json::from_value(serde_json::json!({"issuer":server.uri(),"audience":"openshell-cli","scopes_claim":"scope"})).unwrap()); inner.admin_role = "openshell-admin".into(); @@ -886,6 +923,194 @@ pub mod tests { browser_login_for(state, token, APP).await } + #[tokio::test] + async fn browser_login_uses_only_exact_trusted_control_origins() { + let (_issuer, state, _token) = fixture().await; + for candidate in [ + "https://untrusted.example", + "https://gateway.example.com.untrusted.example", + "https://gateway.example.com:8443", + ] { + let mut start = url::Url::parse(&format!("{APP}{PREFIX}/start")).unwrap(); + start + .query_pairs_mut() + .append_pair("login_origin", candidate); + let response = send(&state, request(Method::GET, start.as_str())).await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert!(!response.headers().contains_key(header::LOCATION)); + assert!(!response.headers().contains_key(header::SET_COOKIE)); + + // A direct request with a forged control Host cannot create a + // different trusted origin, even outside a browser's Origin rules. + let mut control = url::Url::parse(&format!("{candidate}{CONTROL}")).unwrap(); + control.query_pairs_mut().append_pair("service_origin", APP); + assert_eq!( + send(&state, request(Method::GET, control.as_str())) + .await + .status(), + StatusCode::FORBIDDEN + ); + } + for candidate in [GATEWAY, "https://GATEWAY.EXAMPLE.COM:443"] { + let mut start = url::Url::parse(&format!("{APP}{PREFIX}/start")).unwrap(); + start + .query_pairs_mut() + .append_pair("login_origin", candidate); + let response = send(&state, request(Method::GET, start.as_str())).await; + assert_eq!(response.status(), StatusCode::SEE_OTHER); + assert!(location(&response).starts_with(GATEWAY)); + } + } + + #[tokio::test] + async fn empty_login_origins_disable_browser_login_but_preserve_bearer_access() { + let (_issuer, mut state, token) = fixture().await; + Arc::get_mut(&mut state) + .unwrap() + .config + .service_routing + .auth_login_origins + .clear(); + let response = send( + &state, + request( + Method::GET, + &format!("{APP}{PREFIX}/start?login_origin={GATEWAY}"), + ), + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert!(!response.headers().contains_key(header::SET_COOKIE)); + let mut app = request(Method::GET, APP); + app.headers_mut().insert( + header::AUTHORIZATION, + format!("Bearer {token}").parse().unwrap(), + ); + authorize_request(&state, &mut app, "default") + .await + .unwrap(); + assert!(!app.headers().contains_key(header::AUTHORIZATION)); + } + + #[tokio::test] + async fn session_promotion_preserves_capacity_and_fences_replay_and_cleanup() { + let (_issuer, state, token) = fixture().await; + let active = Session { + host: APP.into(), + expires: now() + 600, + pending_until: 0, + login_state: String::new(), + handle: String::new(), + credential_id: String::new(), + cookie_key: String::new(), + redeemed: true, + revoked: false, + }; + let payload = serde_json::to_vec(&active).unwrap(); + let writes = (0..1023) + .map(|n| { + let id = format!("active-{n}"); + AtomicWrite::Create { + object_type: SESSION.into(), + name: id.clone(), + id, + workspace: "default".into(), + payload: payload.clone(), + } + }) + .collect::>(); + state.store.write_atomically(&writes).await.unwrap(); + + let start = send( + &state, + request( + Method::GET, + &format!("{APP}{PREFIX}/start?login_origin={GATEWAY}"), + ), + ) + .await; + let nonce_cookie = response_cookie(&start, LOGIN_COOKIE); + let login_url = url::Url::parse(&location(&start)).unwrap(); + let login_state = login_url + .query_pairs() + .find(|(key, _)| key == "state") + .unwrap() + .1 + .into_owned(); + let mut login = request(Method::POST, &format!("{GATEWAY}{CONTROL}")); + login + .headers_mut() + .insert(header::ORIGIN, GATEWAY.parse().unwrap()); + login.headers_mut().insert( + header::AUTHORIZATION, + format!("Bearer {token}").parse().unwrap(), + ); + *login.body_mut() = Body::from( + serde_json::to_vec(&serde_json::json!({"service_origin":APP,"state":login_state})) + .unwrap(), + ); + let response = send(&state, login).await; + assert_eq!(response.status(), StatusCode::OK); + let json: serde_json::Value = + serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes()) + .unwrap(); + let redeem_url = json["redirect"].as_str().unwrap(); + let code = url::Url::parse(redeem_url) + .unwrap() + .query_pairs() + .find(|(key, _)| key == "code") + .unwrap() + .1 + .into_owned(); + let pending = state + .store + .get(SESSION, &digest(&code).unwrap()) + .await + .unwrap() + .unwrap(); + let redeem = || { + let mut req = request(Method::GET, redeem_url); + req.headers_mut() + .insert(header::COOKIE, nonce_cookie.parse().unwrap()); + req + }; + let (left, right) = tokio::join!(send(&state, redeem()), send(&state, redeem())); + let successful = if left.status() == StatusCode::OK { + assert_eq!(right.status(), StatusCode::UNAUTHORIZED); + left + } else { + assert_eq!(left.status(), StatusCode::UNAUTHORIZED); + assert_eq!(right.status(), StatusCode::OK); + right + }; + assert_eq!( + state + .store + .list(SESSION, "default", 1025, 0) + .await + .unwrap() + .len(), + 1024 + ); + assert_eq!( + send(&state, redeem()).await.status(), + StatusCode::UNAUTHORIZED + ); + // Cleanup may already have selected a pending record when redemption + // replaces it. Its stale claim must not delete the active credential. + retire_session(&state, &pending, session(&pending).unwrap()) + .await + .unwrap(); + let mut app = request(Method::GET, APP); + app.headers_mut().insert( + header::COOKIE, + response_cookie(&successful, COOKIE).parse().unwrap(), + ); + authorize_request(&state, &mut app, "default") + .await + .unwrap(); + } + async fn browser_login_for(state: &Arc, token: &str, app_origin: &str) -> String { let mut url = url::Url::parse(&format!("{GATEWAY}{CONTROL}")).unwrap(); url.query_pairs_mut() @@ -1048,7 +1273,7 @@ pub mod tests { .await .unwrap_err() .code(), - tonic::Code::InvalidArgument + tonic::Code::PermissionDenied ); let cookie = browser_login_for(&state, &token, &app_origin).await; let mut application = request(Method::GET, &format!("{app_origin}/")); diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index 224a1c5bf3..d14bb80e6e 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -766,6 +766,10 @@ fn assemble_server_config( .with_service_auth(args.enable_gateway_service_auth) .with_loopback_service_http(args.enable_loopback_service_http) .with_websocket_tunnel(args.enable_websocket_tunnel); + config.service_routing.auth_login_origins = file + .as_ref() + .and_then(|file| file.openshell.gateway.service_auth_login_origins.clone()) + .unwrap_or_default(); config .service_routing .validate(&config.name) @@ -4868,6 +4872,39 @@ enabled = false }); } + #[test] + fn browser_service_login_origins_load_from_gateway_configuration() { + Environment::new().run(|| { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("gateway.toml"); + std::fs::write( + &path, + r#" +[openshell] +version = 2 +[openshell.gateway] +service_auth_login_origins = ["https://gateway.example.com:8443"] +"#, + ) + .unwrap(); + let (mut args, matches) = parse_with_args(&[ + "openshell-gateway", + "--config", + path.to_str().unwrap(), + "--db-url", + "sqlite::memory:", + "--compute-driver", + "podman", + "--disable-tls", + ]); + let prepared = super::prepare_server_config(&mut args, &matches).unwrap(); + assert_eq!( + prepared.config.service_routing.auth_login_origins, + ["https://gateway.example.com:8443"] + ); + }); + } + #[test] fn service_auth_is_opt_in_with_explicit_cli_environment_and_file_precedence() { Environment::new() diff --git a/crates/openshell-server/src/config_file/mod.rs b/crates/openshell-server/src/config_file/mod.rs index c96f7be8c5..746454d3d3 100644 --- a/crates/openshell-server/src/config_file/mod.rs +++ b/crates/openshell-server/src/config_file/mod.rs @@ -199,6 +199,9 @@ pub struct GatewayFileSection { /// Opt in to gateway authentication for sandbox application requests. #[serde(default)] pub enable_gateway_service_auth: Option, + /// Exact trusted HTTPS control-plane origins for browser service login. + #[serde(default)] + pub service_auth_login_origins: Option>, /// Subject Alternative Names configured on the gateway server certificate. /// Wildcard DNS SANs also enable sandbox service URLs under that domain. #[serde(default)] diff --git a/crates/openshell-server/src/service_routing.rs b/crates/openshell-server/src/service_routing.rs index 7df113c272..1e8e530499 100644 --- a/crates/openshell-server/src/service_routing.rs +++ b/crates/openshell-server/src/service_routing.rs @@ -2040,6 +2040,8 @@ mod tests { let addr = listener.local_addr().unwrap(); let inner = Arc::get_mut(&mut state).unwrap(); inner.config.bind_address = addr; + inner.config.service_routing.auth_login_origins = + vec![format!("https://gateway.example.test:{}", addr.port())]; inner.config.tls = Some(openshell_core::TlsConfig { cert_path: dir.path().join("server-cert.pem"), key_path: dir.path().join("server-key.pem"), diff --git a/deploy/helm/openshell/tests/gateway_config_test.yaml b/deploy/helm/openshell/tests/gateway_config_test.yaml index 5bb2d985ce..25ce590bfe 100644 --- a/deploy/helm/openshell/tests/gateway_config_test.yaml +++ b/deploy/helm/openshell/tests/gateway_config_test.yaml @@ -80,6 +80,18 @@ tests: path: data["gateway.toml"] pattern: '(?m)^enable_gateway_service_auth\s*=\s*false$' + - it: renders exact trusted browser login origins + template: templates/gateway-config.yaml + set: + gatewayConfig: + openshell.gateway: + service_auth_login_origins: + - https://gateway.example.com:8443 + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: 'service_auth_login_origins\s*=\s*\["https://gateway\.example\.com:8443"\]' + - it: disables the WebSocket tunnel unless explicitly enabled for an edge proxy template: templates/gateway-config.yaml asserts: diff --git a/docs/how-it-works/gateways/authentication.mdx b/docs/how-it-works/gateways/authentication.mdx index 319f0e7930..e93b7e00b8 100644 --- a/docs/how-it-works/gateways/authentication.mdx +++ b/docs/how-it-works/gateways/authentication.mdx @@ -57,6 +57,20 @@ application connection. Role, scope, membership, and origin denials return 403. ### Browser sessions +Configure the exact trusted control-plane origins before enabling browser login: + +```toml +[openshell.gateway] +enable_gateway_service_auth = true +service_auth_login_origins = ["https://gateway.example.com"] +``` + +The list defaults to empty, disabling browser login. Bearer and mTLS application +access do not require it. Include each public gateway origin and its port when +nonstandard; wildcards, credentials, paths, queries, and fragments are rejected. +Keep this list consistent across gateway replicas. Application origins do not +belong in this list. + Open the control-plane gateway's sign-in page with the gateway-mediated service origin as `service_origin`, for example: diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 444f85cd72..01d36db771 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2676,6 +2676,13 @@ access controls. See for browser sessions, application credential passthrough, and revocation. Direct app-listener authentication belongs to the ingress provider. +Browser login additionally requires `service_auth_login_origins` in +`[openshell.gateway]`, for example `["https://gateway.example.com:8443"]`. +Only exact HTTPS control-plane origins are allowed; wildcards, credentials, +paths, queries, and fragments are invalid. The default empty list disables +browser login while preserving bearer and mTLS application access. Helm uses +`gatewayConfig."openshell.gateway".service_auth_login_origins`. + When service authentication is enabled, TLS gateways advertise HTTPS for gateway service access, including on loopback, so clients can present an mTLS identity. The separate plaintext loopback service listener cannot accept a client-certificate identity or browser diff --git a/docs/how-it-works/sandboxes/overview.mdx b/docs/how-it-works/sandboxes/overview.mdx index 856cdcbd0d..866070042a 100644 --- a/docs/how-it-works/sandboxes/overview.mdx +++ b/docs/how-it-works/sandboxes/overview.mdx @@ -595,8 +595,10 @@ openshell service expose demo 50051 agent --backend-http-version 2 Use the printed HTTPS URL with an HTTP/2 client. The sandbox server must accept cleartext HTTP/2 with prior knowledge on the declared loopback port. -Gateway-mediated requests require configured gateway authentication and workspace -access whether the app listener is enabled or disabled. Gateway credentials are +With `[openshell.gateway].enable_gateway_service_auth = true`, gateway-mediated +requests require configured gateway authentication and workspace access whether +the app listener is enabled or disabled. The setting defaults to `false`. +When enabled, gateway credentials are consumed before forwarding. Use a browser session, mTLS identity, or separate `X-OpenShell-Authorization` gateway header when the application also needs an `Authorization` header. See [sandbox service authentication](/how-it-works/gateways/authentication#sandbox-service-requests). diff --git a/rfc/0017-sandbox-service-exposure/README.md b/rfc/0017-sandbox-service-exposure/README.md index 4da7ee6b2e..f016b546ae 100644 --- a/rfc/0017-sandbox-service-exposure/README.md +++ b/rfc/0017-sandbox-service-exposure/README.md @@ -154,13 +154,13 @@ Application TLS is configured separately from gateway TLS. Operators provide DNS SNI selects a route; it does not authenticate a user. Direct app-listener access delegates authentication to the ingress provider; implementing that authentication is outside this proposal. Preserve existing listener header handling: strip `Authorization` by default, allow explicit `bearer-passthrough`, and strip gateway/edge identity headers and edge authentication cookies. -Gateway-mediated application HTTP requests and WebSocket upgrades use configured gateway authentication and workspace authorization independently of app-listener enablement, as tracked by #4722. Use the TCP-forwarding access policy, including `sandbox:write` when scopes are enforced. Keep gateway credentials separate from application bearer passthrough and cookies; consume and strip gateway material before forwarding. Browser sessions require a control-plane login flow, origin/CSRF protections, and revocation. Missing, invalid, expired, or revoked credentials fail before application dial; insufficient permissions return 403. WebSockets authenticate at upgrade. Explicit unauthenticated local-development configurations retain their documented behavior. +Gateway-mediated application HTTP requests and WebSocket upgrades can opt into configured gateway authentication and workspace authorization with `[openshell.gateway].enable_gateway_service_auth = true` (default `false`), independently of app-listener enablement, as tracked by #4722. Use the TCP-forwarding access policy, including `sandbox:write` when scopes are enforced. Keep gateway credentials separate from application bearer passthrough and cookies; consume and strip gateway material before forwarding. Browser sessions require a control-plane login flow, origin/CSRF protections, and revocation. Missing, invalid, expired, or revoked credentials fail before application dial; insufficient permissions return 403. WebSockets authenticate at upgrade. Explicit unauthenticated local-development configurations retain their documented behavior. A passthrough proxy cannot inspect HTTP credentials. An edge that terminates TLS must reconnect with the correct service SNI and authority. Restrict supervisor listener access to prevent bypassing required edge authentication; use authenticated backend transport where network restrictions are insufficient. ### Deployment and compatibility -Enable the app-listener path explicitly. Gateway-mediated service clients independently require configured gateway credentials and workspace access; TLS gateway URLs retain HTTPS on loopback to support client certificates. CLI/SDK URLs must use the application ingress domain and public port independently of the gateway endpoint. Status should distinguish configured, advertised, and unavailable routes. Domain migrations require coordinated DNS, TLS, and client changes. +Enable the app-listener path explicitly. When gateway service authentication is enabled, gateway-mediated service clients require configured gateway credentials and workspace access, and TLS gateway URLs retain HTTPS on loopback to support client certificates. CLI/SDK URLs must use the application ingress domain and public port independently of the gateway endpoint. Status should distinguish configured, advertised, and unavailable routes. Domain migrations require coordinated DNS, TLS, and client changes. ## Implementation plan diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index d109447f8f..08fa7c1267 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1999,7 +1999,9 @@ WebSocket upgrades require configured gateway authentication and workspace user access with the app listener disabled or enabled. OIDC scope enforcement requires `sandbox:write` (or `openshell:all`), as for TCP forwarding. Check HTTP 401 for missing/invalid/expired/revoked credentials and 403 for role/scope/membership/origin denial. Browser login starts -at the control-plane `/auth/services?service_origin=...`; the app host receives +at the control-plane `/auth/services?service_origin=...`. Configure exact trusted control-plane origins in +`openshell.gateway.service_auth_login_origins`. An empty list disables browser +login; include the public port and use the same list on every replica. The app host receives only a single-use code and a Secure/HttpOnly cookie. Check shared database and credential-driver availability across replicas. Browser sessions expire within ten minutes and reauthorize on every request. DELETE the same-origin app paths From 1283059f95ad23b89b4420a79ca9528eb22305c5 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Fri, 20 Nov 2026 12:41:36 -0800 Subject: [PATCH 12/15] fix(auth): stabilize revocation and isolate ingress cookies Signed-off-by: Taylor Mutch --- crates/openshell-server/src/auth/oidc.rs | 100 ++++++++++++++++++ .../src/auth/service_session.rs | 16 ++- crates/openshell-supervisor/README.md | 3 +- .../openshell-supervisor/src/app_listener.rs | 100 ++++++++++++++++-- docs/how-it-works/gateways/authentication.mdx | 6 +- 5 files changed, 213 insertions(+), 12 deletions(-) diff --git a/crates/openshell-server/src/auth/oidc.rs b/crates/openshell-server/src/auth/oidc.rs index 92fa899c97..db5c02598e 100644 --- a/crates/openshell-server/src/auth/oidc.rs +++ b/crates/openshell-server/src/auth/oidc.rs @@ -2103,6 +2103,106 @@ pub mod tests { } } + #[tokio::test] + async fn application_revocation_covers_equivalent_ecdsa_signatures() { + use crate::auth::{service_access, service_session}; + use axum::body::Body; + use http::{HeaderMap, Method, Request, StatusCode, header}; + use tower::ServiceExt; + + for (curve, order) in [ + ( + "P-256", + "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", + ), + ( + "P-384", + "ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973", + ), + ] { + let key = ec_test_key("application-key", curve); + let (cache, issuer, mut config, _issuer_server) = + cache_from_jwks(serde_json::json!({"keys": [key.jwk]})).await; + config.scopes_claim.clear(); + let (_server, mut state, _) = service_session::tests::fixture().await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.admin_role.clone_from(&config.admin_role); + let role = config.user_role.clone(); + inner.config.oidc = Some(config.clone()); + inner.oidc_cache = Some(Arc::new(cache)); + let mut header = Header::new(key.algorithm); + header.kid = Some(key.kid); + let mut claims = serde_json::json!({ + "sub": "user-42", "iss": issuer, "aud": config.audience, + "exp": now_secs() + 3600, "roles": [role], "jti": "original" + }); + let token = encode(&header, &claims, &key.encoding_key).unwrap(); + let (signed, encoded_signature) = token.rsplit_once('.').unwrap(); + let mut signature = URL_SAFE_NO_PAD.decode(encoded_signature).unwrap(); + let width = signature.len() / 2; + // ECDSA (r, n-s) verifies the same authenticated signing input. + let mut borrow = 0i16; + for i in (0..width).rev() { + let n = u8::from_str_radix(&order[2 * i..2 * i + 2], 16).unwrap(); + let result = i16::from(n) - i16::from(signature[width + i]) - borrow; + borrow = i16::from(result < 0); + signature[width + i] = u8::try_from(result.rem_euclid(256)).unwrap(); + } + assert_eq!(borrow, 0); + let twin = format!("{signed}.{}", URL_SAFE_NO_PAD.encode(signature)); + assert_ne!(token, twin); + let headers = |token: &str| { + let mut headers = HeaderMap::new(); + headers.insert( + header::AUTHORIZATION, + format!("Bearer {token}").parse().unwrap(), + ); + headers + }; + let peer = service_access::ServicePeer { + secure: true, + ..Default::default() + }; + for variant in [&token, &twin] { + service_access::authorize(&state, &headers(variant), &peer, "default") + .await + .unwrap(); + } + let app = "https://default--demo--web.services.example.com"; + let mut revoke = Request::builder() + .method(Method::DELETE) + .uri(format!("{app}/.openshell/service-auth/credential")) + .header(header::HOST, "default--demo--web.services.example.com") + .header(header::ORIGIN, app) + .header(header::AUTHORIZATION, format!("Bearer {twin}")) + .body(Body::empty()) + .unwrap(); + revoke.extensions_mut().insert(peer.clone()); + assert_eq!( + crate::http::http_router(state.clone()) + .oneshot(revoke) + .await + .unwrap() + .status(), + StatusCode::NO_CONTENT + ); + for variant in [&token, &twin] { + assert_eq!( + service_access::authorize(&state, &headers(variant), &peer, "default") + .await + .unwrap_err() + .code(), + tonic::Code::Unauthenticated + ); + } + claims["jti"] = "fresh".into(); + let fresh = encode(&header, &claims, &key.encoding_key).unwrap(); + service_access::authorize(&state, &headers(&fresh), &peer, "default") + .await + .unwrap(); + } + } + #[tokio::test] async fn unsupported_curve_is_skipped() { let signing = rsa_test_key("good"); diff --git a/crates/openshell-server/src/auth/service_session.rs b/crates/openshell-server/src/auth/service_session.rs index c06be08217..686e668be5 100644 --- a/crates/openshell-server/src/auth/service_session.rs +++ b/crates/openshell-server/src/auth/service_session.rs @@ -100,13 +100,25 @@ fn token_expiry(token: &str) -> Result { .ok_or_else(|| Status::unauthenticated("token expiration required")) } +// Called after authentication. Equivalent signatures must identify the same +// revoked credential; the authenticated signing input is unchanged by them. +fn token_revocation_key(token: &str) -> Result { + let invalid = || Status::unauthenticated("invalid token"); + let (signed, signature) = token.rsplit_once('.').ok_or_else(invalid)?; + let (header, payload) = signed.split_once('.').ok_or_else(invalid)?; + if header.is_empty() || payload.is_empty() || payload.contains('.') || signature.is_empty() { + return Err(invalid()); + } + Ok(format!("jwt-{}", digest(signed)?)) +} + pub async fn check_token(state: &ServerState, token: &str) -> Result<(), Status> { if token.len() > 16384 || token_expiry(token)? <= now() { return Err(Status::unauthenticated("expired or invalid credential")); } if state .store - .get(REVOKED, &digest(token)?) + .get(REVOKED, &token_revocation_key(token)?) .await .map_err(|_| internal())? .is_some() @@ -711,7 +723,7 @@ pub async fn handle( } let token = authorize_request(state, req, workspace).await?; let (key, expires) = if let Some(token) = token { - (digest(&token)?, token_expiry(&token)?) + (token_revocation_key(&token)?, token_expiry(&token)?) } else { let fingerprint = req .extensions() diff --git a/crates/openshell-supervisor/README.md b/crates/openshell-supervisor/README.md index 97f27cd129..0aae46b8ca 100644 --- a/crates/openshell-supervisor/README.md +++ b/crates/openshell-supervisor/README.md @@ -315,7 +315,8 @@ supervisor to reload application certificates. This path uses application or trusted-edge authentication independently from gateway authentication. It validates Host against SNI, preserves public Host/Origin and application cookies, strips gateway/edge identity material, and -retains service-specific bearer passthrough. Hop-by-hop headers are removed from +retains service-specific bearer passthrough. Reserved gateway authentication cookies +are removed from both requests and responses. Hop-by-hop headers are removed from requests and responses, preserving successful WebSocket upgrades. An application closing its upstream HTTP connection does not close the client connection. It has no discovery API or public diff --git a/crates/openshell-supervisor/src/app_listener.rs b/crates/openshell-supervisor/src/app_listener.rs index 7178561b1d..24c3f36b9f 100644 --- a/crates/openshell-supervisor/src/app_listener.rs +++ b/crates/openshell-supervisor/src/app_listener.rs @@ -1017,12 +1017,7 @@ fn sanitize_headers(headers: &mut http::HeaderMap, passthrough: bool, websocket: cookie.split_once('=').is_some_and(|(name, _)| { !name.trim().eq_ignore_ascii_case("CF_Authorization") && !name.trim().eq_ignore_ascii_case("cf-authorization") - && !name - .trim() - .eq_ignore_ascii_case("__Host-openshell-service-session") - && !name - .trim() - .eq_ignore_ascii_case("__Host-openshell-service-login") + && !gateway_cookie_name(name.trim().as_bytes()) }) }) .map(str::trim) @@ -1037,6 +1032,31 @@ fn sanitize_headers(headers: &mut http::HeaderMap, passthrough: bool, websocket: true } +fn gateway_cookie_name(name: &[u8]) -> bool { + name.eq_ignore_ascii_case(b"__Host-openshell-service-session") + || name.eq_ignore_ascii_case(b"__Host-openshell-service-login") +} + +fn strip_gateway_response_cookies(headers: &mut http::HeaderMap) { + let cookies: Vec<_> = headers + .get_all(header::SET_COOKIE) + .iter() + .filter(|value| { + let name = value + .as_bytes() + .split(|byte| *byte == b'=') + .next() + .unwrap_or_default(); + !gateway_cookie_name(name.trim_ascii()) + }) + .cloned() + .collect(); + headers.remove(header::SET_COOKIE); + for cookie in cookies { + headers.append(header::SET_COOKIE, cookie); + } +} + async fn proxy( mut req: Request, sni: String, @@ -1121,6 +1141,7 @@ async fn proxy( }; let upgraded = response.status() == StatusCode::SWITCHING_PROTOCOLS && websocket; strip_hop_headers(response.headers_mut(), upgraded); + strip_gateway_response_cookies(response.headers_mut()); if upgraded { let upstream = hyper::upgrade::on(&mut response); let downstream = downstream.expect("websocket upgrade"); @@ -1574,6 +1595,15 @@ mod tests { .header("connection", "upgrade") .header("upgrade", "websocket") .header("sec-websocket-accept", accept) + .header( + header::SET_COOKIE, + "__Host-openshell-service-login=untrusted; Secure; Path=/", + ) + .header( + header::SET_COOKIE, + "__Host-openshell-service-session=untrusted; Secure; Path=/", + ) + .header(header::SET_COOKIE, "app=session; HttpOnly") .header("x-test-upstream-host", req.headers()[header::HOST].clone()) .header( "x-test-upstream-origin", @@ -1616,7 +1646,20 @@ mod tests { .and_then(|v| v.to_str().ok()) .unwrap_or("absent") ); - Ok::<_, std::convert::Infallible>(Response::new(Body::from(body))) + Ok::<_, std::convert::Infallible>( + Response::builder() + .header( + header::SET_COOKIE, + "__Host-openshell-service-login=untrusted; Secure; Path=/", + ) + .header( + header::SET_COOKIE, + "__Host-openshell-service-session=untrusted; Secure; Path=/", + ) + .header(header::SET_COOKIE, "app=session; HttpOnly") + .body(Body::from(body)) + .unwrap(), + ) }); let _ = hyper::server::conn::http1::Builder::new() .serve_connection(TokioIo::new(server), service) @@ -2060,6 +2103,38 @@ mod tests { ); } + #[test] + fn response_cookies_reserve_only_gateway_auth_names() { + let mut headers = http::HeaderMap::new(); + for value in [ + b"__Host-openshell-service-session=blocked".as_slice(), + b" __HOST-openshell-service-login =blocked", + b"__Host-openshell-service-login=\xff", + b"app=session; HttpOnly", + b"__Host-openshell-app=allowed", + b"opaque=\xff", + ] { + headers.append( + header::SET_COOKIE, + http::HeaderValue::from_bytes(value).unwrap(), + ); + } + strip_gateway_response_cookies(&mut headers); + let cookies: Vec<_> = headers + .get_all(header::SET_COOKIE) + .iter() + .map(http::HeaderValue::as_bytes) + .collect(); + assert_eq!( + cookies, + vec![ + b"app=session; HttpOnly".as_slice(), + b"__Host-openshell-app=allowed", + b"opaque=\xff" + ] + ); + } + #[tokio::test] async fn tls_routes_only_matching_sni_and_authority() { let f = fixture(); @@ -2075,6 +2150,11 @@ mod tests { response.contains(&format!("/hello?x=1 {HOST}:18443 stripped")), "{response}" ); + assert!( + !response.contains("__Host-openshell-service-"), + "{response}" + ); + assert!(response.contains("app=session; HttpOnly"), "{response}"); let mismatch = request( &f, HOST, @@ -2211,6 +2291,12 @@ mod tests { format!("https://{hostname}").parse().unwrap(), ); let (mut ws, response) = tokio_tungstenite::client_async(request, tls).await.unwrap(); + let cookies: Vec<_> = response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .collect(); + assert_eq!(cookies, vec!["app=session; HttpOnly"]); assert_eq!(response.headers()["x-test-upstream-host"], hostname); assert_eq!( response.headers()["x-test-upstream-origin"], diff --git a/docs/how-it-works/gateways/authentication.mdx b/docs/how-it-works/gateways/authentication.mdx index e93b7e00b8..6c3eda7c17 100644 --- a/docs/how-it-works/gateways/authentication.mdx +++ b/docs/how-it-works/gateways/authentication.mdx @@ -126,7 +126,8 @@ curl --request DELETE \ ``` Revocation is durable across gateway replicas and rejects subsequent application -requests, including browser sessions using that token. Obtain a new token or +requests, including browser sessions using that token and equivalent token +signatures. Obtain a new token or rotate the client certificate to regain access. Revocation targets gateway application access; it does not revoke the identity provider's token or alter control-plane RPC credentials. Offline OIDC JWT validation cannot discover an @@ -138,7 +139,8 @@ it admits at most 1,024 outstanding application credential revocations. Direct supervisor app-listener access delegates authentication to the ingress provider. Gateway browser sessions and credentials do not authorize that path. The listener strips the gateway's `__Host-openshell-service-session` and -`__Host-openshell-service-login` cookies, while preserving other application +`__Host-openshell-service-login` cookies from requests and responses, while +preserving other application cookies, including names such as `__Host-openshell-app`. ## Gateway Resolution From 6de1b8294ee12ea27ed87a1a55d67807d38031eb Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Tue, 24 Nov 2026 12:27:31 -0800 Subject: [PATCH 13/15] fix(auth): filter reserved cookies from HTTP/2 responses Signed-off-by: Taylor Mutch --- .../openshell-supervisor/src/app_listener.rs | 9 ++++ .../src/app_listener/tests/http2.rs | 50 +++++++++++++++++-- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/crates/openshell-supervisor/src/app_listener.rs b/crates/openshell-supervisor/src/app_listener.rs index 24c3f36b9f..e26f3f82ba 100644 --- a/crates/openshell-supervisor/src/app_listener.rs +++ b/crates/openshell-supervisor/src/app_listener.rs @@ -1219,6 +1219,7 @@ async fn proxy_http2( return error(StatusCode::BAD_GATEWAY); }; strip_hop_headers(response.headers_mut(), false); + strip_gateway_response_cookies(response.headers_mut()); response.map(|body| relay_body(body, active)) } @@ -1622,6 +1623,14 @@ mod tests { .header("x-upstream-only", "private") .header("keep-alive", "timeout=1") .header(header::CONTENT_TYPE, "text/plain") + .header( + header::SET_COOKIE, + "__Host-openshell-service-login=untrusted; Secure; Path=/", + ) + .header( + header::SET_COOKIE, + "__Host-openshell-service-session=untrusted; Secure; Path=/", + ) .header(header::SET_COOKIE, "app=session; HttpOnly") .body(Body::from("upstream closed")) .unwrap()); diff --git a/crates/openshell-supervisor/src/app_listener/tests/http2.rs b/crates/openshell-supervisor/src/app_listener/tests/http2.rs index c8f93ce716..147bd55e47 100644 --- a/crates/openshell-supervisor/src/app_listener/tests/http2.rs +++ b/crates/openshell-supervisor/src/app_listener/tests/http2.rs @@ -128,6 +128,32 @@ struct Message { text: String, } +#[tokio::test] +async fn http2_frontend_filters_reserved_cookies_from_http1_backend() { + let f = fixture(); + let mut client = http2_client(&f).await; + let response = client + .send_request( + Request::get(format!("https://{HOST}/close")) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let cookies: Vec<_> = response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .map(|value| value.to_str().unwrap()) + .collect(); + assert_eq!(cookies, vec!["app=session; HttpOnly"]); + assert_eq!( + response.into_body().collect().await.unwrap().to_bytes(), + "upstream closed" + ); +} + struct Echo(Arc); struct NotifyOnDrop(Arc); @@ -181,9 +207,18 @@ impl rpc_test::BoundaryLoopbackConnector for GrpcBackend { assert_eq!(request.version(), Version::HTTP_2); assert_eq!(request.headers()[header::TE], "trailers"); assert_eq!(request.headers()["grpc-timeout"], "30000000u"); - let response = tonic::server::Grpc::new(tonic_prost::ProstCodec::default()) + let mut response = tonic::server::Grpc::new(tonic_prost::ProstCodec::default()) .streaming(Echo(cancelled), request) .await; + for cookie in [ + "__Host-openshell-service-login=untrusted; Secure; Path=/", + "__Host-openshell-service-session=untrusted; Secure; Path=/", + "app=session; HttpOnly", + ] { + response + .headers_mut() + .append(header::SET_COOKIE, cookie.parse().unwrap()); + } Ok::<_, std::convert::Infallible>(response) } }); @@ -237,15 +272,22 @@ async fn native_grpc_streams_preserve_deadlines_status_and_per_stream_cancellati let mut request = tonic::Request::new(tokio_stream::wrappers::ReceiverStream::new(rx)); request.set_timeout(Duration::from_secs(30)); grpc.ready().await.unwrap(); - let mut response = grpc + let response = grpc .streaming( request, http::uri::PathAndQuery::from_static("/test.Echo/Stream"), tonic_prost::ProstCodec::::default(), ) .await - .unwrap() - .into_inner(); + .unwrap(); + let cookies: Vec<_> = response + .metadata() + .get_all("set-cookie") + .iter() + .map(|value| value.to_str().unwrap()) + .collect(); + assert_eq!(cookies, vec!["app=session; HttpOnly"]); + let mut response = response.into_inner(); assert_eq!(response.message().await.unwrap().unwrap().text, "hello"); calls.push((tx, response)); } From 08aef23c3fd9511f42772aac6ab60ec3566933db Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Mon, 30 Nov 2026 20:05:17 -0800 Subject: [PATCH 14/15] fix(auth): isolate service quotas and bound application sessions Signed-off-by: Taylor Mutch --- crates/openshell-core/src/app_listener.rs | 6 + crates/openshell-core/src/config.rs | 26 +- crates/openshell-server/README.md | 9 +- crates/openshell-server/src/auth/http.rs | 4 +- .../src/auth/service_access.rs | 2 + .../src/auth/service_session.rs | 742 +++++++++++++++--- crates/openshell-server/src/cli.rs | 17 +- crates/openshell-server/src/lib.rs | 15 +- crates/openshell-server/src/multiplex.rs | 28 + .../openshell-server/src/service_routing.rs | 82 +- .../tests/browser-service-auth.cjs | 2 +- .../openshell-supervisor/src/app_listener.rs | 11 +- deploy/helm/openshell/README.md | 2 + deploy/helm/openshell/values.yaml | 4 + deploy/man/openshell-gateway.8.md | 3 +- docs/how-it-works/gateways/authentication.mdx | 19 +- docs/how-it-works/gateways/configuration.mdx | 1 + rfc/0017-sandbox-service-exposure/README.md | 2 +- skills/debug-openshell-cluster/SKILL.md | 5 + tasks/rust.toml | 4 + 20 files changed, 821 insertions(+), 163 deletions(-) diff --git a/crates/openshell-core/src/app_listener.rs b/crates/openshell-core/src/app_listener.rs index 653c603186..5db86c3cd7 100644 --- a/crates/openshell-core/src/app_listener.rs +++ b/crates/openshell-core/src/app_listener.rs @@ -6,6 +6,12 @@ use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; +/// 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") + || name.eq_ignore_ascii_case(b"__Host-openshell-service-login") +} + /// Explicitly enabled application ingress. Deployment details such as TLS /// Secret names belong to the driver, not to this common configuration. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index 0c38cd311e..7f4c47a134 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -519,10 +519,10 @@ pub struct ServiceRoutingConfig { pub enabled: bool, /// Opt in to gateway authentication for proxied application requests. /// Independent of the supervisor application listener. - pub auth_enabled: bool, + pub enable_gateway_service_auth: bool, /// Exact trusted HTTPS control-plane origins for browser service login. /// Empty disables browser login without affecting bearer or mTLS access. - pub auth_login_origins: Vec, + pub service_auth_login_origins: Vec, /// Base domains accepted for `sandbox--service.` routes. /// The first domain is used when the gateway prints endpoint URLs. @@ -580,7 +580,7 @@ impl ServiceRoutingConfig { /// deploying platform is responsible for, since a single gateway cannot /// observe its siblings. pub fn validate(&self, installation_name: &str) -> crate::error::Result<()> { - for value in &self.auth_login_origins { + for value in &self.service_auth_login_origins { let valid = url::Url::parse(value).is_ok_and(|origin| { origin.scheme() == "https" && origin.host_str().is_some_and(|host| !host.contains('*')) @@ -1610,7 +1610,7 @@ impl Config { /// Opt in to configured gateway authentication on application requests. #[must_use] pub const fn with_service_auth(mut self, enabled: bool) -> Self { - self.service_routing.auth_enabled = enabled; + self.service_routing.enable_gateway_service_auth = enabled; self } @@ -1634,8 +1634,8 @@ impl Default for ServiceRoutingConfig { fn default() -> Self { Self { enabled: true, - auth_enabled: false, - auth_login_origins: Vec::new(), + enable_gateway_service_auth: false, + service_auth_login_origins: Vec::new(), base_domains: default_service_routing_domains(), enable_loopback_service_http: default_enable_loopback_service_http(), service_hostname_format: ServiceHostnameFormat::default(), @@ -2210,7 +2210,7 @@ mod tests { #[test] fn browser_service_login_requires_exact_https_origins() { let mut config = super::ServiceRoutingConfig::default(); - assert!(config.auth_login_origins.is_empty()); + assert!(config.service_auth_login_origins.is_empty()); for invalid in [ "http://gateway.example.com", "https://*.example.com", @@ -2221,10 +2221,10 @@ mod tests { "https://gateway.example.com:0", "not-an-origin", ] { - config.auth_login_origins = vec![invalid.into()]; + config.service_auth_login_origins = vec![invalid.into()]; assert!(config.validate("gateway").is_err()); } - config.auth_login_origins = vec![ + config.service_auth_login_origins = vec![ "https://gateway.example.com".into(), "https://127.0.0.1:8443".into(), ]; @@ -2239,8 +2239,12 @@ mod tests { vec![DEFAULT_SERVICE_ROUTING_DOMAIN.to_string()] ); assert!(cfg.service_routing.enable_loopback_service_http); - assert!(!cfg.service_routing.auth_enabled); - assert!(cfg.with_service_auth(true).service_routing.auth_enabled); + assert!(!cfg.service_routing.enable_gateway_service_auth); + assert!( + cfg.with_service_auth(true) + .service_routing + .enable_gateway_service_auth + ); } #[test] diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index 2ba41e821a..c5d6bb621a 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -499,7 +499,12 @@ stores the access token. Login codes expire after two minutes, sessions after at most ten minutes or token expiry. Every request revalidates the token and workspace authorization. Session deletion, credential revocation, and redemption CAS use the shared database. Redemption atomically replaces the pending record -without consuming another session slot. Expired metadata cleanup and admission are bounded. +without consuming another session slot. Admission is per authenticated principal: +1,024 sessions and 12 login attempts per rolling minute, enforced in the shared +store. A paginated background reaper retires expired sessions, credential secrets, +and revocations on a ten-second cadence. WebSockets close at session/credential +expiry and check shared revocation state every five seconds with a two-second +check timeout. The application path consumes standard gateway bearer headers, or authenticates through a separate `X-OpenShell-Authorization`, browser session, or mTLS identity while preserving application bearer passthrough and cookies. Gateway headers and @@ -513,7 +518,7 @@ credentials. Run it with `OPENSHELL_BROWSER_E2E_CHROME` pointing to Chrome: ```shell OPENSHELL_BROWSER_E2E_CHROME='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' \ - cargo test -p openshell-server --lib gateway_service_auth_real_browser_cross_site_login -- --ignored + mise run test:gateway-service-auth:browser ``` ## Application URL publication diff --git a/crates/openshell-server/src/auth/http.rs b/crates/openshell-server/src/auth/http.rs index 725e119d77..01614163f9 100644 --- a/crates/openshell-server/src/auth/http.rs +++ b/crates/openshell-server/src/auth/http.rs @@ -91,7 +91,9 @@ fn sanitize_callback_host(raw: &Option) -> (String, String) { /// Create the auth router. pub fn router(state: Arc) -> Router { let mut router = Router::new(); - if state.config.service_routing.enabled && state.config.service_routing.auth_enabled { + if state.config.service_routing.enabled + && state.config.service_routing.enable_gateway_service_auth + { router = router.route( "/auth/services", get(service_browser_login).post(service_browser_login), diff --git a/crates/openshell-server/src/auth/service_access.rs b/crates/openshell-server/src/auth/service_access.rs index 76236d8c1e..3a03577c30 100644 --- a/crates/openshell-server/src/auth/service_access.rs +++ b/crates/openshell-server/src/auth/service_access.rs @@ -27,6 +27,7 @@ pub struct ServicePeer { pub secure: bool, pub identity: Option, pub certificate_sha256: Option, + pub certificate_expires_at_ms: Option, pub source: Option, } @@ -445,6 +446,7 @@ mod tests { let peer = ServicePeer { identity: Some(user), certificate_sha256: Some("verified-fingerprint".into()), + certificate_expires_at_ms: Some(openshell_core::time::now_ms() + 60_000), source: None, secure: true, }; diff --git a/crates/openshell-server/src/auth/service_session.rs b/crates/openshell-server/src/auth/service_session.rs index 686e668be5..d38e3ecfdf 100644 --- a/crates/openshell-server/src/auth/service_session.rs +++ b/crates/openshell-server/src/auth/service_session.rs @@ -31,7 +31,14 @@ pub const GATEWAY_AUTH: &str = "x-openshell-authorization"; const LOGIN_COOKIE: &str = "__Host-openshell-service-login"; const SESSION: &str = "gateway_application_session"; const REVOKED: &str = "gateway_application_revocation"; -const REVOCATION_SCOPE: &str = "__gateway_application_auth"; +const LOGIN_ATTEMPT: &str = "gateway_application_login_attempt"; +const RETIRED: &str = "gateway_application_retired_session"; +const PRINCIPAL_LIMIT: u16 = 1024; +const CLEANUP_PAGE_SIZE: u16 = 128; +const LOGIN_RATE_LIMIT: u64 = 12; +const LOGIN_WINDOW: u64 = 60; +const SESSION_LIFETIME: u64 = 600; +const CLEANUP_INTERVAL: std::time::Duration = std::time::Duration::from_secs(10); #[derive(Serialize, Deserialize)] struct Session { @@ -41,7 +48,8 @@ struct Session { login_state: String, handle: String, credential_id: String, - cookie_key: String, + #[serde(default)] + workspace: String, redeemed: bool, revoked: bool, } @@ -70,7 +78,11 @@ fn random() -> Result { .map_err(|_| internal()) } fn session(record: &ObjectRecord) -> Result { - serde_json::from_slice(&record.payload).map_err(|_| internal()) + let mut value: Session = serde_json::from_slice(&record.payload).map_err(|_| internal())?; + if value.workspace.is_empty() { + value.workspace.clone_from(&record.workspace); + } + Ok(value) } fn credential_handle(value: &Session) -> Result { CredentialHandle::decode( @@ -112,7 +124,7 @@ fn token_revocation_key(token: &str) -> Result { Ok(format!("jwt-{}", digest(signed)?)) } -pub async fn check_token(state: &ServerState, token: &str) -> Result<(), Status> { +pub(super) async fn check_token(state: &ServerState, token: &str) -> Result<(), Status> { if token.len() > 16384 || token_expiry(token)? <= now() { return Err(Status::unauthenticated("expired or invalid credential")); } @@ -130,7 +142,10 @@ pub async fn check_token(state: &ServerState, token: &str) -> Result<(), Status> Ok(()) } -pub async fn check_certificate(state: &ServerState, fingerprint: &str) -> Result<(), Status> { +pub(super) async fn check_certificate( + state: &ServerState, + fingerprint: &str, +) -> Result<(), Status> { if state .store .get(REVOKED, &format!("mtls-{fingerprint}")) @@ -189,7 +204,7 @@ fn trusted_login_origin(state: &ServerState, value: &str) -> Result Result { +) -> Result<(String, u64), Status> { let key = digest(value)?; let record = state .store @@ -266,10 +281,9 @@ async fn active_token( .ok_or_else(|| Status::unauthenticated("session expired or revoked"))?; let session = session(&record)?; if !session.redeemed - || session.cookie_key != key || session.revoked || session.host != host - || record.workspace != workspace + || session.workspace != workspace || session.expires <= now() { return Err(Status::unauthenticated("session expired or wrong host")); @@ -282,6 +296,74 @@ async fn active_token( credential_handle(&session)?, ) .await + .map(|token| (token, session.expires)) +} + +/// Only non-secret identifiers survive the HTTP authentication boundary. +#[derive(Clone, Default)] +pub struct UpgradeAuthorization { + expires: Option, + session: Option, + revocations: Vec, +} + +impl UpgradeAuthorization { + fn bound(&mut self, expiry: u64) { + self.expires = Some(self.expires.map_or(expiry, |previous| previous.min(expiry))); + } + + async fn check(&self, state: &ServerState) -> Result<(), Status> { + if self.expires.is_some_and(|expiry| expiry <= now()) { + return Err(Status::unauthenticated("application credential expired")); + } + if let Some(key) = &self.session { + let record = state + .store + .get(SESSION, key) + .await + .map_err(|_| internal())? + .ok_or_else(|| Status::unauthenticated("application session ended"))?; + let value = session(&record)?; + if value.revoked || !value.redeemed || value.expires <= now() { + return Err(Status::unauthenticated("application session ended")); + } + } + for key in &self.revocations { + if state + .store + .get(REVOKED, key) + .await + .map_err(|_| internal())? + .is_some() + { + return Err(Status::unauthenticated("application credential revoked")); + } + } + Ok(()) + } + + pub async fn until_invalid(&self, state: &ServerState) { + let expiry = async { + if let Some(expiry) = self.expires { + tokio::time::sleep(std::time::Duration::from_secs(expiry.saturating_sub(now()))) + .await; + } else { + std::future::pending::<()>().await; + } + }; + tokio::pin!(expiry); + let mut interval = tokio::time::interval(std::time::Duration::from_secs(5)); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + tokio::select! { () = &mut expiry => return, _ = interval.tick() => {} } + if !matches!( + tokio::time::timeout(std::time::Duration::from_secs(2), self.check(state)).await, + Ok(Ok(())) + ) { + return; + } + } + } } pub async fn authorize_request( @@ -303,11 +385,14 @@ pub async fn authorize_request( } let mut headers = req.headers().clone(); let mut consumed = false; + let mut upgrade = UpgradeAuthorization::default(); let token = if let Some(value) = session { secure(req)?; ambient_request(req)?; let host = request_origin(req)?.origin().ascii_serialization(); - let token = active_token(state, &host, workspace, &value).await?; + let (token, expires) = active_token(state, &host, workspace, &value).await?; + upgrade.session = Some(digest(&value)?); + upgrade.bound(expires); headers.insert( header::AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {token}")).map_err(|_| internal())?, @@ -333,7 +418,26 @@ pub async fn authorize_request( consumed = true; super::authenticator::bearer_credential(&headers).map(str::to_string) }; - service_access::authorize(state, &headers, &peer, workspace).await?; + let principal = service_access::authorize(state, &headers, &peer, workspace).await?; + req.extensions_mut().insert(ApplicationPrincipal(principal)); + if let Some(token) = &token { + upgrade.bound(token_expiry(token)?); + upgrade.revocations.push(token_revocation_key(token)?); + } + if (state.config.mtls_auth.enabled || state.config.mtls_auth.operator_enabled) + && let Some(fingerprint) = &peer.certificate_sha256 + { + let expiry = peer + .certificate_expires_at_ms + .and_then(|ms| u64::try_from(ms / 1000).ok()) + .ok_or_else(|| Status::unauthenticated("verified certificate expiration required"))?; + upgrade.bound(expiry); + upgrade.revocations.push(format!("mtls-{fingerprint}")); + } + if upgrade.expires.is_some_and(|expiry| expiry <= now()) { + return Err(Status::unauthenticated("application credential expired")); + } + req.extensions_mut().insert(upgrade); if consumed || token.as_deref().is_some_and(|gateway| { super::authenticator::bearer_credential(req.headers()) == Some(gateway) @@ -344,38 +448,133 @@ pub async fn authorize_request( Ok(token) } -async fn cleanup(state: &ServerState, workspace: &str) -> Result<(), Status> { - for record in state - .store - .list(SESSION, workspace, 1024, 0) - .await - .map_err(|_| internal())? - { - let value = session(&record)?; +#[derive(Clone)] +struct ApplicationPrincipal(Principal); + +fn principal_scope(principal: &Principal) -> Result { + let identity = principal + .user_identity() + .ok_or_else(|| Status::permission_denied("user identity required"))?; + digest(&format!("{:?}:{}", identity.provider, identity.subject)) +} + +async fn cleanup_record(state: &ServerState, record: &ObjectRecord) -> Result<(), Status> { + if record.object_type == SESSION || record.object_type == RETIRED { + let value = session(record)?; if value.revoked || value.expires <= now() || !value.redeemed && value.pending_until <= now() { - retire_session(state, &record, value).await?; + retire_session(state, record, value).await?; + } + } else if serde_json::from_slice::(&record.payload).map_err(|_| internal())? <= now() { + match state + .store + .delete_if(&record.object_type, &record.id, record.resource_version) + .await + { + Ok(_) | Err(PersistenceError::Conflict { .. }) => {} + Err(_) => return Err(internal()), } } + Ok(()) +} + +async fn cleanup_scope(state: &ServerState, kind: &str, owner: &str) -> Result<(), Status> { for record in state .store - .list(REVOKED, REVOCATION_SCOPE, 1024, 0) + .list(kind, owner, u32::from(PRINCIPAL_LIMIT), 0) .await .map_err(|_| internal())? { - if serde_json::from_slice::(&record.payload).map_err(|_| internal())? <= now() { - state - .store - .delete(REVOKED, &record.id) - .await - .map_err(|_| internal())?; - } + cleanup_record(state, &record).await?; } Ok(()) } +async fn admit_login(state: &ServerState, owner: &str) -> Result<(), Status> { + cleanup_scope(state, LOGIN_ATTEMPT, owner).await?; + let key = random()?; + state + .store + .create_if_workspace_count_below( + LOGIN_ATTEMPT, + &key, + &key, + owner, + &serde_json::to_vec(&(now() + LOGIN_WINDOW)).map_err(|_| internal())?, + None, + LOGIN_RATE_LIMIT, + ) + .await + .map_err(|_| internal())? + .ok_or_else(|| Status::resource_exhausted("browser login rate limit reached"))?; + cleanup_scope(state, SESSION, owner).await?; + if state + .store + .list(SESSION, owner, u32::from(PRINCIPAL_LIMIT), 0) + .await + .map_err(|_| internal())? + .len() + >= usize::from(PRINCIPAL_LIMIT) + { + return Err(Status::resource_exhausted("browser session limit reached")); + } + Ok(()) +} + +pub fn spawn_cleanup( + state: std::sync::Arc, + mut shutdown: tokio::sync::watch::Receiver, +) { + // Existing credential secrets must also be retired after auth is disabled. + tokio::spawn(async move { + let mut cursors: [Option; 4] = + std::array::from_fn(|_| None); + let mut interval = tokio::time::interval(CLEANUP_INTERVAL); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + tokio::select! { _ = shutdown.changed() => return, _ = interval.tick() => {} } + for (kind, cursor) in [SESSION, RETIRED, REVOKED, LOGIN_ATTEMPT] + .into_iter() + .zip(&mut cursors) + { + let sweep = async { + let page = state + .store + .list_by_type_after(kind, cursor.as_ref(), u32::from(CLEANUP_PAGE_SIZE)) + .await + .map_err(|_| internal())?; + *cursor = if page.len() == usize::from(CLEANUP_PAGE_SIZE) { + page.last().map(crate::persistence::ObjectCursor::from) + } else { + None + }; + for record in page { + if !matches!( + tokio::time::timeout( + std::time::Duration::from_secs(2), + cleanup_record(&state, &record) + ) + .await, + Ok(Ok(())) + ) { + tracing::warn!("application session cleanup deferred"); + } + } + Ok::<_, Status>(()) + }; + tokio::select! { + _ = shutdown.changed() => return, + result = tokio::time::timeout(std::time::Duration::from_secs(5), sweep) => { + if !matches!(result, Ok(Ok(()))) { tracing::warn!("application session cleanup will retry"); } + } + } + } + } + }); +} + async fn retire_session( state: &ServerState, record: &ObjectRecord, @@ -387,7 +586,7 @@ async fn retire_session( let claim = match state .store .put_if( - SESSION, + &record.object_type, &record.id, &record.name, &record.workspace, @@ -401,17 +600,22 @@ async fn retire_session( Err(PersistenceError::Conflict { .. }) => return Ok(()), Err(_) => return Err(internal()), }; - state + let deletion = state .credentials .delete_application_token( - &record.workspace, + &value.workspace, &value.credential_id, credential_handle(&value)?, ) - .await?; + .await; + if let Err(error) = deletion + && error.code() != tonic::Code::NotFound + { + return Err(error); + } match state .store - .delete_if(SESSION, &record.id, claim.resource_version) + .delete_if(&record.object_type, &record.id, claim.resource_version) .await { Ok(_) | Err(PersistenceError::Conflict { .. }) => Ok(()), @@ -514,7 +718,8 @@ pub async fn control(state: &ServerState, mut req: Request) -> Result) -> Result Status::resource_exhausted("browser session limit reached"), + _ => internal(), + }; + if let Err(error) = state .credentials .delete_application_token(&workspace, &key, credential) - .await?; - return Err(Status::resource_exhausted("browser session unavailable")); + .await + { + let mut retired = record; + retired.revoked = true; + let payload = serde_json::to_vec(&retired).map_err(|_| internal())?; + // A failed compensating deletion must remain available to the reaper. + if state + .store + .put_if( + RETIRED, + &key, + &key, + &owner, + &payload, + None, + WriteCondition::MustCreate, + ) + .await + .is_err() + { + tracing::error!( + "failed to persist application credential cleanup; credential backend requires reconciliation" + ); + } + tracing::warn!(code = ?error.code(), "application credential cleanup deferred"); + } + return Err(original); } target.set_path(&format!("{PREFIX}/redeem")); target.query_pairs_mut().append_pair("code", &value); @@ -603,7 +845,7 @@ pub async fn handle( let mut value = session(&record)?; let nonce = cookie(req.headers(), LOGIN_COOKIE)? .ok_or_else(|| Status::unauthenticated("missing login state"))?; - if record.workspace != workspace + if value.workspace != workspace || value.host != request_origin(req)?.origin().ascii_serialization() || value.redeemed || value.revoked @@ -626,7 +868,6 @@ pub async fn handle( value.redeemed = true; let session_cookie = random()?; let session_key = digest(&session_cookie)?; - value.cookie_key.clone_from(&session_key); let payload = serde_json::to_vec(&value).map_err(|_| internal())?; state .store @@ -640,7 +881,7 @@ pub async fn handle( object_type: SESSION.into(), id: session_key.clone(), name: session_key, - workspace: workspace.into(), + workspace: record.workspace.clone(), payload, }, ]) @@ -670,39 +911,13 @@ pub async fn handle( .await .map_err(|_| internal())? { - let mut value = session(&record)?; - if record.workspace != workspace + let value = session(&record)?; + if value.workspace != workspace || value.host != request_origin(req)?.origin().ascii_serialization() { return Err(Status::permission_denied("wrong session host")); } - value.revoked = true; - state - .store - .put_if( - SESSION, - &key, - &key, - workspace, - &serde_json::to_vec(&value).map_err(|_| internal())?, - None, - WriteCondition::MatchResourceVersion(record.resource_version), - ) - .await - .map_err(|_| internal())?; - state - .credentials - .delete_application_token( - workspace, - &value.credential_id, - credential_handle(&value)?, - ) - .await?; - state - .store - .delete(SESSION, &key) - .await - .map_err(|_| internal())?; + retire_session(state, &record, value).await?; } } return with_cookie( @@ -730,25 +945,50 @@ pub async fn handle( .get::() .and_then(|p| p.certificate_sha256.as_ref()) .ok_or_else(|| Status::invalid_argument("gateway credential required"))?; - (format!("mtls-{fingerprint}"), u64::MAX) + let expires = req + .extensions() + .get::() + .and_then(|peer| peer.certificate_expires_at_ms) + .and_then(|ms| u64::try_from(ms / 1000).ok()) + .filter(|expiry| *expiry > now()) + .ok_or_else(|| { + Status::unauthenticated("verified certificate expiration required") + })?; + (format!("mtls-{fingerprint}"), expires) }; - cleanup(state, workspace).await?; - if state + let owner = req + .extensions() + .get::() + .ok_or_else(internal) + .and_then(|principal| principal_scope(&principal.0))?; + cleanup_scope(state, REVOKED, &owner).await?; + let result = state .store .create_if_workspace_count_below( REVOKED, &key, &key, - REVOCATION_SCOPE, + &owner, &serde_json::to_vec(&expires).map_err(|_| internal())?, None, - 1024, + u64::from(PRINCIPAL_LIMIT), ) - .await - .map_err(|_| internal())? - .is_none() - { - return Err(Status::resource_exhausted("revocation limit reached")); + .await; + if !matches!(result, Ok(Some(_))) { + // Another request may have applied the same revocation while this + // caller waited for admission, including the final quota slot. + let already_revoked = state + .store + .get(REVOKED, &key) + .await + .map_err(|_| internal())? + .is_some(); + if !already_revoked { + return Err(match result { + Ok(None) => Status::resource_exhausted("revocation limit reached"), + _ => internal(), + }); + } } return with_cookie( StatusCode::NO_CONTENT.into_response(), @@ -814,7 +1054,11 @@ pub fn strip_response_cookies(headers: &mut HeaderMap) { .to_str() .ok() .and_then(|v| v.split_once('=')) - .is_some_and(|(name, _)| !name.trim().starts_with("__Host-openshell-")) + .is_some_and(|(name, _)| { + !openshell_core::app_listener::is_gateway_service_auth_cookie( + name.trim().as_bytes(), + ) + }) }) .cloned() .collect(); @@ -824,7 +1068,49 @@ pub fn strip_response_cookies(headers: &mut HeaderMap) { } } -pub fn error(status: &Status) -> Response { +pub fn request_error(state: &ServerState, req: &Request, status: &Status) -> Response { + let mut response = error(status); + let browser_navigation = req.method() == Method::GET + && req + .headers() + .get(header::ACCEPT) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value.contains("text/html")); + if status.code() == tonic::Code::Unauthenticated + && browser_navigation + && secure(req).is_ok() + && let Some(login) = state + .config + .service_routing + .service_auth_login_origins + .first() + && let (Ok(mut login), Ok(service)) = (origin(login), request_origin(req)) + { + login.set_path(CONTROL); + login + .query_pairs_mut() + .append_pair("service_origin", &service.origin().ascii_serialization()); + let href = login + .as_str() + .replace('&', "&") + .replace('"', """) + .replace('<', "<"); + *response.body_mut() = Body::from(format!( + "OpenShell sign in requiredSign in to this service" + )); + response.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/html; charset=utf-8"), + ); + response.headers_mut().insert( + header::CONTENT_SECURITY_POLICY, + HeaderValue::from_static("default-src 'none'; frame-ancestors 'none'; base-uri 'none'"), + ); + } + response +} + +pub(super) fn error(status: &Status) -> Response { let code = match status.code() { tonic::Code::Unauthenticated => StatusCode::UNAUTHORIZED, tonic::Code::PermissionDenied => StatusCode::FORBIDDEN, @@ -832,8 +1118,52 @@ pub fn error(status: &Status) -> Response { tonic::Code::ResourceExhausted => StatusCode::TOO_MANY_REQUESTS, _ => StatusCode::SERVICE_UNAVAILABLE, }; - let mut response = - crate::service_routing::service_error_response(code, "Application authentication failed"); + let (reason, category) = match status.code() { + tonic::Code::Unauthenticated => ( + "Application authentication required", + "authentication_required", + ), + tonic::Code::PermissionDenied => ("Application access denied", "access_denied"), + tonic::Code::InvalidArgument => ( + "Invalid application authentication request", + "invalid_request", + ), + tonic::Code::ResourceExhausted + if status.message() == "browser login rate limit reached" => + { + ( + "Browser sign-in rate limit reached", + "browser_login_rate_limited", + ) + } + tonic::Code::ResourceExhausted if status.message() == "browser session limit reached" => { + ("Browser session limit reached", "browser_session_limit") + } + tonic::Code::ResourceExhausted if status.message() == "revocation limit reached" => ( + "Application credential revocation limit reached", + "credential_revocation_limit", + ), + tonic::Code::ResourceExhausted => ( + "Application authentication capacity exceeded", + "capacity_exceeded", + ), + _ => ( + "Application authentication temporarily unavailable", + "temporarily_unavailable", + ), + }; + let mut response = crate::service_routing::service_error_response(code, reason); + response + .headers_mut() + .insert("x-openshell-auth-error", HeaderValue::from_static(category)); + if matches!( + code, + StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE + ) { + response + .headers_mut() + .insert(header::RETRY_AFTER, HeaderValue::from_static("1")); + } if code == StatusCode::UNAUTHORIZED { response .headers_mut() @@ -852,6 +1182,221 @@ pub mod tests { use std::sync::Arc; use tower::ServiceExt; + #[test] + fn response_cookies_reserve_only_gateway_session_names_in_any_case() { + let mut headers = HeaderMap::new(); + for cookie in [ + "__Host-openshell-app=x; Secure", + "__HOST-OPENSHELL-SERVICE-SESSION=evil; Secure", + "__Host-openshell-service-login=evil; Secure", + "application=y", + ] { + headers.append(header::SET_COOKIE, cookie.parse().unwrap()); + } + strip_response_cookies(&mut headers); + let cookies: Vec<_> = headers + .get_all(header::SET_COOKIE) + .iter() + .map(|v| v.to_str().unwrap()) + .collect(); + assert_eq!(cookies, ["__Host-openshell-app=x; Secure", "application=y"]); + } + + #[test] + fn revocation_identifies_authenticated_signing_input_not_signature_encoding() { + assert_eq!( + token_revocation_key("header.payload.signature-a").unwrap(), + token_revocation_key("header.payload.signature-b").unwrap() + ); + assert_ne!( + token_revocation_key("header.payload.signature-a").unwrap(), + token_revocation_key("header.other.signature-a").unwrap() + ); + } + + #[tokio::test] + async fn login_rate_admission_is_shared_and_isolated_per_principal() { + let state = test_server_state().await; + let mut tasks = tokio::task::JoinSet::new(); + for _ in 0..LOGIN_RATE_LIMIT + 4 { + let state = state.clone(); + tasks.spawn(async move { admit_login(&state, "alice").await }); + } + let mut accepted = 0; + while let Some(result) = tasks.join_next().await { + match result.unwrap() { + Ok(()) => accepted += 1, + Err(error) => assert_eq!(error.code(), tonic::Code::ResourceExhausted), + } + } + assert_eq!(accepted, LOGIN_RATE_LIMIT); + admit_login(&state, "bob").await.unwrap(); + } + + #[tokio::test] + async fn reaper_deletes_expired_session_credentials_without_a_new_login() { + let (_issuer, state, token) = fixture().await; + let cookie = browser_login(&state, &token).await; + let key = digest(cookie.split_once('=').unwrap().1.split(';').next().unwrap()).unwrap(); + let record = state.store.get(SESSION, &key).await.unwrap().unwrap(); + let mut value = session(&record).unwrap(); + value.expires = now(); + let handle = credential_handle(&value).unwrap(); + state + .store + .put_if( + SESSION, + &key, + &key, + &record.workspace, + &serde_json::to_vec(&value).unwrap(), + None, + WriteCondition::MatchResourceVersion(record.resource_version), + ) + .await + .unwrap(); + let (stop, shutdown) = tokio::sync::watch::channel(false); + spawn_cleanup(state.clone(), shutdown); + tokio::time::timeout(std::time::Duration::from_secs(3), async { + while state.store.get(SESSION, &key).await.unwrap().is_some() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert!( + state + .credentials + .resolve_application_token(&value.workspace, &value.credential_id, handle) + .await + .is_err() + ); + stop.send(true).unwrap(); + } + + #[tokio::test] + async fn authenticated_upgrade_observes_logout_and_credential_expiry() { + let (_issuer, state, token) = fixture().await; + let cookie = browser_login(&state, &token).await; + let mut req = application(&cookie); + authorize_request(&state, &mut req, "default") + .await + .unwrap(); + let authorization = req + .extensions() + .get::() + .unwrap() + .clone(); + authorization.check(&state).await.unwrap(); + let mut logout = request(Method::DELETE, &format!("{APP}{PREFIX}/session")); + logout + .headers_mut() + .insert(header::ORIGIN, APP.parse().unwrap()); + logout + .headers_mut() + .insert(header::COOKIE, cookie.parse().unwrap()); + assert_eq!(send(&state, logout).await.status(), StatusCode::NO_CONTENT); + tokio::time::timeout( + std::time::Duration::from_secs(1), + authorization.until_invalid(&state), + ) + .await + .unwrap(); + let expired = UpgradeAuthorization { + expires: Some(now()), + ..Default::default() + }; + tokio::time::timeout( + std::time::Duration::from_secs(1), + expired.until_invalid(&state), + ) + .await + .unwrap(); + } + + #[tokio::test] + async fn racing_duplicate_revocations_never_report_backend_failure() { + let (_issuer, state, token) = fixture().await; + let revoke = || { + let mut req = request(Method::DELETE, &format!("{APP}{PREFIX}/credential")); + req.headers_mut() + .insert(header::ORIGIN, APP.parse().unwrap()); + req.headers_mut().insert( + header::AUTHORIZATION, + format!("Bearer {token}").parse().unwrap(), + ); + req + }; + let (left, right) = tokio::join!(send(&state, revoke()), send(&state, revoke())); + assert!( + left.status() == StatusCode::NO_CONTENT || right.status() == StatusCode::NO_CONTENT + ); + for response in [left, right] { + assert!(matches!( + response.status(), + StatusCode::NO_CONTENT | StatusCode::UNAUTHORIZED + )); + } + } + + #[tokio::test] + async fn another_principals_full_revocation_quota_does_not_block_revocation() { + let (_issuer, state, token) = fixture().await; + let writes = (0..PRINCIPAL_LIMIT) + .map(|n| { + let key = format!("other-credential-{n}"); + AtomicWrite::Create { + object_type: REVOKED.into(), + id: key.clone(), + name: key, + workspace: digest("Oidc:other-user").unwrap(), + payload: serde_json::to_vec(&(now() + 3600)).unwrap(), + } + }) + .collect::>(); + state.store.write_atomically(&writes).await.unwrap(); + let mut req = request(Method::DELETE, &format!("{APP}{PREFIX}/credential")); + req.headers_mut() + .insert(header::ORIGIN, APP.parse().unwrap()); + req.headers_mut().insert( + header::AUTHORIZATION, + format!("Bearer {token}").parse().unwrap(), + ); + assert_eq!(send(&state, req).await.status(), StatusCode::NO_CONTENT); + let record = state + .store + .get(REVOKED, &token_revocation_key(&token).unwrap()) + .await + .unwrap() + .unwrap(); + assert_eq!(record.workspace, digest("Oidc:user-42").unwrap()); + assert_eq!( + serde_json::from_slice::(&record.payload).unwrap(), + token_expiry(&token).unwrap() + ); + } + + #[tokio::test] + async fn browser_authentication_errors_offer_only_the_configured_login_origin() { + let (_issuer, state, _) = fixture().await; + let mut req = request(Method::GET, APP); + req.headers_mut() + .insert(header::ACCEPT, "text/html".parse().unwrap()); + let response = request_error(&state, &req, &Status::unauthenticated("private details")); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + let body = response.into_body().collect().await.unwrap().to_bytes(); + let body = std::str::from_utf8(&body).unwrap(); + assert!(body.contains("https://gateway.example.com/auth/services?service_origin=")); + assert!(!body.contains("private details")); + for (status, expected) in [ + (Status::permission_denied("secret"), "access_denied"), + (Status::resource_exhausted("secret"), "capacity_exceeded"), + (Status::unavailable("secret"), "temporarily_unavailable"), + ] { + assert_eq!(error(&status).headers()["x-openshell-auth-error"], expected); + } + } + const APP: &str = "https://default--demo--web.services.example.com"; const GATEWAY: &str = "https://gateway.example.com"; @@ -861,8 +1406,8 @@ pub mod tests { let mut state = test_server_state().await; let inner = Arc::get_mut(&mut state).unwrap(); inner.config.auth.allow_unauthenticated_users = false; - inner.config.service_routing.auth_enabled = true; - inner.config.service_routing.auth_login_origins = vec![GATEWAY.into()]; + inner.config.service_routing.enable_gateway_service_auth = true; + inner.config.service_routing.service_auth_login_origins = vec![GATEWAY.into()]; inner.config.service_routing.base_domains = vec!["services.example.com".into()]; inner.config.oidc = Some(serde_json::from_value(serde_json::json!({"issuer":server.uri(),"audience":"openshell-cli","scopes_claim":"scope"})).unwrap()); inner.admin_role = "openshell-admin".into(); @@ -981,7 +1526,7 @@ pub mod tests { .unwrap() .config .service_routing - .auth_login_origins + .service_auth_login_origins .clear(); let response = send( &state, @@ -1014,7 +1559,7 @@ pub mod tests { login_state: String::new(), handle: String::new(), credential_id: String::new(), - cookie_key: String::new(), + workspace: "default".into(), redeemed: true, revoked: false, }; @@ -1026,7 +1571,7 @@ pub mod tests { object_type: SESSION.into(), name: id.clone(), id, - workspace: "default".into(), + workspace: digest("Oidc:user-42").unwrap(), payload: payload.clone(), } }) @@ -1098,7 +1643,7 @@ pub mod tests { assert_eq!( state .store - .list(SESSION, "default", 1025, 0) + .list(SESSION, &digest("Oidc:user-42").unwrap(), 1025, 0) .await .unwrap() .len(), @@ -1215,7 +1760,11 @@ pub mod tests { StatusCode::UNAUTHORIZED, "bootstrap code is never an active cookie" ); - let records = state.store.list(SESSION, "default", 1024, 0).await.unwrap(); + let records = state + .store + .list(SESSION, &digest("Oidc:user-42").unwrap(), 1024, 0) + .await + .unwrap(); assert_eq!(records.len(), 1); assert!(!String::from_utf8_lossy(&records[0].payload).contains(token)); cookie @@ -1500,7 +2049,7 @@ pub mod tests { ); let record = state .store - .list(SESSION, "default", 1, 0) + .list(SESSION, &digest("Oidc:user-42").unwrap(), 1, 0) .await .unwrap() .remove(0); @@ -1512,7 +2061,7 @@ pub mod tests { SESSION, &record.id, &record.name, - "default", + &record.workspace, &serde_json::to_vec(&value).unwrap(), None, WriteCondition::Unconditional, @@ -1540,7 +2089,7 @@ pub mod tests { let inner = Arc::get_mut(&mut state).unwrap(); inner.config.service_routing.base_domains = vec!["services.example.com".into()]; inner.config.auth.allow_unauthenticated_users = false; - inner.config.service_routing.auth_enabled = true; + inner.config.service_routing.enable_gateway_service_auth = true; inner.config.mtls_auth.enabled = true; let peer = ServicePeer { secure: true, @@ -1552,6 +2101,7 @@ pub mod tests { provider: IdentityProvider::Mtls, }), certificate_sha256: Some("verified-certificate-digest".into()), + certificate_expires_at_ms: Some(openshell_core::time::now_ms() + 60_000), source: None, }; for enabled in [false, true] { diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index d14bb80e6e..475e06467f 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -352,6 +352,7 @@ struct RunArgs { server_sans: Vec, /// Authenticate sandbox application requests using configured gateway auth. + /// TLS-enabled loopback service URLs use HTTPS when enabled. #[arg(long, env = "OPENSHELL_ENABLE_GATEWAY_SERVICE_AUTH", default_value_t = false, action = ArgAction::Set)] enable_gateway_service_auth: bool, @@ -766,7 +767,7 @@ fn assemble_server_config( .with_service_auth(args.enable_gateway_service_auth) .with_loopback_service_http(args.enable_loopback_service_http) .with_websocket_tunnel(args.enable_websocket_tunnel); - config.service_routing.auth_login_origins = file + config.service_routing.service_auth_login_origins = file .as_ref() .and_then(|file| file.openshell.gateway.service_auth_login_origins.clone()) .unwrap_or_default(); @@ -1161,8 +1162,18 @@ async fn run_from_args( if prepared.config.service_routing.enabled { info!("Gateway-based service routing enabled"); - if prepared.config.service_routing.auth_enabled { + if prepared.config.service_routing.enable_gateway_service_auth { info!("Gateway-mediated service authentication enabled"); + if prepared + .config + .service_routing + .service_auth_login_origins + .is_empty() + { + info!( + "Browser service login disabled: service_auth_login_origins is empty (configure through gateway TOML or Helm gatewayConfig)" + ); + } } else { info!("Gateway-mediated service authentication disabled"); } @@ -4899,7 +4910,7 @@ service_auth_login_origins = ["https://gateway.example.com:8443"] ]); let prepared = super::prepare_server_config(&mut args, &matches).unwrap(); assert_eq!( - prepared.config.service_routing.auth_login_origins, + prepared.config.service_routing.service_auth_login_origins, ["https://gateway.example.com:8443"] ); }); diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 2d8aa3e714..77acb082c9 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -1384,6 +1384,7 @@ pub(crate) async fn run_server( ssh_sessions::spawn_session_reaper(store.clone(), Duration::from_hours(1)); supervisor_session::spawn_relay_reaper(state.clone(), Duration::from_secs(30)); grpc::service_advertisement::spawn_cleanup(state.clone(), shutdown_rx.clone()); + auth::service_session::spawn_cleanup(state.clone(), shutdown_rx.clone()); grpc::mutation_replay::spawn_expiry_sweeper(state.clone(), shutdown_rx.clone()); provider_profile_sources::spawn_refresh(state.clone()); provider_refresh::spawn_refresh_worker(state.clone(), Duration::from_mins(1)); @@ -1633,6 +1634,8 @@ fn spawn_gateway_connection( match acceptor.acceptor().accept(stream).await { Ok(tls_stream) => { let peer_identity = multiplex::extract_peer_identity(&tls_stream); + let certificate_expires_at_ms = + multiplex::extract_peer_certificate_expiry(&tls_stream); let certificate_sha256 = match multiplex::extract_peer_certificate_sha256(&tls_stream) { Ok(fingerprint) => fingerprint, @@ -1642,10 +1645,11 @@ fn spawn_gateway_connection( } }; if let Err(e) = service - .serve_with_verified_certificate( + .serve_with_certificate_expiry( tls_stream, peer_identity, certificate_sha256, + certificate_expires_at_ms, ConnectionSource::Peer(addr), ) .await @@ -4176,14 +4180,15 @@ mod tests { let client_cert = CertificateDer::from(client.der().to_vec()); let key_pem = client_key.serialize_pem().unwrap(); let client_key = PrivateKeyDer::from_pem_slice(key_pem.as_bytes()).unwrap(); - for (enabled, auth_enabled) in [(false, false), (false, true), (true, false), (true, true)] + for (enabled, enable_gateway_service_auth) in + [(false, false), (false, true), (true, false), (true, true)] { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); let mut state = test_state(addr, false).await; let inner = Arc::get_mut(&mut state).unwrap(); inner.config.auth.allow_unauthenticated_users = false; - inner.config.service_routing.auth_enabled = auth_enabled; + inner.config.service_routing.enable_gateway_service_auth = enable_gateway_service_auth; inner.config.mtls_auth.enabled = true; inner.config.supervisor_app_listener.enabled = enabled; inner.config.tls = Some(openshell_core::TlsConfig { @@ -4247,12 +4252,12 @@ mod tests { .unwrap(); let response = String::from_utf8_lossy(&response); assert!( - response.starts_with(if authenticated || !auth_enabled { + response.starts_with(if authenticated || !enable_gateway_service_auth { "HTTP/1.1 404" } else { "HTTP/1.1 401" }), - "listener={enabled}, auth={auth_enabled}, authenticated={authenticated}: {response}" + "listener={enabled}, auth={enable_gateway_service_auth}, authenticated={authenticated}: {response}" ); } stop_listener(shutdown, handle).await; diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 6e045d97aa..8d9cb9abc3 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -272,6 +272,22 @@ impl MultiplexService { certificate_sha256: Option, source: ConnectionSource, ) -> Result<(), Box> + where + S: AsyncRead + AsyncWrite + Unpin + Send + 'static, + { + self.serve_with_certificate_expiry(stream, peer_identity, certificate_sha256, None, source) + .await + } + + /// TLS validity must come from the same verified leaf as the identity. + pub async fn serve_with_certificate_expiry( + &self, + stream: S, + peer_identity: Option, + certificate_sha256: Option, + certificate_expires_at_ms: Option, + source: ConnectionSource, + ) -> Result<(), Box> where S: AsyncRead + AsyncWrite + Unpin + Send + 'static, { @@ -357,6 +373,7 @@ impl MultiplexService { secure: self.state.config.tls.is_some(), identity: peer_identity, certificate_sha256, + certificate_expires_at_ms, source: Some(source), }, )); @@ -1675,6 +1692,17 @@ where }) } +/// Validity metadata parsed from the TLS-verified leaf certificate. X.509 +/// decoding is dependency-owned parsing; verification remains in the TLS backend. +pub fn extract_peer_certificate_expiry( + stream: &tokio_rustls::server::TlsStream, +) -> Option { + use x509_parser::prelude::*; + let leaf = stream.get_ref().1.peer_certificates()?.first()?; + let (_, cert) = X509Certificate::from_der(leaf.as_ref()).ok()?; + cert.validity().not_after.timestamp().checked_mul(1000) +} + /// Fingerprint of the leaf certificate verified during the TLS handshake. pub fn extract_peer_certificate_sha256( stream: &tokio_rustls::server::TlsStream, diff --git a/crates/openshell-server/src/service_routing.rs b/crates/openshell-server/src/service_routing.rs index 1e8e530499..ac3e51390c 100644 --- a/crates/openshell-server/src/service_routing.rs +++ b/crates/openshell-server/src/service_routing.rs @@ -188,7 +188,7 @@ fn endpoint_scheme(config: &openshell_core::Config) -> &'static str { if config.tls.is_none() || (config.bind_address.ip().is_loopback() && config.service_routing.enable_loopback_service_http - && !config.service_routing.auth_enabled) + && !config.service_routing.enable_gateway_service_auth) { "http" } else { @@ -534,7 +534,7 @@ pub async fn proxy_sandbox_service_request( } = target; let service_name = service.unwrap_or_default(); - if state.config.service_routing.auth_enabled { + if state.config.service_routing.enable_gateway_service_auth { if req .uri() .path() @@ -542,13 +542,13 @@ pub async fn proxy_sandbox_service_request( { return match crate::auth::service_session::handle(&state, &mut req, &workspace).await { Ok(response) => response, - Err(error) => crate::auth::service_session::error(&error), + Err(error) => crate::auth::service_session::request_error(&state, &req, &error), }; } if let Err(error) = crate::auth::service_session::authorize_request(&state, &mut req, &workspace).await { - return crate::auth::service_session::error(&error); + return crate::auth::service_session::request_error(&state, &req, &error); } } @@ -752,6 +752,16 @@ async fn proxy_to_endpoint( return Err(err); } + let upgrade_authorization = state + .config + .service_routing + .enable_gateway_service_auth + .then(|| { + req.extensions() + .get::() + .cloned() + }) + .flatten(); let websocket_upgrade = is_websocket_upgrade(&req); let downstream_upgrade = websocket_upgrade.then(|| hyper::upgrade::on(&mut req)); @@ -774,7 +784,7 @@ async fn proxy_to_endpoint( target_port, websocket_upgrade, authorization_mode, - state.config.service_routing.auth_enabled, + state.config.service_routing.enable_gateway_service_auth, )?; let replay = reused.then(|| replayable_request(&upstream)).flatten(); let first_attempt = if reused { @@ -820,12 +830,24 @@ async fn proxy_to_endpoint( emit_service_relay_failure(&endpoint, target_port, "websocket upgrade unavailable"); err })?; + let upgrade_state = state.clone(); tokio::spawn(async move { match (downstream_upgrade.await, upstream_upgrade.await) { (Ok(downstream), Ok(upstream)) => { let mut downstream = TokioIo::new(downstream); let mut upstream = TokioIo::new(upstream); - let _ = tokio::io::copy_bidirectional(&mut downstream, &mut upstream).await; + let authorization = async { + match upgrade_authorization { + Some(authorization) => { + authorization.until_invalid(&upgrade_state).await; + } + None => std::future::pending::<()>().await, + } + }; + tokio::select! { + _ = tokio::io::copy_bidirectional(&mut downstream, &mut upstream) => {}, + () = authorization => {}, + } let _ = downstream.shutdown().await; let _ = upstream.shutdown().await; } @@ -839,14 +861,14 @@ async fn proxy_to_endpoint( }); let (mut parts, _) = response.into_parts(); - if state.config.service_routing.auth_enabled { + if state.config.service_routing.enable_gateway_service_auth { crate::auth::service_session::strip_response_cookies(&mut parts.headers); } return Ok(Response::from_parts(parts, Body::empty())); } let (mut parts, body) = response.into_parts(); - if state.config.service_routing.auth_enabled { + if state.config.service_routing.enable_gateway_service_auth { crate::auth::service_session::strip_response_cookies(&mut parts.headers); } Ok(Response::from_parts(parts, Body::new(body))) @@ -1168,7 +1190,7 @@ fn is_gateway_auth_cookie(name: &str, enable_gateway_service_auth: bool) -> bool name.eq_ignore_ascii_case("CF_Authorization") || name.eq_ignore_ascii_case("cf-authorization") || (enable_gateway_service_auth - && name.to_ascii_lowercase().starts_with("__host-openshell-")) + && openshell_core::app_listener::is_gateway_service_auth_cookie(name.as_bytes())) } pub fn emit_service_endpoint_config_event(endpoint: &ServiceEndpoint, url: &str, created: bool) { @@ -1467,11 +1489,11 @@ mod tests { use tower::ServiceExt as _; for routing_enabled in [false, true] { - for auth_enabled in [false, true] { + for enable_gateway_service_auth in [false, true] { let mut state = crate::grpc::test_support::test_server_state().await; let config = &mut Arc::get_mut(&mut state).unwrap().config; config.service_routing.enabled = routing_enabled; - config.service_routing.auth_enabled = auth_enabled; + config.service_routing.enable_gateway_service_auth = enable_gateway_service_auth; let response = crate::http_router(state) .oneshot( Request::builder() @@ -1482,7 +1504,7 @@ mod tests { ) .await .unwrap(); - if routing_enabled && auth_enabled { + if routing_enabled && enable_gateway_service_auth { assert_ne!(response.status(), StatusCode::NOT_FOUND); } else { assert_eq!(response.status(), StatusCode::NOT_FOUND); @@ -1495,13 +1517,14 @@ mod tests { async fn disabled_gateway_routing_rejects_http_and_websocket_on_both_routers() { use tower::ServiceExt as _; - for auth_enabled in [false, true] { + for enable_gateway_service_auth in [false, true] { for hashed in [false, true] { for listener_enabled in [false, true] { let mut state = crate::grpc::test_support::test_server_state().await; let inner = Arc::get_mut(&mut state).unwrap(); inner.config.service_routing.enabled = false; - inner.config.service_routing.auth_enabled = auth_enabled; + inner.config.service_routing.enable_gateway_service_auth = + enable_gateway_service_auth; inner.config.supervisor_app_listener.enabled = listener_enabled; inner.config.name = "gateway-a".into(); inner.config.service_routing.service_hostname_format = if hashed { @@ -1558,7 +1581,7 @@ mod tests { inner.config.supervisor_app_listener.enabled = enabled; inner.config.mtls_auth.enabled = true; inner.config.auth.allow_unauthenticated_users = false; - assert!(!inner.config.service_routing.auth_enabled); + assert!(!inner.config.service_routing.enable_gateway_service_auth); for router in [ crate::http::http_router(state.clone()), crate::http::service_http_router(state.clone()), @@ -1613,7 +1636,7 @@ mod tests { .header(header::AUTHORIZATION, "Bearer application-token") .header("x-openshell-authorization", "application-header") .header("cf-access-authenticated-user-email", "application-value") - .header(header::COOKIE, "__Host-openshell-app=app-value; ordinary=retained; cf-authorization=edge-value") + .header(header::COOKIE, "__Host-openshell-app=app-value; __HOST-OPENSHELL-SERVICE-SESSION=reserved; ordinary=retained; cf-authorization=edge-value") .body(Body::empty()).unwrap(); let upstream = build_upstream_request( req, @@ -1638,7 +1661,11 @@ mod tests { !enabled ); let cookies = upstream.headers()[header::COOKIE].to_str().unwrap(); - assert_eq!(cookies.contains("__Host-openshell-app"), !enabled); + assert!(cookies.contains("__Host-openshell-app")); + assert_eq!( + cookies.contains("__HOST-OPENSHELL-SERVICE-SESSION"), + !enabled + ); assert!(cookies.contains("ordinary=retained")); assert!(!cookies.contains("cf-authorization")); } @@ -1659,7 +1686,7 @@ mod tests { inner.config.mtls_auth.enabled = true; inner.config.auth.allow_unauthenticated_users = false; inner.config.service_routing = config(); - inner.config.service_routing.auth_enabled = true; + inner.config.service_routing.enable_gateway_service_auth = true; let peer = ServicePeer { identity: Some(Identity { subject: "verified-user".into(), @@ -1782,7 +1809,7 @@ mod tests { use hyper::service::service_fn; use tower::ServiceExt; - for (auth_enabled, listener_enabled) in + for (enable_gateway_service_auth, listener_enabled) in [(false, false), (false, true), (true, false), (true, true)] { let mut state = test_server_state().await; @@ -1791,7 +1818,7 @@ mod tests { inner.config.mtls_auth.enabled = true; inner.config.auth.allow_unauthenticated_users = false; inner.config.service_routing = config(); - inner.config.service_routing.auth_enabled = auth_enabled; + inner.config.service_routing.enable_gateway_service_auth = enable_gateway_service_auth; let mut endpoint = endpoint(); endpoint.authorization_mode = ServiceAuthorizationMode::BearerPassthrough as i32; state.store.put_message(&endpoint).await.unwrap(); @@ -1819,8 +1846,8 @@ mod tests { assert!(!request.headers().contains_key("x-forwarded-client-cert")); assert!(!request.headers().contains_key("cf-access-jwt-assertion")); assert_eq!( - request.headers().contains_key(header::COOKIE), - !auth_enabled + request.headers()[header::COOKIE], + "__Host-openshell-owned=application-cookie" ); let body = request.into_body().collect().await.unwrap().to_bytes(); let mut response = Response::new(Body::from(body)); @@ -1871,17 +1898,14 @@ mod tests { .header("cf-access-jwt-assertion", "edge-token") .body(Body::from("application-payload")) .unwrap(); - if auth_enabled { + if enable_gateway_service_auth { request.extensions_mut().insert(peer); } let response = crate::http::http_router(state) .oneshot(request) .await .unwrap(); - assert_eq!( - response.headers().contains_key(header::SET_COOKIE), - !auth_enabled - ); + assert!(response.headers().contains_key(header::SET_COOKIE)); assert_eq!(response.status(), StatusCode::OK); assert_eq!( response.into_body().collect().await.unwrap().to_bytes(), @@ -2040,7 +2064,7 @@ mod tests { let addr = listener.local_addr().unwrap(); let inner = Arc::get_mut(&mut state).unwrap(); inner.config.bind_address = addr; - inner.config.service_routing.auth_login_origins = + inner.config.service_routing.service_auth_login_origins = vec![format!("https://gateway.example.test:{}", addr.port())]; inner.config.tls = Some(openshell_core::TlsConfig { cert_path: dir.path().join("server-cert.pem"), @@ -2230,7 +2254,7 @@ mod tests { endpoint_url(&cfg, "default", "my-sandbox", "web").as_deref(), Some("http://default--my-sandbox--web.dev.openshell.localhost:8080/") ); - cfg.service_routing.auth_enabled = true; + cfg.service_routing.enable_gateway_service_auth = true; assert_eq!( endpoint_url(&cfg, "default", "my-sandbox", "web").as_deref(), Some("https://default--my-sandbox--web.dev.openshell.localhost:8080/") diff --git a/crates/openshell-server/tests/browser-service-auth.cjs b/crates/openshell-server/tests/browser-service-auth.cjs index d2739d2319..298eacf265 100644 --- a/crates/openshell-server/tests/browser-service-auth.cjs +++ b/crates/openshell-server/tests/browser-service-auth.cjs @@ -76,7 +76,7 @@ async function main() { chrome.kill('SIGKILL'); await new Promise(resolve => chrome.once('exit', resolve)); } - rmSync(profile, { recursive: true, force: true }); + rmSync(profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } } main().catch(error => { process.stderr.write(error.message + '\n'); process.exitCode = 1; }); diff --git a/crates/openshell-supervisor/src/app_listener.rs b/crates/openshell-supervisor/src/app_listener.rs index e26f3f82ba..009edaa8a3 100644 --- a/crates/openshell-supervisor/src/app_listener.rs +++ b/crates/openshell-supervisor/src/app_listener.rs @@ -1017,7 +1017,9 @@ fn sanitize_headers(headers: &mut http::HeaderMap, passthrough: bool, websocket: cookie.split_once('=').is_some_and(|(name, _)| { !name.trim().eq_ignore_ascii_case("CF_Authorization") && !name.trim().eq_ignore_ascii_case("cf-authorization") - && !gateway_cookie_name(name.trim().as_bytes()) + && !openshell_core::app_listener::is_gateway_service_auth_cookie( + name.trim().as_bytes(), + ) }) }) .map(str::trim) @@ -1032,11 +1034,6 @@ fn sanitize_headers(headers: &mut http::HeaderMap, passthrough: bool, websocket: true } -fn gateway_cookie_name(name: &[u8]) -> bool { - name.eq_ignore_ascii_case(b"__Host-openshell-service-session") - || name.eq_ignore_ascii_case(b"__Host-openshell-service-login") -} - fn strip_gateway_response_cookies(headers: &mut http::HeaderMap) { let cookies: Vec<_> = headers .get_all(header::SET_COOKIE) @@ -1047,7 +1044,7 @@ fn strip_gateway_response_cookies(headers: &mut http::HeaderMap) { .split(|byte| *byte == b'=') .next() .unwrap_or_default(); - !gateway_cookie_name(name.trim_ascii()) + !openshell_core::app_listener::is_gateway_service_auth_cookie(name.trim_ascii()) }) .cloned() .collect(); diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index c441cb63e4..2db4573aca 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -661,6 +661,8 @@ for peer identity policies, multi-node registrations, and authorization. | gateway.listenAddress | string | `"0.0.0.0"` | Gateway listener IP. Use `::` for IPv6. | | gatewayConfig | object | `{"openshell":{"version":2},"openshell.gateway":{"enable_gateway_service_routing":false}}` | Non-secret gateway application configuration. Top-level keys name TOML tables and are rendered into the mounted gateway.toml file. Kubernetes resource inputs remain outside this map; template expressions derive the corresponding runtime values from their resource owner. | | gatewayConfig."openshell.gateway".enable_gateway_service_routing | bool | `false` | Opt in to gateway-mediated sandbox service URLs and forwarding. Disabled for Kubernetes; configure application-listener ingress or explicitly enable this path. | +| gatewayConfig."openshell.gateway".enable_gateway_service_auth | bool | `false` | Authenticate gateway-mediated application requests using configured gateway auth. | +| gatewayConfig."openshell.gateway".service_auth_login_origins | list | `[]` | Exact trusted HTTPS control-plane origins for browser login; configure through gateway TOML or this map. | | global.image.pullPolicy | string | `"IfNotPresent"` | Shared OpenShell image pull policy. Individual image pull policies take precedence. | | global.image.registry | string | `"quay.io"` | Shared OpenShell image registry. Individual image registries take precedence. | | global.image.tag | string | `""` | Shared OpenShell image tag. Defaults to the chart appVersion when empty. | diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index e5ae3b736b..11baded8fe 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -448,6 +448,10 @@ gatewayConfig: # SPIFFE ID prefix. SPIRE must authorize the gateway and attest its Sandbox references. # -- Opt in to gateway-mediated sandbox service URLs and forwarding. Disabled for Kubernetes; configure application-listener ingress or explicitly enable this path. enable_gateway_service_routing: false + # Gateway application authentication is opt-in independently of app listeners. + # enable_gateway_service_auth: false + # Exact HTTPS control-plane origins; an empty list disables browser login. + # service_auth_login_origins: ["https://gateway.example.com"] # Server configuration server: diff --git a/deploy/man/openshell-gateway.8.md b/deploy/man/openshell-gateway.8.md index 7f0dd32ca0..54f264f715 100644 --- a/deploy/man/openshell-gateway.8.md +++ b/deploy/man/openshell-gateway.8.md @@ -38,7 +38,8 @@ TLS. **--enable-gateway-service-auth** *BOOL* : Opt in to configured gateway authentication for sandbox application HTTP requests and WebSocket upgrades. Default: **false**. Independent of the - supervisor application listener. Environment: **OPENSHELL_ENABLE_GATEWAY_SERVICE_AUTH**. + supervisor application listener. TLS-enabled loopback service URLs switch to HTTPS + when enabled. Environment: **OPENSHELL_ENABLE_GATEWAY_SERVICE_AUTH**. **--bind-address** *IP* : IP address to bind all listeners to. Default: **127.0.0.1**. diff --git a/docs/how-it-works/gateways/authentication.mdx b/docs/how-it-works/gateways/authentication.mdx index 6c3eda7c17..bda01d5383 100644 --- a/docs/how-it-works/gateways/authentication.mdx +++ b/docs/how-it-works/gateways/authentication.mdx @@ -94,14 +94,19 @@ do not require browser session storage. Login codes expire after two minutes. Sessions expire after ten minutes or the token's expiration, whichever comes first; sign in again rather than silently refreshing the token. Every request revalidates the token and current workspace -membership. Each workspace admits at most 1,024 pending and active sessions; -expired sessions are cleaned up during login. +membership. Each authenticated principal admits at most 1,024 pending and active +sessions and 12 login attempts per rolling minute, shared across gateway replicas. +A background reaper checks pages of expired sessions and their stored tokens every +ten seconds. Cleanup retries backend failures and continues without new logins; +large backlogs can take multiple passes. Cookie and mTLS requests require a matching Origin for unsafe HTTP methods and WebSocket upgrades. Cross-origin browser requests are rejected. Headless mTLS clients making unsafe requests must also provide the matching Origin. Explicit bearer headers avoid ambient browser credentials. WebSockets authenticate at -upgrade; an established connection is not continuously reauthenticated. +upgrade. Established connections close at the earliest session or credential +expiry. They check shared logout/revocation state every five seconds with a +two-second check deadline; failed checks close the connection. ### Logout and credential revocation @@ -132,9 +137,11 @@ rotate the client certificate to regain access. Revocation targets gateway application access; it does not revoke the identity provider's token or alter control-plane RPC credentials. Offline OIDC JWT validation cannot discover an identity provider's individual-token revocations before token expiry or key -changes; use this gateway revocation endpoint for immediate application cutoff. -The gateway retains certificate revocations and removes expired token revocations; -it admits at most 1,024 outstanding application credential revocations. +changes. Gateway revocation rejects subsequent application requests and closes +existing WebSockets within the five-second recheck interval plus its two-second +check deadline. Revocations expire with the token or verified certificate. Each +principal admits at most 1,024 outstanding revocations, independently of other +principals. Direct supervisor app-listener access delegates authentication to the ingress provider. Gateway browser sessions and credentials do not authorize that path. diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 01d36db771..9366f6f69c 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2678,6 +2678,7 @@ Direct app-listener authentication belongs to the ingress provider. Browser login additionally requires `service_auth_login_origins` in `[openshell.gateway]`, for example `["https://gateway.example.com:8443"]`. +This setting is configured through TOML or Helm `gatewayConfig`, with no CLI or environment equivalent. Only exact HTTPS control-plane origins are allowed; wildcards, credentials, paths, queries, and fragments are invalid. The default empty list disables browser login while preserving bearer and mTLS application access. Helm uses diff --git a/rfc/0017-sandbox-service-exposure/README.md b/rfc/0017-sandbox-service-exposure/README.md index f016b546ae..5704e6bdbe 100644 --- a/rfc/0017-sandbox-service-exposure/README.md +++ b/rfc/0017-sandbox-service-exposure/README.md @@ -154,7 +154,7 @@ Application TLS is configured separately from gateway TLS. Operators provide DNS SNI selects a route; it does not authenticate a user. Direct app-listener access delegates authentication to the ingress provider; implementing that authentication is outside this proposal. Preserve existing listener header handling: strip `Authorization` by default, allow explicit `bearer-passthrough`, and strip gateway/edge identity headers and edge authentication cookies. -Gateway-mediated application HTTP requests and WebSocket upgrades can opt into configured gateway authentication and workspace authorization with `[openshell.gateway].enable_gateway_service_auth = true` (default `false`), independently of app-listener enablement, as tracked by #4722. Use the TCP-forwarding access policy, including `sandbox:write` when scopes are enforced. Keep gateway credentials separate from application bearer passthrough and cookies; consume and strip gateway material before forwarding. Browser sessions require a control-plane login flow, origin/CSRF protections, and revocation. Missing, invalid, expired, or revoked credentials fail before application dial; insufficient permissions return 403. WebSockets authenticate at upgrade. Explicit unauthenticated local-development configurations retain their documented behavior. +Gateway-mediated application HTTP requests and WebSocket upgrades can opt into configured gateway authentication and workspace authorization with `[openshell.gateway].enable_gateway_service_auth = true` (default `false`), independently of app-listener enablement, as tracked by #4722. Use the TCP-forwarding access policy, including `sandbox:write` when scopes are enforced. Keep gateway credentials separate from application bearer passthrough and cookies; consume and strip gateway material before forwarding. Browser sessions require a control-plane login flow, origin/CSRF protections, and revocation. Missing, invalid, expired, or revoked credentials fail before application dial; insufficient permissions return 403. Browser sessions store the gateway token in the configured credential backend so each application request reuses current token validation, role/scope mapping, and workspace checks across replicas. This costs a credential write per login and a read per session request; a background reaper removes expired sessions and their secrets. Signed-claims cookies would need a new principal reconstruction path, while encrypted-token cookies would need shared key distribution/rotation and token-size handling. Both alternatives remain separate design options. WebSockets authenticate at upgrade and are bounded by credential/session expiry and shared revocation checks. Explicit unauthenticated local-development configurations retain their documented behavior. A passthrough proxy cannot inspect HTTP credentials. An edge that terminates TLS must reconnect with the correct service SNI and authority. Restrict supervisor listener access to prevent bypassing required edge authentication; use authenticated backend transport where network restrictions are insufficient. diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 08fa7c1267..c187bd9538 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -2024,6 +2024,11 @@ this flag before inspecting the configured gateway authentication and workspace membership. Direct app-listener authentication remains the ingress provider's responsibility. Disabling service auth retains gateway application routing; it does not disable the gateway data path. +Browser login origins are configured through gateway TOML or Helm `gatewayConfig`. +An empty origin list logs that browser login is disabled. Authenticated WebSockets +check shared session/revocation state every five seconds with a two-second deadline +and close at credential/session expiry. Session cleanup runs in background without +requiring another login. ## Azure PostgreSQL workload identity diff --git a/tasks/rust.toml b/tasks/rust.toml index b95c69c595..32c5164b8c 100644 --- a/tasks/rust.toml +++ b/tasks/rust.toml @@ -136,3 +136,7 @@ run = [ # Guard: webpki-root-certs must not appear either (webpki-roots re-exports it). "bash -c 'if cargo tree -p openshell-supervisor -i webpki-root-certs --no-default-features --features system-ca-roots 2>/dev/null | grep -q webpki-root-certs; then echo \"ERROR: webpki-root-certs found in system CA roots build\" >&2; exit 1; fi'", ] + +["test:gateway-service-auth:browser"] +description = "Run the real-Chrome gateway service login regression (set OPENSHELL_BROWSER_E2E_CHROME)" +run = "cargo test -p openshell-server --lib gateway_service_auth_real_browser_cross_site_login -- --ignored" From 6ca1d3cb7f70bf0bec9c8742fcac5b7f2252c884 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Tue, 1 Dec 2026 08:39:39 -0800 Subject: [PATCH 15/15] docs(helm): remove redundant service auth examples Signed-off-by: Taylor Mutch --- deploy/helm/openshell/README.md | 2 -- deploy/helm/openshell/values.yaml | 4 ---- 2 files changed, 6 deletions(-) diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index 2db4573aca..c441cb63e4 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -661,8 +661,6 @@ for peer identity policies, multi-node registrations, and authorization. | gateway.listenAddress | string | `"0.0.0.0"` | Gateway listener IP. Use `::` for IPv6. | | gatewayConfig | object | `{"openshell":{"version":2},"openshell.gateway":{"enable_gateway_service_routing":false}}` | Non-secret gateway application configuration. Top-level keys name TOML tables and are rendered into the mounted gateway.toml file. Kubernetes resource inputs remain outside this map; template expressions derive the corresponding runtime values from their resource owner. | | gatewayConfig."openshell.gateway".enable_gateway_service_routing | bool | `false` | Opt in to gateway-mediated sandbox service URLs and forwarding. Disabled for Kubernetes; configure application-listener ingress or explicitly enable this path. | -| gatewayConfig."openshell.gateway".enable_gateway_service_auth | bool | `false` | Authenticate gateway-mediated application requests using configured gateway auth. | -| gatewayConfig."openshell.gateway".service_auth_login_origins | list | `[]` | Exact trusted HTTPS control-plane origins for browser login; configure through gateway TOML or this map. | | global.image.pullPolicy | string | `"IfNotPresent"` | Shared OpenShell image pull policy. Individual image pull policies take precedence. | | global.image.registry | string | `"quay.io"` | Shared OpenShell image registry. Individual image registries take precedence. | | global.image.tag | string | `""` | Shared OpenShell image tag. Defaults to the chart appVersion when empty. | diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index 11baded8fe..e5ae3b736b 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -448,10 +448,6 @@ gatewayConfig: # SPIFFE ID prefix. SPIRE must authorize the gateway and attest its Sandbox references. # -- Opt in to gateway-mediated sandbox service URLs and forwarding. Disabled for Kubernetes; configure application-listener ingress or explicitly enable this path. enable_gateway_service_routing: false - # Gateway application authentication is opt-in independently of app listeners. - # enable_gateway_service_auth: false - # Exact HTTPS control-plane origins; an empty list disables browser login. - # service_auth_login_origins: ["https://gateway.example.com"] # Server configuration server: