Repository navigation
feat(auth): add discovery-only readers and workspace scopes #4964
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: feat/4722-gateway-service-auth/TaylorMutch
Are you sure you want to change the base?
Changes from all commits
a6bdebc
5372e70
9df02f4
a5ab9a0
1e4e4ec
16d02a1
957d54f
5c63aba
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,194 @@ | ||
| // 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; | ||
|
|
||
| /// 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 { | ||
| 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<Grant>, | ||
| } | ||
|
|
||
| #[derive(Deserialize)] | ||
| #[serde(deny_unknown_fields)] | ||
| pub struct Grant { | ||
| pub certificate_sha256: String, | ||
| #[serde(default)] | ||
| pub workspaces: Vec<String>, | ||
| #[serde(default)] | ||
| pub all_workspaces: bool, | ||
| } | ||
|
|
||
| pub async fn grant(path: Option<&Path>, principal: &DiscoveryPrincipal) -> Result<Grant, Status> { | ||
| 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<Grant, Status> { | ||
| 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"))?; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A broken grants file is invisible to operators, and several boundary cases have no tests. Operator visibility:
Tests missing at the gRPC boundary:
Also, |
||
| 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")); | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
OU=discoverycertificates fall back to full mTLS user authority wheneverdiscovery_grants_fileis unset.This happens when an operator removes the key to turn discovery off, when one replica is missing it, or after a rollback. The reader certificate then becomes an ordinary mTLS user. On an mTLS-only gateway with an empty
admin_role,authorize_workspacetreats every user as platform admin, so a route reader can create sandboxes, exec, and manage providers. Nothing signals the change.authentication.mdxalso says these certificates "cannot act as users or operators, even when ordinary mTLS user authentication … is enabled". That holds only while the grants file is configured.Suggested fix: always classify
OU=discoveryfrom the client CA as a discovery principal, and deny it when no grants file is configured, so it fails closed. If the opt-in behavior is intentional for compatibility, fix the authentication doc and warn against issuing discovery certificates from a CA that pre-upgrade or unconfigured gateways trust withmtls_auth.enabled.