From 594e9fdf0c3b9ab03ecf624c5d844c85f702f5b5 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Mon, 26 Oct 2026 21:07:09 -0700 Subject: [PATCH 01/13] feat(auth): add certificate-bound discovery readers and workspace scopes Implement discovery-only certificate grants, bounded single/set/all workspace views, and live grant and certificate expiry checks. Preserve existing user authorization and reject discovery credentials on other APIs and application requests. Closes #4668 Signed-off-by: Taylor Mutch --- crates/openshell-core/src/config.rs | 3 + crates/openshell-sdk/tests/client_mock.rs | 1 + crates/openshell-server/README.md | 17 + crates/openshell-server/src/auth/audit.rs | 7 +- crates/openshell-server/src/auth/discovery.rs | 192 +++++++ crates/openshell-server/src/auth/guard.rs | 8 +- crates/openshell-server/src/auth/mod.rs | 1 + crates/openshell-server/src/auth/principal.rs | 10 + .../src/auth/service_access.rs | 9 + .../src/auth/workspace_authz.rs | 10 +- crates/openshell-server/src/cli.rs | 13 + crates/openshell-server/src/grpc/policy.rs | 5 +- crates/openshell-server/src/grpc/provider.rs | 3 +- .../src/grpc/service_discovery.rs | 521 +++++++++++++++++- crates/openshell-server/src/grpc/workspace.rs | 5 +- crates/openshell-server/src/lib.rs | 126 +++++ crates/openshell-server/src/multiplex.rs | 71 ++- docs/how-it-works/gateways/authentication.mdx | 9 + docs/how-it-works/gateways/configuration.mdx | 46 ++ proto/README.md | 4 +- proto/openshell.proto | 8 +- skills/debug-openshell-cluster/SKILL.md | 10 + 22 files changed, 1044 insertions(+), 35 deletions(-) create mode 100644 crates/openshell-server/src/auth/discovery.rs diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index 7f4c47a134..3dc0655fce 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -792,6 +792,9 @@ 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, /// 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 diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 39d2f6b01e..170063e984 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -3387,6 +3387,7 @@ async fn raw_discovery_shares_transport_and_refreshes_the_live_auth_slot() { let client = OpenShellClient::connect(config).await.unwrap(); let mut discovery = client.raw_service_discovery(); let request = proto::GetServiceRouteSnapshotRequest { + workspaces: Vec::new(), workspace_scope: Some(proto::workspace_selector("team")), }; assert_eq!( diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index c5d6bb621a..7f86beab55 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -532,3 +532,20 @@ 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, up to 64 distinct `workspaces`, or the +existing all-workspaces selector. Omission and combined selectors fail. +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. + +All-workspaces collection includes future active workspaces and omits terminating +ones, with a 64-workspace scan bound. Selected-workspace collection does not scan +unrelated workspaces. Combined snapshots retain the 4,096-route/4-MiB output bound +and ten-second collection 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..4ef160be2f 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() @@ -729,6 +731,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..974b7167e9 --- /dev/null +++ b/crates/openshell-server/src/auth/discovery.rs @@ -0,0 +1,192 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Operator-managed grants for verified discovery client certificates. + +use super::{ + identity::{Identity, IdentityProvider}, + principal::DiscoveryPrincipal, +}; +use serde::Deserialize; +use std::collections::BTreeSet; +use std::path::Path; +use tokio::io::AsyncReadExt as _; +use tonic::Status; + +pub const MAX_WORKSPACES: usize = 64; +const MAX_FILE_BYTES: usize = 256 * 1024; + +/// Certificate OU marks a restricted credential class, never an authority grant. +/// The separate operator-controlled fingerprint mapping supplies authority. +pub fn is_certificate(identity: &Identity) -> bool { + identity.provider == IdentityProvider::Mtls && identity.roles.iter().any(|r| r == "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, +} + +pub async fn grant(path: Option<&Path>, principal: &DiscoveryPrincipal) -> Result { + tokio::time::timeout( + std::time::Duration::from_secs(2), + load_grant(path, principal), + ) + .await + .map_err(|_| Status::unavailable("discovery grant read timed out"))? +} + +async fn load_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 file = tokio::fs::File::open(path) + .await + .map_err(|_| Status::unavailable("discovery grants unavailable"))?; + let mut bytes = Vec::new(); + file.take( + u64::try_from(MAX_FILE_BYTES + 1).map_err(|_| Status::internal("invalid file limit"))?, + ) + .read_to_end(&mut bytes) + .await + .map_err(|_| Status::unavailable("discovery grants unavailable"))?; + if bytes.len() > MAX_FILE_BYTES { + return Err(Status::resource_exhausted( + "discovery grants file too large", + )); + } + let grants: Grants = serde_json::from_slice(&bytes) + .map_err(|_| Status::unavailable("invalid discovery grants"))?; + if grants.readers.len() > 1024 { + return Err(Status::resource_exhausted("too many discovery grants")); + } + let mut fingerprints = BTreeSet::new(); + for reader in &grants.readers { + if reader.certificate_sha256.len() != 64 + || !reader + .certificate_sha256 + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + || !fingerprints.insert(&reader.certificate_sha256) + || reader.workspaces.len() > MAX_WORKSPACES + || reader.all_workspaces != reader.workspaces.is_empty() + { + return Err(Status::unavailable("invalid discovery grant mapping")); + } + let mut names = BTreeSet::new(); + for workspace in &reader.workspaces { + crate::grpc::workspace::validate_workspace_name(workspace) + .map_err(|_| Status::unavailable("invalid discovery workspace grant"))?; + if !names.insert(workspace) { + return Err(Status::unavailable("duplicate discovery workspace grant")); + } + } + } + grants + .readers + .into_iter() + .find(|g| g.certificate_sha256 == principal.certificate_sha256) + .ok_or_else(|| Status::permission_denied("discovery grant revoked or missing")) +} + +#[cfg(test)] +mod tests { + use super::*; + #[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..39b6b436fe 100644 --- a/crates/openshell-server/src/auth/guard.rs +++ b/crates/openshell-server/src/auth/guard.rs @@ -30,7 +30,10 @@ 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(_) => { + Principal::Discovery(_) + | Principal::Peer(_) + | Principal::Supervisor(_) + | Principal::SupervisorRegistration(_) => { Err(deny( principal, AuthzDenial::MethodNotPermitted, @@ -90,7 +93,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..0b9a95256f 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(super::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)| { diff --git a/crates/openshell-server/src/auth/workspace_authz.rs b/crates/openshell-server/src/auth/workspace_authz.rs index c8bc1e79dc..471cc6ff8f 100644 --- a/crates/openshell-server/src/auth/workspace_authz.rs +++ b/crates/openshell-server/src/auth/workspace_authz.rs @@ -207,7 +207,10 @@ pub async fn authorize_workspace( workspace, grant: AuthGrant::Sandbox, }), - Principal::Peer(_) | Principal::Supervisor(_) | Principal::SupervisorRegistration(_) => { + Principal::Discovery(_) + | Principal::Peer(_) + | Principal::Supervisor(_) + | Principal::SupervisorRegistration(_) => { Err(deny( principal, AuthzDenial::MethodNotPermitted, @@ -246,7 +249,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..c6c1221cc3 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() diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 5dcfdd41e3..0edab2dd9c 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -2794,7 +2794,10 @@ 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(_) => { + Principal::Discovery(_) + | Principal::Peer(_) + | Principal::Supervisor(_) + | Principal::SupervisorRegistration(_) => { Err(Status::permission_denied( "gateway peer and supervisor principals may not resolve sandbox configuration", )) 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..0ca847a8aa 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}; @@ -74,6 +74,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", @@ -249,6 +250,193 @@ async fn authorize( Ok(()) } +#[derive(Clone, Debug)] +enum Selection { + Named(Vec), + All, +} + +fn selection( + scope: Option<&openshell_core::proto::WorkspaceSelector>, + names: &[String], +) -> Result { + if !names.is_empty() { + if scope.is_some() || names.len() > crate::auth::discovery::MAX_WORKSPACES { + return Err(Status::invalid_argument( + "choose a workspace selector or up to 64 workspaces", + )); + } + let mut names = names.to_vec(); + for name in &names { + super::workspace::validate_workspace_name(name)?; + } + names.sort(); + if names.windows(2).any(|pair| pair[0] == pair[1]) { + return Err(Status::invalid_argument("duplicate workspace selection")); + } + return Ok(Selection::Named(names)); + } + if scope.is_some_and(|scope| { + matches!( + scope.selection, + Some(openshell_core::proto::workspace_selector::Selection::AllWorkspaces(_)) + ) + }) { + return Ok(Selection::All); + } + Ok(Selection::Named(vec![ + selected_workspace_name(scope)?.to_string(), + ])) +} + +async fn authorize_selection( + state: &ServerState, + principal: &Principal, + selection: &Selection, +) -> Result<(), Status> { + if let Principal::Discovery(reader) = principal { + let grant = crate::auth::discovery::grant( + state.config.auth.discovery_grants_file.as_deref(), + reader, + ) + .await?; + match selection { + Selection::All if !grant.all_workspaces => { + return Err(Status::permission_denied( + "all-workspaces discovery grant required", + )); + } + Selection::Named(names) + if !grant.all_workspaces + && names.iter().any(|name| !grant.workspaces.contains(name)) => + { + return Err(Status::permission_denied( + "workspace not granted for discovery", + )); + } + _ => return 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(Status::permission_denied( + "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 count = 0; + let mut bytes = 0usize; + loop { + let page = state + .store + .list_by_type_after("workspace", cursor.as_ref(), 65) + .await + .map_err(|_| Status::unavailable("workspace discovery storage unavailable"))?; + count += page.len(); + for record in &page { + bytes = bytes.saturating_add(record.payload.len()); + if count > crate::auth::discovery::MAX_WORKSPACES || bytes > MAX_BYTES { + return Err(Status::resource_exhausted( + "workspace discovery limit exceeded", + )); + } + 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() { + names.push(metadata.name); + } + } + cursor = page.last().map(ObjectCursor::from); + if page.len() < 65 { + 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( @@ -264,16 +452,18 @@ pub async fn get_snapshot( ) -> 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?; + let selection = selection( + request.get_ref().workspace_scope.as_ref(), + &request.get_ref().workspaces, + )?; + authorize_selection(state, &principal, &selection).await?; + let names = selection_workspaces(state, &selection).await?; + let _permits = state.discovery.admit(&principal, &names, false)?; + let snapshot = selected_snapshot(state, &principal, &selection, &names).await?; if let Some(recheck) = request.extensions().get::() { principal = recheck.check(&principal).await?; } - authorize(state, &principal, workspace).await?; + authorize_selection(state, &principal, &selection).await?; Ok(Response::new(GetServiceRouteSnapshotResponse { snapshot: Some(snapshot), })) @@ -285,23 +475,29 @@ 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 selection = selection( + request.get_ref().workspace_scope.as_ref(), + &request.get_ref().workspaces, + )?; + tokio::time::timeout( + SNAPSHOT_TIMEOUT, + authorize_selection(state, &principal, &selection), + ) + .await + .map_err(|_| Status::unavailable("discovery authorization timed out"))??; + let mut admitted_names = selection_workspaces(state, &selection).await?; + let shares = state.discovery.admit(&principal, &admitted_names, true)?; let recheck = request.extensions().get::().cloned(); 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?; + let initial = 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?; let mut revision = initial.revision.clone(); let (tx, rx) = tokio::sync::mpsc::channel(1); tx.try_send(Ok(WatchServiceRoutesResponse { @@ -311,7 +507,7 @@ pub async fn watch( let state = state.clone(); tokio::spawn(async move { let _permit = permit; - let _shares = shares; + 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); @@ -322,12 +518,18 @@ pub async fn watch( _ = interval.tick() => {} } let refresh = async { - authorize(&state, &principal, &workspace).await?; - let snapshot = cached_snapshot(&state, &workspace).await?; + let names = selection_workspaces(&state, &selection).await?; + if names != admitted_names { + drop(shares.take()); + shares = Some(state.discovery.admit(&principal, &names, true)?); + 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! { @@ -607,6 +809,7 @@ mod tests { fn request() -> GetServiceRouteSnapshotRequest { GetServiceRouteSnapshotRequest { + workspaces: Vec::new(), workspace_scope: Some(openshell_core::proto::workspace_selector("default")), } } @@ -632,6 +835,7 @@ mod tests { let error = watch( &state, authed_request(WatchServiceRoutesRequest { + workspaces: Vec::new(), workspace_scope: request().workspace_scope, }), ) @@ -846,6 +1050,7 @@ mod tests { let mut stream = watch( &state, authed_request(WatchServiceRoutesRequest { + workspaces: Vec::new(), workspace_scope: request().workspace_scope, }), ) @@ -911,6 +1116,7 @@ mod tests { get_snapshot( &state, authed_request(GetServiceRouteSnapshotRequest { + workspaces: Vec::new(), workspace_scope: Some(openshell_core::proto::all_workspaces_selector()) }) ) @@ -941,6 +1147,7 @@ mod tests { let error = watch( &state, authed_request(WatchServiceRoutesRequest { + workspaces: Vec::new(), workspace_scope: request().workspace_scope, }), ) @@ -965,6 +1172,7 @@ mod tests { }; state.store.put_message(&member).await.unwrap(); let mut request = authed_request(WatchServiceRoutesRequest { + workspaces: Vec::new(), workspace_scope: request().workspace_scope, }); if let Some(Principal::User(user)) = request.extensions_mut().get_mut::() { @@ -994,6 +1202,7 @@ mod tests { let mut stream = watch( &state, authed_request(WatchServiceRoutesRequest { + workspaces: Vec::new(), workspace_scope: request().workspace_scope, }), ) @@ -1417,6 +1626,7 @@ mod tests { ] { let (state, _, _) = installed_fixture().await; let mut req = authed_request(WatchServiceRoutesRequest { + workspaces: Vec::new(), workspace_scope: request().workspace_scope, }); let principal = req.extensions().get::().unwrap().clone(); @@ -1526,6 +1736,7 @@ mod tests { ); let mut stream = client .watch_service_routes(WatchServiceRoutesRequest { + workspaces: Vec::new(), workspace_scope: request().workspace_scope, }) .await @@ -1569,6 +1780,7 @@ mod tests { } let (state, _, _) = installed_fixture().await; let mut req = authed_request(WatchServiceRoutesRequest { + workspaces: Vec::new(), workspace_scope: request().workspace_scope, }); let identity = Arc::new(std::sync::Mutex::new( @@ -1592,4 +1804,273 @@ 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) + } + + 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 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 + ); + } + assert!(selection(request().workspace_scope.as_ref(), &["default".into()]).is_err()); + assert!(selection(None, &["default".into(), "default".into()]).is_err()); + let selected = GetServiceRouteSnapshotRequest { + workspaces: vec!["default".into(), "team-b".into()], + ..Default::default() + }; + assert!( + get_snapshot(&state, reader_request(selected, &principal)) + .await + .is_ok() + ); + } + + #[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()), + ..Default::default() + }; + 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 + ); + } + + #[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(); + } + assert_eq!( + selected_snapshot(&state, &principal, &Selection::All) + .await + .unwrap_err() + .code(), + tonic::Code::ResourceExhausted + ); + assert!( + selected_snapshot( + &state, + &principal, + &Selection::Named(vec!["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) + .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) + .await + .unwrap() + ); + state + .store + .delete("workspace", "workspace-b") + .await + .unwrap(); + assert_eq!( + selected_snapshot(&state, &principal, &Selection::All) + .await + .unwrap() + .routes + .len(), + 1 + ); + } } diff --git a/crates/openshell-server/src/grpc/workspace.rs b/crates/openshell-server/src/grpc/workspace.rs index 09e1368019..281809e1d3 100644 --- a/crates/openshell-server/src/grpc/workspace.rs +++ b/crates/openshell-server/src/grpc/workspace.rs @@ -65,7 +65,10 @@ fn membership_filter_subject<'a>( } } Principal::Sandbox(_) | Principal::Operator(_) => Ok(None), - Principal::Peer(_) | Principal::Supervisor(_) | Principal::SupervisorRegistration(_) => { + Principal::Discovery(_) + | Principal::Peer(_) + | Principal::Supervisor(_) + | Principal::SupervisorRegistration(_) => { Err(Status::permission_denied( "gateway peer and supervisor principals cannot list workspaces", )) diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 77acb082c9..2534b1d13e 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -4264,6 +4264,132 @@ mod tests { } } + #[tokio::test] + async fn discovery_certificate_authenticates_only_route_rpcs_over_verified_tls() { + use rustls::pki_types::CertificateDer; + 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, "discovery-proxy"); + params + .distinguished_name + .push(rcgen::DnType::OrganizationalUnitName, "discovery"); + 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()); + std::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 = false; + inner.config.auth.discovery_grants_file = Some(dir.path().join("grants.json")); + inner.config.supervisor_app_listener.enabled = false; + 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()), + ..Default::default() + }; + 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, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert!(watch.message().await.unwrap().is_some()); + std::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..fe928d3e3b 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -291,7 +291,15 @@ 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)) + .and(certificate_sha256.as_ref()) + .map(|fingerprint| crate::auth::principal::DiscoveryPrincipal { + certificate_sha256: fingerprint.clone(), + 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| { @@ -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,33 @@ 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 + { + audit::emit_authorization_denial_for( + &path, + &origin(req.headers()), + &Principal::Discovery(reader), + AuthzDenial::MethodNotPermitted, + ); + 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 +1494,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 +1534,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..e497452bf0 100644 --- a/docs/how-it-works/gateways/authentication.mdx +++ b/docs/how-it-works/gateways/authentication.mdx @@ -558,3 +558,12 @@ 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. 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..6976561b07 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2688,3 +2688,49 @@ 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 OU +restricts the certificate to discovery; it does not grant 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} + ] +} +``` + +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. diff --git a/proto/README.md b/proto/README.md index 23306835bd..8bccd383a3 100644 --- a/proto/README.md +++ b/proto/README.md @@ -54,7 +54,9 @@ 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, or a request-specific finite + `workspaces` set mutually exclusive with `workspace_scope`. - 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/openshell.proto b/proto/openshell.proto index 4212445623..22d93ac0ed 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -4563,10 +4563,12 @@ 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. +// Alternatively provide a finite set in workspaces; never combine selectors. message GetServiceRouteSnapshotRequest { openshell.datamodel.v1.WorkspaceSelector workspace_scope = 1; + // Up to 64 distinct canonical workspace references; exclusive with workspace_scope. + repeated string workspaces = 2; } message GetServiceRouteSnapshotResponse { ServiceRouteSnapshot snapshot = 1; @@ -4577,6 +4579,8 @@ message GetServiceRouteSnapshotResponse { // routes during discovery errors; errors are not empty replacements. message WatchServiceRoutesRequest { openshell.datamodel.v1.WorkspaceSelector workspace_scope = 1; + // Up to 64 distinct canonical workspace references; exclusive with workspace_scope. + repeated string workspaces = 2; } message WatchServiceRoutesResponse { ServiceRouteSnapshot snapshot = 1; diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index c187bd9538..cd1b71d49d 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -2030,6 +2030,16 @@ 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. 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. +Single, finite-set, and all-workspaces discovery require explicit selectors; +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 From 5ca0280fee3eba70830dcced423d2a304014dd21 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Tue, 3 Nov 2026 11:06:33 -0800 Subject: [PATCH 02/13] test(auth): enable app listener for discovery TLS coverage Signed-off-by: Taylor Mutch --- crates/openshell-server/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 2534b1d13e..416cedff99 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -4291,7 +4291,7 @@ mod tests { inner.config.auth.allow_unauthenticated_users = false; inner.config.mtls_auth.enabled = false; inner.config.auth.discovery_grants_file = Some(dir.path().join("grants.json")); - inner.config.supervisor_app_listener.enabled = false; + 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"), From b852b3c2affb3517b43ad4aa40e2e8d0e76935cc Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Wed, 4 Nov 2026 10:38:47 -0800 Subject: [PATCH 03/13] test(auth): use shared imports in discovery certificate coverage Signed-off-by: Taylor Mutch --- crates/openshell-server/src/lib.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 416cedff99..5e9b28b8b9 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -4269,7 +4269,7 @@ mod tests { use rustls::pki_types::CertificateDer; 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, "discovery-proxy"); @@ -4283,7 +4283,7 @@ mod tests { 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()); - std::fs::write(dir.path().join("grants.json"),serde_json::to_vec(&serde_json::json!({"readers":[{"certificate_sha256":fingerprint,"all_workspaces":true}]})).unwrap()).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; @@ -4370,7 +4370,7 @@ mod tests { .unwrap() .into_inner(); assert!(watch.message().await.unwrap().is_some()); - std::fs::write(dir.path().join("grants.json"), r#"{"readers":[]}"#).unwrap(); + fs::write(dir.path().join("grants.json"), r#"{"readers":[]}"#).unwrap(); assert_eq!( tokio::time::timeout(Duration::from_secs(3), watch.message()) .await From 9a6ff9f79ba5f108cf833d9de805ca3326883bf0 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Wed, 4 Nov 2026 14:12:53 -0800 Subject: [PATCH 04/13] test(discovery): initialize workspace list in reader-stage fixture Signed-off-by: Taylor Mutch --- crates/openshell-server/src/grpc/service_discovery.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/openshell-server/src/grpc/service_discovery.rs b/crates/openshell-server/src/grpc/service_discovery.rs index 0ca847a8aa..2f90a4c66a 100644 --- a/crates/openshell-server/src/grpc/service_discovery.rs +++ b/crates/openshell-server/src/grpc/service_discovery.rs @@ -837,6 +837,7 @@ mod tests { authed_request(WatchServiceRoutesRequest { workspaces: Vec::new(), workspace_scope: request().workspace_scope, + workspaces: Vec::new(), }), ) .await From a7ccfb84017cb36a5e966dd7e915ac143d74688d Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Mon, 9 Nov 2026 10:54:12 -0800 Subject: [PATCH 05/13] fix(discovery): enforce reader admission across workspace changes Signed-off-by: Taylor Mutch --- .../src/grpc/service_discovery.rs | 86 ++++++++++++++++--- crates/openshell-server/src/multiplex.rs | 11 +-- docs/how-it-works/gateways/configuration.mdx | 6 ++ 3 files changed, 87 insertions(+), 16 deletions(-) diff --git a/crates/openshell-server/src/grpc/service_discovery.rs b/crates/openshell-server/src/grpc/service_discovery.rs index 2f90a4c66a..8a0970bba1 100644 --- a/crates/openshell-server/src/grpc/service_discovery.rs +++ b/crates/openshell-server/src/grpc/service_discovery.rs @@ -835,7 +835,6 @@ mod tests { let error = watch( &state, authed_request(WatchServiceRoutesRequest { - workspaces: Vec::new(), workspace_scope: request().workspace_scope, workspaces: Vec::new(), }), @@ -1122,7 +1121,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::() { @@ -1959,7 +1958,7 @@ mod tests { .unwrap(); } assert_eq!( - selected_snapshot(&state, &principal, &Selection::All) + selected_snapshot(&state, &principal, &Selection::All, &[]) .await .unwrap_err() .code(), @@ -1969,7 +1968,8 @@ mod tests { selected_snapshot( &state, &principal, - &Selection::Named(vec!["default".into()]) + &Selection::Named(vec!["default".into()]), + &["default".into()] ) .await .is_ok() @@ -2044,9 +2044,14 @@ mod tests { .await .unwrap(); let selected = Selection::Named(vec!["default".into(), "team-b".into()]); - let both = selected_snapshot(&state, &principal, &selected) - .await - .unwrap(); + let both = selected_snapshot( + &state, + &principal, + &selected, + &["default".into(), "team-b".into()], + ) + .await + .unwrap(); assert_eq!( both.routes .iter() @@ -2056,9 +2061,14 @@ mod tests { ); assert_eq!( both, - selected_snapshot(&state, &principal, &Selection::All) - .await - .unwrap() + selected_snapshot( + &state, + &principal, + &Selection::All, + &["default".into(), "team-b".into()] + ) + .await + .unwrap() ); state .store @@ -2066,7 +2076,7 @@ mod tests { .await .unwrap(); assert_eq!( - selected_snapshot(&state, &principal, &Selection::All) + selected_snapshot(&state, &principal, &Selection::All, &["default".into()]) .await .unwrap() .routes @@ -2074,4 +2084,58 @@ mod tests { 1 ); } + #[tokio::test] + async fn all_workspace_watch_admits_new_workspaces_before_publishing_their_routes() { + 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()), + workspaces: Vec::new(), + }, + &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(); + let error = tokio::time::timeout(Duration::from_secs(3), stream.next()) + .await + .unwrap() + .unwrap() + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::ResourceExhausted); + assert!(stream.next().await.is_none()); + assert_eq!(state.discovery_watches.available_permits(), 32); + drop(blockers); + assert!( + state + .discovery + .admit(&principal, &["default".into(), "later".into()], true) + .is_ok() + ); + } } diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index fe928d3e3b..0f2771bb1b 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -345,10 +345,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()), ); @@ -357,7 +358,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 diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 6976561b07..3f12b4fe07 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2734,3 +2734,9 @@ 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. + +Finite and all-workspace watches reserve capacity for every selected active +workspace. When that set changes, the watch reacquires workspace capacity before +publishing the next view. A newly selected workspace at capacity returns +`RESOURCE_EXHAUSTED`; the client can reconnect. Installation-record limits apply +per workspace; route and response-size limits also apply to the combined view. From d15988857385e54ab3c0ed02a6c815534ff287ef Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Mon, 16 Nov 2026 11:43:55 -0800 Subject: [PATCH 06/13] fix(discovery): opt into certificate restrictions with grants Signed-off-by: Taylor Mutch --- crates/openshell-server/src/auth/discovery.rs | 10 +- .../src/auth/service_access.rs | 41 ++- crates/openshell-server/src/lib.rs | 254 ++++++++++-------- crates/openshell-server/src/multiplex.rs | 7 +- docs/how-it-works/gateways/configuration.mdx | 6 +- 5 files changed, 187 insertions(+), 131 deletions(-) diff --git a/crates/openshell-server/src/auth/discovery.rs b/crates/openshell-server/src/auth/discovery.rs index 974b7167e9..52ed807a20 100644 --- a/crates/openshell-server/src/auth/discovery.rs +++ b/crates/openshell-server/src/auth/discovery.rs @@ -16,10 +16,12 @@ use tonic::Status; pub const MAX_WORKSPACES: usize = 64; const MAX_FILE_BYTES: usize = 256 * 1024; -/// Certificate OU marks a restricted credential class, never an authority grant. -/// The separate operator-controlled fingerprint mapping supplies authority. -pub fn is_certificate(identity: &Identity) -> bool { - identity.provider == IdentityProvider::Mtls && identity.roles.iter().any(|r| r == "discovery") +/// Configuring grants opts into the restricted OU, never an authority grant. +/// Missing or unreadable configured files must not restore ordinary mTLS access. +pub fn is_certificate(identity: &Identity, grants_file: Option<&Path>) -> bool { + grants_file.is_some() + && identity.provider == IdentityProvider::Mtls + && identity.roles.iter().any(|r| r == "discovery") } pub fn is_method(path: &str) -> bool { diff --git a/crates/openshell-server/src/auth/service_access.rs b/crates/openshell-server/src/auth/service_access.rs index 0b9a95256f..72a52d8204 100644 --- a/crates/openshell-server/src/auth/service_access.rs +++ b/crates/openshell-server/src/auth/service_access.rs @@ -58,11 +58,12 @@ async fn authorize_with_chain( workspace: &str, chain: Option, ) -> Result { - if peer - .identity - .as_ref() - .is_some_and(super::discovery::is_certificate) - { + if peer.identity.as_ref().is_some_and(|identity| { + super::discovery::is_certificate( + identity, + state.config.auth.discovery_grants_file.as_deref(), + ) + }) { return Err(Status::permission_denied( "discovery certificates cannot access applications", )); @@ -425,6 +426,36 @@ mod tests { ); } + #[tokio::test] + async fn discovery_ou_restricts_application_access_only_when_grants_are_configured() { + 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 + .unwrap(); + 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/lib.rs b/crates/openshell-server/src/lib.rs index 5e9b28b8b9..945246d08e 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -4265,129 +4265,145 @@ mod tests { } #[tokio::test] - async fn discovery_certificate_authenticates_only_route_rpcs_over_verified_tls() { - 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"); - 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 = false; - inner.config.auth.discovery_grants_file = Some(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, + async fn discovery_certificate_restriction_requires_configured_grants_over_verified_tls() { + for restricted in [false, 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"); + 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 = !restricted; + 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 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()), - ..Default::default() - }; - 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, - ..Default::default() - }) - .await + + 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() - .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()) + .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); + if !restricted { + assert!( + client + .get_current_user(openshell_core::proto::GetCurrentUserRequest {}) + .await + .is_ok() + ); + stop_listener(shutdown, handle).await; + continue; + } + let request = || openshell_core::proto::GetServiceRouteSnapshotRequest { + workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), + ..Default::default() + }; + 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, + ..Default::default() + }) .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; + .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] diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 0f2771bb1b..3fece9d677 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -293,7 +293,12 @@ impl MultiplexService { { let discovery = peer_identity .as_ref() - .filter(|identity| crate::auth::discovery::is_certificate(identity)) + .filter(|identity| { + crate::auth::discovery::is_certificate( + identity, + self.state.config.auth.discovery_grants_file.as_deref(), + ) + }) .and(certificate_sha256.as_ref()) .map(|fingerprint| crate::auth::principal::DiscoveryPrincipal { certificate_sha256: fingerprint.clone(), diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 3f12b4fe07..7317c36108 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2700,8 +2700,10 @@ 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 OU -restricts the certificate to discovery; it does not grant access. Map the exact +client-authentication certificate from that CA with `OU=discovery`. When +`discovery_grants_file` is configured, this OU restricts the certificate to +discovery; it does not grant access. Without this setting, existing certificates +retain ordinary mTLS authentication behavior. Map the exact lowercase SHA-256 fingerprint of its DER leaf certificate in the grant file: ```json From 1e7867e96d73e2961e0847f9cb5804383f4b51c2 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Wed, 18 Nov 2026 15:43:42 -0800 Subject: [PATCH 07/13] test(discovery): refresh schema inventory after main rebase Signed-off-by: Taylor Mutch --- crates/openshell-server/src/storage_proto.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 79a63a3f8d..84886d13be 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -252,7 +252,7 @@ mod tests { // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a"; + "4b98df90311df26ec072d4fe426659137cbf4b5fb67078c91e02e321915fc7e5"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = From e1a405ea72283884cf9f2eefa8fec12ebc80a08c Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Thu, 19 Nov 2026 13:50:16 -0800 Subject: [PATCH 08/13] fix(discovery): admit callers before workspace resolution Signed-off-by: Taylor Mutch --- crates/openshell-server/README.md | 5 +- .../src/grpc/service_discovery.rs | 256 ++++++++++++++++-- docs/how-it-works/gateways/configuration.mdx | 4 + 3 files changed, 235 insertions(+), 30 deletions(-) diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index 7f86beab55..ef4848bb78 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -545,7 +545,10 @@ principals. Certificate expiry and grant removal are rechecked on active watches All-workspaces collection includes future active workspaces and omits terminating ones, with a 64-workspace scan bound. Selected-workspace collection does not scan unrelated workspaces. Combined snapshots retain the 4,096-route/4-MiB output bound -and ten-second collection deadline; each workspace scan retains its existing +and ten-second deadline covering setup, collection, and final reauthorization. +Caller/global capacity is reserved before workspace lookups. Watches retain +caller capacity while updating workspace reservations, and 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/grpc/service_discovery.rs b/crates/openshell-server/src/grpc/service_discovery.rs index 8a0970bba1..e36a78e1e1 100644 --- a/crates/openshell-server/src/grpc/service_discovery.rs +++ b/crates/openshell-server/src/grpc/service_discovery.rs @@ -106,10 +106,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" }; @@ -125,6 +124,16 @@ impl DiscoveryState { format!("{kind}:{}", principal_key(principal)?), WATCHES_PER_PRINCIPAL, )?); + 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}"), @@ -134,6 +143,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(); @@ -446,6 +467,40 @@ 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 = state.discovery.admit_workspaces(&workspaces, watch)?; + 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, @@ -456,16 +511,17 @@ pub async fn get_snapshot( request.get_ref().workspace_scope.as_ref(), &request.get_ref().workspaces, )?; - authorize_selection(state, &principal, &selection).await?; - let names = selection_workspaces(state, &selection).await?; - let _permits = state.discovery.admit(&principal, &names, false)?; - let snapshot = selected_snapshot(state, &principal, &selection, &names).await?; - if let Some(recheck) = request.extensions().get::() { - principal = recheck.check(&principal).await?; - } - authorize_selection(state, &principal, &selection).await?; + 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), })) } @@ -479,25 +535,18 @@ pub async fn watch( request.get_ref().workspace_scope.as_ref(), &request.get_ref().workspaces, )?; - tokio::time::timeout( - SNAPSHOT_TIMEOUT, - authorize_selection(state, &principal, &selection), - ) - .await - .map_err(|_| Status::unavailable("discovery authorization timed out"))??; - let mut admitted_names = selection_workspaces(state, &selection).await?; - let shares = state.discovery.admit(&principal, &admitted_names, true)?; - let recheck = request.extensions().get::().cloned(); + 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 = selected_snapshot(state, &principal, &selection, &admitted_names).await?; - if let Some(recheck) = &recheck { - principal = recheck.check(&principal).await?; - } - authorize_selection(state, &principal, &selection).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 { @@ -507,6 +556,7 @@ pub async fn watch( let state = state.clone(); tokio::spawn(async move { let _permit = permit; + let _caller_permits = caller_permits; let mut shares = Some(shares); let run = async { let mut interval = tokio::time::interval(REFRESH_INTERVAL); @@ -517,11 +567,11 @@ pub async fn watch( () = tx.closed() => return, _ = interval.tick() => {} } - let refresh = async { + let refresh = tokio::time::timeout(SNAPSHOT_TIMEOUT, async { let names = selection_workspaces(&state, &selection).await?; if names != admitted_names { drop(shares.take()); - shares = Some(state.discovery.admit(&principal, &names, true)?); + shares = Some(state.discovery.admit_workspaces(&names, true)?); admitted_names = names; } let snapshot = @@ -531,10 +581,12 @@ pub async fn watch( } 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, @@ -1840,6 +1892,152 @@ mod tests { request } + #[tokio::test] + async fn exhausted_capacity_rejects_before_finite_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(32) + .unwrap() + } else { + state + .discovery + .unary + .clone() + .try_acquire_many_owned(u32::try_from(MAX_UNARY).unwrap()) + .unwrap() + }]] + } else { + (0..WATCHES_PER_PRINCIPAL) + .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: all.then(openshell_core::proto::all_workspaces_selector), + workspaces: if all { + Vec::new() + } else { + (0..64).map(|n| format!("team-{n}")).collect() + }, + }; + let result = if is_watch { + watch( + &state, + reader_request( + WatchServiceRoutesRequest { + workspace_scope: body.workspace_scope, + workspaces: body.workspaces, + }, + &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(), 32); + let _callers = (0..WATCHES_PER_PRINCIPAL) + .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, + workspaces: Vec::new(), + }); + 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(), 32); + let _callers = (0..WATCHES_PER_PRINCIPAL) + .map(|_| { + state + .discovery + .admit(&principal, &["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; diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 7317c36108..13cb7b0d21 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2737,6 +2737,10 @@ 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. + Finite and all-workspace watches reserve capacity for every selected active workspace. When that set changes, the watch reacquires workspace capacity before publishing the next view. A newly selected workspace at capacity returns From 818c4ddecbfa0f8da759f74337b629cbdf2a02b8 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Mon, 30 Nov 2026 21:16:18 -0800 Subject: [PATCH 09/13] fix(discovery): reserve reader identities and isolate platform scope Signed-off-by: Taylor Mutch --- .../sandbox_create_lifecycle_integration.rs | 3 +- crates/openshell-core/src/proto/mod.rs | 9 + crates/openshell-sdk/src/client.rs | 4 +- .../openshell-sdk/src/provider_readiness.rs | 3 +- crates/openshell-sdk/tests/client_mock.rs | 4 +- crates/openshell-server/README.md | 22 +- crates/openshell-server/src/auth/audit.rs | 9 +- crates/openshell-server/src/auth/discovery.rs | 210 +++++++-- .../src/auth/service_access.rs | 15 +- .../src/auth/workspace_authz.rs | 32 ++ crates/openshell-server/src/cli.rs | 5 + .../src/grpc/mutation_audit.rs | 2 +- .../src/grpc/service_discovery.rs | 397 +++++++++++++----- crates/openshell-server/src/lib.rs | 70 ++- crates/openshell-server/src/multiplex.rs | 23 +- crates/openshell-server/src/storage_proto.rs | 7 +- docs/how-it-works/gateways/authentication.mdx | 5 +- docs/how-it-works/gateways/configuration.mdx | 38 +- proto/README.md | 5 +- proto/datamodel.proto | 15 +- proto/openshell.proto | 11 +- skills/debug-openshell-cluster/SKILL.md | 9 +- 22 files changed, 678 insertions(+), 220 deletions(-) diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index 8d616c69ba..66b73d6176 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -52,7 +52,8 @@ fn selected_workspace( openshell_core::proto::datamodel::v1::workspace_selector::Selection::Workspace( workspace, ) => Some(workspace), - openshell_core::proto::datamodel::v1::workspace_selector::Selection::AllWorkspaces(_) => { + openshell_core::proto::datamodel::v1::workspace_selector::Selection::AllWorkspaces(_) + | openshell_core::proto::datamodel::v1::workspace_selector::Selection::Workspaces(_) => { None } } diff --git a/crates/openshell-core/src/proto/mod.rs b/crates/openshell-core/src/proto/mod.rs index c1dd2f5c7e..01e3c55781 100644 --- a/crates/openshell-core/src/proto/mod.rs +++ b/crates/openshell-core/src/proto/mod.rs @@ -117,6 +117,15 @@ pub fn workspace_selector(workspace: impl Into) -> WorkspaceSelector { } } +/// Build an explicit finite workspace scope for service-route discovery. +pub fn workspaces_selector(workspaces: Vec) -> WorkspaceSelector { + WorkspaceSelector { + selection: Some(workspace_selector::Selection::Workspaces(WorkspaceSet { + names: workspaces, + })), + } +} + /// Build a selector for every workspace supported by a cross-workspace request. pub fn all_workspaces_selector() -> WorkspaceSelector { WorkspaceSelector { 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-sdk/src/provider_readiness.rs b/crates/openshell-sdk/src/provider_readiness.rs index 3a6f979f01..793de52c96 100644 --- a/crates/openshell-sdk/src/provider_readiness.rs +++ b/crates/openshell-sdk/src/provider_readiness.rs @@ -323,7 +323,8 @@ fn request_for_receipt( fn request_workspace(request: &GetSandboxProviderStatusRequest) -> Option<&str> { match request.workspace_scope.as_ref()?.selection.as_ref()? { workspace_selector::Selection::Workspace(workspace) => Some(workspace), - workspace_selector::Selection::AllWorkspaces(_) => None, + workspace_selector::Selection::AllWorkspaces(_) + | workspace_selector::Selection::Workspaces(_) => None, } } diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 170063e984..8f52b030d0 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -34,7 +34,8 @@ fn selected_workspace(scope: &Option) - proto::datamodel::v1::workspace_selector::Selection::Workspace(workspace) => { Some(workspace) } - proto::datamodel::v1::workspace_selector::Selection::AllWorkspaces(_) => None, + proto::datamodel::v1::workspace_selector::Selection::AllWorkspaces(_) + | proto::datamodel::v1::workspace_selector::Selection::Workspaces(_) => None, } } @@ -3387,7 +3388,6 @@ async fn raw_discovery_shares_transport_and_refreshes_the_live_auth_slot() { let client = OpenShellClient::connect(config).await.unwrap(); let mut discovery = client.raw_service_discovery(); let request = proto::GetServiceRouteSnapshotRequest { - workspaces: Vec::new(), workspace_scope: Some(proto::workspace_selector("team")), }; assert_eq!( diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index ef4848bb78..5931a6ae0b 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 @@ -533,8 +535,9 @@ 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, up to 64 distinct `workspaces`, or the -existing all-workspaces selector. Omission and combined selectors fail. +Discovery accepts an explicit workspace, a `WorkspaceSelector.workspaces` +variant containing 1–64 distinct `WorkspaceSet.names`, or the existing +all-workspaces selector. The oneof enforces exclusivity; omission fails. 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 @@ -543,12 +546,13 @@ mapping at `gateway.auth.discovery_grants_file`. They never become user/operator principals. Certificate expiry and grant removal are rechecked on active watches. All-workspaces collection includes future active workspaces and omits terminating -ones, with a 64-workspace scan bound. Selected-workspace collection does not scan -unrelated workspaces. Combined snapshots retain the 4,096-route/4-MiB output bound +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 while updating workspace reservations, and each refresh has -the same ten-second deadline. Each workspace scan retains its existing +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 4ef160be2f..f85d58b213 100644 --- a/crates/openshell-server/src/auth/audit.rs +++ b/crates/openshell-server/src/auth/audit.rs @@ -629,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, @@ -657,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", @@ -677,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))) } diff --git a/crates/openshell-server/src/auth/discovery.rs b/crates/openshell-server/src/auth/discovery.rs index 52ed807a20..5d5dfca791 100644 --- a/crates/openshell-server/src/auth/discovery.rs +++ b/crates/openshell-server/src/auth/discovery.rs @@ -1,27 +1,29 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Operator-managed grants for verified discovery client certificates. +//! Administrator-managed grants for verified discovery certificates. use super::{ identity::{Identity, IdentityProvider}, principal::DiscoveryPrincipal, }; use serde::Deserialize; -use std::collections::BTreeSet; -use std::path::Path; +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); -/// Configuring grants opts into the restricted OU, never an authority grant. -/// Missing or unreadable configured files must not restore ordinary mTLS access. -pub fn is_certificate(identity: &Identity, grants_file: Option<&Path>) -> bool { - grants_file.is_some() - && identity.provider == IdentityProvider::Mtls - && identity.roles.iter().any(|r| r == "discovery") +/// 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 { @@ -53,39 +55,48 @@ pub struct Grant { pub all_workspaces: bool, } -pub async fn grant(path: Option<&Path>, principal: &DiscoveryPrincipal) -> Result { - tokio::time::timeout( - std::time::Duration::from_secs(2), - load_grant(path, principal), - ) - .await - .map_err(|_| Status::unavailable("discovery grant read timed out"))? +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 load_grant(path: Option<&Path>, principal: &DiscoveryPrincipal) -> Result { - if principal.expires_at_ms <= crate::persistence::current_time_ms() { - return Err(Status::unauthenticated("discovery certificate expired")); +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 path = path.ok_or_else(|| Status::permission_denied("discovery grant required"))?; let file = tokio::fs::File::open(path) .await - .map_err(|_| Status::unavailable("discovery grants unavailable"))?; + .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(|_| Status::internal("invalid file limit"))?, - ) - .read_to_end(&mut bytes) - .await - .map_err(|_| Status::unavailable("discovery grants unavailable"))?; + 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(Status::resource_exhausted( - "discovery grants file too large", - )); + return Err(invalid("discovery grants exceed the 256 KiB limit")); } - let grants: Grants = serde_json::from_slice(&bytes) - .map_err(|_| Status::unavailable("invalid discovery grants"))?; + 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(Status::resource_exhausted("too many discovery grants")); + return Err(invalid("discovery grants exceed the 1024-reader limit")); } let mut fingerprints = BTreeSet::new(); for reader in &grants.readers { @@ -93,33 +104,150 @@ async fn load_grant(path: Option<&Path>, principal: &DiscoveryPrincipal) -> Resu || !reader .certificate_sha256 .bytes() - .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) - || !fingerprints.insert(&reader.certificate_sha256) - || reader.workspaces.len() > MAX_WORKSPACES - || reader.all_workspaces != reader.workspaces.is_empty() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) { - return Err(Status::unavailable("invalid discovery grant mapping")); + 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(|_| Status::unavailable("invalid discovery workspace grant"))?; + .map_err(|_| invalid("invalid workspace name in discovery grant"))?; if !names.insert(workspace) { - return Err(Status::unavailable("duplicate discovery workspace grant")); + 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(|g| g.certificate_sha256 == principal.certificate_sha256) + .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"); diff --git a/crates/openshell-server/src/auth/service_access.rs b/crates/openshell-server/src/auth/service_access.rs index 72a52d8204..553e5be613 100644 --- a/crates/openshell-server/src/auth/service_access.rs +++ b/crates/openshell-server/src/auth/service_access.rs @@ -58,12 +58,11 @@ async fn authorize_with_chain( workspace: &str, chain: Option, ) -> Result { - if peer.identity.as_ref().is_some_and(|identity| { - super::discovery::is_certificate( - identity, - state.config.auth.discovery_grants_file.as_deref(), - ) - }) { + if peer + .identity + .as_ref() + .is_some_and(crate::auth::discovery::is_certificate) + { return Err(Status::permission_denied( "discovery certificates cannot access applications", )); @@ -427,7 +426,7 @@ mod tests { } #[tokio::test] - async fn discovery_ou_restricts_application_access_only_when_grants_are_configured() { + 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; @@ -440,7 +439,7 @@ mod tests { }; authorize_with_chain(&state, &HeaderMap::new(), &peer, "default", None) .await - .unwrap(); + .expect_err("discovery identity must not fall back to an ordinary mTLS user"); let directory = tempfile::tempdir().unwrap(); Arc::get_mut(&mut state) .unwrap() diff --git a/crates/openshell-server/src/auth/workspace_authz.rs b/crates/openshell-server/src/auth/workspace_authz.rs index 471cc6ff8f..c892df34bb 100644 --- a/crates/openshell-server/src/auth/workspace_authz.rs +++ b/crates/openshell-server/src/auth/workspace_authz.rs @@ -84,6 +84,10 @@ pub async fn authorize_list_workspace_selector( .await .map(AuthorizedWorkspaceScope::Workspace) } + WorkspaceSelection::Workspaces(_) => Err(openshell_core::rpc_error::invalid_argument( + "workspace_scope", + "finite workspace selection is not supported by this request", + )), WorkspaceSelection::AllWorkspaces(_) => { require_platform_admin(admin_role, principal)?; Ok(AuthorizedWorkspaceScope::AllWorkspaces) @@ -97,6 +101,10 @@ pub async fn authorize_list_workspace_selector( pub fn selected_workspace_name(selector: Option<&WorkspaceSelector>) -> Result<&str, Status> { match selected_workspace(selector)? { WorkspaceSelection::Workspace(workspace) => Ok(workspace), + WorkspaceSelection::Workspaces(_) => Err(openshell_core::rpc_error::invalid_argument( + "workspace_scope", + "finite workspace selection is not supported by this request", + )), WorkspaceSelection::AllWorkspaces(_) => Err(openshell_core::rpc_error::invalid_argument( "workspace_scope", "all_workspaces is not supported by this request", @@ -567,6 +575,30 @@ mod tests { ); } + #[tokio::test] + async fn finite_discovery_scope_is_rejected_by_other_workspace_apis() { + let store = test_store().await; + let selector = openshell_core::proto::workspaces_selector(vec!["default".into()]); + assert_eq!( + selected_workspace_name(Some(&selector)).unwrap_err().code(), + tonic::Code::InvalidArgument + ); + let admin = user_principal("platform-admin", &["openshell-admin"]); + assert_eq!( + authorize_list_workspace_selector( + &store, + "openshell-admin", + &admin, + Some(&selector), + MinWorkspaceRole::User + ) + .await + .unwrap_err() + .code(), + tonic::Code::InvalidArgument + ); + } + #[tokio::test] async fn all_workspaces_requires_platform_admin() { let store = test_store().await; diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index c6c1221cc3..4c8605b739 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -1000,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/mutation_audit.rs b/crates/openshell-server/src/grpc/mutation_audit.rs index 3aca25687b..2e4a175db7 100644 --- a/crates/openshell-server/src/grpc/mutation_audit.rs +++ b/crates/openshell-server/src/grpc/mutation_audit.rs @@ -598,7 +598,7 @@ pub(super) fn scoped( ) -> Vec { let workspace = match selector.and_then(|selector| selector.selection.as_ref()) { Some(Selection::Workspace(name)) => Some(requested("workspace", name)), - Some(Selection::AllWorkspaces(_)) | None => None, + Some(Selection::AllWorkspaces(_) | Selection::Workspaces(_)) | None => None, }; workspace.into_iter().chain(targets).collect() } diff --git a/crates/openshell-server/src/grpc/service_discovery.rs b/crates/openshell-server/src/grpc/service_discovery.rs index e36a78e1e1..12b9f8f805 100644 --- a/crates/openshell-server/src/grpc/service_discovery.rs +++ b/crates/openshell-server/src/grpc/service_discovery.rs @@ -274,40 +274,45 @@ async fn authorize( #[derive(Clone, Debug)] enum Selection { Named(Vec), + Set(Vec), All, } fn selection( scope: Option<&openshell_core::proto::WorkspaceSelector>, - names: &[String], ) -> Result { - if !names.is_empty() { - if scope.is_some() || names.len() > crate::auth::discovery::MAX_WORKSPACES { - return Err(Status::invalid_argument( - "choose a workspace selector or up to 64 workspaces", - )); - } - let mut names = names.to_vec(); - for name in &names { - super::workspace::validate_workspace_name(name)?; - } - names.sort(); - if names.windows(2).any(|pair| pair[0] == pair[1]) { - return Err(Status::invalid_argument("duplicate workspace selection")); + use openshell_core::proto::workspace_selector::Selection as Scope; + match scope.and_then(|scope| scope.selection.as_ref()) { + Some(Scope::Workspaces(set)) => { + if set.names.is_empty() || set.names.len() > crate::auth::discovery::MAX_WORKSPACES { + return Err(Status::invalid_argument( + "select between 1 and 64 workspaces", + )); + } + let mut names = set.names.clone(); + for name in &names { + super::workspace::validate_workspace_name(name)?; + } + names.sort(); + if names.windows(2).any(|pair| pair[0] == pair[1]) { + return Err(Status::invalid_argument("duplicate workspace selection")); + } + Ok(Selection::Set(names)) } - return Ok(Selection::Named(names)); + Some(Scope::AllWorkspaces(_)) => Ok(Selection::All), + _ => Ok(Selection::Named(vec![ + selected_workspace_name(scope)?.to_string(), + ])), } - if scope.is_some_and(|scope| { - matches!( - scope.selection, - Some(openshell_core::proto::workspace_selector::Selection::AllWorkspaces(_)) - ) - }) { - return Ok(Selection::All); +} + +impl Selection { + fn tenant_scope(&self) -> Option<&[String]> { + match self { + Self::Named(names) => Some(names), + _ => None, + } } - Ok(Selection::Named(vec![ - selected_workspace_name(scope)?.to_string(), - ])) } async fn authorize_selection( @@ -316,27 +321,34 @@ async fn authorize_selection( 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?; - match selection { - Selection::All if !grant.all_workspaces => { - return Err(Status::permission_denied( - "all-workspaces discovery grant required", - )); - } - Selection::Named(names) - if !grant.all_workspaces - && names.iter().any(|name| !grant.workspaces.contains(name)) => - { - return Err(Status::permission_denied( - "workspace not granted for discovery", - )); - } - _ => return Ok(()), - } + .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) | Selection::Set(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 => { @@ -344,14 +356,16 @@ async fn authorize_selection( 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(Status::permission_denied( + 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) => { + Selection::Named(names) | Selection::Set(names) => { for name in names { authorize(state, principal, name).await?; } @@ -363,33 +377,31 @@ async fn authorize_selection( async fn active_workspaces(state: &ServerState) -> Result, Status> { let mut cursor: Option = None; let mut names = Vec::new(); - let mut count = 0; let mut bytes = 0usize; loop { let page = state .store - .list_by_type_after("workspace", cursor.as_ref(), 65) + .list_by_type_after("workspace", cursor.as_ref(), 128) .await .map_err(|_| Status::unavailable("workspace discovery storage unavailable"))?; - count += page.len(); for record in &page { - bytes = bytes.saturating_add(record.payload.len()); - if count > crate::auth::discovery::MAX_WORKSPACES || bytes > MAX_BYTES { - return Err(Status::resource_exhausted( - "workspace discovery limit exceeded", - )); - } 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() < 65 { + if page.len() < 128 { break; } } @@ -403,7 +415,7 @@ async fn selection_workspaces( ) -> Result, Status> { match selection { Selection::All => active_workspaces(state).await, - Selection::Named(names) => { + Selection::Named(names) | Selection::Set(names) => { let mut active = Vec::new(); for name in names { match super::workspace::resolve_workspace(state.store.as_ref(), name).await { @@ -485,7 +497,10 @@ async fn prepare_snapshot( tokio::time::timeout(SNAPSHOT_TIMEOUT, async { authorize_selection(state, principal, selection).await?; let workspaces = selection_workspaces(state, selection).await?; - let workspace_permits = state.discovery.admit_workspaces(&workspaces, watch)?; + 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?; @@ -507,10 +522,7 @@ pub async fn get_snapshot( ) -> Result, Status> { let mut principal = super::extract_principal(&request)?; require_enabled(state)?; - let selection = selection( - request.get_ref().workspace_scope.as_ref(), - &request.get_ref().workspaces, - )?; + let selection = selection(request.get_ref().workspace_scope.as_ref())?; let _caller_permits = state.discovery.admit_caller(&principal, false)?; let prepared = prepare_snapshot( state, @@ -531,10 +543,7 @@ pub async fn watch( ) -> Result, Status> { let mut principal = super::extract_principal(&request)?; require_enabled(state)?; - let selection = selection( - request.get_ref().workspace_scope.as_ref(), - &request.get_ref().workspaces, - )?; + let selection = selection(request.get_ref().workspace_scope.as_ref())?; let caller_permits = state.discovery.admit_caller(&principal, true)?; let permit = state .discovery_watches @@ -554,7 +563,7 @@ 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 _caller_permits = caller_permits; let mut shares = Some(shares); @@ -571,7 +580,10 @@ pub async fn watch( let names = selection_workspaces(&state, &selection).await?; if names != admitted_names { drop(shares.take()); - shares = Some(state.discovery.admit_workspaces(&names, true)?); + shares = Some(match selection.tenant_scope() { + Some(tenant) => state.discovery.admit_workspaces(tenant, true)?, + None => Vec::new(), + }); admitted_names = names; } let snapshot = @@ -609,7 +621,7 @@ pub async fn watch( } }; let _ = tokio::time::timeout(WATCH_LIFETIME, run).await; - }); + })); Ok(Response::new(ReceiverStream::new(rx))) } @@ -861,7 +873,6 @@ mod tests { fn request() -> GetServiceRouteSnapshotRequest { GetServiceRouteSnapshotRequest { - workspaces: Vec::new(), workspace_scope: Some(openshell_core::proto::workspace_selector("default")), } } @@ -888,7 +899,6 @@ mod tests { &state, authed_request(WatchServiceRoutesRequest { workspace_scope: request().workspace_scope, - workspaces: Vec::new(), }), ) .await @@ -1102,7 +1112,6 @@ mod tests { let mut stream = watch( &state, authed_request(WatchServiceRoutesRequest { - workspaces: Vec::new(), workspace_scope: request().workspace_scope, }), ) @@ -1152,7 +1161,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( @@ -1168,7 +1223,6 @@ mod tests { get_snapshot( &state, authed_request(GetServiceRouteSnapshotRequest { - workspaces: Vec::new(), workspace_scope: Some(openshell_core::proto::all_workspaces_selector()) }) ) @@ -1199,7 +1253,6 @@ mod tests { let error = watch( &state, authed_request(WatchServiceRoutesRequest { - workspaces: Vec::new(), workspace_scope: request().workspace_scope, }), ) @@ -1224,7 +1277,6 @@ mod tests { }; state.store.put_message(&member).await.unwrap(); let mut request = authed_request(WatchServiceRoutesRequest { - workspaces: Vec::new(), workspace_scope: request().workspace_scope, }); if let Some(Principal::User(user)) = request.extensions_mut().get_mut::() { @@ -1254,7 +1306,6 @@ mod tests { let mut stream = watch( &state, authed_request(WatchServiceRoutesRequest { - workspaces: Vec::new(), workspace_scope: request().workspace_scope, }), ) @@ -1678,7 +1729,6 @@ mod tests { ] { let (state, _, _) = installed_fixture().await; let mut req = authed_request(WatchServiceRoutesRequest { - workspaces: Vec::new(), workspace_scope: request().workspace_scope, }); let principal = req.extensions().get::().unwrap().clone(); @@ -1788,7 +1838,6 @@ mod tests { ); let mut stream = client .watch_service_routes(WatchServiceRoutesRequest { - workspaces: Vec::new(), workspace_scope: request().workspace_scope, }) .await @@ -1832,7 +1881,6 @@ mod tests { } let (state, _, _) = installed_fixture().await; let mut req = authed_request(WatchServiceRoutesRequest { - workspaces: Vec::new(), workspace_scope: request().workspace_scope, }); let identity = Arc::new(std::sync::Mutex::new( @@ -1886,6 +1934,121 @@ mod tests { (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(), + openshell_core::proto::workspaces_selector(names), + ] { + 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()); @@ -1922,12 +2085,13 @@ mod tests { // of the expected admission error, even for a granted reader. state.store.close().await; let body = GetServiceRouteSnapshotRequest { - workspace_scope: all.then(openshell_core::proto::all_workspaces_selector), - workspaces: if all { - Vec::new() + workspace_scope: Some(if all { + openshell_core::proto::all_workspaces_selector() } else { - (0..64).map(|n| format!("team-{n}")).collect() - }, + openshell_core::proto::workspaces_selector( + (0..64).map(|n| format!("team-{n}")).collect(), + ) + }), }; let result = if is_watch { watch( @@ -1935,7 +2099,6 @@ mod tests { reader_request( WatchServiceRoutesRequest { workspace_scope: body.workspace_scope, - workspaces: body.workspaces, }, &principal, ), @@ -2000,7 +2163,6 @@ mod tests { if is_watch { let mut req = authed_request(WatchServiceRoutesRequest { workspace_scope: request().workspace_scope, - workspaces: Vec::new(), }); req.extensions_mut().insert(recheck); watch(&server, req).await.map(|_| ()) @@ -2066,11 +2228,19 @@ mod tests { tonic::Code::PermissionDenied ); } - assert!(selection(request().workspace_scope.as_ref(), &["default".into()]).is_err()); - assert!(selection(None, &["default".into(), "default".into()]).is_err()); + assert!(selection(Some(&openshell_core::proto::workspaces_selector(vec![]))).is_err()); + assert!( + selection(Some(&openshell_core::proto::workspaces_selector(vec![ + "default".into(), + "default".into() + ]))) + .is_err() + ); let selected = GetServiceRouteSnapshotRequest { - workspaces: vec!["default".into(), "team-b".into()], - ..Default::default() + workspace_scope: Some(openshell_core::proto::workspaces_selector(vec![ + "default".into(), + "team-b".into(), + ])), }; assert!( get_snapshot(&state, reader_request(selected, &principal)) @@ -2084,7 +2254,6 @@ mod tests { let (state, principal, dir) = reader_fixture(true).await; let body = WatchServiceRoutesRequest { workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), - ..Default::default() }; let mut stream = watch(&state, reader_request(body, &principal)) .await @@ -2110,6 +2279,25 @@ mod tests { .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] @@ -2155,12 +2343,13 @@ mod tests { .await .unwrap(); } - assert_eq!( - selected_snapshot(&state, &principal, &Selection::All, &[]) + 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 - .unwrap_err() - .code(), - tonic::Code::ResourceExhausted + .is_ok() ); assert!( selected_snapshot( @@ -2283,15 +2472,14 @@ mod tests { ); } #[tokio::test] - async fn all_workspace_watch_admits_new_workspaces_before_publishing_their_routes() { + 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 (state, principal, dir) = reader_fixture(true).await; let mut stream = watch( &state, reader_request( WatchServiceRoutesRequest { workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), - workspaces: Vec::new(), }, &principal, ), @@ -2320,14 +2508,21 @@ mod tests { }) .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::ResourceExhausted); - assert!(stream.next().await.is_none()); - assert_eq!(state.discovery_watches.available_permits(), 32); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + drop(stream); drop(blockers); assert!( state diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 945246d08e..ac07413f93 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -4265,8 +4265,10 @@ mod tests { } #[tokio::test] - async fn discovery_certificate_restriction_requires_configured_grants_over_verified_tls() { - for restricted in [false, true] { + 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()); @@ -4277,6 +4279,13 @@ mod tests { 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 = @@ -4291,7 +4300,9 @@ mod tests { 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 = !restricted; + 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; @@ -4348,20 +4359,60 @@ mod tests { 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!( + assert_eq!( client .get_current_user(openshell_core::proto::GetCurrentUserRequest {}) .await - .is_ok() + .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 request = || openshell_core::proto::GetServiceRouteSnapshotRequest { - workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), - ..Default::default() - }; + 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()) @@ -4379,7 +4430,6 @@ mod tests { let mut watch = discovery .watch_service_routes(openshell_core::proto::WatchServiceRoutesRequest { workspace_scope: request().workspace_scope, - ..Default::default() }) .await .unwrap() diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 3fece9d677..32a1785ad9 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -293,15 +293,9 @@ impl MultiplexService { { let discovery = peer_identity .as_ref() - .filter(|identity| { - crate::auth::discovery::is_certificate( - identity, - self.state.config.auth.discovery_grants_file.as_deref(), - ) - }) - .and(certificate_sha256.as_ref()) - .map(|fingerprint| crate::auth::principal::DiscoveryPrincipal { - certificate_sha256: fingerprint.clone(), + .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 { @@ -1399,12 +1393,11 @@ where if let Err(status) = crate::auth::discovery::grant(discovery_grants_file.as_deref(), &reader).await { - audit::emit_authorization_denial_for( - &path, - &origin(req.headers()), - &Principal::Discovery(reader), - AuthzDenial::MethodNotPermitted, - ); + 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) diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 84886d13be..42c5cb5b1d 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -248,11 +248,12 @@ mod tests { // updates use a separate capability/service and add one classified RPC. // Discovery RPCs move to ServiceDiscovery. Application URL maps add two // public-only messages alongside main's public APIs; durable schemas - // and the public/durable overlap remain unchanged. + // and the public/durable overlap remain unchanged. WorkspaceSet adds one + // public-only message; discovery reserves its former request field 2. // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "4b98df90311df26ec072d4fe426659137cbf4b5fb67078c91e02e321915fc7e5"; + "cd37435b54fb5fdef1de1f839098aa00f3fe5a50a03314f1ff78fab83ad67d73"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = @@ -820,7 +821,7 @@ mod tests { overlap_hash.as_str(), ), ( - (369, 32), + (370, 32), (104, 23), (88, 23), PUBLIC_RPC_SCHEMA_SHA256, diff --git a/docs/how-it-works/gateways/authentication.mdx b/docs/how-it-works/gateways/authentication.mdx index e497452bf0..3e4e3b7869 100644 --- a/docs/how-it-works/gateways/authentication.mdx +++ b/docs/how-it-works/gateways/authentication.mdx @@ -564,6 +564,9 @@ For OIDC gateways, `metadata.json` also stores the issuer, CLI client ID, option 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. See +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 13cb7b0d21..8d0097576f 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`. @@ -2700,10 +2700,10 @@ 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`. When -`discovery_grants_file` is configured, this OU restricts the certificate to -discovery; it does not grant access. Without this setting, existing certificates -retain ordinary mTLS authentication behavior. Map the exact +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 @@ -2715,6 +2715,11 @@ lowercase SHA-256 fingerprint of its DER leaf certificate in the grant file: } ``` +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. @@ -2741,8 +2746,19 @@ 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. -Finite and all-workspace watches reserve capacity for every selected active -workspace. When that set changes, the watch reacquires workspace capacity before -publishing the next view. A newly selected workspace at capacity returns -`RESOURCE_EXHAUSTED`; the client can reconnect. Installation-record limits apply -per workspace; route and response-size limits also apply to the combined view. +Finite selections use the `workspace_scope` oneof, for example: + +```json +{"workspaceScope":{"workspaces":{"names":["team-a","team-b"]}}} +``` + +Select one workspace with `workspaceScope.workspace`, or the whole platform with +`workspaceScope.allWorkspaces`. A finite set accepts 1–64 distinct canonical names; +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. + +Finite and 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. diff --git a/proto/README.md b/proto/README.md index 8bccd383a3..599d256b10 100644 --- a/proto/README.md +++ b/proto/README.md @@ -55,8 +55,9 @@ identifies the service being exposed. explicitly document and authorize cross-workspace access. The supported public collections are sandboxes, sandbox templates, providers, and services. Service-route snapshot/watch discovery also accepts this selector - with explicit platform discovery authorization, or a request-specific finite - `workspaces` set mutually exclusive with `workspace_scope`. + with explicit platform discovery authorization. Discovery additionally supports + `WorkspaceSelector.workspaces`, a `WorkspaceSet` of canonical `names` (1–64). + Other requests reject finite selections. The oneof enforces exclusivity. - 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..a7b9e93d25 100644 --- a/proto/datamodel.proto +++ b/proto/datamodel.proto @@ -5,14 +5,15 @@ syntax = "proto3"; package openshell.datamodel.v1; -import "options.proto"; import "google/protobuf/timestamp.proto"; +import "options.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 +// Cross-workspace list requests additionally accept `all_workspaces`; discovery +// also accepts the finite `workspaces` variant. The containing request documents +// which selections it supports; an omitted // selector is invalid for workspace-scoped operations. message WorkspaceSelector { oneof selection { @@ -22,12 +23,20 @@ message WorkspaceSelector { // All workspaces the caller is authorized to access. Only supported by // requests that explicitly document cross-workspace behavior. AllWorkspaces all_workspaces = 2; + // A finite set of distinct canonical workspace references. Supported only + // by service-route discovery; other requests reject this variant. + WorkspaceSet workspaces = 3; } } // Marker for the all-workspaces selector variant. message AllWorkspaces {} +// Explicit finite discovery scope; gateways accept up to 64 distinct names. +message WorkspaceSet { + repeated string names = 1; +} + // Kubernetes-style metadata shared by all top-level OpenShell domain objects. // // This structure provides consistent metadata (identity, labels, annotations, diff --git a/proto/openshell.proto b/proto/openshell.proto index 22d93ac0ed..80a75d512a 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -4563,12 +4563,11 @@ message SupervisorServiceAdvertisement { string service_domain = 5; } -// Select one workspace, or all active workspaces with an explicit platform grant. -// Alternatively provide a finite set in workspaces; never combine selectors. +// Select one workspace, a finite set, or all active workspaces with an explicit platform grant. message GetServiceRouteSnapshotRequest { openshell.datamodel.v1.WorkspaceSelector workspace_scope = 1; - // Up to 64 distinct canonical workspace references; exclusive with workspace_scope. - repeated string workspaces = 2; + reserved 2; + reserved "workspaces"; } message GetServiceRouteSnapshotResponse { ServiceRouteSnapshot snapshot = 1; @@ -4579,8 +4578,8 @@ message GetServiceRouteSnapshotResponse { // routes during discovery errors; errors are not empty replacements. message WatchServiceRoutesRequest { openshell.datamodel.v1.WorkspaceSelector workspace_scope = 1; - // Up to 64 distinct canonical workspace references; exclusive with workspace_scope. - repeated string workspaces = 2; + reserved 2; + reserved "workspaces"; } message WatchServiceRoutesResponse { ServiceRouteSnapshot snapshot = 1; diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index cd1b71d49d..2502d6f339 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -2034,11 +2034,16 @@ 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. Verify the projected grant file on every replica; +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. Single, finite-set, and all-workspaces discovery require explicit selectors; -workspace users retain membership checks and cannot request platform scope. +finite sets use `workspace_scope.workspaces.names` (1–64 names). 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 From fc997e9f095b792ee9115f36cce54eb408de18af Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Fri, 4 Dec 2026 10:02:27 -0800 Subject: [PATCH 10/13] style(auth): format supervisor registration restrictions Signed-off-by: Taylor Mutch --- crates/openshell-server/src/auth/guard.rs | 12 +++++------- crates/openshell-server/src/auth/workspace_authz.rs | 12 +++++------- crates/openshell-server/src/grpc/policy.rs | 8 +++----- crates/openshell-server/src/grpc/workspace.rs | 8 +++----- 4 files changed, 16 insertions(+), 24 deletions(-) diff --git a/crates/openshell-server/src/auth/guard.rs b/crates/openshell-server/src/auth/guard.rs index 39b6b436fe..b41d5b9848 100644 --- a/crates/openshell-server/src/auth/guard.rs +++ b/crates/openshell-server/src/auth/guard.rs @@ -33,13 +33,11 @@ pub fn ensure_sandbox_scope(principal: &Principal, claimed_sandbox_id: &str) -> 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::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(()) diff --git a/crates/openshell-server/src/auth/workspace_authz.rs b/crates/openshell-server/src/auth/workspace_authz.rs index c892df34bb..01e26b2f23 100644 --- a/crates/openshell-server/src/auth/workspace_authz.rs +++ b/crates/openshell-server/src/auth/workspace_authz.rs @@ -218,13 +218,11 @@ pub async fn authorize_workspace( Principal::Discovery(_) | Principal::Peer(_) | Principal::Supervisor(_) - | Principal::SupervisorRegistration(_) => { - Err(deny( - principal, - AuthzDenial::MethodNotPermitted, - "gateway peer and supervisor principals cannot perform workspace operations", - )) - } + | Principal::SupervisorRegistration(_) => Err(deny( + principal, + AuthzDenial::MethodNotPermitted, + "gateway peer and supervisor principals cannot perform workspace operations", + )), Principal::Anonymous => Err(Status::unauthenticated("authentication required")), } } diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 0edab2dd9c..65af25a55a 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -2797,11 +2797,9 @@ async fn resolve_sandbox_by_name_for_principal( Principal::Discovery(_) | Principal::Peer(_) | Principal::Supervisor(_) - | Principal::SupervisorRegistration(_) => { - Err(Status::permission_denied( - "gateway peer and supervisor principals may not resolve sandbox configuration", - )) - } + | 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/workspace.rs b/crates/openshell-server/src/grpc/workspace.rs index 281809e1d3..1f6c1c0960 100644 --- a/crates/openshell-server/src/grpc/workspace.rs +++ b/crates/openshell-server/src/grpc/workspace.rs @@ -68,11 +68,9 @@ fn membership_filter_subject<'a>( Principal::Discovery(_) | Principal::Peer(_) | Principal::Supervisor(_) - | Principal::SupervisorRegistration(_) => { - Err(Status::permission_denied( - "gateway peer and supervisor principals cannot list workspaces", - )) - } + | Principal::SupervisorRegistration(_) => Err(Status::permission_denied( + "gateway peer and supervisor principals cannot list workspaces", + )), Principal::Anonymous => Err(Status::unauthenticated("authentication required")), } } From b2535259d8eb7f37dfd9c47067914557d3ba89b1 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Fri, 4 Dec 2026 10:36:44 -0800 Subject: [PATCH 11/13] refactor(discovery): keep workspace requests single or platform scoped Signed-off-by: Taylor Mutch --- .../sandbox_create_lifecycle_integration.rs | 3 +- crates/openshell-core/src/config.rs | 20 ++ crates/openshell-core/src/proto/mod.rs | 9 - .../openshell-sdk/src/provider_readiness.rs | 3 +- crates/openshell-sdk/tests/client_mock.rs | 3 +- crates/openshell-server/README.md | 11 +- .../src/auth/workspace_authz.rs | 32 --- .../src/grpc/mutation_audit.rs | 2 +- .../src/grpc/service_discovery.rs | 245 +++++++++++++----- crates/openshell-server/src/lib.rs | 9 +- crates/openshell-server/src/storage_proto.rs | 7 +- docs/how-it-works/gateways/configuration.mdx | 24 +- proto/README.md | 4 +- proto/datamodel.proto | 13 +- proto/openshell.proto | 6 +- skills/debug-openshell-cluster/SKILL.md | 9 +- 16 files changed, 255 insertions(+), 145 deletions(-) diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index 66b73d6176..8d616c69ba 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -52,8 +52,7 @@ fn selected_workspace( openshell_core::proto::datamodel::v1::workspace_selector::Selection::Workspace( workspace, ) => Some(workspace), - openshell_core::proto::datamodel::v1::workspace_selector::Selection::AllWorkspaces(_) - | openshell_core::proto::datamodel::v1::workspace_selector::Selection::Workspaces(_) => { + openshell_core::proto::datamodel::v1::workspace_selector::Selection::AllWorkspaces(_) => { None } } diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index 3dc0655fce..b803a35abe 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -795,6 +795,9 @@ 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 @@ -803,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-core/src/proto/mod.rs b/crates/openshell-core/src/proto/mod.rs index 01e3c55781..c1dd2f5c7e 100644 --- a/crates/openshell-core/src/proto/mod.rs +++ b/crates/openshell-core/src/proto/mod.rs @@ -117,15 +117,6 @@ pub fn workspace_selector(workspace: impl Into) -> WorkspaceSelector { } } -/// Build an explicit finite workspace scope for service-route discovery. -pub fn workspaces_selector(workspaces: Vec) -> WorkspaceSelector { - WorkspaceSelector { - selection: Some(workspace_selector::Selection::Workspaces(WorkspaceSet { - names: workspaces, - })), - } -} - /// Build a selector for every workspace supported by a cross-workspace request. pub fn all_workspaces_selector() -> WorkspaceSelector { WorkspaceSelector { diff --git a/crates/openshell-sdk/src/provider_readiness.rs b/crates/openshell-sdk/src/provider_readiness.rs index 793de52c96..3a6f979f01 100644 --- a/crates/openshell-sdk/src/provider_readiness.rs +++ b/crates/openshell-sdk/src/provider_readiness.rs @@ -323,8 +323,7 @@ fn request_for_receipt( fn request_workspace(request: &GetSandboxProviderStatusRequest) -> Option<&str> { match request.workspace_scope.as_ref()?.selection.as_ref()? { workspace_selector::Selection::Workspace(workspace) => Some(workspace), - workspace_selector::Selection::AllWorkspaces(_) - | workspace_selector::Selection::Workspaces(_) => None, + workspace_selector::Selection::AllWorkspaces(_) => None, } } diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 8f52b030d0..39d2f6b01e 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -34,8 +34,7 @@ fn selected_workspace(scope: &Option) - proto::datamodel::v1::workspace_selector::Selection::Workspace(workspace) => { Some(workspace) } - proto::datamodel::v1::workspace_selector::Selection::AllWorkspaces(_) - | proto::datamodel::v1::workspace_selector::Selection::Workspaces(_) => None, + proto::datamodel::v1::workspace_selector::Selection::AllWorkspaces(_) => None, } } diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index 5931a6ae0b..359c9e610a 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -535,9 +535,9 @@ 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, a `WorkspaceSelector.workspaces` -variant containing 1–64 distinct `WorkspaceSet.names`, or the existing -all-workspaces selector. The oneof enforces exclusivity; omission fails. +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 @@ -545,6 +545,11 @@ TLS client CA, and receive authority only through the operator-managed fingerpri 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 diff --git a/crates/openshell-server/src/auth/workspace_authz.rs b/crates/openshell-server/src/auth/workspace_authz.rs index 01e26b2f23..6a97ea84d1 100644 --- a/crates/openshell-server/src/auth/workspace_authz.rs +++ b/crates/openshell-server/src/auth/workspace_authz.rs @@ -84,10 +84,6 @@ pub async fn authorize_list_workspace_selector( .await .map(AuthorizedWorkspaceScope::Workspace) } - WorkspaceSelection::Workspaces(_) => Err(openshell_core::rpc_error::invalid_argument( - "workspace_scope", - "finite workspace selection is not supported by this request", - )), WorkspaceSelection::AllWorkspaces(_) => { require_platform_admin(admin_role, principal)?; Ok(AuthorizedWorkspaceScope::AllWorkspaces) @@ -101,10 +97,6 @@ pub async fn authorize_list_workspace_selector( pub fn selected_workspace_name(selector: Option<&WorkspaceSelector>) -> Result<&str, Status> { match selected_workspace(selector)? { WorkspaceSelection::Workspace(workspace) => Ok(workspace), - WorkspaceSelection::Workspaces(_) => Err(openshell_core::rpc_error::invalid_argument( - "workspace_scope", - "finite workspace selection is not supported by this request", - )), WorkspaceSelection::AllWorkspaces(_) => Err(openshell_core::rpc_error::invalid_argument( "workspace_scope", "all_workspaces is not supported by this request", @@ -573,30 +565,6 @@ mod tests { ); } - #[tokio::test] - async fn finite_discovery_scope_is_rejected_by_other_workspace_apis() { - let store = test_store().await; - let selector = openshell_core::proto::workspaces_selector(vec!["default".into()]); - assert_eq!( - selected_workspace_name(Some(&selector)).unwrap_err().code(), - tonic::Code::InvalidArgument - ); - let admin = user_principal("platform-admin", &["openshell-admin"]); - assert_eq!( - authorize_list_workspace_selector( - &store, - "openshell-admin", - &admin, - Some(&selector), - MinWorkspaceRole::User - ) - .await - .unwrap_err() - .code(), - tonic::Code::InvalidArgument - ); - } - #[tokio::test] async fn all_workspaces_requires_platform_admin() { let store = test_store().await; diff --git a/crates/openshell-server/src/grpc/mutation_audit.rs b/crates/openshell-server/src/grpc/mutation_audit.rs index 2e4a175db7..3aca25687b 100644 --- a/crates/openshell-server/src/grpc/mutation_audit.rs +++ b/crates/openshell-server/src/grpc/mutation_audit.rs @@ -598,7 +598,7 @@ pub(super) fn scoped( ) -> Vec { let workspace = match selector.and_then(|selector| selector.selection.as_ref()) { Some(Selection::Workspace(name)) => Some(requested("workspace", name)), - Some(Selection::AllWorkspaces(_) | Selection::Workspaces(_)) | None => None, + Some(Selection::AllWorkspaces(_)) | None => None, }; workspace.into_iter().chain(targets).collect() } diff --git a/crates/openshell-server/src/grpc/service_discovery.rs b/crates/openshell-server/src/grpc/service_discovery.rs index 12b9f8f805..b81593a5ec 100644 --- a/crates/openshell-server/src/grpc/service_discovery.rs +++ b/crates/openshell-server/src/grpc/service_discovery.rs @@ -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(), @@ -83,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, @@ -122,7 +146,7 @@ impl DiscoveryState { } permits.push(self.share( format!("{kind}:{}", principal_key(principal)?), - WATCHES_PER_PRINCIPAL, + self.caller_limit(watch), )?); Ok(permits) } @@ -274,7 +298,6 @@ async fn authorize( #[derive(Clone, Debug)] enum Selection { Named(Vec), - Set(Vec), All, } @@ -283,22 +306,6 @@ fn selection( ) -> Result { use openshell_core::proto::workspace_selector::Selection as Scope; match scope.and_then(|scope| scope.selection.as_ref()) { - Some(Scope::Workspaces(set)) => { - if set.names.is_empty() || set.names.len() > crate::auth::discovery::MAX_WORKSPACES { - return Err(Status::invalid_argument( - "select between 1 and 64 workspaces", - )); - } - let mut names = set.names.clone(); - for name in &names { - super::workspace::validate_workspace_name(name)?; - } - names.sort(); - if names.windows(2).any(|pair| pair[0] == pair[1]) { - return Err(Status::invalid_argument("duplicate workspace selection")); - } - Ok(Selection::Set(names)) - } Some(Scope::AllWorkspaces(_)) => Ok(Selection::All), _ => Ok(Selection::Named(vec![ selected_workspace_name(scope)?.to_string(), @@ -334,7 +341,7 @@ async fn authorize_selection( AuthzDenial::DiscoveryGrantRequired, "all-workspaces discovery grant required", )), - Selection::Named(names) | Selection::Set(names) if !grant.all_workspaces => names + Selection::Named(names) if !grant.all_workspaces => names .iter() .find(|name| !grant.workspaces.contains(name)) .map_or_else( @@ -365,7 +372,7 @@ async fn authorize_selection( } require_platform_admin(&state.admin_role, principal) } - Selection::Named(names) | Selection::Set(names) => { + Selection::Named(names) => { for name in names { authorize(state, principal, name).await?; } @@ -415,7 +422,7 @@ async fn selection_workspaces( ) -> Result, Status> { match selection { Selection::All => active_workspaces(state).await, - Selection::Named(names) | Selection::Set(names) => { + Selection::Named(names) => { let mut active = Vec::new(); for name in names { match super::workspace::resolve_workspace(state.store.as_ref(), name).await { @@ -871,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")), @@ -1119,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 @@ -1152,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; } }) @@ -1247,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( @@ -1297,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] @@ -1322,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] @@ -1587,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(); @@ -1755,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 @@ -1948,10 +2031,7 @@ mod tests { .code(), tonic::Code::ResourceExhausted ); - for scope in [ - openshell_core::proto::all_workspaces_selector(), - openshell_core::proto::workspaces_selector(names), - ] { + for scope in [openshell_core::proto::all_workspaces_selector()] { get_snapshot( &state, reader_request( @@ -2056,7 +2136,7 @@ mod tests { } #[tokio::test] - async fn exhausted_capacity_rejects_before_finite_or_all_workspace_lookups() { + 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] { @@ -2066,7 +2146,9 @@ mod tests { state .discovery_watches .clone() - .try_acquire_many_owned(32) + .try_acquire_many_owned( + u32::try_from(state.config.auth.discovery.max_watches).unwrap(), + ) .unwrap() } else { state @@ -2077,7 +2159,7 @@ mod tests { .unwrap() }]] } else { - (0..WATCHES_PER_PRINCIPAL) + (0..state.discovery.caller_limit(is_watch)) .map(|_| state.discovery.admit_caller(&principal, is_watch).unwrap()) .collect() }; @@ -2088,9 +2170,7 @@ mod tests { workspace_scope: Some(if all { openshell_core::proto::all_workspaces_selector() } else { - openshell_core::proto::workspaces_selector( - (0..64).map(|n| format!("team-{n}")).collect(), - ) + openshell_core::proto::workspace_selector("default") }), }; let result = if is_watch { @@ -2113,8 +2193,11 @@ mod tests { 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(), 32); - let _callers = (0..WATCHES_PER_PRINCIPAL) + 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::>(); } @@ -2188,12 +2271,18 @@ mod tests { 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(), 32); - let _callers = (0..WATCHES_PER_PRINCIPAL) + 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(&principal, &["default".into()], is_watch) + .admit_workspaces(&["default".into()], is_watch) .unwrap() }) .collect::>(); @@ -2228,25 +2317,59 @@ mod tests { tonic::Code::PermissionDenied ); } - assert!(selection(Some(&openshell_core::proto::workspaces_selector(vec![]))).is_err()); - assert!( - selection(Some(&openshell_core::proto::workspaces_selector(vec![ - "default".into(), - "default".into() - ]))) - .is_err() - ); - let selected = GetServiceRouteSnapshotRequest { - workspace_scope: Some(openshell_core::proto::workspaces_selector(vec![ - "default".into(), - "team-b".into(), - ])), - }; - assert!( - get_snapshot(&state, reader_request(selected, &principal)) + 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 - .is_ok() + .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] diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index ac07413f93..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, diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 42c5cb5b1d..79a63a3f8d 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -248,12 +248,11 @@ mod tests { // updates use a separate capability/service and add one classified RPC. // Discovery RPCs move to ServiceDiscovery. Application URL maps add two // public-only messages alongside main's public APIs; durable schemas - // and the public/durable overlap remain unchanged. WorkspaceSet adds one - // public-only message; discovery reserves its former request field 2. + // and the public/durable overlap remain unchanged. // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "cd37435b54fb5fdef1de1f839098aa00f3fe5a50a03314f1ff78fab83ad67d73"; + "edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = @@ -821,7 +820,7 @@ mod tests { overlap_hash.as_str(), ), ( - (370, 32), + (369, 32), (104, 23), (88, 23), PUBLIC_RPC_SCHEMA_SHA256, diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 8d0097576f..99e5a23fb4 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2746,19 +2746,33 @@ 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. -Finite selections use the `workspace_scope` oneof, for example: +Select one workspace per snapshot or watch: ```json -{"workspaceScope":{"workspaces":{"names":["team-a","team-b"]}}} +{"workspaceScope":{"workspace":"team-a"}} ``` -Select one workspace with `workspaceScope.workspace`, or the whole platform with -`workspaceScope.allWorkspaces`. A finite set accepts 1–64 distinct canonical names; +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. -Finite and all-workspace requests use principal/global capacity independently of +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 599d256b10..2c202f8b6f 100644 --- a/proto/README.md +++ b/proto/README.md @@ -55,9 +55,7 @@ identifies the service being exposed. explicitly document and authorize cross-workspace access. The supported public collections are sandboxes, sandbox templates, providers, and services. Service-route snapshot/watch discovery also accepts this selector - with explicit platform discovery authorization. Discovery additionally supports - `WorkspaceSelector.workspaces`, a `WorkspaceSet` of canonical `names` (1–64). - Other requests reject finite selections. The oneof enforces exclusivity. + 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 a7b9e93d25..0ec0f8834c 100644 --- a/proto/datamodel.proto +++ b/proto/datamodel.proto @@ -11,9 +11,8 @@ import "options.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`; discovery -// also accepts the finite `workspaces` variant. The containing request documents -// which selections it supports; an omitted +// Cross-workspace requests additionally accept `all_workspaces` when documented. +// An omitted // selector is invalid for workspace-scoped operations. message WorkspaceSelector { oneof selection { @@ -23,20 +22,12 @@ message WorkspaceSelector { // All workspaces the caller is authorized to access. Only supported by // requests that explicitly document cross-workspace behavior. AllWorkspaces all_workspaces = 2; - // A finite set of distinct canonical workspace references. Supported only - // by service-route discovery; other requests reject this variant. - WorkspaceSet workspaces = 3; } } // Marker for the all-workspaces selector variant. message AllWorkspaces {} -// Explicit finite discovery scope; gateways accept up to 64 distinct names. -message WorkspaceSet { - repeated string names = 1; -} - // Kubernetes-style metadata shared by all top-level OpenShell domain objects. // // This structure provides consistent metadata (identity, labels, annotations, diff --git a/proto/openshell.proto b/proto/openshell.proto index 80a75d512a..09a5af6e57 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -4563,11 +4563,9 @@ message SupervisorServiceAdvertisement { string service_domain = 5; } -// Select one workspace, a finite set, or all active workspaces with an explicit platform grant. +// Select one workspace, or all active workspaces with an explicit platform grant. message GetServiceRouteSnapshotRequest { openshell.datamodel.v1.WorkspaceSelector workspace_scope = 1; - reserved 2; - reserved "workspaces"; } message GetServiceRouteSnapshotResponse { ServiceRouteSnapshot snapshot = 1; @@ -4578,8 +4576,6 @@ message GetServiceRouteSnapshotResponse { // routes during discovery errors; errors are not empty replacements. message WatchServiceRoutesRequest { openshell.datamodel.v1.WorkspaceSelector workspace_scope = 1; - reserved 2; - reserved "workspaces"; } message WatchServiceRoutesResponse { ServiceRouteSnapshot snapshot = 1; diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 2502d6f339..cca32b298a 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -2040,9 +2040,12 @@ 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. -Single, finite-set, and all-workspaces discovery require explicit selectors; -finite sets use `workspace_scope.workspaces.names` (1–64 names). All-workspaces -has no 64-row ceiling, and platform consumers do not take per-tenant permits. +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 From f6bebdb6bde83c4ef51deab1f1d693525f229da4 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Fri, 4 Dec 2026 10:57:59 -0800 Subject: [PATCH 12/13] style(discovery): explicitly match platform workspace scope Signed-off-by: Taylor Mutch --- crates/openshell-server/src/grpc/service_discovery.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/openshell-server/src/grpc/service_discovery.rs b/crates/openshell-server/src/grpc/service_discovery.rs index b81593a5ec..1d1d95dcaa 100644 --- a/crates/openshell-server/src/grpc/service_discovery.rs +++ b/crates/openshell-server/src/grpc/service_discovery.rs @@ -317,7 +317,7 @@ impl Selection { fn tenant_scope(&self) -> Option<&[String]> { match self { Self::Named(names) => Some(names), - _ => None, + Self::All => None, } } } From 07a45f99d972c3683fb3277bacbf00f919da5e52 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Fri, 4 Dec 2026 11:27:13 -0800 Subject: [PATCH 13/13] docs(proto): minimize discovery selector comment changes Signed-off-by: Taylor Mutch --- proto/datamodel.proto | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/proto/datamodel.proto b/proto/datamodel.proto index 0ec0f8834c..bc779d39b9 100644 --- a/proto/datamodel.proto +++ b/proto/datamodel.proto @@ -5,15 +5,14 @@ syntax = "proto3"; package openshell.datamodel.v1; -import "google/protobuf/timestamp.proto"; import "options.proto"; +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 requests additionally accept `all_workspaces` when documented. -// An omitted -// selector is invalid for workspace-scoped operations. +// An omitted selector is invalid for workspace-scoped operations. message WorkspaceSelector { oneof selection { // One explicitly named workspace. Use `default` to select the gateway's