|
| 1 | +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +//! Operator-managed grants for verified discovery client certificates. |
| 5 | +
|
| 6 | +use super::{ |
| 7 | + identity::{Identity, IdentityProvider}, |
| 8 | + principal::DiscoveryPrincipal, |
| 9 | +}; |
| 10 | +use serde::Deserialize; |
| 11 | +use std::collections::BTreeSet; |
| 12 | +use std::path::Path; |
| 13 | +use tokio::io::AsyncReadExt as _; |
| 14 | +use tonic::Status; |
| 15 | + |
| 16 | +pub const MAX_WORKSPACES: usize = 64; |
| 17 | +const MAX_FILE_BYTES: usize = 256 * 1024; |
| 18 | + |
| 19 | +/// Certificate OU marks a restricted credential class, never an authority grant. |
| 20 | +/// The separate operator-controlled fingerprint mapping supplies authority. |
| 21 | +pub fn is_certificate(identity: &Identity) -> bool { |
| 22 | + identity.provider == IdentityProvider::Mtls && identity.roles.iter().any(|r| r == "discovery") |
| 23 | +} |
| 24 | + |
| 25 | +pub fn is_method(path: &str) -> bool { |
| 26 | + matches!( |
| 27 | + path, |
| 28 | + "/openshell.v1.OpenShell/GetServiceRouteSnapshot" |
| 29 | + | "/openshell.v1.OpenShell/WatchServiceRoutes" |
| 30 | + ) && super::method_authz::lookup(path).is_some_and(|entry| { |
| 31 | + entry.auth_mode == super::method_authz::AuthMode::Bearer |
| 32 | + && entry.scope.as_deref() == Some("sandbox:read") |
| 33 | + && entry.workspace_role.as_deref() == Some("user") |
| 34 | + && entry.global_role.is_none() |
| 35 | + }) |
| 36 | +} |
| 37 | + |
| 38 | +#[derive(Deserialize)] |
| 39 | +#[serde(deny_unknown_fields)] |
| 40 | +struct Grants { |
| 41 | + readers: Vec<Grant>, |
| 42 | +} |
| 43 | + |
| 44 | +#[derive(Deserialize)] |
| 45 | +#[serde(deny_unknown_fields)] |
| 46 | +pub struct Grant { |
| 47 | + pub certificate_sha256: String, |
| 48 | + #[serde(default)] |
| 49 | + pub workspaces: Vec<String>, |
| 50 | + #[serde(default)] |
| 51 | + pub all_workspaces: bool, |
| 52 | +} |
| 53 | + |
| 54 | +pub async fn grant(path: Option<&Path>, principal: &DiscoveryPrincipal) -> Result<Grant, Status> { |
| 55 | + tokio::time::timeout( |
| 56 | + std::time::Duration::from_secs(2), |
| 57 | + load_grant(path, principal), |
| 58 | + ) |
| 59 | + .await |
| 60 | + .map_err(|_| Status::unavailable("discovery grant read timed out"))? |
| 61 | +} |
| 62 | + |
| 63 | +async fn load_grant(path: Option<&Path>, principal: &DiscoveryPrincipal) -> Result<Grant, Status> { |
| 64 | + if principal.expires_at_ms <= crate::persistence::current_time_ms() { |
| 65 | + return Err(Status::unauthenticated("discovery certificate expired")); |
| 66 | + } |
| 67 | + let path = path.ok_or_else(|| Status::permission_denied("discovery grant required"))?; |
| 68 | + let file = tokio::fs::File::open(path) |
| 69 | + .await |
| 70 | + .map_err(|_| Status::unavailable("discovery grants unavailable"))?; |
| 71 | + let mut bytes = Vec::new(); |
| 72 | + file.take( |
| 73 | + u64::try_from(MAX_FILE_BYTES + 1).map_err(|_| Status::internal("invalid file limit"))?, |
| 74 | + ) |
| 75 | + .read_to_end(&mut bytes) |
| 76 | + .await |
| 77 | + .map_err(|_| Status::unavailable("discovery grants unavailable"))?; |
| 78 | + if bytes.len() > MAX_FILE_BYTES { |
| 79 | + return Err(Status::resource_exhausted( |
| 80 | + "discovery grants file too large", |
| 81 | + )); |
| 82 | + } |
| 83 | + let grants: Grants = serde_json::from_slice(&bytes) |
| 84 | + .map_err(|_| Status::unavailable("invalid discovery grants"))?; |
| 85 | + if grants.readers.len() > 1024 { |
| 86 | + return Err(Status::resource_exhausted("too many discovery grants")); |
| 87 | + } |
| 88 | + let mut fingerprints = BTreeSet::new(); |
| 89 | + for reader in &grants.readers { |
| 90 | + if reader.certificate_sha256.len() != 64 |
| 91 | + || !reader |
| 92 | + .certificate_sha256 |
| 93 | + .bytes() |
| 94 | + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) |
| 95 | + || !fingerprints.insert(&reader.certificate_sha256) |
| 96 | + || reader.workspaces.len() > MAX_WORKSPACES |
| 97 | + || reader.all_workspaces != reader.workspaces.is_empty() |
| 98 | + { |
| 99 | + return Err(Status::unavailable("invalid discovery grant mapping")); |
| 100 | + } |
| 101 | + let mut names = BTreeSet::new(); |
| 102 | + for workspace in &reader.workspaces { |
| 103 | + crate::grpc::workspace::validate_workspace_name(workspace) |
| 104 | + .map_err(|_| Status::unavailable("invalid discovery workspace grant"))?; |
| 105 | + if !names.insert(workspace) { |
| 106 | + return Err(Status::unavailable("duplicate discovery workspace grant")); |
| 107 | + } |
| 108 | + } |
| 109 | + } |
| 110 | + grants |
| 111 | + .readers |
| 112 | + .into_iter() |
| 113 | + .find(|g| g.certificate_sha256 == principal.certificate_sha256) |
| 114 | + .ok_or_else(|| Status::permission_denied("discovery grant revoked or missing")) |
| 115 | +} |
| 116 | + |
| 117 | +#[cfg(test)] |
| 118 | +mod tests { |
| 119 | + use super::*; |
| 120 | + #[tokio::test] |
| 121 | + async fn fingerprint_grants_reload_and_never_derive_authority_from_subject_roles() { |
| 122 | + let dir = tempfile::tempdir().unwrap(); |
| 123 | + let path = dir.path().join("grants.json"); |
| 124 | + let reader = DiscoveryPrincipal { |
| 125 | + certificate_sha256: "a".repeat(64), |
| 126 | + expires_at_ms: crate::persistence::current_time_ms() + 60_000, |
| 127 | + }; |
| 128 | + let write = |readers: serde_json::Value| { |
| 129 | + std::fs::write( |
| 130 | + &path, |
| 131 | + serde_json::to_vec(&serde_json::json!({"readers":readers})).unwrap(), |
| 132 | + ) |
| 133 | + .unwrap(); |
| 134 | + }; |
| 135 | + write( |
| 136 | + serde_json::json!([{"certificate_sha256":reader.certificate_sha256,"workspaces":["default"]}]), |
| 137 | + ); |
| 138 | + assert_eq!( |
| 139 | + grant(Some(&path), &reader).await.unwrap().workspaces, |
| 140 | + vec!["default"] |
| 141 | + ); |
| 142 | + let unrelated = DiscoveryPrincipal { |
| 143 | + certificate_sha256: "b".repeat(64), |
| 144 | + ..reader.clone() |
| 145 | + }; |
| 146 | + assert_eq!( |
| 147 | + grant(Some(&path), &unrelated).await.err().unwrap().code(), |
| 148 | + tonic::Code::PermissionDenied |
| 149 | + ); |
| 150 | + write(serde_json::json!([])); |
| 151 | + assert_eq!( |
| 152 | + grant(Some(&path), &reader).await.err().unwrap().code(), |
| 153 | + tonic::Code::PermissionDenied |
| 154 | + ); |
| 155 | + write( |
| 156 | + serde_json::json!([{"certificate_sha256":reader.certificate_sha256,"all_workspaces":true,"workspaces":["default"]}]), |
| 157 | + ); |
| 158 | + assert_eq!( |
| 159 | + grant(Some(&path), &reader).await.err().unwrap().code(), |
| 160 | + tonic::Code::Unavailable |
| 161 | + ); |
| 162 | + assert_eq!( |
| 163 | + grant( |
| 164 | + Some(&path), |
| 165 | + &DiscoveryPrincipal { |
| 166 | + expires_at_ms: 0, |
| 167 | + ..reader |
| 168 | + } |
| 169 | + ) |
| 170 | + .await |
| 171 | + .err() |
| 172 | + .unwrap() |
| 173 | + .code(), |
| 174 | + tonic::Code::Unauthenticated |
| 175 | + ); |
| 176 | + } |
| 177 | + #[test] |
| 178 | + fn every_other_rpc_is_denied_including_unclassified_methods() { |
| 179 | + for path in super::super::method_authz::all_paths() { |
| 180 | + assert_eq!( |
| 181 | + is_method(path), |
| 182 | + matches!( |
| 183 | + path, |
| 184 | + "/openshell.v1.OpenShell/GetServiceRouteSnapshot" |
| 185 | + | "/openshell.v1.OpenShell/WatchServiceRoutes" |
| 186 | + ), |
| 187 | + "{path}" |
| 188 | + ); |
| 189 | + } |
| 190 | + assert!(!is_method("/openshell.v1.OpenShell/FutureReadMethod")); |
| 191 | + } |
| 192 | +} |
0 commit comments