From ea8eda6d5b2eba410ed3ce0d1b272b4f17b927eb Mon Sep 17 00:00:00 2001 From: Shiju Date: Wed, 9 Sep 2026 20:28:55 +0000 Subject: [PATCH 1/4] feat(supervisor): enforce MCP request protocol versions (#3241) * feat(supervisor): enforce MCP request protocol versions Signed-off-by: Shiju * fix(supervisor): enforce MCP versions across HTTP forwarding Apply shared request-version guards before authorization and after forward-request rewriting. Require version metadata to survive HTTP header cleanup, and cover valid initialization and selected-revision forwarding through middleware. Signed-off-by: Shiju --------- Signed-off-by: Shiju --- architecture/sandbox.md | 2 +- .../src/l7/jsonrpc.rs | 57 ++++ .../src/l7/mcp.rs | 318 +++++++++++++++++ .../src/l7/mod.rs | 1 + .../src/l7/relay.rs | 320 +++++++++++++++++- .../src/l7/rest.rs | 3 +- .../openshell-supervisor-network/src/proxy.rs | 211 +++++++++++- docs/reference/policy-schema.mdx | 4 +- docs/sandboxes/policies.mdx | 4 +- e2e/mcp-conformance/README.md | 2 +- 10 files changed, 905 insertions(+), 17 deletions(-) create mode 100644 crates/openshell-supervisor-network/src/l7/mcp.rs diff --git a/architecture/sandbox.md b/architecture/sandbox.md index 8676ac9a56..6920112f59 100644 --- a/architecture/sandbox.md +++ b/architecture/sandbox.md @@ -157,7 +157,7 @@ support `params` matchers; generic JSON-RPC rules match only the method. JSON-RPC responses and server-to-client MCP messages on response or SSE streams are relayed but are not currently parsed for policy enforcement. -Every `protocol: mcp` endpoint carries a canonical, nonempty `mcp.versions` allowlist drawn from OpenShell's exact revision registry: `2025-03-26`, `2025-06-18`, and `2025-11-25`. A policy author may omit the entire `mcp` object when using the other endpoint defaults, or omit `mcp.versions` while setting another MCP option. Both forms resolve immediately to the exact allowlist `["2025-11-25"]`; omission never means latest or all known revisions. Defaulting applies only when the corresponding YAML key is absent: `mcp: null`, `versions: null`, and an explicit `versions: []` are invalid. At protobuf ingress, an empty repeated field means omission and uses the same default because protobuf repeated fields do not preserve presence. Normalization stores and serializes the materialized allowlist in semantic order, so adding a supported revision to the registry never widens a previously normalized policy. An explicit nonempty allowlist remains available as an advanced compatibility or downgrade control. The registry is a closed set rather than a date range, so duplicate or padded values, unknown dates, and moving aliases such as `draft` or `latest` are rejected. The sessionless `2026-07-28` revision is not accepted until OpenShell supports its distinct per-request runtime contract. A version names a core protocol revision only; there is no policy syntax for layering a separately named SEP onto it. The registry owns immutable batch-shape metadata: `2025-03-26` permits nonempty same-side top-level JSON-RPC batches, which OpenShell's planned enforcement caps at 64 members, while `2025-06-18` and `2025-11-25` prohibit top-level arrays. These are declared profile facts, not current forwarding claims. The allowlist does not yet select request parsing or forwarding behavior. Later response-aware runtime state must observe the successful server response, require the selected revision to be in the allowlist, and apply that one exact profile without a union or fallback; OpenShell must not bind the client proposal in `initialize` as though it were the server-selected revision. +Every `protocol: mcp` endpoint carries a canonical, nonempty `mcp.versions` allowlist drawn from OpenShell's exact revision registry: `2025-03-26`, `2025-06-18`, and `2025-11-25`. A policy author may omit the entire `mcp` object when using the other endpoint defaults, or omit `mcp.versions` while setting another MCP option. Both forms resolve immediately to the exact allowlist `["2025-11-25"]`; omission never means latest or all known revisions. Defaulting applies only when the corresponding YAML key is absent: `mcp: null`, `versions: null`, and an explicit `versions: []` are invalid. At protobuf ingress, an empty repeated field means omission and uses the same default because protobuf repeated fields do not preserve presence. Normalization stores and serializes the materialized allowlist in semantic order, so adding a supported revision to the registry never widens a previously normalized policy. An explicit nonempty allowlist remains available as an advanced compatibility or downgrade control. The registry is a closed set rather than a date range, so duplicate or padded values, unknown dates, and moving aliases such as `draft` or `latest` are rejected. The sessionless `2026-07-28` revision is not accepted until OpenShell supports its distinct per-request contract. A version names a core protocol revision only; there is no policy syntax for layering a separately named SEP onto it. For every MCP HTTP request except a valid standalone `initialize`, the supervisor reads exactly one `MCP-Protocol-Version` header and requires that revision to appear in the endpoint allowlist. If the header is absent, the MCP transport specification defines `2025-03-26` as the compatibility fallback; OpenShell permits that fallback only when the allowlist contains it. Duplicate, empty, or unsupported header values receive `400 Bad Request`, while a supported revision outside the allowlist receives `403 Forbidden`. The supervisor repeats this check after middleware changes the request and before any upstream write. This check does not store session state or infer a version from a previous connection request. The registry also owns immutable batch-shape metadata: `2025-03-26` permits nonempty same-side top-level JSON-RPC batches, which OpenShell's planned enforcement caps at 64 members, while `2025-06-18` and `2025-11-25` prohibit top-level arrays. The current request parser does not yet apply these version-specific batch rules. For admitted HTTP requests, the proxy can run an ordered supervisor middleware chain after L7 policy evaluation and before credential injection. Destination diff --git a/crates/openshell-supervisor-network/src/l7/jsonrpc.rs b/crates/openshell-supervisor-network/src/l7/jsonrpc.rs index c6a65f76c4..aea53edc08 100644 --- a/crates/openshell-supervisor-network/src/l7/jsonrpc.rs +++ b/crates/openshell-supervisor-network/src/l7/jsonrpc.rs @@ -86,6 +86,54 @@ pub(crate) async fn parse_jsonrpc_http_request Result { + if jsonrpc_receive_stream_request(request) { + return Ok(JsonRpcRequestInfo::receive_stream()); + } + + let header_end = request + .raw_header + .windows(4) + .position(|window| window == b"\r\n\r\n") + .ok_or_else(|| miette::miette!("HTTP request headers are missing the CRLF terminator"))? + + 4; + let body = &request.raw_header[header_end..]; + match request.body_length { + crate::l7::provider::BodyLength::None if body.is_empty() => {} + crate::l7::provider::BodyLength::ContentLength(length) => { + let length = usize::try_from(length) + .map_err(|_| miette::miette!("HTTP request body length exceeds platform limit"))?; + if body.len() != length { + return Err(miette::miette!( + "buffered HTTP request body length does not match Content-Length" + )); + } + } + crate::l7::provider::BodyLength::None => { + return Err(miette::miette!( + "buffered HTTP request has bytes without body framing" + )); + } + crate::l7::provider::BodyLength::Chunked => { + return Err(miette::miette!( + "buffered JSON-RPC request retained chunked framing" + )); + } + } + + Ok(parse_jsonrpc_body_with_options(body, inspection_options)) +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct JsonRpcRequestInfo { /// Calls found in the request body. Responses and receive-stream GETs have @@ -169,6 +217,12 @@ pub struct JsonRpcCallInfo { /// MCP `tools/call` tool name when known. Generic JSON-RPC leaves this /// unset because params are not inspected. pub tool: Option, + /// Whether this call is a JSON-RPC notification without an `id`. + /// + /// MCP initialization is a request, so transport code uses this bit to + /// avoid treating an extension notification named `initialize` as the + /// header-exempt initialization exchange. + pub is_notification: bool, } impl JsonRpcRequestInfo { @@ -365,6 +419,7 @@ fn parse_jsonrpc_call( method: method.to_string(), params: HashMap::new(), tool: None, + is_notification: value.get("id").is_none(), }) } @@ -421,6 +476,7 @@ fn parse_mcp_call( method: mcp_request.method_name().to_string(), params, tool, + is_notification: false, }); } @@ -441,6 +497,7 @@ fn parse_mcp_call( method: notification.method, params: HashMap::new(), tool: None, + is_notification: true, }) } diff --git a/crates/openshell-supervisor-network/src/l7/mcp.rs b/crates/openshell-supervisor-network/src/l7/mcp.rs new file mode 100644 index 0000000000..d5fbaed8bc --- /dev/null +++ b/crates/openshell-supervisor-network/src/l7/mcp.rs @@ -0,0 +1,318 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! MCP Streamable HTTP request-version selection. + +use openshell_core::mcp::McpProtocolVersion; + +use crate::l7::jsonrpc::JsonRpcRequestInfo; +use crate::l7::provider::L7Request; + +const MCP_PROTOCOL_VERSION_HEADER: &str = "mcp-protocol-version"; + +/// Protocol revision selected for one MCP HTTP request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum McpRequestProtocolVersion { + /// A valid standalone initialize request selects its revision in the JSON-RPC body. + Initialization, + /// A subsequent request selected an exact revision from its header or the legacy fallback. + Selected(McpProtocolVersion), +} + +/// Failure to select a policy-allowed protocol revision for an MCP HTTP request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum McpProtocolVersionError { + /// The HTTP header block could not yield one unambiguous end-to-end value. + InvalidHeader, + /// The header value is not an MCP revision supported by this `OpenShell` build. + UnsupportedHeaderValue, + /// The selected supported revision is absent from the endpoint allowlist. + NotAllowed(McpProtocolVersion), +} + +impl McpProtocolVersionError { + /// Return the HTTP status for this transport or policy rejection. + #[must_use] + pub(super) const fn http_status(self) -> &'static str { + match self { + Self::InvalidHeader | Self::UnsupportedHeaderValue => "400 Bad Request", + Self::NotAllowed(_) => "403 Forbidden", + } + } + + /// Return a stable machine-readable response code. + #[must_use] + pub(super) const fn response_code(self) -> &'static str { + match self { + Self::InvalidHeader => "invalid_mcp_protocol_version_header", + Self::UnsupportedHeaderValue => "unsupported_mcp_protocol_version", + Self::NotAllowed(_) => "mcp_protocol_version_not_allowed", + } + } +} + +impl std::fmt::Display for McpProtocolVersionError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::InvalidHeader => formatter.write_str( + "MCP-Protocol-Version must contain one non-empty end-to-end header value", + ), + Self::UnsupportedHeaderValue => { + formatter.write_str("MCP-Protocol-Version names an unsupported protocol version") + } + Self::NotAllowed(version) => write!( + formatter, + "MCP protocol version {version} is not allowed by endpoint policy" + ), + } + } +} + +impl std::error::Error for McpProtocolVersionError {} + +/// Select and authorize the protocol revision for one MCP HTTP request. +/// +/// MCP initialization negotiates its revision in the JSON-RPC body and is the +/// only request exempt from the header. Every other request is self-contained: +/// an absent header selects the specification-defined `2025-03-26` fallback, +/// and the resulting supported revision must appear in the endpoint allowlist. +pub(super) fn select_request_protocol_version( + request: &L7Request, + info: &JsonRpcRequestInfo, + allowed_versions: &[McpProtocolVersion], +) -> Result { + if is_standalone_initialize(info) { + return Ok(McpRequestProtocolVersion::Initialization); + } + + let version = match request_protocol_version_header(&request.raw_header)? { + Some(value) => value + .parse::() + .map_err(|_| McpProtocolVersionError::UnsupportedHeaderValue)?, + None => McpProtocolVersion::V2025_03_26, + }; + if !allowed_versions.contains(&version) { + return Err(McpProtocolVersionError::NotAllowed(version)); + } + + Ok(McpRequestProtocolVersion::Selected(version)) +} + +fn is_standalone_initialize(info: &JsonRpcRequestInfo) -> bool { + !info.is_batch + && !info.has_response + && info.error.is_none() + && matches!( + info.calls.as_slice(), + [call] if call.method == "initialize" && !call.is_notification + ) +} + +fn request_protocol_version_header( + raw_header: &[u8], +) -> Result, McpProtocolVersionError> { + let header_end = raw_header + .windows(4) + .position(|window| window == b"\r\n\r\n") + .ok_or(McpProtocolVersionError::InvalidHeader)? + + 4; + let headers = std::str::from_utf8(&raw_header[..header_end]) + .map_err(|_| McpProtocolVersionError::InvalidHeader)?; + // Forwarding removes Connection-nominated fields. A revision field must + // survive that cleanup. Use the forwarding parser's canonical field names + // so authorization and removal agree, including after middleware rebuilds. + let nominated = crate::l7::rest::connection_nominated_header_names(&raw_header[..header_end]) + .map_err(|_| McpProtocolVersionError::InvalidHeader)?; + if nominated.contains(MCP_PROTOCOL_VERSION_HEADER) { + return Err(McpProtocolVersionError::InvalidHeader); + } + let mut values = headers.split("\r\n").skip(1).filter_map(|line| { + let (name, value) = line.split_once(':')?; + // HTTP field-value optional whitespace is only SP or HTAB. Using + // Unicode whitespace trimming here would accept bytes that are part + // of the protocol-version value rather than HTTP framing. + name.eq_ignore_ascii_case(MCP_PROTOCOL_VERSION_HEADER) + .then_some(value.trim_matches([' ', '\t'])) + }); + let Some(value) = values.next() else { + return Ok(None); + }; + if value.is_empty() || values.next().is_some() { + return Err(McpProtocolVersionError::InvalidHeader); + } + Ok(Some(value)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::l7::jsonrpc::{JsonRpcInspectionMode, parse_jsonrpc_body}; + use crate::l7::provider::BodyLength; + + fn request(method: &str, headers: &str) -> L7Request { + L7Request { + action: method.to_string(), + target: "/mcp".to_string(), + query_params: std::collections::HashMap::new(), + raw_header: format!("{method} /mcp HTTP/1.1\r\nHost: example.test\r\n{headers}\r\n") + .into_bytes(), + body_length: BodyLength::None, + } + } + + fn request_info(body: &[u8]) -> JsonRpcRequestInfo { + parse_jsonrpc_body(body, JsonRpcInspectionMode::Mcp) + } + + #[test] + fn standalone_initialize_uses_body_negotiation_only() { + let info = request_info( + br#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}"#, + ); + + assert_eq!( + select_request_protocol_version(&request("POST", ""), &info, &[]), + Ok(McpRequestProtocolVersion::Initialization) + ); + } + + #[test] + fn initialize_notification_is_not_treated_as_initialization() { + let info = request_info(br#"{"jsonrpc":"2.0","method":"initialize","params":{}}"#); + + assert_eq!( + select_request_protocol_version( + &request("POST", ""), + &info, + &[McpProtocolVersion::V2025_03_26] + ), + Ok(McpRequestProtocolVersion::Selected( + McpProtocolVersion::V2025_03_26 + )) + ); + } + + #[test] + fn subsequent_requests_select_exact_header_for_every_http_method() { + let info = request_info(br#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#); + + for method in ["POST", "GET", "DELETE"] { + assert_eq!( + select_request_protocol_version( + &request(method, "MCP-Protocol-Version: 2025-11-25\r\n"), + &info, + &[McpProtocolVersion::V2025_11_25] + ), + Ok(McpRequestProtocolVersion::Selected( + McpProtocolVersion::V2025_11_25 + )), + "method {method} must use the same per-request selection" + ); + } + } + + #[test] + fn missing_header_uses_only_the_legacy_specification_fallback() { + let info = request_info(br#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#); + + assert_eq!( + select_request_protocol_version( + &request("POST", ""), + &info, + &[McpProtocolVersion::V2025_03_26] + ), + Ok(McpRequestProtocolVersion::Selected( + McpProtocolVersion::V2025_03_26 + )) + ); + assert_eq!( + select_request_protocol_version( + &request("POST", ""), + &info, + &[McpProtocolVersion::V2025_11_25] + ), + Err(McpProtocolVersionError::NotAllowed( + McpProtocolVersion::V2025_03_26 + )) + ); + } + + #[test] + fn repeated_or_empty_headers_are_bad_requests() { + let info = request_info(br#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#); + + for headers in [ + "MCP-Protocol-Version:\r\n", + "MCP-Protocol-Version: 2025-11-25\r\nMCP-Protocol-Version: 2025-11-25\r\n", + "MCP-Protocol-Version: 2025-03-26\r\nmcp-protocol-version: 2025-11-25\r\n", + ] { + assert_eq!( + select_request_protocol_version( + &request("POST", headers), + &info, + &[McpProtocolVersion::V2025_11_25] + ), + Err(McpProtocolVersionError::InvalidHeader) + ); + } + } + + #[test] + fn protocol_version_must_remain_an_end_to_end_field() { + for connection_options in [ + "mcp-protocol-version", + "keep-alive, MCP-Protocol-Version", + "\tMcp-Protocol-Version\t, close", + ] { + let headers = request("POST", &format!("Connection: {connection_options}\r\n")); + assert_eq!( + request_protocol_version_header(&headers.raw_header), + Err(McpProtocolVersionError::InvalidHeader), + "revision metadata cannot be declared hop-by-hop" + ); + } + let headers = request("POST", "Connection: keep-alive, x-request-id\r\n"); + assert_eq!( + request_protocol_version_header(&headers.raw_header), + Ok(None) + ); + } + + #[test] + fn unsupported_or_non_exact_header_values_are_bad_requests() { + let info = request_info(br#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#); + + for value in [ + "2026-07-28", + "2025-11-25, 2025-03-26", + "2025-11-25x", + "\u{00a0}2025-11-25", + ] { + assert_eq!( + select_request_protocol_version( + &request("POST", &format!("MCP-Protocol-Version: {value}\r\n")), + &info, + &[McpProtocolVersion::V2025_11_25] + ), + Err(McpProtocolVersionError::UnsupportedHeaderValue) + ); + } + } + + #[test] + fn supported_but_disallowed_header_is_forbidden() { + let info = request_info(br#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#); + + let error = select_request_protocol_version( + &request("POST", "MCP-Protocol-Version: 2025-06-18\r\n"), + &info, + &[McpProtocolVersion::V2025_11_25], + ) + .expect_err("supported revision is outside endpoint policy"); + assert_eq!( + error, + McpProtocolVersionError::NotAllowed(McpProtocolVersion::V2025_06_18) + ); + assert_eq!(error.http_status(), "403 Forbidden"); + } +} diff --git a/crates/openshell-supervisor-network/src/l7/mod.rs b/crates/openshell-supervisor-network/src/l7/mod.rs index 990619f963..77e4497d48 100644 --- a/crates/openshell-supervisor-network/src/l7/mod.rs +++ b/crates/openshell-supervisor-network/src/l7/mod.rs @@ -11,6 +11,7 @@ pub mod graphql; pub(crate) mod http; pub mod jsonrpc; +pub(crate) mod mcp; pub(crate) mod middleware; pub mod path; pub mod provider; diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index aec52cf9cd..d022622a38 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -164,6 +164,93 @@ where Ok(()) } +/// Enforce MCP request-version policy and emit a transport or policy rejection. +/// Non-MCP adapters share this entry point without changing their behavior. +pub(crate) async fn enforce_mcp_protocol_version( + config: &L7EndpointConfig, + request: &crate::l7::provider::L7Request, + info: &crate::l7::jsonrpc::JsonRpcRequestInfo, + client: &mut W, + ctx: &L7EvalContext, + redacted_target: &str, +) -> Result +where + W: AsyncWrite + Unpin, +{ + if config.protocol != L7Protocol::Mcp { + return Ok(true); + } + + match crate::l7::mcp::select_request_protocol_version(request, info, &config.mcp_versions) { + Ok(crate::l7::mcp::McpRequestProtocolVersion::Initialization) => Ok(true), + Ok(crate::l7::mcp::McpRequestProtocolVersion::Selected(version)) => { + debug!(mcp_protocol_version = %version, "Selected MCP request protocol version"); + Ok(true) + } + Err(error) => { + let reason = error.to_string(); + let summary = l7_protocol_log_summary(None, Some(info)); + ocsf_emit!(build_l7_request_event( + ctx, + &request.action, + redacted_target, + "deny", + "l7-mcp", + &reason, + summary.as_deref(), + )); + let deny_group = match error { + crate::l7::mcp::McpProtocolVersionError::NotAllowed(_) => "l7_policy", + crate::l7::mcp::McpProtocolVersionError::InvalidHeader + | crate::l7::mcp::McpProtocolVersionError::UnsupportedHeaderValue => { + "l7_parse_rejection" + } + }; + emit_activity(ctx, true, deny_group); + + let body = serde_json::json!({ + "error": error.response_code(), + "detail": reason, + "policy": ctx.policy_name, + "layer": "l7", + "protocol": "mcp", + "method": request.action, + "path": redacted_target, + }); + crate::l7::rest::send_json_response( + &ctx.policy_name, + body, + client, + error.http_status(), + ) + .await?; + Ok(false) + } + } +} + +/// Reinspect the buffered outgoing MCP request after request transformations. +/// The forwarding adapter must call this before any upstream request write. +pub(crate) async fn enforce_final_mcp_protocol_version( + config: &L7EndpointConfig, + request: &crate::l7::provider::L7Request, + client: &mut W, + ctx: &L7EvalContext, + redacted_target: &str, +) -> Result +where + W: AsyncWrite + Unpin, +{ + if config.protocol != L7Protocol::Mcp { + return Ok(true); + } + let info = crate::l7::jsonrpc::inspect_buffered_jsonrpc_http_request( + request, + crate::l7::jsonrpc::JsonRpcInspectionOptions::for_config(config), + )?; + enforce_mcp_protocol_version(config, request, &info, client, ctx, redacted_target).await +} + fn build_request_authority_mismatch_event(ctx: &L7EvalContext) -> openshell_ocsf::OcsfEvent { HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Fail) @@ -688,6 +775,12 @@ where graphql: graphql_info.clone(), jsonrpc: jsonrpc_info.clone(), }; + if let Some(info) = jsonrpc_info.as_ref() + && !enforce_mcp_protocol_version(config, &req, info, client, ctx, &redacted_target) + .await? + { + return Ok(()); + } let websocket_request = crate::l7::rest::request_is_websocket_upgrade(&req.raw_header); if config.protocol == L7Protocol::Websocket && !websocket_request { crate::l7::rest::RestProvider::default() @@ -790,6 +883,11 @@ where return Ok(()); } }; + if !enforce_final_mcp_protocol_version(config, &req, client, ctx, &redacted_target) + .await? + { + return Ok(()); + } let scoped_ctx = scoped_context_for_request(ctx, &req); let ctx = scoped_ctx.as_ref().unwrap_or(ctx); let mut middleware_session = if let Some(chain) = websocket_chain.as_deref() { @@ -1759,9 +1857,6 @@ where return Ok(()); } - // Future MCP version-profile request checks should hook here before OPA - // evaluation. See McpOptions in proto/sandbox.proto for the policy - // roadmap and source documentation. let parsed = match crate::l7::jsonrpc::parse_jsonrpc_http_request( client, config.json_rpc_max_body_bytes, @@ -1817,6 +1912,11 @@ where graphql: None, jsonrpc: Some(jsonrpc_info.clone()), }; + if !enforce_mcp_protocol_version(config, &req, &jsonrpc_info, client, ctx, &redacted_target) + .await? + { + return Ok(()); + } let hard_deny_reason = l7_request_hard_deny_reason(config.protocol, &request_info); let force_deny = hard_deny_reason.is_some(); @@ -1928,6 +2028,11 @@ where return Ok(()); } }; + if !enforce_final_mcp_protocol_version(config, &req, client, ctx, &redacted_target) + .await? + { + return Ok(()); + } let scoped_ctx = scoped_context_for_request(ctx, &req); let ctx = scoped_ctx.as_ref().unwrap_or(ctx); // Future MCP response/SSE introspection or rewrite would hook here @@ -8574,6 +8679,213 @@ network_policies: .unwrap(); } + #[tokio::test] + async fn mcp_relay_forwards_standalone_initialize_without_version_header() { + let (config, tunnel_engine, ctx) = mcp_test_relay_context(); + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_with_inspection( + &config, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + let body = br#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}"#; + let request = format!( + "POST /mcp HTTP/1.1\r\nHost: mcp.example.test:8000\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + app.write_all(request.as_bytes()).await.unwrap(); + app.write_all(body).await.unwrap(); + + let mut upstream_bytes = vec![0; 2048]; + let count = tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read(&mut upstream_bytes), + ) + .await + .expect("standalone initialize should reach upstream") + .unwrap(); + let upstream_request = String::from_utf8_lossy(&upstream_bytes[..count]); + assert!(upstream_request.contains(r#""method":"initialize""#)); + + upstream + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 36\r\nConnection: close\r\n\r\n{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}", + ) + .await + .unwrap(); + let mut response = [0; 512]; + let count = + tokio::time::timeout(std::time::Duration::from_secs(1), app.read(&mut response)) + .await + .expect("initialize response should reach client") + .unwrap(); + assert!(String::from_utf8_lossy(&response[..count]).contains("200 OK")); + + drop(app); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should complete") + .unwrap() + .unwrap(); + } + + async fn run_rejected_mcp_version_request( + route_selected: bool, + version_headers: &str, + ) -> (String, Vec) { + let (config, tunnel_engine, ctx) = mcp_test_relay_context(); + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + if route_selected { + relay_with_route_selection( + &[config], + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + } else { + relay_with_inspection( + &config, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + } + }); + + let body = br#"{"jsonrpc":"2.0","id":7,"result":{"ok":true}}"#; + let request = format!( + "POST /mcp HTTP/1.1\r\nHost: mcp.example.test:8000\r\nContent-Type: application/json\r\n{version_headers}Content-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + app.write_all(request.as_bytes()).await.unwrap(); + app.write_all(body).await.unwrap(); + + let mut response = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(1), + app.read_to_end(&mut response), + ) + .await + .expect("MCP version rejection should close the client response") + .unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should complete after version rejection") + .unwrap() + .unwrap(); + + let mut forwarded = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read_to_end(&mut forwarded), + ) + .await + .expect("version rejection should close upstream without forwarding") + .unwrap(); + ( + String::from_utf8(response).expect("UTF-8 response"), + forwarded, + ) + } + + #[tokio::test] + async fn mcp_relay_rejects_invalid_disallowed_and_missing_versions_without_forwarding() { + for (headers, status, code) in [ + ( + "MCP-Protocol-Version: 2026-07-28\r\n", + "400 Bad Request", + "unsupported_mcp_protocol_version", + ), + ( + "MCP-Protocol-Version: 2025-11-25\r\nMCP-Protocol-Version: 2025-11-25\r\n", + "400 Bad Request", + "invalid_mcp_protocol_version_header", + ), + ( + "MCP-Protocol-Version: 2025-06-18\r\n", + "403 Forbidden", + "mcp_protocol_version_not_allowed", + ), + ("", "403 Forbidden", "mcp_protocol_version_not_allowed"), + ] { + let (response, forwarded) = run_rejected_mcp_version_request(false, headers).await; + assert!( + response.starts_with(&format!("HTTP/1.1 {status}")), + "{response}" + ); + assert!(response.contains(code), "{response}"); + assert!(forwarded.is_empty(), "rejected request reached upstream"); + } + } + + #[tokio::test] + async fn route_selected_mcp_relay_enforces_request_version_before_forwarding() { + let (response, forwarded) = + run_rejected_mcp_version_request(true, "MCP-Protocol-Version: 2026-07-28\r\n").await; + + assert!( + response.starts_with("HTTP/1.1 400 Bad Request"), + "{response}" + ); + assert!( + response.contains("unsupported_mcp_protocol_version"), + "{response}" + ); + assert!(forwarded.is_empty(), "rejected request reached upstream"); + } + + #[tokio::test] + async fn final_mcp_version_check_reclassifies_a_rewritten_initialize_body() { + let (config, _, ctx) = mcp_test_relay_context(); + let final_body = br#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#; + let mut raw_header = format!( + "POST /mcp HTTP/1.1\r\nHost: mcp.example.test:8000\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + final_body.len() + ) + .into_bytes(); + raw_header.extend_from_slice(final_body); + let request = crate::l7::provider::L7Request { + action: "POST".to_string(), + target: "/mcp".to_string(), + query_params: std::collections::HashMap::new(), + raw_header, + body_length: crate::l7::provider::BodyLength::ContentLength(final_body.len() as u64), + }; + let (mut client, mut relay_client) = tokio::io::duplex(2048); + + let allowed = + enforce_final_mcp_protocol_version(&config, &request, &mut relay_client, &ctx, "/mcp") + .await + .expect("final request inspection"); + assert!( + !allowed, + "rewritten non-initialize request must require a version" + ); + drop(relay_client); + + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + let response = String::from_utf8(response).expect("UTF-8 response"); + assert!(response.starts_with("HTTP/1.1 403 Forbidden"), "{response}"); + assert!( + response.contains("mcp_protocol_version_not_allowed"), + "{response}" + ); + } + #[tokio::test] async fn mcp_relay_forwards_jsonrpc_response_frame() { let (config, tunnel_engine, ctx) = mcp_test_relay_context(); @@ -8592,7 +8904,7 @@ network_policies: let body = br#"{"jsonrpc":"2.0","id":7,"result":{"action":"accept","content":{}}}"#; let request = format!( - "POST /mcp HTTP/1.1\r\nHost: mcp.example.test:8000\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + "POST /mcp HTTP/1.1\r\nHost: mcp.example.test:8000\r\nContent-Type: application/json\r\nMCP-Protocol-Version: 2025-11-25\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len() ); app.write_all(request.as_bytes()).await.unwrap(); diff --git a/crates/openshell-supervisor-network/src/l7/rest.rs b/crates/openshell-supervisor-network/src/l7/rest.rs index 93315a671a..42bf3a33df 100644 --- a/crates/openshell-supervisor-network/src/l7/rest.rs +++ b/crates/openshell-supervisor-network/src/l7/rest.rs @@ -2639,7 +2639,8 @@ async fn send_forbidden_json( send_json_response(policy_name, body, client, "403 Forbidden").await } -async fn send_json_response( +/// Send a platform-owned JSON response with an explicit HTTP status. +pub(crate) async fn send_json_response( policy_name: &str, body: serde_json::Value, client: &mut C, diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 2fefb788eb..add7be9b33 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -4651,9 +4651,8 @@ async fn handle_forward_proxy( raw_header: forward_request_bytes, body_length, }; - if crate::l7::jsonrpc::jsonrpc_receive_stream_request(&jsonrpc_request) { - forward_request_bytes = jsonrpc_request.raw_header; - Some(crate::l7::jsonrpc::JsonRpcRequestInfo::receive_stream()) + let info = if crate::l7::jsonrpc::jsonrpc_receive_stream_request(&jsonrpc_request) { + crate::l7::jsonrpc::JsonRpcRequestInfo::receive_stream() } else { let body = match crate::l7::http::read_body_for_inspection( client, @@ -4686,12 +4685,28 @@ async fn handle_forward_proxy( return Ok(()); } }; - forward_request_bytes = jsonrpc_request.raw_header; - Some(crate::l7::jsonrpc::parse_jsonrpc_body_with_options( + crate::l7::jsonrpc::parse_jsonrpc_body_with_options( &body, crate::l7::jsonrpc::JsonRpcInspectionOptions::for_config(&l7_config.config), - )) + ) + }; + // Forward HTTP shares the MCP transport gate with CONNECT before + // method authorization. Borrow the buffered request so checking + // the version does not copy the inspected body. + if !crate::l7::relay::enforce_mcp_protocol_version( + &l7_config.config, + &jsonrpc_request, + &info, + client, + &l7_ctx, + &telemetry_path, + ) + .await? + { + return Ok(()); } + forward_request_bytes = jsonrpc_request.raw_header; + Some(info) } else { None }; @@ -5159,6 +5174,38 @@ async fn handle_forward_proxy( } }; + // Middleware and credential rewriting can change request headers. Check + // the final origin-form bytes after hop-by-hop sanitization, before an + // upstream connection exists, so forwarding preserves the MCP decision. + let rewritten = match forward_l7_reeval.as_ref() { + Some((config, _)) if config.protocol == crate::l7::L7Protocol::Mcp => { + let request = crate::l7::rest::request_from_buffered_http( + method, + middleware_path, + &upstream_target, + rewritten, + )?; + if !crate::l7::relay::enforce_final_mcp_protocol_version( + config, + &request, + client, + &l7_ctx, + &telemetry_path, + ) + .await? + { + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::MiddlewareSessionEndReason::Cancellation) + .await; + } + return Ok(()); + } + request.raw_header + } + _ => rewritten, + }; + if let Err(e) = forward_generation_guard.ensure_current() { warn!( host = %host_lc, @@ -5813,6 +5860,158 @@ network_policies: {} } } + #[tokio::test] + async fn plaintext_mcp_forwarding_preserves_initialization_and_selected_revision() { + if !cfg!(target_os = "linux") { + eprintln!("skipping: handler identity binding requires /proc (Linux)"); + return; + } + let Some(upstream_ip) = non_loopback_test_ipv4() else { + eprintln!("skipping: no routable non-loopback IPv4 test address"); + return; + }; + + for (body, version_header) in [ + ( + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}"#, + "", + ), + ( + r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#, + "MCP-Protocol-Version: 2025-11-25\r\n", + ), + ] { + let upstream_listener = TcpListener::bind((upstream_ip, 0)) + .await + .expect("bind MCP upstream listener"); + let upstream_port = upstream_listener.local_addr().unwrap().port(); + let executable = std::env::current_exe().expect("current executable"); + let data = format!( + r#" +network_middlewares: + inspect: + middleware: openshell/regex + on_error: fail_closed + endpoints: + include: ["{upstream_ip}"] +network_policies: + mcp-upstream: + name: mcp-upstream + endpoints: + - host: "{upstream_ip}" + port: {upstream_port} + path: /mcp + protocol: mcp + enforcement: enforce + rules: + - allow: + method: initialize + - allow: + method: tools/list + binaries: + - {{ path: "{executable}" }} +"#, + executable = executable.display(), + ); + let engine = Arc::new( + OpaEngine::from_strings(include_str!("../data/sandbox-policy.rego"), &data) + .expect("load MCP policy"), + ); + let registry = openshell_supervisor_middleware::MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + Vec::new(), + ) + .await + .expect("connect built-in middleware"); + engine + .replace_middleware_registry(registry) + .expect("install built-in middleware"); + + let upstream = tokio::spawn(async move { + let (mut socket, _) = upstream_listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 2048]; + loop { + let count = socket.read(&mut chunk).await.unwrap(); + assert_ne!(count, 0, "MCP request closed before its body completed"); + request.extend_from_slice(&chunk[..count]); + if let Some(header_end) = request + .windows(4) + .position(|window| window == b"\r\n\r\n") + .map(|end| end + 4) + && request.len() >= header_end + body.len() + { + assert_eq!(&request[header_end..], body.as_bytes()); + break; + } + } + socket + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok", + ) + .await + .unwrap(); + String::from_utf8(request).expect("UTF-8 MCP request") + }); + let proxy_listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind proxy listener"); + let proxy_address = proxy_listener.local_addr().unwrap(); + let target = format!("http://{upstream_ip}:{upstream_port}/mcp"); + let request = format!( + "POST {target} HTTP/1.1\r\nHost: {upstream_ip}:{upstream_port}\r\nContent-Type: application/json\r\n{version_header}Content-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len(), + ); + let client = tokio::spawn(async move { + let mut socket = TcpStream::connect(proxy_address).await.unwrap(); + let mut response = Vec::new(); + socket.read_to_end(&mut response).await.unwrap(); + response + }); + let (mut proxy_connection, _) = proxy_listener.accept().await.unwrap(); + + tokio::time::timeout( + std::time::Duration::from_secs(30), + handle_forward_proxy( + "POST", + &target, + request.as_bytes(), + request.len(), + &mut proxy_connection, + engine, + Arc::new(BinaryIdentityCache::new()), + Arc::new(AtomicU32::new(std::process::id())), + None, + AgentProposals::default(), + Arc::new(None), + None, + None, + None, + None, + None, + ), + ) + .await + .expect("MCP forwarding should complete") + .expect("handle valid MCP request"); + drop(proxy_connection); + + let response = client.await.expect("join MCP client"); + assert!(response.starts_with(b"HTTP/1.1 200 OK")); + let forwarded = upstream.await.expect("join MCP upstream"); + assert!(forwarded.starts_with("POST /mcp HTTP/1.1\r\n")); + if version_header.is_empty() { + assert!( + !forwarded + .to_ascii_lowercase() + .contains("mcp-protocol-version:") + ); + } else { + assert!(forwarded.contains(version_header)); + } + } + } + #[tokio::test] async fn plaintext_websocket_preflight_denial_does_not_connect_upstream() { if !cfg!(target_os = "linux") { diff --git a/docs/reference/policy-schema.mdx b/docs/reference/policy-schema.mdx index 73a6b5cfc4..8f7baa3130 100644 --- a/docs/reference/policy-schema.mdx +++ b/docs/reference/policy-schema.mdx @@ -185,7 +185,7 @@ Each endpoint defines a reachable destination and optional inspection rules. | `graphql_persisted_queries` | map | No | Trusted GraphQL persisted-query registry keyed by hash or saved-query ID. Values contain `operation_type`, optional `operation_name`, and optional root `fields`. | | `graphql_max_body_bytes` | integer | No | Maximum GraphQL-over-HTTP request body bytes buffered for inspection. Defaults to `65536`. | | `mcp` | object | No | MCP endpoint options for `protocol: mcp`. Omit this key to use all MCP endpoint defaults, including the exact `2025-11-25` revision; `mcp: null` is invalid. The object is rejected on other protocols. Every MCP endpoint must still set a concrete `host` and `port` or `ports`; an entry containing only `protocol: mcp` is invalid and is not treated as a wildcard endpoint. | -| `mcp.versions` | list of string | No | Nonempty allowlist of exact supported MCP core revisions: `2025-03-26`, `2025-06-18`, and `2025-11-25`. Omission resolves to the exact allowlist `["2025-11-25"]`; it never means latest or all known revisions. The key must be absent to use this default; `versions: null` and `versions: []` are invalid. Use an explicit nonempty list only for intentional compatibility or downgrade control. The exact floor is `2025-03-26`; this is a closed set, not a date range. Values must be unique and contain no extra whitespace. Moving aliases such as `draft` and `latest`, unknown dates, and named SEP overlays are not accepted. OpenShell stores the materialized list in semantic order. The sessionless `2026-07-28` revision is not accepted until its distinct per-request runtime contract is supported. This field declares compatibility but does not yet select request parsing or forwarding behavior. For an unsupported revision, omit `protocol` and `mcp` only when deliberate uninspected L4 passthrough is an acceptable weaker boundary. | +| `mcp.versions` | list of string | No | Nonempty allowlist of exact supported MCP core revisions: `2025-03-26`, `2025-06-18`, and `2025-11-25`. Omission resolves to the exact allowlist `["2025-11-25"]`; it never means latest or all known revisions. The key must be absent to use this default; `versions: null` and `versions: []` are invalid. Values must be unique, contain no extra whitespace, and name a revision in the closed supported set. For every request except a valid standalone `initialize`, OpenShell selects the revision from one `MCP-Protocol-Version` header or, when the header is absent, the MCP specification's `2025-03-26` compatibility fallback. The selected revision must appear in this allowlist. Duplicate, empty, or unsupported header values receive `400 Bad Request`; a supported revision outside the allowlist receives `403 Forbidden`. The sessionless `2026-07-28` revision is not yet supported. For an unsupported revision, omit `protocol` and `mcp` only when deliberate uninspected L4 passthrough is an acceptable weaker boundary. | | `mcp.max_body_bytes` | integer | No | Maximum MCP JSON-RPC-over-HTTP request body bytes buffered for inspection. Defaults to `65536`. | | `mcp.strict_tool_names` | bool | No | Defaults to `true`. Requires `tools/call` `params.name` values to match `^[A-Za-z0-9_.-]{1,128}$` before policy evaluation. Set to `false` only for compatibility with MCP servers that intentionally use non-recommended tool names. Wildcard `tool` matchers require this to remain enabled. | | `mcp.allow_all_known_mcp_methods` | bool | No | Defaults to `false`. When `true`, enables the endpoint MCP method profile: omitted `rules` allow all MCP-family methods and all tools before `deny_rules`, and omitted rule `method` uses that profile. When unset or `false`, explicit MCP method rules are required; rules with `tool` or `params.name` must set `method: tools/call`. | @@ -346,7 +346,7 @@ Do not combine `method`, `path`, or `query` with `operation_type`, `operation_na ##### MCP Allow And Deny Rules (`protocol: mcp`) -MCP rules match sandbox-to-server MCP Streamable HTTP request bodies by MCP method and optional tool selectors. OpenShell parses the underlying JSON-RPC 2.0 envelope, validates known MCP request and notification params, and preserves unknown extension methods as policy-addressable literal method strings. An endpoint that omits `mcp.versions`, including one that omits the entire `mcp` object, immediately resolves to the exact `2025-11-25` allowlist. Canonical serialization and stored policy data contain that explicit materialized list, so adding another supported revision cannot widen the normalized policy. The schema validates and canonicalizes an explicit nonempty allowlist as an advanced compatibility or downgrade control, but it does not yet use the allowlist to select request parsing or forwarding behavior. Later runtime negotiation must select one server-confirmed revision from the allowlist and apply only that profile, never a union or fallback. `mcp.allow_all_known_mcp_methods` defaults to `false`, so endpoints require explicit MCP method rules. Set it to `true` to enable the endpoint method profile; in that mode, rules can omit `method`, and tool selectors are normalized to `tools/call` internally. By default, `tools/call` `params.name` must match the MCP-recommended tool-name pattern `^[A-Za-z0-9_.-]{1,128}$`; configure `mcp.strict_tool_names: false` on the endpoint only to allow a server that intentionally uses names outside that pattern. Wildcard `tool` matchers require `mcp.strict_tool_names` to remain enabled. JSON-RPC responses and server-to-client MCP messages on response bodies or SSE streams are relayed but are not currently parsed for policy enforcement. +MCP rules match sandbox-to-server MCP Streamable HTTP request bodies by MCP method and optional tool selectors. OpenShell parses the underlying JSON-RPC 2.0 envelope, validates known MCP request and notification params, and preserves unknown extension methods as policy-addressable literal method strings. An endpoint that omits `mcp.versions`, including one that omits the entire `mcp` object, immediately resolves to the exact `2025-11-25` allowlist. Canonical serialization and stored policy data contain that explicit materialized list, so adding another supported revision cannot widen the normalized policy. For every request except a valid standalone `initialize`, OpenShell checks exactly one `MCP-Protocol-Version` value against the allowlist before policy evaluation and repeats the check after middleware changes the request. An absent header selects the `2025-03-26` compatibility fallback; it does not select the policy default. The check stores no connection or session state. The current parser remains version-independent and does not yet apply the batch rules recorded in each revision's wire profile. `mcp.allow_all_known_mcp_methods` defaults to `false`, so endpoints require explicit MCP method rules. Set it to `true` to enable the endpoint method profile; in that mode, rules can omit `method`, and tool selectors are normalized to `tools/call` internally. By default, `tools/call` `params.name` must match the MCP-recommended tool-name pattern `^[A-Za-z0-9_.-]{1,128}$`; configure `mcp.strict_tool_names: false` on the endpoint only to allow a server that intentionally uses names outside that pattern. Wildcard `tool` matchers require `mcp.strict_tool_names` to remain enabled. JSON-RPC responses and server-to-client MCP messages on response bodies or SSE streams are relayed but are not currently parsed for policy enforcement. Use `rules` for MCP allow rules and `deny_rules` for MCP deny rules. Deny rules take precedence over allow rules. If an MCP endpoint sets `mcp.allow_all_known_mcp_methods: true` and omits `rules`, OpenShell allows all MCP-family methods and all tools, then applies any `deny_rules`. Otherwise, the endpoint must define explicit rules. A broad allow or deny rule whose method matcher includes `tools/call` cannot be combined with tool-specific allow rules because it would bypass or erase the tool filter; add `tool` or `params.name` to scope `tools/call`, or remove the tool-specific rules. In a batch request, one denied call denies the full batch. diff --git a/docs/sandboxes/policies.mdx b/docs/sandboxes/policies.mdx index d0fc05b061..af25238a6b 100644 --- a/docs/sandboxes/policies.mdx +++ b/docs/sandboxes/policies.mdx @@ -738,7 +738,7 @@ REST rules can also constrain query parameter values: ### MCP and JSON-RPC matching -MCP endpoints use `protocol: mcp`. The proxy parses sandbox-to-server MCP Streamable HTTP request bodies, validates known MCP request and notification params, can evaluate the MCP method against rule `method`, and can match tool calls with the `tool` alias. Unknown extension methods stay addressable as literal method strings. You may omit the entire `mcp` stanza when using its defaults, or omit only `mcp.versions` when setting another MCP option. OpenShell immediately resolves either form to the exact `["2025-11-25"]` allowlist and stores the materialized list in canonical policy data. Adding another supported revision therefore never widens a normalized policy. Defaulting requires the `mcp` or `mcp.versions` key to be absent; explicit `mcp: null`, `versions: null`, and `versions: []` values are invalid. Use an explicit nonempty allowlist only for intentional compatibility or downgrade control. Supported revisions are `2025-03-26`, `2025-06-18`, and `2025-11-25`; the exact support floor is `2025-03-26`, and this is a closed set rather than a date range. Explicit values must be unique and contain no extra whitespace; OpenShell stores them in semantic order. Moving aliases such as `draft` or `latest` are rejected because they could change policy meaning without a policy edit; omission never means all known versions. The sessionless `2026-07-28` revision is not accepted until OpenShell supports its distinct per-request runtime contract. A version identifies a core MCP revision only; there is no policy syntax for separately named SEP overlays. The allowlist establishes the policy contract but does not yet select request parsing or forwarding behavior. Later runtime negotiation must select one server-confirmed revision from the allowlist and apply that exact profile, never a union or fallback. `mcp.allow_all_known_mcp_methods` defaults to `false`, so endpoints require explicit MCP method rules. Set it to `true` to enable the endpoint method profile; in that mode, rules can omit `method`, and tool selectors are normalized to `tools/call` internally. By default, MCP `tools/call` tool names must match `^[A-Za-z0-9_.-]{1,128}$`; set `mcp.strict_tool_names: false` on that endpoint only when a server intentionally uses names outside the MCP-recommended pattern. Wildcard `tool` matchers require `mcp.strict_tool_names` to remain enabled. Generic JSON-RPC endpoints use `protocol: json-rpc` and evaluate `method`. +MCP endpoints use `protocol: mcp`. The proxy parses sandbox-to-server MCP Streamable HTTP request bodies, validates known MCP request and notification params, can evaluate the MCP method against rule `method`, and can match tool calls with the `tool` alias. Unknown extension methods stay addressable as literal method strings. You may omit the entire `mcp` stanza when using its defaults, or omit only `mcp.versions` when setting another MCP option. OpenShell immediately resolves either form to the exact `["2025-11-25"]` allowlist and stores the materialized list in canonical policy data. Adding another supported revision therefore never widens a normalized policy. Defaulting requires the `mcp` or `mcp.versions` key to be absent; explicit `mcp: null`, `versions: null`, and `versions: []` values are invalid. Use an explicit nonempty allowlist only for intentional compatibility or downgrade control. Supported revisions are `2025-03-26`, `2025-06-18`, and `2025-11-25`; the exact support floor is `2025-03-26`, and this is a closed set rather than a date range. Explicit values must be unique and contain no extra whitespace; OpenShell stores them in semantic order. Moving aliases such as `draft` or `latest` are rejected because they could change policy meaning without a policy edit; omission never means all known versions. The sessionless `2026-07-28` revision is not accepted until OpenShell supports its distinct per-request contract. A version identifies a core MCP revision only; there is no policy syntax for separately named SEP overlays. For every MCP HTTP request except a valid standalone `initialize`, OpenShell selects the revision from one `MCP-Protocol-Version` header or, when the header is absent, the MCP specification's `2025-03-26` compatibility fallback. The selected revision must appear in the allowlist. Duplicate, empty, and unsupported header values receive `400 Bad Request`; a supported revision outside the allowlist receives `403 Forbidden`. OpenShell checks the request again after middleware changes it and before forwarding. Generic JSON-RPC endpoints do not use this header and continue to evaluate only `method`. `mcp.allow_all_known_mcp_methods` defaults to `false`, so endpoints require explicit MCP method rules. Set it to `true` to enable the endpoint method profile; in that mode, rules can omit `method`, and tool selectors are normalized to `tools/call` internally. By default, MCP `tools/call` tool names must match `^[A-Za-z0-9_.-]{1,128}$`; set `mcp.strict_tool_names: false` on that endpoint only when a server intentionally uses names outside the MCP-recommended pattern. Wildcard `tool` matchers require `mcp.strict_tool_names` to remain enabled. The current registry declares these profile facts for later runtime enforcement: @@ -746,7 +746,7 @@ The current registry declares these profile facts for later runtime enforcement: - `2025-06-18` prohibits top-level JSON-RPC arrays. - `2025-11-25` prohibits top-level JSON-RPC arrays. -These declarations do not change the current version-independent request parser. OpenShell does not yet treat the client's `initialize.params.protocolVersion` as the selected profile, inspect the server's negotiated revision, bind `MCP-Session-Id`, or validate `MCP-Protocol-Version` on later requests. Later runtime selection must observe the successful server response, verify that the selected revision appears in the effective allowlist, and bind that one exact profile without a union or fallback so the proxy does not interfere with version negotiation. +OpenShell uses the per-request header only to enforce the allowlist; the current parser does not yet apply these version-specific batch rules. OpenShell does not treat the client's `initialize.params.protocolVersion` as the selected revision, inspect the server's initialization response, or bind `MCP-Session-Id`. The version check is stateless and applies independently to each later request, including GET and DELETE. MCP endpoints must declare a concrete destination with `host` and `port` or `ports`. A policy entry that only sets `protocol: mcp` is invalid and is not treated as a wildcard MCP authorization. Use `path: /mcp` when the server's MCP endpoint is path-scoped; omitting `path` matches every HTTP path on that host and port. diff --git a/e2e/mcp-conformance/README.md b/e2e/mcp-conformance/README.md index 0be6b34c22..8d244ab612 100644 --- a/e2e/mcp-conformance/README.md +++ b/e2e/mcp-conformance/README.md @@ -35,7 +35,7 @@ bridge at `host.openshell.internal` (the alias `e2e/with-docker-gateway.sh` attaches to the CI job container on the e2e network), at `host.docker.internal` on local Docker Desktop, or via `--add-host ...:host-gateway` on local Linux. -The generated policy uses `protocol: mcp`, inserts the conformance runner's spec revision into the endpoint allowlist, and sets `mcp.allow_all_known_mcp_methods: true` so omitted rule methods use the endpoint MCP method profile. This schema declaration does not yet make OpenShell select or enforce that wire profile; the conformance runner still owns the revision used by its client and server. The policy keeps OpenShell deny-by-default at the network boundary while allowing the upstream scenarios to exercise MCP behavior. The policy body lives in `policy-template.yaml`; the wrapper renders its MCP revision, host, port, and path placeholders from the upstream server URL. +The generated policy uses `protocol: mcp`, inserts the conformance runner's spec revision into the endpoint allowlist, and sets `mcp.allow_all_known_mcp_methods: true` so omitted rule methods use the endpoint MCP method profile. OpenShell enforces that allowlist on each non-initialize request using `MCP-Protocol-Version`, with `2025-03-26` as the missing-header fallback. The conformance runner selects the revision used by its client and server; OpenShell's request-version check does not yet provide complete revision-specific message parsing or response validation. The policy keeps OpenShell deny-by-default at the network boundary while allowing the upstream scenarios to exercise MCP behavior. The policy body lives in `policy-template.yaml`; the wrapper renders its MCP revision, host, port, and path placeholders from the upstream server URL. For local runs, the wrapper builds `openshell/supervisor:dev` automatically when no supervisor image override is set. Set `OPENSHELL_DOCKER_SUPERVISOR_IMAGE` From 8211274bfb73aec0eb031164a8a155a9661d073d Mon Sep 17 00:00:00 2001 From: Shiju Date: Wed, 9 Sep 2026 22:44:40 +0000 Subject: [PATCH 2/4] fix(e2e): follow credential storage identity (#3202) Signed-off-by: Drew Newberry Signed-off-by: Shiju Co-authored-by: Drew Newberry --- e2e/rust/tests/credential_drivers.rs | 107 ++++++++++++++++++++------- 1 file changed, 81 insertions(+), 26 deletions(-) diff --git a/e2e/rust/tests/credential_drivers.rs b/e2e/rust/tests/credential_drivers.rs index 34a457b542..fd8ebb0607 100644 --- a/e2e/rust/tests/credential_drivers.rs +++ b/e2e/rust/tests/credential_drivers.rs @@ -41,6 +41,12 @@ fn credential_driver() -> String { .unwrap_or_else(|_| "kubernetes-secrets".to_string()) } +#[derive(Debug)] +struct ProviderIdentity { + id: String, + workspace: String, +} + fn vault_namespace() -> String { std::env::var("OPENSHELL_E2E_VAULT_NAMESPACE").unwrap_or_else(|_| "vault".to_string()) } @@ -53,23 +59,28 @@ fn vault_token() -> String { std::env::var("OPENSHELL_E2E_VAULT_TOKEN").unwrap_or_else(|_| "root".to_string()) } -fn managed_kubernetes_secret_name(provider_name: &str) -> String { +fn managed_credential_hash(identity: &ProviderIdentity, provider_name: &str) -> String { + // This test stores an ordinary provider credential, whose storage object ID is + // the provider ID, so both managed drivers use these four identity fields. let mut hasher = Sha256::new(); + hasher.update(identity.workspace.as_bytes()); + hasher.update([0]); + hasher.update(identity.id.as_bytes()); + hasher.update([0]); hasher.update(provider_name.as_bytes()); hasher.update([0]); hasher.update(CREDENTIAL_KEY.as_bytes()); let digest = hasher.finalize(); - let hex = format!("{digest:x}"); + format!("{digest:x}") +} + +fn managed_kubernetes_secret_name(identity: &ProviderIdentity, provider_name: &str) -> String { + let hex = managed_credential_hash(identity, provider_name); format!("openshell-cred-{}", &hex[..40]) } -fn managed_vault_path(provider_name: &str) -> String { - let mut hasher = Sha256::new(); - hasher.update(provider_name.as_bytes()); - hasher.update([0]); - hasher.update(CREDENTIAL_KEY.as_bytes()); - let digest = hasher.finalize(); - let hex = format!("{digest:x}"); +fn managed_vault_path(identity: &ProviderIdentity, provider_name: &str) -> String { + let hex = managed_credential_hash(identity, provider_name); format!("openshell/provider-credentials/{}", &hex[..40]) } @@ -217,6 +228,31 @@ async fn create_provider(name: &str, secret_value: &str) -> Result Result { + let (output, code) = run_cli(&["provider", "list", "--output", "json"]).await; + let clean = strip_ansi(&output); + if code != 0 { + return Err(format!("provider list failed (exit {code}):\n{clean}")); + } + let providers: Vec = serde_json::from_str(&clean) + .map_err(|err| format!("failed to parse provider list JSON: {err}\n{clean}"))?; + let provider = providers + .iter() + .find(|provider| provider["name"].as_str() == Some(provider_name)) + .ok_or_else(|| format!("provider '{provider_name}' was not returned by provider list"))?; + let id = provider["id"] + .as_str() + .filter(|id| !id.is_empty()) + .ok_or_else(|| format!("provider '{provider_name}' did not include an ID"))?; + let workspace = provider["workspace"] + .as_str() + .ok_or_else(|| format!("provider '{provider_name}' did not include a workspace"))?; + Ok(ProviderIdentity { + id: id.to_string(), + workspace: workspace.to_string(), + }) +} + async fn assert_provider_get_does_not_expose_secret( provider_name: &str, secret_value: &str, @@ -296,11 +332,12 @@ async fn configure_vault_storage() -> Result<(), String> { } async fn assert_kubernetes_secret_stored( + identity: &ProviderIdentity, provider_name: &str, secret_value: &str, ) -> Result<(), String> { let namespace = namespace(); - let secret_name = managed_kubernetes_secret_name(provider_name); + let secret_name = managed_kubernetes_secret_name(identity, provider_name); let encoded = kubectl(&[ "-n", &namespace, @@ -322,9 +359,12 @@ async fn assert_kubernetes_secret_stored( Ok(()) } -async fn assert_kubernetes_secret_deleted(provider_name: &str) -> Result<(), String> { +async fn assert_kubernetes_secret_deleted( + identity: &ProviderIdentity, + provider_name: &str, +) -> Result<(), String> { let namespace = namespace(); - let secret_name = managed_kubernetes_secret_name(provider_name); + let secret_name = managed_kubernetes_secret_name(identity, provider_name); match kubectl(&["-n", &namespace, "get", "secret", &secret_name]).await { Ok(output) => Err(format!( "Kubernetes Secret '{secret_name}' still exists after provider deletion:\n{output}" @@ -333,8 +373,12 @@ async fn assert_kubernetes_secret_deleted(provider_name: &str) -> Result<(), Str } } -async fn assert_vault_secret_stored(provider_name: &str, secret_value: &str) -> Result<(), String> { - let logical_path = managed_vault_path(provider_name); +async fn assert_vault_secret_stored( + identity: &ProviderIdentity, + provider_name: &str, + secret_value: &str, +) -> Result<(), String> { + let logical_path = managed_vault_path(identity, provider_name); let output = bao(&[ "kv", "get", @@ -348,8 +392,11 @@ async fn assert_vault_secret_stored(provider_name: &str, secret_value: &str) -> Ok(()) } -async fn assert_vault_secret_deleted(provider_name: &str) -> Result<(), String> { - let logical_path = managed_vault_path(provider_name); +async fn assert_vault_secret_deleted( + identity: &ProviderIdentity, + provider_name: &str, +) -> Result<(), String> { + let logical_path = managed_vault_path(identity, provider_name); match bao(&[ "kv", "get", @@ -367,20 +414,27 @@ async fn assert_vault_secret_deleted(provider_name: &str) -> Result<(), String> async fn assert_backend_stored( driver: &str, + identity: &ProviderIdentity, provider_name: &str, secret_value: &str, ) -> Result<(), String> { match driver { - "kubernetes-secrets" => assert_kubernetes_secret_stored(provider_name, secret_value).await, - "vault" => assert_vault_secret_stored(provider_name, secret_value).await, + "kubernetes-secrets" => { + assert_kubernetes_secret_stored(identity, provider_name, secret_value).await + } + "vault" => assert_vault_secret_stored(identity, provider_name, secret_value).await, other => Err(format!("unsupported credential driver '{other}'")), } } -async fn assert_backend_deleted(driver: &str, provider_name: &str) -> Result<(), String> { +async fn assert_backend_deleted( + driver: &str, + identity: &ProviderIdentity, + provider_name: &str, +) -> Result<(), String> { match driver { - "kubernetes-secrets" => assert_kubernetes_secret_deleted(provider_name).await, - "vault" => assert_vault_secret_deleted(provider_name).await, + "kubernetes-secrets" => assert_kubernetes_secret_deleted(identity, provider_name).await, + "vault" => assert_vault_secret_deleted(identity, provider_name).await, other => Err(format!("unsupported credential driver '{other}'")), } } @@ -409,23 +463,24 @@ async fn provider_credentials_are_stored_in_configured_backend() { .expect("configure Vault storage fixture"); } - let result: Result<(), String> = async { + let result: Result = async { create_provider(&provider_name, &secret_value).await?; assert_provider_get_does_not_expose_secret(&provider_name, &secret_value).await?; - assert_backend_stored(&driver, &provider_name, &secret_value).await?; + let identity = provider_identity(&provider_name).await?; + assert_backend_stored(&driver, &identity, &provider_name, &secret_value).await?; assert_provider_placeholder_available_in_sandbox( &provider_name, &sandbox_name, &secret_value, ) .await?; - Ok(()) + Ok(identity) } .await; delete_provider(&provider_name).await; - assert_backend_deleted(&driver, &provider_name) + let identity = result.expect("credential storage e2e failed"); + assert_backend_deleted(&driver, &identity, &provider_name) .await .expect("credential backend object should be deleted with provider"); - result.expect("credential storage e2e failed"); } From 3ea0ce896ca31a62f377e61ffe0ebb2843c84786 Mon Sep 17 00:00:00 2001 From: Shiju Date: Wed, 9 Sep 2026 22:45:32 +0000 Subject: [PATCH 3/4] fix(cli): reconcile provisional container exits (#3204) Keep watching briefly when a compute driver reports ContainerExited without a canonical main-process result. This prevents --no-keep cleanup from deleting the sandbox before the supervisor publishes the authoritative exit status. Signed-off-by: Shiju --- crates/openshell-cli/src/run.rs | 37 ++++- .../sandbox_create_lifecycle_integration.rs | 151 +++++++++++++++++- 2 files changed, 186 insertions(+), 2 deletions(-) diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index abdb4bfa61..fbad0d505f 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -69,6 +69,8 @@ use std::process::Command; use std::time::{Duration, Instant}; use tonic::{Code, Status}; +const PROVISIONAL_CONTAINER_EXIT_RECONCILIATION_TIMEOUT: Duration = Duration::from_secs(5); + // Re-export SSH functions for backward compatibility pub use crate::ssh::{Editor, print_ssh_config}; pub use crate::ssh::{ @@ -251,6 +253,19 @@ fn has_main_process_result(sandbox: &Sandbox) -> bool { }) } +fn is_provisional_container_exit(sandbox: &Sandbox) -> bool { + let phase = SandboxPhase::try_from(sandbox.phase()).unwrap_or(SandboxPhase::Unknown); + phase == SandboxPhase::Error + && sandbox.status.as_ref().is_some_and(|status| { + status.exit_code.is_none() + && status.conditions.iter().any(|condition| { + condition.r#type == "Ready" + && condition.status.eq_ignore_ascii_case("false") + && condition.reason == "ContainerExited" + }) + }) +} + fn build_sandbox_resource_limits( cpu: Option<&str>, memory: Option<&str>, @@ -765,6 +780,12 @@ pub async fn sandbox_create( .unwrap_or(300), ); let mut provisioning_idle_deadline = Instant::now() + provision_timeout; + // The compute driver can publish ContainerExited while the supervisor's + // authoritative canonical-process result is waiting for the same gateway + // state lock. Keep watching briefly so the provisional error cannot race + // ephemeral cleanup, but retain a deadline for containers that exit before + // the supervisor can report a result. + let mut provisional_container_exit_deadline: Option = None; // Track whether we saw the gateway become ready (from log messages). let mut saw_gateway_ready = false; @@ -773,8 +794,15 @@ pub async fn sandbox_create( // longer than the default timeout pulling and preparing large images, // but only recognized progress events extend the idle deadline. Logs // and generic status churn must not keep a stuck sandbox alive forever. - let remaining = provisioning_idle_deadline.saturating_duration_since(Instant::now()); + let now = Instant::now(); + let mut remaining = provisioning_idle_deadline.saturating_duration_since(now); + if let Some(deadline) = provisional_container_exit_deadline { + remaining = remaining.min(deadline.saturating_duration_since(now)); + } if remaining.is_zero() { + if provisional_container_exit_deadline.is_some() { + break; + } let timeout_message = provisioning_timeout_message( provision_timeout.as_secs(), resource_requirements.as_ref(), @@ -794,6 +822,7 @@ pub async fn sandbox_create( let item = match maybe_item { Ok(Some(item)) => item, Ok(None) => break, // stream ended + Err(_elapsed) if provisional_container_exit_deadline.is_some() => break, Err(_elapsed) => { // Timeout fired — the stream was idle for too long. let timeout_message = provisioning_timeout_message( @@ -850,6 +879,12 @@ pub async fn sandbox_create( format!("{}: {}", condition.reason, condition.message); } } + if is_provisional_container_exit(&s) { + provisional_container_exit_deadline.get_or_insert_with(|| { + Instant::now() + PROVISIONAL_CONTAINER_EXIT_RECONCILIATION_TIMEOUT + }); + continue; + } break; } diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index 33d15f7c5b..d9e3cdad98 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -38,7 +38,7 @@ use std::time::{Duration, Instant}; use tempfile::TempDir; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpListener; -use tokio::sync::{Mutex, mpsc}; +use tokio::sync::{Mutex, Notify, mpsc}; use tokio_stream::wrappers::TcpListenerStream; use tonic::transport::{Certificate as TlsCertificate, Identity, Server, ServerTlsConfig}; use tonic::{Response, Status}; @@ -53,6 +53,9 @@ struct SandboxState { vm_slow_progress_before_ready: Arc, vm_log_churn_before_ready: Arc, terminal_before_relay: Arc, + terminal_after_provisional_container_exit: Arc, + provisional_container_exit_without_result: Arc, + provisional_container_exit_sent: Arc, ssh_session_failures_remaining: Arc, ssh_session_requests: Arc, global_settings: Arc>>, @@ -567,6 +570,16 @@ impl OpenShell for TestOpenShell { .load(Ordering::SeqCst); let vm_log_churn_before_ready = self.state.vm_log_churn_before_ready.load(Ordering::SeqCst); let terminal_before_relay = self.state.terminal_before_relay.load(Ordering::SeqCst); + let terminal_after_provisional_container_exit = self + .state + .terminal_after_provisional_container_exit + .load(Ordering::SeqCst); + let provisional_container_exit_without_result = self + .state + .provisional_container_exit_without_result + .load(Ordering::SeqCst); + let provisional_container_exit_sent = + Arc::clone(&self.state.provisional_container_exit_sent); tokio::spawn(async move { let mut provisioning = Sandbox { @@ -610,11 +623,44 @@ impl OpenShell for TestOpenShell { }); completed.set_phase(SandboxPhase::Completed as i32); + let mut provisional_container_exit = error.clone(); + if let Some(ready) = provisional_container_exit + .status + .as_mut() + .and_then(|status| status.conditions.first_mut()) + { + ready.reason = "ContainerExited".to_string(); + ready.message = "Sandbox container exited".to_string(); + } + let _ = tx .send(Ok(SandboxStreamEvent { payload: Some(sandbox_stream_event::Payload::Sandbox(provisioning)), })) .await; + if terminal_after_provisional_container_exit + || provisional_container_exit_without_result + { + let _ = tx + .send(Ok(SandboxStreamEvent { + payload: Some(sandbox_stream_event::Payload::Sandbox( + provisional_container_exit, + )), + })) + .await; + provisional_container_exit_sent.notify_waiters(); + if provisional_container_exit_without_result { + std::future::pending::<()>().await; + return; + } + tokio::task::yield_now().await; + let _ = tx + .send(Ok(SandboxStreamEvent { + payload: Some(sandbox_stream_event::Payload::Sandbox(completed)), + })) + .await; + return; + } if vm_error_after_started { let _ = tx .send(Ok(SandboxStreamEvent { @@ -2188,6 +2234,109 @@ async fn sandbox_create_retries_terminal_attachment_until_relay_registers() { ); } +#[tokio::test] +async fn sandbox_create_waits_for_main_result_after_provisional_container_exit() { + let server = run_server().await; + server + .openshell + .state + .terminal_after_provisional_container_exit + .store(true, Ordering::SeqCst); + let fake_ssh_dir = tempfile::tempdir().unwrap(); + let xdg_dir = tempfile::tempdir().unwrap(); + let _env = test_env(&fake_ssh_dir, &xdg_dir); + let tls = test_tls(&server); + install_fake_ssh(&fake_ssh_dir); + + let exit_code = run::sandbox_create( + &server.endpoint, + "openshell", + run::SandboxCreateConfig { + name: Some("fast-ephemeral-command"), + keep: false, + command: &["echo".into(), "OK".into()], + ..test_config() + }, + "default", + &tls, + ) + .await + .expect("a provisional container exit must yield to the canonical main-process result"); + + assert_eq!(exit_code, 0); + assert_eq!( + deleted_names(&server).await, + vec![vec!["fast-ephemeral-command".to_string()]] + ); +} + +#[tokio::test] +async fn sandbox_create_bounds_provisional_container_exit_reconciliation() { + let server = run_server().await; + server + .openshell + .state + .provisional_container_exit_without_result + .store(true, Ordering::SeqCst); + let fake_ssh_dir = tempfile::tempdir().unwrap(); + let xdg_dir = tempfile::tempdir().unwrap(); + let _env = test_env(&fake_ssh_dir, &xdg_dir); + let tls = test_tls(&server); + install_fake_ssh(&fake_ssh_dir); + + let provisional_container_exit_sent = server + .openshell + .state + .provisional_container_exit_sent + .notified(); + tokio::pin!(provisional_container_exit_sent); + let command = ["echo".into(), "OK".into()]; + let create = run::sandbox_create( + &server.endpoint, + "openshell", + run::SandboxCreateConfig { + name: Some("missing-main-result"), + command: &command, + ..test_config() + }, + "default", + &tls, + ); + tokio::pin!(create); + + tokio::select! { + () = &mut provisional_container_exit_sent => {} + result = &mut create => panic!("sandbox create returned before the provisional exit was observed: {result:?}"), + } + let reconciliation_started = Instant::now(); + let result = tokio::time::timeout(Duration::from_secs(10), &mut create) + .await + .expect("provisional container exit reconciliation must remain bounded"); + let reconciliation_elapsed = reconciliation_started.elapsed(); + + let err = result + .expect_err("a missing canonical main-process result must retain the container exit error"); + + let rendered = err.to_string(); + assert!( + rendered.contains("sandbox entered error phase while provisioning"), + "unexpected error: {rendered}" + ); + assert!( + rendered.contains("ContainerExited: Sandbox container exited"), + "unexpected error: {rendered}" + ); + assert!( + !rendered.contains("timed out"), + "unexpected error: {rendered}" + ); + assert!( + reconciliation_elapsed >= Duration::from_secs(5), + "provisional container exit returned before reconciliation: {reconciliation_elapsed:?}" + ); + assert!(deleted_names(&server).await.is_empty()); +} + #[tokio::test] async fn sandbox_create_deletes_command_sessions_with_no_keep() { let server = run_server().await; From a0814443f19c07102b19ff09d6ead3d3ba59f9c5 Mon Sep 17 00:00:00 2001 From: Piotr Mlocek Date: Wed, 9 Sep 2026 23:34:34 +0000 Subject: [PATCH 4/4] feat(docs): publish versioned release snapshots (#3149) * feat(docs): add version availability labels Signed-off-by: Piotr Mlocek * fix(docs): use supported Python for sync Signed-off-by: Piotr Mlocek * feat(docs): publish versioned docs from releases Signed-off-by: Piotr Mlocek * fix(docs): format dev version label Signed-off-by: Piotr Mlocek * chore(docs): upgrade Fern CLI to 5.112.0 Signed-off-by: Piotr Mlocek * fix(docs): make release publishing monotonic Signed-off-by: Piotr Mlocek * fix(docs): preserve snapshot release identity Signed-off-by: Piotr Mlocek * docs(fern): document versioned publishing Signed-off-by: Piotr Mlocek * test(docs): cover explicit snapshot rollback Signed-off-by: Piotr Mlocek * refactor(docs): use Fern refs for versions Signed-off-by: Piotr Mlocek * fix(docs): bundle components for ref versions Signed-off-by: Piotr Mlocek * revert(docs): keep complete version copies Signed-off-by: Piotr Mlocek * fix(docs): publish latest and dev channels Signed-off-by: Piotr Mlocek --------- Signed-off-by: Piotr Mlocek --- .github/workflows/publish-docs-website.yml | 1 + .github/workflows/release-dev.yml | 31 +- .github/workflows/release-tag.yml | 37 +- .github/workflows/sync-docs.yml | 99 +++- AGENTS.md | 4 +- CONTRIBUTING.md | 4 +- architecture/build.md | 8 +- fern/README.md | 67 +++ fern/fern.config.json | 2 +- tasks/scripts/sync_docs_website.py | 347 +++++++++++-- tasks/scripts/sync_docs_website_test.py | 576 ++++++++++++++++++++- tasks/test.toml | 6 +- 12 files changed, 1074 insertions(+), 108 deletions(-) create mode 100644 fern/README.md diff --git a/.github/workflows/publish-docs-website.yml b/.github/workflows/publish-docs-website.yml index dfb24b9cea..5c99492b6e 100644 --- a/.github/workflows/publish-docs-website.yml +++ b/.github/workflows/publish-docs-website.yml @@ -25,6 +25,7 @@ permissions: concurrency: group: docs-website cancel-in-progress: false + queue: max defaults: run: diff --git a/.github/workflows/release-dev.yml b/.github/workflows/release-dev.yml index 18b5f33a2e..cfb1a0b546 100644 --- a/.github/workflows/release-dev.yml +++ b/.github/workflows/release-dev.yml @@ -28,6 +28,7 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} outputs: python_version: ${{ steps.v.outputs.python }} + docs_version: ${{ steps.v.outputs.docs_version }} cargo_version: ${{ steps.v.outputs.cargo }} deb_version: ${{ steps.v.outputs.deb }} rpm_version: ${{ steps.v.outputs.rpm_version }} @@ -47,11 +48,15 @@ jobs: id: v run: | set -euo pipefail - echo "python=$(uv run python tasks/scripts/release.py get-version --dev --python)" >> "$GITHUB_OUTPUT" - echo "cargo=$(uv run python tasks/scripts/release.py get-version --dev --cargo)" >> "$GITHUB_OUTPUT" - echo "deb=$(uv run python tasks/scripts/release.py get-version --dev --deb)" >> "$GITHUB_OUTPUT" - echo "rpm_version=$(uv run python tasks/scripts/release.py get-version --dev --rpm-version)" >> "$GITHUB_OUTPUT" - echo "rpm_release=$(uv run python tasks/scripts/release.py get-version --dev --rpm-release)" >> "$GITHUB_OUTPUT" + python_version=$(uv run python tasks/scripts/release.py get-version --dev --python) + { + echo "python=${python_version}" + echo "docs_version=${python_version%%+*}" + echo "cargo=$(uv run python tasks/scripts/release.py get-version --dev --cargo)" + echo "deb=$(uv run python tasks/scripts/release.py get-version --dev --deb)" + echo "rpm_version=$(uv run python tasks/scripts/release.py get-version --dev --rpm-version)" + echo "rpm_release=$(uv run python tasks/scripts/release.py get-version --dev --rpm-release)" + } >> "$GITHUB_OUTPUT" build-cli: needs: compute-versions @@ -628,6 +633,22 @@ jobs: release-kind: dev pin-sha: ${{ github.sha }} + publish-fern-docs: + name: Sync and Publish Fern Docs + needs: [compute-versions, release-dev, release-helm, trigger-wheel-publish] + permissions: + contents: write + uses: ./.github/workflows/sync-docs.yml + with: + operation: sync + channel: dev + source_ref: ${{ github.sha }} + release_version: ${{ needs.compute-versions.outputs.docs_version }} + display_name: Dev + availability: beta + publish: true + secrets: inherit + trigger-wheel-publish: name: Trigger Wheel Publish needs: [compute-versions, release-dev] diff --git a/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml index b3c45c97fb..2fe62fa25b 100644 --- a/.github/workflows/release-tag.yml +++ b/.github/workflows/release-tag.yml @@ -664,31 +664,20 @@ jobs: if-no-files-found: error publish-fern-docs: - name: Publish Fern Docs - needs: [compute-versions, release] + name: Sync and Publish Fern Docs + needs: [compute-versions, release, publish-sdk-typescript, release-helm, trigger-wheel-publish] if: needs.compute-versions.outputs.is_prerelease != 'true' - runs-on: ubuntu-latest - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ inputs.tag || github.ref }} - - - name: Setup Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 - with: - node-version: "24" - - - name: Install Fern CLI - run: | - FERN_VERSION=$(node -p "require('./fern/fern.config.json').version") - npm install -g "fern-api@${FERN_VERSION}" - - - name: Publish Fern docs - env: - FERN_TOKEN: ${{ secrets.FERN_TOKEN }} - working-directory: ./fern - run: fern generate --docs + permissions: + contents: write + uses: ./.github/workflows/sync-docs.yml + with: + operation: sync + channel: latest + source_ref: ${{ needs.compute-versions.outputs.source_sha }} + release_version: ${{ needs.compute-versions.outputs.semver }} + display_name: Latest (v${{ needs.compute-versions.outputs.semver }}) + publish: true + secrets: inherit publish-sdk-typescript: name: Publish TypeScript SDK diff --git a/.github/workflows/sync-docs.yml b/.github/workflows/sync-docs.yml index db2f29f736..63c4a6b8b8 100644 --- a/.github/workflows/sync-docs.yml +++ b/.github/workflows/sync-docs.yml @@ -4,6 +4,49 @@ name: Sync Docs Website on: + workflow_call: + inputs: + operation: + description: "Whether to sync or remove a docs snapshot" + required: true + type: string + channel: + description: "Docs channel to update or remove" + required: true + type: string + source_ref: + description: "Source commit SHA, branch, or tag to snapshot when operation=sync" + required: false + type: string + release_version: + description: "Release version used to order mutable channels" + required: false + type: string + version_slug: + description: "Version slug when channel=version" + required: false + type: string + display_name: + description: "Optional version selector display name" + required: false + type: string + availability: + description: "Optional Fern availability status" + required: false + type: string + publish: + description: "Publish production docs after syncing" + required: false + default: false + type: boolean + allow_rollback: + description: "Allow an explicitly requested mutable-channel rollback" + required: false + default: false + type: boolean + secrets: + FERN_TOKEN: + required: false workflow_dispatch: inputs: operation: @@ -21,19 +64,38 @@ on: options: - dev - latest + - stable - version source_ref: description: "Source commit SHA, branch, or tag to snapshot when operation=sync" required: false type: string + release_version: + description: "Release version, e.g. 0.1.2 or 0.1.3.dev4" + required: false + type: string version_slug: description: "Version slug when channel=version, e.g. v0.0.36" required: false type: string display_name: - description: "Optional version selector display name" + description: "Optional selector name, e.g. Dev" + required: false + type: string + availability: + description: "Optional Fern status: beta, deprecated, ga, or stable" required: false type: string + publish: + description: "Publish production docs after syncing" + required: false + default: false + type: boolean + allow_rollback: + description: "Allow an explicitly requested mutable-channel rollback" + required: false + default: false + type: boolean permissions: contents: write @@ -41,6 +103,7 @@ permissions: concurrency: group: docs-website cancel-in-progress: false + queue: max defaults: run: @@ -65,6 +128,7 @@ jobs: OPERATION: ${{ inputs.operation }} CHANNEL: ${{ inputs.channel }} SOURCE_REF: ${{ inputs.source_ref }} + RELEASE_VERSION: ${{ inputs.release_version }} VERSION_SLUG: ${{ inputs.version_slug }} run: | set -euo pipefail @@ -72,8 +136,12 @@ jobs: echo "source_ref is required when operation=sync" >&2 exit 1 fi - if [[ "$CHANNEL" == "version" && -z "$VERSION_SLUG" ]]; then - echo "version_slug is required when channel=version" >&2 + if [[ "$CHANNEL" =~ ^(dev|latest|stable)$ && -z "$RELEASE_VERSION" ]]; then + echo "release_version is required for dev, latest, and stable channels" >&2 + exit 1 + fi + if [[ "$CHANNEL" =~ ^(stable|version)$ && -z "$VERSION_SLUG" ]]; then + echo "version_slug is required for stable and version channels" >&2 exit 1 fi @@ -96,6 +164,7 @@ jobs: uses: astral-sh/setup-uv@ae62891fec2bb8e7d6c99fc78c9fec3a63790f8d # v10.0.0 with: version: "0.10.12" + python-version: "3.13" - name: Update docs snapshot # Inputs flow in as quoted env vars to avoid shell injection; see the @@ -104,17 +173,32 @@ jobs: OPERATION: ${{ inputs.operation }} CHANNEL: ${{ inputs.channel }} SOURCE_REF: ${{ inputs.source_ref }} + RELEASE_VERSION: ${{ inputs.release_version }} VERSION_SLUG: ${{ inputs.version_slug }} DISPLAY_NAME: ${{ inputs.display_name }} + AVAILABILITY: ${{ inputs.availability }} + ALLOW_ROLLBACK: ${{ inputs.allow_rollback }} run: | + SOURCE_SHA="" + if [[ "$OPERATION" == "sync" ]]; then + SOURCE_SHA=$(git -C source rev-parse HEAD) + fi + rollback_args=() + if [[ "$ALLOW_ROLLBACK" == "true" ]]; then + rollback_args+=(--allow-rollback) + fi uv run automation/tasks/scripts/sync_docs_website.py \ --operation "$OPERATION" \ --source-root source \ --docs-website-root docs-website \ --channel "$CHANNEL" \ --source-ref "$SOURCE_REF" \ + --source-sha "$SOURCE_SHA" \ + --release-version "$RELEASE_VERSION" \ --version-slug "$VERSION_SLUG" \ - --display-name "$DISPLAY_NAME" + --display-name "$DISPLAY_NAME" \ + --availability "$AVAILABILITY" \ + "${rollback_args[@]}" - name: Setup Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 @@ -160,3 +244,10 @@ jobs: git commit -m "docs(website): remove ${target} docs" fi git push origin HEAD:docs-website + + - name: Publish Fern docs + if: ${{ inputs.publish }} + env: + FERN_TOKEN: ${{ secrets.FERN_TOKEN }} + working-directory: docs-website/fern + run: fern generate --docs diff --git a/AGENTS.md b/AGENTS.md index 533510737b..0b35bd02f7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -255,9 +255,9 @@ When behavior, commands, or development workflows change, review the related age - When making changes, update the relevant documentation in the `architecture/` directory. - When changes affect user-facing behavior, update the relevant published docs pages under `docs/` and navigation in `docs/index.yml`. - When changing gateway TOML fields, driver-specific config options, config defaults, or Helm rendering of `gateway.toml`, update `docs/reference/gateway-config.mdx` in the same branch. -- `fern/` contains the Fern site config, components, preview workflow inputs, and publish settings. +- `fern/` contains the Fern site config, components, preview workflow inputs, publish settings, and publishing documentation in `fern/README.md`. - Follow the docs style guide in [docs/CONTRIBUTING.mdx](docs/CONTRIBUTING.mdx): active voice, minimal formatting, no filler introductions, `shell` fences for copyable commands, and no duplicate body H1. -- Fern PR previews run through `.github/workflows/branch-docs.yml`, and production publish runs through the `publish-fern-docs` job in `.github/workflows/release-tag.yml` for stable release tags. +- Fern PR previews run through `.github/workflows/branch-docs.yml`. Release Dev publishes `dev`, and Release Tag publishes an immutable stable version plus `latest`. Both production paths call `.github/workflows/sync-docs.yml` once. - Use the `update-docs-from-commits` skill to scan recent commits and draft doc updates. ### Architecture Docs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e0b69f8b6f..12fb5c0f4c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -488,9 +488,9 @@ mise run docs PRs that touch `docs/**` or `fern/**` are validated by `.github/workflows/branch-docs.yml`, and they get a preview when `FERN_TOKEN` is available to the workflow. -Fern docs publishing is handled by the `publish-fern-docs` job in `.github/workflows/release-tag.yml` when a stable release tag is created. +Release Dev publishes the `dev` docs version from `main`. Release Tag publishes an immutable stable version and updates `latest`. See [fern/README.md](fern/README.md) for the source layout, version model, and publishing workflows. -`docs/` is the source-of-truth docs tree. `fern/` contains the site config, components, and theme assets that publish those pages. +`docs/` is the source-of-truth docs tree. `fern/` contains the site configuration, components, theme assets, and its README. See [docs/CONTRIBUTING.mdx](docs/CONTRIBUTING.mdx) for the current docs authoring guide. diff --git a/architecture/build.md b/architecture/build.md index 5f371f8f15..6d41db4198 100644 --- a/architecture/build.md +++ b/architecture/build.md @@ -487,13 +487,7 @@ settings, exceptions, and the contributor and maintainer workflows. ## Docs Site -Published docs live in `docs/`. Navigation lives in `docs/index.yml`. Fern site -configuration, components, theme assets, and publish settings live in `fern/`. - -Use `mise run docs` for strict validation and `mise run docs:serve` for local -preview. PR previews are produced by `.github/workflows/branch-docs.yml` when -Fern credentials are available. Production docs publish from the release tag -workflow. +Published docs live in `docs/`, and Fern site configuration lives in `fern/`. See [fern/README.md](../fern/README.md) for the source layout, local development commands, version model, and publishing workflows. ## Validation Expectations diff --git a/fern/README.md b/fern/README.md new file mode 100644 index 0000000000..b8e0ea3964 --- /dev/null +++ b/fern/README.md @@ -0,0 +1,67 @@ +# Fern documentation site + +OpenShell uses [Fern](https://buildwithfern.com/) to validate, preview, and publish the documentation at [docs.nvidia.com/openshell](https://docs.nvidia.com/openshell/). This directory contains the site configuration and presentation files. The documentation content lives in `docs/`. + +## Repository layout + +| Path | Purpose | +|---|---| +| `docs/` | MDX pages, navigation in `docs/index.yml`, and page-specific components. | +| `fern/docs.yml` | Site, theme, version, redirect, and navigation configuration. | +| `fern/fern.config.json` | Fern organization and pinned CLI version. | +| `fern/components/` | Shared site components. | +| `fern/assets/` | Logos and other shared assets. | +| `fern/main.css` | Site-wide styles. | + +In a normal source checkout, `fern/docs.yml` points the `latest` version at `docs/index.yml`. Release automation builds the multi-version configuration on the generated `docs-website` branch. + +## Local development + +Start a local Fern server from the repository root: + +```shell +mise run docs:serve +``` + +Validate the configuration, navigation, and links without starting a server: + +```shell +mise run docs +``` + +The tasks read the Fern CLI version from `fern/fern.config.json`, so local checks and GitHub Actions use the same version. See [docs/CONTRIBUTING.mdx](../docs/CONTRIBUTING.mdx) for the authoring and style guide. + +## Pull request previews + +`.github/workflows/branch-docs.yml` validates pull requests that change documentation or Fern configuration. When the workflow can access `FERN_TOKEN`, it publishes a Fern preview from the pull request checkout and adds the preview URL to the pull request. This path does not use or update the `docs-website` branch. + +## Versioned production site + +The generated `docs-website` branch contains the complete production input for Fern. Each version has an exact copy of its source commit's `docs/` tree under `fern/pages-/` and a navigation file under `fern/versions/`. `fern/.docs-snapshots.yml` records the original source ref, resolved source commit, and release version for each managed snapshot. + +The automated site uses these version types: + +| Version | Source | Update policy | Fern status | +|---|---|---|---| +| `latest` | The newest stable release. | Mutable. A maintenance release older than the current stable release cannot move it backward unless a maintainer explicitly allows a rollback. | No status before v0.1.0. | +| `dev` | The most recent successful Release Dev run from `main`. | Mutable. Automation rejects an older version or the same version from a different commit unless a maintainer explicitly allows a rollback. | Beta. | + +Release Dev waits for the development artifacts and Helm chart, then calls `.github/workflows/sync-docs.yml` once. The reusable workflow updates `dev`, validates the generated site, commits and pushes the branch when needed, and publishes the production site once. + +Release Tag follows the same sequence for a non-prerelease tag after the release artifacts, SDK package, Helm chart, and wheel publication complete. It updates `latest` when the release is not older than the current version, then publishes the production site once. + +The sync and publish workflows share the `docs-website` concurrency group. This serializes writes and publication. Queued runs remain pending instead of replacing one another. + +The `dev` snapshot also owns the shared Fern configuration, components, assets, and CSS on `docs-website`. The `latest` snapshot copies its documentation and navigation but does not replace those shared files. This keeps the site configuration aligned with `main` while preserving the released content. + +## Manual maintenance and publishing + +Maintainers can run `.github/workflows/sync-docs.yml` manually to add, refresh, or remove a historical version snapshot. The workflow preserves snapshots that were not selected. Production publishing is disabled by default for a manual sync. + +`.github/workflows/publish-docs-website.yml` validates and publishes the existing `docs-website` branch without syncing content. Its default mode creates a preview. Selecting production mode publishes the live site, so use it only for an intentional production republish. + +Run the automated sync tests after changing the version model or either publishing workflow: + +```shell +mise run test:docs-website +``` diff --git a/fern/fern.config.json b/fern/fern.config.json index 9ec6917e2e..635e3615c9 100644 --- a/fern/fern.config.json +++ b/fern/fern.config.json @@ -1,4 +1,4 @@ { "organization": "nvidia", - "version": "5.40.0" + "version": "5.112.0" } diff --git a/tasks/scripts/sync_docs_website.py b/tasks/scripts/sync_docs_website.py index 0e04e8528e..62000394d3 100644 --- a/tasks/scripts/sync_docs_website.py +++ b/tasks/scripts/sync_docs_website.py @@ -1,28 +1,32 @@ #!/usr/bin/env python3 +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + # /// script # requires-python = ">=3.9" # dependencies = [ +# "packaging==25.0", # "PyYAML==6.0.2", # ] # /// -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - from __future__ import annotations import argparse import re import shutil import sys -import tempfile from dataclasses import dataclass from pathlib import Path from typing import cast import yaml +from packaging.version import InvalidVersion, Version SLUG_RE = re.compile(r"^[A-Za-z0-9._-]+$") +DISPLAY_VERSION_RE = re.compile(r"\bv?(\d+\.\d+\.\d+(?:[.-]?[A-Za-z0-9]+)*)\b") +VERSION_AVAILABILITIES = {"beta", "deprecated", "ga", "stable"} +SNAPSHOT_METADATA_FILE = ".docs-snapshots.yml" YamlMapping = dict[str, object] @@ -31,21 +35,26 @@ class VersionEntry: slug: str display_name: str path: str + availability: str | None = None def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( - description="Sync or remove one docs snapshot in the docs-website branch." + description="Sync or remove docs snapshots in the docs-website branch." ) parser.add_argument("--operation", choices=["sync", "remove"], default="sync") parser.add_argument("--source-root", type=Path) parser.add_argument("--docs-website-root", required=True, type=Path) parser.add_argument( - "--channel", required=True, choices=["dev", "latest", "version"] + "--channel", required=True, choices=["dev", "latest", "stable", "version"] ) parser.add_argument("--source-ref", default="") + parser.add_argument("--source-sha", default="") + parser.add_argument("--release-version", default="") parser.add_argument("--version-slug", default="") parser.add_argument("--display-name", default="") + parser.add_argument("--availability", default="") + parser.add_argument("--allow-rollback", action="store_true") return parser.parse_args() @@ -59,7 +68,9 @@ def resolve_slug(channel: str, version_slug: str) -> str: if channel == "latest": return "latest" if not version_slug: - raise ValueError("--version-slug is required when --channel=version") + raise ValueError( + "--version-slug is required when --channel=stable or --channel=version" + ) if not SLUG_RE.fullmatch(version_slug): raise ValueError( f"version slug contains unsupported characters: {version_slug}" @@ -79,24 +90,41 @@ def resolve_display_name( return slug +def resolve_availability(channel: str, override: str) -> str | None: + availability = override or ("beta" if channel == "dev" else "") + if not availability: + return None + if availability not in VERSION_AVAILABILITIES: + supported = ", ".join(sorted(VERSION_AVAILABILITIES)) + raise ValueError( + f"unsupported version availability {availability!r}; expected one of: {supported}" + ) + return availability + + +def parse_release_version(value: str) -> Version: + try: + return Version(value.removeprefix("v")) + except InvalidVersion as exc: + raise ValueError(f"invalid release version: {value}") from exc + + +def default_stable_availability(release_version: str) -> str | None: + if parse_release_version(release_version) >= Version("0.1.0"): + return "stable" + return None + + def ensure_existing(path: Path, label: str) -> None: if not path.exists(): raise FileNotFoundError(f"{label} does not exist: {path}") -def reset_directory(src: Path, dst: Path, *, preserve_components: bool) -> None: +def reset_directory(src: Path, dst: Path) -> None: ensure_existing(src, "source directory") - preserved_components: Path | None = None - if preserve_components and (dst / "_components").is_dir(): - preserved_components = Path(tempfile.mkdtemp()) / "_components" - shutil.copytree(dst / "_components", preserved_components) if dst.exists(): shutil.rmtree(dst) shutil.copytree(src, dst) - if preserved_components is not None: - if (dst / "_components").exists(): - shutil.rmtree(dst / "_components") - shutil.copytree(preserved_components, dst / "_components") def merge_directory(src: Path, dst: Path, *, overwrite: bool) -> None: @@ -138,6 +166,110 @@ def write_yaml(path: Path, data: YamlMapping) -> None: ) +def read_snapshot_metadata(path: Path) -> dict[str, dict[str, str]]: + if not path.exists(): + return {} + data = read_yaml(path) + raw_snapshots = data.get("snapshots") + if raw_snapshots is None: + return {} + if not isinstance(raw_snapshots, dict): + raise ValueError(f"expected snapshots mapping in {path}") + + snapshots: dict[str, dict[str, str]] = {} + for raw_slug, raw_snapshot in raw_snapshots.items(): + if not isinstance(raw_slug, str) or not isinstance(raw_snapshot, dict): + raise ValueError(f"invalid snapshot metadata in {path}") + snapshot = cast("YamlMapping", raw_snapshot) + source_ref = snapshot.get("source-ref") + source_sha = snapshot.get("source-sha", "") + version = snapshot.get("version") + if ( + not isinstance(source_ref, str) + or not isinstance(source_sha, str) + or not isinstance(version, str) + ): + raise ValueError(f"invalid snapshot metadata for {raw_slug} in {path}") + snapshots[raw_slug] = { + "source-ref": source_ref, + "source-sha": source_sha, + "version": version, + } + return snapshots + + +def write_snapshot_metadata(path: Path, snapshots: dict[str, dict[str, str]]) -> None: + write_yaml(path, {"snapshots": snapshots}) + + +def seed_mutable_snapshot_metadata( + snapshots: dict[str, dict[str, str]], docs_yml: Path, slug: str +) -> None: + if slug in snapshots: + return + data = read_yaml(docs_yml) + for entry in parse_versions(data.get("versions")): + if entry.slug != slug: + continue + match = DISPLAY_VERSION_RE.search(entry.display_name) + if match is not None: + snapshots[slug] = { + "source-ref": "", + "source-sha": "", + "version": str(parse_release_version(match.group(1))), + } + return + + +def ensure_immutable_snapshot( + snapshots: dict[str, dict[str, str]], + target_fern: Path, + slug: str, + source_sha: str, +) -> None: + existing = snapshots.get(slug) + if existing is not None: + if existing["source-sha"] != source_sha: + raise ValueError( + f"immutable snapshot {slug} already points to " + f"{existing['source-sha']}, not {source_sha}" + ) + return + if (target_fern / f"pages-{slug}").exists(): + raise ValueError( + f"immutable snapshot {slug} already exists without source metadata" + ) + + +def ensure_monotonic_snapshot( + snapshots: dict[str, dict[str, str]], + slug: str, + source_sha: str, + release_version: str, + *, + allow_rollback: bool, +) -> bool: + existing = snapshots.get(slug) + if existing is None: + return True + + incoming_version = parse_release_version(release_version) + existing_version = parse_release_version(existing["version"]) + if incoming_version < existing_version and not allow_rollback: + return False + if ( + incoming_version == existing_version + and bool(existing["source-sha"]) + and existing["source-sha"] != source_sha + and not allow_rollback + ): + raise ValueError( + f"snapshot {slug} version {release_version} already points to " + f"{existing['source-sha']}, not {source_sha}" + ) + return True + + def prefix_path(value: object, pages_dir: str) -> object: if not isinstance(value, str): return value @@ -179,13 +311,21 @@ def parse_versions(raw_versions: object) -> list[VersionEntry]: slug = entry.get("slug") display_name = entry.get("display-name") path = entry.get("path") + availability = entry.get("availability") if ( isinstance(slug, str) and isinstance(display_name, str) and isinstance(path, str) ): entries.append( - VersionEntry(slug=slug, display_name=display_name, path=path) + VersionEntry( + slug=slug, + display_name=display_name, + path=path, + availability=availability + if isinstance(availability, str) + else None, + ) ) return entries @@ -210,14 +350,17 @@ def ordered_entries( def render_versions(entries: list[VersionEntry]) -> list[dict[str, str]]: - return [ - { + rendered: list[dict[str, str]] = [] + for entry in entries: + item = { "display-name": entry.display_name, "path": entry.path, "slug": entry.slug, } - for entry in entries - ] + if entry.availability is not None: + item["availability"] = entry.availability + rendered.append(item) + return rendered def component_dirs(fern_dir: Path) -> list[str]: @@ -246,6 +389,35 @@ def update_docs_yml(docs_yml: Path, updated: VersionEntry, fern_dir: Path) -> No write_yaml(docs_yml, data) +def write_snapshot( + source_docs: Path, + source_fern: Path, + target_fern: Path, + entry: VersionEntry, + *, + refresh_shared: bool, +) -> None: + pages_dir = f"pages-{entry.slug}" + reset_directory(source_docs, target_fern / pages_dir) + if refresh_shared: + merge_directory(source_fern / "assets", target_fern / "assets", overwrite=True) + merge_directory( + source_fern / "components", target_fern / "components", overwrite=True + ) + copy_if_exists(source_fern / "main.css", target_fern / "main.css") + copy_if_exists( + source_fern / "fern.config.json", target_fern / "fern.config.json" + ) + + versions_dir = target_fern / "versions" + versions_dir.mkdir(parents=True, exist_ok=True) + write_yaml( + versions_dir / f"{entry.slug}.yml", + version_navigation(source_docs / "index.yml", pages_dir), + ) + update_docs_yml(target_fern / "docs.yml", entry, target_fern) + + def remove_docs_yml_entry(docs_yml: Path, slug: str, fern_dir: Path) -> None: data = read_yaml(docs_yml) entries = [ @@ -275,50 +447,118 @@ def sync_docs(args: argparse.Namespace) -> None: source_ref = clean_input(args.source_ref) if not source_ref: raise ValueError("--source-ref is required when --operation=sync") + source_sha = clean_input(getattr(args, "source_sha", "")) + if not source_sha: + raise ValueError("--source-sha is required when --operation=sync") + release_version = clean_input(getattr(args, "release_version", "")) version_slug = clean_input(args.version_slug) display_override = clean_input(args.display_name) + availability_override = clean_input(args.availability) + if channel in {"dev", "latest", "stable"} and not release_version: + raise ValueError( + "--release-version is required for dev, latest, and stable channels" + ) slug = resolve_slug(channel, version_slug) display_name = resolve_display_name(channel, slug, source_ref, display_override) - pages_dir = f"pages-{slug}" - refresh_shared = channel in {"dev", "latest"} - - reset_directory( - source_docs, - target_fern / pages_dir, - preserve_components=not refresh_shared, - ) - merge_directory( - source_fern / "assets", target_fern / "assets", overwrite=refresh_shared - ) - merge_directory( - source_fern / "components", target_fern / "components", overwrite=refresh_shared - ) - if refresh_shared: - copy_if_exists(source_fern / "main.css", target_fern / "main.css") - copy_if_exists( - source_fern / "fern.config.json", target_fern / "fern.config.json" + availability = resolve_availability(channel, availability_override) + metadata_path = target_fern / SNAPSHOT_METADATA_FILE + snapshots = read_snapshot_metadata(metadata_path) + docs_yml = target_fern / "docs.yml" + + if channel == "stable": + parsed_version = parse_release_version(release_version) + expected_slug = f"v{parsed_version}" + if slug != expected_slug: + raise ValueError(f"stable version slug must be {expected_slug}, got {slug}") + ensure_immutable_snapshot(snapshots, target_fern, slug, source_sha) + stable_availability = availability or default_stable_availability( + release_version ) + write_snapshot( + source_docs, + source_fern, + target_fern, + VersionEntry( + slug=slug, + display_name=slug, + path=f"./versions/{slug}.yml", + availability=stable_availability, + ), + refresh_shared=False, + ) + snapshots[slug] = { + "source-ref": source_ref, + "source-sha": source_sha, + "version": str(parsed_version), + } - versions_dir = target_fern / "versions" - versions_dir.mkdir(parents=True, exist_ok=True) - write_yaml( - versions_dir / f"{slug}.yml", - version_navigation(source_docs / "index.yml", pages_dir), - ) + seed_mutable_snapshot_metadata(snapshots, docs_yml, "latest") + if ensure_monotonic_snapshot( + snapshots, + "latest", + source_sha, + release_version, + allow_rollback=bool(getattr(args, "allow_rollback", False)), + ): + write_snapshot( + source_docs, + source_fern, + target_fern, + VersionEntry( + slug="latest", + display_name=display_override or f"Latest ({slug})", + path="./versions/latest.yml", + availability=stable_availability, + ), + refresh_shared=False, + ) + snapshots["latest"] = { + "source-ref": source_ref, + "source-sha": source_sha, + "version": str(parsed_version), + } + write_snapshot_metadata(metadata_path, snapshots) + print(f"Synced immutable {slug} docs from {source_ref}") + return + + if channel in {"dev", "latest"}: + seed_mutable_snapshot_metadata(snapshots, docs_yml, slug) + if not ensure_monotonic_snapshot( + snapshots, + slug, + source_sha, + release_version, + allow_rollback=bool(getattr(args, "allow_rollback", False)), + ): + print( + f"Skipped stale {slug} docs {release_version}; " + f"current version is {snapshots[slug]['version']}" + ) + return + else: + ensure_immutable_snapshot(snapshots, target_fern, slug, source_sha) + release_version = release_version or slug.removeprefix("v") - update_docs_yml( - target_fern / "docs.yml", + write_snapshot( + source_docs, + source_fern, + target_fern, VersionEntry( slug=slug, display_name=display_name, path=f"./versions/{slug}.yml", + availability=availability, ), - target_fern, + refresh_shared=channel == "dev", ) + snapshots[slug] = { + "source-ref": source_ref, + "source-sha": source_sha, + "version": release_version, + } + write_snapshot_metadata(metadata_path, snapshots) - print( - f"Synced {channel} docs from {source_ref} to fern/{pages_dir} ({display_name})" - ) + print(f"Synced {channel} docs from {source_ref} to fern/pages-{slug}") def remove_docs(args: argparse.Namespace) -> None: @@ -340,6 +580,11 @@ def remove_docs(args: argparse.Namespace) -> None: version_file.unlink() remove_docs_yml_entry(target_fern / "docs.yml", slug, target_fern) + metadata_path = target_fern / SNAPSHOT_METADATA_FILE + snapshots = read_snapshot_metadata(metadata_path) + if slug in snapshots: + del snapshots[slug] + write_snapshot_metadata(metadata_path, snapshots) print(f"Removed {slug} docs from docs website branch") diff --git a/tasks/scripts/sync_docs_website_test.py b/tasks/scripts/sync_docs_website_test.py index 722f3f48f6..076181ee39 100644 --- a/tasks/scripts/sync_docs_website_test.py +++ b/tasks/scripts/sync_docs_website_test.py @@ -11,23 +11,106 @@ from __future__ import annotations from argparse import Namespace -from typing import TYPE_CHECKING, cast +from pathlib import Path +from typing import cast import pytest import sync_docs_website as sdw import yaml -if TYPE_CHECKING: - from pathlib import Path - def read_yaml(path: Path) -> dict: return yaml.safe_load(path.read_text(encoding="utf-8")) +def read_workflow(name: str) -> dict: + path = Path(__file__).resolve().parents[2] / ".github" / "workflows" / name + return yaml.load(path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) + + +def test_release_workflows_sync_and_publish_docs_once() -> None: + dev = read_workflow("release-dev.yml") + tag = read_workflow("release-tag.yml") + dev_job = dev["jobs"]["publish-fern-docs"] + tag_job = tag["jobs"]["publish-fern-docs"] + + assert dev_job["needs"] == [ + "compute-versions", + "release-dev", + "release-helm", + "trigger-wheel-publish", + ] + assert dev_job["uses"] == "./.github/workflows/sync-docs.yml" + assert dev_job["with"]["channel"] == "dev" + assert ( + dev_job["with"]["release_version"] + == "${{ needs.compute-versions.outputs.docs_version }}" + ) + assert dev_job["with"]["publish"] == "true" + assert dev_job["with"]["display_name"] == "Dev" + assert dev_job["with"]["availability"] == "beta" + + assert tag_job["needs"] == [ + "compute-versions", + "release", + "publish-sdk-typescript", + "release-helm", + "trigger-wheel-publish", + ] + assert tag_job["uses"] == "./.github/workflows/sync-docs.yml" + assert tag_job["with"]["channel"] == "latest" + assert ( + tag_job["with"]["release_version"] + == "${{ needs.compute-versions.outputs.semver }}" + ) + assert "version_slug" not in tag_job["with"] + assert ( + tag_job["with"]["display_name"] + == "Latest (v${{ needs.compute-versions.outputs.semver }})" + ) + assert tag_job["with"]["publish"] == "true" + assert "is_prerelease != 'true'" in tag_job["if"] + + for workflow_name in ("release-dev.yml", "release-tag.yml"): + workflow_path = ( + Path(__file__).resolve().parents[2] + / ".github" + / "workflows" + / workflow_name + ) + workflow_text = workflow_path.read_text(encoding="utf-8") + assert workflow_text.count("uses: ./.github/workflows/sync-docs.yml") == 1 + assert "fern generate --docs" not in workflow_text + + +def test_sync_workflow_serializes_sync_and_publish() -> None: + workflow = read_workflow("sync-docs.yml") + triggers = workflow["on"] + publish_input = triggers["workflow_call"]["inputs"]["publish"] + assert publish_input["type"] == "boolean" + assert publish_input["default"] == "false" + assert workflow["concurrency"]["group"] == "docs-website" + assert workflow["concurrency"]["queue"] == "max" + publish_workflow = read_workflow("publish-docs-website.yml") + assert publish_workflow["concurrency"]["queue"] == "max" + + steps = workflow["jobs"]["sync"]["steps"] + step_names = [step["name"] for step in steps] + assert step_names.index("Commit docs website changes") < step_names.index( + "Publish Fern docs" + ) + publish_step = next(step for step in steps if step["name"] == "Publish Fern docs") + assert publish_step["if"] == "${{ inputs.publish }}" + assert publish_step["working-directory"] == "docs-website/fern" + update_step = next(step for step in steps if step["name"] == "Update docs snapshot") + assert "git -C source rev-parse HEAD" in update_step["run"] + assert '--source-sha "$SOURCE_SHA"' in update_step["run"] + + def test_resolve_slug_channels() -> None: assert sdw.resolve_slug("dev", "") == "dev" assert sdw.resolve_slug("latest", "") == "latest" + assert sdw.resolve_slug("stable", "v0.1.0") == "v0.1.0" assert sdw.resolve_slug("version", "v0.0.36") == "v0.0.36" @@ -55,6 +138,38 @@ def test_resolve_display_name() -> None: assert sdw.resolve_display_name("dev", "dev", "main", "Custom") == "Custom" +def test_resolve_availability() -> None: + assert sdw.resolve_availability("dev", "") == "beta" + assert sdw.resolve_availability("latest", "") is None + assert sdw.resolve_availability("version", "") is None + assert sdw.resolve_availability("version", "deprecated") == "deprecated" + with pytest.raises(ValueError): + sdw.resolve_availability("dev", "alpha") + + +def test_parse_and_render_versions_preserves_availability() -> None: + raw_versions = [ + { + "display-name": "v0.0.36", + "path": "./versions/v0.0.36.yml", + "slug": "v0.0.36", + "availability": "deprecated", + } + ] + + entries = sdw.parse_versions(raw_versions) + + assert entries == [ + sdw.VersionEntry( + "v0.0.36", + "v0.0.36", + "./versions/v0.0.36.yml", + "deprecated", + ) + ] + assert sdw.render_versions(entries) == raw_versions + + def test_ordered_entries_pins_latest_then_dev() -> None: existing = [ sdw.VersionEntry("v0.0.36", "v0.0.36", "./versions/v0.0.36.yml"), @@ -113,12 +228,26 @@ def _make_docs_website_tree(root: Path) -> None: (fern / "docs.yml").write_text(yaml.safe_dump({"versions": []}), encoding="utf-8") -def test_sync_docs_creates_snapshot(tmp_path: Path) -> None: +def test_sync_docs_creates_planned_latest_and_dev_selector(tmp_path: Path) -> None: source = tmp_path / "source" website = tmp_path / "docs-website" _make_source_tree(source) _make_docs_website_tree(website) + sdw.sync_docs( + Namespace( + operation="sync", + source_root=source, + docs_website_root=website, + channel="latest", + source_ref="release-sha", + source_sha="release-sha", + release_version="0.0.116", + version_slug="", + display_name="Latest (v0.0.116)", + availability="", + ) + ) sdw.sync_docs( Namespace( operation="sync", @@ -126,8 +255,11 @@ def test_sync_docs_creates_snapshot(tmp_path: Path) -> None: docs_website_root=website, channel="dev", source_ref="main", + source_sha="dev-sha", + release_version="0.0.117.dev56", version_slug="", - display_name="", + display_name="Dev", + availability="beta", ) ) @@ -139,12 +271,364 @@ def test_sync_docs_creates_snapshot(tmp_path: Path) -> None: assert version_nav["navigation"][0]["path"] == "../pages-dev/intro.mdx" docs_yml = read_yaml(fern / "docs.yml") - slugs = [entry["slug"] for entry in docs_yml["versions"]] - assert slugs == ["dev"] - assert docs_yml["versions"][0]["path"] == "./versions/dev.yml" + assert docs_yml["versions"] == [ + { + "display-name": "Latest (v0.0.116)", + "path": "./versions/latest.yml", + "slug": "latest", + }, + { + "display-name": "Dev", + "path": "./versions/dev.yml", + "slug": "dev", + "availability": "beta", + }, + ] assert "./components" in docs_yml["experimental"]["mdx-components"] +def test_sync_docs_preserves_other_version_availability(tmp_path: Path) -> None: + source = tmp_path / "source" + website = tmp_path / "docs-website" + _make_source_tree(source) + _make_docs_website_tree(website) + docs_yml_path = website / "fern" / "docs.yml" + docs_yml_path.write_text( + yaml.safe_dump( + { + "versions": [ + { + "display-name": "v0.0.36", + "path": "./versions/v0.0.36.yml", + "slug": "v0.0.36", + "availability": "deprecated", + } + ] + } + ), + encoding="utf-8", + ) + + sdw.sync_docs( + Namespace( + operation="sync", + source_root=source, + docs_website_root=website, + channel="dev", + source_ref="main", + source_sha="dev-sha", + release_version="0.0.117.dev56", + version_slug="", + display_name="Dev (v0.0.117.dev56)", + availability="beta", + ) + ) + + versions = read_yaml(docs_yml_path)["versions"] + assert versions == [ + { + "display-name": "Dev (v0.0.117.dev56)", + "path": "./versions/dev.yml", + "slug": "dev", + "availability": "beta", + }, + { + "display-name": "v0.0.36", + "path": "./versions/v0.0.36.yml", + "slug": "v0.0.36", + "availability": "deprecated", + }, + ] + + +def test_stable_sync_creates_immutable_version_and_promotes_latest( + tmp_path: Path, +) -> None: + source = tmp_path / "source" + website = tmp_path / "docs-website" + _make_source_tree(source) + _make_docs_website_tree(website) + + sdw.sync_docs( + Namespace( + source_root=source, + docs_website_root=website, + channel="stable", + source_ref="v0.2.0", + source_sha="new-sha", + release_version="0.2.0", + version_slug="v0.2.0", + display_name="", + availability="", + allow_rollback=False, + ) + ) + + fern = website / "fern" + assert (fern / "pages-v0.2.0" / "intro.mdx").is_file() + assert (fern / "pages-latest" / "intro.mdx").is_file() + versions = read_yaml(fern / "docs.yml")["versions"] + assert [entry["slug"] for entry in versions] == ["latest", "v0.2.0"] + assert versions[0]["display-name"] == "Latest (v0.2.0)" + assert versions[0]["availability"] == "stable" + assert versions[1]["availability"] == "stable" + snapshots = read_yaml(fern / sdw.SNAPSHOT_METADATA_FILE)["snapshots"] + assert snapshots["latest"] == { + "source-ref": "v0.2.0", + "source-sha": "new-sha", + "version": "0.2.0", + } + assert snapshots["v0.2.0"] == { + "source-ref": "v0.2.0", + "source-sha": "new-sha", + "version": "0.2.0", + } + + +def test_n_minus_one_sync_does_not_move_latest_backwards(tmp_path: Path) -> None: + current = tmp_path / "current" + maintenance = tmp_path / "maintenance" + website = tmp_path / "docs-website" + _make_source_tree(current) + _make_source_tree(maintenance) + (current / "docs" / "intro.mdx").write_text("# Current\n", encoding="utf-8") + (maintenance / "docs" / "intro.mdx").write_text("# Maintenance\n", encoding="utf-8") + _make_docs_website_tree(website) + + for source, source_sha, version in ( + (current, "current-sha", "0.3.1"), + (maintenance, "maintenance-sha", "0.2.7"), + ): + sdw.sync_docs( + Namespace( + source_root=source, + docs_website_root=website, + channel="stable", + source_ref=f"v{version}", + source_sha=source_sha, + release_version=version, + version_slug=f"v{version}", + display_name="", + availability="", + allow_rollback=False, + ) + ) + + fern = website / "fern" + assert (fern / "pages-latest" / "intro.mdx").read_text( + encoding="utf-8" + ) == "# Current\n" + assert (fern / "pages-v0.2.7" / "intro.mdx").read_text( + encoding="utf-8" + ) == "# Maintenance\n" + snapshots = read_yaml(fern / sdw.SNAPSHOT_METADATA_FILE)["snapshots"] + assert snapshots["latest"] == { + "source-ref": "v0.3.1", + "source-sha": "current-sha", + "version": "0.3.1", + } + + +def test_stable_sync_preserves_newer_legacy_latest_without_metadata( + tmp_path: Path, +) -> None: + source = tmp_path / "source" + website = tmp_path / "docs-website" + _make_source_tree(source) + _make_docs_website_tree(website) + fern = website / "fern" + (fern / "pages-latest").mkdir() + (fern / "pages-latest" / "intro.mdx").write_text( + "# Existing latest\n", encoding="utf-8" + ) + (fern / "docs.yml").write_text( + yaml.safe_dump( + { + "versions": [ + { + "display-name": "Latest (v0.3.1)", + "path": "./versions/latest.yml", + "slug": "latest", + } + ] + } + ), + encoding="utf-8", + ) + + sdw.sync_docs( + Namespace( + source_root=source, + docs_website_root=website, + channel="stable", + source_ref="v0.2.7", + source_sha="maintenance-sha", + release_version="0.2.7", + version_slug="v0.2.7", + display_name="", + availability="", + allow_rollback=False, + ) + ) + + assert (fern / "pages-latest" / "intro.mdx").read_text( + encoding="utf-8" + ) == "# Existing latest\n" + snapshots = read_yaml(fern / sdw.SNAPSHOT_METADATA_FILE)["snapshots"] + assert snapshots["latest"] == { + "source-ref": "", + "source-sha": "", + "version": "0.3.1", + } + + +def test_dev_sync_rejects_stale_or_conflicting_updates(tmp_path: Path) -> None: + current = tmp_path / "current" + stale = tmp_path / "stale" + website = tmp_path / "docs-website" + _make_source_tree(current) + _make_source_tree(stale) + (current / "docs" / "intro.mdx").write_text("# Current\n", encoding="utf-8") + (stale / "docs" / "intro.mdx").write_text("# Stale\n", encoding="utf-8") + _make_docs_website_tree(website) + + def sync(source: Path, source_sha: str, version: str) -> None: + sdw.sync_docs( + Namespace( + source_root=source, + docs_website_root=website, + channel="dev", + source_ref="main", + source_sha=source_sha, + release_version=version, + version_slug="", + display_name=f"Dev (v{version})", + availability="beta", + allow_rollback=False, + ) + ) + + sync(current, "current-sha", "0.3.2.dev10") + sync(stale, "stale-sha", "0.3.2.dev9") + intro = website / "fern" / "pages-dev" / "intro.mdx" + assert intro.read_text(encoding="utf-8") == "# Current\n" + + with pytest.raises(ValueError, match="already points to current-sha"): + sync(stale, "other-sha", "0.3.2.dev10") + + +def test_dev_sync_allows_explicit_rollback(tmp_path: Path) -> None: + current = tmp_path / "current" + stale = tmp_path / "stale" + website = tmp_path / "docs-website" + _make_source_tree(current) + _make_source_tree(stale) + (current / "docs" / "intro.mdx").write_text("# Current\n", encoding="utf-8") + (stale / "docs" / "intro.mdx").write_text("# Rolled back\n", encoding="utf-8") + _make_docs_website_tree(website) + + def sync(source: Path, source_sha: str, version: str, allow_rollback: bool) -> None: + sdw.sync_docs( + Namespace( + source_root=source, + docs_website_root=website, + channel="dev", + source_ref="main", + source_sha=source_sha, + release_version=version, + version_slug="", + display_name=f"Dev (v{version})", + availability="beta", + allow_rollback=allow_rollback, + ) + ) + + sync(current, "current-sha", "0.3.2.dev10", False) + sync(stale, "rollback-sha", "0.3.2.dev9", True) + + fern = website / "fern" + assert (fern / "pages-dev" / "intro.mdx").read_text( + encoding="utf-8" + ) == "# Rolled back\n" + snapshots = read_yaml(fern / sdw.SNAPSHOT_METADATA_FILE)["snapshots"] + assert snapshots["dev"] == { + "source-ref": "main", + "source-sha": "rollback-sha", + "version": "0.3.2.dev9", + } + + +def test_immutable_snapshot_cannot_change_source(tmp_path: Path) -> None: + source = tmp_path / "source" + website = tmp_path / "docs-website" + _make_source_tree(source) + _make_docs_website_tree(website) + args = Namespace( + source_root=source, + docs_website_root=website, + channel="stable", + source_ref="main", + source_sha="release-sha", + release_version="0.2.0", + version_slug="v0.2.0", + display_name="", + availability="", + allow_rollback=False, + ) + sdw.sync_docs(args) + + args.source_sha = "different-sha" + with pytest.raises(ValueError, match=r"immutable snapshot v0\.2\.0"): + sdw.sync_docs(args) + + +def test_only_dev_refreshes_shared_fern_files(tmp_path: Path) -> None: + dev = tmp_path / "dev" + release = tmp_path / "release" + website = tmp_path / "docs-website" + _make_source_tree(dev) + _make_source_tree(release) + (dev / "fern" / "components" / "Card.tsx").write_text( + "export const Card = 'dev';\n", encoding="utf-8" + ) + (release / "fern" / "components" / "Card.tsx").write_text( + "export const Card = 'release';\n", encoding="utf-8" + ) + _make_docs_website_tree(website) + + sdw.sync_docs( + Namespace( + source_root=dev, + docs_website_root=website, + channel="dev", + source_ref="main", + source_sha="dev-sha", + release_version="0.2.1.dev1", + version_slug="", + display_name="Dev (v0.2.1.dev1)", + availability="beta", + allow_rollback=False, + ) + ) + sdw.sync_docs( + Namespace( + source_root=release, + docs_website_root=website, + channel="stable", + source_ref="v0.2.0", + source_sha="release-sha", + release_version="0.2.0", + version_slug="v0.2.0", + display_name="", + availability="", + allow_rollback=False, + ) + ) + + card = website / "fern" / "components" / "Card.tsx" + assert card.read_text(encoding="utf-8") == "export const Card = 'dev';\n" + + def test_remove_docs_drops_snapshot(tmp_path: Path) -> None: source = tmp_path / "source" website = tmp_path / "docs-website" @@ -157,8 +641,10 @@ def test_remove_docs_drops_snapshot(tmp_path: Path) -> None: docs_website_root=website, channel="version", source_ref="v0.0.36", + source_sha="release-sha", version_slug="v0.0.36", display_name="", + availability="deprecated", ) sdw.sync_docs(base) @@ -175,6 +661,7 @@ def test_remove_docs_drops_snapshot(tmp_path: Path) -> None: source_ref="", version_slug="v0.0.36", display_name="", + availability="", ) ) @@ -182,3 +669,74 @@ def test_remove_docs_drops_snapshot(tmp_path: Path) -> None: assert not (fern / "versions" / "v0.0.36.yml").exists() docs_yml = read_yaml(fern / "docs.yml") assert [entry["slug"] for entry in docs_yml["versions"]] == [] + + +@pytest.mark.parametrize("channel", ["stable", "version"]) +def test_immutable_snapshot_uses_resolved_commit_identity( + tmp_path: Path, channel: str +) -> None: + source = tmp_path / "source" + website = tmp_path / "docs-website" + _make_source_tree(source) + _make_docs_website_tree(website) + args = Namespace( + source_root=source, + docs_website_root=website, + channel=channel, + source_ref="main", + source_sha="first-sha", + release_version="0.2.0" if channel == "stable" else "", + version_slug="v0.2.0", + display_name="", + availability="", + allow_rollback=False, + ) + sdw.sync_docs(args) + + (source / "docs" / "intro.mdx").write_text("# Changed\n", encoding="utf-8") + args.source_sha = "second-sha" + + with pytest.raises(ValueError, match=r"immutable snapshot v0\.2\.0"): + sdw.sync_docs(args) + assert (website / "fern" / "pages-v0.2.0" / "intro.mdx").read_text( + encoding="utf-8" + ) == "# Intro\n" + + +def test_stable_promotion_replaces_latest_page_components(tmp_path: Path) -> None: + old = tmp_path / "old" + new = tmp_path / "new" + website = tmp_path / "docs-website" + _make_source_tree(old) + _make_source_tree(new) + (old / "docs" / "_components").mkdir() + (old / "docs" / "_components" / "Widget.tsx").write_text( + "export const Widget = 'old';\n", encoding="utf-8" + ) + (new / "docs" / "_components").mkdir() + (new / "docs" / "_components" / "Widget.tsx").write_text( + "export const Widget = 'new';\n", encoding="utf-8" + ) + _make_docs_website_tree(website) + + for source, source_sha, version in ( + (old, "old-sha", "1.0.0"), + (new, "new-sha", "1.1.0"), + ): + sdw.sync_docs( + Namespace( + source_root=source, + docs_website_root=website, + channel="stable", + source_ref=f"v{version}", + source_sha=source_sha, + release_version=version, + version_slug=f"v{version}", + display_name="", + availability="", + allow_rollback=False, + ) + ) + + widget = website / "fern" / "pages-latest" / "_components" / "Widget.tsx" + assert widget.read_text(encoding="utf-8") == "export const Widget = 'new';\n" diff --git a/tasks/test.toml b/tasks/test.toml index bb1fa2e9ab..3df9b7371a 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -19,9 +19,9 @@ depends = [ ["test:docs-website"] description = "Test the docs-website sync script" -# --no-project skips installing the OpenShell package; --with supplies pytest -# and the script's runtime dependency (PyYAML), which lives outside the project env. -run = "uv run --no-project --with pytest --with pyyaml pytest tasks/scripts/sync_docs_website_test.py" +# --no-project skips installing the OpenShell package; --with supplies the test +# dependencies and the script's runtime dependency, which live outside the project env. +run = "uv run --no-project --with pytest --with pytest-asyncio --with pyyaml pytest tasks/scripts/sync_docs_website_test.py" ["test:sbom"] description = "Run SBOM tooling tests"