From 292c633f39d31956109da07eeafa6133d5375dbd Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Mon, 30 Nov 2026 21:59:44 +0000 Subject: [PATCH 01/10] feat(server): add descriptor-guided protobuf wire scanner Implement step 1 of RFC 0027. The scanner walks raw protobuf bytes against the compiled public and storage descriptors before prost decodes them, reporting unknown tags, reserved tags, and unrecognized enum values with dotted field paths. It bounds nesting at 32 levels and stops after 16 violations, never echoes field contents, and redacts enum values on fields marked secret. Rejections map to INVALID_ARGUMENT with ErrorInfo reason UNKNOWN_PROTOBUF_FIELD and BadRequest field violations. Add helpers that extract, scan, and splice raw Sandbox.spec.policy bytes so read-modify-writes on an older gateway can preserve policy fields a newer gateway wrote. Ingress and persistence callers follow in later steps. Refs #6097 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Mrunal Patel --- crates/openshell-core/src/rpc_error.rs | 4 + crates/openshell-server/src/lib.rs | 1 + .../src/wire_validation/mod.rs | 527 ++++++++++++++++++ .../src/wire_validation/sandbox_policy.rs | 327 +++++++++++ .../src/wire_validation/tests.rs | 417 ++++++++++++++ 5 files changed, 1276 insertions(+) create mode 100644 crates/openshell-server/src/wire_validation/mod.rs create mode 100644 crates/openshell-server/src/wire_validation/sandbox_policy.rs create mode 100644 crates/openshell-server/src/wire_validation/tests.rs diff --git a/crates/openshell-core/src/rpc_error.rs b/crates/openshell-core/src/rpc_error.rs index 5c4b2ab602..d663123ff0 100644 --- a/crates/openshell-core/src/rpc_error.rs +++ b/crates/openshell-core/src/rpc_error.rs @@ -16,6 +16,10 @@ pub use tonic_types::{ErrorDetails, StatusExt}; /// Domain of gateway-owned machine-readable error reasons. pub const ERROR_DOMAIN: &str = "openshell.nvidia.com"; +/// Reason reported when a request carries protobuf fields or enum values the +/// gateway does not know (RFC 0027). +pub const UNKNOWN_PROTOBUF_FIELD: &str = "UNKNOWN_PROTOBUF_FIELD"; + /// Reason reported when a request lost the mutation lock budget. pub const MUTATION_LOCK_TIMEOUT: &str = "MUTATION_LOCK_TIMEOUT"; diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 48140e872d..c1c3893fe8 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -65,6 +65,7 @@ pub(crate) mod tls_test_utils; pub mod tracing_bus; mod tracing_setup; mod watch_cursor; +mod wire_validation; mod ws_tunnel; use axum::Router; diff --git a/crates/openshell-server/src/wire_validation/mod.rs b/crates/openshell-server/src/wire_validation/mod.rs new file mode 100644 index 0000000000..cf5cb901ff --- /dev/null +++ b/crates/openshell-server/src/wire_validation/mod.rs @@ -0,0 +1,527 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Descriptor-guided protobuf wire validation (RFC 0027). +//! +//! `prost` silently discards unknown field tags and decodes unknown enum +//! integers as raw `i32` values. Under version skew that drops restrictions a +//! newer client or gateway wrote. This module walks raw protobuf bytes against +//! the compiled descriptors *before* `prost` decodes them and reports every +//! unknown tag, reserved tag, or unrecognized enum value. +//! +//! The walk allocates nothing per field: `string` and `bytes` payloads are +//! skipped by length, and only embedded messages are descended into. +//! `google.protobuf.Struct`, `Value`, and `ListValue` need no special case: +//! their caller-authored keys are map keys, so only the wrapper tags are +//! checked. + +// Ingress and persistence callers land in follow-up changes (RFC 0027 +// implementation steps 2 and 3). +#![allow(dead_code)] + +pub mod sandbox_policy; + +use std::collections::HashMap; +use std::fmt; +use std::sync::LazyLock; + +use openshell_core::rpc_error::{self, ErrorDetails, StatusExt}; +use prost_reflect::{ + DescriptorPool, ExtensionDescriptor, FieldDescriptor, Kind, MessageDescriptor, +}; +use tonic::{Code, Status}; + +/// Maximum embedded-message nesting below the root message. +pub const MAX_DEPTH: usize = 32; + +/// Violations collected before the scan stops. +pub const MAX_VIOLATIONS: usize = 16; + +/// Reserved tags that stored policies written before 0.1.0 may still carry. +/// +/// `NetworkBinary` tag 2 held `advisor_proposed`; `decode_stored_policy` +/// migrates it. Pass this to [`ScanOptions::allowed_reserved`] only on stored +/// policy loaders, never at ingress. +pub const LEGACY_STORED_POLICY_RESERVED: &[(&str, u32)] = + &[("openshell.sandbox.v1.NetworkBinary", 2)]; + +const SECRET_EXTENSION: &str = "openshell.options.v1.secret"; +const MAX_FIELD_NUMBER: u64 = (1 << 29) - 1; + +static DESCRIPTORS: LazyLock = LazyLock::new(|| { + let mut pool = DescriptorPool::decode(openshell_core::FILE_DESCRIPTOR_SET) + .expect("the embedded public protobuf descriptor set must be valid"); + pool.decode_file_descriptor_set(crate::storage_proto::STORAGE_FILE_DESCRIPTOR_SET) + .expect("the embedded storage protobuf descriptor set must be valid"); + pool +}); + +static SECRET: LazyLock> = + LazyLock::new(|| DESCRIPTORS.get_extension_by_name(SECRET_EXTENSION)); + +/// Look up a public or storage message descriptor by full name. +pub fn message_descriptor(full_name: &str) -> Option { + DESCRIPTORS.get_message_by_name(full_name) +} + +/// What the scanner found wrong with one field. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ViolationKind { + /// A field number the message does not declare. + UnknownField { tag: u32 }, + /// A field number the message reserves. + ReservedField { tag: u32 }, + /// An enum integer the enum does not declare. `value` is `None` on + /// fields marked `(openshell.options.v1.secret)`. + UnknownEnumValue { value: Option }, +} + +/// One rejected field, addressed by its dotted path from the root message. +/// +/// Repeated message fields carry their wire occurrence index (`rules[2]`) and +/// map values carry `[*]`, so the path never echoes a caller-authored key. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FieldViolation { + pub path: String, + pub kind: ViolationKind, +} + +impl FieldViolation { + /// `google.rpc.BadRequest.FieldViolation.field`: `#` for + /// unknown or reserved tags and `` for enum values. + pub fn field(&self) -> String { + match self.kind { + ViolationKind::UnknownField { tag } | ViolationKind::ReservedField { tag } => { + format!("{}#{tag}", self.path) + } + ViolationKind::UnknownEnumValue { .. } => self.path.clone(), + } + } + + /// Human-readable description that never echoes field contents. + pub fn description(&self) -> String { + match self.kind { + ViolationKind::UnknownField { tag } => format!("unknown field {tag}"), + ViolationKind::ReservedField { tag } => format!("reserved field {tag}"), + ViolationKind::UnknownEnumValue { value: Some(value) } => { + format!("unrecognized enum value {value}") + } + ViolationKind::UnknownEnumValue { value: None } => "unrecognized enum value".into(), + } + } +} + +/// Why a protobuf payload failed wire validation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WireRejection { + /// The bytes are not a well-formed encoding of the message. + Malformed(&'static str), + /// Embedded messages nest deeper than [`MAX_DEPTH`]. + TooDeep, + /// Fields or enum values this build does not know. + Violations { + violations: Vec, + /// More violations followed the first [`MAX_VIOLATIONS`]. + truncated: bool, + }, +} + +impl WireRejection { + /// Ingress status for a rejected request frame. + /// + /// Unknown fields map to `INVALID_ARGUMENT` with `ErrorInfo` reason + /// `UNKNOWN_PROTOBUF_FIELD` and one `BadRequest` violation per field. + pub fn into_status(self) -> Status { + match self { + Self::Malformed(_) | Self::TooDeep => Status::invalid_argument(self.to_string()), + Self::Violations { violations, .. } => { + let mut details = ErrorDetails::with_error_info( + rpc_error::UNKNOWN_PROTOBUF_FIELD, + rpc_error::ERROR_DOMAIN, + HashMap::from([( + "gateway_version".to_string(), + openshell_core::VERSION.to_string(), + )]), + ); + for violation in &violations { + details.add_bad_request_violation(violation.field(), violation.description()); + } + Status::with_error_details( + Code::InvalidArgument, + format!( + "request uses protobuf fields or enum values unknown to gateway {}; \ + upgrade the gateway or omit the newer fields", + openshell_core::VERSION + ), + details, + ) + } + } + } +} + +impl fmt::Display for WireRejection { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Malformed(reason) => write!(f, "malformed protobuf message: {reason}"), + Self::TooDeep => write!(f, "protobuf message nesting exceeds {MAX_DEPTH} levels"), + Self::Violations { + violations, + truncated, + } => { + f.write_str("unknown protobuf fields or enum values:")?; + for (index, violation) in violations.iter().enumerate() { + let separator = if index == 0 { " " } else { ", " }; + write!(f, "{separator}{}", violation.field())?; + } + if *truncated { + f.write_str(", ...")?; + } + Ok(()) + } + } + } +} + +impl std::error::Error for WireRejection {} + +/// Scan tuning for one call site. +#[derive(Debug, Default, Clone, Copy)] +pub struct ScanOptions<'a> { + /// `(message full name, field number)` pairs whose *reserved* tags are + /// tolerated. Unreserved unknown tags are always reported. + pub allowed_reserved: &'a [(&'a str, u32)], +} + +/// Validate `bytes` as an encoding of `descriptor` that uses only known +/// fields and enum values. +pub fn scan( + descriptor: &MessageDescriptor, + bytes: &[u8], + options: ScanOptions<'_>, +) -> Result<(), WireRejection> { + let mut scanner = Scanner { + options, + path: String::new(), + violations: Vec::new(), + }; + match scanner.message(descriptor, bytes, 0) { + Ok(()) if scanner.violations.is_empty() => Ok(()), + Ok(()) => Err(WireRejection::Violations { + violations: scanner.violations, + truncated: false, + }), + Err(Abort::Full) => Err(WireRejection::Violations { + violations: scanner.violations, + truncated: true, + }), + Err(Abort::Malformed(reason)) => Err(WireRejection::Malformed(reason)), + Err(Abort::TooDeep) => Err(WireRejection::TooDeep), + } +} + +/// Validate `bytes` against the message named `full_name`. +/// +/// # Panics +/// When `full_name` is not in the compiled descriptors. Call sites name +/// messages compiled into this binary. +pub fn scan_named( + full_name: &str, + bytes: &[u8], + options: ScanOptions<'_>, +) -> Result<(), WireRejection> { + let descriptor = message_descriptor(full_name) + .unwrap_or_else(|| panic!("missing compiled descriptor for {full_name}")); + scan(&descriptor, bytes, options) +} + +enum Abort { + Malformed(&'static str), + TooDeep, + /// [`MAX_VIOLATIONS`] reached and another violation was found. + Full, +} + +impl From<&'static str> for Abort { + fn from(reason: &'static str) -> Self { + Self::Malformed(reason) + } +} + +struct Scanner<'a> { + options: ScanOptions<'a>, + path: String, + violations: Vec, +} + +impl Scanner<'_> { + fn message( + &mut self, + descriptor: &MessageDescriptor, + input: &[u8], + depth: usize, + ) -> Result<(), Abort> { + // Occurrence counters for repeated message fields, keyed by number. + let mut occurrences: Vec<(u32, usize)> = Vec::new(); + let mut fields = FieldIter::new(input); + while let Some(field) = fields.next_field()? { + let Some(known) = descriptor.get_field(field.number) else { + self.unknown_field(descriptor, field.number)?; + continue; + }; + match known.kind() { + Kind::Message(child) => { + expect_wire_type(field.wire_type, WIRE_LEN)?; + if depth >= MAX_DEPTH { + return Err(Abort::TooDeep); + } + let restore = self.path.len(); + self.push_segment(descriptor, &known, &mut occurrences); + self.message(&child, field.value, depth + 1)?; + self.path.truncate(restore); + } + Kind::Enum(enum_descriptor) => match field.wire_type { + WIRE_VARINT => { + self.enum_value(descriptor, &known, &enum_descriptor, field.value)?; + } + WIRE_LEN if known.is_list() => { + let mut packed = field.value; + while !packed.is_empty() { + let (_, len) = read_varint(packed)?; + self.enum_value(descriptor, &known, &enum_descriptor, &packed[..len])?; + packed = &packed[len..]; + } + } + _ => return Err("enum field has the wrong wire type".into()), + }, + kind => { + let expected = scalar_wire_type(&kind); + let packed = known.is_list() && expected != WIRE_LEN; + if field.wire_type != expected && !(packed && field.wire_type == WIRE_LEN) { + return Err("scalar field has the wrong wire type".into()); + } + } + } + } + Ok(()) + } + + fn unknown_field(&mut self, descriptor: &MessageDescriptor, tag: u32) -> Result<(), Abort> { + let reserved = descriptor + .reserved_ranges() + .any(|range| range.contains(&tag)); + if reserved { + let allowed = self + .options + .allowed_reserved + .iter() + .any(|(message, number)| *number == tag && *message == descriptor.full_name()); + if allowed { + return Ok(()); + } + return self.record(ViolationKind::ReservedField { tag }); + } + self.record(ViolationKind::UnknownField { tag }) + } + + fn enum_value( + &mut self, + parent: &MessageDescriptor, + field: &FieldDescriptor, + enum_descriptor: &prost_reflect::EnumDescriptor, + varint: &[u8], + ) -> Result<(), Abort> { + let (raw, _) = read_varint(varint)?; + // Protobuf encodes int32 enum values as sign-extended varints; prost + // truncates the same way. + #[allow(clippy::cast_possible_truncation)] + let value = raw as i32; + if enum_descriptor.get_value(value).is_some() { + return Ok(()); + } + let restore = self.path.len(); + self.push_name(parent, field); + let kind = ViolationKind::UnknownEnumValue { + value: (!is_secret(field)).then_some(value), + }; + let result = self.record(kind); + self.path.truncate(restore); + result + } + + fn record(&mut self, kind: ViolationKind) -> Result<(), Abort> { + if self.violations.len() == MAX_VIOLATIONS { + return Err(Abort::Full); + } + self.violations.push(FieldViolation { + path: self.path.clone(), + kind, + }); + Ok(()) + } + + /// Append the path segment for descending into message field `field`. + fn push_segment( + &mut self, + parent: &MessageDescriptor, + field: &FieldDescriptor, + occurrences: &mut Vec<(u32, usize)>, + ) { + self.push_name(parent, field); + if field.is_map() { + self.path.push_str("[*]"); + } else if field.is_list() { + let number = field.number(); + let index = if let Some((_, count)) = occurrences.iter_mut().find(|(n, _)| *n == number) + { + *count += 1; + *count - 1 + } else { + occurrences.push((number, 1)); + 0 + }; + self.path.push('['); + self.path.push_str(&index.to_string()); + self.path.push(']'); + } + } + + fn push_name(&mut self, parent: &MessageDescriptor, field: &FieldDescriptor) { + // A map value is addressed by its map field's `[*]` segment alone. + if parent.is_map_entry() && field.number() == 2 { + return; + } + if !self.path.is_empty() { + self.path.push('.'); + } + self.path.push_str(field.name()); + } +} + +fn is_secret(field: &FieldDescriptor) -> bool { + SECRET.as_ref().is_some_and(|extension| { + let options = field.options(); + options.has_extension(extension) && options.get_extension(extension).as_bool() == Some(true) + }) +} + +pub const WIRE_VARINT: u8 = 0; +pub const WIRE_FIXED64: u8 = 1; +pub const WIRE_LEN: u8 = 2; +pub const WIRE_FIXED32: u8 = 5; + +fn scalar_wire_type(kind: &Kind) -> u8 { + match kind { + Kind::Double | Kind::Fixed64 | Kind::Sfixed64 => WIRE_FIXED64, + Kind::Float | Kind::Fixed32 | Kind::Sfixed32 => WIRE_FIXED32, + Kind::String | Kind::Bytes | Kind::Message(_) => WIRE_LEN, + Kind::Int32 + | Kind::Int64 + | Kind::Uint32 + | Kind::Uint64 + | Kind::Sint32 + | Kind::Sint64 + | Kind::Bool + | Kind::Enum(_) => WIRE_VARINT, + } +} + +fn expect_wire_type(actual: u8, expected: u8) -> Result<(), Abort> { + if actual == expected { + Ok(()) + } else { + Err("message field has the wrong wire type".into()) + } +} + +/// One encoded field: its key and the bytes of its value. +/// +/// For length-delimited fields `value` excludes the length prefix; for the +/// other wire types it is the raw varint or fixed-width bytes. `raw` spans the +/// whole field including its key. +#[derive(Debug, Clone, Copy)] +pub struct WireField<'a> { + pub number: u32, + pub wire_type: u8, + pub value: &'a [u8], + pub raw: &'a [u8], +} + +/// Iterator over the top-level fields of one encoded message. +pub struct FieldIter<'a> { + input: &'a [u8], + offset: usize, +} + +impl<'a> FieldIter<'a> { + pub fn new(input: &'a [u8]) -> Self { + Self { input, offset: 0 } + } + + pub fn next_field(&mut self) -> Result>, &'static str> { + if self.offset >= self.input.len() { + return Ok(None); + } + let start = self.offset; + let (key, key_len) = read_varint(&self.input[start..])?; + let number = key >> 3; + if number == 0 || number > MAX_FIELD_NUMBER { + return Err("invalid field number"); + } + let number = u32::try_from(number).map_err(|_| "invalid field number")?; + let wire_type = (key & 7).to_le_bytes()[0]; + let value_start = start + key_len; + let rest = &self.input[value_start..]; + let (value_offset, value_len) = match wire_type { + WIRE_VARINT => (0, read_varint(rest)?.1), + WIRE_FIXED64 => (0, 8), + WIRE_LEN => { + let (len, prefix_len) = read_varint(rest)?; + let len = usize::try_from(len).map_err(|_| "length overflow")?; + (prefix_len, len) + } + WIRE_FIXED32 => (0, 4), + _ => return Err("unsupported wire type"), + }; + let value_begin = value_start + value_offset; + let end = value_begin + .checked_add(value_len) + .filter(|end| *end <= self.input.len()) + .ok_or("truncated field")?; + self.offset = end; + Ok(Some(WireField { + number, + wire_type, + value: &self.input[value_begin..end], + raw: &self.input[start..end], + })) + } +} + +pub fn read_varint(input: &[u8]) -> Result<(u64, usize), &'static str> { + let mut value = 0u64; + for (index, byte) in input.iter().copied().take(10).enumerate() { + value |= u64::from(byte & 0x7f) << (index * 7); + if byte & 0x80 == 0 { + return Ok((value, index + 1)); + } + } + Err("invalid varint") +} + +pub fn write_varint(output: &mut Vec, mut value: u64) { + while value >= 0x80 { + output.push(value.to_le_bytes()[0] | 0x80); + value >>= 7; + } + output.push(value.to_le_bytes()[0]); +} + +pub fn write_len_field(output: &mut Vec, number: u32, payload: &[u8]) { + write_varint(output, (u64::from(number) << 3) | u64::from(WIRE_LEN)); + write_varint(output, payload.len() as u64); + output.extend_from_slice(payload); +} + +#[cfg(test)] +mod tests; diff --git a/crates/openshell-server/src/wire_validation/sandbox_policy.rs b/crates/openshell-server/src/wire_validation/sandbox_policy.rs new file mode 100644 index 0000000000..b3bcf4dd0e --- /dev/null +++ b/crates/openshell-server/src/wire_validation/sandbox_policy.rs @@ -0,0 +1,327 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Raw `Sandbox.spec.policy` preservation across read-modify-writes. +//! +//! A gateway that decodes a `Sandbox` written by a newer gateway drops the +//! newer policy restrictions. Re-encoding that `Sandbox` after an unrelated +//! change (status, labels, image state) would erase them from storage. These +//! helpers carry the stored policy bytes through such updates unchanged. +//! +//! Callers pass stored payloads *after* legacy time-field migration, the same +//! bytes they hand to `prost`. + +use openshell_core::proto::{Sandbox, SandboxPolicy}; +use prost::Message; + +use super::{FieldIter, ScanOptions, WIRE_LEN, WireRejection, write_len_field}; + +/// `Sandbox.spec`. +const SANDBOX_SPEC: u32 = 2; +/// `SandboxSpec.policy`. +const SPEC_POLICY: u32 = 7; + +const SANDBOX_POLICY: &str = "openshell.sandbox.v1.SandboxPolicy"; + +/// Raw `Sandbox.spec.policy` bytes, or `None` when no policy is encoded. +/// +/// Protobuf merges repeated occurrences of an embedded message, so the +/// payloads of every occurrence are concatenated in wire order. +pub fn extract_spec_policy(sandbox: &[u8]) -> Result>, WireRejection> { + let mut policy: Option> = None; + let mut fields = FieldIter::new(sandbox); + while let Some(field) = fields.next_field().map_err(WireRejection::Malformed)? { + if field.number != SANDBOX_SPEC { + continue; + } + require_len(field.wire_type)?; + let mut spec_fields = FieldIter::new(field.value); + while let Some(spec_field) = spec_fields.next_field().map_err(WireRejection::Malformed)? { + if spec_field.number == SPEC_POLICY { + require_len(spec_field.wire_type)?; + policy + .get_or_insert_with(Vec::new) + .extend_from_slice(spec_field.value); + } + } + } + Ok(policy) +} + +/// Validate the raw `Sandbox.spec.policy` against the compiled schema before +/// any policy evaluation, canonicalization, or delivery uses it. +pub fn scan_spec_policy(sandbox: &[u8]) -> Result<(), WireRejection> { + extract_spec_policy(sandbox)?.map_or(Ok(()), |policy| { + super::scan_named(SANDBOX_POLICY, &policy, ScanOptions::default()) + }) +} + +/// Replace every `Sandbox.spec.policy` occurrence in `encoded` with `policy`. +/// +/// The policy takes the position of the first policy occurrence in the first +/// `spec`, or the end of that `spec` when it has none. A `spec` is created +/// when `encoded` has none and `policy` is `Some`. +pub fn splice_spec_policy(encoded: &[u8], policy: Option<&[u8]>) -> Result, WireRejection> { + let mut output = Vec::with_capacity(encoded.len() + policy.map_or(0, <[u8]>::len) + 8); + let mut pending = policy; + let mut fields = FieldIter::new(encoded); + while let Some(field) = fields.next_field().map_err(WireRejection::Malformed)? { + if field.number != SANDBOX_SPEC { + output.extend_from_slice(field.raw); + continue; + } + require_len(field.wire_type)?; + let spec = rewrite_spec(field.value, pending.take())?; + write_len_field(&mut output, SANDBOX_SPEC, &spec); + } + if let Some(policy) = pending { + let mut spec = Vec::with_capacity(policy.len() + 8); + write_len_field(&mut spec, SPEC_POLICY, policy); + write_len_field(&mut output, SANDBOX_SPEC, &spec); + } + Ok(output) +} + +/// Encode `updated`, keeping the stored policy bytes from `original` when the +/// update did not change the policy this build understands. +/// +/// When `updated.spec.policy` differs from the known fields of the stored +/// policy, the caller intentionally replaced it and the new encoding wins. +pub fn encode_preserving_spec_policy( + original: &[u8], + updated: &Sandbox, +) -> Result, WireRejection> { + let encoded = updated.encode_to_vec(); + let Some(stored) = extract_spec_policy(original)? else { + return Ok(encoded); + }; + let stored_known = SandboxPolicy::decode(stored.as_slice()) + .map_err(|_| WireRejection::Malformed("stored sandbox policy does not decode"))?; + let updated_policy = updated.spec.as_ref().and_then(|spec| spec.policy.as_ref()); + if updated_policy != Some(&stored_known) { + return Ok(encoded); + } + splice_spec_policy(&encoded, Some(&stored)) +} + +fn rewrite_spec(spec: &[u8], policy: Option<&[u8]>) -> Result, WireRejection> { + let mut output = Vec::with_capacity(spec.len() + policy.map_or(0, <[u8]>::len) + 8); + let mut pending = policy; + let mut fields = FieldIter::new(spec); + while let Some(field) = fields.next_field().map_err(WireRejection::Malformed)? { + if field.number == SPEC_POLICY { + require_len(field.wire_type)?; + if let Some(policy) = pending.take() { + write_len_field(&mut output, SPEC_POLICY, policy); + } + } else { + output.extend_from_slice(field.raw); + } + } + if let Some(policy) = pending { + write_len_field(&mut output, SPEC_POLICY, policy); + } + Ok(output) +} + +fn require_len(wire_type: u8) -> Result<(), WireRejection> { + if wire_type == WIRE_LEN { + Ok(()) + } else { + Err(WireRejection::Malformed( + "message field has the wrong wire type", + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::wire_validation::{ViolationKind, write_varint}; + use openshell_core::proto::NetworkPolicyRule; + use openshell_core::proto::SandboxSpec; + use openshell_core::proto::datamodel::v1::ObjectMeta; + + fn policy_with_rule(name: &str) -> SandboxPolicy { + let mut policy = SandboxPolicy::default(); + policy.network_policies.insert( + name.to_string(), + NetworkPolicyRule { + name: name.to_string(), + ..Default::default() + }, + ); + policy + } + + fn sandbox(policy: Option) -> Sandbox { + Sandbox { + metadata: Some(ObjectMeta { + id: "sbx-1".into(), + name: "demo".into(), + ..Default::default() + }), + spec: Some(SandboxSpec { + log_level: "info".into(), + policy, + ..Default::default() + }), + ..Default::default() + } + } + + /// Append an unknown varint field to an encoded message. + fn with_unknown(mut payload: Vec, tag: u32, value: u64) -> Vec { + write_varint(&mut payload, u64::from(tag) << 3); + write_varint(&mut payload, value); + payload + } + + /// Encode `sandbox` with `policy_bytes` as its raw spec.policy. + fn encode_with_raw_policy(sandbox: &Sandbox, policy_bytes: &[u8]) -> Vec { + splice_spec_policy(&sandbox.encode_to_vec(), Some(policy_bytes)).unwrap() + } + + #[test] + fn extract_returns_none_without_policy() { + assert_eq!( + extract_spec_policy(&sandbox(None).encode_to_vec()).unwrap(), + None + ); + assert_eq!(extract_spec_policy(&[]).unwrap(), None); + } + + #[test] + fn extract_returns_exact_policy_bytes() { + let policy = policy_with_rule("github"); + let raw = with_unknown(policy.encode_to_vec(), 900, 1); + let stored = encode_with_raw_policy(&sandbox(Some(policy)), &raw); + assert_eq!(extract_spec_policy(&stored).unwrap(), Some(raw)); + } + + #[test] + fn extract_merges_repeated_occurrences() { + let first = policy_with_rule("a").encode_to_vec(); + let second = policy_with_rule("b").encode_to_vec(); + let mut spec_a = Vec::new(); + write_len_field(&mut spec_a, SPEC_POLICY, &first); + let mut spec_b = Vec::new(); + write_len_field(&mut spec_b, SPEC_POLICY, &second); + let mut encoded = Vec::new(); + write_len_field(&mut encoded, SANDBOX_SPEC, &spec_a); + write_len_field(&mut encoded, SANDBOX_SPEC, &spec_b); + + let merged = extract_spec_policy(&encoded).unwrap().unwrap(); + let decoded_sandbox = Sandbox::decode(encoded.as_slice()).unwrap(); + assert_eq!( + SandboxPolicy::decode(merged.as_slice()).unwrap(), + decoded_sandbox.spec.unwrap().policy.unwrap() + ); + } + + #[test] + fn splice_round_trips_through_prost() { + let policy = policy_with_rule("github"); + let original = sandbox(Some(policy.clone())); + let spliced = + splice_spec_policy(&original.encode_to_vec(), Some(&policy.encode_to_vec())).unwrap(); + assert_eq!(Sandbox::decode(spliced.as_slice()).unwrap(), original); + } + + #[test] + fn splice_creates_spec_when_missing() { + let policy = policy_with_rule("github"); + let bare = Sandbox::default(); + let spliced = + splice_spec_policy(&bare.encode_to_vec(), Some(&policy.encode_to_vec())).unwrap(); + let decoded = Sandbox::decode(spliced.as_slice()).unwrap(); + assert_eq!(decoded.spec.unwrap().policy.unwrap(), policy); + } + + #[test] + fn splice_none_removes_policy() { + let spliced = splice_spec_policy( + &sandbox(Some(policy_with_rule("github"))).encode_to_vec(), + None, + ) + .unwrap(); + assert_eq!(extract_spec_policy(&spliced).unwrap(), None); + let decoded = Sandbox::decode(spliced.as_slice()).unwrap(); + assert_eq!(decoded.spec.unwrap().log_level, "info"); + } + + #[test] + fn unrelated_update_preserves_newer_policy_bytes() { + let policy = policy_with_rule("github"); + // A newer gateway wrote a restriction this build does not know. + let newer_policy = with_unknown(policy.encode_to_vec(), 900, 1); + let stored = encode_with_raw_policy(&sandbox(Some(policy)), &newer_policy); + + // This build decodes (dropping tag 900) and changes only labels. + let mut updated = Sandbox::decode(stored.as_slice()).unwrap(); + updated + .metadata + .as_mut() + .unwrap() + .labels + .insert("team".into(), "infra".into()); + assert_eq!( + extract_spec_policy(&updated.encode_to_vec()).unwrap(), + Some(policy_with_rule("github").encode_to_vec()), + "plain prost re-encoding drops the newer restriction" + ); + + let rewritten = encode_preserving_spec_policy(&stored, &updated).unwrap(); + assert_eq!(extract_spec_policy(&rewritten).unwrap(), Some(newer_policy)); + let decoded = Sandbox::decode(rewritten.as_slice()).unwrap(); + assert_eq!(decoded.metadata.unwrap().labels["team"], "infra"); + } + + #[test] + fn intentional_policy_replacement_wins() { + let policy = policy_with_rule("github"); + let newer_policy = with_unknown(policy.encode_to_vec(), 900, 1); + let stored = encode_with_raw_policy(&sandbox(Some(policy)), &newer_policy); + + let mut updated = Sandbox::decode(stored.as_slice()).unwrap(); + let replacement = policy_with_rule("pypi"); + updated.spec.as_mut().unwrap().policy = Some(replacement.clone()); + + let rewritten = encode_preserving_spec_policy(&stored, &updated).unwrap(); + assert_eq!( + extract_spec_policy(&rewritten).unwrap(), + Some(replacement.encode_to_vec()) + ); + } + + #[test] + fn scan_spec_policy_reports_unknown_policy_fields() { + let policy = policy_with_rule("github"); + assert_eq!( + scan_spec_policy(&sandbox(Some(policy.clone())).encode_to_vec()), + Ok(()) + ); + + let newer_policy = with_unknown(policy.encode_to_vec(), 900, 1); + let stored = encode_with_raw_policy(&sandbox(Some(policy)), &newer_policy); + let Err(WireRejection::Violations { violations, .. }) = scan_spec_policy(&stored) else { + panic!("expected a violation"); + }; + assert_eq!(violations.len(), 1); + assert_eq!(violations[0].kind, ViolationKind::UnknownField { tag: 900 }); + assert_eq!(violations[0].field(), "#900"); + } + + #[test] + fn malformed_payload_is_rejected() { + assert!(matches!( + extract_spec_policy(&[0x12, 0x05, 0x00]), + Err(WireRejection::Malformed(_)) + )); + // Sandbox.spec encoded as a varint. + assert!(matches!( + extract_spec_policy(&[0x10, 0x01]), + Err(WireRejection::Malformed(_)) + )); + } +} diff --git a/crates/openshell-server/src/wire_validation/tests.rs b/crates/openshell-server/src/wire_validation/tests.rs new file mode 100644 index 0000000000..95f87c744c --- /dev/null +++ b/crates/openshell-server/src/wire_validation/tests.rs @@ -0,0 +1,417 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use openshell_core::proto::{ + NetworkBinary, NetworkEndpoint, NetworkPolicyRule, Sandbox, SandboxPolicy, + SandboxRestartPolicy, SandboxSpec, +}; +use prost::Message; + +const SANDBOX: &str = "openshell.v1.Sandbox"; +const POLICY: &str = "openshell.sandbox.v1.SandboxPolicy"; + +fn varint_field(output: &mut Vec, number: u32, value: u64) { + write_varint(output, u64::from(number) << 3); + write_varint(output, value); +} + +fn with_unknown(mut payload: Vec, number: u32) -> Vec { + varint_field(&mut payload, number, 1); + payload +} + +fn violations(result: Result<(), WireRejection>) -> (Vec, bool) { + match result { + Err(WireRejection::Violations { + violations, + truncated, + }) => (violations, truncated), + other => panic!("expected violations, got {other:?}"), + } +} + +fn fields(result: Result<(), WireRejection>) -> Vec { + violations(result) + .0 + .iter() + .map(FieldViolation::field) + .collect() +} + +fn rule_with_endpoints(count: usize) -> NetworkPolicyRule { + NetworkPolicyRule { + name: "github".into(), + endpoints: (0..count) + .map(|index| NetworkEndpoint { + host: format!("host{index}.example.com"), + port: 443, + ..Default::default() + }) + .collect(), + binaries: vec![NetworkBinary { + path: "/usr/bin/git".into(), + }], + } +} + +#[test] +fn known_messages_pass() { + let mut policy = SandboxPolicy::default(); + policy + .network_policies + .insert("github".into(), rule_with_endpoints(3)); + let sandbox = Sandbox { + spec: Some(SandboxSpec { + policy: Some(policy.clone()), + restart_policy: SandboxRestartPolicy::OnFailure.into(), + command: vec!["sleep".into(), "infinity".into()], + ..Default::default() + }), + ..Default::default() + }; + assert_eq!( + scan_named(POLICY, &policy.encode_to_vec(), ScanOptions::default()), + Ok(()) + ); + assert_eq!( + scan_named(SANDBOX, &sandbox.encode_to_vec(), ScanOptions::default()), + Ok(()) + ); + assert_eq!(scan_named(SANDBOX, &[], ScanOptions::default()), Ok(())); +} + +#[test] +fn unknown_root_field_is_reported() { + let bytes = with_unknown(SandboxPolicy::default().encode_to_vec(), 900); + let (found, truncated) = violations(scan_named(POLICY, &bytes, ScanOptions::default())); + assert!(!truncated); + assert_eq!( + found, + vec![FieldViolation { + path: String::new(), + kind: ViolationKind::UnknownField { tag: 900 }, + }] + ); + assert_eq!(found[0].field(), "#900"); +} + +#[test] +fn nested_paths_name_map_values_and_repeated_indexes() { + let mut rule = rule_with_endpoints(0); + let endpoints = [ + NetworkEndpoint { + host: "a.example.com".into(), + ..Default::default() + } + .encode_to_vec(), + with_unknown( + NetworkEndpoint { + host: "b.example.com".into(), + ..Default::default() + } + .encode_to_vec(), + 901, + ), + ]; + rule.endpoints.clear(); + let mut rule_bytes = rule.encode_to_vec(); + for endpoint in &endpoints { + write_len_field(&mut rule_bytes, 2, endpoint); + } + let rule_bytes = with_unknown(rule_bytes, 902); + + // network_policies is map at tag 5. + let mut entry = Vec::new(); + write_len_field(&mut entry, 1, b"caller-authored-key"); + write_len_field(&mut entry, 2, &rule_bytes); + let mut policy = Vec::new(); + write_len_field(&mut policy, 5, &entry); + + assert_eq!( + fields(scan_named(POLICY, &policy, ScanOptions::default())), + vec![ + "network_policies[*].endpoints[1]#901".to_string(), + "network_policies[*]#902".to_string(), + ] + ); +} + +#[test] +fn reserved_tags_are_reported_unless_allowed() { + // NetworkBinary reserves tag 2, the legacy advisor_proposed flag. + let binary = with_unknown( + NetworkBinary { + path: "/usr/bin/git".into(), + } + .encode_to_vec(), + 2, + ); + let descriptor = message_descriptor("openshell.sandbox.v1.NetworkBinary").unwrap(); + let (found, _) = violations(scan(&descriptor, &binary, ScanOptions::default())); + assert_eq!(found[0].kind, ViolationKind::ReservedField { tag: 2 }); + assert_eq!(found[0].description(), "reserved field 2"); + + let legacy = ScanOptions { + allowed_reserved: LEGACY_STORED_POLICY_RESERVED, + }; + assert_eq!(scan(&descriptor, &binary, legacy), Ok(())); + + // The allowance never covers unreserved tags. + let unreserved = with_unknown(binary, 3); + assert_eq!( + fields(scan(&descriptor, &unreserved, legacy)), + vec!["#3".to_string()] + ); +} + +#[test] +fn unknown_enum_values_are_reported() { + let sandbox = Sandbox { + spec: Some(SandboxSpec { + log_level: "info".into(), + ..Default::default() + }), + ..Default::default() + }; + let mut spec = SandboxSpec { + log_level: "info".into(), + ..Default::default() + } + .encode_to_vec(); + // SandboxSpec.restart_policy = 99. + varint_field(&mut spec, 15, 99); + let mut bytes = Sandbox { + spec: None, + ..sandbox + } + .encode_to_vec(); + write_len_field(&mut bytes, 2, &spec); + + let (found, _) = violations(scan_named(SANDBOX, &bytes, ScanOptions::default())); + assert_eq!( + found, + vec![FieldViolation { + path: "spec.restart_policy".into(), + kind: ViolationKind::UnknownEnumValue { value: Some(99) }, + }] + ); + assert_eq!(found[0].field(), "spec.restart_policy"); + assert_eq!(found[0].description(), "unrecognized enum value 99"); +} + +#[test] +fn negative_enum_values_decode_like_prost() { + let mut spec = Vec::new(); + // -1 as a sign-extended ten-byte varint. + varint_field(&mut spec, 15, u64::MAX); + let (found, _) = violations(scan_named( + "openshell.v1.SandboxSpec", + &spec, + ScanOptions::default(), + )); + assert_eq!( + found[0].kind, + ViolationKind::UnknownEnumValue { value: Some(-1) } + ); +} + +#[test] +fn packed_repeated_enums_are_checked() { + // InterceptorBinding.phases is `repeated GatewayInterceptorPhase`. + let descriptor = + message_descriptor("openshell.gateway_interceptor.v1.InterceptorBinding").unwrap(); + let mut packed = Vec::new(); + write_varint(&mut packed, 2); + write_varint(&mut packed, 77); + let mut bytes = Vec::new(); + write_len_field(&mut bytes, 3, &packed); + let (found, _) = violations(scan(&descriptor, &bytes, ScanOptions::default())); + assert_eq!( + found, + vec![FieldViolation { + path: "phases".into(), + kind: ViolationKind::UnknownEnumValue { value: Some(77) }, + }] + ); + + // Unpacked encoding of the same field is equally checked. + let mut unpacked = Vec::new(); + varint_field(&mut unpacked, 3, 2); + assert_eq!(scan(&descriptor, &unpacked, ScanOptions::default()), Ok(())); + varint_field(&mut unpacked, 3, 78); + assert_eq!( + fields(scan(&descriptor, &unpacked, ScanOptions::default())), + vec!["phases"] + ); +} + +#[test] +fn struct_keys_are_not_inspected() { + let mut nested = prost_types::Struct::default(); + nested.fields.insert( + "any_caller_key".into(), + prost_types::Value { + kind: Some(prost_types::value::Kind::StringValue("value".into())), + }, + ); + assert_eq!( + scan_named( + "google.protobuf.Struct", + &nested.encode_to_vec(), + ScanOptions::default() + ), + Ok(()) + ); +} + +#[test] +fn nesting_beyond_limit_is_rejected() { + fn nested_value(depth: usize) -> prost_types::Value { + let mut value = prost_types::Value { + kind: Some(prost_types::value::Kind::NumberValue(1.0)), + }; + for _ in 0..depth { + value = prost_types::Value { + kind: Some(prost_types::value::Kind::ListValue( + prost_types::ListValue { + values: vec![value], + }, + )), + }; + } + value + } + // Each list level nests ListValue then Value: two messages per level. + let shallow = nested_value(MAX_DEPTH / 2).encode_to_vec(); + assert_eq!( + scan_named("google.protobuf.Value", &shallow, ScanOptions::default()), + Ok(()) + ); + let deep = nested_value(MAX_DEPTH / 2 + 1).encode_to_vec(); + assert_eq!( + scan_named("google.protobuf.Value", &deep, ScanOptions::default()), + Err(WireRejection::TooDeep) + ); +} + +#[test] +fn violations_stop_after_limit() { + let mut bytes = Vec::new(); + for number in 0..(u32::try_from(MAX_VIOLATIONS).unwrap() + 4) { + varint_field(&mut bytes, 900 + number, 1); + } + let (found, truncated) = violations(scan_named(POLICY, &bytes, ScanOptions::default())); + assert_eq!(found.len(), MAX_VIOLATIONS); + assert!(truncated); + + let mut exact = Vec::new(); + for number in 0..u32::try_from(MAX_VIOLATIONS).unwrap() { + varint_field(&mut exact, 900 + number, 1); + } + let (found, truncated) = violations(scan_named(POLICY, &exact, ScanOptions::default())); + assert_eq!(found.len(), MAX_VIOLATIONS); + assert!(!truncated); +} + +#[test] +fn malformed_encodings_are_rejected() { + let options = ScanOptions::default(); + // Truncated length-delimited field. + assert!(matches!( + scan_named(POLICY, &[0x2a, 0x05, 0x00], options), + Err(WireRejection::Malformed(_)) + )); + // Field number zero. + assert!(matches!( + scan_named(POLICY, &[0x00, 0x00], options), + Err(WireRejection::Malformed(_)) + )); + // Group wire type. + assert!(matches!( + scan_named(POLICY, &[0x0b], options), + Err(WireRejection::Malformed(_)) + )); + // Overlong varint. + assert!(matches!( + scan_named(POLICY, &[0xff; 11], options), + Err(WireRejection::Malformed(_)) + )); + // Message field encoded as a varint: network_policies (tag 5). + assert!(matches!( + scan_named(POLICY, &[0x28, 0x01], options), + Err(WireRejection::Malformed(_)) + )); +} + +#[test] +fn unknown_fields_with_any_wire_type_are_skipped() { + let mut bytes = Vec::new(); + // Tag 900 as fixed64, fixed32, and length-delimited. + write_varint(&mut bytes, (900 << 3) | 1); + bytes.extend_from_slice(&[0; 8]); + write_varint(&mut bytes, (901 << 3) | 5); + bytes.extend_from_slice(&[0; 4]); + write_len_field(&mut bytes, 902, b"opaque"); + assert_eq!( + fields(scan_named(POLICY, &bytes, ScanOptions::default())), + vec!["#900", "#901", "#902"] + ); +} + +#[test] +fn secret_option_resolves() { + let descriptor = message_descriptor("openshell.compute.v1.AuthenticateSandboxRequest").unwrap(); + assert!(is_secret( + &descriptor.get_field_by_name("credential").unwrap() + )); + let policy = message_descriptor(POLICY).unwrap(); + assert!(!is_secret(&policy.get_field(1).unwrap())); +} + +#[test] +fn status_carries_error_info_and_field_violations() { + let bytes = with_unknown(SandboxPolicy::default().encode_to_vec(), 900); + let status = scan_named(POLICY, &bytes, ScanOptions::default()) + .unwrap_err() + .into_status(); + assert_eq!(status.code(), Code::InvalidArgument); + let details = rpc_error::decode_details(&status).expect("status details"); + let info = details.error_info().expect("error info"); + assert_eq!(info.reason, rpc_error::UNKNOWN_PROTOBUF_FIELD); + assert_eq!(info.domain, rpc_error::ERROR_DOMAIN); + assert_eq!(info.metadata["gateway_version"], openshell_core::VERSION); + let bad_request = details.bad_request().expect("bad request"); + assert_eq!(bad_request.field_violations.len(), 1); + assert_eq!(bad_request.field_violations[0].field, "#900"); + assert_eq!( + bad_request.field_violations[0].description, + "unknown field 900" + ); +} + +#[test] +fn malformed_status_has_no_unknown_field_reason() { + let status = WireRejection::Malformed("truncated field").into_status(); + assert_eq!(status.code(), Code::InvalidArgument); + assert!( + rpc_error::decode_details(&status) + .and_then(|details| details.error_info().cloned()) + .is_none() + ); +} + +#[test] +fn display_never_echoes_values() { + let mut payload = SandboxPolicy::default().encode_to_vec(); + write_len_field(&mut payload, 900, b"super-secret-token"); + let rejection = scan_named(POLICY, &payload, ScanOptions::default()).unwrap_err(); + let rendered = rejection.to_string(); + assert!(!rendered.contains("super-secret-token")); + let status = rejection.into_status(); + assert!(!status.message().contains("super-secret-token")); + assert!( + !String::from_utf8_lossy(status.details()).contains("super-secret-token"), + "status details must not echo unknown field bytes" + ); +} From 694ee7224ad897370f6793018c4f2342a52708cd Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Mon, 30 Nov 2026 22:18:07 +0000 Subject: [PATCH 02/10] feat(server): reject unknown protobuf fields at gRPC ingress Implement step 2 of RFC 0027. A wrapper ahead of the gateway interceptors scans every request frame of strict RPCs against the method's input descriptor before interceptors or tonic decode it. Strict RPCs are those with unauthenticated, bearer, operator, or dual auth, plus any RPC whose request reaches a policy type, such as SubmitPolicyAnalysis. Non-policy sandbox, peer, and supervisor RPCs stay exempt during 0.x. Unary and server-streaming requests are reassembled and validated before dispatch, so a rejected request never reaches durable request admission. Client streams are validated frame by frame and end with the scanner's status. Compressed frames return UNIMPLEMENTED and frames above the route's decoding limit return RESOURCE_EXHAUSTED. Keep the exact status and details when a request body fails: interceptor body collection, the interactive exec start frame, and ForwardTcp relay frames now pass the validation status to the client. Rejections count in openshell_server_grpc_unknown_fields_total. Refs #6097 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Mrunal Patel --- .../grpc/mutation_replay/streaming/tests.rs | 55 ++ crates/openshell-server/src/grpc/sandbox.rs | 69 +- crates/openshell-server/src/multiplex.rs | 322 +++++++- .../src/wire_validation/ingress.rs | 720 ++++++++++++++++++ .../src/wire_validation/mod.rs | 1 + docs/sdk/api-errors.mdx | 1 + 6 files changed, 1151 insertions(+), 17 deletions(-) create mode 100644 crates/openshell-server/src/wire_validation/ingress.rs diff --git a/crates/openshell-server/src/grpc/mutation_replay/streaming/tests.rs b/crates/openshell-server/src/grpc/mutation_replay/streaming/tests.rs index db3ef352fa..b3ba61c1c0 100644 --- a/crates/openshell-server/src/grpc/mutation_replay/streaming/tests.rs +++ b/crates/openshell-server/src/grpc/mutation_replay/streaming/tests.rs @@ -718,3 +718,58 @@ async fn interactive_wire_start_is_admitted_under_its_own_method_namespace() { drop(output); server.abort(); } + +fn with_unknown_field(mut message: Vec, tag: u64) -> Vec { + prost::encoding::encode_varint(tag << 3, &mut message); + prost::encoding::encode_varint(1, &mut message); + message +} + +#[tokio::test] +async fn interactive_start_rejected_by_ingress_leaves_request_id_unused() { + use crate::grpc::OpenShellService; + use openshell_core::proto::open_shell_server::OpenShell; + + let directory = tempfile::tempdir().unwrap(); + let state = setup("sqlite::memory:", &directory).await; + let req = request(&state).await; + let invalid = with_unknown_field(interactive_start(req.clone()).encode_to_vec(), 900); + let stream = crate::wire_validation::ingress::validated_request_stream::( + "/openshell.v1.OpenShell/ExecSandboxInteractive", + &[invalid], + ); + + let status = OpenShellService::new(state.clone()) + .exec_sandbox_interactive(authed_request(stream)) + .await + .unwrap_err(); + + assert_eq!(status.code(), tonic::Code::InvalidArgument); + assert_eq!(reason(&status), rpc_error::UNKNOWN_PROTOBUF_FIELD); + assert!( + state + .store + .list_by_type_after(OBJECT_TYPE, None, 100) + .await + .unwrap() + .is_empty(), + "a rejected start frame writes no admission record" + ); + + // The same request_id still admits a valid start. + let mut messages = register(&state, &sandbox_id(&state, &req).await); + let (mut client, server) = wire_client(state.clone(), None, None).await; + let output = exec_rpc(&mut client, req, true).await.unwrap(); + receive_relay(&state, &mut messages).await; + assert_eq!( + state + .store + .list_by_type_after(OBJECT_TYPE, None, 100) + .await + .unwrap() + .len(), + 1 + ); + drop(output); + server.abort(); +} diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 8e5762a33b..cf44fa60b5 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -3282,6 +3282,7 @@ async fn bridge_forward_tcp_stream( let sandbox_id_in = sandbox_id.to_string(); let channel_id_in = channel_id.to_string(); + let tx_in = tx.clone(); tokio::spawn(async move { loop { match inbound.message().await { @@ -3305,6 +3306,11 @@ async fn bridge_forward_tcp_stream( Ok(None) => break, Err(err) => { debug!(sandbox_id = %sandbox_id_in, channel_id = %channel_id_in, error = %err, "ForwardTcp: inbound stream ended"); + // Report request-frame rejections (RFC 0027 ingress + // validation) to the client instead of a silent close. + if is_request_frame_rejection(&err) { + let _ = tx_in.send(Err(err)).await; + } break; } } @@ -3339,6 +3345,15 @@ async fn bridge_forward_tcp_stream( } } +/// Whether a request-stream error is the gateway rejecting a client frame +/// rather than transport loss. +fn is_request_frame_rejection(status: &Status) -> bool { + matches!( + status.code(), + tonic::Code::InvalidArgument | tonic::Code::ResourceExhausted | tonic::Code::Unimplemented + ) +} + // --------------------------------------------------------------------------- // Interactive exec handler (bidirectional stdin streaming) // --------------------------------------------------------------------------- @@ -3391,10 +3406,9 @@ pub(super) async fn handle_exec_sandbox_interactive( ) -> Result>>, Status> { let (metadata, extensions, mut input_stream) = request.into_parts(); - let first_msg = input_stream - .message() - .await - .map_err(|e| Status::internal(format!("failed to read first message: {e}")))?; + // Keep the request stream's own status: ingress validation rejects an + // invalid start frame with INVALID_ARGUMENT and structured details. + let first_msg = input_stream.message().await?; let req = validate_interactive_exec_start(first_msg)?; super::mutation_audit::record_exec_targets(&req); @@ -4472,6 +4486,53 @@ mod tests { }; use crate::compute::NoopTestDriver; + #[tokio::test] + async fn forward_tcp_reports_rejected_request_frames_to_the_client() { + use openshell_core::proto::tcp_forward_frame::Payload; + use tokio::io::AsyncReadExt; + + let data = |bytes: &[u8]| { + TcpForwardFrame { + payload: Some(Payload::Data(bytes.to_vec())), + } + .encode_to_vec() + }; + let mut invalid = data(b"dropped"); + prost::encoding::encode_varint(900 << 3, &mut invalid); + prost::encoding::encode_varint(1, &mut invalid); + let inbound = crate::wire_validation::ingress::validated_request_stream::( + "/openshell.v1.OpenShell/ForwardTcp", + &[data(b"hello"), invalid], + ); + let (mut relay, gateway_side) = tokio::io::duplex(1024); + let (tx, mut rx) = mpsc::channel(4); + let bridge = tokio::spawn(async move { + bridge_forward_tcp_stream(inbound, gateway_side, tx, "sb", "ch").await; + }); + + let mut forwarded = Vec::new(); + relay.read_to_end(&mut forwarded).await.unwrap(); + assert_eq!( + forwarded, b"hello", + "only frames before the rejection reach the relay" + ); + + let status = rx.recv().await.unwrap().unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + let details = openshell_core::rpc_error::decode_details(&status).unwrap(); + assert_eq!( + details.error_info().unwrap().reason, + openshell_core::rpc_error::UNKNOWN_PROTOBUF_FIELD + ); + assert_eq!( + details.bad_request().unwrap().field_violations[0].field, + "#900" + ); + + drop(relay); + bridge.await.unwrap(); + } + #[test] fn exec_requires_ssh_channel_close_after_exit_status() { assert_eq!(exec_loop_result(Some(0), true).unwrap(), 0); diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 6b8a4d1406..168d8a808d 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -53,7 +53,7 @@ use crate::{ auth::oidc::{self, OidcAuthenticator}, auth::principal::{OperatorPrincipal, Principal, UserPrincipal}, auth::workspace_authz::{MinWorkspaceRole, authorize_workspace}, - http_router, service_http_router, + http_router, service_http_router, wire_validation, }; /// Request-ID generator that produces a UUID v4 for each inbound request. @@ -292,10 +292,13 @@ impl MultiplexService { }; let openshell = OpenShellServer::new(OpenShellService::new(self.state.clone())) .max_decoding_message_size(MAX_GRPC_DECODE_SIZE); - let openshell = GatewayInterceptorGrpcService::new( - openshell, - self.state.gateway_interceptors.clone(), - Some(self.state.clone()), + let openshell = IngressValidationService::new( + GatewayInterceptorGrpcService::new( + openshell, + self.state.gateway_interceptors.clone(), + Some(self.state.clone()), + ), + MAX_GRPC_DECODE_SIZE, ); // The private host stream carries launch secrets, so it bypasses the // configurable interceptors. @@ -316,17 +319,23 @@ impl MultiplexService { let reflection = self.state.reflection_service.clone(); let sandbox_updates = SandboxUpdatesServer::new(OpenShellService::new(self.state.clone())) .max_decoding_message_size(MAX_GRPC_DECODE_SIZE); - let sandbox_updates = GatewayInterceptorGrpcService::new( - sandbox_updates, - self.state.gateway_interceptors.clone(), - Some(self.state.clone()), + let sandbox_updates = IngressValidationService::new( + GatewayInterceptorGrpcService::new( + sandbox_updates, + self.state.gateway_interceptors.clone(), + Some(self.state.clone()), + ), + MAX_GRPC_DECODE_SIZE, ); let discovery = ServiceDiscoveryServer::new(OpenShellService::new(self.state.clone())) .max_decoding_message_size(MAX_GRPC_DECODE_SIZE); - let discovery = GatewayInterceptorGrpcService::new( - discovery, - self.state.gateway_interceptors.clone(), - Some(self.state.clone()), + let discovery = IngressValidationService::new( + GatewayInterceptorGrpcService::new( + discovery, + self.state.gateway_interceptors.clone(), + Some(self.state.clone()), + ), + MAX_GRPC_DECODE_SIZE, ); let authz_policy = self.state.config.oidc.as_ref().map(AuthzPolicy::from); let authenticator_chain = build_authenticator_chain(&self.state); @@ -454,6 +463,93 @@ where } } +/// Scans request frames of strict RPCs for unknown protobuf fields and enum +/// values (RFC 0027) before interceptors or tonic decode them. +/// +/// Unary and server-streaming requests are validated in full before dispatch, +/// so a rejected request never reaches durable request admission. Client +/// streams are validated frame by frame; a rejected frame ends the request +/// stream with the scanner's `tonic::Status`. +#[derive(Clone)] +struct IngressValidationService { + inner: S, + /// The decoding limit of the `tonic` server this wrapper fronts. + max_message_bytes: usize, +} + +impl IngressValidationService { + const fn new(inner: S, max_message_bytes: usize) -> Self { + Self { + inner, + max_message_bytes, + } + } +} + +impl tower::Service> for IngressValidationService +where + S: tower::Service, Response = Response> + + Clone + + Send + + 'static, + S::Future: Send + 'static, + S::Error: Send + 'static, +{ + type Response = S::Response; + type Error = S::Error; + type Future = Pin> + Send>>; + + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.inner.poll_ready(cx) + } + + fn call(&mut self, req: Request) -> Self::Future { + let mut inner = self.inner.clone(); + let max_message_bytes = self.max_message_bytes; + let method = wire_validation::ingress::method(req.uri().path()) + .filter(|method| method.disposition == wire_validation::ingress::Disposition::Strict); + let Some(method) = method else { + return Box::pin(async move { inner.ready().await?.call(req).await }); + }; + + Box::pin(async move { + if req + .headers() + .get("grpc-encoding") + .is_some_and(|encoding| encoding != "identity") + { + return Ok(tonic::Status::unimplemented( + "compressed gRPC requests are not supported", + ) + .into_http()); + } + let (parts, body) = req.into_parts(); + let body = if method.client_streaming { + BoxBody( + wire_validation::ingress::ValidatingBody::new(body, method, max_message_bytes) + .boxed_unsync(), + ) + } else { + match wire_validation::ingress::collect_single_frame( + method, + body, + max_message_bytes, + ) + .await + { + Ok(frame) => boxed_body_from_bytes(frame), + Err(status) => return Ok(status.into_http()), + } + }; + inner + .ready() + .await? + .call(Request::from_parts(parts, body)) + .await + }) + } +} + /// `OpenShell` gRPC wrapper that applies configured gateway interceptors before /// tonic dispatches to a specific RPC handler. #[derive(Clone)] @@ -697,6 +793,12 @@ async fn collect_intercepted_grpc_body(body: BoxBody) -> Result() { + Ok(status) => return *status, + Err(err) => err, + }; if err.downcast_ref::().is_some() { tonic::Status::resource_exhausted(format!( "gRPC request body exceeds interceptor evaluation limit of {MAX_INTERCEPTED_GRPC_BODY_SIZE} bytes" @@ -1712,6 +1814,7 @@ mod tests { ProviderProfileSnapshotRequest, gateway_interceptor_server::{GatewayInterceptor, GatewayInterceptorServer}, }; + use openshell_core::rpc_error::StatusExt as _; use std::convert::Infallible; use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -2095,6 +2198,199 @@ mod tests { interceptor_task.abort(); } + fn with_unknown_field(mut message: Vec, tag: u64) -> Vec { + prost::encoding::encode_varint(tag << 3, &mut message); + prost::encoding::encode_varint(1, &mut message); + message + } + + fn status_from_response(response: &Response) -> tonic::Status { + tonic::Status::from_header_map(response.headers()).expect("trailers-only status response") + } + + fn assert_unknown_field_status(status: &tonic::Status, field: &str) { + assert_eq!(status.code(), tonic::Code::InvalidArgument); + let details = openshell_core::rpc_error::decode_details(status).expect("status details"); + assert_eq!( + details.error_info().unwrap().reason, + openshell_core::rpc_error::UNKNOWN_PROTOBUF_FIELD + ); + let violations = &details.bad_request().unwrap().field_violations; + assert_eq!(violations.len(), 1); + assert_eq!(violations[0].field, field); + } + + /// Inner service that counts calls and drains the request body, recording + /// the first body error as a `tonic::Status`. + fn draining_service( + calls: Arc, + body_error: Arc>>, + ) -> impl Service< + Request, + Response = Response, + Error = Infallible, + Future = impl Future, Infallible>> + Send, + > + Clone + + Send + + 'static { + tower::service_fn(move |request: Request| { + let calls = calls.clone(); + let body_error = body_error.clone(); + async move { + calls.fetch_add(1, Ordering::SeqCst); + if let Err(error) = request.into_body().collect().await { + *body_error.lock().unwrap() = Some(tonic::Status::from_error(error)); + } + Ok::<_, Infallible>(tonic::Status::ok("").into_http()) + } + }) + } + + #[tokio::test] + async fn ingress_validation_rejects_unknown_unary_field_before_dispatch() { + let calls = Arc::new(AtomicUsize::new(0)); + let body_error = Arc::new(Mutex::new(None)); + let mut service = IngressValidationService::new( + draining_service(calls.clone(), body_error.clone()), + MAX_GRPC_DECODE_SIZE, + ); + + let invalid = with_unknown_field(CreateSandboxRequest::default().encode_to_vec(), 900); + let request = Request::builder() + .uri("/openshell.v1.OpenShell/CreateSandbox") + .body(boxed_body_from_bytes(grpc_frame(&invalid))) + .unwrap(); + let response = service.ready().await.unwrap().call(request).await.unwrap(); + assert_unknown_field_status(&status_from_response(&response), "#900"); + assert_eq!(calls.load(Ordering::SeqCst), 0, "rejected before dispatch"); + + let valid = CreateSandboxRequest::default().encode_to_vec(); + let request = Request::builder() + .uri("/openshell.v1.OpenShell/CreateSandbox") + .body(boxed_body_from_bytes(grpc_frame(&valid))) + .unwrap(); + service.ready().await.unwrap().call(request).await.unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(body_error.lock().unwrap().is_none()); + } + + #[tokio::test] + async fn ingress_validation_runs_before_gateway_interceptors() { + let (runtime, interceptor_task) = post_commit_test_runtime(CREATE_SANDBOX_RPC).await; + let calls = Arc::new(AtomicUsize::new(0)); + let mut service = IngressValidationService::new( + GatewayInterceptorGrpcService::new( + draining_service(calls.clone(), Arc::new(Mutex::new(None))), + Some(runtime), + None, + ), + MAX_GRPC_DECODE_SIZE, + ); + let invalid = with_unknown_field(CreateSandboxRequest::default().encode_to_vec(), 900); + let request = Request::builder() + .uri("/openshell.v1.OpenShell/CreateSandbox") + .body(boxed_body_from_bytes(grpc_frame(&invalid))) + .unwrap(); + let response = service.ready().await.unwrap().call(request).await.unwrap(); + assert_unknown_field_status(&status_from_response(&response), "#900"); + assert_eq!(calls.load(Ordering::SeqCst), 0); + interceptor_task.abort(); + } + + #[tokio::test] + async fn ingress_validation_exempts_internal_runtime_rpcs() { + let calls = Arc::new(AtomicUsize::new(0)); + let body_error = Arc::new(Mutex::new(None)); + let mut service = IngressValidationService::new( + draining_service(calls.clone(), body_error.clone()), + MAX_GRPC_DECODE_SIZE, + ); + let request = Request::builder() + .uri("/openshell.v1.OpenShell/PushSandboxLogs") + .body(boxed_body_from_bytes(grpc_frame(&with_unknown_field( + Vec::new(), + 900, + )))) + .unwrap(); + service.ready().await.unwrap().call(request).await.unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(body_error.lock().unwrap().is_none()); + } + + #[tokio::test] + async fn ingress_validation_ends_client_stream_with_status() { + use openshell_core::proto::{ExecSandboxInput, exec_sandbox_input}; + + let calls = Arc::new(AtomicUsize::new(0)); + let body_error = Arc::new(Mutex::new(None)); + let mut service = IngressValidationService::new( + draining_service(calls.clone(), body_error.clone()), + MAX_GRPC_DECODE_SIZE, + ); + let stdin = ExecSandboxInput { + payload: Some(exec_sandbox_input::Payload::Stdin(b"ls".to_vec())), + } + .encode_to_vec(); + let mut body = grpc_frame(&stdin).to_vec(); + body.extend_from_slice(&grpc_frame(&with_unknown_field(stdin, 900))); + let request = Request::builder() + .uri("/openshell.v1.OpenShell/ExecSandboxInteractive") + .body(boxed_body_from_bytes(Bytes::from(body))) + .unwrap(); + service.ready().await.unwrap().call(request).await.unwrap(); + assert_eq!( + calls.load(Ordering::SeqCst), + 1, + "streams dispatch immediately" + ); + let status = body_error.lock().unwrap().take().expect("stream error"); + assert_unknown_field_status(&status, "#900"); + } + + #[tokio::test] + async fn ingress_validation_rejects_compressed_requests() { + let calls = Arc::new(AtomicUsize::new(0)); + let mut service = IngressValidationService::new( + draining_service(calls.clone(), Arc::new(Mutex::new(None))), + MAX_GRPC_DECODE_SIZE, + ); + let request = Request::builder() + .uri("/openshell.v1.OpenShell/CreateSandbox") + .header("grpc-encoding", "gzip") + .body(boxed_body_from_bytes(grpc_frame(&[]))) + .unwrap(); + let response = service.ready().await.unwrap().call(request).await.unwrap(); + assert_eq!( + status_from_response(&response).code(), + tonic::Code::Unimplemented + ); + assert_eq!(calls.load(Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn intercepted_grpc_body_collection_preserves_body_status() { + let status = tonic::Status::with_error_details( + tonic::Code::InvalidArgument, + "rejected", + openshell_core::rpc_error::ErrorDetails::with_error_info( + openshell_core::rpc_error::UNKNOWN_PROTOBUF_FIELD, + openshell_core::rpc_error::ERROR_DOMAIN, + std::collections::HashMap::new(), + ), + ); + let body = BoxBody( + StreamBody::new(futures::stream::iter([Err::< + http_body::Frame, + Box, + >(Box::new(status))])) + .boxed_unsync(), + ); + let collected = collect_intercepted_grpc_body(body).await.unwrap_err(); + assert_eq!(collected.code(), tonic::Code::InvalidArgument); + assert_eq!(collected.message(), "rejected"); + assert!(openshell_core::rpc_error::decode_details(&collected).is_some()); + } + #[derive(Clone, Default)] struct ReplayTestInterceptor { modifications: Arc, diff --git a/crates/openshell-server/src/wire_validation/ingress.rs b/crates/openshell-server/src/wire_validation/ingress.rs new file mode 100644 index 0000000000..4432150d3a --- /dev/null +++ b/crates/openshell-server/src/wire_validation/ingress.rs @@ -0,0 +1,720 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Ingress gRPC frame validation (RFC 0027). +//! +//! Each compiled gateway RPC has a static disposition. `Strict` RPCs have +//! every uncompressed request frame scanned before Gateway Interceptors or +//! `tonic` decode it. During `0.x`, `sandbox`, `peer`, and `supervisor` RPCs +//! stay exempt unless their request reaches a policy type. + +use std::collections::{HashMap, HashSet}; +use std::pin::Pin; +use std::sync::LazyLock; +use std::task::{Context, Poll, ready}; + +use bytes::{Buf, Bytes, BytesMut}; +use http_body::{Body, Frame}; +use prost_reflect::{Kind, MessageDescriptor}; +use tonic::Status; + +use super::{DESCRIPTORS, ScanOptions, WireRejection}; +use crate::auth::descriptor_authz; +use crate::auth::method_authz::AuthMode; + +/// Packages whose services the gateway serves. +const GATEWAY_PACKAGES: &[&str] = &["openshell.v1", "openshell.supervisor.host.v1"]; + +/// Messages whose presence in a request makes the RPC strict on any auth mode. +const POLICY_TYPES: &[&str] = &[ + "openshell.sandbox.v1.SandboxPolicy", + "openshell.sandbox.v1.NetworkPolicyRule", + "openshell.sandbox.v1.NetworkEndpoint", +]; + +const GRPC_FRAME_HEADER_LEN: usize = 5; + +/// How the gateway treats a method's request frames. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Disposition { + /// Reject unknown fields and enum values. + Strict, + /// Pass frames to `tonic` unchanged. + Ignore, +} + +/// Static ingress metadata for one compiled RPC. +#[derive(Debug)] +pub struct IngressMethod { + pub disposition: Disposition, + pub input: MessageDescriptor, + pub client_streaming: bool, + /// `openshell.v1.OpenShell` style service name, for metrics. + pub service: String, + pub method: String, +} + +static METHODS: LazyLock> = LazyLock::new(build_methods); + +/// Ingress metadata for a gRPC request path, if the gateway compiles it. +pub fn method(path: &str) -> Option<&'static IngressMethod> { + METHODS.get(path) +} + +fn build_methods() -> HashMap { + let policy_types: HashSet<&str> = POLICY_TYPES.iter().copied().collect(); + let mut methods = HashMap::new(); + for service in DESCRIPTORS.services() { + if !GATEWAY_PACKAGES.contains(&service.parent_file().package_name()) { + continue; + } + for method in service.methods() { + let path = format!("/{}/{}", service.full_name(), method.name()); + let input = method.input(); + let auth_mode = descriptor_authz::lookup(&path).map(|entry| entry.auth_mode); + let disposition = disposition(auth_mode, reaches_any(&input, &policy_types)); + methods.insert( + path, + IngressMethod { + disposition, + input, + client_streaming: method.is_client_streaming(), + service: service.full_name().to_string(), + method: method.name().to_string(), + }, + ); + } + } + methods +} + +fn disposition(auth_mode: Option, carries_policy: bool) -> Disposition { + match auth_mode { + Some( + AuthMode::Unauthenticated | AuthMode::Bearer | AuthMode::Operator | AuthMode::Dual, + ) => Disposition::Strict, + // Internal runtime and HA peer protocols stay exempt during 0.x + // unless a policy can ride along (RFC 0027). + Some(AuthMode::Sandbox | AuthMode::Peer | AuthMode::Supervisor) | None => { + if carries_policy { + Disposition::Strict + } else { + Disposition::Ignore + } + } + } +} + +/// Whether `root`'s transitive message closure contains any of `targets`. +fn reaches_any(root: &MessageDescriptor, targets: &HashSet<&str>) -> bool { + let mut seen = HashSet::new(); + let mut stack = vec![root.clone()]; + while let Some(message) = stack.pop() { + if !seen.insert(message.full_name().to_string()) { + continue; + } + if targets.contains(message.full_name()) { + return true; + } + for field in message.fields() { + if let Kind::Message(child) = field.kind() { + stack.push(child); + } + } + } + false +} + +/// Count and convert a scanner rejection into the ingress status. +fn reject(method: &IngressMethod, rejection: WireRejection) -> Status { + if matches!(rejection, WireRejection::Violations { .. }) { + metrics::counter!( + "openshell_server_grpc_unknown_fields_total", + "service" => method.service.clone(), + "method" => method.method.clone(), + ) + .increment(1); + } + rejection.into_status() +} + +/// Incremental gRPC length-prefixed frame reassembler. +/// +/// HTTP/2 `DATA` chunks may split one frame or coalesce several. The header +/// is checked as soon as its five bytes arrive, so an oversized or compressed +/// frame is refused before its payload is buffered. +#[derive(Debug)] +struct FrameDecoder { + buffer: BytesMut, + max_message_bytes: usize, +} + +impl FrameDecoder { + fn new(max_message_bytes: usize) -> Self { + Self { + buffer: BytesMut::new(), + max_message_bytes, + } + } + + fn push(&mut self, data: &mut impl Buf) { + while data.has_remaining() { + let chunk = data.chunk(); + self.buffer.extend_from_slice(chunk); + let len = chunk.len(); + data.advance(len); + } + } + + /// The next complete frame, header included. + fn next_frame(&mut self) -> Result, Status> { + if self.buffer.len() < GRPC_FRAME_HEADER_LEN { + return Ok(None); + } + if self.buffer[0] != 0 { + return Err(Status::unimplemented( + "compressed gRPC request frames are not supported", + )); + } + let length = u32::from_be_bytes([ + self.buffer[1], + self.buffer[2], + self.buffer[3], + self.buffer[4], + ]); + let length = usize::try_from(length).unwrap_or(usize::MAX); + if length > self.max_message_bytes { + return Err(Status::resource_exhausted(format!( + "gRPC message length {length} exceeds limit of {} bytes", + self.max_message_bytes + ))); + } + let total = GRPC_FRAME_HEADER_LEN + length; + if self.buffer.len() < total { + return Ok(None); + } + Ok(Some(self.buffer.split_to(total).freeze())) + } + + fn is_empty(&self) -> bool { + self.buffer.is_empty() + } +} + +fn truncated_frame() -> Status { + Status::invalid_argument("gRPC request ended inside a message frame") +} + +fn scan_frame(method: &IngressMethod, frame: &[u8]) -> Result<(), Status> { + super::scan( + &method.input, + &frame[GRPC_FRAME_HEADER_LEN..], + ScanOptions::default(), + ) + .map_err(|rejection| reject(method, rejection)) +} + +fn status_from_body_error(error: Box) -> Status { + Status::from_error(error) +} + +/// Read and validate the single request message of a unary or +/// server-streaming RPC. +/// +/// Returns the frame bytes unchanged, or no bytes when the body is empty so +/// `tonic` reports the missing message. +pub async fn collect_single_frame( + method: &IngressMethod, + mut body: B, + max_message_bytes: usize, +) -> Result +where + B: Body> + Unpin, +{ + use http_body_util::BodyExt; + + let mut decoder = FrameDecoder::new(max_message_bytes); + let mut message: Option = None; + while let Some(frame) = body.frame().await { + let frame = frame.map_err(status_from_body_error)?; + let Ok(mut data) = frame.into_data() else { + continue; + }; + if message.is_some() && data.has_remaining() { + return Err(second_message()); + } + decoder.push(&mut data); + if let Some(frame) = decoder.next_frame()? { + if !decoder.is_empty() { + return Err(second_message()); + } + scan_frame(method, &frame)?; + message = Some(frame); + } + } + if !decoder.is_empty() { + return Err(truncated_frame()); + } + Ok(message.unwrap_or_default()) +} + +fn second_message() -> Status { + Status::invalid_argument("unary gRPC request must contain exactly one message") +} + +/// Request body that validates each frame of a client-streaming RPC before +/// passing it on unchanged. +/// +/// A rejected frame surfaces as a body error carrying the `tonic::Status`, so +/// `tonic::Status::from_error` hands handlers the exact code and details. +pub struct ValidatingBody { + inner: B, + method: &'static IngressMethod, + decoder: FrameDecoder, + pending_error: Option, + finished: bool, +} + +impl ValidatingBody { + pub fn new(inner: B, method: &'static IngressMethod, max_message_bytes: usize) -> Self { + Self { + inner, + method, + decoder: FrameDecoder::new(max_message_bytes), + pending_error: None, + finished: false, + } + } + + /// Validated complete frames, or the first error after them. + fn drain(&mut self) -> Option> { + let mut validated = BytesMut::new(); + loop { + match self.decoder.next_frame() { + Ok(Some(frame)) => { + if let Err(status) = scan_frame(self.method, &frame) { + self.pending_error = Some(status); + break; + } + validated.extend_from_slice(&frame); + } + Ok(None) => break, + Err(status) => { + self.pending_error = Some(status); + break; + } + } + } + if !validated.is_empty() { + return Some(Ok(validated.freeze())); + } + self.pending_error.take().map(Err) + } + + fn fail(&mut self, status: Status) -> Poll, BodyError>>> { + self.finished = true; + Poll::Ready(Some(Err(Box::new(status)))) + } +} + +type BodyError = Box; + +impl Body for ValidatingBody +where + B: Body + Unpin, +{ + type Data = Bytes; + type Error = BodyError; + + fn poll_frame( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { + let this = self.get_mut(); + loop { + if let Some(status) = this.pending_error.take() { + return this.fail(status); + } + if this.finished { + return Poll::Ready(None); + } + match this.drain() { + Some(Ok(data)) => return Poll::Ready(Some(Ok(Frame::data(data)))), + Some(Err(status)) => return this.fail(status), + None => {} + } + match ready!(Pin::new(&mut this.inner).poll_frame(cx)) { + Some(Ok(frame)) => match frame.into_data() { + Ok(mut data) => this.decoder.push(&mut data), + Err(frame) => return Poll::Ready(Some(Ok(frame))), + }, + Some(Err(error)) => { + this.finished = true; + return Poll::Ready(Some(Err(error))); + } + None => { + if !this.decoder.is_empty() { + return this.fail(truncated_frame()); + } + this.finished = true; + return Poll::Ready(None); + } + } + } + } + + fn is_end_stream(&self) -> bool { + self.finished + } +} + +/// Test support: a `tonic` request stream whose raw `frames` (message +/// payloads, without gRPC headers) pass through ingress validation for +/// `path`, as they would behind the gateway's multiplexer. +#[cfg(test)] +pub fn validated_request_stream(path: &str, frames: &[Vec]) -> tonic::Streaming +where + T: prost::Message + Default + Send + 'static, +{ + struct Decode(std::marker::PhantomData); + + impl tonic::codec::Decoder for Decode { + type Item = T; + type Error = Status; + + fn decode(&mut self, buf: &mut tonic::codec::DecodeBuf<'_>) -> Result, Status> { + T::decode(buf) + .map(Some) + .map_err(|error| Status::internal(error.to_string())) + } + } + + let mut body = Vec::new(); + for frame in frames { + body.push(0); + body.extend_from_slice(&u32::try_from(frame.len()).unwrap().to_be_bytes()); + body.extend_from_slice(frame); + } + let method = method(path).unwrap_or_else(|| panic!("missing ingress method {path}")); + let body = http_body_util::BodyExt::map_err( + http_body_util::Full::new(Bytes::from(body)), + |never: std::convert::Infallible| -> BodyError { match never {} }, + ); + tonic::Streaming::new_request( + Decode(std::marker::PhantomData), + ValidatingBody::new(body, method, usize::MAX), + None, + None, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::wire_validation::write_varint; + use http_body_util::{BodyExt, StreamBody}; + use openshell_core::proto::{ + ExecSandboxInput, ExecSandboxRequest, GetSandboxRequest, exec_sandbox_input, + }; + use openshell_core::rpc_error; + use prost::Message; + + const MAX: usize = 1_048_576; + + fn frame(payload: &[u8]) -> Vec { + let mut out = vec![0]; + out.extend_from_slice(&u32::try_from(payload.len()).unwrap().to_be_bytes()); + out.extend_from_slice(payload); + out + } + + fn with_unknown(mut payload: Vec, tag: u32) -> Vec { + write_varint(&mut payload, u64::from(tag) << 3); + write_varint(&mut payload, 1); + payload + } + + type TestBody = http_body_util::combinators::UnsyncBoxBody; + + /// A body that yields `chunks` as separate `DATA` frames. + fn chunked(chunks: Vec>) -> TestBody { + let frames = chunks + .into_iter() + .map(|chunk| Ok::<_, BodyError>(Frame::data(Bytes::from(chunk)))); + StreamBody::new(futures::stream::iter(frames)).boxed_unsync() + } + + fn path_method(path: &str) -> &'static IngressMethod { + method(path).unwrap_or_else(|| panic!("missing {path}")) + } + + fn unknown_field_reason(status: &Status) -> Option { + rpc_error::decode_details(status) + .and_then(|details| details.error_info().map(|info| info.reason.clone())) + } + + #[test] + fn every_compiled_gateway_rpc_has_a_disposition() { + descriptor_authz::init().unwrap(); + let mut compiled = 0; + for service in DESCRIPTORS.services() { + if !GATEWAY_PACKAGES.contains(&service.parent_file().package_name()) { + continue; + } + for rpc in service.methods() { + compiled += 1; + let path = format!("/{}/{}", service.full_name(), rpc.name()); + assert!( + descriptor_authz::lookup(&path).is_some(), + "{path} has no authorization entry" + ); + assert!(method(&path).is_some(), "{path} has no ingress disposition"); + } + } + assert_eq!(METHODS.len(), compiled); + } + + #[test] + fn streaming_dispositions_match_rfc() { + let expected = [ + ("/openshell.v1.OpenShell/ExecSandbox", Disposition::Strict), + ("/openshell.v1.OpenShell/WatchSandbox", Disposition::Strict), + ( + "/openshell.v1.ServiceDiscovery/WatchServiceRoutes", + Disposition::Strict, + ), + ( + "/openshell.v1.OpenShell/ExecSandboxInteractive", + Disposition::Strict, + ), + ("/openshell.v1.OpenShell/ForwardTcp", Disposition::Strict), + ( + "/openshell.v1.OpenShell/PushSandboxLogs", + Disposition::Ignore, + ), + ( + "/openshell.v1.OpenShell/ConnectSupervisor", + Disposition::Ignore, + ), + ("/openshell.v1.OpenShell/RelayStream", Disposition::Ignore), + ("/openshell.v1.OpenShell/PeerRelay", Disposition::Ignore), + ( + "/openshell.supervisor.host.v1.SupervisorHost/Attach", + Disposition::Ignore, + ), + ]; + for (path, disposition) in expected { + assert_eq!(path_method(path).disposition, disposition, "{path}"); + } + let streaming = METHODS + .values() + .filter(|method| method.client_streaming) + .count() + + DESCRIPTORS + .services() + .filter(|service| GATEWAY_PACKAGES.contains(&service.parent_file().package_name())) + .flat_map(|service| service.methods().collect::>()) + .filter(|method| method.is_server_streaming() && !method.is_client_streaming()) + .count(); + assert_eq!(streaming, expected.len(), "streaming RPC inventory changed"); + } + + #[test] + fn policy_bearing_internal_rpcs_are_strict() { + let submit = path_method("/openshell.v1.OpenShell/SubmitPolicyAnalysis"); + assert_eq!( + descriptor_authz::lookup("/openshell.v1.OpenShell/SubmitPolicyAnalysis") + .unwrap() + .auth_mode, + AuthMode::Sandbox + ); + assert_eq!(submit.disposition, Disposition::Strict); + assert_eq!( + path_method("/openshell.v1.OpenShell/UpdateConfig").disposition, + Disposition::Strict + ); + for (path, entry) in METHODS.iter() { + let auth_mode = descriptor_authz::lookup(path).unwrap().auth_mode; + let carries_policy = reaches_any(&entry.input, &POLICY_TYPES.iter().copied().collect()); + if carries_policy { + assert_eq!(entry.disposition, Disposition::Strict, "{path}"); + } + if matches!( + auth_mode, + AuthMode::Sandbox | AuthMode::Peer | AuthMode::Supervisor + ) && !carries_policy + { + assert_eq!(entry.disposition, Disposition::Ignore, "{path}"); + } + } + } + + #[tokio::test] + async fn unary_frame_split_across_chunks_is_accepted() { + let method = path_method("/openshell.v1.OpenShell/GetSandbox"); + let bytes = frame( + &GetSandboxRequest { + name: "demo".into(), + ..Default::default() + } + .encode_to_vec(), + ); + let chunks = bytes.chunks(2).map(<[u8]>::to_vec).collect(); + let collected = collect_single_frame(method, chunked(chunks), MAX) + .await + .unwrap(); + assert_eq!(collected.as_ref(), bytes.as_slice()); + } + + #[tokio::test] + async fn unary_unknown_field_is_rejected_with_details() { + let method = path_method("/openshell.v1.OpenShell/GetSandbox"); + let payload = with_unknown( + GetSandboxRequest { + name: "demo".into(), + ..Default::default() + } + .encode_to_vec(), + 900, + ); + let status = collect_single_frame(method, chunked(vec![frame(&payload)]), MAX) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + assert_eq!( + unknown_field_reason(&status).as_deref(), + Some(rpc_error::UNKNOWN_PROTOBUF_FIELD) + ); + } + + #[tokio::test] + async fn unary_framing_errors() { + let method = path_method("/openshell.v1.OpenShell/GetSandbox"); + let one = frame(&GetSandboxRequest::default().encode_to_vec()); + + let mut two = one.clone(); + two.extend_from_slice(&one); + let status = collect_single_frame(method, chunked(vec![two]), MAX) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + + let status = collect_single_frame(method, chunked(vec![one.clone(), one.clone()]), MAX) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + + let status = collect_single_frame(method, chunked(vec![vec![0, 0, 0, 0, 9, 1]]), MAX) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + + let mut compressed = one.clone(); + compressed[0] = 1; + let status = collect_single_frame(method, chunked(vec![compressed]), MAX) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::Unimplemented); + + assert!( + collect_single_frame(method, chunked(Vec::new()), MAX) + .await + .unwrap() + .is_empty() + ); + } + + #[tokio::test] + async fn oversized_frame_is_refused_from_its_header() { + let method = path_method("/openshell.v1.OpenShell/GetSandbox"); + let header = { + let mut header = vec![0]; + header.extend_from_slice(&u32::try_from(MAX + 1).unwrap().to_be_bytes()); + header + }; + let status = collect_single_frame(method, chunked(vec![header.clone()]), MAX) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::ResourceExhausted); + + // A larger per-route limit admits the same length. + let payload = vec![0u8; MAX + 1]; + let mut big = header; + big.extend_from_slice(&payload); + let status = collect_single_frame(method, chunked(vec![big]), MAX * 4) + .await + .unwrap_err(); + // The payload is not a valid GetSandboxRequest; the size check passed. + assert_ne!(status.code(), tonic::Code::ResourceExhausted); + } + + fn exec_start() -> Vec { + ExecSandboxInput { + payload: Some(exec_sandbox_input::Payload::Start(ExecSandboxRequest { + sandbox: "demo".into(), + command: vec!["sh".into()], + ..Default::default() + })), + } + .encode_to_vec() + } + + fn exec_stdin(data: &[u8]) -> Vec { + ExecSandboxInput { + payload: Some(exec_sandbox_input::Payload::Stdin(data.to_vec())), + } + .encode_to_vec() + } + + async fn drain_body(body: ValidatingBody) -> (Vec, Option) { + let mut body = body; + let mut data = Vec::new(); + while let Some(frame) = body.frame().await { + match frame { + Ok(frame) => data.extend_from_slice(&frame.into_data().unwrap()), + Err(error) => return (data, Some(Status::from_error(error))), + } + } + (data, None) + } + + #[tokio::test] + async fn streaming_frames_pass_through_unchanged() { + let method = path_method("/openshell.v1.OpenShell/ExecSandboxInteractive"); + let mut stream = frame(&exec_start()); + stream.extend_from_slice(&frame(&exec_stdin(b"echo hi\n"))); + stream.extend_from_slice(&frame(&exec_stdin(&[0xff; 64]))); + // Coalesced and split chunks. + let chunks = stream.chunks(7).map(<[u8]>::to_vec).collect(); + let (data, error) = drain_body(ValidatingBody::new(chunked(chunks), method, MAX)).await; + assert!(error.is_none()); + assert_eq!(data, stream); + } + + #[tokio::test] + async fn streaming_unknown_field_after_valid_frames_is_rejected() { + let method = path_method("/openshell.v1.OpenShell/ExecSandboxInteractive"); + let start = frame(&exec_start()); + let bad = frame(&with_unknown(exec_stdin(b"x"), 900)); + let mut stream = start.clone(); + stream.extend_from_slice(&bad); + let (data, error) = + drain_body(ValidatingBody::new(chunked(vec![stream]), method, MAX)).await; + assert_eq!(data, start, "frames before the rejected one pass through"); + let status = error.expect("validation error"); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + assert_eq!( + unknown_field_reason(&status).as_deref(), + Some(rpc_error::UNKNOWN_PROTOBUF_FIELD) + ); + } + + #[tokio::test] + async fn streaming_truncated_frame_is_rejected() { + let method = path_method("/openshell.v1.OpenShell/ExecSandboxInteractive"); + let mut start = frame(&exec_start()); + start.pop(); + let (_, error) = drain_body(ValidatingBody::new(chunked(vec![start]), method, MAX)).await; + assert_eq!(error.unwrap().code(), tonic::Code::InvalidArgument); + } +} diff --git a/crates/openshell-server/src/wire_validation/mod.rs b/crates/openshell-server/src/wire_validation/mod.rs index cf5cb901ff..b1339d6dee 100644 --- a/crates/openshell-server/src/wire_validation/mod.rs +++ b/crates/openshell-server/src/wire_validation/mod.rs @@ -19,6 +19,7 @@ // implementation steps 2 and 3). #![allow(dead_code)] +pub mod ingress; pub mod sandbox_policy; use std::collections::HashMap; diff --git a/docs/sdk/api-errors.mdx b/docs/sdk/api-errors.mdx index 661c52d66b..48fa5f7186 100644 --- a/docs/sdk/api-errors.mdx +++ b/docs/sdk/api-errors.mdx @@ -29,6 +29,7 @@ Recognized gateway reasons include the following. | Reason | Code | Recovery | |---|---|---| | `INVALID_ARGUMENT` | `INVALID_ARGUMENT` | Correct the fields listed in `BadRequest`. | +| `UNKNOWN_PROTOBUF_FIELD` | `INVALID_ARGUMENT` | The request uses a field or enum value the gateway does not know, usually because the client is newer than the gateway. `BadRequest` names each field as `#` for an unknown or reserved field number, or `` for an unrecognized enum value. `metadata.gateway_version` reports the gateway build. Upgrade the gateway or leave the newer fields unset. A rejected unary request or `ExecSandboxInteractive` start frame leaves its `request_id` unused. A rejected later stdin or resize frame ends an admitted execution, and that `request_id` follows the normal exec replay rules. | | `RESOURCE_VERSION_CONFLICT` | `ABORTED` | Read the resource again and construct a new conditional write. `metadata.recovery` is `REFRESH_STATE`; `current_resource_version` is included when known. | | `PROFILE_SOURCE_UNAVAILABLE` | `UNAVAILABLE` | Retry a profile snapshot read after at least the supplied delay. | | `DATABASE_UNAVAILABLE` | `UNAVAILABLE` | The gateway could not get a database connection within 5 seconds. Retry after at least the supplied delay. | From 5d3c2c6a4d454100ef0cf4fa6b6bdd1a34f8feaa Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Mon, 30 Nov 2026 22:38:03 +0000 Subject: [PATCH 03/10] feat(server): validate stored policies at the persistence boundary Implement step 3 of RFC 0027. Stored payloads that carry policy are scanned before prost decodes them, so a policy written by a newer gateway is refused instead of silently broadened: - Policy revisions and the global policy setting are scanned on load and fail with FAILED_PRECONDITION, which configuration delivery turns into a not-admitted configuration. Only the legacy NetworkBinary advisor flag is tolerated. - Draft chunks scan proposed_rule and both effective policies before the proposed rule is re-encoded. - Stored provider profiles scan their endpoint restrictions. - Sandbox.spec.policy is scanned from the raw row wherever it is evaluated, canonicalized, compared, or delivered. Sandbox writes through the store, and the policy-revision projection, keep the stored spec.policy bytes when the update leaves the policy this build understands unchanged, so an unrelated status or label update on an older gateway no longer erases newer restrictions. A test pins the durable roots that reach policy types. Make the oversized-configuration delivery test truncate providers with compare-and-swap. Its unconditional write raced the gateway's concurrent admission update and could be lost. Rejections count in openshell_server_stored_policy_unknown_fields_total. Refs #6097 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Mrunal Patel --- .../src/config_delivery/mod.rs | 116 +++++++- crates/openshell-server/src/grpc/mod.rs | 3 + crates/openshell-server/src/grpc/policy.rs | 50 ++++ .../src/grpc/policy/config_inputs.rs | 8 + .../openshell-server/src/persistence/mod.rs | 102 +++++++ .../src/persistence/postgres.rs | 6 +- .../src/persistence/sqlite.rs | 6 +- .../openshell-server/src/persistence/tests.rs | 215 ++++++++++++++ crates/openshell-server/src/policy_store.rs | 74 +++++ .../src/provider_profile_sources.rs | 6 +- crates/openshell-server/src/storage_proto.rs | 47 +++ .../src/wire_validation/mod.rs | 5 +- .../src/wire_validation/sandbox_policy.rs | 70 +++-- .../src/wire_validation/stored.rs | 279 ++++++++++++++++++ 14 files changed, 940 insertions(+), 47 deletions(-) create mode 100644 crates/openshell-server/src/wire_validation/stored.rs diff --git a/crates/openshell-server/src/config_delivery/mod.rs b/crates/openshell-server/src/config_delivery/mod.rs index 335c1a0b09..3066bb3df8 100644 --- a/crates/openshell-server/src/config_delivery/mod.rs +++ b/crates/openshell-server/src/config_delivery/mod.rs @@ -1732,6 +1732,110 @@ mod tests { } } + fn policy_with_unknown_field() -> Vec { + use prost::Message as _; + let mut policy = openshell_core::proto::SandboxPolicy { + version: 1, + ..Default::default() + } + .encode_to_vec(); + prost::encoding::encode_varint(900 << 3, &mut policy); + prost::encoding::encode_varint(1, &mut policy); + policy + } + + fn assert_not_admitted(built: Option) { + let Some(BuiltSandboxConfig::Rejected { + sandbox_config, + error_code, + .. + }) = built + else { + panic!("expected a rejected configuration"); + }; + assert_eq!(error_code, Code::FailedPrecondition); + assert!(!sandbox_config.configuration_admitted); + assert!(sandbox_config.policy.is_none()); + } + + #[tokio::test] + async fn stored_policy_revision_with_unknown_fields_is_not_admitted() { + use crate::policy_store::PolicyStoreExt as _; + + let state = push_state().await; + put_sandbox(&state, "sandbox", &[]).await; + state + .store + .put_policy_revision( + &uuid::Uuid::new_v4().to_string(), + "sandbox", + "default", + 1, + &policy_with_unknown_field(), + "hash", + ) + .await + .unwrap(); + + assert_not_admitted( + build_sandbox_config(&state, "sandbox", Vec::new()) + .await + .unwrap(), + ); + } + + #[tokio::test] + async fn sandbox_spec_policy_with_unknown_fields_is_not_admitted() { + use prost::Message as _; + + let state = push_state().await; + let sandbox = Sandbox { + metadata: Some(ObjectMeta { + id: "sandbox".into(), + name: "sandbox".into(), + workspace: "default".into(), + ..Default::default() + }), + spec: Some(SandboxSpec { + policy: Some(openshell_core::proto::SandboxPolicy { + version: 1, + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }; + let payload = crate::wire_validation::sandbox_policy::splice_spec_policy( + &sandbox.encode_to_vec(), + Some(&policy_with_unknown_field()), + ) + .unwrap(); + state + .store + .put("sandbox", "sandbox", "sandbox", "default", &payload, None) + .await + .unwrap(); + + assert_not_admitted( + build_sandbox_config(&state, "sandbox", Vec::new()) + .await + .unwrap(), + ); + let error = crate::grpc::policy::initialize_policy_history( + state.store.as_ref(), + &state + .store + .get_message::("sandbox") + .await + .unwrap() + .unwrap(), + crate::grpc::policy::InitialPolicyHistoryStatus::Pending, + ) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition); + } + #[test] fn fanout_marks_ten_thousand_sessions_once_each() { let delivery = ConfigDelivery::for_db_connections(5); @@ -2257,14 +2361,16 @@ mod tests { .await .unwrap(); - let mut sandbox = state + // Compare-and-swap: the gateway concurrently records the rejection + // admission on the same sandbox, and an unconditional write could + // lose to its update. + state .store - .get_message::("large-config") + .update_message_cas::("large-config", 0, |sandbox| { + sandbox.spec.as_mut().unwrap().providers.truncate(16); + }) .await - .unwrap() .unwrap(); - sandbox.spec.as_mut().unwrap().providers.truncate(16); - state.store.put_message(&sandbox).await.unwrap(); change_policy(&state, "large-config", 3).await; publish_sandbox(&state, "large-config"); let recovery = sent_config( diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index 5bfb592196..d17af2bb5b 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -123,6 +123,9 @@ pub fn persistence_error_to_status( format!("{operation} failed: the database is unavailable; retry the request"), std::time::Duration::from_secs(1), ), + error @ PersistenceError::UnknownFields(_) => { + Status::failed_precondition(format!("{operation} failed: {error}")) + } other => Status::internal(format!("{operation} failed: {other}")), } } diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index b9d5fa8fff..c4ece458b6 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -2002,6 +2002,9 @@ async fn current_effective_policy_from_records( .await .map_err(|e| Status::internal(format!("fetch latest policy failed: {e}")))? }; + if global_policy.is_none() && latest_policy.is_none() { + require_known_spec_policy(state.store.as_ref(), sandbox).await?; + } effective_policy_from_captured_inputs( catalog, records, @@ -2436,6 +2439,7 @@ pub(super) async fn current_base_policy_for_sandbox( let (policy, _) = canonical_policy_record_identity(&record)?; return Ok(policy); } + require_known_spec_policy(store, sandbox).await?; sandbox .spec .as_ref() @@ -3013,6 +3017,7 @@ async fn build_sandbox_config_snapshot_with_sources( match spec.policy.clone() { None => (None, 0, String::new(), PolicySource::Sandbox), Some(spec_policy) => { + require_known_spec_policy(state.store.as_ref(), sandbox).await?; let spec_policy = validate_and_canonicalize_stored_policy( spec_policy, STORED_POLICY_SOURCE_SPEC, @@ -3236,6 +3241,7 @@ pub async fn initialize_policy_history( { return Ok(false); } + require_known_spec_policy(store, sandbox).await?; let policy = validate_and_canonicalize_stored_policy(policy.clone(), STORED_POLICY_SOURCE_SPEC)?; store @@ -4662,6 +4668,8 @@ async fn handle_update_config_inner( .map_err(|error| { super::persistence_error_to_status(error, "acquire policy mutation lock") })?; + // Merges build on, and replacements compare against, the spec baseline. + require_known_spec_policy(state.store.as_ref(), &sandbox).await?; if has_merge_ops { let global_settings = load_global_settings(state.store.as_ref()).await?; if global_settings.settings.contains_key(POLICY_SETTING_KEY) { @@ -7082,6 +7090,40 @@ pub(super) async fn handle_get_draft_history( // Policy helper functions // --------------------------------------------------------------------------- +/// Refuse a sandbox spec policy whose stored bytes carry restrictions this +/// build would drop (RFC 0027). +/// +/// The decoded `Sandbox` has already lost unknown fields, so read the raw +/// row. Call before evaluating, canonicalizing, comparing, or delivering a +/// spec policy. +pub async fn require_known_spec_policy(store: &Store, sandbox: &Sandbox) -> Result<(), Status> { + if sandbox + .spec + .as_ref() + .and_then(|spec| spec.policy.as_ref()) + .is_none() + { + return Ok(()); + } + let Some(record) = store + .get(Sandbox::object_type(), sandbox.object_id()) + .await + .map_err(|error| super::persistence_error_to_status(error, "fetch sandbox"))? + else { + return Ok(()); + }; + let payload = + crate::persistence::migrate_legacy_time_fields(Sandbox::object_type(), &record.payload) + .map_err(|error| Status::internal(format!("decode sandbox failed: {error}")))?; + match crate::wire_validation::sandbox_policy::extract_spec_policy(&payload) { + Ok(Some(policy)) => crate::wire_validation::stored::require_known_stored_policy( + &policy, + crate::wire_validation::stored::StoredPolicySource::Spec, + ), + Ok(None) | Err(_) => Ok(()), + } +} + /// Rebuilds a policy revision's identity from its checked canonical payload. /// /// `PolicyRecord::policy_hash` is persisted metadata and cannot prove what the @@ -7090,6 +7132,10 @@ pub(super) async fn handle_get_draft_history( fn canonical_policy_record_identity( record: &PolicyRecord, ) -> Result<(ProtoSandboxPolicy, String), Status> { + crate::wire_validation::stored::require_known_stored_policy( + record.policy_payload.as_slice(), + crate::wire_validation::stored::StoredPolicySource::History, + )?; let decoded = decode_stored_policy(record.policy_payload.as_slice()) .map_err(|error| Status::internal(format!("decode policy revision failed: {error}")))?; let policy = validate_and_canonicalize_stored_policy(decoded, STORED_POLICY_SOURCE_HISTORY)?; @@ -8375,6 +8421,10 @@ fn decode_policy_from_global_settings( let raw = hex::decode(encoded) .map_err(|e| Status::internal(format!("global policy decode failed: {e}")))?; + crate::wire_validation::stored::require_known_stored_policy( + raw.as_slice(), + crate::wire_validation::stored::StoredPolicySource::Global, + )?; let policy = decode_stored_policy(raw.as_slice()) .map_err(|e| Status::internal(format!("global policy protobuf decode failed: {e}")))?; validate_and_canonicalize_stored_policy(policy, STORED_POLICY_SOURCE_GLOBAL).map(Some) diff --git a/crates/openshell-server/src/grpc/policy/config_inputs.rs b/crates/openshell-server/src/grpc/policy/config_inputs.rs index f8905bc992..485792a7a1 100644 --- a/crates/openshell-server/src/grpc/policy/config_inputs.rs +++ b/crates/openshell-server/src/grpc/policy/config_inputs.rs @@ -68,6 +68,14 @@ pub async fn load_sandbox_config_inputs( .map_err(|e| Status::internal(format!("fetch policy history failed: {e}"))) }, )?; + // Without history or a global override, the spec policy is the source. + if latest_policy.is_none() + && !global_settings + .settings + .contains_key(super::POLICY_SETTING_KEY) + { + super::require_known_spec_policy(store, &sandbox).await?; + } Ok(SandboxConfigInputs { sandbox, catalog, diff --git a/crates/openshell-server/src/persistence/mod.rs b/crates/openshell-server/src/persistence/mod.rs index cb8ee48173..1b01f83805 100644 --- a/crates/openshell-server/src/persistence/mod.rs +++ b/crates/openshell-server/src/persistence/mod.rs @@ -59,6 +59,10 @@ pub enum PersistenceError { Migration(String), #[error("decode error: {0}")] Decode(String), + /// A stored policy-bearing payload uses protobuf fields or enum values + /// this build does not know (RFC 0027). Decoding it would drop them. + #[error("stored payload uses unknown fields: {0}")] + UnknownFields(String), #[error("encode error: {0}")] Encode(String), #[error("pagination error: {0}")] @@ -341,12 +345,30 @@ fn decode_record( record: ObjectRecord, ) -> PersistenceResult { let payload = legacy_time_wire::migrate(T::object_type(), &record.payload)?; + require_known_policy_fields(T::object_type(), &payload)?; let mut message = T::decode(payload.as_slice()) .map_err(|e| PersistenceError::Decode(format!("protobuf decode error: {e}")))?; message.set_resource_version(record.resource_version); Ok(message) } +/// Refuse a stored payload whose policy restrictions this build would drop. +/// +/// Only object types whose generic decode reaches policy restrictions are +/// scanned here; policy revisions, drafts, and sandbox spec policies are +/// checked where policy is loaded. +fn require_known_policy_fields(object_type: &str, payload: &[u8]) -> PersistenceResult<()> { + if object_type != ::object_type() { + return Ok(()); + } + match crate::wire_validation::stored::scan_stored_provider_profile(payload) { + Ok(()) | Err(crate::wire_validation::WireRejection::Malformed(_)) => Ok(()), + Err(rejection) => Err(PersistenceError::UnknownFields(format!( + "provider profile endpoints: {rejection}" + ))), + } +} + /// Dispatch a method call to the underlying store implementation. /// /// Every `Store` method is a two-arm `match self { Postgres(s) => s.method(...).await, … }` @@ -645,6 +667,19 @@ impl Store { labels: Option<&str>, condition: WriteCondition, ) -> PersistenceResult { + let expected_version = match condition { + WriteCondition::MustCreate => None, + WriteCondition::MatchResourceVersion(version) => Some(Some(version)), + WriteCondition::Unconditional => Some(None), + }; + let payload = match expected_version { + Some(expected_version) => { + self.preserve_sandbox_spec_policy(object_type, id, payload, expected_version) + .await? + } + None => std::borrow::Cow::Borrowed(payload), + }; + let payload = payload.as_ref(); store_dispatch_traced!(self.put_if( object_type, id, @@ -656,6 +691,42 @@ impl Store { )) } + /// Keep the stored `Sandbox.spec.policy` bytes on a sandbox update that did + /// not change the policy this build understands (RFC 0027). + /// + /// A sandbox written by a newer gateway may carry policy restrictions this + /// build decodes away. Without this, an unrelated update such as a status + /// or label change would erase them from storage. The splice applies only + /// when the stored row is the version being replaced; any doubt leaves + /// `payload` unchanged. + async fn preserve_sandbox_spec_policy<'a>( + &self, + object_type: &str, + id: &str, + payload: &'a [u8], + expected_version: Option, + ) -> PersistenceResult> { + use std::borrow::Cow; + if object_type != ::object_type() { + return Ok(Cow::Borrowed(payload)); + } + let Some(stored) = self.get(object_type, id).await? else { + return Ok(Cow::Borrowed(payload)); + }; + if expected_version.is_some_and(|version| version != stored.resource_version) { + return Ok(Cow::Borrowed(payload)); + } + let Ok(stored) = legacy_time_wire::migrate(object_type, &stored.payload) else { + return Ok(Cow::Borrowed(payload)); + }; + Ok( + match crate::wire_validation::sandbox_policy::preserve_spec_policy(&stored, payload) { + Ok(Some(spliced)) => Cow::Owned(spliced), + Ok(None) | Err(_) => Cow::Borrowed(payload), + }, + ) + } + /// Create an object that is safe to lose in a crash. /// /// Behaves like [`Self::put_if`] with [`WriteCondition::MustCreate`], but @@ -731,6 +802,29 @@ impl Store { &self, writes: &[AtomicWrite], ) -> PersistenceResult>> { + let mut preserved: Option> = None; + for (index, write) in writes.iter().enumerate() { + let AtomicWrite::Update { + object_type, + id, + payload, + expected_version, + .. + } = write + else { + continue; + }; + if let std::borrow::Cow::Owned(spliced) = self + .preserve_sandbox_spec_policy(object_type, id, payload, Some(*expected_version)) + .await? + { + let owned = preserved.get_or_insert_with(|| writes.to_vec()); + if let AtomicWrite::Update { payload, .. } = &mut owned[index] { + *payload = spliced; + } + } + } + let writes = preserved.as_deref().unwrap_or(writes); store_dispatch_traced!(self.write_atomically(writes)) } @@ -752,6 +846,10 @@ impl Store { payload: &[u8], labels: Option<&str>, ) -> PersistenceResult<()> { + let payload = self + .preserve_sandbox_spec_policy(object_type, id, payload, None) + .await?; + let payload = payload.as_ref(); store_dispatch_traced!(self.put_scoped( object_type, id, @@ -1709,6 +1807,10 @@ impl Store { payload: &[u8], labels: Option<&str>, ) -> PersistenceResult<()> { + let payload = self + .preserve_sandbox_spec_policy(object_type, id, payload, None) + .await?; + let payload = payload.as_ref(); store_dispatch_traced!(self.put(object_type, id, name, workspace, payload, labels)) } diff --git a/crates/openshell-server/src/persistence/postgres.rs b/crates/openshell-server/src/persistence/postgres.rs index d212d85ba9..f5ae59f4a6 100644 --- a/crates/openshell-server/src/persistence/postgres.rs +++ b/crates/openshell-server/src/persistence/postgres.rs @@ -19,7 +19,6 @@ use crate::policy_store::{ }; use openshell_core::SetResourceVersion; use openshell_core::proto::Sandbox; -use prost::Message; use sqlx::pool::PoolConnection; use sqlx::postgres::PgPoolOptions; use sqlx::{Connection, Postgres, QueryBuilder, Row}; @@ -2045,7 +2044,10 @@ WHERE object_type = 'sandbox' AND id = $1 AND resource_version = $4 ", ) .bind(&write.sandbox_id) - .bind(sandbox.encode_to_vec()) + .bind(crate::policy_store::encode_projected_sandbox( + &sandbox_payload, + &sandbox, + )?) .bind(now_ms) .bind(i64::try_from(current_version).unwrap_or(i64::MAX)) .execute(&mut *tx) diff --git a/crates/openshell-server/src/persistence/sqlite.rs b/crates/openshell-server/src/persistence/sqlite.rs index b98b65ce3d..591a52140c 100644 --- a/crates/openshell-server/src/persistence/sqlite.rs +++ b/crates/openshell-server/src/persistence/sqlite.rs @@ -14,7 +14,6 @@ use crate::policy_store::{ use openshell_core::SetResourceVersion; use openshell_core::paths::set_file_owner_only; use openshell_core::proto::Sandbox; -use prost::Message; use sqlx::sqlite::{ SqliteConnectOptions, SqliteConnection, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous, }; @@ -1611,7 +1610,10 @@ WHERE "object_type" = 'sandbox' AND "id" = ?1 AND "resource_version" = ?4 "#, ) .bind(&write.sandbox_id) - .bind(sandbox.encode_to_vec()) + .bind(crate::policy_store::encode_projected_sandbox( + &sandbox_payload, + &sandbox, + )?) .bind(now_ms) .bind(i64::try_from(current_version).unwrap_or(i64::MAX)) .execute(&mut *tx) diff --git a/crates/openshell-server/src/persistence/tests.rs b/crates/openshell-server/src/persistence/tests.rs index 62069afdaf..20fcdad4ae 100644 --- a/crates/openshell-server/src/persistence/tests.rs +++ b/crates/openshell-server/src/persistence/tests.rs @@ -3331,3 +3331,218 @@ async fn postgres_atomic_write_groups_run_on_a_one_connection_pool() { drop(store); schema.drop_schema().await; } + +/// Encode `sandbox` with `policy` as the raw bytes of its `spec.policy`. +fn sandbox_with_raw_policy(sandbox: &Sandbox, policy: &[u8]) -> Vec { + crate::wire_validation::sandbox_policy::splice_spec_policy( + &sandbox.encode_to_vec(), + Some(policy), + ) + .unwrap() +} + +/// Append an unknown varint field, as a newer gateway's restriction would. +fn with_unknown_field(mut payload: Vec, tag: u64) -> Vec { + prost::encoding::encode_varint(tag << 3, &mut payload); + prost::encoding::encode_varint(1, &mut payload); + payload +} + +fn rfc0027_sandbox(id: &str) -> Sandbox { + Sandbox { + metadata: Some(ProtoObjectMeta { + id: id.to_string(), + name: id.to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + spec: Some(SandboxSpec { + policy: Some(SandboxPolicy { + version: 1, + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + } +} + +async fn stored_spec_policy(store: &Store, id: &str) -> Option> { + let record = store + .get(Sandbox::object_type(), id) + .await + .unwrap() + .unwrap(); + crate::wire_validation::sandbox_policy::extract_spec_policy(&record.payload).unwrap() +} + +#[tokio::test] +async fn sandbox_updates_preserve_newer_spec_policy_bytes() { + let store = test_store().await; + let sandbox = rfc0027_sandbox("sandbox-newer-policy"); + let known = sandbox.spec.as_ref().unwrap().policy.clone().unwrap(); + let newer = with_unknown_field(known.encode_to_vec(), 900); + store + .put( + Sandbox::object_type(), + "sandbox-newer-policy", + "sandbox-newer-policy", + "default", + &sandbox_with_raw_policy(&sandbox, &newer), + None, + ) + .await + .unwrap(); + + // An unrelated read-modify-write keeps the newer restriction. + store + .update_message_cas::("sandbox-newer-policy", 0, |sandbox| { + sandbox + .metadata + .as_mut() + .unwrap() + .labels + .insert("team".to_string(), "infra".to_string()); + }) + .await + .unwrap(); + assert_eq!( + stored_spec_policy(&store, "sandbox-newer-policy").await, + Some(newer.clone()) + ); + let mut current = store + .get_message::("sandbox-newer-policy") + .await + .unwrap() + .unwrap(); + assert_eq!(current.metadata.as_ref().unwrap().labels["team"], "infra"); + + // So does an unconditional rewrite and an atomic group update. + store.put_message(¤t).await.unwrap(); + assert_eq!( + stored_spec_policy(&store, "sandbox-newer-policy").await, + Some(newer.clone()) + ); + let record = store + .get(Sandbox::object_type(), "sandbox-newer-policy") + .await + .unwrap() + .unwrap(); + store + .write_atomically(&[super::AtomicWrite::Update { + object_type: Sandbox::object_type().to_string(), + id: "sandbox-newer-policy".to_string(), + payload: current.encode_to_vec(), + expected_version: record.resource_version, + }]) + .await + .unwrap(); + assert_eq!( + stored_spec_policy(&store, "sandbox-newer-policy").await, + Some(newer) + ); + + // An intentional replacement wins. + let replacement = SandboxPolicy { + version: 2, + ..Default::default() + }; + current.spec.as_mut().unwrap().policy = Some(replacement.clone()); + store.put_message(¤t).await.unwrap(); + assert_eq!( + stored_spec_policy(&store, "sandbox-newer-policy").await, + Some(replacement.encode_to_vec()) + ); +} + +#[tokio::test] +async fn policy_revision_projection_preserves_newer_spec_policy_bytes() { + let store = test_store().await; + let sandbox = rfc0027_sandbox("sandbox-projection"); + let known = sandbox.spec.as_ref().unwrap().policy.clone().unwrap(); + let newer = with_unknown_field(known.encode_to_vec(), 900); + store + .put( + Sandbox::object_type(), + "sandbox-projection", + "sandbox-projection", + "default", + &sandbox_with_raw_policy(&sandbox, &newer), + None, + ) + .await + .unwrap(); + + store + .put_policy_revision_atomic(&AtomicPolicyRevisionWrite { + id: "projection-revision".to_string(), + sandbox_id: "sandbox-projection".to_string(), + workspace: "default".to_string(), + version: 1, + policy_payload: known.encode_to_vec(), + policy_hash: "hash".to_string(), + provenance: StdHashMap::new(), + expected_resource_version: 0, + annotations: StdHashMap::from([("note".to_string(), "projected".to_string())]), + backfill_policy: Some(known), + }) + .await + .unwrap(); + + assert_eq!( + stored_spec_policy(&store, "sandbox-projection").await, + Some(newer) + ); +} + +#[tokio::test] +async fn provider_profiles_with_unknown_endpoint_fields_fail_to_load() { + use crate::storage_proto::StoredProviderProfile; + use openshell_core::proto::{NetworkEndpoint, ProviderProfile}; + + let store = test_store().await; + let mut profile = ProviderProfile { + id: "custom".to_string(), + ..Default::default() + } + .encode_to_vec(); + // ProviderProfile.endpoints (tag 6) with a newer endpoint restriction. + let endpoint = with_unknown_field( + NetworkEndpoint { + host: "api.example.com".to_string(), + port: 443, + ..Default::default() + } + .encode_to_vec(), + 900, + ); + prost::encoding::encode_key(6, prost::encoding::WireType::LengthDelimited, &mut profile); + prost::encoding::encode_varint(endpoint.len() as u64, &mut profile); + profile.extend_from_slice(&endpoint); + let mut stored = Vec::new(); + prost::encoding::encode_key(2, prost::encoding::WireType::LengthDelimited, &mut stored); + prost::encoding::encode_varint(profile.len() as u64, &mut stored); + stored.extend_from_slice(&profile); + store + .put( + StoredProviderProfile::object_type(), + "custom-id", + "custom", + "default", + &stored, + None, + ) + .await + .unwrap(); + + let error = store + .get_message::("custom-id") + .await + .unwrap_err(); + assert!( + matches!(error, PersistenceError::UnknownFields(_)), + "{error}" + ); + let status = crate::grpc::persistence_error_to_status(error, "fetch provider profile"); + assert_eq!(status.code(), tonic::Code::FailedPrecondition); +} diff --git a/crates/openshell-server/src/policy_store.rs b/crates/openshell-server/src/policy_store.rs index c610f21fb8..efa6abd24b 100644 --- a/crates/openshell-server/src/policy_store.rs +++ b/crates/openshell-server/src/policy_store.rs @@ -135,6 +135,20 @@ pub fn project_policy_revision_onto_sandbox( Ok((sandbox, changed)) } +/// Encode a sandbox produced by [`project_policy_revision_onto_sandbox`], +/// keeping the stored `spec.policy` bytes when the projection left the policy +/// this build understands unchanged (RFC 0027). +pub fn encode_projected_sandbox( + stored_payload: &[u8], + sandbox: &Sandbox, +) -> PersistenceResult> { + let stored = crate::persistence::migrate_legacy_time_fields("sandbox", stored_payload)?; + Ok( + crate::wire_validation::sandbox_policy::encode_preserving_spec_policy(&stored, sandbox) + .unwrap_or_else(|_| sandbox.encode_to_vec()), + ) +} + pub trait PolicyStoreExt { /// Insert version-one policy history when the sandbox still has no policy /// revisions. Existing history and apply status are left untouched. @@ -676,6 +690,16 @@ pub fn draft_chunk_record_from_parts( created_at_ms: i64, updated_at_ms: i64, ) -> PersistenceResult { + // Scan policy fields before prost drops unknown restrictions and the + // proposed rule is re-encoded (RFC 0027). + match crate::wire_validation::stored::scan_draft_chunk_payload(payload) { + Ok(()) | Err(crate::wire_validation::WireRejection::Malformed(_)) => {} + Err(rejection) => { + return Err(PersistenceError::UnknownFields(format!( + "draft chunk {id}: {rejection}" + ))); + } + } let wrapper = DraftChunkPayload::decode(payload) .map_err(|e| PersistenceError::Decode(format!("decode draft chunk wrapper failed: {e}")))?; let proposed_rule = wrapper @@ -719,6 +743,56 @@ mod tests { SandboxStatus, }; + #[test] + fn draft_chunks_with_unknown_policy_fields_fail_to_decode() { + use crate::storage_proto::DraftChunkPayload; + + let payload = DraftChunkPayload { + rule_name: "github".to_string(), + proposed_rule: Some(NetworkPolicyRule { + name: "github".to_string(), + ..Default::default() + }), + ..Default::default() + } + .encode_to_vec(); + let parts = |payload: &[u8]| { + draft_chunk_record_from_parts( + "chunk".to_string(), + "sandbox".to_string(), + "pending".to_string(), + 1, + payload, + 1, + 1, + ) + }; + assert!(parts(&payload).is_ok()); + + // A newer gateway's restriction on the proposed rule (tag 2). + let mut rule = NetworkPolicyRule { + name: "github".to_string(), + ..Default::default() + } + .encode_to_vec(); + prost::encoding::encode_varint(900 << 3, &mut rule); + prost::encoding::encode_varint(1, &mut rule); + let mut restricted = payload; + prost::encoding::encode_key( + 2, + prost::encoding::WireType::LengthDelimited, + &mut restricted, + ); + prost::encoding::encode_varint(rule.len() as u64, &mut restricted); + restricted.extend_from_slice(&rule); + + let error = parts(&restricted).unwrap_err(); + assert!( + matches!(error, PersistenceError::UnknownFields(_)), + "{error}" + ); + } + #[test] fn static_projection_requires_durable_evidence_of_no_previous_activation() { let baseline = openshell_policy::restrictive_default_policy(); diff --git a/crates/openshell-server/src/provider_profile_sources.rs b/crates/openshell-server/src/provider_profile_sources.rs index 7fcf64c4d2..f289df4b20 100644 --- a/crates/openshell-server/src/provider_profile_sources.rs +++ b/crates/openshell-server/src/provider_profile_sources.rs @@ -137,7 +137,7 @@ impl ProviderProfileSource for UserProviderProfileSource { .get_message_by_name::(namespace, id) .await .map_err(|error| { - Status::internal(format!("fetch provider profile failed: {error}")) + crate::grpc::persistence_error_to_status(error, "fetch provider profile") })? { let version = stored_profile_resource_version(&stored); @@ -170,7 +170,7 @@ impl ProviderProfileSource for UserProviderProfileSource { .collect_messages(ObjectListQuery::Workspace("")) .await .map_err(|e| { - Status::internal(format!("list platform provider profiles failed: {e}")) + crate::grpc::persistence_error_to_status(e, "list platform provider profiles") })?; for stored in platform_stored { let resource_version = stored_profile_resource_version(&stored); @@ -191,7 +191,7 @@ impl ProviderProfileSource for UserProviderProfileSource { .collect_messages(ObjectListQuery::Workspace(workspace)) .await .map_err(|e| { - Status::internal(format!("list workspace provider profiles failed: {e}")) + crate::grpc::persistence_error_to_status(e, "list workspace provider profiles") })?; for stored in ws_stored { let resource_version = stored_profile_resource_version(&stored); diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 4c452c7cf3..db7f2bf17e 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -624,6 +624,53 @@ mod tests { assert_eq!(unknown.outcome, 99); } + /// Every durable root that can carry policy restrictions must be scanned + /// or byte-preserved at the persistence boundary (RFC 0027). A new root + /// here needs that protection before it is added to the expected set. + #[test] + fn durable_roots_that_reach_policy_types_are_protected() { + const POLICY_TYPES: [&str; 3] = [ + ".openshell.sandbox.v1.SandboxPolicy", + ".openshell.sandbox.v1.NetworkPolicyRule", + ".openshell.sandbox.v1.NetworkEndpoint", + ]; + let public = FileDescriptorSet::decode(openshell_core::FILE_DESCRIPTOR_SET) + .expect("public descriptor set must decode"); + let storage = FileDescriptorSet::decode(STORAGE_FILE_DESCRIPTOR_SET) + .expect("storage descriptor set must decode"); + let mut index = SchemaIndex::default(); + index_descriptor(&mut index, &storage); + index_descriptor(&mut index, &public); + + let reaching = DURABLE_ROOTS + .iter() + .copied() + .filter(|root| { + let closure = schema_closure(&index, [(*root).to_string()]); + POLICY_TYPES + .iter() + .any(|policy_type| closure.messages.contains(*policy_type)) + }) + .collect::>(); + assert_eq!( + reaching, + [ + // Global settings store hex-encoded SandboxPolicy bytes. + ".openshell.sandbox.v1.SandboxPolicy", + // draft_chunk_record_from_parts scans tags 2, 17, and 18. + ".openshell.storage.v1.DraftChunkPayload", + // canonical_policy_record_identity scans the raw policy. + ".openshell.storage.v1.PolicyRevisionPayload", + // decode_record scans profile endpoints. + ".openshell.storage.v1.StoredProviderProfile", + // Store writes preserve spec.policy bytes; policy readers + // call require_known_spec_policy. + ".openshell.v1.Sandbox", + ], + "a durable root that reaches a policy type needs RFC 0027 persistence-boundary protection" + ); + } + #[test] fn public_and_durable_schema_inventories_are_complete() { let public = FileDescriptorSet::decode(openshell_core::FILE_DESCRIPTOR_SET) diff --git a/crates/openshell-server/src/wire_validation/mod.rs b/crates/openshell-server/src/wire_validation/mod.rs index b1339d6dee..ba05b0c2b4 100644 --- a/crates/openshell-server/src/wire_validation/mod.rs +++ b/crates/openshell-server/src/wire_validation/mod.rs @@ -15,12 +15,9 @@ //! their caller-authored keys are map keys, so only the wrapper tags are //! checked. -// Ingress and persistence callers land in follow-up changes (RFC 0027 -// implementation steps 2 and 3). -#![allow(dead_code)] - pub mod ingress; pub mod sandbox_policy; +pub mod stored; use std::collections::HashMap; use std::fmt; diff --git a/crates/openshell-server/src/wire_validation/sandbox_policy.rs b/crates/openshell-server/src/wire_validation/sandbox_policy.rs index b3bcf4dd0e..9382f28ab9 100644 --- a/crates/openshell-server/src/wire_validation/sandbox_policy.rs +++ b/crates/openshell-server/src/wire_validation/sandbox_policy.rs @@ -14,15 +14,13 @@ use openshell_core::proto::{Sandbox, SandboxPolicy}; use prost::Message; -use super::{FieldIter, ScanOptions, WIRE_LEN, WireRejection, write_len_field}; +use super::{FieldIter, WIRE_LEN, WireRejection, write_len_field}; /// `Sandbox.spec`. const SANDBOX_SPEC: u32 = 2; /// `SandboxSpec.policy`. const SPEC_POLICY: u32 = 7; -const SANDBOX_POLICY: &str = "openshell.sandbox.v1.SandboxPolicy"; - /// Raw `Sandbox.spec.policy` bytes, or `None` when no policy is encoded. /// /// Protobuf merges repeated occurrences of an embedded message, so the @@ -48,14 +46,6 @@ pub fn extract_spec_policy(sandbox: &[u8]) -> Result>, WireReject Ok(policy) } -/// Validate the raw `Sandbox.spec.policy` against the compiled schema before -/// any policy evaluation, canonicalization, or delivery uses it. -pub fn scan_spec_policy(sandbox: &[u8]) -> Result<(), WireRejection> { - extract_spec_policy(sandbox)?.map_or(Ok(()), |policy| { - super::scan_named(SANDBOX_POLICY, &policy, ScanOptions::default()) - }) -} - /// Replace every `Sandbox.spec.policy` occurrence in `encoded` with `policy`. /// /// The policy takes the position of the first policy occurrence in the first @@ -92,16 +82,35 @@ pub fn encode_preserving_spec_policy( updated: &Sandbox, ) -> Result, WireRejection> { let encoded = updated.encode_to_vec(); + Ok(preserve_spec_policy(original, &encoded)?.unwrap_or(encoded)) +} + +/// `encoded` with the stored `spec.policy` bytes of `original` spliced back, +/// or `None` when there is nothing to preserve. +/// +/// Splices only when both encodings carry a policy and their known fields +/// are equal, so a removed or replaced policy is never resurrected. +pub fn preserve_spec_policy( + original: &[u8], + encoded: &[u8], +) -> Result>, WireRejection> { let Some(stored) = extract_spec_policy(original)? else { - return Ok(encoded); + return Ok(None); + }; + let Some(updated) = extract_spec_policy(encoded)? else { + return Ok(None); + }; + if stored == updated { + return Ok(None); + } + let decode = |bytes: &[u8]| { + SandboxPolicy::decode(bytes) + .map_err(|_| WireRejection::Malformed("sandbox policy does not decode")) }; - let stored_known = SandboxPolicy::decode(stored.as_slice()) - .map_err(|_| WireRejection::Malformed("stored sandbox policy does not decode"))?; - let updated_policy = updated.spec.as_ref().and_then(|spec| spec.policy.as_ref()); - if updated_policy != Some(&stored_known) { - return Ok(encoded); + if decode(&stored)? != decode(&updated)? { + return Ok(None); } - splice_spec_policy(&encoded, Some(&stored)) + splice_spec_policy(encoded, Some(&stored)).map(Some) } fn rewrite_spec(spec: &[u8], policy: Option<&[u8]>) -> Result, WireRejection> { @@ -137,7 +146,7 @@ fn require_len(wire_type: u8) -> Result<(), WireRejection> { #[cfg(test)] mod tests { use super::*; - use crate::wire_validation::{ViolationKind, write_varint}; + use crate::wire_validation::write_varint; use openshell_core::proto::NetworkPolicyRule; use openshell_core::proto::SandboxSpec; use openshell_core::proto::datamodel::v1::ObjectMeta; @@ -295,21 +304,20 @@ mod tests { } #[test] - fn scan_spec_policy_reports_unknown_policy_fields() { + fn preserve_never_resurrects_a_removed_policy() { let policy = policy_with_rule("github"); - assert_eq!( - scan_spec_policy(&sandbox(Some(policy.clone())).encode_to_vec()), - Ok(()) - ); - let newer_policy = with_unknown(policy.encode_to_vec(), 900, 1); let stored = encode_with_raw_policy(&sandbox(Some(policy)), &newer_policy); - let Err(WireRejection::Violations { violations, .. }) = scan_spec_policy(&stored) else { - panic!("expected a violation"); - }; - assert_eq!(violations.len(), 1); - assert_eq!(violations[0].kind, ViolationKind::UnknownField { tag: 900 }); - assert_eq!(violations[0].field(), "#900"); + let mut updated = Sandbox::decode(stored.as_slice()).unwrap(); + updated.spec.as_mut().unwrap().policy = None; + assert_eq!( + preserve_spec_policy(&stored, &updated.encode_to_vec()).unwrap(), + None + ); + assert_eq!( + preserve_spec_policy(&sandbox(None).encode_to_vec(), &stored).unwrap(), + None + ); } #[test] diff --git a/crates/openshell-server/src/wire_validation/stored.rs b/crates/openshell-server/src/wire_validation/stored.rs new file mode 100644 index 0000000000..36f538d75a --- /dev/null +++ b/crates/openshell-server/src/wire_validation/stored.rs @@ -0,0 +1,279 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Persistence-boundary validation of stored policy payloads (RFC 0027). +//! +//! A newer gateway sharing storage, or one rolled back from, can leave policy +//! restrictions this build does not know. Loaders scan the raw bytes before +//! `prost` decodes them so such a policy is refused rather than silently +//! broadened. + +use tonic::Status; + +use super::{ + FieldIter, LEGACY_STORED_POLICY_RESERVED, ScanOptions, WIRE_LEN, WireRejection, scan_named, +}; + +const SANDBOX_POLICY: &str = "openshell.sandbox.v1.SandboxPolicy"; +const NETWORK_POLICY_RULE: &str = "openshell.sandbox.v1.NetworkPolicyRule"; +const NETWORK_ENDPOINT: &str = "openshell.sandbox.v1.NetworkEndpoint"; + +/// `DraftChunkPayload` fields that carry policy. +const DRAFT_PROPOSED_RULE: u32 = 2; +const DRAFT_CURRENT_EFFECTIVE_POLICY: u32 = 17; +const DRAFT_CANDIDATE_EFFECTIVE_POLICY: u32 = 18; +/// `StoredProviderProfile.profile` and `ProviderProfile.endpoints`. +const STORED_PROFILE: u32 = 2; +const PROFILE_ENDPOINTS: u32 = 6; + +const LEGACY: ScanOptions<'static> = ScanOptions { + allowed_reserved: LEGACY_STORED_POLICY_RESERVED, +}; + +/// Where a stored policy was loaded from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StoredPolicySource { + /// A sandbox policy revision. + History, + /// The gateway-wide policy setting. + Global, + /// `Sandbox.spec.policy`. + Spec, +} + +impl StoredPolicySource { + /// The `source` label of `openshell_server_stored_policy_unknown_fields_total`. + const fn label(self) -> &'static str { + match self { + Self::History => "policy_history", + Self::Global => "global_policy", + Self::Spec => "spec_policy", + } + } + + const fn description(self) -> &'static str { + match self { + Self::History => "sandbox policy history", + Self::Global => "global policy setting", + Self::Spec => "sandbox spec policy", + } + } +} + +/// Count a stored payload this build refuses, by where it was stored. +fn count(source: &'static str) { + metrics::counter!( + "openshell_server_stored_policy_unknown_fields_total", + "source" => source, + ) + .increment(1); +} + +/// Refuse a stored policy with unknown fields or enum values. +/// +/// Returns `FAILED_PRECONDITION` so configuration delivery marks the +/// configuration not admitted. Malformed bytes pass through: the caller's +/// `prost` decode reports them exactly as before. +pub fn require_known_stored_policy( + payload: &[u8], + source: StoredPolicySource, +) -> Result<(), Status> { + match scan_named(SANDBOX_POLICY, payload, LEGACY) { + Ok(()) | Err(WireRejection::Malformed(_)) => Ok(()), + Err(rejection) => { + count(source.label()); + Err(stored_rejection(source.description(), &rejection)) + } + } +} + +/// The status for a stored policy this build cannot represent. +pub fn stored_rejection(source: &str, rejection: &WireRejection) -> Status { + Status::failed_precondition(format!( + "{source} uses protobuf fields this gateway ({}) does not know; \ + upgrade the gateway or replace the policy ({rejection})", + openshell_core::VERSION + )) +} + +/// Scan the policy-bearing fields of a raw `DraftChunkPayload`. +pub fn scan_draft_chunk_payload(payload: &[u8]) -> Result<(), WireRejection> { + let mut fields = FieldIter::new(payload); + while let Some(field) = fields.next_field().map_err(WireRejection::Malformed)? { + let message = match field.number { + DRAFT_PROPOSED_RULE => NETWORK_POLICY_RULE, + DRAFT_CURRENT_EFFECTIVE_POLICY | DRAFT_CANDIDATE_EFFECTIVE_POLICY => SANDBOX_POLICY, + _ => continue, + }; + require_len(field.wire_type)?; + scan_named(message, field.value, LEGACY).inspect_err(|_| count("draft_chunk"))?; + } + Ok(()) +} + +/// Scan the endpoint restrictions of a raw `StoredProviderProfile`. +pub fn scan_stored_provider_profile(payload: &[u8]) -> Result<(), WireRejection> { + let mut fields = FieldIter::new(payload); + while let Some(field) = fields.next_field().map_err(WireRejection::Malformed)? { + if field.number != STORED_PROFILE { + continue; + } + require_len(field.wire_type)?; + let mut profile = FieldIter::new(field.value); + while let Some(profile_field) = profile.next_field().map_err(WireRejection::Malformed)? { + if profile_field.number != PROFILE_ENDPOINTS { + continue; + } + require_len(profile_field.wire_type)?; + scan_named( + NETWORK_ENDPOINT, + profile_field.value, + ScanOptions::default(), + ) + .inspect_err(|_| count("provider_profile"))?; + } + } + Ok(()) +} + +fn require_len(wire_type: u8) -> Result<(), WireRejection> { + if wire_type == WIRE_LEN { + Ok(()) + } else { + Err(WireRejection::Malformed( + "message field has the wrong wire type", + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::storage_proto::{DraftChunkPayload, StoredProviderProfile}; + use crate::wire_validation::{ViolationKind, write_len_field, write_varint}; + use openshell_core::proto::{ + NetworkBinary, NetworkEndpoint, NetworkPolicyRule, ProviderProfile, SandboxPolicy, + }; + use prost::Message; + + fn with_unknown(mut payload: Vec, tag: u32) -> Vec { + write_varint(&mut payload, u64::from(tag) << 3); + write_varint(&mut payload, 1); + payload + } + + fn rule() -> NetworkPolicyRule { + NetworkPolicyRule { + name: "github".into(), + endpoints: vec![NetworkEndpoint { + host: "github.com".into(), + port: 443, + ..Default::default() + }], + binaries: vec![NetworkBinary { + path: "/usr/bin/git".into(), + }], + } + } + + #[test] + fn stored_policy_with_unknown_field_is_a_failed_precondition() { + let policy = SandboxPolicy::default().encode_to_vec(); + assert!(require_known_stored_policy(&policy, StoredPolicySource::History).is_ok()); + let status = + require_known_stored_policy(&with_unknown(policy, 900), StoredPolicySource::History) + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::FailedPrecondition); + assert!(status.message().contains("#900"), "{}", status.message()); + assert!(crate::grpc::policy::is_configuration_rejection(&status)); + } + + #[test] + fn stored_policy_tolerates_the_legacy_advisor_flag_only() { + let mut binary = NetworkBinary { + path: "/usr/bin/git".into(), + } + .encode_to_vec(); + write_varint(&mut binary, 2 << 3); + write_varint(&mut binary, 1); + let mut rule = Vec::new(); + write_len_field(&mut rule, 3, &binary); + let mut entry = Vec::new(); + write_len_field(&mut entry, 1, b"github"); + write_len_field(&mut entry, 2, &rule); + let mut policy = Vec::new(); + write_len_field(&mut policy, 5, &entry); + assert!(require_known_stored_policy(&policy, StoredPolicySource::History).is_ok()); + } + + #[test] + fn malformed_stored_policy_is_left_to_the_decoder() { + assert!(require_known_stored_policy(&[0x2a, 0x05], StoredPolicySource::History).is_ok()); + } + + #[test] + fn draft_chunk_scans_policy_fields_only() { + let payload = DraftChunkPayload { + rule_name: "github".into(), + proposed_rule: Some(rule()), + current_effective_policy: Some(SandboxPolicy::default()), + ..Default::default() + } + .encode_to_vec(); + assert_eq!(scan_draft_chunk_payload(&payload), Ok(())); + // An unknown draft wrapper field is not a policy restriction. + assert_eq!( + scan_draft_chunk_payload(&with_unknown(payload.clone(), 900)), + Ok(()) + ); + + let mut restricted = payload; + write_len_field( + &mut restricted, + DRAFT_PROPOSED_RULE, + &with_unknown(rule().encode_to_vec(), 901), + ); + let Err(WireRejection::Violations { violations, .. }) = + scan_draft_chunk_payload(&restricted) + else { + panic!("expected a violation"); + }; + assert_eq!(violations[0].kind, ViolationKind::UnknownField { tag: 901 }); + + let mut candidate = Vec::new(); + write_len_field( + &mut candidate, + DRAFT_CANDIDATE_EFFECTIVE_POLICY, + &with_unknown(Vec::new(), 902), + ); + assert!(scan_draft_chunk_payload(&candidate).is_err()); + } + + #[test] + fn stored_profile_scans_endpoint_restrictions() { + let stored = StoredProviderProfile { + metadata: None, + profile: Some(ProviderProfile { + endpoints: vec![rule().endpoints[0].clone()], + ..Default::default() + }), + }; + let payload = stored.encode_to_vec(); + assert_eq!(scan_stored_provider_profile(&payload), Ok(())); + + let mut profile = stored.profile.unwrap().encode_to_vec(); + write_len_field( + &mut profile, + PROFILE_ENDPOINTS, + &with_unknown(NetworkEndpoint::default().encode_to_vec(), 903), + ); + let mut restricted = Vec::new(); + write_len_field(&mut restricted, STORED_PROFILE, &profile); + let Err(WireRejection::Violations { violations, .. }) = + scan_stored_provider_profile(&restricted) + else { + panic!("expected a violation"); + }; + assert_eq!(violations[0].field(), "#903"); + } +} From 6e294575fc95018bdae53ef55382dd329040ee81 Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Mon, 30 Nov 2026 23:11:39 +0000 Subject: [PATCH 04/10] ci(proto): freeze protobuf definitions on patch trains Implement the release-train check from RFC 0027 step 4. train_policy() now classifies the active train as none, patch, or minor instead of returning one allows_breaks flag: - none: no pre-release train is active. Additive changes may merge so a feat change can start the next minor train; breaking changes fail. - patch: proto/ is frozen. Added services, RPCs, messages, fields, extensions, enums, or enum values fail alongside breaking changes. - minor: additive changes pass and breaking changes are warnings during 0.x. Additions are found by comparing definition inventories from buf JSON images, keyed by number so renames are not additions. Add unit tests, including an end-to-end buf check when buf is installed, and run them with test:python-scripts. Refs #6097 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Mrunal Patel --- tasks/scripts/check_proto_compatibility.py | 163 +++++++++++--- .../scripts/check_proto_compatibility_test.py | 207 ++++++++++++++++++ tasks/scripts/codex_compatibility.py | 16 +- tasks/test.toml | 4 +- 4 files changed, 354 insertions(+), 36 deletions(-) create mode 100644 tasks/scripts/check_proto_compatibility_test.py diff --git a/tasks/scripts/check_proto_compatibility.py b/tasks/scripts/check_proto_compatibility.py index 8a2ba37134..33c71cb06c 100644 --- a/tasks/scripts/check_proto_compatibility.py +++ b/tasks/scripts/check_proto_compatibility.py @@ -5,11 +5,13 @@ import argparse import io +import json import os import subprocess import sys import tarfile import tempfile +from dataclasses import dataclass from pathlib import Path from release import _parse_prerelease_tag, _parse_semver_tag @@ -21,7 +23,43 @@ def git(*args: str) -> str: ).stdout.strip() -def train_policy(ref: str, release: str | None) -> tuple[str, str, bool]: +NONE = "none" +PATCH = "patch" +MINOR = "minor" + + +@dataclass(frozen=True) +class TrainPolicy: + """Protobuf change policy for the active release train. + + - ``none``: no pre-release train is active. Additive changes may merge so a + ``feat:`` change can start the next minor train; breaking changes are + forbidden. + - ``patch``: a patch train or patch tag. ``proto/`` is frozen: neither + breaking nor additive descriptor changes are allowed. + - ``minor``: a minor (or major) train or tag. Additive changes are allowed, + and breaking changes are reported as warnings during ``0.x``. + """ + + baseline: str + description: str + kind: str + + @property + def allows_breaks(self) -> bool: + return self.kind == MINOR + + @property + def allows_additions(self) -> bool: + return self.kind != PATCH + + +def train_kind(version: tuple[int, int, int], previous: tuple[int, int, int]) -> str: + """Classify a release newer than the latest stable release.""" + return MINOR if version[:2] > previous[:2] else PATCH + + +def train_policy(ref: str, release: str | None) -> TrainPolicy: tags = git("tag", "--merged", ref, "--list", "v*").splitlines() stable = sorted( (version, tag) @@ -33,7 +71,7 @@ def train_policy(ref: str, release: str | None) -> tuple[str, str, bool]: (version, tag) for tag in tags if (version := _parse_prerelease_tag(tag)) ) if not prereleases or (stable and prereleases[-1][0][:3] <= stable[-1][0]): - return "", "none", False + return TrainPolicy("", NONE, NONE) release = prereleases[-1][1] if not stable: @@ -46,8 +84,56 @@ def train_policy(ref: str, release: str | None) -> tuple[str, str, bool]: if version <= previous: raise ValueError(f"Release {release} must be newer than stable {baseline}.") train = "v" + ".".join(map(str, version)) - allows_breaks = version[:2] > previous[:2] - return baseline, f"{train} (latest stable: {baseline})", allows_breaks + kind = train_kind(version, previous) + return TrainPolicy(baseline, f"{train} {kind} (latest stable: {baseline})", kind) + + +def definitions(image: dict) -> set[str]: + """Wire-relevant definitions in a ``buf build`` JSON image. + + Fields and enum values are keyed by number, so a rename is not an + addition. Removals are left to ``buf breaking``. + """ + found: set[str] = set() + + def add_enum(prefix: str, enum: dict) -> None: + name = f"{prefix}.{enum['name']}" if prefix else enum["name"] + found.add(f"enum {name}") + for value in enum.get("value", []): + found.add(f"enum value {name}={value.get('number', 0)}") + + def add_message(prefix: str, message: dict) -> None: + name = f"{prefix}.{message['name']}" if prefix else message["name"] + found.add(f"message {name}") + for field in message.get("field", []): + found.add(f"field {name}#{field['number']}") + for extension in message.get("extension", []): + found.add(f"extension {extension['extendee']}#{extension['number']}") + for nested in message.get("nestedType", []): + add_message(name, nested) + for enum in message.get("enumType", []): + add_enum(name, enum) + + for file in image.get("file", []): + package = file.get("package", "") + for message in file.get("messageType", []): + add_message(package, message) + for enum in file.get("enumType", []): + add_enum(package, enum) + for extension in file.get("extension", []): + found.add(f"extension {extension['extendee']}#{extension['number']}") + for service in file.get("service", []): + service_name = ( + f"{package}.{service['name']}" if package else service["name"] + ) + found.add(f"service {service_name}") + for method in service.get("method", []): + found.add(f"rpc {service_name}/{method['name']}") + return found + + +def added_definitions(before: dict, after: dict) -> list[str]: + return sorted(definitions(after) - definitions(before)) def export_proto(ref: str, destination: Path) -> None: @@ -58,7 +144,28 @@ def export_proto(ref: str, destination: Path) -> None: snapshot.extractall(destination, filter="data") -def compare(candidate: str, baseline: str, allows_breaks: bool) -> int: +def build_image(snapshot: Path, error_format: str) -> dict: + """Build ``proto/`` into a JSON descriptor image without source info.""" + output = snapshot / "image.json" + subprocess.run( + [ + "buf", + "build", + "proto", + "--exclude-imports", + "--exclude-source-info", + "--error-format", + error_format, + "-o", + str(output), + ], + cwd=snapshot, + check=True, + ) + return json.loads(output.read_text()) + + +def compare(candidate: str, baseline: str, policy: TrainPolicy) -> int: with tempfile.TemporaryDirectory(prefix="openshell-proto-") as directory: root = Path(directory) export_proto(baseline, root / "before") @@ -68,20 +175,22 @@ def compare(candidate: str, baseline: str, allows_breaks: bool) -> int: ) # Buf also returns 100 for compiler diagnostics. Validate both snapshots # before treating that status from `breaking` as an allowed API change. - for snapshot in ("before", "after"): - subprocess.run( - [ - "buf", - "build", - "proto", - "--error-format", - error_format, - "-o", - os.devnull, - ], - cwd=root / snapshot, - check=True, - ) + images = { + snapshot: build_image(root / snapshot, error_format) + for snapshot in ("before", "after") + } + frozen = 0 + if not policy.allows_additions: + additions = added_definitions(images["before"], images["after"]) + prefix = "::error ::" if error_format == "github-actions" else "" + for addition in additions: + print(f"{prefix}Patch train freezes proto/: added {addition}") + if additions: + print( + "Additive protobuf changes belong in a minor train; merge them " + "after this patch release or start the next minor train." + ) + frozen = 1 result = subprocess.run( [ "buf", @@ -100,14 +209,14 @@ def compare(candidate: str, baseline: str, allows_breaks: bool) -> int: check=False, ) diagnostics = result.stdout + result.stderr - if result.returncode == 100 and allows_breaks: + if result.returncode == 100 and policy.allows_breaks: print(diagnostics.replace("::error ", "::warning "), end="") print( "Breaking changes allowed by the version increment; review migration guidance." ) - return 0 + return frozen print(diagnostics, end="") - return result.returncode + return result.returncode or frozen def main() -> int: @@ -121,17 +230,19 @@ def main() -> int: "rev-parse", "--verify", "--end-of-options", f"{args.ref}^{{commit}}" ) release = ref.removeprefix("refs/tags/") if ref.startswith("refs/tags/") else None - stable, train, allows_breaks = train_policy(candidate, release) - baseline = f"refs/tags/{stable}" if release else candidate + policy = train_policy(candidate, release) + baseline = f"refs/tags/{policy.baseline}" if release else candidate if not release: # merge-tree writes only Git objects, leaving HEAD and the worktree # intact. Target-only additions are therefore not mistaken for deletions. candidate = git("merge-tree", "--write-tree", baseline, "HEAD").splitlines()[0] print( - f"Train: {train}; breaking changes {'allowed' if allows_breaks else 'forbidden'}" + f"Train: {policy.description}; " + f"additive changes {'allowed' if policy.allows_additions else 'forbidden'}; " + f"breaking changes {'allowed' if policy.allows_breaks else 'forbidden'}" ) print(f"Comparing {candidate} against {baseline}", flush=True) - return compare(candidate, baseline, allows_breaks) + return compare(candidate, baseline, policy) if __name__ == "__main__": diff --git a/tasks/scripts/check_proto_compatibility_test.py b/tasks/scripts/check_proto_compatibility_test.py new file mode 100644 index 0000000000..af843337b6 --- /dev/null +++ b/tasks/scripts/check_proto_compatibility_test.py @@ -0,0 +1,207 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import check_proto_compatibility as compat + + +def _with_tags(monkeypatch: pytest.MonkeyPatch, tags: list[str]) -> None: + monkeypatch.setattr(compat, "git", lambda *_args: "\n".join(tags)) + + +@pytest.mark.parametrize( + ("tags", "kind", "baseline"), + [ + (["v0.1.0", "v0.1.1"], compat.NONE, ""), + # A pre-release already promoted to stable no longer defines a train. + (["v0.1.0", "v0.1.1-pre.1", "v0.1.1"], compat.NONE, ""), + (["v0.1.0", "v0.1.1-pre.1"], compat.PATCH, "v0.1.0"), + (["v0.1.0", "v0.2.0-pre.3"], compat.MINOR, "v0.1.0"), + (["v0.9.4", "v1.0.0-pre.1"], compat.MINOR, "v0.9.4"), + ], +) +def test_branch_train_classification( + monkeypatch: pytest.MonkeyPatch, tags: list[str], kind: str, baseline: str +) -> None: + _with_tags(monkeypatch, tags) + + policy = compat.train_policy("HEAD", None) + + assert policy.kind == kind + assert policy.baseline == baseline + + +@pytest.mark.parametrize( + ("release", "kind"), + [ + ("v0.1.1", compat.PATCH), + ("v0.1.1-pre.2", compat.PATCH), + ("v0.2.0", compat.MINOR), + ("v0.2.0-pre.1", compat.MINOR), + ], +) +def test_tag_qualification_classification( + monkeypatch: pytest.MonkeyPatch, release: str, kind: str +) -> None: + _with_tags(monkeypatch, ["v0.1.0", release]) + + policy = compat.train_policy(release, release) + + assert policy.kind == kind + assert policy.baseline == "v0.1.0" + assert kind in policy.description + + +@pytest.mark.parametrize( + ("kind", "additions", "breaks"), + [ + (compat.NONE, True, False), + (compat.PATCH, False, False), + (compat.MINOR, True, True), + ], +) +def test_policy_permissions(kind: str, additions: bool, breaks: bool) -> None: + policy = compat.TrainPolicy("v0.1.0", kind, kind) + + assert policy.allows_additions is additions + assert policy.allows_breaks is breaks + + +def test_tag_must_be_newer_than_stable(monkeypatch: pytest.MonkeyPatch) -> None: + _with_tags(monkeypatch, ["v0.2.0", "v0.1.9"]) + + with pytest.raises(ValueError, match="must be newer"): + compat.train_policy("v0.1.9", "v0.1.9") + + +def _image(*, field_numbers=(1,), values=(0, 1), methods=("Get",)) -> dict: + return { + "file": [ + { + "name": "demo.proto", + "package": "demo.v1", + "messageType": [ + { + "name": "Outer", + "field": [ + {"name": f"f{number}", "number": number} + for number in field_numbers + ], + "nestedType": [{"name": "Inner"}], + } + ], + "enumType": [ + { + "name": "Mode", + "value": [ + # protojson omits a zero number. + {"name": f"MODE_{value}"} + | ({"number": value} if value else {}) + for value in values + ], + } + ], + "service": [ + {"name": "Demo", "method": [{"name": name} for name in methods]} + ], + } + ] + } + + +def test_definitions_cover_wire_relevant_declarations() -> None: + assert compat.definitions(_image()) == { + "message demo.v1.Outer", + "message demo.v1.Outer.Inner", + "field demo.v1.Outer#1", + "enum demo.v1.Mode", + "enum value demo.v1.Mode=0", + "enum value demo.v1.Mode=1", + "service demo.v1.Demo", + "rpc demo.v1.Demo/Get", + } + + +def test_added_definitions_report_only_additions() -> None: + before = _image() + after = _image(field_numbers=(1, 2), values=(0, 1, 2), methods=("Get", "Watch")) + + assert compat.added_definitions(before, after) == [ + "enum value demo.v1.Mode=2", + "field demo.v1.Outer#2", + "rpc demo.v1.Demo/Watch", + ] + # Removals are breaking changes, which `buf breaking` reports. + assert compat.added_definitions(after, before) == [] + + +def test_renames_are_not_additions() -> None: + before = _image() + after = _image() + after["file"][0]["messageType"][0]["field"][0]["name"] = "renamed" + + assert compat.added_definitions(before, after) == [] + + +PROTO = """syntax = "proto3"; +package demo.v1; +message Request { + string name = 1; +%s} +""" + + +def _commit(repo: Path, extra_field: str) -> str: + (repo / "proto" / "demo.proto").write_text(PROTO % extra_field) + subprocess.run(["git", "add", "-A"], cwd=repo, check=True) + subprocess.run( + ["git", "commit", "-q", "--no-verify", "-m", "snapshot"], cwd=repo, check=True + ) + return subprocess.run( + ["git", "rev-parse", "HEAD"], + cwd=repo, + check=True, + capture_output=True, + text=True, + ).stdout.strip() + + +@pytest.mark.skipif(shutil.which("buf") is None, reason="buf is not installed") +@pytest.mark.parametrize( + ("kind", "expected"), [(compat.PATCH, 1), (compat.MINOR, 0), (compat.NONE, 0)] +) +def test_additive_change_fails_only_on_patch_trains( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + kind: str, + expected: int, +) -> None: + repo = tmp_path / "repo" + (repo / "proto").mkdir(parents=True) + (repo / "buf.yaml").write_text( + "version: v2\nmodules:\n - path: proto\nbreaking:\n use:\n - FILE\n" + ) + subprocess.run(["git", "init", "-q"], cwd=repo, check=True) + for key, value in (("user.name", "test"), ("user.email", "test@example.com")): + subprocess.run(["git", "config", key, value], cwd=repo, check=True) + before = _commit(repo, "") + after = _commit(repo, " string note = 2;\n") + monkeypatch.chdir(repo) + monkeypatch.delenv("GITHUB_ACTIONS", raising=False) + + result = compat.compare(after, before, compat.TrainPolicy("v0.1.0", kind, kind)) + + assert result == expected + output = capsys.readouterr().out + assert ("added field demo.v1.Request#2" in output) is (kind == compat.PATCH) diff --git a/tasks/scripts/codex_compatibility.py b/tasks/scripts/codex_compatibility.py index 59f893f11c..ddf7e97772 100644 --- a/tasks/scripts/codex_compatibility.py +++ b/tasks/scripts/codex_compatibility.py @@ -31,17 +31,17 @@ def resolve_candidate(tag: str, expected_sha: str) -> dict: ) if expected_sha and candidate != expected_sha: raise ValueError("Candidate tag does not match the qualification source SHA.") - baseline, train, allows_breaks = train_policy(candidate, tag) + policy = train_policy(candidate, tag) return { "candidate_tag": tag, "candidate_sha": candidate, "source_sha": candidate, - "baseline_tag": baseline, + "baseline_tag": policy.baseline, "baseline_sha": git( - "rev-parse", "--verify", f"refs/tags/{baseline}^{{commit}}" + "rev-parse", "--verify", f"refs/tags/{policy.baseline}^{{commit}}" ), - "train": train, - "allows_breaks": allows_breaks, + "train": policy.description, + "allows_breaks": policy.allows_breaks, } @@ -52,7 +52,7 @@ def resolve_branch(base_ref: str, source_sha: str, pr_number: int) -> dict: "rev-parse", "--verify", "--end-of-options", f"{base_ref}^{{commit}}" ) candidate = git("rev-parse", "--verify", f"{source_sha}^{{commit}}") - _, train, allows_breaks = train_policy(baseline, None) + policy = train_policy(baseline, None) merged = git("merge-tree", "--write-tree", baseline, candidate).splitlines()[0] return { "candidate_tag": f"PR #{pr_number}" if pr_number else candidate[:12], @@ -60,8 +60,8 @@ def resolve_branch(base_ref: str, source_sha: str, pr_number: int) -> dict: "source_sha": candidate, "baseline_tag": base_ref, "baseline_sha": baseline, - "train": train, - "allows_breaks": allows_breaks, + "train": policy.description, + "allows_breaks": policy.allows_breaks, "mode": "branch", } diff --git a/tasks/test.toml b/tasks/test.toml index bdd923de3f..e71ff50b0d 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -191,8 +191,8 @@ run_windows = "echo Skipping test:postgres-runner: the Unix PostgreSQL test runn hide = true ["test:python-scripts"] -description = "Test the release, RPM, and E2E gateway config tooling" -run = "uv run --no-project --with pytest --with pyyaml pytest -o \"python_files=*_test.py\" tasks/scripts/release_formula_test.py tasks/scripts/release_tooling_test.py deploy/rpm/ e2e/configs/gateway/" +description = "Test the release, protobuf compatibility, RPM, and E2E gateway config tooling" +run = "uv run --no-project --with pytest --with pyyaml pytest -o \"python_files=*_test.py\" tasks/scripts/release_formula_test.py tasks/scripts/release_tooling_test.py tasks/scripts/check_proto_compatibility_test.py deploy/rpm/ e2e/configs/gateway/" hide = true ["test:python"] From 1e97966637ec0349e0ca4a5fb18f3004c6fe0e37 Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Mon, 30 Nov 2026 23:19:05 +0000 Subject: [PATCH 05/10] docs: document unknown-field rejection and upgrade order Describe RFC 0027 for operators and API authors: - The support matrix gains the gateway-first upgrade order, the collector-settings exception, version-skew behavior, and rollback guidance, and notes that new protobuf definitions ship only in minor releases. - proto/README.md asks authors to add definitions only on minor trains, leave unset fields at defaults, and gate new policy restrictions on a supervisor capability. - Gateway metrics list the ingress and stored-policy rejection counters. Refs #6097 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Mrunal Patel --- docs/about/support-matrix.mdx | 39 +++++++++++++++++++++++++- docs/observability/gateway-metrics.mdx | 2 ++ proto/README.md | 10 +++++++ 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/docs/about/support-matrix.mdx b/docs/about/support-matrix.mdx index 73ba85efb7..ebc55f4ce0 100644 --- a/docs/about/support-matrix.mdx +++ b/docs/about/support-matrix.mdx @@ -31,7 +31,8 @@ publication when there are changes and every blocking qualification check passes. A security release may ship sooner. Stable APIs and other Stable interfaces remain backward-compatible across -patch releases. Patch releases can contain fixes and additive functionality. A +patch releases. Patch releases can contain fixes and additive functionality, +but never new protobuf API definitions; those ship in a minor release. A breaking change to a Stable interface requires a minor release with notice and migration guidance. Interfaces marked Experimental may change or be removed in a patch release. @@ -45,6 +46,42 @@ updates do not backport features. Refer to [RFC 0014](https://github.com/ai-openshell/openshell/blob/main/rfc/0014-release-stability/README.md) for the complete release and compatibility policy. +### Upgrade order + +Upgrade gateways first: + +1. Upgrade every gateway replica. Do not use API fields, policy restrictions, + or features new in the release until every replica runs it. +2. Upgrade sandbox supervisors and standalone compute drivers. +3. Enable new policies or features once the supervisors that enforce them + support them. + +Collector settings are the exception. Upgrade supervisors and standalone +compute drivers with or before the gateway before you enable new collector +`headers`, `headers_file`, or TLS settings under +[OTLP Export](/how-it-works/gateways/configuration#otlp-export). + +The gateway rejects a public API request that uses a protobuf field or enum +value it does not know with `UNKNOWN_PROTOBUF_FIELD`, so a newer CLI or SDK +fails fast against an older gateway instead of having restrictions silently +dropped. Leave the newer fields unset or upgrade the gateway. Refer to +[API errors](/sdk/api-errors). The gateway also refuses to deliver a stored +policy, draft, or custom provider profile that uses restrictions it does not +know, and marks the sandbox configuration as not admitted. + +### Roll back a gateway + +Before you downgrade gateways, replace or remove policies, drafts, and custom +provider profiles that use restrictions from the newer release. The older +gateway marks affected sandbox configurations as not admitted, and supervisors +apply `policy_validation_failure_mode`: `fail_closed` blocks new egress, and +`retain_last_valid` keeps the last admitted revision, which may be broader than +the refused one. + +Gateway releases before this validation silently drop restrictions they do not +know. Do not roll back to one of them while newer restrictions remain in +storage. + ## Supported Platforms OpenShell publishes multi-architecture gateway images for `linux/amd64` and `linux/arm64`. The CLI, policy prover, package-managed gateway, and standalone gateway binary are supported on the following host platforms: diff --git a/docs/observability/gateway-metrics.mdx b/docs/observability/gateway-metrics.mdx index 5f24a9e192..4d10ec5f61 100644 --- a/docs/observability/gateway-metrics.mdx +++ b/docs/observability/gateway-metrics.mdx @@ -265,6 +265,8 @@ The gateway also records every API request and its background database check: |---|---|---|---| | `openshell_server_grpc_requests_total` | Counter | `method`, `code` | gRPC requests by method name and numeric status code, including internal peer requests. Streaming RPCs record the status known when the response headers are sent. | | `openshell_server_grpc_request_duration_seconds` | Summary | `method`, `code` | Time until the response headers are sent. For streaming RPCs this covers setup only. | +| `openshell_server_grpc_unknown_fields_total` | Counter | `service`, `method` | API requests rejected with `UNKNOWN_PROTOBUF_FIELD` because they use protobuf fields or enum values this gateway does not know, usually from a newer client. | +| `openshell_server_stored_policy_unknown_fields_total` | Counter | `source` | Stored policies refused because they use restrictions this gateway does not know, usually after a rollback or during a mixed-version rollout. `source` is `policy_history`, `global_policy`, `spec_policy`, `draft_chunk`, or `provider_profile`. Affected sandbox configurations are not admitted. | | `openshell_server_http_requests_total` | Counter | `path`, `status` | HTTP requests on the API port. `path` is `/_ws_tunnel`, `/auth`, or `unknown`. | | `openshell_server_http_request_duration_seconds` | Summary | `path`, `status` | Duration of those HTTP requests. | | `openshell_server_readiness_database_healthy` | Gauge | None | `1` when the last background database check succeeded, otherwise `0`. | diff --git a/proto/README.md b/proto/README.md index 7a313009cf..2266b974be 100644 --- a/proto/README.md +++ b/proto/README.md @@ -85,6 +85,16 @@ identifies the service being exposed. - Review changes against both the public descriptor closure and durable stored protobuf closure. The `public_and_durable_schema_inventories_are_complete` test in `openshell-server` owns both inventories. +- Add services, RPCs, messages, fields, enums, and enum values only in a + minor release train (`feat:`). The protobuf compatibility check freezes + `proto/` during patch trains and fails additive changes there. +- The gateway rejects request fields and enum values it does not know with + `UNKNOWN_PROTOBUF_FIELD`, and refuses stored policies that use them. Leave an + unset field at its default so older gateways still accept requests from newer + clients. +- Gate every new policy restriction on a supervisor capability checked by + `require_policy_capabilities` in `openshell-server`, so a gateway never + delivers a restriction to a supervisor that cannot enforce it. - Regenerate Rust, Python, Go, and TypeScript bindings after contract changes. Run `mise run pre-commit`, the affected SDK checks, and relevant server tests before submitting the change. From 9b289db295704eec206a41f5d9ea64168dbff52d Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Mon, 30 Nov 2026 23:22:57 +0000 Subject: [PATCH 06/10] test(server): reject newer restrictions on policy-bearing RPCs Cover the RFC 0027 acceptance case for the two RPCs that carry policy: UpdateConfig, which sandboxes may call, and SubmitPolicyAnalysis, which is sandbox-authenticated but strict because its proposed rule reaches a policy type. A restriction nested inside the policy is rejected before dispatch with UNKNOWN_PROTOBUF_FIELD and its field path. Refs #6097 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Mrunal Patel --- crates/openshell-server/src/multiplex.rs | 75 ++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 168d8a808d..fb2e2b289a 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -2297,6 +2297,81 @@ mod tests { interceptor_task.abort(); } + /// A newer restriction nested inside a policy, as a newer CLI or supervisor + /// would send it to the policy-bearing RPCs. + fn policy_with_newer_restriction() -> Vec { + let rule = policy_with_newer_restriction_rule(); + // SandboxPolicy.network_policies (tag 5) entry: key 1, value 2. + let mut entry = Vec::new(); + prost::encoding::string::encode(1, &"github".to_string(), &mut entry); + prost::encoding::bytes::encode(2, &rule, &mut entry); + let mut policy = openshell_core::proto::SandboxPolicy::default().encode_to_vec(); + prost::encoding::bytes::encode(5, &entry, &mut policy); + policy + } + + #[tokio::test] + async fn ingress_validation_rejects_newer_policy_restrictions() { + use openshell_core::proto::{ + PolicyChunk, SubmitPolicyAnalysisRequest, UpdateConfigRequest, + }; + + let calls = Arc::new(AtomicUsize::new(0)); + let mut service = IngressValidationService::new( + draining_service(calls.clone(), Arc::new(Mutex::new(None))), + MAX_GRPC_DECODE_SIZE, + ); + let policy = policy_with_newer_restriction(); + + // UpdateConfig is dual-authenticated, so sandbox callers are checked too. + let mut update = UpdateConfigRequest::default().encode_to_vec(); + prost::encoding::bytes::encode(2, &policy, &mut update); + + // SubmitPolicyAnalysis is sandbox-authenticated, but its proposed rule + // reaches a policy type, so it is strict during 0.x. + let mut chunk = PolicyChunk { + rule_name: "github".to_string(), + ..Default::default() + } + .encode_to_vec(); + prost::encoding::bytes::encode(4, &policy_with_newer_restriction_rule(), &mut chunk); + let mut submit = SubmitPolicyAnalysisRequest::default().encode_to_vec(); + prost::encoding::bytes::encode(2, &chunk, &mut submit); + + for (path, body, field) in [ + ( + "/openshell.v1.OpenShell/UpdateConfig", + update, + "policy.network_policies[*]#900", + ), + ( + "/openshell.v1.OpenShell/SubmitPolicyAnalysis", + submit, + "proposed_chunks[0].proposed_rule#900", + ), + ] { + let request = Request::builder() + .uri(path) + .body(boxed_body_from_bytes(grpc_frame(&body))) + .unwrap(); + let response = service.ready().await.unwrap().call(request).await.unwrap(); + assert_unknown_field_status(&status_from_response(&response), field); + } + assert_eq!(calls.load(Ordering::SeqCst), 0); + } + + /// A `NetworkPolicyRule` carrying a restriction this build does not know. + fn policy_with_newer_restriction_rule() -> Vec { + with_unknown_field( + openshell_core::proto::NetworkPolicyRule { + name: "github".to_string(), + ..Default::default() + } + .encode_to_vec(), + 900, + ) + } + #[tokio::test] async fn ingress_validation_exempts_internal_runtime_rpcs() { let calls = Arc::new(AtomicUsize::new(0)); From 924ce737aa8ca3dc38de8562997e4710562fd6b2 Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Tue, 1 Dec 2026 04:18:19 +0000 Subject: [PATCH 07/10] fix(server): close gaps in stored policy validation Address review feedback on RFC 0027 persistence-boundary validation: - Image update begin and complete keep the locked row's spec.policy bytes; they wrote the sandbox directly and erased newer restrictions. - The spec policy check and its use share one stored row. A sandbox read from storage whose policy no longer matches the row gets ABORTED so the caller reads again, and a deleted row gets NOT_FOUND. Resource versions alone cannot detect this because unconditional writes keep them. - Stored policies, drafts, and profile endpoints the scanner cannot parse are refused, even where prost would decode them, such as unknown groups. - An unreadable provider profile no longer fails the whole catalog. It is left out, configurations whose providers resolve to it are not admitted, and DeleteProviderProfile can still remove it. - Draft RPCs map an unreadable stored draft to FAILED_PRECONDITION instead of INTERNAL. - ForwardTcp holds a weak response sender in its request reader, so the response still ends at relay EOF while the client keeps sending. Refs #6097 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Mrunal Patel --- .../src/config_delivery/mod.rs | 53 ++++ crates/openshell-server/src/grpc/policy.rs | 295 +++++++++++++++--- .../src/grpc/policy/config_inputs.rs | 15 +- crates/openshell-server/src/grpc/provider.rs | 6 +- crates/openshell-server/src/grpc/sandbox.rs | 64 +++- .../openshell-server/src/persistence/mod.rs | 13 +- .../src/persistence/sandbox_image.rs | 120 ++++++- crates/openshell-server/src/policy_store.rs | 13 +- .../src/provider_profile_sources.rs | 214 ++++++++++--- crates/openshell-server/src/storage_proto.rs | 2 +- .../src/wire_validation/stored.rs | 81 +++-- docs/observability/gateway-metrics.mdx | 2 +- 12 files changed, 716 insertions(+), 162 deletions(-) diff --git a/crates/openshell-server/src/config_delivery/mod.rs b/crates/openshell-server/src/config_delivery/mod.rs index 3066bb3df8..24d4401b41 100644 --- a/crates/openshell-server/src/config_delivery/mod.rs +++ b/crates/openshell-server/src/config_delivery/mod.rs @@ -1836,6 +1836,59 @@ mod tests { assert_eq!(error.code(), Code::FailedPrecondition); } + #[tokio::test] + async fn unreadable_provider_profile_rejects_only_dependent_configurations() { + use openshell_core::proto::{NetworkEndpoint, ProviderProfile}; + use prost::Message as _; + + let state = push_state().await; + // A platform profile for `github` whose endpoint carries a restriction + // from a newer gateway. + let mut endpoint = NetworkEndpoint { + host: "api.github.com".into(), + port: 443, + ..Default::default() + } + .encode_to_vec(); + prost::encoding::encode_varint(900 << 3, &mut endpoint); + prost::encoding::encode_varint(1, &mut endpoint); + let mut profile = ProviderProfile { + id: "github".into(), + ..Default::default() + } + .encode_to_vec(); + prost::encoding::bytes::encode(6, &endpoint, &mut profile); + let mut stored = Vec::new(); + prost::encoding::bytes::encode(2, &profile, &mut stored); + state + .store + .put( + "provider_profile", + "github-profile", + "github", + "", + &stored, + None, + ) + .await + .unwrap(); + put_provider(&state, "gh").await; + put_sandbox(&state, "uses-profile", &["gh"]).await; + put_sandbox(&state, "unrelated", &[]).await; + + assert_not_admitted( + build_sandbox_config(&state, "uses-profile", Vec::new()) + .await + .unwrap(), + ); + assert!(matches!( + build_sandbox_config(&state, "unrelated", Vec::new()) + .await + .unwrap(), + Some(BuiltSandboxConfig::Built(..)) + )); + } + #[test] fn fanout_marks_ten_thousand_sessions_once_each() { let delivery = ConfigDelivery::for_db_connections(5); diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index c4ece458b6..a14a8aaab5 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -1152,7 +1152,7 @@ async fn reconcile_pending_chunks_covered_by_policy( .store .list_draft_chunks(sandbox_id, Some("pending")) .await - .map_err(|error| Status::internal(format!("list pending chunks failed: {error}")))?; + .map_err(|error| super::persistence_error_to_status(error, "list pending chunks"))?; let mut reconciled = 0; for chunk in pending { let Some(rule) = decode_draft_chunk_rule(&chunk)? else { @@ -1230,7 +1230,7 @@ async fn refresh_pending_chunk_evaluations( .store .list_draft_chunks(sandbox.object_id(), Some("pending")) .await - .map_err(|error| Status::internal(format!("list pending chunks failed: {error}")))?; + .map_err(|error| super::persistence_error_to_status(error, "list pending chunks"))?; if pending.len() > MAX_PENDING_REFRESH_PER_POLICY_CHANGE { debug!( sandbox_id = %sandbox.object_id(), @@ -1824,7 +1824,7 @@ async fn auto_approve_chunk( .store .get_draft_chunk(chunk_id) .await - .map_err(|e| Status::internal(format!("fetch chunk failed: {e}")))? + .map_err(|e| super::persistence_error_to_status(e, "fetch chunk"))? .ok_or_else(|| Status::not_found("chunk not found"))?; // The chunk may have been superseded or rejected by something else @@ -2002,9 +2002,13 @@ async fn current_effective_policy_from_records( .await .map_err(|e| Status::internal(format!("fetch latest policy failed: {e}")))? }; - if global_policy.is_none() && latest_policy.is_none() { - require_known_spec_policy(state.store.as_ref(), sandbox).await?; - } + let checked; + let sandbox = if global_policy.is_none() && latest_policy.is_none() { + checked = Box::pin(with_known_spec_policy(state.store.as_ref(), sandbox)).await?; + &checked + } else { + sandbox + }; effective_policy_from_captured_inputs( catalog, records, @@ -2439,11 +2443,10 @@ pub(super) async fn current_base_policy_for_sandbox( let (policy, _) = canonical_policy_record_identity(&record)?; return Ok(policy); } - require_known_spec_policy(store, sandbox).await?; - sandbox + Box::pin(with_known_spec_policy(store, sandbox)) + .await? .spec - .as_ref() - .and_then(|spec| spec.policy.clone()) + .and_then(|spec| spec.policy) .map_or_else( || Ok(ProtoSandboxPolicy::default()), |policy| validate_and_canonicalize_stored_policy(policy, STORED_POLICY_SOURCE_SPEC), @@ -3014,10 +3017,17 @@ async fn build_sandbox_config_snapshot_with_sources( .as_ref() .ok_or_else(|| Status::internal("sandbox has no spec"))?; - match spec.policy.clone() { + let spec_policy = if spec.policy.is_some() { + Box::pin(with_known_spec_policy(state.store.as_ref(), sandbox)) + .await? + .spec + .and_then(|spec| spec.policy) + } else { + None + }; + match spec_policy { None => (None, 0, String::new(), PolicySource::Sandbox), Some(spec_policy) => { - require_known_spec_policy(state.store.as_ref(), sandbox).await?; let spec_policy = validate_and_canonicalize_stored_policy( spec_policy, STORED_POLICY_SOURCE_SPEC, @@ -3230,9 +3240,14 @@ pub async fn initialize_policy_history( sandbox: &Sandbox, status: InitialPolicyHistoryStatus, ) -> Result { - let Some(policy) = sandbox.spec.as_ref().and_then(|spec| spec.policy.as_ref()) else { + if sandbox + .spec + .as_ref() + .and_then(|spec| spec.policy.as_ref()) + .is_none() + { return Ok(false); - }; + } if store .get_latest_policy(sandbox.object_id()) .await @@ -3241,9 +3256,14 @@ pub async fn initialize_policy_history( { return Ok(false); } - require_known_spec_policy(store, sandbox).await?; - let policy = - validate_and_canonicalize_stored_policy(policy.clone(), STORED_POLICY_SOURCE_SPEC)?; + let Some(policy) = with_known_spec_policy(store, sandbox) + .await? + .spec + .and_then(|spec| spec.policy) + else { + return Ok(false); + }; + let policy = validate_and_canonicalize_stored_policy(policy, STORED_POLICY_SOURCE_SPEC)?; store .put_initial_policy_revision( &PolicyRecord { @@ -4669,7 +4689,7 @@ async fn handle_update_config_inner( super::persistence_error_to_status(error, "acquire policy mutation lock") })?; // Merges build on, and replacements compare against, the spec baseline. - require_known_spec_policy(state.store.as_ref(), &sandbox).await?; + let sandbox = with_known_spec_policy(state.store.as_ref(), &sandbox).await?; if has_merge_ops { let global_settings = load_global_settings(state.store.as_ref()).await?; if global_settings.settings.contains_key(POLICY_SETTING_KEY) { @@ -5954,7 +5974,7 @@ pub(super) async fn handle_submit_policy_analysis( .list_draft_chunks(&sandbox_id, None) .await .map_err(|error| { - Status::internal(format!("list draft chunks for dedup failed: {error}")) + super::persistence_error_to_status(error, "list draft chunks for dedup") })?; incoming_observation_key .as_ref() @@ -6213,7 +6233,7 @@ pub(super) async fn handle_get_draft_policy( .store .list_draft_chunks(&sandbox_id, status_filter) .await - .map_err(|e| Status::internal(format!("list draft chunks failed: {e}")))?; + .map_err(|e| super::persistence_error_to_status(e, "list draft chunks"))?; let draft_version = state .store @@ -6286,7 +6306,7 @@ async fn handle_approve_draft_chunk_inner( .store .get_draft_chunk(&req.chunk_id) .await - .map_err(|e| Status::internal(format!("fetch chunk failed: {e}")))? + .map_err(|e| super::persistence_error_to_status(e, "fetch chunk"))? .ok_or_else(|| Status::not_found("chunk not found"))?; ensure_chunk_belongs_to_sandbox(&chunk, &sandbox_id)?; @@ -6432,7 +6452,7 @@ async fn handle_reject_draft_chunk_inner( .store .get_draft_chunk(&req.chunk_id) .await - .map_err(|e| Status::internal(format!("fetch chunk failed: {e}")))? + .map_err(|e| super::persistence_error_to_status(e, "fetch chunk"))? .ok_or_else(|| Status::not_found("chunk not found"))?; ensure_chunk_belongs_to_sandbox(&chunk, &sandbox_id)?; @@ -6537,7 +6557,7 @@ async fn handle_approve_all_draft_chunks_inner( .store .list_draft_chunks(&sandbox_id, Some("pending")) .await - .map_err(|e| Status::internal(format!("list draft chunks failed: {e}")))?; + .map_err(|e| super::persistence_error_to_status(e, "list draft chunks"))?; if pending_chunks.is_empty() { return Err(Status::failed_precondition("no pending chunks to approve")); @@ -6845,7 +6865,7 @@ pub(super) async fn handle_edit_draft_chunk( .store .get_draft_chunk(&req.chunk_id) .await - .map_err(|e| Status::internal(format!("fetch chunk failed: {e}")))? + .map_err(|e| super::persistence_error_to_status(e, "fetch chunk"))? .ok_or_else(|| Status::not_found("chunk not found"))?; ensure_chunk_belongs_to_sandbox(&chunk, &sandbox_id)?; @@ -6918,7 +6938,7 @@ async fn handle_undo_draft_chunk_inner( .store .get_draft_chunk(&req.chunk_id) .await - .map_err(|e| Status::internal(format!("fetch chunk failed: {e}")))? + .map_err(|e| super::persistence_error_to_status(e, "fetch chunk"))? .ok_or_else(|| Status::not_found("chunk not found"))?; ensure_chunk_belongs_to_sandbox(&chunk, &sandbox_id)?; @@ -7038,7 +7058,7 @@ pub(super) async fn handle_get_draft_history( .store .list_draft_chunks(&sandbox_id, None) .await - .map_err(|e| Status::internal(format!("list draft chunks failed: {e}")))?; + .map_err(|e| super::persistence_error_to_status(e, "list draft chunks"))?; let mut entries: Vec = Vec::new(); @@ -7090,38 +7110,62 @@ pub(super) async fn handle_get_draft_history( // Policy helper functions // --------------------------------------------------------------------------- -/// Refuse a sandbox spec policy whose stored bytes carry restrictions this -/// build would drop (RFC 0027). +/// Check `sandbox.spec.policy` against the raw stored row before it is used +/// (RFC 0027). /// -/// The decoded `Sandbox` has already lost unknown fields, so read the raw -/// row. Call before evaluating, canonicalizing, comparing, or delivering a -/// spec policy. -pub async fn require_known_spec_policy(store: &Store, sandbox: &Sandbox) -> Result<(), Status> { - if sandbox - .spec - .as_ref() - .and_then(|spec| spec.policy.as_ref()) - .is_none() - { - return Ok(()); - } +/// A decoded `Sandbox` has already lost unknown fields, so the raw row decides: +/// +/// - When the caller's policy equals the known fields of the stored policy, +/// it came from that row. The row is scanned and a policy with restrictions +/// this build does not know is refused. +/// - When a sandbox read from storage no longer matches the row, the row +/// changed after the read and the check cannot vouch for the caller's copy: +/// `ABORTED`, so the caller reads again. Resource versions are not enough +/// here, because unconditional writes keep them. +/// - An unsaved sandbox (resource version 0) holds a policy this build +/// constructed, which no stored bytes back. +/// +/// Call before evaluating, canonicalizing, comparing, or delivering a spec +/// policy, and use the returned sandbox. +pub async fn with_known_spec_policy(store: &Store, sandbox: &Sandbox) -> Result { + use crate::wire_validation::stored::{StoredPolicySource, require_known_stored_policy}; + + let Some(policy) = sandbox.spec.as_ref().and_then(|spec| spec.policy.as_ref()) else { + return Ok(sandbox.clone()); + }; + let read_version = openshell_core::GetResourceVersion::get_resource_version(sandbox); let Some(record) = store .get(Sandbox::object_type(), sandbox.object_id()) .await .map_err(|error| super::persistence_error_to_status(error, "fetch sandbox"))? else { - return Ok(()); + if read_version == 0 { + return Ok(sandbox.clone()); + } + return Err(Status::not_found( + "sandbox was deleted while its policy was loaded", + )); }; let payload = crate::persistence::migrate_legacy_time_fields(Sandbox::object_type(), &record.payload) .map_err(|error| Status::internal(format!("decode sandbox failed: {error}")))?; - match crate::wire_validation::sandbox_policy::extract_spec_policy(&payload) { - Ok(Some(policy)) => crate::wire_validation::stored::require_known_stored_policy( - &policy, - crate::wire_validation::stored::StoredPolicySource::Spec, - ), - Ok(None) | Err(_) => Ok(()), + let raw = crate::wire_validation::sandbox_policy::extract_spec_policy(&payload) + .map_err(|rejection| StoredPolicySource::Spec.reject(&rejection))?; + let stored = raw + .as_deref() + .map(ProtoSandboxPolicy::decode) + .transpose() + .map_err(|error| Status::internal(format!("decode sandbox spec policy failed: {error}")))?; + if stored.as_ref() == Some(policy) { + if let Some(raw) = raw { + require_known_stored_policy(&raw, StoredPolicySource::Spec)?; + } + } else if read_version != 0 { + return Err(Status::aborted( + "sandbox policy changed while it was loaded; retry", + )); } + Ok(sandbox.clone()) } /// Rebuilds a policy revision's identity from its checked canonical payload. @@ -17695,6 +17739,163 @@ mod tests { ); } + #[tokio::test] + async fn spec_policy_check_and_use_share_one_stored_row() { + let state = test_server_state().await; + let policy = |version| ProtoSandboxPolicy { + version, + ..Default::default() + }; + let newer = { + let mut bytes = policy(1).encode_to_vec(); + prost::encoding::encode_varint(900 << 3, &mut bytes); + prost::encoding::encode_varint(1, &mut bytes); + bytes + }; + let base = test_sandbox("sb-race", "race", policy(1), vec![]); + let write_raw = |payload: Vec| { + let store = state.store.clone(); + async move { + store + .put("sandbox", "sb-race", "race", "default", &payload, None) + .await + .unwrap(); + } + }; + let splice = |policy: &[u8]| { + crate::wire_validation::sandbox_policy::splice_spec_policy( + &base.encode_to_vec(), + Some(policy), + ) + .unwrap() + }; + + // The decoded copy of a row with a newer restriction is refused. + write_raw(splice(&newer)).await; + let stripped = state + .store + .get_message::("sb-race") + .await + .unwrap() + .unwrap(); + let error = with_known_spec_policy(state.store.as_ref(), &stripped) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition); + + // The row is replaced by a clean, different policy after the read: the + // stripped copy must not pass on the strength of the newer row. + write_raw(splice(&policy(2).encode_to_vec())).await; + let error = with_known_spec_policy(state.store.as_ref(), &stripped) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::Aborted); + + // A fresh read of the replacement passes. + let current = state + .store + .get_message::("sb-race") + .await + .unwrap() + .unwrap(); + assert!( + with_known_spec_policy(state.store.as_ref(), ¤t) + .await + .is_ok() + ); + + // An unsaved sandbox with its own policy is not tied to the row. + let unsaved = test_sandbox("sb-race", "race", policy(3), vec![]); + let checked = with_known_spec_policy(state.store.as_ref(), &unsaved) + .await + .unwrap(); + assert_eq!(checked.spec.unwrap().policy, Some(policy(3))); + + // A deleted row fails a stored read; an unsaved sandbox has no row. + state.store.delete("sandbox", "sb-race").await.unwrap(); + let error = with_known_spec_policy(state.store.as_ref(), ¤t) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::NotFound); + assert!( + with_known_spec_policy(state.store.as_ref(), &base) + .await + .is_ok() + ); + } + + #[tokio::test] + async fn draft_rpcs_refuse_drafts_with_newer_restrictions() { + let state = test_server_state().await; + let sandbox_id = "sb-newer-draft"; + let sandbox_name = "newer-draft"; + state + .store + .put_message(&test_sandbox( + sandbox_id, + sandbox_name, + ProtoSandboxPolicy::default(), + vec![], + )) + .await + .unwrap(); + let chunk = pending_draft_chunk("newer-draft-chunk", sandbox_id); + state + .store + .put_draft_chunk(&chunk, None, "default") + .await + .unwrap(); + + // A newer gateway stored a proposed rule restriction this build does + // not know. Protobuf merges the extra proposed_rule occurrence. + let mut rule = NetworkPolicyRule { + name: chunk.rule_name.clone(), + ..Default::default() + } + .encode_to_vec(); + prost::encoding::encode_varint(900 << 3, &mut rule); + prost::encoding::encode_varint(1, &mut rule); + let mut payload = crate::policy_store::draft_chunk_payload_from_record(&chunk).unwrap(); + prost::encoding::bytes::encode(2, &rule, &mut payload); + let sql = format!( + "UPDATE objects SET payload = X'{}' WHERE id = '{}'", + hex::encode(&payload), + chunk.id + ); + state + .store + .execute_for_test(Box::leak(sql.into_boxed_str())) + .await; + + let workspace_scope = Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )); + let error = handle_get_draft_policy( + &state, + with_user(Request::new(GetDraftPolicyRequest { + sandbox: sandbox_name.to_string(), + workspace_scope: workspace_scope.clone(), + status_filter: String::new(), + })), + ) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition, "{error}"); + + let error = Box::pin(handle_approve_draft_chunk( + &state, + with_user(Request::new(ApproveDraftChunkRequest { + sandbox: sandbox_name.to_string(), + workspace_scope, + chunk_id: chunk.id.clone(), + ..Default::default() + })), + )) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition, "{error}"); + } + #[tokio::test] async fn approve_all_recomputes_empty_legacy_security_notes() { let state = test_server_state().await; diff --git a/crates/openshell-server/src/grpc/policy/config_inputs.rs b/crates/openshell-server/src/grpc/policy/config_inputs.rs index 485792a7a1..ca9463fb39 100644 --- a/crates/openshell-server/src/grpc/policy/config_inputs.rs +++ b/crates/openshell-server/src/grpc/policy/config_inputs.rs @@ -68,14 +68,23 @@ pub async fn load_sandbox_config_inputs( .map_err(|e| Status::internal(format!("fetch policy history failed: {e}"))) }, )?; + // Only sandboxes whose providers use an unreadable profile are refused. + for record in &provider_records { + catalog.require_compatible_profile( + &record.provider.r#type, + &record.provider.profile_workspace, + )?; + } // Without history or a global override, the spec policy is the source. - if latest_policy.is_none() + let sandbox = if latest_policy.is_none() && !global_settings .settings .contains_key(super::POLICY_SETTING_KEY) { - super::require_known_spec_policy(store, &sandbox).await?; - } + Box::pin(super::with_known_spec_policy(store, &sandbox)).await? + } else { + sandbox + }; Ok(SandboxConfigInputs { sandbox, catalog, diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index e14424bc9c..593ca6a0c5 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -3483,9 +3483,11 @@ pub(super) async fn handle_delete_provider_profile( ))); } + // Read the row without decoding it: a profile this build cannot read + // safely (RFC 0027) must still be removable. let existing = state .store - .get_message_by_name::(&workspace, &id) + .get_by_name(StoredProviderProfile::object_type(), &workspace, &id) .await .map_err(|e| Status::internal(format!("fetch provider profile failed: {e}")))?; let Some(existing) = existing else { @@ -3504,7 +3506,7 @@ pub(super) async fn handle_delete_provider_profile( state .store - .delete(StoredProviderProfile::object_type(), existing.object_id()) + .delete(StoredProviderProfile::object_type(), &existing.id) .await .map_err(|e| Status::internal(format!("delete provider profile failed: {e}")))?; publish_provider_profile_change(state, &workspace); diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index cf44fa60b5..7beb94845e 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -3282,7 +3282,9 @@ async fn bridge_forward_tcp_stream( let sandbox_id_in = sandbox_id.to_string(); let channel_id_in = channel_id.to_string(); - let tx_in = tx.clone(); + // A weak sender: the response stream must still end when the relay reader + // below finishes, even while the client keeps its request stream open. + let tx_in = tx.downgrade(); tokio::spawn(async move { loop { match inbound.message().await { @@ -3308,8 +3310,10 @@ async fn bridge_forward_tcp_stream( debug!(sandbox_id = %sandbox_id_in, channel_id = %channel_id_in, error = %err, "ForwardTcp: inbound stream ended"); // Report request-frame rejections (RFC 0027 ingress // validation) to the client instead of a silent close. - if is_request_frame_rejection(&err) { - let _ = tx_in.send(Err(err)).await; + if is_request_frame_rejection(&err) + && let Some(tx) = tx_in.upgrade() + { + let _ = tx.send(Err(err)).await; } break; } @@ -4533,6 +4537,60 @@ mod tests { bridge.await.unwrap(); } + #[tokio::test] + async fn forward_tcp_response_ends_at_relay_eof_while_request_stream_stays_open() { + use http_body_util::StreamBody; + use openshell_core::proto::tcp_forward_frame::Payload; + + struct Decode; + impl tonic::codec::Decoder for Decode { + type Item = TcpForwardFrame; + type Error = Status; + fn decode( + &mut self, + buf: &mut tonic::codec::DecodeBuf<'_>, + ) -> Result, Status> { + TcpForwardFrame::decode(buf) + .map(Some) + .map_err(|error| Status::internal(error.to_string())) + } + } + + // The client keeps its request stream open for the whole test. + let (request_tx, request_rx) = mpsc::channel::< + Result, Box>, + >(1); + let inbound = tonic::Streaming::new_request( + Decode, + StreamBody::new(ReceiverStream::new(request_rx)), + None, + None, + ); + let (mut relay, gateway_side) = tokio::io::duplex(1024); + let (tx, mut rx) = mpsc::channel(4); + let bridge = tokio::spawn(async move { + bridge_forward_tcp_stream(inbound, gateway_side, tx, "sb", "ch").await; + }); + + tokio::io::AsyncWriteExt::write_all(&mut relay, b"bye") + .await + .unwrap(); + tokio::io::AsyncWriteExt::shutdown(&mut relay) + .await + .unwrap(); + let first = rx.recv().await.unwrap().unwrap(); + assert!(matches!(first.payload, Some(Payload::Data(data)) if data == b"bye")); + + // Relay EOF ends the response even though the request stream is open. + tokio::time::timeout(std::time::Duration::from_secs(5), async { + assert!(rx.recv().await.is_none()); + }) + .await + .expect("response stream ends at relay EOF"); + bridge.await.unwrap(); + drop(request_tx); + } + #[test] fn exec_requires_ssh_channel_close_after_exit_status() { assert_eq!(exec_loop_result(Some(0), true).unwrap(), 0); diff --git a/crates/openshell-server/src/persistence/mod.rs b/crates/openshell-server/src/persistence/mod.rs index 1b01f83805..0b09ea452e 100644 --- a/crates/openshell-server/src/persistence/mod.rs +++ b/crates/openshell-server/src/persistence/mod.rs @@ -341,7 +341,7 @@ pub fn generate_name() -> String { /// Extracted to avoid repeating the identical decode-and-hydrate block across /// `get_message`, `get_message_by_name`, `list_messages`, and /// `list_messages_with_selector`. -fn decode_record( +pub fn decode_record( record: ObjectRecord, ) -> PersistenceResult { let payload = legacy_time_wire::migrate(T::object_type(), &record.payload)?; @@ -361,12 +361,11 @@ fn require_known_policy_fields(object_type: &str, payload: &[u8]) -> Persistence if object_type != ::object_type() { return Ok(()); } - match crate::wire_validation::stored::scan_stored_provider_profile(payload) { - Ok(()) | Err(crate::wire_validation::WireRejection::Malformed(_)) => Ok(()), - Err(rejection) => Err(PersistenceError::UnknownFields(format!( - "provider profile endpoints: {rejection}" - ))), - } + // A partial scan never passes, even where prost would decode the bytes. + crate::wire_validation::stored::scan_stored_provider_profile(payload).map_err(|rejection| { + crate::wire_validation::stored::StoredPolicySource::ProviderProfile.count(); + PersistenceError::UnknownFields(format!("provider profile endpoints: {rejection}")) + }) } /// Dispatch a method call to the underlying store implementation. diff --git a/crates/openshell-server/src/persistence/sandbox_image.rs b/crates/openshell-server/src/persistence/sandbox_image.rs index 70877c4d52..251b9d2ee7 100644 --- a/crates/openshell-server/src/persistence/sandbox_image.rs +++ b/crates/openshell-server/src/persistence/sandbox_image.rs @@ -48,11 +48,27 @@ fn decode_state(sandbox_id: &str, payload: &[u8]) -> PersistenceResult PersistenceResult { + decode_locked_sandbox(sandbox_id, payload, resource_version).map(|locked| locked.sandbox) +} + +/// A locked sandbox row: the decoded message and the stored bytes it came +/// from, so a rewrite can keep `spec.policy` fields this build does not know. +struct LockedSandbox { + sandbox: Sandbox, + payload: Vec, +} + +fn decode_locked_sandbox( + sandbox_id: &str, + payload: &[u8], + resource_version: i64, +) -> PersistenceResult { if resource_version < 1 { return Err(PersistenceError::Database( "invalid sandbox resource version".into(), @@ -72,7 +88,7 @@ fn decode_sandbox( } // The SQL column, not a possibly stale protobuf field, is authoritative. sandbox.set_resource_version(resource_version.cast_unsigned()); - Ok(sandbox) + Ok(LockedSandbox { sandbox, payload }) } fn resource_version(sandbox: &Sandbox) -> u64 { @@ -360,7 +376,11 @@ ORDER BY id LIMIT $2", expected_resource_version: u64, ) -> PersistenceResult { let mut tx = ImageTransaction::begin(self).await?; - let sandbox = match tx.lock_sandbox(sandbox_id).await { + let sandbox = match tx + .lock_sandbox(sandbox_id) + .await + .map(|locked| locked.sandbox) + { Ok(sandbox) => sandbox, Err(PersistenceError::Conflict { current_resource_version: None, @@ -449,18 +469,24 @@ ORDER BY id LIMIT $2", intent: &StoredSandboxImageUpdate, ) -> PersistenceResult { let mut tx = ImageTransaction::begin(self).await?; - let sandbox = tx.lock_sandbox(sandbox_id).await?; + let locked = tx.lock_sandbox(sandbox_id).await?; let state = tx.lock_state(sandbox_id).await?; - let previous_version = resource_version(&sandbox); + let previous_version = resource_version(&locked.sandbox); let (sandbox, state) = project_begin( - sandbox, + locked.sandbox, state, expected_sandbox_resource_version, expected_revision, intent, )?; - tx.write_projection(sandbox_id, previous_version, &sandbox, &state) - .await?; + tx.write_projection( + sandbox_id, + previous_version, + &locked.payload, + &sandbox, + &state, + ) + .await?; tx.commit().await?; Ok(sandbox) } @@ -472,16 +498,22 @@ ORDER BY id LIMIT $2", intent: &StoredSandboxImageUpdate, ) -> PersistenceResult { let mut tx = ImageTransaction::begin(self).await?; - let sandbox = tx.lock_sandbox(sandbox_id).await?; + let locked = tx.lock_sandbox(sandbox_id).await?; let state = tx.lock_state(sandbox_id).await?; - let previous_version = resource_version(&sandbox); - let (sandbox, state) = project_complete(sandbox, state, intent)?; + let previous_version = resource_version(&locked.sandbox); + let (sandbox, state) = project_complete(locked.sandbox, state, intent)?; if resource_version(&sandbox) == previous_version { tx.commit().await?; return Ok(sandbox); } - tx.write_projection(sandbox_id, previous_version, &sandbox, &state) - .await?; + tx.write_projection( + sandbox_id, + previous_version, + &locked.payload, + &sandbox, + &state, + ) + .await?; tx.commit().await?; Ok(sandbox) } @@ -506,7 +538,7 @@ impl ImageTransaction { .map_err(|error| map_db_error(&error)) } - async fn lock_sandbox(&mut self, sandbox_id: &str) -> PersistenceResult { + async fn lock_sandbox(&mut self, sandbox_id: &str) -> PersistenceResult { let row = match self { Self::Sqlite(tx) => { sqlx::query_as::<_, (Vec, i64)>( @@ -529,7 +561,7 @@ WHERE object_type = 'sandbox' AND id = $1 FOR UPDATE", } .map_err(|error| map_db_error(&error))? .ok_or_else(|| conflict(None))?; - decode_sandbox(sandbox_id, &row.0, row.1) + decode_locked_sandbox(sandbox_id, &row.0, row.1) } async fn lock_state( @@ -563,10 +595,14 @@ WHERE object_type = 'sandbox' AND id = $1 FOR UPDATE", .transpose() } + /// `stored_payload` is the locked row's migrated payload. Its + /// `spec.policy` bytes are kept when the projection left the policy this + /// build understands unchanged (RFC 0027). async fn write_projection( &mut self, sandbox_id: &str, previous_version: u64, + stored_payload: &[u8], sandbox: &Sandbox, state: &StoredSandboxImageState, ) -> PersistenceResult<()> { @@ -574,7 +610,12 @@ WHERE object_type = 'sandbox' AND id = $1 FOR UPDATE", PersistenceError::Encode("sandbox resource version exceeds database range".into()) })?; let now_ms = current_time_ms(); - let sandbox_payload = sandbox.encode_to_vec(); + let sandbox_payload = + crate::wire_validation::sandbox_policy::encode_preserving_spec_policy( + stored_payload, + sandbox, + ) + .unwrap_or_else(|_| sandbox.encode_to_vec()); let labels = sandbox.metadata.as_ref().map(|metadata| &metadata.labels); let labels = serde_json::to_value(labels) .map_err(|error| PersistenceError::Encode(error.to_string()))?; @@ -1092,6 +1133,55 @@ mod tests { ); } + #[tokio::test] + async fn image_updates_preserve_newer_spec_policy_bytes() { + use crate::wire_validation::sandbox_policy::{extract_spec_policy, splice_spec_policy}; + + let store = super::super::test_store().await; + let mut original = sandbox(); + let policy = openshell_core::proto::SandboxPolicy { + version: 1, + ..Default::default() + }; + original.spec.as_mut().unwrap().policy = Some(policy.clone()); + // A restriction from a newer gateway that this build does not know. + let mut newer = policy.encode_to_vec(); + prost::encoding::encode_varint(900 << 3, &mut newer); + prost::encoding::encode_varint(1, &mut newer); + store + .put( + "sandbox", + "sandbox-id", + original.metadata.as_ref().unwrap().name.as_str(), + original.metadata.as_ref().unwrap().workspace.as_str(), + &splice_spec_policy(&original.encode_to_vec(), Some(&newer)).unwrap(), + None, + ) + .await + .unwrap(); + let stored_policy = || async { + let record = store.get("sandbox", "sandbox-id").await.unwrap().unwrap(); + extract_spec_policy(&record.payload).unwrap() + }; + let current = store + .get_message::("sandbox-id") + .await + .unwrap() + .unwrap(); + + store + .begin_sandbox_image_update("sandbox-id", resource_version(¤t), 0, &intent()) + .await + .unwrap(); + assert_eq!(stored_policy().await, Some(newer.clone()), "after begin"); + + store + .complete_sandbox_image_update("sandbox-id", &intent()) + .await + .unwrap(); + assert_eq!(stored_policy().await, Some(newer), "after complete"); + } + #[tokio::test] async fn sqlite_sandbox_deletion_preserves_intent_on_conflict() { let store = super::super::test_store().await; diff --git a/crates/openshell-server/src/policy_store.rs b/crates/openshell-server/src/policy_store.rs index efa6abd24b..c7b4057d75 100644 --- a/crates/openshell-server/src/policy_store.rs +++ b/crates/openshell-server/src/policy_store.rs @@ -692,13 +692,12 @@ pub fn draft_chunk_record_from_parts( ) -> PersistenceResult { // Scan policy fields before prost drops unknown restrictions and the // proposed rule is re-encoded (RFC 0027). - match crate::wire_validation::stored::scan_draft_chunk_payload(payload) { - Ok(()) | Err(crate::wire_validation::WireRejection::Malformed(_)) => {} - Err(rejection) => { - return Err(PersistenceError::UnknownFields(format!( - "draft chunk {id}: {rejection}" - ))); - } + // A partial scan never passes, even where prost would decode the bytes. + if let Err(rejection) = crate::wire_validation::stored::scan_draft_chunk_payload(payload) { + crate::wire_validation::stored::StoredPolicySource::Draft.count(); + return Err(PersistenceError::UnknownFields(format!( + "draft chunk {id}: {rejection}" + ))); } let wrapper = DraftChunkPayload::decode(payload) .map_err(|e| PersistenceError::Decode(format!("decode draft chunk wrapper failed: {e}")))?; diff --git a/crates/openshell-server/src/provider_profile_sources.rs b/crates/openshell-server/src/provider_profile_sources.rs index f289df4b20..1a0017a78b 100644 --- a/crates/openshell-server/src/provider_profile_sources.rs +++ b/crates/openshell-server/src/provider_profile_sources.rs @@ -65,6 +65,17 @@ impl ObjectType for StoredProviderProfile { pub struct ProviderProfileSnapshot { revision: String, profiles: Vec, + /// Stored profiles this build cannot read without dropping endpoint + /// restrictions (RFC 0027). They stay out of the catalog, and only + /// configurations whose providers resolve to them are refused. + incompatible: Vec, +} + +/// A stored profile whose endpoint restrictions this build does not know. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IncompatibleProfile { + pub scope: ProfileScope, + pub id: String, } #[async_trait] @@ -98,6 +109,9 @@ pub trait ProviderProfileSource: Send + Sync + std::fmt::Debug { snapshot .profiles .retain(|profile| normalize_profile_id(&profile.profile.id).as_deref() == Some(id)); + snapshot + .incompatible + .retain(|profile| normalize_profile_id(&profile.id).as_deref() == Some(id)); Ok(snapshot) } } @@ -126,6 +140,7 @@ impl ProviderProfileSource for UserProviderProfileSource { id: &str, ) -> Result { let mut profiles = Vec::with_capacity(2); + let mut incompatible = Vec::new(); for (namespace, scope) in [ ("", ProfileScope::Platform), (workspace, ProfileScope::Workspace), @@ -133,13 +148,27 @@ impl ProviderProfileSource for UserProviderProfileSource { if namespace.is_empty() && scope == ProfileScope::Workspace { continue; } - if let Some(stored) = store + let stored = match store .get_message_by_name::(namespace, id) .await - .map_err(|error| { - crate::grpc::persistence_error_to_status(error, "fetch provider profile") - })? { + Ok(stored) => stored, + Err(crate::persistence::PersistenceError::UnknownFields(reason)) => { + warn_incompatible_profile(id, &reason); + incompatible.push(IncompatibleProfile { + scope, + id: id.to_string(), + }); + continue; + } + Err(error) => { + return Err(crate::grpc::persistence_error_to_status( + error, + "fetch provider profile", + )); + } + }; + if let Some(stored) = stored { let version = stored_profile_resource_version(&stored); if let Some(profile) = stored.profile { let mut profile = profile_response_payload(profile, version); @@ -154,7 +183,11 @@ impl ProviderProfileSource for UserProviderProfileSource { .map(|entry| entry.profile.clone()) .collect::>(), ); - Ok(ProviderProfileSnapshot { revision, profiles }) + Ok(ProviderProfileSnapshot { + revision, + profiles, + incompatible, + }) } async fn snapshot( @@ -166,51 +199,37 @@ impl ProviderProfileSource for UserProviderProfileSource { let mut hasher = Sha256::new(); hasher.update(b"openshell-user-provider-profile-source-v1"); - let platform_stored: Vec = store - .collect_messages(ObjectListQuery::Workspace("")) - .await - .map_err(|e| { - crate::grpc::persistence_error_to_status(e, "list platform provider profiles") - })?; - for stored in platform_stored { - let resource_version = stored_profile_resource_version(&stored); - hasher.update(resource_version.to_le_bytes()); - if let Some(profile) = stored.profile { - let mut profile = profile_response_payload(profile, resource_version); - normalize_provider_profile_mcp_fields(&mut profile); - hasher.update(canonical_provider_profile_bytes(&profile)); - profiles.push(ScopedSnapshotProfile { - scope: ProfileScope::Platform, - profile, - }); - } - } - + let mut incompatible = Vec::new(); + let mut scopes = vec![(ProfileScope::Platform, "")]; if !workspace.is_empty() { - let ws_stored: Vec = store - .collect_messages(ObjectListQuery::Workspace(workspace)) - .await - .map_err(|e| { - crate::grpc::persistence_error_to_status(e, "list workspace provider profiles") - })?; - for stored in ws_stored { + scopes.push((ProfileScope::Workspace, workspace)); + } + for (scope, namespace) in scopes { + let (stored_profiles, unreadable) = collect_stored_profiles(store, namespace).await?; + for stored in stored_profiles { let resource_version = stored_profile_resource_version(&stored); hasher.update(resource_version.to_le_bytes()); if let Some(profile) = stored.profile { let mut profile = profile_response_payload(profile, resource_version); normalize_provider_profile_mcp_fields(&mut profile); hasher.update(canonical_provider_profile_bytes(&profile)); - profiles.push(ScopedSnapshotProfile { - scope: ProfileScope::Workspace, - profile, - }); + profiles.push(ScopedSnapshotProfile { scope, profile }); } } + for (id, resource_version) in unreadable { + // A profile becoming readable again must change the revision. + hasher.update(b"incompatible"); + hasher.update(resource_version.to_le_bytes()); + hasher.update((id.len() as u64).to_le_bytes()); + hasher.update(id.as_bytes()); + incompatible.push(IncompatibleProfile { scope, id }); + } } Ok(ProviderProfileSnapshot { revision: format!("sha256:{:x}", hasher.finalize()), profiles, + incompatible, }) } } @@ -252,7 +271,11 @@ impl ProviderProfileSource for GatewayInterceptorProfileSource { profile, }) .collect(); - Ok(ProviderProfileSnapshot { revision, profiles }) + Ok(ProviderProfileSnapshot { + revision, + profiles, + incompatible: Vec::new(), + }) } } @@ -363,6 +386,7 @@ impl ProviderProfileSource for CachedProviderProfileSource { Ok(ProviderProfileSnapshot { revision: cached.snapshot.revision.clone(), profiles: cached.profiles_by_id.get(id).cloned().unwrap_or_default(), + incompatible: Vec::new(), }) } @@ -427,6 +451,8 @@ pub struct EffectiveProviderProfileCatalog { profiles: BTreeMap, revision: String, source_count: usize, + /// Stored profiles left out because this build cannot read them safely. + incompatible: Vec, } impl ProviderProfileSources { @@ -555,6 +581,7 @@ impl ProviderProfileSources { snapshot: ProviderProfileSnapshot { revision, profiles: scoped, + incompatible: Vec::new(), }, })]) } @@ -592,6 +619,7 @@ impl ProviderProfileSources { profile, }) .collect(), + incompatible: Vec::new(), }) .collect(), fetch_count, @@ -603,8 +631,9 @@ impl ProviderProfileSources { store: &Store, workspace: &str, ) -> Result { - let snapshots = self.snapshots(store, workspace).await?; - let catalog = build_effective_profiles(snapshots)?; + let (snapshots, incompatible) = self.snapshots(store, workspace).await?; + let mut catalog = build_effective_profiles(snapshots)?; + catalog.incompatible = incompatible; debug!( catalog_revision = %catalog.revision(), source_fetch_count = catalog.source_count(), @@ -623,8 +652,10 @@ impl ProviderProfileSources { let id = normalize_profile_id(id) .ok_or_else(|| Status::failed_precondition("invalid provider profile id"))?; let mut snapshots = Vec::with_capacity(self.sources.len()); + let mut incompatible = Vec::new(); for source in &self.sources { let snapshot = source.snapshot_profile(store, workspace, &id).await?; + incompatible.extend(snapshot.incompatible); snapshots.push(CollectedProviderProfileSnapshot { source_id: source.source_id().to_string(), revision: snapshot.revision, @@ -634,17 +665,27 @@ impl ProviderProfileSources { allow_empty: true, }); } - build_effective_profiles(snapshots) + let mut catalog = build_effective_profiles(snapshots)?; + catalog.incompatible = incompatible; + Ok(catalog) } async fn snapshots( &self, store: &Store, workspace: &str, - ) -> Result, Status> { + ) -> Result< + ( + Vec, + Vec, + ), + Status, + > { let mut snapshots = Vec::with_capacity(self.sources.len()); + let mut incompatible = Vec::new(); for source in &self.sources { let snapshot = source.snapshot(store, workspace).await?; + incompatible.extend(snapshot.incompatible); snapshots.push(CollectedProviderProfileSnapshot { source_id: source.source_id().to_string(), revision: snapshot.revision, @@ -653,8 +694,56 @@ impl ProviderProfileSources { allow_empty: source.allow_empty(), }); } - Ok(snapshots) + Ok((snapshots, incompatible)) + } +} + +/// Stored profiles in one workspace namespace, decoded row by row. +/// +/// A profile whose endpoint restrictions this build does not know is +/// returned by name and resource version instead of failing the listing, so +/// it affects only configurations that use it (RFC 0027). +async fn collect_stored_profiles( + store: &Store, + namespace: &str, +) -> Result<(Vec, Vec<(String, u64)>), Status> { + let records = store + .collect_records( + StoredProviderProfile::object_type(), + ObjectListQuery::Workspace(namespace), + ) + .await + .map_err(|error| { + crate::grpc::persistence_error_to_status(error, "list provider profiles") + })?; + let mut profiles = Vec::with_capacity(records.len()); + let mut incompatible = Vec::new(); + for record in records { + let (name, resource_version) = (record.name.clone(), record.resource_version); + match crate::persistence::decode_record::(record) { + Ok(profile) => profiles.push(profile), + Err(crate::persistence::PersistenceError::UnknownFields(reason)) => { + warn_incompatible_profile(&name, &reason); + incompatible.push((name, resource_version)); + } + Err(error) => { + return Err(crate::grpc::persistence_error_to_status( + error, + "decode provider profile", + )); + } + } } + Ok((profiles, incompatible)) +} + +fn warn_incompatible_profile(id: &str, reason: &str) { + warn!( + profile = %id, + reason = %reason, + "provider profile uses endpoint restrictions this gateway does not know; \ + configurations that use it are not admitted" + ); } fn record_refresh(outcome: &'static str) { @@ -773,6 +862,45 @@ impl EffectiveProviderProfileCatalog { } } + /// Refuse a provider whose profile this build cannot read safely. + /// + /// Resolves the profile the way [`Self::get_type_profile_for_scope`] + /// does: a workspace profile applies when one exists for a provider with + /// a profile workspace, otherwise the platform profile. Returns + /// `FAILED_PRECONDITION`, so the configuration is not admitted. + pub(crate) fn require_compatible_profile( + &self, + id: &str, + profile_workspace: &str, + ) -> Result<(), Status> { + let Some(id) = normalize_profile_id(id) else { + return Ok(()); + }; + let incompatible_in = |scope: ProfileScope| { + self.incompatible + .iter() + .any(|profile| profile.scope == scope && profile.id == id) + }; + let readable_workspace = self + .profiles + .get(&id) + .is_some_and(|entry| entry.effective.scope == ProfileScope::Workspace); + let refused = if profile_workspace.is_empty() { + incompatible_in(ProfileScope::Platform) + } else { + incompatible_in(ProfileScope::Workspace) + || (!readable_workspace && incompatible_in(ProfileScope::Platform)) + }; + if refused { + return Err(Status::failed_precondition(format!( + "provider profile '{id}' uses endpoint restrictions this gateway ({}) does not \ + know; upgrade the gateway or replace the profile", + openshell_core::VERSION + ))); + } + Ok(()) + } + /// The non-user source that manages this profile, if any. /// /// Profiles are import-only, so the only read-only profiles left are the @@ -1024,6 +1152,7 @@ fn build_effective_profiles( profiles, revision: format!("sha256:{:x}", catalog_hasher.finalize()), source_count, + incompatible: Vec::new(), }) } @@ -2718,6 +2847,7 @@ mod tests { scope: ProfileScope::Static, profile: profile("github"), }], + incompatible: Vec::new(), }) } } diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index db7f2bf17e..0e99b460e8 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -664,7 +664,7 @@ mod tests { // decode_record scans profile endpoints. ".openshell.storage.v1.StoredProviderProfile", // Store writes preserve spec.policy bytes; policy readers - // call require_known_spec_policy. + // read through with_known_spec_policy. ".openshell.v1.Sandbox", ], "a durable root that reaches a policy type needs RFC 0027 persistence-boundary protection" diff --git a/crates/openshell-server/src/wire_validation/stored.rs b/crates/openshell-server/src/wire_validation/stored.rs index 36f538d75a..0b46ba0b57 100644 --- a/crates/openshell-server/src/wire_validation/stored.rs +++ b/crates/openshell-server/src/wire_validation/stored.rs @@ -30,7 +30,7 @@ const LEGACY: ScanOptions<'static> = ScanOptions { allowed_reserved: LEGACY_STORED_POLICY_RESERVED, }; -/// Where a stored policy was loaded from. +/// Where a stored policy-bearing payload was loaded from. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StoredPolicySource { /// A sandbox policy revision. @@ -39,6 +39,10 @@ pub enum StoredPolicySource { Global, /// `Sandbox.spec.policy`. Spec, + /// A policy advisor draft chunk. + Draft, + /// A custom provider profile's endpoints. + ProviderProfile, } impl StoredPolicySource { @@ -48,6 +52,8 @@ impl StoredPolicySource { Self::History => "policy_history", Self::Global => "global_policy", Self::Spec => "spec_policy", + Self::Draft => "draft_chunk", + Self::ProviderProfile => "provider_profile", } } @@ -56,44 +62,45 @@ impl StoredPolicySource { Self::History => "sandbox policy history", Self::Global => "global policy setting", Self::Spec => "sandbox spec policy", + Self::Draft => "policy draft chunk", + Self::ProviderProfile => "provider profile endpoints", } } -} -/// Count a stored payload this build refuses, by where it was stored. -fn count(source: &'static str) { - metrics::counter!( - "openshell_server_stored_policy_unknown_fields_total", - "source" => source, - ) - .increment(1); + /// Count a stored payload this build refuses. + pub fn count(self) { + metrics::counter!( + "openshell_server_stored_policy_unknown_fields_total", + "source" => self.label(), + ) + .increment(1); + } + + /// Count `rejection` and return the status refusing the stored payload. + /// + /// `FAILED_PRECONDITION` makes configuration delivery mark the + /// configuration not admitted. + pub fn reject(self, rejection: &WireRejection) -> Status { + self.count(); + Status::failed_precondition(format!( + "{} cannot be read safely by this gateway ({}); upgrade the gateway or \ + replace the stored data ({rejection})", + self.description(), + openshell_core::VERSION + )) + } } -/// Refuse a stored policy with unknown fields or enum values. +/// Refuse a stored policy this build cannot scan completely. /// -/// Returns `FAILED_PRECONDITION` so configuration delivery marks the -/// configuration not admitted. Malformed bytes pass through: the caller's -/// `prost` decode reports them exactly as before. +/// Unknown fields, unknown enum values, and bytes the scanner cannot parse +/// are all refused before `prost` decodes the policy: a partial scan never +/// passes, even where `prost` itself would decode the bytes. pub fn require_known_stored_policy( payload: &[u8], source: StoredPolicySource, ) -> Result<(), Status> { - match scan_named(SANDBOX_POLICY, payload, LEGACY) { - Ok(()) | Err(WireRejection::Malformed(_)) => Ok(()), - Err(rejection) => { - count(source.label()); - Err(stored_rejection(source.description(), &rejection)) - } - } -} - -/// The status for a stored policy this build cannot represent. -pub fn stored_rejection(source: &str, rejection: &WireRejection) -> Status { - Status::failed_precondition(format!( - "{source} uses protobuf fields this gateway ({}) does not know; \ - upgrade the gateway or replace the policy ({rejection})", - openshell_core::VERSION - )) + scan_named(SANDBOX_POLICY, payload, LEGACY).map_err(|rejection| source.reject(&rejection)) } /// Scan the policy-bearing fields of a raw `DraftChunkPayload`. @@ -106,7 +113,7 @@ pub fn scan_draft_chunk_payload(payload: &[u8]) -> Result<(), WireRejection> { _ => continue, }; require_len(field.wire_type)?; - scan_named(message, field.value, LEGACY).inspect_err(|_| count("draft_chunk"))?; + scan_named(message, field.value, LEGACY)?; } Ok(()) } @@ -129,8 +136,7 @@ pub fn scan_stored_provider_profile(payload: &[u8]) -> Result<(), WireRejection> NETWORK_ENDPOINT, profile_field.value, ScanOptions::default(), - ) - .inspect_err(|_| count("provider_profile"))?; + )?; } } Ok(()) @@ -207,8 +213,15 @@ mod tests { } #[test] - fn malformed_stored_policy_is_left_to_the_decoder() { - assert!(require_known_stored_policy(&[0x2a, 0x05], StoredPolicySource::History).is_ok()); + fn unscannable_stored_policy_is_refused() { + // A truncated field, and an unknown group that prost would skip. + for payload in [&[0x2a, 0x05][..], &[0xa3, 0x38, 0xa4, 0x38][..]] { + let status = + require_known_stored_policy(payload, StoredPolicySource::History).unwrap_err(); + assert_eq!(status.code(), tonic::Code::FailedPrecondition); + } + // prost accepts the group, so the scanner is the only guard. + assert!(::decode(&[0xa3, 0x38, 0xa4, 0x38][..]).is_ok()); } #[test] diff --git a/docs/observability/gateway-metrics.mdx b/docs/observability/gateway-metrics.mdx index 4d10ec5f61..d560d01d6c 100644 --- a/docs/observability/gateway-metrics.mdx +++ b/docs/observability/gateway-metrics.mdx @@ -266,7 +266,7 @@ The gateway also records every API request and its background database check: | `openshell_server_grpc_requests_total` | Counter | `method`, `code` | gRPC requests by method name and numeric status code, including internal peer requests. Streaming RPCs record the status known when the response headers are sent. | | `openshell_server_grpc_request_duration_seconds` | Summary | `method`, `code` | Time until the response headers are sent. For streaming RPCs this covers setup only. | | `openshell_server_grpc_unknown_fields_total` | Counter | `service`, `method` | API requests rejected with `UNKNOWN_PROTOBUF_FIELD` because they use protobuf fields or enum values this gateway does not know, usually from a newer client. | -| `openshell_server_stored_policy_unknown_fields_total` | Counter | `source` | Stored policies refused because they use restrictions this gateway does not know, usually after a rollback or during a mixed-version rollout. `source` is `policy_history`, `global_policy`, `spec_policy`, `draft_chunk`, or `provider_profile`. Affected sandbox configurations are not admitted. | +| `openshell_server_stored_policy_unknown_fields_total` | Counter | `source` | Stored policies refused because they use restrictions this gateway does not know or cannot read safely, usually after a rollback or during a mixed-version rollout. `source` is `policy_history`, `global_policy`, `spec_policy`, `draft_chunk`, or `provider_profile`. Sandbox configurations that use an affected policy or profile are not admitted. | | `openshell_server_http_requests_total` | Counter | `path`, `status` | HTTP requests on the API port. `path` is `/_ws_tunnel`, `/auth`, or `unknown`. | | `openshell_server_http_request_duration_seconds` | Summary | `path`, `status` | Duration of those HTTP requests. | | `openshell_server_readiness_database_healthy` | Gauge | None | `1` when the last background database check succeeded, otherwise `0`. | From 7a8d05ffc0e1225ecba31dd70be39554e63de89e Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Tue, 1 Dec 2026 04:18:19 +0000 Subject: [PATCH 08/10] ci(proto): keep 1.x minor trains additive-only Breaking changes are now allowed only on 0.x minor trains and on major trains, including 1.0.0. Within 1.x and later majors, a minor train is additive-only, as RFC 0027 requires. Add a major train kind and test a breaking change on a 1.x minor train. Refs #6097 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Mrunal Patel --- tasks/scripts/check_proto_compatibility.py | 17 ++++-- .../scripts/check_proto_compatibility_test.py | 52 ++++++++++++++++--- 2 files changed, 58 insertions(+), 11 deletions(-) diff --git a/tasks/scripts/check_proto_compatibility.py b/tasks/scripts/check_proto_compatibility.py index 33c71cb06c..0a7783c1f5 100644 --- a/tasks/scripts/check_proto_compatibility.py +++ b/tasks/scripts/check_proto_compatibility.py @@ -26,6 +26,7 @@ def git(*args: str) -> str: NONE = "none" PATCH = "patch" MINOR = "minor" +MAJOR = "major" @dataclass(frozen=True) @@ -37,17 +38,21 @@ class TrainPolicy: forbidden. - ``patch``: a patch train or patch tag. ``proto/`` is frozen: neither breaking nor additive descriptor changes are allowed. - - ``minor``: a minor (or major) train or tag. Additive changes are allowed, - and breaking changes are reported as warnings during ``0.x``. + - ``minor``: a minor train or tag. Additive changes are allowed. Breaking + changes are reported as warnings during ``0.x`` and fail within ``1.x`` + and later majors. + - ``major``: a major train or tag, including ``1.0.0``. Breaking changes + are reported as warnings. """ baseline: str description: str kind: str + major: int = 0 @property def allows_breaks(self) -> bool: - return self.kind == MINOR + return self.kind == MAJOR or (self.kind == MINOR and self.major == 0) @property def allows_additions(self) -> bool: @@ -56,6 +61,8 @@ def allows_additions(self) -> bool: def train_kind(version: tuple[int, int, int], previous: tuple[int, int, int]) -> str: """Classify a release newer than the latest stable release.""" + if version[0] > previous[0]: + return MAJOR return MINOR if version[:2] > previous[:2] else PATCH @@ -85,7 +92,9 @@ def train_policy(ref: str, release: str | None) -> TrainPolicy: raise ValueError(f"Release {release} must be newer than stable {baseline}.") train = "v" + ".".join(map(str, version)) kind = train_kind(version, previous) - return TrainPolicy(baseline, f"{train} {kind} (latest stable: {baseline})", kind) + return TrainPolicy( + baseline, f"{train} {kind} (latest stable: {baseline})", kind, version[0] + ) def definitions(image: dict) -> set[str]: diff --git a/tasks/scripts/check_proto_compatibility_test.py b/tasks/scripts/check_proto_compatibility_test.py index af843337b6..8d3ed50e49 100644 --- a/tasks/scripts/check_proto_compatibility_test.py +++ b/tasks/scripts/check_proto_compatibility_test.py @@ -27,7 +27,8 @@ def _with_tags(monkeypatch: pytest.MonkeyPatch, tags: list[str]) -> None: (["v0.1.0", "v0.1.1-pre.1", "v0.1.1"], compat.NONE, ""), (["v0.1.0", "v0.1.1-pre.1"], compat.PATCH, "v0.1.0"), (["v0.1.0", "v0.2.0-pre.3"], compat.MINOR, "v0.1.0"), - (["v0.9.4", "v1.0.0-pre.1"], compat.MINOR, "v0.9.4"), + (["v0.9.4", "v1.0.0-pre.1"], compat.MAJOR, "v0.9.4"), + (["v1.0.2", "v1.1.0-pre.1"], compat.MINOR, "v1.0.2"), ], ) def test_branch_train_classification( @@ -63,15 +64,21 @@ def test_tag_qualification_classification( @pytest.mark.parametrize( - ("kind", "additions", "breaks"), + ("kind", "major", "additions", "breaks"), [ - (compat.NONE, True, False), - (compat.PATCH, False, False), - (compat.MINOR, True, True), + (compat.NONE, 0, True, False), + (compat.PATCH, 0, False, False), + (compat.MINOR, 0, True, True), + # Within 1.x and later majors, minor trains are additive-only. + (compat.MINOR, 1, True, False), + (compat.MAJOR, 1, True, True), + (compat.PATCH, 1, False, False), ], ) -def test_policy_permissions(kind: str, additions: bool, breaks: bool) -> None: - policy = compat.TrainPolicy("v0.1.0", kind, kind) +def test_policy_permissions( + kind: str, major: int, additions: bool, breaks: bool +) -> None: + policy = compat.TrainPolicy("v0.1.0", kind, kind, major) assert policy.allows_additions is additions assert policy.allows_breaks is breaks @@ -205,3 +212,34 @@ def test_additive_change_fails_only_on_patch_trains( assert result == expected output = capsys.readouterr().out assert ("added field demo.v1.Request#2" in output) is (kind == compat.PATCH) + + +@pytest.mark.skipif(shutil.which("buf") is None, reason="buf is not installed") +@pytest.mark.parametrize( + ("kind", "major", "expected"), + [(compat.MINOR, 0, 0), (compat.MINOR, 1, 100), (compat.MAJOR, 1, 0)], +) +def test_breaking_change_fails_on_a_1x_minor_train( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + kind: str, + major: int, + expected: int, +) -> None: + repo = tmp_path / "repo" + (repo / "proto").mkdir(parents=True) + (repo / "buf.yaml").write_text( + "version: v2\nmodules:\n - path: proto\nbreaking:\n use:\n - FILE\n" + ) + subprocess.run(["git", "init", "-q"], cwd=repo, check=True) + for key, value in (("user.name", "test"), ("user.email", "test@example.com")): + subprocess.run(["git", "config", key, value], cwd=repo, check=True) + before = _commit(repo, " string note = 2;\n") + # Removing a field is a breaking change. + after = _commit(repo, "") + monkeypatch.chdir(repo) + monkeypatch.delenv("GITHUB_ACTIONS", raising=False) + + policy = compat.TrainPolicy(f"v{major}.0.0", kind, kind, major) + + assert compat.compare(after, before, policy) == expected From 6ac8a470bfa6c8a464775073c428739cc5d086d9 Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Tue, 1 Dec 2026 05:19:53 +0000 Subject: [PATCH 09/10] fix(server): isolate unreadable stored policies and profiles Address the second round of RFC 0027 review feedback: - Startup preflight sets aside a sandbox whose stored policy or provider profile this gateway cannot read, instead of failing run_server. Delivery still refuses it. Such refusals now carry ErrorInfo reason UNKNOWN_PROTOBUF_FIELD so callers can tell them apart. - Scoped profile resolution enforces incompatibility itself, so an unreadable workspace profile never falls back to a same-ID platform profile, including for brokered token grants. - Provider profile endpoints are scanned before legacy migration, so an unreadable endpoint, such as one with a group, stays isolated to that profile instead of failing the whole catalog. - UpdateProviderProfiles reads only the stored metadata and row version, so a compatible full replacement can repair an unreadable profile in place while keeping the version check. Refs #6097 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Mrunal Patel --- .../src/config_delivery/mod.rs | 98 ++++++------ crates/openshell-server/src/grpc/mod.rs | 4 +- crates/openshell-server/src/grpc/policy.rs | 108 ++++++++++++- crates/openshell-server/src/grpc/provider.rs | 142 ++++++++++++++++-- .../src/grpc/provider/access_token.rs | 129 ++++++++++++++++ .../openshell-server/src/persistence/mod.rs | 5 +- .../src/provider_profile_sources.rs | 18 ++- .../src/wire_validation/stored.rs | 38 ++++- 8 files changed, 472 insertions(+), 70 deletions(-) diff --git a/crates/openshell-server/src/config_delivery/mod.rs b/crates/openshell-server/src/config_delivery/mod.rs index 24d4401b41..34af532606 100644 --- a/crates/openshell-server/src/config_delivery/mod.rs +++ b/crates/openshell-server/src/config_delivery/mod.rs @@ -1841,52 +1841,60 @@ mod tests { use openshell_core::proto::{NetworkEndpoint, ProviderProfile}; use prost::Message as _; - let state = push_state().await; - // A platform profile for `github` whose endpoint carries a restriction - // from a newer gateway. - let mut endpoint = NetworkEndpoint { - host: "api.github.com".into(), - port: 443, - ..Default::default() - } - .encode_to_vec(); - prost::encoding::encode_varint(900 << 3, &mut endpoint); - prost::encoding::encode_varint(1, &mut endpoint); - let mut profile = ProviderProfile { - id: "github".into(), - ..Default::default() - } - .encode_to_vec(); - prost::encoding::bytes::encode(6, &endpoint, &mut profile); - let mut stored = Vec::new(); - prost::encoding::bytes::encode(2, &profile, &mut stored); - state - .store - .put( - "provider_profile", - "github-profile", - "github", - "", - &stored, - None, - ) - .await - .unwrap(); - put_provider(&state, "gh").await; - put_sandbox(&state, "uses-profile", &["gh"]).await; - put_sandbox(&state, "unrelated", &[]).await; - - assert_not_admitted( - build_sandbox_config(&state, "uses-profile", Vec::new()) - .await - .unwrap(), - ); - assert!(matches!( - build_sandbox_config(&state, "unrelated", Vec::new()) + // A newer endpoint restriction, and a group that legacy migration + // cannot walk: both affect only sandboxes that use the profile. + let unknown_field = { + let mut bytes = Vec::new(); + prost::encoding::encode_varint(900 << 3, &mut bytes); + prost::encoding::encode_varint(1, &mut bytes); + bytes + }; + let group = vec![0xa3, 0x38, 0xa4, 0x38]; + for unreadable in [unknown_field, group] { + let state = push_state().await; + let mut endpoint = NetworkEndpoint { + host: "api.github.com".into(), + port: 443, + ..Default::default() + } + .encode_to_vec(); + endpoint.extend_from_slice(&unreadable); + let mut profile = ProviderProfile { + id: "github".into(), + ..Default::default() + } + .encode_to_vec(); + prost::encoding::bytes::encode(6, &endpoint, &mut profile); + let mut stored = Vec::new(); + prost::encoding::bytes::encode(2, &profile, &mut stored); + state + .store + .put( + "provider_profile", + "github-profile", + "github", + "", + &stored, + None, + ) .await - .unwrap(), - Some(BuiltSandboxConfig::Built(..)) - )); + .unwrap(); + put_provider(&state, "gh").await; + put_sandbox(&state, "uses-profile", &["gh"]).await; + put_sandbox(&state, "unrelated", &[]).await; + + assert_not_admitted( + build_sandbox_config(&state, "uses-profile", Vec::new()) + .await + .unwrap(), + ); + assert!(matches!( + build_sandbox_config(&state, "unrelated", Vec::new()) + .await + .unwrap(), + Some(BuiltSandboxConfig::Built(..)) + )); + } } #[test] diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index d17af2bb5b..5c6c5c661c 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -124,7 +124,9 @@ pub fn persistence_error_to_status( std::time::Duration::from_secs(1), ), error @ PersistenceError::UnknownFields(_) => { - Status::failed_precondition(format!("{operation} failed: {error}")) + crate::wire_validation::stored::incompatible_status(&format!( + "{operation} failed: {error}" + )) } other => Status::internal(format!("{operation} failed: {other}")), } diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index a14a8aaab5..743bda446b 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -2551,8 +2551,24 @@ async fn validate_provider_composition_for_existing_sandboxes( let catalog = catalogs .get(&workspace) .expect("catalog was inserted for sandbox workspace"); - let base_policy = - current_base_policy_for_sandbox(state.store.as_ref(), &sandbox).await?; + // Stored data this build cannot read safely (RFC 0027) refuses only + // this sandbox: its configuration is not admitted on delivery. Like + // an unsupported Cedar policy, it must not stop the gateway. + let base_policy = match current_base_policy_for_sandbox(state.store.as_ref(), &sandbox) + .await + { + Ok(policy) => policy, + Err(error) if crate::wire_validation::stored::is_incompatible(&error) => { + warn!( + workspace = %workspace, + sandbox = %sandbox.object_name(), + error = %error.message(), + "skipping provider composition check for a sandbox whose stored policy this gateway cannot read" + ); + continue; + } + Err(error) => return Err(error), + }; // A provider deleted under a sandbox leaves a dangling reference. The // sandbox already fails closed, so warn and validate the rest. let (records, missing) = super::provider::load_existing_provider_environment_records( @@ -2570,6 +2586,22 @@ async fn validate_provider_composition_for_existing_sandboxes( "sandbox references providers that no longer exist" ); } + if let Some(error) = records.iter().find_map(|record| { + catalog + .require_compatible_profile( + &record.provider.r#type, + &record.provider.profile_workspace, + ) + .err() + }) { + warn!( + workspace = %workspace, + sandbox = %sandbox.object_name(), + error = %error.message(), + "skipping provider composition check for a sandbox whose provider profile this gateway cannot read" + ); + continue; + } let provider_layers = provider_policy_context_from_records(catalog, &records).layers; validate_candidate_effective_policy(&base_policy, &provider_layers).map_err(|error| { Status::failed_precondition(format!( @@ -24077,6 +24109,78 @@ mod tests { assert!(settings.settings.contains_key(POLICY_SETTING_KEY)); } + /// A sandbox with providers whose stored policy revision carries a + /// restriction this build does not know. + async fn install_sandbox_with_newer_policy(state: &Arc) -> Sandbox { + use crate::policy_store::PolicyStoreExt as _; + + state + .store + .put_message(&test_provider("provider-newer", "newer-profile")) + .await + .unwrap(); + state + .store + .put_message(&test_sandbox( + "sandbox-newer", + "sandbox-newer", + test_policy_with_rule("base", "api.example.com"), + vec!["provider-newer".to_string()], + )) + .await + .unwrap(); + let mut newer = test_policy_with_rule("base", "api.example.com").encode_to_vec(); + prost::encoding::encode_varint(900 << 3, &mut newer); + prost::encoding::encode_varint(1, &mut newer); + state + .store + .put_policy_revision( + "newer-revision", + "sandbox-newer", + "default", + 1, + &newer, + "hash", + ) + .await + .unwrap(); + state + .store + .get_message::("sandbox-newer") + .await + .unwrap() + .unwrap() + } + + #[tokio::test] + async fn startup_preflight_sets_aside_a_sandbox_with_an_unreadable_policy() { + let state = test_server_state().await; + let affected = install_sandbox_with_newer_policy(&state).await; + install_dangling_provider_sandbox(&state).await; + + validate_provider_composition_startup_preflight(&state) + .await + .expect("one unreadable sandbox policy must not stop the gateway"); + + // Delivery still refuses the affected sandbox. + let error = load_sandbox_config(&state, &affected).await.unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition); + assert!(crate::wire_validation::stored::is_incompatible(&error)); + } + + #[tokio::test] + async fn startup_preflight_still_checks_sandboxes_beside_an_unreadable_policy() { + let state = test_server_state().await; + install_sandbox_with_newer_policy(&state).await; + install_ambiguous_provider_binding(&state, "upgrade").await; + + let error = validate_provider_composition_startup_preflight(&state) + .await + .expect_err("other sandboxes are still validated"); + + assert!(error.message().contains("sandbox-upgrade"), "{error}"); + } + #[tokio::test] async fn startup_preflight_rejects_persisted_ambiguous_provider_binding() { let state = test_server_state().await; diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index 593ca6a0c5..2c11e48a01 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -3366,16 +3366,15 @@ pub(super) async fn handle_update_provider_profiles( .into_iter() .next() .ok_or_else(|| Status::internal("validated provider profile update is missing"))?; - let mut stored = state - .store - .get_message_by_name::(&workspace, &target_id) - .await - .map_err(|e| Status::internal(format!("fetch provider profile failed: {e}")))? + // The profile is replaced whole, so its stored body need not be readable. + let metadata = stored_profile_metadata(state.store.as_ref(), &workspace, &target_id) + .await? .ok_or_else(|| Status::not_found("provider profile not found"))?; - let current_version = stored - .metadata - .as_ref() - .map_or(0, |metadata| metadata.resource_version); + let current_version = metadata.resource_version; + let mut stored = StoredProviderProfile { + metadata: Some(metadata), + profile: None, + }; if current_version != expected_resource_version { return Err(Status::aborted(format!( "provider profile was modified concurrently (current resource_version: {current_version})" @@ -3516,6 +3515,44 @@ pub(super) async fn handle_delete_provider_profile( })) } +/// A stored custom profile's metadata, with the row's resource version. +/// +/// Only `StoredProviderProfile.metadata` is decoded, so an update can replace +/// a profile whose body this build cannot read safely (RFC 0027). +async fn stored_profile_metadata( + store: &Store, + workspace: &str, + id: &str, +) -> Result, Status> { + const METADATA: u32 = 1; + let Some(record) = store + .get_by_name(StoredProviderProfile::object_type(), workspace, id) + .await + .map_err(|e| Status::internal(format!("fetch provider profile failed: {e}")))? + else { + return Ok(None); + }; + let corrupt = || Status::internal("stored provider profile metadata is unreadable"); + let mut fields = crate::wire_validation::FieldIter::new(&record.payload); + let mut metadata_only = Vec::new(); + while let Some(field) = fields.next_field().map_err(|_| corrupt())? { + if field.number == METADATA { + metadata_only.extend_from_slice(field.raw); + } + } + let migrated = crate::persistence::migrate_legacy_time_fields( + StoredProviderProfile::object_type(), + &metadata_only, + ) + .map_err(|_| corrupt())?; + let mut metadata = StoredProviderProfile::decode(migrated.as_slice()) + .map_err(|_| corrupt())? + .metadata + .unwrap_or_default(); + metadata.resource_version = record.resource_version; + Ok(Some(metadata)) +} + pub(super) fn get_provider_type_profile_for_scope( catalog: &EffectiveProviderProfileCatalog, id: &str, @@ -4293,10 +4330,8 @@ async fn profile_update_target_diagnostics( }); return Ok(diagnostics); } - if store - .get_message_by_name::(workspace, target_id) - .await - .map_err(|e| Status::internal(format!("fetch provider profile failed: {e}")))? + if stored_profile_metadata(store, workspace, target_id) + .await? .is_none() { diagnostics.push(ProfileValidationDiagnostic { @@ -7618,6 +7653,87 @@ pub(super) mod tests { assert!(repaired.updated, "{:?}", repaired.diagnostics); } + #[tokio::test] + async fn unreadable_custom_profile_can_be_replaced_in_place() { + let state = test_server_state().await; + let mut original = stored_provider_profile(custom_profile("custom-api")); + original.metadata.as_mut().unwrap().labels = + HashMap::from([("team".to_string(), "platform".to_string())]); + // A newer gateway added an endpoint restriction this build does not know. + let mut endpoint = NetworkEndpoint::default().encode_to_vec(); + prost::encoding::encode_varint(900 << 3, &mut endpoint); + prost::encoding::encode_varint(1, &mut endpoint); + let mut body = Vec::new(); + prost::encoding::bytes::encode(6, &endpoint, &mut body); + let mut payload = original.encode_to_vec(); + prost::encoding::bytes::encode(2, &body, &mut payload); + state + .store + .put( + StoredProviderProfile::object_type(), + original.object_id(), + "custom-api", + "default", + &payload, + Some(r#"{"team":"platform"}"#), + ) + .await + .unwrap(); + assert!( + state + .store + .get_message_by_name::("default", "custom-api") + .await + .is_err(), + "the stored profile is unreadable before the repair" + ); + let version = state + .store + .get_by_name( + StoredProviderProfile::object_type(), + "default", + "custom-api", + ) + .await + .unwrap() + .unwrap() + .resource_version; + let update = |expected_resource_version| { + authed_request(UpdateProviderProfilesRequest { + id: "custom-api".into(), + workspace_scope: Some(default_workspace_selector()), + expected_resource_version, + profile: Some(ProviderProfileImportItem { + profile: Some(custom_profile("custom-api")), + source: "repair.yaml".into(), + }), + ..Default::default() + }) + }; + + // The version check still guards the replacement. + let concurrent = handle_update_provider_profiles(&state, update(version + 1)) + .await + .unwrap_err(); + assert_eq!(concurrent.code(), Code::Aborted); + + let repaired = handle_update_provider_profiles(&state, update(version)) + .await + .unwrap() + .into_inner(); + assert!(repaired.updated, "{:?}", repaired.diagnostics); + let after = state + .store + .get_message_by_name::("default", "custom-api") + .await + .unwrap() + .unwrap(); + let metadata = after.metadata.unwrap(); + assert_eq!(metadata.id, original.object_id()); + assert_eq!(metadata.labels["team"], "platform"); + assert!(metadata.resource_version > version); + } + #[tokio::test] async fn update_provider_profile_replaces_custom_profile_and_preserves_metadata() { let state = test_server_state().await; diff --git a/crates/openshell-server/src/grpc/provider/access_token.rs b/crates/openshell-server/src/grpc/provider/access_token.rs index 2936803b0a..8ef9a6d766 100644 --- a/crates/openshell-server/src/grpc/provider/access_token.rs +++ b/crates/openshell-server/src/grpc/provider/access_token.rs @@ -672,6 +672,135 @@ mod tests { drop(guards); assert!(admission.active.lock().unwrap().is_empty()); } + /// A provider profile with a brokered token grant credential. + fn grant_profile(id: &str) -> openshell_core::proto::ProviderProfile { + use openshell_core::proto::{ + NetworkAccessPreset, NetworkEndpoint, NetworkEnforcementMode, + ProviderCredentialTokenGrant, ProviderProfile, ProviderProfileCredential, + }; + ProviderProfile { + id: id.into(), + display_name: id.into(), + credentials: vec![ProviderProfileCredential { + name: "access_token".into(), + auth_style: "bearer".into(), + header_name: "Authorization".into(), + token_grant: Some(ProviderCredentialTokenGrant { + token_endpoint: "https://identity.example.test/token".into(), + audience: "resource".into(), + ..Default::default() + }), + ..Default::default() + }], + endpoints: vec![NetworkEndpoint { + host: "api.example.test".into(), + port: 443, + protocol: "rest".into(), + access: NetworkAccessPreset::ReadOnly.into(), + enforcement: NetworkEnforcementMode::Enforce.into(), + path: "/**".into(), + ..Default::default() + }], + ..Default::default() + } + } + + #[tokio::test] + async fn unreadable_workspace_profile_never_falls_back_to_the_platform_grant() { + use crate::persistence::ObjectType as _; + use crate::storage_proto::StoredProviderProfile; + use openshell_core::proto::datamodel::v1::ObjectMeta; + + let state = crate::grpc::test_support::test_server_state().await; + // A readable platform profile `graph` with a token grant. + state + .store + .put_message(&crate::provider_profile_sources::stored_provider_profile( + grant_profile("graph"), + )) + .await + .unwrap(); + let provider = Provider { + metadata: Some(ObjectMeta { + id: "provider-graph-id".into(), + name: "graph-provider".into(), + workspace: "default".into(), + ..Default::default() + }), + r#type: "graph".into(), + // Workspace-scoped resolution: a workspace profile wins. + profile_workspace: "default".into(), + ..Default::default() + }; + state.store.put_message(&provider).await.unwrap(); + let sandbox = Sandbox { + metadata: Some(ObjectMeta { + id: "sb-graph".into(), + name: "graph".into(), + workspace: "default".into(), + ..Default::default() + }), + spec: Some(openshell_core::proto::SandboxSpec { + providers: vec!["graph-provider".into()], + ..Default::default() + }), + ..Default::default() + }; + state.store.put_message(&sandbox).await.unwrap(); + let mut configured = HashMap::new(); + insert_dynamic_credentials_for_profile( + &mut configured, + &openshell_providers::ProviderTypeProfile::from_proto(&grant_profile("graph")), + "graph-provider", + "provider-graph-id", + ) + .unwrap(); + let key = configured + .into_keys() + .next() + .expect("a configured grant key"); + + // With only the platform profile, the grant is authorized. + assert!(grant_configuration(&state, "sb-graph", &key).await.is_ok()); + + // A workspace profile `graph` that this build cannot read safely now + // shadows it, and resolution must not fall back to the platform one. + let mut endpoint = openshell_core::proto::NetworkEndpoint::default().encode_to_vec(); + prost::encoding::encode_varint(900 << 3, &mut endpoint); + prost::encoding::encode_varint(1, &mut endpoint); + let mut body = grant_profile("graph").encode_to_vec(); + prost::encoding::bytes::encode(6, &endpoint, &mut body); + let mut stored = StoredProviderProfile { + metadata: Some(ObjectMeta { + id: "workspace-graph".into(), + name: "graph".into(), + workspace: "default".into(), + ..Default::default() + }), + profile: None, + } + .encode_to_vec(); + prost::encoding::bytes::encode(2, &body, &mut stored); + state + .store + .put( + StoredProviderProfile::object_type(), + "workspace-graph", + "graph", + "default", + &stored, + None, + ) + .await + .unwrap(); + + let error = grant_configuration(&state, "sb-graph", &key) + .await + .err() + .expect("an unreadable workspace profile refuses the grant"); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + } + #[tokio::test] async fn broker_requires_a_signed_session_even_with_a_sandbox_principal() { let state = crate::grpc::test_support::test_server_state().await; diff --git a/crates/openshell-server/src/persistence/mod.rs b/crates/openshell-server/src/persistence/mod.rs index 0b09ea452e..7b8c15d9e2 100644 --- a/crates/openshell-server/src/persistence/mod.rs +++ b/crates/openshell-server/src/persistence/mod.rs @@ -344,8 +344,11 @@ pub fn generate_name() -> String { pub fn decode_record( record: ObjectRecord, ) -> PersistenceResult { + // Scan before legacy migration, which fails on bytes it cannot walk and + // would turn an unreadable profile into a generic decode error. Endpoints + // hold no legacy time fields, so the raw and migrated scans agree. + require_known_policy_fields(T::object_type(), &record.payload)?; let payload = legacy_time_wire::migrate(T::object_type(), &record.payload)?; - require_known_policy_fields(T::object_type(), &payload)?; let mut message = T::decode(payload.as_slice()) .map_err(|e| PersistenceError::Decode(format!("protobuf decode error: {e}")))?; message.set_resource_version(record.resource_version); diff --git a/crates/openshell-server/src/provider_profile_sources.rs b/crates/openshell-server/src/provider_profile_sources.rs index 1a0017a78b..5d47ec7026 100644 --- a/crates/openshell-server/src/provider_profile_sources.rs +++ b/crates/openshell-server/src/provider_profile_sources.rs @@ -844,6 +844,14 @@ impl EffectiveProviderProfileCatalog { id: &str, profile_workspace: &str, ) -> Option<&ScopedProfileEntry> { + // An unreadable profile in the resolving scope never falls back to + // another scope's profile with the same ID (RFC 0027). + if self + .require_compatible_profile(id, profile_workspace) + .is_err() + { + return None; + } let id = normalize_profile_id(id)?; let entry = self.profiles.get(&id)?; @@ -892,11 +900,13 @@ impl EffectiveProviderProfileCatalog { || (!readable_workspace && incompatible_in(ProfileScope::Platform)) }; if refused { - return Err(Status::failed_precondition(format!( - "provider profile '{id}' uses endpoint restrictions this gateway ({}) does not \ + return Err(crate::wire_validation::stored::incompatible_status( + &format!( + "provider profile '{id}' uses endpoint restrictions this gateway ({}) does not \ know; upgrade the gateway or replace the profile", - openshell_core::VERSION - ))); + openshell_core::VERSION + ), + )); } Ok(()) } diff --git a/crates/openshell-server/src/wire_validation/stored.rs b/crates/openshell-server/src/wire_validation/stored.rs index 0b46ba0b57..629b4355c4 100644 --- a/crates/openshell-server/src/wire_validation/stored.rs +++ b/crates/openshell-server/src/wire_validation/stored.rs @@ -77,12 +77,9 @@ impl StoredPolicySource { } /// Count `rejection` and return the status refusing the stored payload. - /// - /// `FAILED_PRECONDITION` makes configuration delivery mark the - /// configuration not admitted. pub fn reject(self, rejection: &WireRejection) -> Status { self.count(); - Status::failed_precondition(format!( + incompatible_status(&format!( "{} cannot be read safely by this gateway ({}); upgrade the gateway or \ replace the stored data ({rejection})", self.description(), @@ -91,6 +88,38 @@ impl StoredPolicySource { } } +/// `FAILED_PRECONDITION` for stored data this build cannot read safely. +/// +/// Configuration delivery marks such a configuration not admitted. The +/// `UNKNOWN_PROTOBUF_FIELD` reason lets callers that scan many sandboxes, such +/// as the startup preflight, set one affected sandbox aside instead of failing. +pub fn incompatible_status(message: &str) -> Status { + use openshell_core::rpc_error::{self, ErrorDetails, StatusExt}; + + Status::with_error_details( + tonic::Code::FailedPrecondition, + message, + ErrorDetails::with_error_info( + rpc_error::UNKNOWN_PROTOBUF_FIELD, + rpc_error::ERROR_DOMAIN, + std::collections::HashMap::from([( + "gateway_version".to_string(), + openshell_core::VERSION.to_string(), + )]), + ), + ) +} + +/// Whether `status` refuses stored data this build cannot read safely. +pub fn is_incompatible(status: &Status) -> bool { + status.code() == tonic::Code::FailedPrecondition + && openshell_core::rpc_error::decode_details(status).is_some_and(|details| { + details.error_info().is_some_and(|info| { + info.reason == openshell_core::rpc_error::UNKNOWN_PROTOBUF_FIELD + }) + }) +} + /// Refuse a stored policy this build cannot scan completely. /// /// Unknown fields, unknown enum values, and bytes the scanner cannot parse @@ -190,6 +219,7 @@ mod tests { require_known_stored_policy(&with_unknown(policy, 900), StoredPolicySource::History) .unwrap_err(); assert_eq!(status.code(), tonic::Code::FailedPrecondition); + assert!(is_incompatible(&status)); assert!(status.message().contains("#900"), "{}", status.message()); assert!(crate::grpc::policy::is_configuration_rejection(&status)); } From a86786414dff180e5ba4e5efed4188a5a4893e2d Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Tue, 1 Dec 2026 05:55:56 +0000 Subject: [PATCH 10/10] fix(server): keep repair paths open for unreadable stored data Address the third round of RFC 0027 review feedback: - An unreadable global policy counts as a global override, so provider composition is treated as off. Startup and profile changes no longer fail on it, delivery still refuses it, and a compatible UpdateConfig replacement restores delivery. - GetProviderProfile reports an unreadable profile in the requested scope with its row resource_version in ErrorInfo metadata and the message, instead of NOT_FOUND or a same-ID platform profile. Operators can repair it using public RPCs alone. - LintProviderProfiles checks profile existence from stored metadata only, so linting a replacement for an unreadable profile works. - Profile change diagnostics load a sandbox's base policy only when the sandbox uses a changed profile, so an unrelated unreadable policy no longer blocks platform profile imports or updates. Refs #6097 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Mrunal Patel --- crates/openshell-server/src/grpc/policy.rs | 76 +++++- crates/openshell-server/src/grpc/provider.rs | 233 ++++++++++++++---- .../src/provider_profile_sources.rs | 88 ++++--- .../src/wire_validation/stored.rs | 23 +- 4 files changed, 340 insertions(+), 80 deletions(-) diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 743bda446b..b2deb9f9fb 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -2485,7 +2485,20 @@ pub(super) async fn validate_candidate_provider_attachments( pub(super) async fn provider_policy_composition_enabled(store: &Store) -> Result { let global_settings = load_global_settings(store).await?; - provider_policy_composition_enabled_in(&global_settings) + match provider_policy_composition_enabled_in(&global_settings) { + // A global policy this gateway cannot read (RFC 0027) is still an + // override, so composition stays off. Configuration delivery refuses + // it until an operator replaces it; startup and profile changes must + // not fail on it, or the replacement could never be accepted. + Err(error) if crate::wire_validation::stored::is_incompatible(&error) => { + warn!( + error = %error.message(), + "treating a global policy this gateway cannot read as a global override" + ); + Ok(false) + } + result => result, + } } fn provider_policy_composition_enabled_in(settings: &StoredSettings) -> Result { @@ -24181,6 +24194,67 @@ mod tests { assert!(error.message().contains("sandbox-upgrade"), "{error}"); } + #[tokio::test] + async fn unreadable_global_policy_starts_the_gateway_and_can_be_replaced() { + let state = test_server_state().await; + state + .store + .put_message(&test_sandbox( + "sandbox-global", + "sandbox-global", + test_policy_with_rule("base", "api.example.com"), + vec![], + )) + .await + .unwrap(); + let sandbox = state + .store + .get_message::("sandbox-global") + .await + .unwrap() + .unwrap(); + let mut newer = test_policy_with_rule("global", "api.example.com").encode_to_vec(); + prost::encoding::encode_varint(900 << 3, &mut newer); + prost::encoding::encode_varint(1, &mut newer); + save_global_settings( + state.store.as_ref(), + &StoredSettings { + revision: 1, + settings: std::iter::once(( + POLICY_SETTING_KEY.to_string(), + StoredSettingValue::Bytes(hex::encode(&newer)), + )) + .collect(), + ..Default::default() + }, + ) + .await + .unwrap(); + + validate_provider_composition_startup_preflight(&state) + .await + .expect("an unreadable global policy must not stop the gateway"); + let error = load_sandbox_config(&state, &sandbox).await.unwrap_err(); + assert!( + crate::wire_validation::stored::is_incompatible(&error), + "{error}" + ); + + // A compatible replacement through the public API restores delivery. + handle_update_config( + &state, + with_user(Request::new(UpdateConfigRequest { + global: true, + policy: Some(test_policy_with_rule("global", "api.example.com")), + ..Default::default() + })), + ) + .await + .expect("a compatible global policy replaces the unreadable one"); + let config = load_sandbox_config(&state, &sandbox).await.unwrap(); + assert!(config.policy.is_some()); + } + #[tokio::test] async fn startup_preflight_rejects_persisted_ambiguous_provider_binding() { let state = test_server_state().await; diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index 2c11e48a01..f312ce8788 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -3179,6 +3179,9 @@ pub(super) async fn handle_get_provider_profile( .provider_profile_sources .snapshot_catalog(state.store.as_ref(), &workspace) .await?; + // An unreadable profile in this scope is reported with its version, so it + // can be exported for repair, never hidden behind another scope's profile. + catalog.require_compatible_profile(&id, &workspace)?; let profile = catalog .get_profile(&id) .ok_or_else(|| Status::not_found("provider profile not found"))?; @@ -4260,10 +4263,8 @@ async fn profile_conflict_diagnostics( }); continue; } - if store - .get_message_by_name::(workspace, &id) - .await - .map_err(|e| Status::internal(format!("fetch provider profile failed: {e}")))? + if stored_profile_metadata(store, workspace, &id) + .await? .is_some() { diagnostics.push(ProfileValidationDiagnostic { @@ -4273,12 +4274,7 @@ async fn profile_conflict_diagnostics( message: format!("custom provider profile '{id}' already exists"), severity: "error".to_string(), }); - } else if !workspace.is_empty() - && store - .get_message_by_name::("", &id) - .await - .map_err(|e| Status::internal(format!("fetch provider profile failed: {e}")))? - .is_some() + } else if !workspace.is_empty() && stored_profile_metadata(store, "", &id).await?.is_some() { diagnostics.push(ProfileValidationDiagnostic { source: source.clone(), @@ -4410,29 +4406,44 @@ async fn profile_attached_sandbox_diagnostics( let sandbox_name = sandbox.object_name().to_string(); let sandbox_workspace = sandbox.object_workspace().to_string(); let spec = sandbox.spec.as_ref().expect("filtered by scan_sandboxes"); + let provider_ws = if is_platform_scope { + &sandbox_workspace + } else { + workspace + }; + let mut providers = Vec::with_capacity(spec.providers.len()); + for provider_name in &spec.providers { + if let Some(provider) = store + .get_message_by_name::(provider_ws, provider_name) + .await + .map_err(|e| Status::internal(format!("fetch provider failed: {e}")))? + { + providers.push((provider_name, provider)); + } + } + let profile_id_of = |provider: &Provider| { + normalize_profile_id(&provider.r#type) + .unwrap_or_else(|| provider.r#type.trim().to_string()) + }; + let scope_mismatch = |provider: &Provider| { + (is_platform_scope && !provider.profile_workspace.is_empty()) + || (!is_platform_scope && provider.profile_workspace.is_empty()) + }; + // Only sandboxes that use a changed profile are validated, so an + // unrelated sandbox's policy, readable or not, never blocks the change. + if !providers.iter().any(|(_, provider)| { + !scope_mismatch(provider) && candidate_profiles.contains_key(&profile_id_of(provider)) + }) { + continue; + } let base_policy = super::policy::current_base_policy_for_sandbox(store, &sandbox).await?; let mut bindings = Vec::new(); let mut provider_layers = Vec::new(); let mut imported_profiles_used = Vec::<(String, String)>::new(); - for provider_name in &spec.providers { - let provider_ws = if is_platform_scope { - &sandbox_workspace - } else { - workspace - }; - let Some(provider) = store - .get_message_by_name::(provider_ws, provider_name) - .await - .map_err(|e| Status::internal(format!("fetch provider failed: {e}")))? - else { - continue; - }; - let profile_id = normalize_profile_id(&provider.r#type) - .unwrap_or_else(|| provider.r#type.trim().to_string()); - let scope_mismatch = (is_platform_scope && !provider.profile_workspace.is_empty()) - || (!is_platform_scope && provider.profile_workspace.is_empty()); - if scope_mismatch { + for (provider_name, provider) in providers { + let profile_id = profile_id_of(&provider); + if scope_mismatch(&provider) { bindings.extend(dynamic_token_grant_bindings_for_provider_with_catalog( catalog, &provider, )); @@ -7538,6 +7549,99 @@ pub(super) mod tests { assert!(response.imported); } + /// A sandbox attached to a provider of `profile_type` whose stored policy + /// revision carries a restriction this build does not know. + async fn sandbox_with_unreadable_policy( + state: &Arc, + sandbox_name: &str, + profile_type: &str, + ) { + use crate::policy_store::PolicyStoreExt as _; + use openshell_core::proto::datamodel::v1::ObjectMeta; + use openshell_core::proto::{Sandbox, SandboxPolicy, SandboxSpec}; + + let provider_name = format!("{sandbox_name}-provider"); + state + .store + .put_message(&Provider { + metadata: Some(ObjectMeta { + id: format!("{provider_name}-id"), + name: provider_name.clone(), + workspace: "default".into(), + ..Default::default() + }), + r#type: profile_type.into(), + ..Default::default() + }) + .await + .unwrap(); + state + .store + .put_message(&Sandbox { + metadata: Some(ObjectMeta { + id: format!("{sandbox_name}-id"), + name: sandbox_name.into(), + workspace: "default".into(), + ..Default::default() + }), + spec: Some(SandboxSpec { + providers: vec![provider_name], + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap(); + let mut newer = SandboxPolicy::default().encode_to_vec(); + prost::encoding::encode_varint(900 << 3, &mut newer); + prost::encoding::encode_varint(1, &mut newer); + state + .store + .put_policy_revision( + &format!("{sandbox_name}-revision"), + &format!("{sandbox_name}-id"), + "default", + 1, + &newer, + "hash", + ) + .await + .unwrap(); + } + + #[tokio::test] + async fn unreadable_policy_blocks_only_profile_changes_its_sandbox_depends_on() { + let state = test_server_state().await; + sandbox_with_unreadable_policy(&state, "unrelated", "other-profile").await; + let import = |id: &str| { + authed_request(ImportProviderProfilesRequest { + request_id: String::new(), + profiles: vec![ProviderProfileImportItem { + profile: Some(custom_profile(id)), + source: format!("{id}.yaml"), + }], + workspace_scope: None, + }) + }; + + // An unrelated sandbox's unreadable policy does not block the import. + let imported = handle_import_provider_profiles(&state, import("platform-new")) + .await + .unwrap() + .into_inner(); + assert!(imported.imported, "{:?}", imported.diagnostics); + + // A sandbox that uses the changed profile is still validated. + sandbox_with_unreadable_policy(&state, "dependent", "platform-dependent").await; + let error = handle_import_provider_profiles(&state, import("platform-dependent")) + .await + .unwrap_err(); + assert!( + crate::wire_validation::stored::is_incompatible(&error), + "{error}" + ); + } + #[tokio::test] async fn import_platform_provider_profile_waits_for_sandbox_mutation_in_any_workspace() { let state = test_server_state().await; @@ -7654,7 +7758,7 @@ pub(super) mod tests { } #[tokio::test] - async fn unreadable_custom_profile_can_be_replaced_in_place() { + async fn unreadable_custom_profile_can_be_repaired_through_public_rpcs() { let state = test_server_state().await; let mut original = stored_provider_profile(custom_profile("custom-api")); original.metadata.as_mut().unwrap().labels = @@ -7679,25 +7783,34 @@ pub(super) mod tests { ) .await .unwrap(); + // A same-ID platform profile must not hide the unreadable one. + let mut platform = stored_provider_profile(custom_profile("custom-api")); + platform.metadata.as_mut().unwrap().workspace = String::new(); + state.store.put_message(&platform).await.unwrap(); + let get = || { + handle_get_provider_profile( + &state, + authed_request(GetProviderProfileRequest { + id: "custom-api".into(), + workspace_scope: Some(default_workspace_selector()), + }), + ) + }; + + // The public lookup reports the unreadable profile and its version. + let unreadable = get().await.unwrap_err(); assert!( - state - .store - .get_message_by_name::("default", "custom-api") - .await - .is_err(), - "the stored profile is unreadable before the repair" + crate::wire_validation::stored::is_incompatible(&unreadable), + "{unreadable}" ); - let version = state - .store - .get_by_name( - StoredProviderProfile::object_type(), - "default", - "custom-api", - ) - .await + let version: u64 = openshell_core::rpc_error::decode_details(&unreadable) .unwrap() + .error_info() .unwrap() - .resource_version; + .metadata["resource_version"] + .parse() + .unwrap(); + assert!(version > 0); let update = |expected_resource_version| { authed_request(UpdateProviderProfilesRequest { id: "custom-api".into(), @@ -7711,6 +7824,29 @@ pub(super) mod tests { }) }; + // The CLI lints a replacement before updating; the unreadable stored + // profile must not turn that into an internal error. + let lint = handle_lint_provider_profiles( + &state, + authed_request(LintProviderProfilesRequest { + workspace_scope: Some(default_workspace_selector()), + profiles: vec![ProviderProfileImportItem { + profile: Some(custom_profile("custom-api")), + source: "repair.yaml".into(), + }], + }), + ) + .await + .expect("lint reads only the stored profile's metadata") + .into_inner(); + assert!( + lint.diagnostics + .iter() + .any(|diagnostic| diagnostic.message.contains("already exists")), + "{:?}", + lint.diagnostics + ); + // The version check still guards the replacement. let concurrent = handle_update_provider_profiles(&state, update(version + 1)) .await @@ -7722,16 +7858,19 @@ pub(super) mod tests { .unwrap() .into_inner(); assert!(repaired.updated, "{:?}", repaired.diagnostics); - let after = state + let after = get().await.unwrap().into_inner().profile.unwrap(); + assert_eq!(after.scope, "workspace"); + assert!(after.resource_version > version); + let metadata = state .store .get_message_by_name::("default", "custom-api") .await .unwrap() + .unwrap() + .metadata .unwrap(); - let metadata = after.metadata.unwrap(); assert_eq!(metadata.id, original.object_id()); assert_eq!(metadata.labels["team"], "platform"); - assert!(metadata.resource_version > version); } #[tokio::test] diff --git a/crates/openshell-server/src/provider_profile_sources.rs b/crates/openshell-server/src/provider_profile_sources.rs index 5d47ec7026..22004d4f97 100644 --- a/crates/openshell-server/src/provider_profile_sources.rs +++ b/crates/openshell-server/src/provider_profile_sources.rs @@ -76,6 +76,8 @@ pub struct ProviderProfileSnapshot { pub struct IncompatibleProfile { pub scope: ProfileScope, pub id: String, + /// The stored row's version, which a replacement must name. + pub resource_version: u64, } #[async_trait] @@ -155,9 +157,20 @@ impl ProviderProfileSource for UserProviderProfileSource { Ok(stored) => stored, Err(crate::persistence::PersistenceError::UnknownFields(reason)) => { warn_incompatible_profile(id, &reason); + let resource_version = store + .get_by_name(StoredProviderProfile::object_type(), namespace, id) + .await + .map_err(|error| { + crate::grpc::persistence_error_to_status( + error, + "fetch provider profile", + ) + })? + .map_or(0, |record| record.resource_version); incompatible.push(IncompatibleProfile { scope, id: id.to_string(), + resource_version, }); continue; } @@ -222,7 +235,11 @@ impl ProviderProfileSource for UserProviderProfileSource { hasher.update(resource_version.to_le_bytes()); hasher.update((id.len() as u64).to_le_bytes()); hasher.update(id.as_bytes()); - incompatible.push(IncompatibleProfile { scope, id }); + incompatible.push(IncompatibleProfile { + scope, + id, + resource_version, + }); } } @@ -870,45 +887,60 @@ impl EffectiveProviderProfileCatalog { } } - /// Refuse a provider whose profile this build cannot read safely. + /// The stored profile this build cannot read safely that a lookup of `id` + /// for `profile_workspace` would resolve to, if any. /// - /// Resolves the profile the way [`Self::get_type_profile_for_scope`] - /// does: a workspace profile applies when one exists for a provider with - /// a profile workspace, otherwise the platform profile. Returns - /// `FAILED_PRECONDITION`, so the configuration is not admitted. - pub(crate) fn require_compatible_profile( + /// Resolves the way [`Self::get_type_profile_for_scope`] does: a workspace + /// profile applies when one exists for a non-empty profile workspace, + /// otherwise the platform profile. + pub(crate) fn incompatible_profile( &self, id: &str, profile_workspace: &str, - ) -> Result<(), Status> { - let Some(id) = normalize_profile_id(id) else { - return Ok(()); - }; + ) -> Option<&IncompatibleProfile> { + let id = normalize_profile_id(id)?; let incompatible_in = |scope: ProfileScope| { self.incompatible .iter() - .any(|profile| profile.scope == scope && profile.id == id) + .find(|profile| profile.scope == scope && profile.id == id) }; + if profile_workspace.is_empty() { + return incompatible_in(ProfileScope::Platform); + } let readable_workspace = self .profiles .get(&id) .is_some_and(|entry| entry.effective.scope == ProfileScope::Workspace); - let refused = if profile_workspace.is_empty() { - incompatible_in(ProfileScope::Platform) - } else { - incompatible_in(ProfileScope::Workspace) - || (!readable_workspace && incompatible_in(ProfileScope::Platform)) - }; - if refused { - return Err(crate::wire_validation::stored::incompatible_status( - &format!( - "provider profile '{id}' uses endpoint restrictions this gateway ({}) does not \ - know; upgrade the gateway or replace the profile", - openshell_core::VERSION - ), - )); - } - Ok(()) + incompatible_in(ProfileScope::Workspace).or_else(|| { + (!readable_workspace) + .then(|| incompatible_in(ProfileScope::Platform)) + .flatten() + }) + } + + /// Refuse a provider whose profile this build cannot read safely. + /// + /// Returns `FAILED_PRECONDITION` with the stored row's `resource_version`, + /// so the configuration is not admitted and an operator can replace it. + pub(crate) fn require_compatible_profile( + &self, + id: &str, + profile_workspace: &str, + ) -> Result<(), Status> { + self.incompatible_profile(id, profile_workspace) + .map_or(Ok(()), |profile| { + Err(crate::wire_validation::stored::incompatible_status_with( + &format!( + "provider profile '{}' (resource_version {}) uses endpoint restrictions \ + this gateway ({}) does not know; upgrade the gateway or replace the \ + profile with that resource_version", + profile.id, + profile.resource_version, + openshell_core::VERSION + ), + [("resource_version", profile.resource_version.to_string())], + )) + }) } /// The non-user source that manages this profile, if any. diff --git a/crates/openshell-server/src/wire_validation/stored.rs b/crates/openshell-server/src/wire_validation/stored.rs index 629b4355c4..d1d4268147 100644 --- a/crates/openshell-server/src/wire_validation/stored.rs +++ b/crates/openshell-server/src/wire_validation/stored.rs @@ -94,18 +94,33 @@ impl StoredPolicySource { /// `UNKNOWN_PROTOBUF_FIELD` reason lets callers that scan many sandboxes, such /// as the startup preflight, set one affected sandbox aside instead of failing. pub fn incompatible_status(message: &str) -> Status { + incompatible_status_with(message, []) +} + +/// [`incompatible_status`] with extra `ErrorInfo` metadata, such as the +/// affected row's `resource_version` an operator needs to replace it. +pub fn incompatible_status_with( + message: &str, + metadata: [(&str, String); N], +) -> Status { use openshell_core::rpc_error::{self, ErrorDetails, StatusExt}; + let mut details = std::collections::HashMap::from([( + "gateway_version".to_string(), + openshell_core::VERSION.to_string(), + )]); + details.extend( + metadata + .into_iter() + .map(|(key, value)| (key.to_string(), value)), + ); Status::with_error_details( tonic::Code::FailedPrecondition, message, ErrorDetails::with_error_info( rpc_error::UNKNOWN_PROTOBUF_FIELD, rpc_error::ERROR_DOMAIN, - std::collections::HashMap::from([( - "gateway_version".to_string(), - openshell_core::VERSION.to_string(), - )]), + details, ), ) }