diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index 7f4c47a134..b803a35abe 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -792,6 +792,12 @@ pub struct MtlsAuthConfig { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct GatewayAuthConfig { + /// Operator-managed JSON discovery certificate grant file, reloaded on requests/watches. + #[serde(default)] + pub discovery_grants_file: Option, + /// Concurrent discovery-watch admission limits, per gateway process. + #[serde(default)] + pub discovery: DiscoveryLimits, /// When true, unauthenticated user/CLI calls are accepted as a local /// developer principal. This is an unsafe local-development escape hatch /// for trusted, non-shared gateways. Sandbox supervisor calls still use @@ -800,6 +806,23 @@ pub struct GatewayAuthConfig { pub allow_unauthenticated_users: bool, } +/// `[openshell.gateway.auth.discovery]` watch admission budgets. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct DiscoveryLimits { + pub max_watches: usize, + pub max_watches_per_principal: usize, +} + +impl Default for DiscoveryLimits { + fn default() -> Self { + Self { + max_watches: 128, + max_watches_per_principal: 64, + } + } +} + /// One configured gateway interceptor service. #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] diff --git a/crates/openshell-sdk/src/client.rs b/crates/openshell-sdk/src/client.rs index 7d11bf3e9c..6461ec6343 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -1056,13 +1056,13 @@ impl OpenShellClient { workspace: &str, options: CreateRetryOptions, ) -> Result { - self.create_with_retry_using( + Box::pin(self.create_with_retry_using( request, workspace, options, create_retry_seed(), tokio::time::sleep, - ) + )) .await } diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index c5d6bb621a..359c9e610a 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -438,8 +438,8 @@ or starting a watch. `openshell.v1.ServiceDiscovery.GetServiceRouteSnapshot` and `WatchServiceRoutes` expose accepted installations for one explicit active workspace. They require `sandbox:read` and workspace -user access; omitted/all-workspaces selectors and sandbox principals are rejected. -Dedicated discovery machine grants are separate work. +user access. Omitted selectors and sandbox principals are rejected. Dedicated +reader grants and cross-workspace scopes are described below. Each successful response replaces the complete view. Consumers preserve the returned hostname as TLS SNI and HTTP authority when dialing the supervisor @@ -468,7 +468,9 @@ failure, configuration changes during collection or timeout return `UNAVAILABLE` malformed records return `INTERNAL`. Watches recheck bearer authentication and workspace authorization each second, use a one-message buffer, and end after one minute or a five-second blocked send. -Each gateway allows 32 watches, at most four per principal and 16 per workspace. +Each gateway allows 32 watches, at most four per principal. The eight-snapshot / +16-watch per-workspace limits apply only to explicit single-workspace requests; +finite and all-workspace consumers use caller/global limits independently. Cache reuse adds at most one refresh interval to collection freshness; consumers must independently honor the advertised lease expiry. Reconnect and relist on stream termination; revisions are opaque @@ -532,3 +534,30 @@ URL responses and discovery agree with that installed name. A mode or gateway name change changes configuration identity, withdrawing old discovery evidence until the supervisor acknowledges the replacement. Hash inputs and encoding are shared with gateway-mediated routing in `openshell-core::app_listener`. + +Discovery accepts an explicit workspace or the existing all-workspaces selector; +omission fails. Consumers of a finite grant open one watch per granted workspace +and combine the resulting views, replacing only the updated workspace's routes. +Workspace users retain role/scope/membership authorization for every requested +workspace; all-workspaces access requires platform administration or a dedicated +certificate grant. Discovery certificates carry `OU=discovery`, use the configured +TLS client CA, and receive authority only through the operator-managed fingerprint +mapping at `gateway.auth.discovery_grants_file`. They never become user/operator +principals. Certificate expiry and grant removal are rechecked on active watches. + +`gateway.auth.discovery.max_watches` (128) and `max_watches_per_principal` (64) +bound concurrent watches per gateway process. Size these for the number of +consumer replicas times their workspace subscriptions. Unary and per-workspace +admission budgets remain independent. + +All-workspaces collection includes future active workspaces and omits terminating +ones, without a fixed workspace-count ceiling. Active workspace metadata is +bounded to 4 MiB within the collection deadline. Selected-workspace collection +does not scan unrelated workspaces. Combined snapshots retain the 4,096-route/4-MiB output bound +and ten-second deadline covering setup, collection, and final reauthorization. +Caller/global capacity is reserved before workspace lookups. Watches retain +caller capacity, with tenant-local permits only for single-workspace requests. +Each refresh has the same ten-second deadline. Each workspace scan retains its existing +1,000-record/4-MiB input bounds. Overflow and storage failures are errors, never +partial successful views. A workspace-set change during collection requires a +retry; this is not a cross-resource transactional snapshot. diff --git a/crates/openshell-server/src/auth/audit.rs b/crates/openshell-server/src/auth/audit.rs index 59613f57a9..f85d58b213 100644 --- a/crates/openshell-server/src/auth/audit.rs +++ b/crates/openshell-server/src/auth/audit.rs @@ -219,7 +219,8 @@ fn authenticated(principal: &Principal) -> bool { match principal { Principal::User(user) => user.identity.provider != IdentityProvider::LocalDev, Principal::Anonymous => false, - Principal::Operator(_) + Principal::Discovery(_) + | Principal::Operator(_) | Principal::Sandbox(_) | Principal::Peer(_) | Principal::Supervisor(_) @@ -230,7 +231,7 @@ fn authenticated(principal: &Principal) -> bool { /// The mechanism that established `principal`, when it has an audit label. fn mechanism(principal: &Principal) -> Option { match principal { - Principal::Operator(_) => Some(AuthMechanism::Mtls), + Principal::Discovery(_) | Principal::Operator(_) => Some(AuthMechanism::Mtls), Principal::User(user) => match user.identity.provider { IdentityProvider::Oidc => Some(AuthMechanism::Oidc), IdentityProvider::Mtls => Some(AuthMechanism::Mtls), @@ -258,6 +259,7 @@ fn credential_digest( peer_certificate_sha256: Option<&str>, ) -> Option<[u8; 32]> { let credential = match principal { + Principal::Discovery(reader) => reader.certificate_sha256.as_str(), Principal::Operator(operator) => operator.certificate_sha256.as_str(), Principal::User(user) if user.identity.provider == IdentityProvider::Mtls => { peer_certificate_sha256.unwrap_or_default() @@ -627,6 +629,10 @@ pub enum AuthzDenial<'a> { /// The principal type may not call the method, or may not call it with /// these arguments. MethodNotPermitted, + /// A discovery-only principal lacks its administrator-managed grant. + DiscoveryGrantRequired, + /// The discovery grant does not authorize the selected workspace. + DiscoveryWorkspaceNotGranted { workspace: &'a str }, /// The method is not one the gateway knows, for example one added by a /// newer client. UnknownMethod, @@ -655,6 +661,8 @@ impl AuthzDenial<'_> { fn category(self) -> &'static str { match self { Self::MethodNotPermitted => "method_not_permitted", + Self::DiscoveryGrantRequired => "discovery_grant_required", + Self::DiscoveryWorkspaceNotGranted { .. } => "discovery_workspace_not_granted", Self::UnknownMethod => "unknown_method", Self::MissingRole => "missing_role", Self::MissingScope => "missing_scope", @@ -675,7 +683,8 @@ impl AuthzDenial<'_> { Self::CrossSandboxName { name } => { Some(ResourceDetails::named("sandbox", bounded(name))) } - Self::NotWorkspaceMember { workspace } + Self::DiscoveryWorkspaceNotGranted { workspace } + | Self::NotWorkspaceMember { workspace } | Self::InsufficientWorkspaceRole { workspace } => { Some(ResourceDetails::named("workspace", bounded(workspace))) } @@ -729,6 +738,7 @@ fn principal_user(principal: &Principal) -> User { Principal::Supervisor(supervisor) => { User::other(&supervisor.identity.subject, "Supervisor") } + Principal::Discovery(reader) => User::other(&reader.certificate_sha256, "Discovery Reader"), Principal::Anonymous => User::unidentified(), } } diff --git a/crates/openshell-server/src/auth/discovery.rs b/crates/openshell-server/src/auth/discovery.rs new file mode 100644 index 0000000000..5d5dfca791 --- /dev/null +++ b/crates/openshell-server/src/auth/discovery.rs @@ -0,0 +1,322 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Administrator-managed grants for verified discovery certificates. + +use super::{ + identity::{Identity, IdentityProvider}, + principal::DiscoveryPrincipal, +}; +use serde::Deserialize; +use std::{ + collections::BTreeSet, + path::Path, + sync::atomic::{AtomicI64, Ordering}, +}; +use tokio::io::AsyncReadExt as _; +use tonic::Status; + +pub const MAX_WORKSPACES: usize = 64; +const MAX_FILE_BYTES: usize = 256 * 1024; +static NEXT_WARNING_MS: AtomicI64 = AtomicI64::new(0); + +/// The reserved OU is always restricted, even if its grant configuration is absent. +pub fn is_certificate(identity: &Identity) -> bool { + identity.provider == IdentityProvider::Mtls + && identity.roles.iter().any(|role| role == "discovery") +} + +pub fn is_method(path: &str) -> bool { + matches!( + path, + "/openshell.v1.ServiceDiscovery/GetServiceRouteSnapshot" + | "/openshell.v1.ServiceDiscovery/WatchServiceRoutes" + ) && super::method_authz::lookup(path).is_some_and(|entry| { + entry.auth_mode == super::method_authz::AuthMode::Bearer + && entry.scope.as_deref() == Some("sandbox:read") + && entry.workspace_role.as_deref() == Some("user") + && entry.global_role.is_none() + }) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Grants { + readers: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Grant { + pub certificate_sha256: String, + #[serde(default)] + pub workspaces: Vec, + #[serde(default)] + pub all_workspaces: bool, +} + +struct ConfigError { + client: Status, + diagnostic: String, +} +fn invalid(message: impl Into) -> ConfigError { + ConfigError { + client: Status::unavailable("discovery grants unavailable or invalid"), + diagnostic: message.into(), + } +} + +async fn read_file(path: &Path) -> Result { + if path.as_os_str().is_empty() { + return Err(invalid("discovery grants path is empty")); + } + let metadata = tokio::fs::metadata(path) + .await + .map_err(|error| invalid(format!("cannot inspect grants file: {:?}", error.kind())))?; + if !metadata.is_file() { + return Err(invalid("discovery grants must be a regular file")); + } + let file = tokio::fs::File::open(path) + .await + .map_err(|error| invalid(format!("cannot open grants file: {:?}", error.kind())))?; + let mut bytes = Vec::new(); + file.take(u64::try_from(MAX_FILE_BYTES + 1).map_err(|_| invalid("invalid file bound"))?) + .read_to_end(&mut bytes) + .await + .map_err(|error| invalid(format!("cannot read grants file: {:?}", error.kind())))?; + if bytes.len() > MAX_FILE_BYTES { + return Err(invalid("discovery grants exceed the 256 KiB limit")); + } + let grants: Grants = serde_json::from_slice(&bytes).map_err(|error| { + invalid(format!( + "invalid grants JSON/schema at line {}, column {} ({:?})", + error.line(), + error.column(), + error.classify() + )) + })?; + if grants.readers.len() > 1024 { + return Err(invalid("discovery grants exceed the 1024-reader limit")); + } + let mut fingerprints = BTreeSet::new(); + for reader in &grants.readers { + if reader.certificate_sha256.len() != 64 + || !reader + .certificate_sha256 + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + return Err(invalid( + "certificate_sha256 must contain 64 lowercase hexadecimal digits", + )); + } + if !fingerprints.insert(&reader.certificate_sha256) { + return Err(invalid("duplicate discovery certificate fingerprint")); + } + if reader.workspaces.len() > MAX_WORKSPACES { + return Err(invalid( + "finite discovery grants accept at most 64 workspaces", + )); + } + if reader.all_workspaces != reader.workspaces.is_empty() { + return Err(invalid( + "select either all_workspaces or a nonempty workspaces list", + )); + } + let mut names = BTreeSet::new(); + for workspace in &reader.workspaces { + crate::grpc::workspace::validate_workspace_name(workspace) + .map_err(|_| invalid("invalid workspace name in discovery grant"))?; + if !names.insert(workspace) { + return Err(invalid("duplicate workspace in discovery grant")); + } + } + } + Ok(grants) +} + +async fn read_config(path: &Path) -> Result { + tokio::time::timeout(std::time::Duration::from_secs(2), read_file(path)) + .await + .map_err(|_| invalid("reading discovery grants exceeded two seconds"))? +} + +/// Validate initial configuration before the gateway starts serving requests. +pub async fn validate_configured(path: Option<&Path>) -> Result<(), String> { + if let Some(path) = path { + read_config(path).await.map_err(|error| { + format!("discovery grants {}: {}", path.display(), error.diagnostic) + })?; + } + Ok(()) +} + +pub async fn grant(path: Option<&Path>, principal: &DiscoveryPrincipal) -> Result { + if principal.expires_at_ms <= crate::persistence::current_time_ms() { + return Err(Status::unauthenticated("discovery certificate expired")); + } + let path = path.ok_or_else(|| Status::permission_denied("discovery grant required"))?; + let grants = read_config(path).await.map_err(|error| { + let now = crate::persistence::current_time_ms(); + let next = NEXT_WARNING_MS.load(Ordering::Relaxed); + if now >= next && NEXT_WARNING_MS.compare_exchange(next, now.saturating_add(30_000), Ordering::Relaxed, Ordering::Relaxed).is_ok() { + tracing::warn!(path = %path.display(), error = %error.diagnostic, "discovery grants reload failed; access denied"); + } + error.client + })?; + grants + .readers + .into_iter() + .find(|reader| reader.certificate_sha256 == principal.certificate_sha256) + .ok_or_else(|| Status::permission_denied("discovery grant revoked or missing")) +} + +/// Return the original status while recording the appropriate denial category. +pub fn audit_failure(principal: &super::principal::Principal, status: Status) -> Status { + use super::{ + audit, + authenticator::{AuthFailureReason, AuthMechanism, AuthRejection}, + }; + match status.code() { + tonic::Code::Unauthenticated => audit::reject_credential( + None, + AuthRejection::new( + AuthMechanism::Mtls, + AuthFailureReason::ExpiredCredential, + status, + ), + ), + tonic::Code::PermissionDenied => audit::deny( + principal, + audit::AuthzDenial::DiscoveryGrantRequired, + status.message(), + ), + _ => status, + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[tokio::test] + async fn initial_configuration_requires_a_regular_valid_mapping_but_allows_no_readers() { + assert!(validate_configured(None).await.is_ok()); + assert!( + validate_configured(Some(Path::new(""))) + .await + .unwrap_err() + .contains("empty") + ); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("grants.json"); + assert!( + validate_configured(Some(&path)) + .await + .unwrap_err() + .contains("NotFound") + ); + std::fs::write(&path, r#"{"readers":[{"all_workspace":true}]}"#).unwrap(); + assert!( + validate_configured(Some(&path)) + .await + .unwrap_err() + .contains("JSON/schema") + ); + std::fs::write(&path, r#"{"readers":[]}"#).unwrap(); + validate_configured(Some(&path)).await.unwrap(); + assert!( + validate_configured(Some(dir.path())) + .await + .unwrap_err() + .contains("regular file") + ); + } + + #[test] + fn reserved_discovery_ou_is_restricted_independently_of_other_roles() { + let identity = Identity { + subject: "reader".into(), + display_name: None, + roles: vec!["discovery".into(), "operator".into()], + scopes: vec![], + provider: IdentityProvider::Mtls, + }; + assert!(is_certificate(&identity)); + assert!(!is_certificate(&Identity { + provider: IdentityProvider::Oidc, + ..identity + })); + } + #[tokio::test] + async fn fingerprint_grants_reload_and_never_derive_authority_from_subject_roles() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("grants.json"); + let reader = DiscoveryPrincipal { + certificate_sha256: "a".repeat(64), + expires_at_ms: crate::persistence::current_time_ms() + 60_000, + }; + let write = |readers: serde_json::Value| { + std::fs::write( + &path, + serde_json::to_vec(&serde_json::json!({"readers":readers})).unwrap(), + ) + .unwrap(); + }; + write( + serde_json::json!([{"certificate_sha256":reader.certificate_sha256,"workspaces":["default"]}]), + ); + assert_eq!( + grant(Some(&path), &reader).await.unwrap().workspaces, + vec!["default"] + ); + let unrelated = DiscoveryPrincipal { + certificate_sha256: "b".repeat(64), + ..reader.clone() + }; + assert_eq!( + grant(Some(&path), &unrelated).await.err().unwrap().code(), + tonic::Code::PermissionDenied + ); + write(serde_json::json!([])); + assert_eq!( + grant(Some(&path), &reader).await.err().unwrap().code(), + tonic::Code::PermissionDenied + ); + write( + serde_json::json!([{"certificate_sha256":reader.certificate_sha256,"all_workspaces":true,"workspaces":["default"]}]), + ); + assert_eq!( + grant(Some(&path), &reader).await.err().unwrap().code(), + tonic::Code::Unavailable + ); + assert_eq!( + grant( + Some(&path), + &DiscoveryPrincipal { + expires_at_ms: 0, + ..reader + } + ) + .await + .err() + .unwrap() + .code(), + tonic::Code::Unauthenticated + ); + } + #[test] + fn every_other_rpc_is_denied_including_unclassified_methods() { + for path in super::super::method_authz::all_paths() { + assert_eq!( + is_method(path), + matches!( + path, + "/openshell.v1.ServiceDiscovery/GetServiceRouteSnapshot" + | "/openshell.v1.ServiceDiscovery/WatchServiceRoutes" + ), + "{path}" + ); + } + assert!(!is_method("/openshell.v1.OpenShell/FutureReadMethod")); + } +} diff --git a/crates/openshell-server/src/auth/guard.rs b/crates/openshell-server/src/auth/guard.rs index 7d13739a87..b41d5b9848 100644 --- a/crates/openshell-server/src/auth/guard.rs +++ b/crates/openshell-server/src/auth/guard.rs @@ -30,13 +30,14 @@ use tonic::Status; pub fn ensure_sandbox_scope(principal: &Principal, claimed_sandbox_id: &str) -> Result<(), Status> { match principal { Principal::User(_) | Principal::Operator(_) => Ok(()), - Principal::Peer(_) | Principal::Supervisor(_) | Principal::SupervisorRegistration(_) => { - Err(deny( - principal, - AuthzDenial::MethodNotPermitted, - "gateway peer and supervisor principals may not call sandbox-scoped methods", - )) - } + Principal::Discovery(_) + | Principal::Peer(_) + | Principal::Supervisor(_) + | Principal::SupervisorRegistration(_) => Err(deny( + principal, + AuthzDenial::MethodNotPermitted, + "gateway peer and supervisor principals may not call sandbox-scoped methods", + )), Principal::Sandbox(p) => { if p.sandbox_id == claimed_sandbox_id { Ok(()) @@ -90,7 +91,8 @@ pub fn ensure_sandbox_principal_scope( ensure_sandbox_scope(principal, claimed_sandbox_id)?; Ok(p.clone()) } - Principal::User(_) + Principal::Discovery(_) + | Principal::User(_) | Principal::Operator(_) | Principal::Peer(_) | Principal::Supervisor(_) diff --git a/crates/openshell-server/src/auth/mod.rs b/crates/openshell-server/src/auth/mod.rs index f4ae2d08a9..d51ef2e97d 100644 --- a/crates/openshell-server/src/auth/mod.rs +++ b/crates/openshell-server/src/auth/mod.rs @@ -13,6 +13,7 @@ pub mod authenticator; pub mod authz; pub mod compute_driver; pub mod descriptor_authz; +pub mod discovery; pub mod extension_mint_limit; pub mod guard; mod http; diff --git a/crates/openshell-server/src/auth/principal.rs b/crates/openshell-server/src/auth/principal.rs index f09efc8261..48089cab43 100644 --- a/crates/openshell-server/src/auth/principal.rs +++ b/crates/openshell-server/src/auth/principal.rs @@ -23,6 +23,8 @@ use openshell_core::jwt::CredentialEpoch; /// retrieve it via `req.extensions().get::()`. #[derive(Debug, Clone)] pub enum Principal { + /// Restricted verified certificate; authority is reloaded from an administrator grant. + Discovery(DiscoveryPrincipal), /// Human caller authenticated via OIDC (Keycloak, Entra ID, Okta, etc.). User(UserPrincipal), /// Gateway-wide administrator authenticated only by a verified operator certificate. @@ -61,6 +63,13 @@ pub struct OperatorPrincipal { pub certificate_sha256: String, } +/// Verified TLS discovery identity. No general user, role, or application authority. +#[derive(Debug, Clone)] +pub struct DiscoveryPrincipal { + pub certificate_sha256: String, + pub expires_at_ms: i64, +} + impl Principal { /// Identity of a human/API caller, preserving its distinct principal variant. pub fn user_identity(&self) -> Option<&Identity> { @@ -153,6 +162,7 @@ impl Principal { Self::SupervisorRegistration(identity) => { format!("supervisor-registration:{}", identity.route) } + Self::Discovery(reader) => format!("discovery:{}", reader.certificate_sha256), Self::Anonymous => "anonymous".to_string(), } } diff --git a/crates/openshell-server/src/auth/service_access.rs b/crates/openshell-server/src/auth/service_access.rs index 3a03577c30..553e5be613 100644 --- a/crates/openshell-server/src/auth/service_access.rs +++ b/crates/openshell-server/src/auth/service_access.rs @@ -58,6 +58,15 @@ async fn authorize_with_chain( workspace: &str, chain: Option, ) -> Result { + if peer + .identity + .as_ref() + .is_some_and(crate::auth::discovery::is_certificate) + { + return Err(Status::permission_denied( + "discovery certificates cannot access applications", + )); + } let origin = RequestOrigin::new(peer.source, headers); let principal = authenticate(state, headers, peer, chain).await.map_err( |(status, mechanism, reason)| { @@ -416,6 +425,36 @@ mod tests { ); } + #[tokio::test] + async fn discovery_ou_always_restricts_application_access() { + 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; + user.roles.push("discovery".into()); + let peer = ServicePeer { + identity: Some(user), + ..Default::default() + }; + authorize_with_chain(&state, &HeaderMap::new(), &peer, "default", None) + .await + .expect_err("discovery identity must not fall back to an ordinary mTLS user"); + let directory = tempfile::tempdir().unwrap(); + Arc::get_mut(&mut state) + .unwrap() + .config + .auth + .discovery_grants_file = Some(directory.path().join("missing-grants.json")); + assert_eq!( + authorize_with_chain(&state, &HeaderMap::new(), &peer, "default", None) + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + } + #[tokio::test] async fn service_access_uses_only_verified_mtls_identity_and_operator_fingerprint() { let mut state = state().await; diff --git a/crates/openshell-server/src/auth/workspace_authz.rs b/crates/openshell-server/src/auth/workspace_authz.rs index c8bc1e79dc..6a97ea84d1 100644 --- a/crates/openshell-server/src/auth/workspace_authz.rs +++ b/crates/openshell-server/src/auth/workspace_authz.rs @@ -207,13 +207,14 @@ pub async fn authorize_workspace( workspace, grant: AuthGrant::Sandbox, }), - Principal::Peer(_) | Principal::Supervisor(_) | Principal::SupervisorRegistration(_) => { - Err(deny( - principal, - AuthzDenial::MethodNotPermitted, - "gateway peer and supervisor principals cannot perform workspace operations", - )) - } + Principal::Discovery(_) + | Principal::Peer(_) + | Principal::Supervisor(_) + | Principal::SupervisorRegistration(_) => Err(deny( + principal, + AuthzDenial::MethodNotPermitted, + "gateway peer and supervisor principals cannot perform workspace operations", + )), Principal::Anonymous => Err(Status::unauthenticated("authentication required")), } } @@ -246,7 +247,10 @@ pub fn require_platform_admin(admin_role: &str, principal: &Principal) -> Result } Principal::User(_) => "platform admin role required for cross-workspace operations", Principal::Sandbox(_) => "sandbox principals cannot perform cross-workspace operations", - Principal::Peer(_) | Principal::Supervisor(_) | Principal::SupervisorRegistration(_) => { + Principal::Discovery(_) + | Principal::Peer(_) + | Principal::Supervisor(_) + | Principal::SupervisorRegistration(_) => { "gateway peer and supervisor principals cannot perform cross-workspace operations" } Principal::Anonymous => return Err(Status::unauthenticated("authentication required")), diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index 475e06467f..4c8605b739 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -961,7 +961,20 @@ fn unauthenticated_users_allowed(file: Option<&ConfigFile>) -> bool { /// Reject an implicit development gateway before starting any listeners or services. fn validate_user_auth(config: &openshell_core::Config) -> Result<()> { + if config.auth.discovery_grants_file.is_some() + && config + .tls + .as_ref() + .and_then(|tls| tls.client_ca_path.as_ref()) + .is_none() + { + return Err(miette::miette!( + "discovery grants require TLS and a client CA" + )); + } + if !config.auth.allow_unauthenticated_users + && config.auth.discovery_grants_file.is_none() && !config.mtls_auth.enabled && !config.mtls_auth.operator_enabled && config.oidc.is_none() @@ -987,6 +1000,11 @@ async fn run_from_args( ) -> Result<()> { let prepared = prepare_server_config_with_drivers(&mut args, &matches, &compute_drivers)?; validate_user_auth(&prepared.config)?; + crate::auth::discovery::validate_configured( + prepared.config.auth.discovery_grants_file.as_deref(), + ) + .await + .map_err(|error| miette::miette!("{error}"))?; openshell_ocsf::register_trace_correlation_extractor( openshell_otel::current_ocsf_trace_correlation, diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 5dcfdd41e3..65af25a55a 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -2794,11 +2794,12 @@ async fn resolve_sandbox_by_name_for_principal( Principal::User(_) | Principal::Operator(_) => { sandbox.ok_or_else(|| Status::not_found("sandbox not found")) } - Principal::Peer(_) | Principal::Supervisor(_) | Principal::SupervisorRegistration(_) => { - Err(Status::permission_denied( - "gateway peer and supervisor principals may not resolve sandbox configuration", - )) - } + Principal::Discovery(_) + | Principal::Peer(_) + | Principal::Supervisor(_) + | Principal::SupervisorRegistration(_) => Err(Status::permission_denied( + "gateway peer and supervisor principals may not resolve sandbox configuration", + )), Principal::Anonymous => Err(Status::unauthenticated( "sandbox-scoped methods require an authenticated caller", )), diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index bfc34f9835..9f0dfc9c46 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -4813,7 +4813,8 @@ async fn exchange_provider_subject_token_inner( let auth_code = match request.extensions().get::() { Some(Principal::Sandbox(principal)) if principal.sandbox_id == req.sandbox_id => None, Some( - Principal::Sandbox(_) + Principal::Discovery(_) + | Principal::Sandbox(_) | Principal::User(_) | Principal::Operator(_) | Principal::Peer(_) diff --git a/crates/openshell-server/src/grpc/service_discovery.rs b/crates/openshell-server/src/grpc/service_discovery.rs index 437d4e78bd..1d1d95dcaa 100644 --- a/crates/openshell-server/src/grpc/service_discovery.rs +++ b/crates/openshell-server/src/grpc/service_discovery.rs @@ -24,7 +24,7 @@ use super::service_advertisement::{Installation, OBJECT_TYPE, current_sandbox, v use crate::ServerState; use crate::auth::principal::Principal; use crate::auth::workspace_authz::{ - MinWorkspaceRole, authorize_workspace, selected_workspace_name, + MinWorkspaceRole, authorize_workspace, require_platform_admin, selected_workspace_name, }; use crate::persistence::{ObjectCursor, ObjectRecord, current_time_ms}; @@ -42,13 +42,14 @@ pub type RouteWatchStream = ReceiverStream)>; type CacheSlot = Arc>; #[derive(Debug)] pub struct DiscoveryState { + max_watches_per_principal: usize, unary: Arc, collections: Arc, shares: std::sync::Mutex< @@ -60,6 +61,8 @@ pub struct DiscoveryState { impl Default for DiscoveryState { fn default() -> Self { Self { + max_watches_per_principal: openshell_core::config::DiscoveryLimits::default() + .max_watches_per_principal, unary: Arc::new(tokio::sync::Semaphore::new(MAX_UNARY)), collections: Arc::new(tokio::sync::Semaphore::new(MAX_COLLECTIONS)), shares: std::sync::Mutex::default(), @@ -74,6 +77,7 @@ fn principal_key(principal: &Principal) -> Result { "user:{:?}:{}", user.identity.provider, user.identity.subject )), + Principal::Discovery(reader) => Ok(format!("discovery:{}", reader.certificate_sha256)), Principal::Operator(operator) => Ok(format!("operator:{}", operator.certificate_sha256)), _ => Err(Status::permission_denied( "service discovery requires a user/API identity", @@ -82,6 +86,27 @@ fn principal_key(principal: &Principal) -> Result { } impl DiscoveryState { + pub fn new(limits: &openshell_core::config::DiscoveryLimits) -> Result { + if [limits.max_watches, limits.max_watches_per_principal] + .iter() + .any(|value| *value == 0 || *value > tokio::sync::Semaphore::MAX_PERMITS) + { + return Err("discovery watch limits must be positive and fit semaphore capacity"); + } + Ok(Self { + max_watches_per_principal: limits.max_watches_per_principal, + ..Self::default() + }) + } + + fn caller_limit(&self, watch: bool) -> usize { + if watch { + self.max_watches_per_principal + } else { + UNARY_PER_PRINCIPAL + } + } + fn share( &self, key: String, @@ -105,10 +130,9 @@ impl DiscoveryState { .map_err(|_| Status::resource_exhausted("discovery caller or workspace limit exceeded")) } - pub(crate) fn admit( + fn admit_caller( &self, principal: &Principal, - workspaces: &[String], watch: bool, ) -> Result, Status> { let kind = if watch { "watch" } else { "snapshot" }; @@ -122,8 +146,18 @@ impl DiscoveryState { } permits.push(self.share( format!("{kind}:{}", principal_key(principal)?), - WATCHES_PER_PRINCIPAL, + self.caller_limit(watch), )?); + Ok(permits) + } + + fn admit_workspaces( + &self, + workspaces: &[String], + watch: bool, + ) -> Result, Status> { + let kind = if watch { "watch" } else { "snapshot" }; + let mut permits = Vec::new(); for workspace in workspaces { permits.push(self.share( format!("{kind}:workspace:{workspace}"), @@ -133,6 +167,18 @@ impl DiscoveryState { Ok(permits) } + #[cfg(test)] + fn admit( + &self, + principal: &Principal, + workspaces: &[String], + watch: bool, + ) -> Result, Status> { + let mut permits = self.admit_caller(principal, watch)?; + permits.extend(self.admit_workspaces(workspaces, watch)?); + Ok(permits) + } + async fn slot(&self, workspace: &str) -> Result { let mut cache = self.cache.lock().await; let now = tokio::time::Instant::now(); @@ -249,6 +295,188 @@ async fn authorize( Ok(()) } +#[derive(Clone, Debug)] +enum Selection { + Named(Vec), + All, +} + +fn selection( + scope: Option<&openshell_core::proto::WorkspaceSelector>, +) -> Result { + use openshell_core::proto::workspace_selector::Selection as Scope; + match scope.and_then(|scope| scope.selection.as_ref()) { + Some(Scope::AllWorkspaces(_)) => Ok(Selection::All), + _ => Ok(Selection::Named(vec![ + selected_workspace_name(scope)?.to_string(), + ])), + } +} + +impl Selection { + fn tenant_scope(&self) -> Option<&[String]> { + match self { + Self::Named(names) => Some(names), + Self::All => None, + } + } +} + +async fn authorize_selection( + state: &ServerState, + principal: &Principal, + selection: &Selection, +) -> Result<(), Status> { + if let Principal::Discovery(reader) = principal { + use crate::auth::audit::{AuthzDenial, deny}; + let grant = crate::auth::discovery::grant( + state.config.auth.discovery_grants_file.as_deref(), + reader, + ) + .await + .map_err(|status| crate::auth::discovery::audit_failure(principal, status))?; + return match selection { + Selection::All if !grant.all_workspaces => Err(deny( + principal, + AuthzDenial::DiscoveryGrantRequired, + "all-workspaces discovery grant required", + )), + Selection::Named(names) if !grant.all_workspaces => names + .iter() + .find(|name| !grant.workspaces.contains(name)) + .map_or_else( + || Ok(()), + |workspace| { + Err(deny( + principal, + AuthzDenial::DiscoveryWorkspaceNotGranted { workspace }, + "workspace not granted for discovery", + )) + }, + ), + _ => Ok(()), + }; + } + match selection { + Selection::All => { + if let Principal::User(user) = principal { + let explicit_dev = state.config.auth.allow_unauthenticated_users + && user.identity.provider == crate::auth::identity::IdentityProvider::LocalDev; + if !explicit_dev && state.admin_role.is_empty() { + return Err(crate::auth::audit::deny( + principal, + crate::auth::audit::AuthzDenial::PlatformAdminRequired, + "explicit platform discovery authority required", + )); + } + } + require_platform_admin(&state.admin_role, principal) + } + Selection::Named(names) => { + for name in names { + authorize(state, principal, name).await?; + } + Ok(()) + } + } +} + +async fn active_workspaces(state: &ServerState) -> Result, Status> { + let mut cursor: Option = None; + let mut names = Vec::new(); + let mut bytes = 0usize; + loop { + let page = state + .store + .list_by_type_after("workspace", cursor.as_ref(), 128) + .await + .map_err(|_| Status::unavailable("workspace discovery storage unavailable"))?; + for record in &page { + let workspace = openshell_core::proto::Workspace::decode(record.payload.as_slice()) + .map_err(|_| Status::internal("invalid workspace record"))?; + let metadata = workspace + .metadata + .ok_or_else(|| Status::internal("workspace metadata missing"))?; + if metadata.deletion_time.is_none() { + bytes = bytes.saturating_add(record.payload.len()); + if bytes > MAX_BYTES { + return Err(Status::resource_exhausted( + "workspace discovery metadata byte limit exceeded", + )); + } + names.push(metadata.name); + } + } + cursor = page.last().map(ObjectCursor::from); + if page.len() < 128 { + break; + } + } + names.sort(); + Ok(names) +} + +async fn selection_workspaces( + state: &ServerState, + selection: &Selection, +) -> Result, Status> { + match selection { + Selection::All => active_workspaces(state).await, + Selection::Named(names) => { + let mut active = Vec::new(); + for name in names { + match super::workspace::resolve_workspace(state.store.as_ref(), name).await { + Ok(workspace) if !workspace.terminating => active.push(name.clone()), + Ok(_) => {} + Err(error) if error.code() == tonic::Code::NotFound => {} + Err(error) => return Err(error), + } + } + Ok(active) + } + } +} + +async fn selected_snapshot( + state: &ServerState, + principal: &Principal, + selection: &Selection, + admitted_workspaces: &[String], +) -> Result { + tokio::time::timeout(SNAPSHOT_TIMEOUT, async { + authorize_selection(state, principal, selection).await?; + let before = selection_workspaces(state, selection).await?; + if before != admitted_workspaces { + return Err(Status::unavailable( + "workspace set changed during admission; retry", + )); + } + let names = before.clone(); + let mut result = ServiceRouteSnapshot::default(); + let mut bytes = 0usize; + for name in names { + let part = cached_snapshot(state, &name).await?; + bytes = bytes.saturating_add(part.encoded_len()); + if bytes > MAX_BYTES - 128 || result.routes.len() + part.routes.len() > MAX_ROUTES { + return Err(Status::resource_exhausted( + "combined discovery limit exceeded", + )); + } + result.routes.extend(part.routes); + } + if before != selection_workspaces(state, selection).await? { + return Err(Status::unavailable( + "workspace set changed during discovery; retry", + )); + } + // Recheck grants/membership after collection, before publishing a view. + authorize_selection(state, principal, selection).await?; + finish_snapshot(result.routes) + }) + .await + .map_err(|_| Status::unavailable("service discovery collection timed out"))? +} + fn require_enabled(state: &ServerState) -> Result<(), Status> { if !state.config.supervisor_app_listener.enabled { return Err(Status::failed_precondition( @@ -258,24 +486,61 @@ fn require_enabled(state: &ServerState) -> Result<(), Status> { Ok(()) } +struct PreparedSnapshot { + snapshot: ServiceRouteSnapshot, + workspaces: Vec, + workspace_permits: Vec, +} + +/// Caller/global capacity must be held before doing any authorization or +/// workspace I/O. One deadline covers preparation through final reauthorization. +async fn prepare_snapshot( + state: &ServerState, + principal: &mut Principal, + selection: &Selection, + recheck: Option<&BearerRecheck>, + watch: bool, +) -> Result { + tokio::time::timeout(SNAPSHOT_TIMEOUT, async { + authorize_selection(state, principal, selection).await?; + let workspaces = selection_workspaces(state, selection).await?; + let workspace_permits = match selection.tenant_scope() { + Some(names) => state.discovery.admit_workspaces(names, watch)?, + None => Vec::new(), + }; + let snapshot = selected_snapshot(state, principal, selection, &workspaces).await?; + if let Some(recheck) = recheck { + *principal = recheck.check(principal).await?; + } + authorize_selection(state, principal, selection).await?; + Ok(PreparedSnapshot { + snapshot, + workspaces, + workspace_permits, + }) + }) + .await + .map_err(|_| Status::unavailable("service discovery preparation timed out"))? +} + pub async fn get_snapshot( state: &Arc, request: Request, ) -> Result, Status> { let mut principal = super::extract_principal(&request)?; require_enabled(state)?; - let workspace = selected_workspace_name(request.get_ref().workspace_scope.as_ref())?; - authorize(state, &principal, workspace).await?; - let _permits = state - .discovery - .admit(&principal, &[workspace.to_string()], false)?; - let snapshot = cached_snapshot(state, workspace).await?; - if let Some(recheck) = request.extensions().get::() { - principal = recheck.check(&principal).await?; - } - authorize(state, &principal, workspace).await?; + let selection = selection(request.get_ref().workspace_scope.as_ref())?; + let _caller_permits = state.discovery.admit_caller(&principal, false)?; + let prepared = prepare_snapshot( + state, + &mut principal, + &selection, + request.extensions().get::(), + false, + ) + .await?; Ok(Response::new(GetServiceRouteSnapshotResponse { - snapshot: Some(snapshot), + snapshot: Some(prepared.snapshot), })) } @@ -285,23 +550,19 @@ pub async fn watch( ) -> Result, Status> { let mut principal = super::extract_principal(&request)?; require_enabled(state)?; - let workspace = - selected_workspace_name(request.get_ref().workspace_scope.as_ref())?.to_string(); - authorize(state, &principal, &workspace).await?; - let shares = state - .discovery - .admit(&principal, std::slice::from_ref(&workspace), true)?; - let recheck = request.extensions().get::().cloned(); + let selection = selection(request.get_ref().workspace_scope.as_ref())?; + let caller_permits = state.discovery.admit_caller(&principal, true)?; let permit = state .discovery_watches .clone() .try_acquire_owned() .map_err(|_| Status::resource_exhausted("too many service discovery watches"))?; - let initial = cached_snapshot(state, &workspace).await?; - if let Some(recheck) = &recheck { - principal = recheck.check(&principal).await?; - } - authorize(state, &principal, &workspace).await?; + let recheck = request.extensions().get::().cloned(); + let PreparedSnapshot { + snapshot: initial, + workspaces: mut admitted_names, + workspace_permits: shares, + } = prepare_snapshot(state, &mut principal, &selection, recheck.as_ref(), true).await?; let mut revision = initial.revision.clone(); let (tx, rx) = tokio::sync::mpsc::channel(1); tx.try_send(Ok(WatchServiceRoutesResponse { @@ -309,9 +570,10 @@ pub async fn watch( })) .map_err(|_| Status::cancelled("discovery client closed"))?; let state = state.clone(); - tokio::spawn(async move { + tokio::spawn(crate::auth::audit::in_current_request(async move { let _permit = permit; - let _shares = shares; + let _caller_permits = caller_permits; + let mut shares = Some(shares); let run = async { let mut interval = tokio::time::interval(REFRESH_INTERVAL); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); @@ -321,18 +583,29 @@ pub async fn watch( () = tx.closed() => return, _ = interval.tick() => {} } - let refresh = async { - authorize(&state, &principal, &workspace).await?; - let snapshot = cached_snapshot(&state, &workspace).await?; + let refresh = tokio::time::timeout(SNAPSHOT_TIMEOUT, async { + let names = selection_workspaces(&state, &selection).await?; + if names != admitted_names { + drop(shares.take()); + shares = Some(match selection.tenant_scope() { + Some(tenant) => state.discovery.admit_workspaces(tenant, true)?, + None => Vec::new(), + }); + admitted_names = names; + } + let snapshot = + selected_snapshot(&state, &principal, &selection, &admitted_names).await?; if let Some(recheck) = &recheck { principal = recheck.check(&principal).await?; } - authorize(&state, &principal, &workspace).await?; + authorize_selection(&state, &principal, &selection).await?; Ok::<_, Status>(snapshot) - }; + }); let result = tokio::select! { () = tx.closed() => return, - result = refresh => result, + result = refresh => result.unwrap_or_else(|_| { + Err(Status::unavailable("service discovery refresh timed out")) + }), }; let message = match result { Ok(next) if next.revision == revision => continue, @@ -355,7 +628,7 @@ pub async fn watch( } }; let _ = tokio::time::timeout(WATCH_LIFETIME, run).await; - }); + })); Ok(Response::new(ReceiverStream::new(rx))) } @@ -605,6 +878,64 @@ mod tests { use crate::grpc::test_support::authed_request; use tokio_stream::StreamExt as _; + #[test] + fn watch_admission_supports_a_full_finite_grant_and_configured_budgets() { + use openshell_core::config::DiscoveryLimits; + let principal = Principal::Discovery(crate::auth::principal::DiscoveryPrincipal { + certificate_sha256: "a".repeat(64), + expires_at_ms: i64::MAX, + }); + for limit in [64, 3] { + let state = DiscoveryState::new(&DiscoveryLimits { + max_watches_per_principal: limit, + ..Default::default() + }) + .unwrap(); + let permits = (0..limit) + .map(|_| state.admit_caller(&principal, true).unwrap()) + .collect::>(); + assert_eq!( + state.admit_caller(&principal, true).unwrap_err().code(), + tonic::Code::ResourceExhausted + ); + assert!(state.admit_caller(&principal, false).is_ok()); + drop(permits); + assert!(state.admit_caller(&principal, true).is_ok()); + } + } + + #[test] + fn discovery_watch_limits_reject_invalid_capacity() { + use openshell_core::config::{DiscoveryLimits, GatewayAuthConfig}; + let auth: GatewayAuthConfig = serde_json::from_value(serde_json::json!({ + "discovery": {"max_watches_per_principal": 7} + })) + .unwrap(); + assert_eq!(auth.discovery.max_watches, 128); + assert_eq!( + DiscoveryState::new(&auth.discovery) + .unwrap() + .caller_limit(true), + 7 + ); + for invalid in [0, tokio::sync::Semaphore::MAX_PERMITS + 1] { + assert!( + DiscoveryState::new(&DiscoveryLimits { + max_watches: invalid, + ..Default::default() + }) + .is_err() + ); + assert!( + DiscoveryState::new(&DiscoveryLimits { + max_watches_per_principal: invalid, + ..Default::default() + }) + .is_err() + ); + } + } + fn request() -> GetServiceRouteSnapshotRequest { GetServiceRouteSnapshotRequest { workspace_scope: Some(openshell_core::proto::workspace_selector("default")), @@ -853,7 +1184,10 @@ mod tests { .unwrap() .into_inner(); let first = stream.next().await.unwrap().unwrap().snapshot.unwrap(); - assert_eq!(state.discovery_watches.available_permits(), 31); + assert_eq!( + state.discovery_watches.available_permits(), + state.config.auth.discovery.max_watches - 1 + ); report.lease_sequence = 2; accept(&state, &owner, &report, current_time_ms() + 14_000) .await @@ -886,7 +1220,9 @@ mod tests { assert!(withdrawn.routes.is_empty()); drop(stream); tokio::time::timeout(Duration::from_secs(2), async { - while state.discovery_watches.available_permits() != 32 { + while state.discovery_watches.available_permits() + != state.config.auth.discovery.max_watches + { tokio::task::yield_now().await; } }) @@ -895,7 +1231,53 @@ mod tests { } #[tokio::test] - async fn explicit_workspace_and_membership_are_required_and_watch_capacity_is_bounded() { + async fn user_platform_discovery_requires_an_explicit_configured_admin_role() { + for admin_role in ["openshell-admin", ""] { + let (mut state, _, _) = installed_fixture().await; + let inner = Arc::get_mut(&mut state).unwrap(); + inner.admin_role = admin_role.into(); + inner.config.auth.allow_unauthenticated_users = false; + let mut principal = user("ordinary-user"); + if let Principal::User(user) = &mut principal { + user.identity.roles.clear(); + } + let scope = Some(openshell_core::proto::all_workspaces_selector()); + assert_eq!( + get_snapshot( + &state, + reader_request( + GetServiceRouteSnapshotRequest { + workspace_scope: scope.clone() + }, + &principal + ) + ) + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + assert_eq!( + watch( + &state, + reader_request( + WatchServiceRoutesRequest { + workspace_scope: scope + }, + &principal + ) + ) + .await + .err() + .unwrap() + .code(), + tonic::Code::PermissionDenied + ); + } + } + + #[tokio::test] + async fn workspace_selections_require_authority_and_watch_capacity_is_bounded() { let (state, _, _) = installed_fixture().await; assert_eq!( get_snapshot( @@ -915,7 +1297,7 @@ mod tests { }) ) .await - .is_err() + .is_ok() ); let mut outsider = authed_request(request()); if let Some(Principal::User(user)) = outsider.extensions_mut().get_mut::() { @@ -935,7 +1317,7 @@ mod tests { let _all = state .discovery_watches .clone() - .acquire_many_owned(32) + .acquire_many_owned(u32::try_from(state.config.auth.discovery.max_watches).unwrap()) .await .unwrap(); let error = watch( @@ -985,7 +1367,10 @@ mod tests { .unwrap_err(); assert_eq!(error.code(), tonic::Code::PermissionDenied); assert!(stream.next().await.is_none()); - assert_eq!(state.discovery_watches.available_permits(), 32); + assert_eq!( + state.discovery_watches.available_permits(), + state.config.auth.discovery.max_watches + ); } #[tokio::test] @@ -1010,7 +1395,10 @@ mod tests { .unwrap() .is_none() ); - assert_eq!(state.discovery_watches.available_permits(), 32); + assert_eq!( + state.discovery_watches.available_permits(), + state.config.auth.discovery.max_watches + ); } #[tokio::test] @@ -1275,7 +1663,11 @@ mod tests { #[test] fn admission_bounds_each_principal_workspace_and_unary_pool_and_releases_capacity() { - let state = DiscoveryState::default(); + let state = DiscoveryState::new(&openshell_core::config::DiscoveryLimits { + max_watches_per_principal: 4, + ..Default::default() + }) + .unwrap(); let a = vec!["a".into()]; let b = vec!["b".into()]; let mut watches = Vec::new(); @@ -1443,7 +1835,10 @@ mod tests { .unwrap_err(); assert_eq!(error.code(), tonic::Code::Unauthenticated); assert!(stream.next().await.is_none()); - assert_eq!(state.discovery_watches.available_permits(), 32); + assert_eq!( + state.discovery_watches.available_permits(), + state.config.auth.discovery.max_watches + ); assert!( state .discovery @@ -1592,4 +1987,671 @@ mod tests { .unwrap_err(); assert_eq!(error.code(), tonic::Code::PermissionDenied); } + async fn reader_fixture(all: bool) -> (Arc, Principal, tempfile::TempDir) { + let (mut state, owner, report) = installed_fixture().await; + accept(&state, &owner, &report, current_time_ms() + 10_000) + .await + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("grants.json"); + let fingerprint = "a".repeat(64); + let grant = if all { + serde_json::json!({"certificate_sha256":fingerprint,"all_workspaces":true}) + } else { + serde_json::json!({"certificate_sha256":fingerprint,"workspaces":["default","team-b"]}) + }; + std::fs::write( + &path, + serde_json::to_vec(&serde_json::json!({"readers":[grant]})).unwrap(), + ) + .unwrap(); + Arc::get_mut(&mut state) + .unwrap() + .config + .auth + .discovery_grants_file = Some(path); + let principal = Principal::Discovery(crate::auth::principal::DiscoveryPrincipal { + certificate_sha256: fingerprint, + expires_at_ms: current_time_ms() + 60_000, + }); + (state, principal, dir) + } + + #[tokio::test] + async fn tenant_snapshot_saturation_does_not_consume_platform_admission() { + let (state, principal, _dir) = reader_fixture(true).await; + let names = vec!["default".into()]; + let _tenant_permits = (0..8) + .map(|_| state.discovery.admit_workspaces(&names, false).unwrap()) + .collect::>(); + assert_eq!( + get_snapshot(&state, reader_request(request(), &principal)) + .await + .unwrap_err() + .code(), + tonic::Code::ResourceExhausted + ); + for scope in [openshell_core::proto::all_workspaces_selector()] { + get_snapshot( + &state, + reader_request( + GetServiceRouteSnapshotRequest { + workspace_scope: Some(scope), + }, + &principal, + ), + ) + .await + .unwrap(); + } + } + + #[tokio::test] + async fn tenant_and_platform_watches_do_not_take_each_others_workspace_permits() { + for platform in [false, true] { + let (state, principal, dir) = reader_fixture(true).await; + let fingerprints = (0..WATCHES_PER_WORKSPACE) + .map(|n| format!("{n:064x}")) + .collect::>(); + let mut readers = fingerprints.iter().map(|fingerprint| serde_json::json!({"certificate_sha256":fingerprint,"all_workspaces":true})).collect::>(); + readers.push( + serde_json::json!({"certificate_sha256":"a".repeat(64),"all_workspaces":true}), + ); + std::fs::write( + dir.path().join("grants.json"), + serde_json::to_vec(&serde_json::json!({"readers":readers})).unwrap(), + ) + .unwrap(); + let mut streams = Vec::new(); + for fingerprint in fingerprints { + let caller = Principal::Discovery(crate::auth::principal::DiscoveryPrincipal { + certificate_sha256: fingerprint, + expires_at_ms: current_time_ms() + 60_000, + }); + let scope = if platform { + openshell_core::proto::all_workspaces_selector() + } else { + openshell_core::proto::workspace_selector("default") + }; + let mut stream = watch( + &state, + reader_request( + WatchServiceRoutesRequest { + workspace_scope: Some(scope), + }, + &caller, + ), + ) + .await + .unwrap() + .into_inner(); + stream.next().await.unwrap().unwrap(); + streams.push(stream); + } + assert_eq!(streams.len(), WATCHES_PER_WORKSPACE); + let scope = if platform { + openshell_core::proto::workspace_selector("default") + } else { + openshell_core::proto::all_workspaces_selector() + }; + let mut probe = watch( + &state, + reader_request( + WatchServiceRoutesRequest { + workspace_scope: Some(scope), + }, + &principal, + ), + ) + .await + .unwrap() + .into_inner(); + probe.next().await.unwrap().unwrap(); + } + } + + #[tokio::test] + async fn denied_discovery_scope_emits_a_workspace_authorization_event() { + let (state, principal, _dir) = reader_fixture(false).await; + let path = "/openshell.v1.ServiceDiscovery/GetServiceRouteSnapshot"; + let scope = Selection::Named(vec!["ungranted".into()]); + let (result, events) = crate::auth::audit::test_support::audited( + path, + authorize_selection(&state, &principal, &scope), + ) + .await; + assert_eq!(result.unwrap_err().code(), tonic::Code::PermissionDenied); + assert_eq!(events.len(), 1); + crate::auth::audit::test_support::assert_denial( + &events[0], + path, + "discovery_workspace_not_granted", + ); + } + + fn reader_request(body: T, principal: &Principal) -> Request { + let mut request = Request::new(body); + request.extensions_mut().insert(principal.clone()); + request + } + + #[tokio::test] + async fn exhausted_capacity_rejects_before_named_or_all_workspace_lookups() { + for is_watch in [false, true] { + for global in [false, true] { + for all in [false, true] { + let (state, principal, _dir) = reader_fixture(true).await; + let blockers = if global { + vec![vec![if is_watch { + state + .discovery_watches + .clone() + .try_acquire_many_owned( + u32::try_from(state.config.auth.discovery.max_watches).unwrap(), + ) + .unwrap() + } else { + state + .discovery + .unary + .clone() + .try_acquire_many_owned(u32::try_from(MAX_UNARY).unwrap()) + .unwrap() + }]] + } else { + (0..state.discovery.caller_limit(is_watch)) + .map(|_| state.discovery.admit_caller(&principal, is_watch).unwrap()) + .collect() + }; + // Any workspace lookup would fail with a storage error instead + // of the expected admission error, even for a granted reader. + state.store.close().await; + let body = GetServiceRouteSnapshotRequest { + workspace_scope: Some(if all { + openshell_core::proto::all_workspaces_selector() + } else { + openshell_core::proto::workspace_selector("default") + }), + }; + let result = if is_watch { + watch( + &state, + reader_request( + WatchServiceRoutesRequest { + workspace_scope: body.workspace_scope, + }, + &principal, + ), + ) + .await + .map(|_| ()) + } else { + get_snapshot(&state, reader_request(body, &principal)) + .await + .map(|_| ()) + }; + assert_eq!(result.unwrap_err().code(), tonic::Code::ResourceExhausted); + drop(blockers); + assert_eq!(state.discovery.unary.available_permits(), MAX_UNARY); + assert_eq!( + state.discovery_watches.available_permits(), + state.config.auth.discovery.max_watches + ); + let _callers = (0..state.discovery.caller_limit(is_watch)) + .map(|_| state.discovery.admit_caller(&principal, is_watch).unwrap()) + .collect::>(); + } + } + } + } + + #[tokio::test] + async fn preparation_deadline_bounds_final_authentication_and_releases_capacity() { + use crate::auth::authenticator::{ + AuthRejection, Authentication, Authenticator, AuthenticatorChain, + }; + struct PendingCredential(Arc); + #[async_trait::async_trait] + impl Authenticator for PendingCredential { + async fn authenticate( + &self, + _: &http::HeaderMap, + _: &str, + ) -> Result { + self.0.notify_one(); + std::future::pending().await + } + } + for is_watch in [false, true] { + let (state, _, _) = installed_fixture().await; + let principal = authed_request(()) + .extensions() + .get::() + .unwrap() + .clone(); + let started = Arc::new(tokio::sync::Notify::new()); + let recheck = BearerRecheck { + chain: AuthenticatorChain::new(vec![Arc::new(PendingCredential(started.clone()))]), + headers: http::HeaderMap::new(), + policy: None, + path: if is_watch { + "/openshell.v1.ServiceDiscovery/WatchServiceRoutes" + } else { + "/openshell.v1.ServiceDiscovery/GetServiceRouteSnapshot" + } + .into(), + }; + let server = state.clone(); + let task = tokio::spawn(async move { + if is_watch { + let mut req = authed_request(WatchServiceRoutesRequest { + workspace_scope: request().workspace_scope, + }); + req.extensions_mut().insert(recheck); + watch(&server, req).await.map(|_| ()) + } else { + let mut req = authed_request(request()); + req.extensions_mut().insert(recheck); + get_snapshot(&server, req).await.map(|_| ()) + } + }); + // Pause only after database/file work completes, so simulated time + // cannot race SQLite's blocking worker during fixture preparation. + tokio::time::timeout(Duration::from_secs(5), started.notified()) + .await + .unwrap(); + tokio::time::pause(); + tokio::time::advance(SNAPSHOT_TIMEOUT).await; + let error = tokio::time::timeout(Duration::from_secs(1), task) + .await + .unwrap() + .unwrap() + .unwrap_err(); + tokio::time::resume(); + assert_eq!(error.code(), tonic::Code::Unavailable); + assert_eq!(error.message(), "service discovery preparation timed out"); + assert_eq!(state.discovery.unary.available_permits(), MAX_UNARY); + assert_eq!( + state.discovery_watches.available_permits(), + state.config.auth.discovery.max_watches + ); + let _callers = (0..state.discovery.caller_limit(is_watch)) + .map(|_| state.discovery.admit_caller(&principal, is_watch).unwrap()) + .collect::>(); + let _workspaces = (0..if is_watch { WATCHES_PER_WORKSPACE } else { 8 }) + .map(|_| { + state + .discovery + .admit_workspaces(&["default".into()], is_watch) + .unwrap() + }) + .collect::>(); + } + } + + #[tokio::test] + async fn machine_selection_does_not_grant_workspace_or_application_permissions() { + let (state, principal, _dir) = reader_fixture(false).await; + assert!( + get_snapshot(&state, reader_request(request(), &principal)) + .await + .is_ok() + ); + assert!( + authorize_workspace( + &state.store, + &state.admin_role, + &principal, + "default", + MinWorkspaceRole::User + ) + .await + .is_err() + ); + for scope in [Selection::All, Selection::Named(vec!["not-granted".into()])] { + assert_eq!( + authorize_selection(&state, &principal, &scope) + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + } + for workspace in ["default", "team-b"] { + let selected = GetServiceRouteSnapshotRequest { + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), + }; + assert!( + get_snapshot(&state, reader_request(selected, &principal)) + .await + .is_ok() + ); + } + } + + #[tokio::test] + async fn finite_grant_supports_independent_workspace_watches_and_revocation() { + let (state, principal, dir) = reader_fixture(false).await; + let mut streams = Vec::new(); + for workspace in ["default", "team-b"] { + let mut stream = watch( + &state, + reader_request( + WatchServiceRoutesRequest { + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), + }, + &principal, + ), + ) + .await + .unwrap() + .into_inner(); + assert!(stream.next().await.unwrap().is_ok()); + streams.push(stream); + } + std::fs::write( + dir.path().join("grants.json"), + serde_json::to_vec(&serde_json::json!({ + "readers": [{"certificate_sha256": "a".repeat(64), "workspaces": ["team-b"]}] + })) + .unwrap(), + ) + .unwrap(); + assert_eq!( + tokio::time::timeout(Duration::from_secs(3), streams[0].next()) + .await + .unwrap() + .unwrap() + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + match tokio::time::timeout(Duration::from_millis(1500), streams[1].next()).await { + Ok(Some(Ok(_))) | Err(_) => {} + other => panic!("the still-granted workspace watch terminated: {other:?}"), + } + } + + #[tokio::test] + async fn machine_watch_rechecks_grants_and_certificate_expiry() { + let (state, principal, dir) = reader_fixture(true).await; + let body = WatchServiceRoutesRequest { + workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), + }; + let mut stream = watch(&state, reader_request(body, &principal)) + .await + .unwrap() + .into_inner(); + assert!(stream.next().await.unwrap().is_ok()); + std::fs::write(dir.path().join("grants.json"), r#"{"readers":[]}"#).unwrap(); + let error = tokio::time::timeout(Duration::from_secs(3), stream.next()) + .await + .unwrap() + .unwrap() + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + assert!(stream.next().await.is_none()); + let expired = Principal::Discovery(crate::auth::principal::DiscoveryPrincipal { + certificate_sha256: "a".repeat(64), + expires_at_ms: 0, + }); + assert_eq!( + get_snapshot(&state, reader_request(request(), &expired)) + .await + .unwrap_err() + .code(), + tonic::Code::Unauthenticated + ); + std::fs::write(dir.path().join("grants.json"), serde_json::to_vec(&serde_json::json!({"readers":[{"certificate_sha256":"a".repeat(64),"all_workspaces":true}]})).unwrap()).unwrap(); + let expiring = Principal::Discovery(crate::auth::principal::DiscoveryPrincipal { + certificate_sha256: "a".repeat(64), + expires_at_ms: current_time_ms() + 2000, + }); + let body = WatchServiceRoutesRequest { + workspace_scope: request().workspace_scope, + }; + let mut watch = watch(&state, reader_request(body, &expiring)) + .await + .unwrap() + .into_inner(); + assert!(watch.next().await.unwrap().is_ok()); + let error = tokio::time::timeout(Duration::from_secs(5), watch.next()) + .await + .unwrap() + .unwrap() + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::Unauthenticated); + } + + #[tokio::test] + async fn all_workspace_views_follow_creation_and_deletion_with_bounded_output() { + use openshell_core::proto::{ObjectMeta, Workspace}; + let (state, principal, _dir) = reader_fixture(true).await; + assert_eq!( + selection_workspaces(&state, &Selection::All).await.unwrap(), + vec!["default"] + ); + let mut workspace = Workspace { + metadata: Some(ObjectMeta { + id: "team-b".into(), + name: "team-b".into(), + ..Default::default() + }), + ..Default::default() + }; + state.store.put_message(&workspace).await.unwrap(); + assert_eq!( + selection_workspaces(&state, &Selection::All).await.unwrap(), + vec!["default", "team-b"] + ); + workspace.metadata.as_mut().unwrap().deletion_time = + Some(openshell_core::time::timestamp_from_millis(current_time_ms()).unwrap()); + state.store.put_message(&workspace).await.unwrap(); + assert_eq!( + selection_workspaces(&state, &Selection::All).await.unwrap(), + vec!["default"] + ); + for n in 0..crate::auth::discovery::MAX_WORKSPACES { + let name = format!("w-{n}"); + state + .store + .put_message(&Workspace { + metadata: Some(ObjectMeta { + id: name.clone(), + name, + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap(); + } + let names = selection_workspaces(&state, &Selection::All).await.unwrap(); + assert_eq!(names.len(), 65); + assert!(!names.contains(&"team-b".into())); + assert!( + selected_snapshot(&state, &principal, &Selection::All, &names) + .await + .is_ok() + ); + assert!( + selected_snapshot( + &state, + &principal, + &Selection::Named(vec!["default".into()]), + &["default".into()] + ) + .await + .is_ok() + ); + } + #[tokio::test] + async fn finite_and_platform_snapshots_combine_actual_routes_and_withdraw_deleted_workspaces() { + use openshell_core::proto::{ObjectMeta, ServiceEndpoint, Workspace}; + let (state, principal, _dir) = reader_fixture(true).await; + state + .store + .put_message(&Workspace { + metadata: Some(ObjectMeta { + id: "workspace-b".into(), + name: "team-b".into(), + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap(); + let mut sandbox = state + .store + .get_message::("sandbox") + .await + .unwrap() + .unwrap(); + let meta = sandbox.metadata.as_mut().unwrap(); + meta.id = "sandbox-b".into(); + meta.workspace = "team-b".into(); + state.store.put_message(&sandbox).await.unwrap(); + let mut endpoint = state + .store + .get_message::("endpoint") + .await + .unwrap() + .unwrap(); + endpoint.sandbox_id = "sandbox-b".into(); + let meta = endpoint.metadata.as_mut().unwrap(); + meta.id = "endpoint-b".into(); + meta.workspace = "team-b".into(); + state.store.put_message(&endpoint).await.unwrap(); + let owner = crate::supervisor_owner::SupervisorOwnerIndex::new( + state.store.clone(), + crate::supervisor_owner::OWNER_TTL, + ) + .publish( + "sandbox-b", + "session-b", + "instance-b", + 1, + "replica", + "local://replica", + ) + .await + .unwrap(); + let config = super::super::policy::build_sandbox_config_snapshot(&state, &sandbox) + .await + .unwrap(); + accept( + &state, + &owner, + &openshell_core::proto::SupervisorServiceAdvertisement { + service_domain: "services.example.com".into(), + lease_sequence: 1, + configuration_instance_id: config.configuration_instance_id, + config_revision: config.config_revision, + routes: config.service_routes, + }, + current_time_ms() + 10_000, + ) + .await + .unwrap(); + let selected = Selection::Named(vec!["default".into(), "team-b".into()]); + let both = selected_snapshot( + &state, + &principal, + &selected, + &["default".into(), "team-b".into()], + ) + .await + .unwrap(); + assert_eq!( + both.routes + .iter() + .map(|route| route.workspace.as_str()) + .collect::>(), + vec!["default", "team-b"] + ); + assert_eq!( + both, + selected_snapshot( + &state, + &principal, + &Selection::All, + &["default".into(), "team-b".into()] + ) + .await + .unwrap() + ); + state + .store + .delete("workspace", "workspace-b") + .await + .unwrap(); + assert_eq!( + selected_snapshot(&state, &principal, &Selection::All, &["default".into()]) + .await + .unwrap() + .routes + .len(), + 1 + ); + } + #[tokio::test] + async fn all_workspace_watch_ignores_new_tenant_permit_saturation() { + use openshell_core::proto::{ObjectMeta, Workspace}; + let (state, principal, dir) = reader_fixture(true).await; + let mut stream = watch( + &state, + reader_request( + WatchServiceRoutesRequest { + workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), + }, + &principal, + ), + ) + .await + .unwrap() + .into_inner(); + assert!(stream.next().await.unwrap().is_ok()); + let blockers = (0..WATCHES_PER_WORKSPACE) + .map(|n| { + state + .discovery + .admit(&user(&format!("blocker-{n}")), &["later".into()], true) + .unwrap() + }) + .collect::>(); + state + .store + .put_message(&Workspace { + metadata: Some(ObjectMeta { + id: "later".into(), + name: "later".into(), + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap(); + // An empty new workspace leaves the route revision unchanged. The + // platform watch must survive the refresh despite the tenant quota. + assert!( + tokio::time::timeout(Duration::from_millis(1500), stream.next()) + .await + .is_err() + ); + std::fs::write(dir.path().join("grants.json"), r#"{"readers":[]}"#).unwrap(); + let error = tokio::time::timeout(Duration::from_secs(3), stream.next()) + .await + .unwrap() + .unwrap() + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + drop(stream); + drop(blockers); + assert!( + state + .discovery + .admit(&principal, &["default".into(), "later".into()], true) + .is_ok() + ); + } } diff --git a/crates/openshell-server/src/grpc/workspace.rs b/crates/openshell-server/src/grpc/workspace.rs index 09e1368019..1f6c1c0960 100644 --- a/crates/openshell-server/src/grpc/workspace.rs +++ b/crates/openshell-server/src/grpc/workspace.rs @@ -65,11 +65,12 @@ fn membership_filter_subject<'a>( } } Principal::Sandbox(_) | Principal::Operator(_) => Ok(None), - Principal::Peer(_) | Principal::Supervisor(_) | Principal::SupervisorRegistration(_) => { - Err(Status::permission_denied( - "gateway peer and supervisor principals cannot list workspaces", - )) - } + Principal::Discovery(_) + | Principal::Peer(_) + | Principal::Supervisor(_) + | Principal::SupervisorRegistration(_) => Err(Status::permission_denied( + "gateway peer and supervisor principals cannot list workspaces", + )), Principal::Anonymous => Err(Status::unauthenticated("authentication required")), } } diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 77acb082c9..9b5fb187d6 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -663,6 +663,11 @@ impl ServerState { oidc_cache: Option>, credentials: credentials::CredentialRuntime, ) -> Result { + let discovery = grpc::service_discovery::DiscoveryState::new(&config.auth.discovery) + .map_err(Error::config)?; + let discovery_watches = Arc::new(tokio::sync::Semaphore::new( + config.auth.discovery.max_watches, + )); let sandbox_identity = spiffe_broker::sandbox_identity_provider(&config).map_err(Error::config)?; let replica_id = compute::lease::replica_id(); @@ -708,8 +713,8 @@ impl ServerState { gateway_ring: Arc::new(std::sync::RwLock::new(gateway_ring::GatewayRing::default())), gateway_peers: Arc::new(std::sync::RwLock::new(HashMap::new())), supervisor_spread: Arc::default(), - discovery: grpc::service_discovery::DiscoveryState::default(), - discovery_watches: Arc::new(tokio::sync::Semaphore::new(32)), + discovery, + discovery_watches, extension_mint_limiter: auth::extension_mint_limit::ExtensionMintLimiter::default(), middleware_registry: Arc::new(MiddlewareRegistry::default()), oidc_cache, @@ -4264,6 +4269,198 @@ mod tests { } } + #[tokio::test] + async fn discovery_certificates_never_gain_user_or_operator_authority_without_grants() { + for (restricted, mixed_operator) in + [(false, false), (true, false), (false, true), (true, true)] + { + use rustls::pki_types::CertificateDer; + let dir = tempdir().unwrap(); + let (ca, ca_key) = generate_test_certs_with_ca(dir.path()); + let mut params = CertificateParams::new(Vec::::new()).unwrap(); + params + .distinguished_name + .push(rcgen::DnType::CommonName, "discovery-proxy"); + params + .distinguished_name + .push(rcgen::DnType::OrganizationalUnitName, "discovery"); + if mixed_operator { + params + .distinguished_name + // A second OU with the same OID; using the named enum again + // would replace the discovery OU in rcgen's map. + .push(rcgen::DnType::CustomDnType(vec![2, 5, 4, 11]), "operator"); + } + 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_pem_key = key_pem.clone(); + let fingerprint = hex::encode(openshell_crypto::sha256(client_cert.as_ref()).unwrap()); + fs::write(dir.path().join("grants.json"),serde_json::to_vec(&serde_json::json!({"readers":[{"certificate_sha256":fingerprint,"all_workspaces":true}]})).unwrap()).unwrap(); + 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.mtls_auth.operator_enabled = mixed_operator; + inner.admin_role.clear(); + inner.config.auth.discovery_grants_file = + restricted.then(|| dir.path().join("grants.json")); + inner.config.supervisor_app_listener.enabled = true; + 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, + )); + + let tls = tonic::transport::ClientTlsConfig::new() + .domain_name("localhost") + .ca_certificate(tonic::transport::Certificate::from_pem(ca.pem())) + .identity(tonic::transport::Identity::from_pem( + client.pem(), + client_pem_key, + )); + let channel = tonic::transport::Endpoint::from_shared(format!( + "https://localhost:{}", + addr.port() + )) + .unwrap() + .tls_config(tls) + .unwrap() + .connect() + .await + .unwrap(); + let mut discovery = + openshell_core::proto::service_discovery_client::ServiceDiscoveryClient::new( + channel.clone(), + ); + let mut client = OpenShellClient::new(channel); + let request = || openshell_core::proto::GetServiceRouteSnapshotRequest { + workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), + }; + assert_eq!( + client + .get_provider_credentials( + openshell_core::proto::GetProviderCredentialsRequest { + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default" + )), + name: "provider".into(), + credential_keys: vec!["api_key".into()], + ..Default::default() + } + ) + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied, + "restricted={restricted}, mixed_operator={mixed_operator}" + ); + if !restricted { + assert_eq!( + client + .get_current_user(openshell_core::proto::GetCurrentUserRequest {}) + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + assert_eq!( + discovery + .get_service_route_snapshot(request()) + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + stop_listener(shutdown, handle).await; + continue; + } + let mut conflicting = tonic::Request::new(request()); + conflicting.metadata_mut().insert( + "authorization", + "Bearer must-not-upgrade-authority".parse().unwrap(), + ); + assert_eq!( + discovery + .get_service_route_snapshot(conflicting) + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + assert!( + discovery + .get_service_route_snapshot(request()) + .await + .is_ok() + ); + assert_eq!( + client + .get_current_user(openshell_core::proto::GetCurrentUserRequest {}) + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + let mut watch = discovery + .watch_service_routes(openshell_core::proto::WatchServiceRoutesRequest { + workspace_scope: request().workspace_scope, + }) + .await + .unwrap() + .into_inner(); + assert!(watch.message().await.unwrap().is_some()); + fs::write(dir.path().join("grants.json"), r#"{"readers":[]}"#).unwrap(); + assert_eq!( + tokio::time::timeout(Duration::from_secs(3), watch.message()) + .await + .unwrap() + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + assert_eq!( + discovery + .get_service_route_snapshot(request()) + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + 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 8d9cb9abc3..32a1785ad9 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -291,7 +291,14 @@ impl MultiplexService { where S: AsyncRead + AsyncWrite + Unpin + Send + 'static, { - let operator = if self.state.config.mtls_auth.operator_enabled { + let discovery = peer_identity + .as_ref() + .filter(|identity| crate::auth::discovery::is_certificate(identity)) + .map(|_| crate::auth::principal::DiscoveryPrincipal { + certificate_sha256: certificate_sha256.clone().unwrap_or_default(), + expires_at_ms: certificate_expires_at_ms.unwrap_or(0), + }); + let operator = if discovery.is_none() && self.state.config.mtls_auth.operator_enabled { peer_identity .as_ref() .filter(|identity| { @@ -337,10 +344,11 @@ impl MultiplexService { self.state.gateway_interceptors.clone(), Some(self.state.clone()), ); - let discovery = ServiceDiscoveryServer::new(OpenShellService::new(self.state.clone())) - .max_decoding_message_size(MAX_GRPC_DECODE_SIZE); - let discovery = GatewayInterceptorGrpcService::new( - discovery, + let discovery_service = + ServiceDiscoveryServer::new(OpenShellService::new(self.state.clone())) + .max_decoding_message_size(MAX_GRPC_DECODE_SIZE); + let discovery_service = GatewayInterceptorGrpcService::new( + discovery_service, self.state.gateway_interceptors.clone(), Some(self.state.clone()), ); @@ -349,7 +357,7 @@ impl MultiplexService { let grpc_service = AuthGrpcRouter::with_peer_identity( GrpcRouter::new(openshell, reflection) .with_sandbox_updates(sandbox_updates) - .with_discovery(discovery), + .with_discovery(discovery_service), authenticator_chain, authz_policy, self.state @@ -363,6 +371,10 @@ impl MultiplexService { ) .with_peer_certificate(certificate_sha256.clone()) .with_operator(operator) + .with_discovery( + discovery, + self.state.config.auth.discovery_grants_file.clone(), + ) .with_connection_source(source) .with_logons(self.state.logons.clone()); let mut grpc_service = @@ -870,6 +882,13 @@ fn gateway_principal_fields(principal: &Principal) -> BTreeMap { fields.insert("subject".to_string(), supervisor.identity.subject.clone()); fields.insert("token_id".to_string(), supervisor.identity.token_id.clone()); } + Principal::Discovery(reader) => { + fields.insert("kind".to_string(), "discovery".to_string()); + fields.insert( + "certificate_sha256".to_string(), + reader.certificate_sha256.clone(), + ); + } Principal::Anonymous => { fields.insert("kind".to_string(), "anonymous".to_string()); } @@ -1224,6 +1243,8 @@ pub struct AuthGrpcRouter { mtls_auth_enabled: bool, allow_unauthenticated_users: bool, operator: Option, + discovery: Option, + discovery_grants_file: Option, connection_source: Option, logons: audit::Logons, } @@ -1255,11 +1276,23 @@ impl AuthGrpcRouter { mtls_auth_enabled, allow_unauthenticated_users, operator: None, + discovery: None, + discovery_grants_file: None, connection_source: None, logons: audit::Logons::default(), } } + fn with_discovery( + mut self, + discovery: Option, + path: Option, + ) -> Self { + self.discovery = discovery; + self.discovery_grants_file = path; + self + } + fn with_operator(mut self, operator: Option) -> Self { self.operator = operator; self @@ -1322,6 +1355,8 @@ where let mtls_auth_enabled = self.mtls_auth_enabled; let allow_unauthenticated_users = self.allow_unauthenticated_users; let operator = self.operator.clone(); + let discovery = self.discovery.clone(); + let discovery_grants_file = self.discovery_grants_file.clone(); let connection_source = self.connection_source; let logons = self.logons.clone(); let peer_certificate_sha256 = self.peer_certificate_sha256.clone(); @@ -1341,7 +1376,32 @@ where return inner.ready().await?.call(req).await; } - let principal = if let Some(operator) = operator { + let principal = if let Some(reader) = discovery { + if req.headers().contains_key(http::header::AUTHORIZATION) + || !crate::auth::discovery::is_method(&path) + { + audit::emit_authorization_denial_for( + &path, + &origin(req.headers()), + &Principal::Discovery(reader), + AuthzDenial::MethodNotPermitted, + ); + return Ok(status_response(tonic::Status::permission_denied( + "discovery certificates may call only discovery methods without bearer credentials", + ))); + } + if let Err(status) = + crate::auth::discovery::grant(discovery_grants_file.as_deref(), &reader).await + { + let principal = Principal::Discovery(reader); + let status = audit::with_request(path.clone(), origin(req.headers()), async { + crate::auth::discovery::audit_failure(&principal, status) + }) + .await; + return Ok(status_response(status)); + } + Principal::Discovery(reader) + } else if let Some(operator) = operator { if req.headers().contains_key(http::header::AUTHORIZATION) { audit::emit_authentication_failure( &path, @@ -1433,6 +1493,9 @@ where Some((denial, tonic::Status::permission_denied(message))) }; let denial = match principal { + Principal::Discovery(_) if !crate::auth::discovery::is_method(&path) => { + method_denied("discovery method required") + } Principal::Operator(_) if !crate::auth::method_authz::is_operator_callable(&path) => { @@ -1470,7 +1533,8 @@ where "anonymous callers may not call authenticated methods", ))); } - Principal::Operator(_) + Principal::Discovery(_) + | Principal::Operator(_) | Principal::Sandbox(_) | Principal::Peer(_) | Principal::Supervisor(_) diff --git a/docs/how-it-works/gateways/authentication.mdx b/docs/how-it-works/gateways/authentication.mdx index bda01d5383..3e4e3b7869 100644 --- a/docs/how-it-works/gateways/authentication.mdx +++ b/docs/how-it-works/gateways/authentication.mdx @@ -558,3 +558,15 @@ Installers can also seed read-only defaults under `/etc/openshell/` (or a non-em Only `active_gateway` and `metadata.json` fall back to the system layout. mTLS bundles, OIDC tokens, edge tokens, and `last_sandbox` remain per-user state. For OIDC gateways, `metadata.json` also stores the issuer, CLI client ID, optional audience, and requested scopes. Treat `oidc_token.json` as a credential. OpenShell writes it with owner-only file permissions. + +### Discovery-only certificates + +An administrator can grant an `OU=discovery` client certificate access to route +snapshots and watches for selected workspaces or the whole platform. These +certificates cannot act as users or operators, even when ordinary mTLS user +authentication or local development access is enabled, or the grants configuration +is missing. The reserved OU takes precedence over `OU=operator`. Upgrade all +trusted gateways before issuing reader certificates; older binaries cannot enforce +this restriction. See +[discovery reader configuration](./configuration#discovery-reader-grants) for +fingerprint mappings, rotation, and revocation. diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 9366f6f69c..99e5a23fb4 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2611,14 +2611,14 @@ TLS endpoint, installation version, and expiry. Preserve the hostname as TLS SNI and HTTP authority when routing directly to the endpoint. Remove absent routes and expire cached entries even during discovery errors. An API error does not mean the workspace has no routes. Watches end after one minute; reconnect and -relist when they end. Discovery-only machine credentials are separate work. +relist when they end. Use [discovery reader grants](#discovery-reader-grants) for noninteractive route consumers. Discovery limits apply per gateway process: 1,000 installation records, 4,096 routes, and 4 MiB per snapshot, with a ten-second collection timeout. Up to four collections and 16 unary requests run concurrently. Collections wait for a free slot within the ten-second timeout; unary requests are limited to four per principal and eight per workspace. Watches are limited to 32 total, -four per principal, and 16 per workspace. Capacity and size limits return +four per principal, and 16 per workspace for explicit single-workspace queries. Finite and all-workspace queries use caller/global capacity independently of tenant-local quotas. Capacity and size limits return `RESOURCE_EXHAUSTED`; storage failures, configuration changes during collection, and timeouts return `UNAVAILABLE`; corrupt records return `INTERNAL`. Disabling the app listener returns `FAILED_PRECONDITION`. @@ -2688,3 +2688,91 @@ When service authentication is enabled, TLS gateways advertise HTTPS for gateway 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. + +### Discovery reader grants + +Configure an administrator-managed JSON file to authorize noninteractive route +readers without workspace membership or operator access: + +```toml +[openshell.gateway.auth] +discovery_grants_file = "/run/discovery/grants.json" +``` + +This requires gateway TLS and a configured client CA. Issue each reader a +client-authentication certificate from that CA with `OU=discovery`. This reserved +OU always restricts the certificate to discovery, including when the grants file +is unconfigured, removed, or invalid. It never grants user or operator authority, +even with an additional `OU=operator`. A missing mapping denies access. Map the exact +lowercase SHA-256 fingerprint of its DER leaf certificate in the grant file: + +```json +{ + "readers": [ + {"certificate_sha256": "<64 lowercase hex digits>", "workspaces": ["team-a", "team-b"]}, + {"certificate_sha256": "", "all_workspaces": true} + ] +} +``` + +The gateway validates a configured file at startup, including empty/missing paths +and JSON/schema errors. A valid empty `readers` list denies all reader identities. +Failed reloads deny access and emit rate-limited diagnostics with the file path +and error category or JSON line/column; grant contents are not logged. + +Each entry selects either a nonempty workspace set or all workspaces. Only +`GetServiceRouteSnapshot` and `WatchServiceRoutes` accept this identity. It grants +no user, application, exec, forwarding, provider, or administrative access. +Combining a discovery certificate with bearer credentials is rejected. + +Upgrade every gateway replica to a version supporting discovery-only certificates +before provisioning reader identities. Mount the same administrator-controlled +mapping on every replica. Keep +it writable only by the administrator and update it atomically. The gateway +reloads it on requests and watch refreshes. Removing a fingerprint revokes its +authority on existing connections. Grant-file reads have a two-second deadline; +watches recheck at one-second refreshes and after bounded collection. Allow up +to sixteen seconds for collection and a backpressured watch to terminate, plus +file propagation to each replica in the deployment's revocation bound. Missing or invalid files fail +closed; consumers must independently expire cached routes during errors. +Certificates are also checked against their handshake-derived expiry. + +For rotation, add the replacement fingerprint, project the new certificate/key +to the consumer, then remove the old fingerprint. The proxy reloads mounted +identity and trust files on reconnect. No certificate issuance or renewal is +performed by the gateway. + +Snapshot and watch requests reserve caller/global capacity before workspace +lookups. Setup and each watch refresh have a ten-second deadline covering +collection and final reauthorization. + +Select one workspace per snapshot or watch: + +```json +{"workspaceScope":{"workspace":"team-a"}} +``` + +For a finite grant, open one watch per granted workspace and combine the views. +Each snapshot replaces only that workspace's routes. Keep each workspace's +replacement and error state separate. Select the whole platform with `workspaceScope.allWorkspaces`; +all-workspaces discovery has no fixed workspace-count ceiling. It includes future +active workspaces and omits terminating ones, with a 4-MiB active-workspace metadata +budget and the collection deadline. A finite grant cannot request whole-platform +scope. Ordinary workspace users retain their membership checks. + +All-workspace requests use principal/global capacity independently of +per-workspace tenant quotas. Installation-record limits apply per workspace; +route and response-size limits also apply to the combined view. + +Watch admission limits apply per gateway process: + +```toml +[openshell.gateway.auth.discovery] +max_watches = 128 +max_watches_per_principal = 64 +``` + +Both values must be positive. Size the budgets for the number of consumer +replicas multiplied by their workspace subscriptions, allowing for reconnects. +Identities sharing a certificate share the per-principal budget. Unary snapshot +requests and per-workspace tenant quotas retain separate admission budgets. diff --git a/proto/README.md b/proto/README.md index 23306835bd..2c202f8b6f 100644 --- a/proto/README.md +++ b/proto/README.md @@ -54,7 +54,8 @@ identifies the service being exposed. - Accept `WorkspaceSelector.all_workspaces` only on collection-list RPCs that explicitly document and authorize cross-workspace access. The supported public collections are sandboxes, sandbox templates, providers, and - services. + services. Service-route snapshot/watch discovery also accepts this selector + with explicit platform discovery authorization. - Requests whose primary resource is a workspace use `name`, not `workspace_scope`. - Document every request that permits an omitted selector. Current exceptions diff --git a/proto/datamodel.proto b/proto/datamodel.proto index 7506360d67..bc779d39b9 100644 --- a/proto/datamodel.proto +++ b/proto/datamodel.proto @@ -11,9 +11,8 @@ import "google/protobuf/timestamp.proto"; // Selects the workspace scope for a public API request. // // Requests that operate on one workspace require a non-empty `workspace`. -// Cross-workspace list requests additionally accept `all_workspaces`. The -// containing request documents which selections it supports; an omitted -// selector is invalid for workspace-scoped operations. +// Cross-workspace requests additionally accept `all_workspaces` when documented. +// An omitted selector is invalid for workspace-scoped operations. message WorkspaceSelector { oneof selection { // One explicitly named workspace. Use `default` to select the gateway's diff --git a/proto/openshell.proto b/proto/openshell.proto index 4212445623..09a5af6e57 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -4563,8 +4563,7 @@ message SupervisorServiceAdvertisement { string service_domain = 5; } -// One explicit active workspace is required. Omitted and all-workspaces -// selectors are rejected; discovery-only machine grants are separate work. +// Select one workspace, or all active workspaces with an explicit platform grant. message GetServiceRouteSnapshotRequest { openshell.datamodel.v1.WorkspaceSelector workspace_scope = 1; } diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index c187bd9538..cca32b298a 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -2030,6 +2030,24 @@ check shared session/revocation state every five seconds with a two-second deadl and close at credential/session expiry. Session cleanup runs in background without requiring another login. +For discovery-only readers, verify the TLS client CA and an `OU=discovery` +certificate whose lowercase DER SHA-256 fingerprint appears in the +administrator-managed `openshell.gateway.auth.discovery_grants_file` JSON. +Missing mappings, duplicate fingerprints, invalid scope combinations, and expired +certificates fail closed. `OU=discovery` remains restricted even without a grants +configuration and takes precedence over `OU=operator`. Configured grants files +are validated at startup; reload failures produce rate-limited diagnostics. +Verify the projected grant file on every replica; +propagation precedes the gateway's one-second refresh and bounded collection +rechecks. Do not replace a discovery identity with an operator certificate. +Discovery requests explicitly select one workspace or all workspaces. A finite +grant authorizes separate watches for each listed workspace; consumers combine +their views. Check `openshell.gateway.auth.discovery.max_watches` (128) and +`max_watches_per_principal` (64) against the subscription and consumer-replica +counts on each gateway. All-workspaces has no 64-row ceiling, and platform +consumers do not take per-tenant permits. +Workspace users retain membership checks and cannot request platform scope. + ## Azure PostgreSQL workload identity When `database_auth = "azure-workload-identity"` is configured, verify the gateway