From d4b667ed74e01f1c4ccf94072a97f575cb4784a0 Mon Sep 17 00:00:00 2001 From: Shiju Date: Mon, 2 Nov 2026 19:54:49 +0530 Subject: [PATCH] fix(middleware): preserve HTTP request failure causes Carry typed causes through HTTP request middleware diagnostics. Distinguish local deadlines, gRPC statuses, built-in errors and stale-policy cancellation while preserving diagnostic messages and response selection. Track live upstream writes from the first attempt through the final flush. Retain delivery progress when a stage fails while output is still queued. Refs #4144 Signed-off-by: Shiju --- .../src/policy_types.rs | 30 +- .../src/http_hooks/pipeline.rs | 119 +++++-- .../src/http_hooks/request.rs | 8 +- .../src/http_hooks/tests.rs | 240 +++++++++----- .../src/lib.rs | 305 +++++++++++++----- .../src/request_failure.rs | 105 ++++++ .../src/l7/middleware.rs | 183 +++++++++-- .../src/l7/mod.rs | 1 + .../src/l7/relay.rs | 6 +- .../src/l7/request_delivery.rs | 50 +++ .../src/l7/rest/http_response/http_hooks.rs | 2 + .../src/l7/rest/request_body.rs | 126 ++++++-- .../supervisor-middleware/operations.mdx | 2 + 13 files changed, 933 insertions(+), 244 deletions(-) create mode 100644 crates/openshell-supervisor-middleware/src/request_failure.rs create mode 100644 crates/openshell-supervisor-network/src/l7/request_delivery.rs diff --git a/crates/openshell-policy-runtime-interface/src/policy_types.rs b/crates/openshell-policy-runtime-interface/src/policy_types.rs index 11d9156ebb..509e902975 100644 --- a/crates/openshell-policy-runtime-interface/src/policy_types.rs +++ b/crates/openshell-policy-runtime-interface/src/policy_types.rs @@ -384,6 +384,26 @@ pub struct PolicyGenerationGuard { revalidator: Option>, } +/// The policy that authorized a request no longer applies. +#[derive(Debug)] +pub struct StalePolicyGeneration { + captured: u64, + current: u64, +} + +impl std::fmt::Display for StalePolicyGeneration { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "policy generation is stale [captured_generation:{} current_generation:{}]", + self.captured, self.current + ) + } +} + +impl std::error::Error for StalePolicyGeneration {} +impl miette::Diagnostic for StalePolicyGeneration {} + /// Builds a [`PolicyGenerationGuard`] for any state holding a plain /// `Arc` generation counter and matching `watch::Sender`. /// @@ -445,11 +465,11 @@ impl PolicyGenerationGuard { pub fn ensure_current(&self) -> Result<()> { if self.is_stale() { - return Err(miette::miette!( - "policy generation is stale [captured_generation:{} current_generation:{}]", - self.captured_generation(), - self.current_generation(), - )); + return Err(StalePolicyGeneration { + captured: self.captured_generation(), + current: self.current_generation(), + } + .into()); } Ok(()) } diff --git a/crates/openshell-supervisor-middleware/src/http_hooks/pipeline.rs b/crates/openshell-supervisor-middleware/src/http_hooks/pipeline.rs index e62d869e92..3768d25422 100644 --- a/crates/openshell-supervisor-middleware/src/http_hooks/pipeline.rs +++ b/crates/openshell-supervisor-middleware/src/http_hooks/pipeline.rs @@ -41,10 +41,10 @@ use openshell_core::proto::{ use crate::headers::{self, HeaderAuthority}; use crate::{ - ChainRunner, DescribedChainEntry, HttpHookVersion, MAX_MIDDLEWARE_CHAIN_TIMEOUT, - MAX_MIDDLEWARE_PAYLOAD_BYTES, MiddlewareDenial, MiddlewareDiagnosticPolicy, - MiddlewareInvocation, MiddlewareSessionPermit, NamespacedFinding, OnError, - TransformedBodyPolicy, middleware_denial_reason, safe_reason, + ChainRunner, DescribedChainEntry, HttpHookVersion, HttpRequestFailureKind, + MAX_MIDDLEWARE_CHAIN_TIMEOUT, MAX_MIDDLEWARE_PAYLOAD_BYTES, MiddlewareDenial, + MiddlewareDiagnosticPolicy, MiddlewareInvocation, MiddlewareSessionPermit, NamespacedFinding, + OnError, TransformedBodyPolicy, middleware_denial_reason, safe_reason, }; /// Largest normalized body chunk a stage sends or receives. @@ -197,6 +197,8 @@ pub enum HttpStageOutcome { /// Audit record for one stage and phase. Carries no service-provided text. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HttpStageInvocation { + /// Failure cause retained without service text or status metadata. + pub failure_kind: Option, pub config_name: String, pub implementation: String, pub outcome: HttpStageOutcome, @@ -213,6 +215,8 @@ pub struct HttpStageInvocation { /// Findings, metadata, and invocations for one exchange. #[derive(Debug, Default)] pub struct HttpStageDiagnostics { + /// Terminal cause, including failures with no failed stage invocation. + pub failure_kind: Option, pub findings: Vec, pub metadata: BTreeMap>, pub invocations: Vec, @@ -221,6 +225,7 @@ pub struct HttpStageDiagnostics { impl HttpStageDiagnostics { /// Append `other`, keeping chain order. pub fn extend(&mut self, other: Self) { + self.failure_kind = other.failure_kind.or(self.failure_kind); self.findings.extend(other.findings); self.metadata.extend(other.metadata); self.invocations.extend(other.invocations); @@ -248,6 +253,7 @@ impl HttpStageDiagnostics { .iter_mut() .find(|(existing, _)| existing.name == invocation.config_name) { + existing.failure_kind = invocation.failure_kind.or(existing.failure_kind); existing.failed |= invocation.failed; existing.transformed |= invocation.transformed; if denied { @@ -258,6 +264,7 @@ impl HttpStageDiagnostics { } applied.push(( MiddlewareInvocation { + failure_kind: invocation.failure_kind, name: invocation.config_name.clone(), implementation: invocation.implementation.clone(), decision: if denied { @@ -286,6 +293,8 @@ impl HttpStageDiagnostics { /// The exchange failed closed or was denied. #[derive(Debug)] pub struct HttpMiddlewareFailure { + /// Cause preserved independently of sandbox failure codes and diagnostics. + pub kind: Option, /// Platform-owned reason: `middleware_denied:[:]` for a /// denial, `middleware_failed: ` for a failure, and /// `middleware_cancelled: ` when the input producer went away. @@ -1558,13 +1567,17 @@ async fn run_checkpoint( .ok() .flatten() .is_none_or(|previous| previous != body); - if replaced && let Some(reason) = transformed_body_denial(body_policy, &body) { + if replaced && let Some((reason, kind)) = transformed_body_denial(body_policy, &body) { return Err(TaskError::Failed(HttpMiddlewareFailure { + kind, reason, denial: None, failure: None, end_reason: MiddlewareSessionEndReason::PolicyDenial, - diagnostics: Box::default(), + diagnostics: Box::new(HttpStageDiagnostics { + failure_kind: kind, + ..Default::default() + }), })); } let (header_mutations, output_body_bytes) = start.expect("a started stage output"); @@ -2009,15 +2022,21 @@ async fn drive_buffered( } /// The body policy's verdict on a replaced body, or `None` when it passes. -fn transformed_body_denial(policy: TransformedBodyPolicy<'_>, body: &[u8]) -> Option { +fn transformed_body_denial( + policy: TransformedBodyPolicy<'_>, + body: &[u8], +) -> Option<(String, Option)> { let TransformedBodyPolicy::Reevaluate(validate) = policy else { return None; }; match validate(body) { - Ok(reason) => reason, - Err(error) => Some(format!( - "transformed_body_policy_evaluation_failed: {}", - safe_reason(&error.to_string()) + Ok(reason) => reason.map(|reason| (reason, None)), + Err(error) => Some(( + format!( + "transformed_body_policy_evaluation_failed: {}", + safe_reason(&error.to_string()) + ), + Some(HttpRequestFailureKind::PolicyEvaluation), )), } } @@ -2179,7 +2198,16 @@ async fn drive_stream( held.send_replace(false); } StageResult::OutputChunk(chunk) if started => { - if chunk.data.is_empty() || chunk.data.len() > chunk_limit { + if chunk.data.len() > chunk_limit { + return Err(entry_failure_with_code( + entry, + "stream_output_chunk_invalid", + HttpFailureCode::LifecycleViolation, + HttpRequestFailureKind::Capacity, + ) + .into()); + } + if chunk.data.is_empty() { return Err(entry_failure(entry, "stream_output_chunk_invalid").into()); } output_bytes = output_bytes.saturating_add(chunk.data.len()); @@ -2266,19 +2294,31 @@ pub(super) fn classify_result( /// Classify an RPC status. Every status fails the exchange closed; the reason /// is platform-owned for external services. fn status_failure(entry: &DescribedChainEntry, status: &tonic::Status) -> HttpMiddlewareFailure { - match status.code() { - tonic::Code::DeadlineExceeded => entry_failure(entry, "middleware_timeout"), - // The service does not implement the HTTP hook RPC its binding - // selected. - tonic::Code::Unimplemented => entry_failure(entry, "middleware_unimplemented"), - // The reason may carry an in-process service's status text, so the - // sandbox sees only that the middleware failed. - _ => entry_failure_with_code( - entry, - &diagnostic_policy(entry).error_reason(status), + let service = entry + .service + .as_ref() + .expect("a status comes from a resolved stage"); + let (reason, code) = match status.code() { + tonic::Code::DeadlineExceeded => { + ("middleware_timeout".to_string(), HttpFailureCode::Timeout) + } + // The service does not implement the HTTP hook RPC its binding selected. + tonic::Code::Unimplemented => ( + "middleware_unimplemented".to_string(), + HttpFailureCode::LifecycleViolation, + ), + // In-process status text stays in diagnostics, never the sandbox code. + _ => ( + service.diagnostic_policy.error_reason(status), HttpFailureCode::Unavailable, ), - } + }; + entry_failure_with_code( + entry, + &reason, + code, + service.service.status_failure_kind(status.code()), + ) } fn diagnostic_policy(entry: &DescribedChainEntry) -> MiddlewareDiagnosticPolicy { @@ -2298,6 +2338,7 @@ fn mutation_failure( entry, &diagnostic_policy(entry).header_mutation_error_reason(error), HttpFailureCode::HeaderMutation(error.code()), + HttpRequestFailureKind::HeaderMutation, ) } @@ -2413,6 +2454,7 @@ pub(super) fn denial( .invocations .push(invocation(entry, HttpStageOutcome::Deny, reason_code)); HttpMiddlewareFailure { + kind: None, reason: middleware_denial_reason(&denial.config_name, denial.reason_code.as_deref()), denial: Some(denial), failure: None, @@ -2423,7 +2465,12 @@ pub(super) fn denial( /// The stage failed and the exchange fails closed. pub fn entry_failure(entry: &DescribedChainEntry, reason: &str) -> HttpMiddlewareFailure { - entry_failure_with_code(entry, reason, HttpFailureCode::of_reason(reason)) + entry_failure_with_code( + entry, + reason, + HttpFailureCode::of_reason(reason), + HttpRequestFailureKind::of_platform_reason(reason), + ) } /// The stage failed with `reason`, which the sandbox sees as `code`. @@ -2431,14 +2478,20 @@ fn entry_failure_with_code( entry: &DescribedChainEntry, reason: &str, code: HttpFailureCode, + kind: HttpRequestFailureKind, ) -> HttpMiddlewareFailure { - let mut diagnostics = HttpStageDiagnostics::default(); + let mut diagnostics = HttpStageDiagnostics { + failure_kind: Some(kind), + ..Default::default() + }; diagnostics.invocations.push(HttpStageInvocation { + failure_kind: Some(kind), failed: true, failure_reason: Some(reason.to_string()), ..invocation(entry, HttpStageOutcome::FailClosed, None) }); HttpMiddlewareFailure { + kind: Some(kind), reason: format!("middleware_failed: {reason}"), denial: None, failure: Some(Box::new(MiddlewareFailureDetail { @@ -2452,22 +2505,32 @@ fn entry_failure_with_code( /// The exchange failed for a reason no single stage owns. pub fn platform_failure(reason: &str) -> HttpMiddlewareFailure { + let kind = HttpRequestFailureKind::InvalidResult; HttpMiddlewareFailure { + kind: Some(kind), reason: format!("middleware_failed: {reason}"), denial: None, failure: None, end_reason: MiddlewareSessionEndReason::MiddlewareFailure, - diagnostics: Box::default(), + diagnostics: Box::new(HttpStageDiagnostics { + failure_kind: Some(kind), + ..Default::default() + }), } } fn cancelled(reason: &str) -> HttpMiddlewareFailure { + let kind = HttpRequestFailureKind::Cancelled; HttpMiddlewareFailure { + kind: Some(kind), reason: format!("middleware_cancelled: {reason}"), denial: None, failure: None, end_reason: MiddlewareSessionEndReason::Cancellation, - diagnostics: Box::default(), + diagnostics: Box::new(HttpStageDiagnostics { + failure_kind: Some(kind), + ..Default::default() + }), } } @@ -2477,6 +2540,7 @@ pub fn invocation( reason_code: Option, ) -> HttpStageInvocation { HttpStageInvocation { + failure_kind: None, config_name: entry.entry.name.clone(), implementation: entry.entry.implementation.clone(), outcome, @@ -2491,6 +2555,7 @@ pub fn invocation( pub fn fail_open_invocation(entry: &DescribedChainEntry, reason: &str) -> HttpStageInvocation { HttpStageInvocation { + failure_kind: Some(HttpRequestFailureKind::of_platform_reason(reason)), failed: true, failure_reason: Some(reason.to_string()), ..invocation(entry, HttpStageOutcome::FailOpen, None) diff --git a/crates/openshell-supervisor-middleware/src/http_hooks/request.rs b/crates/openshell-supervisor-middleware/src/http_hooks/request.rs index 1b945a733c..2eb1beb724 100644 --- a/crates/openshell-supervisor-middleware/src/http_hooks/request.rs +++ b/crates/openshell-supervisor-middleware/src/http_hooks/request.rs @@ -267,7 +267,13 @@ fn capacity_exhausted(headers: Vec) -> HttpRequestPreflightOutcome { allowed: false, reason: "middleware_failed: session_capacity_exhausted".into(), session_capacity_exhausted: true, - ..outcome(headers, HttpStageDiagnostics::default()) + ..outcome( + headers, + HttpStageDiagnostics { + failure_kind: Some(crate::HttpRequestFailureKind::Capacity), + ..Default::default() + }, + ) } } diff --git a/crates/openshell-supervisor-middleware/src/http_hooks/tests.rs b/crates/openshell-supervisor-middleware/src/http_hooks/tests.rs index 5b2f652398..ef1781b707 100644 --- a/crates/openshell-supervisor-middleware/src/http_hooks/tests.rs +++ b/crates/openshell-supervisor-middleware/src/http_hooks/tests.rs @@ -150,6 +150,7 @@ enum Preflight { Inspect(HttpBodyMode), Deny(&'static str), Fail(tonic::Code), + Stall, } /// What a scripted stage does with the body it selected. @@ -345,6 +346,7 @@ impl InProcessMiddleware for ScriptedStage { })) } Preflight::Fail(code) => Err(tonic::Status::new(*code, "scripted")), + Preflight::Stall => futures::future::pending().await, } } Some(http_request_hook_event::Event::Begin(started)) => { @@ -393,7 +395,11 @@ impl InProcessMiddleware for ScriptedStage { } result(http_request_hook_result::Result::OutputChunk( HttpOutputChunk { - data: chunk.data.to_ascii_uppercase(), + data: if let Body::Replace(bytes) = body { + bytes.to_vec() + } else { + chunk.data.to_ascii_uppercase() + }, }, )) } @@ -1005,53 +1011,53 @@ async fn waiting_for_a_stream_slot_does_not_hold_a_preflight_slot() { assert_eq!(free_slots(&runner), (MAX_HTTP_HOOK_BUFFERING_SLOTS, 0),); } -#[tokio::test] +#[tokio::test(start_paused = true)] async fn failures_name_the_failed_stage_and_a_platform_code() { - for (case, preflight, code) in [ - // No status means "cannot inspect": a proxy between OpenShell and the - // service may rewrite status codes. + use crate::HttpRequestFailureKind as Kind; + use tonic::Code; + let service_failure = |status, code| { ( - "FAILED_PRECONDITION", - Preflight::Fail(tonic::Code::FailedPrecondition), - HttpFailureCode::Unavailable, - ), + Preflight::Fail(status), + crate::DEFAULT_MIDDLEWARE_TIMEOUT, + code, + Kind::InProcessService, + ) + }; + for (preflight, timeout, code, kind) in [ + service_failure(Code::FailedPrecondition, HttpFailureCode::Unavailable), + service_failure(Code::DeadlineExceeded, HttpFailureCode::Timeout), + service_failure(Code::Unimplemented, HttpFailureCode::LifecycleViolation), + service_failure(Code::Unavailable, HttpFailureCode::Unavailable), + service_failure(Code::Internal, HttpFailureCode::Unavailable), ( - "DEADLINE_EXCEEDED", - Preflight::Fail(tonic::Code::DeadlineExceeded), + Preflight::Stall, + std::time::Duration::from_millis(5), HttpFailureCode::Timeout, + Kind::StageTimeout, ), ( - "UNIMPLEMENTED", - Preflight::Fail(tonic::Code::Unimplemented), - HttpFailureCode::LifecycleViolation, - ), - // The reason keeps an in-process service's status text; the code - // the sandbox sees does not. - ( - "UNAVAILABLE", - Preflight::Fail(tonic::Code::Unavailable), - HttpFailureCode::Unavailable, - ), - ( - "INTERNAL", - Preflight::Fail(tonic::Code::Internal), - HttpFailureCode::Unavailable, + Preflight::Stall, + MAX_MIDDLEWARE_CHAIN_TIMEOUT * 2, + HttpFailureCode::Timeout, + Kind::ChainTimeout, ), ] { - let (runner, described) = + let (runner, mut described) = scripted_chain(vec![scripted("example/a", preflight, Body::Unchanged)]).await; - let preflight = runner + described[0].timeout = timeout; + let result = runner .preflight_described_http_request(described, request_input(b"hello")) .await .expect("preflight"); - assert!(!preflight.allowed, "{case}"); + assert!(!result.allowed, "{kind:?}"); + assert_eq!(result.diagnostics.failure_kind, Some(kind)); + assert_eq!(result.diagnostics.applied()[0].failure_kind, Some(kind)); assert_eq!( - preflight.failure, + result.failure, Some(MiddlewareFailureDetail { config_name: Some("example/a-config".into()), code, - }), - "{case}" + }) ); } @@ -1067,51 +1073,75 @@ async fn failures_name_the_failed_stage_and_a_platform_code() { .expect("preflight"); assert!(denied.denial.is_some()); assert!(denied.failure.is_none()); + assert_eq!(denied.diagnostics.failure_kind, None); + assert_eq!(denied.diagnostics.applied()[0].failure_kind, None); } #[tokio::test] -async fn failure_reasons_map_to_a_closed_set_of_sandbox_codes() { +async fn stage_failures_retain_their_sandbox_code_and_compacted_cause() { + use crate::HttpRequestFailureKind::{ + Capacity, ChainTimeout, InvalidResult, Io, StageTimeout, StreamIdleTimeout, Unavailable, + WholeBodyTimeout, + }; let (_, described) = scripted_chain(vec![scripted( "example/a", Preflight::Continue, Body::Unchanged, )]) .await; - for (reason, code) in [ - ("middleware_cannot_inspect", "middleware_cannot_inspect"), - ("head_input_over_capacity", "middleware_cannot_inspect"), + let cannot_inspect = "middleware_cannot_inspect"; + let timeout = "middleware_timeout"; + let unavailable = "middleware_unavailable"; + let body_limit = "body_over_limit"; + let lifecycle = "middleware_lifecycle_violation"; + for (reason, code, kind) in [ + ("middleware_cannot_inspect", cannot_inspect, InvalidResult), + ("head_input_over_capacity", cannot_inspect, Capacity), ( "response_input_unrepresentable", - "middleware_cannot_inspect", - ), - ("middleware_timeout", "middleware_timeout"), - ("middleware_chain_timeout", "middleware_timeout"), - ("middleware_body_timeout", "middleware_timeout"), - ("middleware_stall_timeout", "stream_idle_timeout"), - ("binding_not_described", "middleware_unavailable"), - ("session_capacity_exhausted", "middleware_unavailable"), - ("buffered_input_over_capacity", "body_over_limit"), - ("buffered_output_over_capacity", "body_over_limit"), - ("request_output_over_capacity", "body_over_limit"), - ( - "middleware_hook_versions_mixed", - "middleware_hook_versions_mixed", + cannot_inspect, + InvalidResult, ), - ("middleware_unimplemented", "middleware_lifecycle_violation"), + ("middleware_timeout", timeout, StageTimeout), + ("middleware_chain_timeout", timeout, ChainTimeout), + ("middleware_body_timeout", timeout, WholeBodyTimeout), ( - "middleware_result_stream_closed", - "middleware_lifecycle_violation", + "middleware_stall_timeout", + "stream_idle_timeout", + StreamIdleTimeout, ), + ("binding_not_described", unavailable, Unavailable), + ("session_capacity_exhausted", unavailable, Capacity), + ("buffered_input_over_capacity", body_limit, Capacity), + ("buffered_output_over_capacity", body_limit, Capacity), + ("request_output_over_capacity", body_limit, Capacity), ( - "stream_output_length_mismatch", - "middleware_lifecycle_violation", + "middleware_hook_versions_mixed", + "middleware_hook_versions_mixed", + InvalidResult, ), - ("preflight_result_unknown", "middleware_lifecycle_violation"), + ("middleware_unimplemented", lifecycle, InvalidResult), + ("middleware_result_stream_closed", lifecycle, Io), + ("stream_output_length_mismatch", lifecycle, InvalidResult), + ("preflight_result_unknown", lifecycle, InvalidResult), + ("diagnostics_reason_over_capacity", lifecycle, Capacity), + ("middleware_stream_closed", lifecycle, Io), ] { - let failure = entry_failure(&described[0], reason) - .failure - .expect("failure detail"); - assert_eq!(failure.code.as_str(), code, "{reason}"); + let failure = entry_failure(&described[0], reason); + assert_eq!(failure.failure.unwrap().code.as_str(), code, "{reason}"); + assert_eq!(failure.kind, Some(kind), "{reason}"); + let mut diagnostics = crate::HttpStageDiagnostics::default(); + diagnostics.invocations.push(super::pipeline::invocation( + &described[0], + HttpStageOutcome::Duplex, + None, + )); + diagnostics.extend(*failure.diagnostics); + assert_eq!(diagnostics.failure_kind, Some(kind), "{reason}"); + let applied = diagnostics.applied(); + assert_eq!(applied.len(), 1); + assert!(applied[0].failed); + assert_eq!(applied[0].failure_kind, Some(kind), "{reason}"); } } @@ -1517,6 +1547,30 @@ async fn adjacent_buffered_stages_share_capacity_instead_of_deadlocking() { ); } +async fn finish_request_body( + session: crate::HttpRequestPipeline, + body: &[u8], +) -> Result { + let (input, inputs) = mpsc::channel(4); + input + .send(HttpBodyInput::Chunk(body.to_vec())) + .await + .unwrap(); + input + .send(HttpBodyInput::End { + trailers: Vec::new(), + }) + .await + .unwrap(); + let (output, mut outputs) = mpsc::channel(4); + let collect = async { while outputs.recv().await.is_some() {} }; + let (finish, ()) = tokio::join!( + session.run_with_body_policy(inputs, output, TransformedBodyPolicy::NotPolicyRelevant), + collect + ); + finish +} + #[tokio::test(start_paused = true)] async fn deferred_preflight_capacity_wait_is_bounded_and_releases_the_stream_slot() { let first = scripted( @@ -1538,27 +1592,7 @@ async fn deferred_preflight_capacity_wait_is_bounded_and_releases_the_stream_slo .acquire_many_owned(u32::try_from(MAX_HTTP_HOOK_BUFFERING_SLOTS).unwrap()) .await .unwrap(); - let (input, inputs) = mpsc::channel(4); - input - .send(HttpBodyInput::Chunk(b"hello".to_vec())) - .await - .unwrap(); - input - .send(HttpBodyInput::End { - trailers: Vec::new(), - }) - .await - .unwrap(); - let (output, mut outputs) = mpsc::channel(4); - let collect = async { while outputs.recv().await.is_some() {} }; - let (finish, ()) = tokio::join!( - preflight.pipeline.unwrap().run_with_body_policy( - inputs, - output, - TransformedBodyPolicy::NotPolicyRelevant - ), - collect - ); + let finish = finish_request_body(preflight.pipeline.unwrap(), b"hello").await; let failure = finish.expect_err("no preflight capacity"); assert_eq!(failure.failure.unwrap().code, HttpFailureCode::Unavailable); assert!(second.preflights.lock().unwrap().is_empty()); @@ -1696,3 +1730,47 @@ async fn stages_cannot_change_headers_that_reference_credentials() { ); } } + +#[tokio::test] +async fn duplex_chunk_capacity_is_distinct_from_invalid_output() { + use crate::HttpRequestFailureKind; + for (chunk, expected) in [ + (&[b'x'; 1024][..], None), + (&[b'x'; 1025][..], Some(HttpRequestFailureKind::Capacity)), + (&[][..], Some(HttpRequestFailureKind::InvalidResult)), + ] { + let stage = scripted( + "example/a", + Preflight::Inspect(HttpBodyMode::Duplex), + Body::Replace(chunk), + ); + let (runner, described) = scripted_chain(vec![stage]).await; + let preflight = runner + .preflight_described_http_request(described, request_input(b"a")) + .await + .expect("preflight"); + let finish = finish_request_body(preflight.pipeline.unwrap(), b"a").await; + match expected { + None => assert_eq!( + finish.expect("exact chunk limit").diagnostics.failure_kind, + None + ), + Some(expected) => { + let failure = finish.expect_err("invalid chunk"); + assert_eq!(failure.kind, Some(expected)); + assert_eq!( + failure.diagnostics.applied()[0].failure_kind, + Some(expected) + ); + assert_eq!( + failure.reason, + "middleware_failed: stream_output_chunk_invalid" + ); + assert_eq!( + failure.failure.unwrap().code, + HttpFailureCode::LifecycleViolation + ); + } + } + } +} diff --git a/crates/openshell-supervisor-middleware/src/lib.rs b/crates/openshell-supervisor-middleware/src/lib.rs index 2f6d5ca7b0..4d46bf5aa2 100644 --- a/crates/openshell-supervisor-middleware/src/lib.rs +++ b/crates/openshell-supervisor-middleware/src/lib.rs @@ -8,6 +8,8 @@ mod diagnostics; pub mod headers; mod http_hooks; mod remote; +mod request_failure; +pub use request_failure::HttpRequestFailureKind; mod response; mod websocket; @@ -679,6 +681,8 @@ pub struct HttpRequestInput { #[derive(Debug, Clone)] pub struct ChainOutcome { + /// Failure cause, independent of diagnostic text and explicit denials. + pub failure_kind: Option, pub allowed: bool, pub reason: String, pub body: Vec, @@ -710,6 +714,8 @@ pub struct NamespacedFinding { #[derive(Debug, Clone, PartialEq, Eq)] pub struct MiddlewareInvocation { + /// Failure cause, independent of diagnostic text and explicit denials. + pub failure_kind: Option, pub name: String, pub implementation: String, pub decision: Decision, @@ -724,7 +730,7 @@ enum OnErrorAction { /// `fail_open`: skip this middleware, leaving the request unchanged. FailOpen, /// `fail_closed`: short-circuit the chain and deny with the given reason. - FailClosed(String), + FailClosed(String, HttpRequestFailureKind), } /// Apply a middleware entry's `on_error` policy after a failure (service error or @@ -732,11 +738,13 @@ enum OnErrorAction { fn apply_on_error( entry: &DescribedChainEntry, reason: &str, + failure_kind: HttpRequestFailureKind, applied: &mut Vec, ) -> OnErrorAction { match entry.entry.on_error { OnError::FailOpen => { applied.push(MiddlewareInvocation { + failure_kind: Some(failure_kind), name: entry.entry.name.clone(), implementation: entry.entry.implementation.clone(), decision: Decision::Allow, @@ -747,13 +755,14 @@ fn apply_on_error( } OnError::FailClosed => { applied.push(MiddlewareInvocation { + failure_kind: Some(failure_kind), name: entry.entry.name.clone(), implementation: entry.entry.implementation.clone(), decision: Decision::Deny, transformed: false, failed: true, }); - OnErrorAction::FailClosed(format!("middleware_failed: {reason}")) + OnErrorAction::FailClosed(format!("middleware_failed: {reason}"), failure_kind) } } } @@ -784,6 +793,13 @@ enum MiddlewareDispatch { } impl MiddlewareDispatch { + fn status_failure_kind(&self, code: tonic::Code) -> HttpRequestFailureKind { + match self { + Self::InProcess(_) => HttpRequestFailureKind::InProcessService, + Self::Grpc(_) => HttpRequestFailureKind::RemoteStatus(code), + } + } + async fn describe( &self, ) -> std::result::Result, tonic::Status> { @@ -2115,6 +2131,7 @@ impl ChainRunner { .find(|entry| entry.http_hook_version() == Some(HttpHookVersion::Current)) { return Ok(ChainOutcome { + failure_kind: Some(HttpRequestFailureKind::InvalidResult), allowed: false, reason: format!("middleware_failed: {MIDDLEWARE_HOOK_VERSIONS_MIXED}"), body: input.body, @@ -2122,6 +2139,7 @@ impl ChainRunner { findings: Vec::new(), metadata: BTreeMap::new(), applied: vec![MiddlewareInvocation { + failure_kind: Some(HttpRequestFailureKind::InvalidResult), name: entry.entry.name.clone(), implementation: entry.entry.implementation.clone(), decision: Decision::Deny, @@ -2180,10 +2198,16 @@ impl ChainRunner { for entry in entries { let Some(_binding) = entry.binding.as_ref() else { - match apply_on_error(entry, "binding_not_described", &mut applied) { + match apply_on_error( + entry, + "binding_not_described", + HttpRequestFailureKind::Unavailable, + &mut applied, + ) { OnErrorAction::FailOpen => continue, - OnErrorAction::FailClosed(reason) => { + OnErrorAction::FailClosed(reason, failure_kind) => { return Ok(ChainOutcome { + failure_kind: Some(failure_kind), allowed: false, reason, body, @@ -2197,10 +2221,16 @@ impl ChainRunner { } }; if body.len() > entry.max_payload_bytes { - match apply_on_error(entry, "request_body_over_capacity", &mut applied) { + match apply_on_error( + entry, + "request_body_over_capacity", + HttpRequestFailureKind::Capacity, + &mut applied, + ) { OnErrorAction::FailOpen => continue, - OnErrorAction::FailClosed(reason) => { + OnErrorAction::FailClosed(reason, failure_kind) => { return Ok(ChainOutcome { + failure_kind: Some(failure_kind), allowed: false, reason, body, @@ -2223,10 +2253,16 @@ impl ChainRunner { &entry.entry.implementation, ); if let Err(reason) = validate_request_view(request) { - match apply_on_error(entry, reason, &mut applied) { + match apply_on_error( + entry, + reason, + HttpRequestFailureKind::of_platform_reason(reason), + &mut applied, + ) { OnErrorAction::FailOpen => continue, - OnErrorAction::FailClosed(reason) => { + OnErrorAction::FailClosed(reason, failure_kind) => { return Ok(ChainOutcome { + failure_kind: Some(failure_kind), allowed: false, reason, body, @@ -2244,10 +2280,16 @@ impl ChainRunner { }; let remaining = chain_deadline.saturating_duration_since(tokio::time::Instant::now()); if remaining.is_zero() { - match apply_on_error(entry, "middleware_chain_timeout", &mut applied) { + match apply_on_error( + entry, + "middleware_chain_timeout", + HttpRequestFailureKind::ChainTimeout, + &mut applied, + ) { OnErrorAction::FailOpen => continue, - OnErrorAction::FailClosed(reason) => { + OnErrorAction::FailClosed(reason, failure_kind) => { return Ok(ChainOutcome { + failure_kind: Some(failure_kind), allowed: false, reason, body, @@ -2260,24 +2302,38 @@ impl ChainRunner { } } } - let mut result = match call_with_timeout( + let evaluated = match tokio::time::timeout( entry.timeout.min(remaining), - "EvaluateHttpRequest", service.service.evaluate_http_request(request), ) .await { - Ok(result) => result.into_inner(), - Err(err) => { - let reason = if err.code() == tonic::Code::DeadlineExceeded { + Ok(Ok(response)) => Ok(response.into_inner()), + Ok(Err(status)) => { + let reason = if status.code() == tonic::Code::DeadlineExceeded { "middleware_timeout".to_string() } else { - service.diagnostic_policy.error_reason(&err) + service.diagnostic_policy.error_reason(&status) }; - match apply_on_error(entry, &reason, &mut applied) { + Err((reason, service.service.status_failure_kind(status.code()))) + } + Err(_) => { + let failure_kind = if remaining <= entry.timeout { + HttpRequestFailureKind::ChainTimeout + } else { + HttpRequestFailureKind::StageTimeout + }; + Err(("middleware_timeout".to_string(), failure_kind)) + } + }; + let mut result = match evaluated { + Ok(result) => result, + Err((reason, failure_kind)) => { + match apply_on_error(entry, &reason, failure_kind, &mut applied) { OnErrorAction::FailOpen => continue, - OnErrorAction::FailClosed(reason) => { + OnErrorAction::FailClosed(reason, failure_kind) => { return Ok(ChainOutcome { + failure_kind: Some(failure_kind), allowed: false, reason, body, @@ -2293,10 +2349,16 @@ impl ChainRunner { }; if let Err(reason) = validate_response_envelope(&result) { - match apply_on_error(entry, reason, &mut applied) { + match apply_on_error( + entry, + reason, + HttpRequestFailureKind::of_platform_reason(reason), + &mut applied, + ) { OnErrorAction::FailOpen => continue, - OnErrorAction::FailClosed(reason) => { + OnErrorAction::FailClosed(reason, failure_kind) => { return Ok(ChainOutcome { + failure_kind: Some(failure_kind), allowed: false, reason, body, @@ -2317,10 +2379,16 @@ impl ChainRunner { let decision = match Decision::try_from(result.decision) { Ok(decision @ (Decision::Allow | Decision::Deny)) => decision, Ok(Decision::Unspecified) | Err(_) => { - match apply_on_error(entry, "invalid_response_decision", &mut applied) { + match apply_on_error( + entry, + "invalid_response_decision", + HttpRequestFailureKind::InvalidResult, + &mut applied, + ) { OnErrorAction::FailOpen => continue, - OnErrorAction::FailClosed(reason) => { + OnErrorAction::FailClosed(reason, failure_kind) => { return Ok(ChainOutcome { + failure_kind: Some(failure_kind), allowed: false, reason, body, @@ -2355,6 +2423,7 @@ impl ChainRunner { ); } applied.push(MiddlewareInvocation { + failure_kind: None, name: entry.entry.name.clone(), implementation: entry.entry.implementation.clone(), decision, @@ -2362,6 +2431,7 @@ impl ChainRunner { failed: false, }); return Ok(ChainOutcome { + failure_kind: None, allowed: false, reason: middleware_denial_reason( &denial.config_name, @@ -2377,10 +2447,16 @@ impl ChainRunner { } if result.has_body && result.body.len() > entry.max_payload_bytes { - match apply_on_error(entry, "response_body_over_capacity", &mut applied) { + match apply_on_error( + entry, + "response_body_over_capacity", + HttpRequestFailureKind::Capacity, + &mut applied, + ) { OnErrorAction::FailOpen => continue, - OnErrorAction::FailClosed(reason) => { + OnErrorAction::FailClosed(reason, failure_kind) => { return Ok(ChainOutcome { + failure_kind: Some(failure_kind), allowed: false, reason, body, @@ -2411,10 +2487,16 @@ impl ChainRunner { let reason = service .diagnostic_policy .header_mutation_error_reason(&error); - match apply_on_error(entry, &reason, &mut applied) { + match apply_on_error( + entry, + &reason, + HttpRequestFailureKind::HeaderMutation, + &mut applied, + ) { OnErrorAction::FailOpen => continue, - OnErrorAction::FailClosed(reason) => { + OnErrorAction::FailClosed(reason, failure_kind) => { return Ok(ChainOutcome { + failure_kind: Some(failure_kind), allowed: false, reason, body, @@ -2454,6 +2536,7 @@ impl ChainRunner { ); } applied.push(MiddlewareInvocation { + failure_kind: None, name: entry.entry.name.clone(), implementation: entry.entry.implementation.clone(), decision, @@ -2468,15 +2551,19 @@ impl ChainRunner { if body_transformed && let TransformedBodyPolicy::Reevaluate(validate) = transformed_body_policy { - let denied = match validate(&body) { - Ok(reason) => reason, - Err(error) => Some(format!( - "transformed_body_policy_evaluation_failed: {}", - safe_reason(&error.to_string()) - )), + let (denied, failure_kind) = match validate(&body) { + Ok(reason) => (reason, None), + Err(error) => ( + Some(format!( + "transformed_body_policy_evaluation_failed: {}", + safe_reason(&error.to_string()) + )), + Some(HttpRequestFailureKind::PolicyEvaluation), + ), }; if let Some(reason) = denied { return Ok(ChainOutcome { + failure_kind, allowed: false, reason, body, @@ -2491,6 +2578,7 @@ impl ChainRunner { } Ok(ChainOutcome { + failure_kind: None, allowed: true, reason: String::new(), body, @@ -3141,37 +3229,51 @@ mod tests { } #[tokio::test] - async fn fail_open_allows_unavailable_middleware() { - let unavailable = ChainEntry { - name: "missing".into(), - implementation: "third-party/missing".into(), - order: 0, - config: prost_types::Struct::default(), - on_error: OnError::FailOpen, - }; - let outcome = builtin_runner() - .evaluate(&[unavailable], input("hello")) - .await - .expect("evaluate"); - assert!(outcome.allowed); - assert_eq!(outcome.body, b"hello"); - } - - #[tokio::test] - async fn fail_closed_denies_unavailable_middleware() { - let unavailable = ChainEntry { - name: "missing".into(), + async fn on_error_preserves_the_stage_cause_and_only_fails_the_closed_request() { + let runner = builtin_runner(); + let missing = ChainEntry { implementation: "third-party/missing".into(), - order: 0, - config: prost_types::Struct::default(), - on_error: OnError::FailClosed, + ..entry("missing", OnError::FailClosed) }; - let outcome = builtin_runner() - .evaluate(&[unavailable], input("hello")) - .await - .expect("evaluate"); - assert!(!outcome.allowed); - assert!(outcome.reason.starts_with("middleware_failed:")); + for (stage, body, kind, reason) in [ + ( + missing, + b"hello".as_slice(), + HttpRequestFailureKind::Unavailable, + "binding_not_described", + ), + ( + entry("redact", OnError::FailClosed), + &[0xff], + HttpRequestFailureKind::InProcessService, + "requires UTF-8 request bodies", + ), + ] { + for on_error in [OnError::FailOpen, OnError::FailClosed] { + let outcome = runner + .evaluate( + &[ChainEntry { + on_error, + ..stage.clone() + }], + HttpRequestInput { + body: body.to_vec(), + ..input("") + }, + ) + .await + .expect("evaluate middleware"); + let allowed = on_error == OnError::FailOpen; + assert_eq!(outcome.allowed, allowed); + assert_eq!(outcome.body, body); + assert_eq!(outcome.failure_kind, (!allowed).then_some(kind)); + assert_eq!(outcome.applied[0].failure_kind, Some(kind)); + if !allowed { + assert!(outcome.reason.starts_with("middleware_failed:")); + assert!(outcome.reason.contains(reason)); + } + } + } } #[tokio::test] @@ -3608,6 +3710,10 @@ mod tests { .expect("policy evaluator failure should be a chain outcome"); assert!(!outcome.allowed); + assert_eq!( + outcome.failure_kind, + Some(HttpRequestFailureKind::PolicyEvaluation) + ); assert!( outcome .reason @@ -4714,6 +4820,10 @@ mod tests { .await .expect("operator timeout outcome"); assert!(!outcome.allowed); + assert_eq!( + outcome.failure_kind, + Some(HttpRequestFailureKind::StageTimeout) + ); assert_eq!(outcome.reason, "middleware_failed: middleware_timeout"); } @@ -4773,12 +4883,21 @@ mod tests { .expect("bind test middleware"); let address = listener.local_addr().expect("test middleware address"); let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let (fail_requests, failure_enabled) = tokio::sync::watch::channel(false); let server = tonic::transport::Server::builder() - .add_service(SupervisorMiddlewareServer::new(ScriptedService { - manifest_name: "test/middleware".into(), - max_body_bytes: 4096, - result: allow_result(), - })) + .add_service(SupervisorMiddlewareServer::with_interceptor( + ScriptedService { + manifest_name: "test/middleware".into(), + max_body_bytes: 4096, + result: allow_result(), + }, + move |request: Request<()>| { + if *failure_enabled.borrow() { + return Err(tonic::Status::deadline_exceeded("service deadline")); + } + Ok(request) + }, + )) .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { let _ = shutdown_rx.await; }); @@ -4818,26 +4937,25 @@ mod tests { vec![registration.clone()] ); - let outcome = ChainRunner::from_registry(registry) - .evaluate( - &[ - ChainEntry { - name: "primary".into(), - implementation: "local-guard-service".into(), - order: 0, - config: prost_types::Struct::default(), - on_error: OnError::FailClosed, - }, - ChainEntry { - name: "secondary".into(), - implementation: "secondary-guard-service".into(), - order: 10, - config: prost_types::Struct::default(), - on_error: OnError::FailClosed, - }, - ], - input("hello"), - ) + let runner = ChainRunner::from_registry(registry); + let entries = [ + ChainEntry { + name: "primary".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }, + ChainEntry { + name: "secondary".into(), + implementation: "secondary-guard-service".into(), + order: 10, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }, + ]; + let outcome = runner + .evaluate(&entries, input("hello")) .await .expect("remote evaluation"); assert!(outcome.allowed); @@ -4845,6 +4963,21 @@ mod tests { assert_eq!(outcome.applied[0].implementation, registration.name); assert_eq!(outcome.applied[1].implementation, second_registration.name); + fail_requests.send_replace(true); + let failure = runner + .evaluate(&entries, input("hello")) + .await + .expect("remote status"); + assert!(!failure.allowed); + assert_eq!( + failure.failure_kind, + Some(HttpRequestFailureKind::RemoteStatus( + tonic::Code::DeadlineExceeded + )) + ); + assert_eq!(failure.applied[0].failure_kind, failure.failure_kind); + assert_eq!(failure.reason, "middleware_failed: middleware_timeout"); + let _ = shutdown_tx.send(()); server_task .await diff --git a/crates/openshell-supervisor-middleware/src/request_failure.rs b/crates/openshell-supervisor-middleware/src/request_failure.rs new file mode 100644 index 0000000000..82ddbce631 --- /dev/null +++ b/crates/openshell-supervisor-middleware/src/request_failure.rs @@ -0,0 +1,105 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Platform-owned failure causes, independent of service diagnostic text. + +/// Retains why HTTP request processing failed across middleware and relay layers. +/// +/// Explicit policy denials have no failure kind. Remote status codes are retained +/// without status messages or metadata, which may contain workload data. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum HttpRequestFailureKind { + StageTimeout, + ChainTimeout, + RequestBodyTimeout, + WholeBodyTimeout, + StreamIdleTimeout, + RemoteStatus(tonic::Code), + InProcessService, + Unavailable, + InvalidResult, + Capacity, + HeaderMutation, + Io, + Cancelled, + PolicyEvaluation, +} + +impl HttpRequestFailureKind { + pub(crate) fn of_platform_reason(reason: &str) -> Self { + match reason { + "middleware_timeout" => Self::StageTimeout, + "middleware_chain_timeout" => Self::ChainTimeout, + "middleware_body_timeout" => Self::WholeBodyTimeout, + "middleware_stall_timeout" => Self::StreamIdleTimeout, + "binding_not_described" => Self::Unavailable, + "head_input_over_capacity" + | "buffered_input_over_capacity" + | "buffered_output_over_capacity" + | "request_output_over_capacity" + | "session_capacity_exhausted" + | "diagnostics_reason_over_capacity" + | "diagnostics_findings_over_capacity" + | "diagnostics_metadata_over_capacity" + | "request_body_over_capacity" + | "request_config_over_capacity" + | "request_context_over_capacity" + | "request_target_over_capacity" + | "request_header_count_over_capacity" + | "request_header_bytes_over_capacity" + | "response_body_over_capacity" + | "response_reason_over_capacity" + | "header_mutation_count_over_capacity" + | "header_mutation_bytes_over_capacity" + | "response_findings_over_capacity" + | "response_finding_over_capacity" + | "response_metadata_count_over_capacity" + | "response_metadata_bytes_over_capacity" + | "response_envelope_over_capacity" => Self::Capacity, + "middleware_stream_closed" | "middleware_result_stream_closed" => Self::Io, + _ => Self::InvalidResult, + } + } + + /// Returns a fixed category safe for operator diagnostics and span attributes. + #[must_use] + pub const fn category(self) -> &'static str { + match self { + Self::StageTimeout + | Self::ChainTimeout + | Self::RequestBodyTimeout + | Self::WholeBodyTimeout + | Self::StreamIdleTimeout => "timeout", + Self::RemoteStatus(_) => "remote_status", + Self::InProcessService => "in_process_service", + Self::Unavailable => "unavailable", + Self::InvalidResult => "protocol", + Self::Capacity => "capacity", + Self::HeaderMutation => "header_mutation", + Self::Io => "io", + Self::Cancelled => "cancelled", + Self::PolicyEvaluation => "policy_evaluation", + } + } + + /// Identifies the platform deadline; a remote `DEADLINE_EXCEEDED` is a status. + #[must_use] + pub const fn deadline_scope(self) -> Option<&'static str> { + match self { + Self::StageTimeout => Some("stage"), + Self::ChainTimeout => Some("chain"), + Self::RequestBodyTimeout => Some("request_body"), + Self::WholeBodyTimeout => Some("whole_body"), + Self::StreamIdleTimeout => Some("stream_idle"), + _ => None, + } + } +} + +impl std::fmt::Display for HttpRequestFailureKind { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.category()) + } +} + +impl std::error::Error for HttpRequestFailureKind {} diff --git a/crates/openshell-supervisor-network/src/l7/middleware.rs b/crates/openshell-supervisor-network/src/l7/middleware.rs index 70f6985c1c..0ae2d5913d 100644 --- a/crates/openshell-supervisor-network/src/l7/middleware.rs +++ b/crates/openshell-supervisor-network/src/l7/middleware.rs @@ -15,8 +15,8 @@ use openshell_ocsf::{ }; use openshell_supervisor_middleware::{ ChainHttpHookVersion, HttpBodyInput, HttpBodyOutput, HttpFailureCode, HttpMiddlewareFailure, - HttpPipelineFinish, HttpRequestPipeline, HttpRequestPreflightInput, HttpStageDiagnostics, - MiddlewareFailureDetail, + HttpPipelineFinish, HttpRequestFailureKind, HttpRequestPipeline, HttpRequestPreflightInput, + HttpStageDiagnostics, MiddlewareFailureDetail, }; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; @@ -1297,6 +1297,7 @@ async fn apply_pipeline_middleware_chain( { Ok(unit) => unit, Err(_) if client.timed_out => return Err(BodyRunError::ClientTimeout), - Err(error) => return Err(BodyRunError::Client(error)), + Err(error) => { + let kind = if error.is::() { + HttpRequestFailureKind::Cancelled + } else { + HttpRequestFailureKind::Io + }; + return Err(BodyRunError::Client { kind, error }); + } }; let Some(unit) = unit else { break; @@ -1629,17 +1643,23 @@ impl RequestEvents { false, "middleware_cancelled: client_progress_timeout", None, - HttpStageDiagnostics::default(), + HttpStageDiagnostics { + failure_kind: Some(HttpRequestFailureKind::RequestBodyTimeout), + ..Default::default() + }, correlation, ); Ok(MiddlewareApplyResult::RequestTimeout) } - BodyRunError::Client(error) => { + BodyRunError::Client { kind, error } => { self.emit( false, "middleware_cancelled: request_body_read_failed", None, - HttpStageDiagnostics::default(), + HttpStageDiagnostics { + failure_kind: Some(kind), + ..Default::default() + }, correlation, ); Err(error) @@ -1650,6 +1670,7 @@ impl RequestEvents { /// A request body that request middleware streams to the upstream. pub struct RequestBodyStream { + pub(crate) delivery: super::request_delivery::RequestDelivery, reader: crate::l7::rest::RequestBodyReader, session: Option, events: RequestEvents, @@ -1734,11 +1755,13 @@ impl RequestBodyStream { if failure.end_reason == MiddlewareSessionEndReason::Cancellation && upstream_failed.load(Ordering::Acquire) => { + let mut diagnostics = *failure.diagnostics; + diagnostics.failure_kind = Some(HttpRequestFailureKind::Io); self.events.emit( false, "middleware_cancelled: upstream_write_failed", None, - *failure.diagnostics, + diagnostics, correlation, ); return Err(miette!("upstream stopped accepting the request body")); @@ -1747,12 +1770,16 @@ impl RequestBodyStream { }; let failure = match &error { BodyRunError::Middleware(failure) => crate::l7::rest::LiveRequestFailure::Middleware { + kind: failure.kind, + delivery: self.delivery.clone(), reason: failure.reason.clone(), denial: failure.denial.clone(), failure: failure.failure.as_deref().cloned(), }, - BodyRunError::ClientTimeout => crate::l7::rest::LiveRequestFailure::ClientTimeout, - BodyRunError::Client(_) => { + BodyRunError::ClientTimeout => crate::l7::rest::LiveRequestFailure::ClientTimeout { + delivery: self.delivery.clone(), + }, + BodyRunError::Client { .. } => { return self .events .body_failed(error, correlation) @@ -1773,7 +1800,10 @@ impl RequestBodyStream { false, &format!("middleware_cancelled: {reason}"), None, - HttpStageDiagnostics::default(), + HttpStageDiagnostics { + failure_kind: Some(HttpRequestFailureKind::Cancelled), + ..Default::default() + }, correlation, ); } @@ -1790,7 +1820,6 @@ pub(super) fn request_middleware_events( denial: Option<&openshell_supervisor_middleware::MiddlewareDenial>, diagnostics: &HttpStageDiagnostics, ) -> Vec { - let applied = diagnostics.applied(); let req = crate::l7::provider::L7Request { action: action.to_string(), target: target.to_string(), @@ -1801,19 +1830,29 @@ pub(super) fn request_middleware_events( middleware_events( ctx, &req, - &openshell_supervisor_middleware::ChainOutcome { - allowed, - reason: reason.to_string(), - body: Vec::new(), - header_mutations: Vec::new(), - findings: diagnostics.findings.clone(), - metadata: diagnostics.metadata.clone(), - applied, - denial: denial.cloned(), - }, + &request_middleware_outcome(allowed, reason, denial, diagnostics), ) } +fn request_middleware_outcome( + allowed: bool, + reason: &str, + denial: Option<&openshell_supervisor_middleware::MiddlewareDenial>, + diagnostics: &HttpStageDiagnostics, +) -> openshell_supervisor_middleware::ChainOutcome { + openshell_supervisor_middleware::ChainOutcome { + failure_kind: diagnostics.failure_kind, + allowed, + reason: reason.to_string(), + body: Vec::new(), + header_mutations: Vec::new(), + findings: diagnostics.findings.clone(), + metadata: diagnostics.metadata.clone(), + applied: diagnostics.applied(), + denial: denial.cloned(), + } +} + /// The sandbox stopped sending a request body that DUPLEX request /// middleware was processing; the request was aborted. pub(super) fn request_client_timeout_event( @@ -1857,7 +1896,10 @@ pub(super) fn mixed_protocol_events( target: &str, chain: &[openshell_supervisor_middleware::DescribedChainEntry], ) -> Vec { - let mut diagnostics = HttpStageDiagnostics::default(); + let mut diagnostics = HttpStageDiagnostics { + failure_kind: Some(HttpRequestFailureKind::InvalidResult), + ..Default::default() + }; if let Some(entry) = chain.iter().find(|entry| { entry.http_hook_version() == Some(openshell_supervisor_middleware::HttpHookVersion::Current) }) { @@ -1866,6 +1908,7 @@ pub(super) fn mixed_protocol_events( .push(openshell_supervisor_middleware::HttpStageInvocation { config_name: entry.config_name().to_string(), implementation: entry.implementation().to_string(), + failure_kind: Some(HttpRequestFailureKind::InvalidResult), outcome: openshell_supervisor_middleware::HttpStageOutcome::FailClosed, input_bytes: 0, output_bytes: None, @@ -2363,6 +2406,7 @@ mod trace_tests { findings: Vec, ) -> ChainOutcome { ChainOutcome { + failure_kind: None, allowed, reason: reason.to_string(), body: vec![], @@ -2498,6 +2542,7 @@ mod trace_tests { true, "", vec![MiddlewareInvocation { + failure_kind: None, name: "redact".into(), implementation: "test/redact".into(), decision: openshell_core::proto::Decision::Allow, @@ -2587,6 +2632,7 @@ mod trace_tests { for allowed in [true, false] { let (events, received) = exported("warn", || { let invocation = MiddlewareInvocation { + failure_kind: None, name: "guard".to_string(), implementation: "test/guard".to_string(), decision: if allowed { @@ -3293,3 +3339,92 @@ mod tests { } } } + +#[cfg(test)] +mod failure_cause_tests { + use super::*; + + #[tokio::test] + async fn body_read_preserves_generation_and_client_errors() { + use crate::policy_types::{StalePolicyGeneration, generation_guard_for}; + use std::sync::atomic::AtomicU64; + + let generation = Arc::new(AtomicU64::new(1)); + let (tx, _) = tokio::sync::watch::channel(1); + let guard = generation_guard_for(1, 1, &generation, &tx).unwrap(); + generation.store(2, Ordering::Release); + + // A successful read reaches the stale-policy check. EOF fails before it. + for (mut client, expected_kind, expected_message) in [ + ( + b"x".as_slice(), + HttpRequestFailureKind::Cancelled, + "policy generation is stale [captured_generation:1 current_generation:2]", + ), + ( + b"".as_slice(), + HttpRequestFailureKind::Io, + "connection closed before the request body ended", + ), + ] { + let mut reader = crate::l7::rest::RequestBodyReader::Fixed { + buffered: Vec::new(), + position: 0, + remaining: 1, + }; + let (input, _receiver) = mpsc::channel(1); + let Err(failure @ BodyRunError::Client { kind, .. }) = + feed_request_body(&mut reader, &mut client, &guard, 1, None, input).await + else { + panic!("expected a body read failure"); + }; + assert_eq!(kind, expected_kind); + let mut events = RequestEvents { + context: L7EvalContext::default(), + action: "POST".into(), + target: "/".into(), + preflight: HttpStageDiagnostics::default(), + terminal_reason: None, + span: None, + }; + let error = events.body_failed(failure, None).err().unwrap(); + assert_eq!(error.to_string(), expected_message); + assert_eq!( + error.is::(), + kind == HttpRequestFailureKind::Cancelled + ); + } + } + + #[test] + fn request_terminal_cause_survives_successful_stage_records() { + for kind in [ + HttpRequestFailureKind::RequestBodyTimeout, + HttpRequestFailureKind::Cancelled, + ] { + let diagnostics = HttpStageDiagnostics { + failure_kind: Some(kind), + invocations: vec![openshell_supervisor_middleware::HttpStageInvocation { + failure_kind: None, + config_name: "guard".into(), + implementation: "test/guard".into(), + outcome: openshell_supervisor_middleware::HttpStageOutcome::Duplex, + input_bytes: 0, + output_bytes: None, + transformed: false, + failed: false, + reason_code: None, + failure_reason: None, + }], + ..Default::default() + }; + let outcome = + request_middleware_outcome(false, "unchanged diagnostic", None, &diagnostics); + assert_eq!(outcome.failure_kind, Some(kind)); + assert!(!outcome.allowed); + assert!(outcome.denial.is_none()); + assert!(!outcome.applied[0].failed); + assert_eq!(outcome.applied[0].failure_kind, None); + } + } +} diff --git a/crates/openshell-supervisor-network/src/l7/mod.rs b/crates/openshell-supervisor-network/src/l7/mod.rs index 2e3419bdc5..d23509e9bf 100644 --- a/crates/openshell-supervisor-network/src/l7/mod.rs +++ b/crates/openshell-supervisor-network/src/l7/mod.rs @@ -17,6 +17,7 @@ pub(crate) mod middleware; pub mod path; pub mod provider; pub mod relay; +pub(crate) mod request_delivery; mod request_trace; pub mod rest; pub mod tls; diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 4512dce4cb..7f0fad468d 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -1257,7 +1257,7 @@ async fn reject_live_request_body( .await?; } } - crate::l7::rest::LiveRequestFailure::ClientTimeout => { + crate::l7::rest::LiveRequestFailure::ClientTimeout { .. } => { if let Some(correlation) = correlation { correlation.record_rejection( 408, @@ -9670,6 +9670,7 @@ network_policies: body_length: crate::l7::provider::BodyLength::None, }; let outcome = ChainOutcome { + failure_kind: None, allowed: true, reason: String::new(), // The transformed body still holds the raw secret; emission must never @@ -9688,6 +9689,7 @@ network_policies: }], metadata: BTreeMap::new(), applied: vec![MiddlewareInvocation { + failure_kind: None, name: "regex-redactor".into(), implementation: "openshell/regex".into(), decision: openshell_core::proto::Decision::Allow, @@ -9763,6 +9765,7 @@ network_policies: ); let denied_outcome = ChainOutcome { + failure_kind: None, allowed: false, reason: "middleware_denied:content-guard:content_match".into(), body: Vec::new(), @@ -9770,6 +9773,7 @@ network_policies: findings: Vec::new(), metadata: BTreeMap::new(), applied: vec![MiddlewareInvocation { + failure_kind: None, name: "content-guard".into(), implementation: "example/content-guard".into(), decision: openshell_core::proto::Decision::Deny, diff --git a/crates/openshell-supervisor-network/src/l7/request_delivery.rs b/crates/openshell-supervisor-network/src/l7/request_delivery.rs new file mode 100644 index 0000000000..e4e99e2c68 --- /dev/null +++ b/crates/openshell-supervisor-network/src/l7/request_delivery.rs @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Observes local upstream writes without deciding whether a request is allowed. + +use std::sync::{ + Arc, + atomic::{AtomicU8, Ordering}, +}; + +/// Local forwarding progress; completion does not prove upstream processing. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RequestDeliveryState { + NotStarted, + Started, + Completed, +} + +/// Shared by the body runner and its writer so cancellation retains progress. +#[derive(Clone, Default)] +pub struct RequestDelivery(Arc); + +impl std::fmt::Debug for RequestDelivery { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.state().fmt(formatter) + } +} + +impl RequestDelivery { + /// Call before awaiting a write, because an error can follow a partial write. + pub(crate) fn start(&self) { + let _ = self + .0 + .compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire); + } + + /// Call after the body, framing and final upstream flush succeed. + pub(crate) fn complete(&self) { + self.0.store(2, Ordering::Release); + } + + pub(crate) fn state(&self) -> RequestDeliveryState { + match self.0.load(Ordering::Acquire) { + 0 => RequestDeliveryState::NotStarted, + 1 => RequestDeliveryState::Started, + // Only start and complete can write this private atomic. + _ => RequestDeliveryState::Completed, + } + } +} diff --git a/crates/openshell-supervisor-network/src/l7/rest/http_response/http_hooks.rs b/crates/openshell-supervisor-network/src/l7/rest/http_response/http_hooks.rs index 3e638c042a..9913c947ce 100644 --- a/crates/openshell-supervisor-network/src/l7/rest/http_response/http_hooks.rs +++ b/crates/openshell-supervisor-network/src/l7/rest/http_response/http_hooks.rs @@ -1096,6 +1096,7 @@ mod tests { 200, &HttpStageDiagnostics { invocations: vec![HttpStageInvocation { + failure_kind: None, config_name: "guard".into(), implementation: "test/guard".into(), outcome, @@ -1240,6 +1241,7 @@ mod tests { }; let diagnostics = HttpStageDiagnostics { invocations: vec![HttpStageInvocation { + failure_kind: None, config_name: "guard".into(), implementation: "test/guard".into(), outcome: HttpStageOutcome::Deny, diff --git a/crates/openshell-supervisor-network/src/l7/rest/request_body.rs b/crates/openshell-supervisor-network/src/l7/rest/request_body.rs index eb0069532c..c1e22b5dce 100644 --- a/crates/openshell-supervisor-network/src/l7/rest/request_body.rs +++ b/crates/openshell-supervisor-network/src/l7/rest/request_body.rs @@ -11,8 +11,9 @@ use std::sync::atomic::{AtomicBool, Ordering}; +use crate::l7::request_delivery::{RequestDelivery, RequestDeliveryState}; use futures::FutureExt as _; -use openshell_supervisor_middleware::{HttpBodyOutput, HttpPipelineFinish}; +use openshell_supervisor_middleware::{HttpBodyOutput, HttpPipelineFinish, HttpRequestFailureKind}; use super::*; @@ -541,22 +542,31 @@ fn commit_live_head( pub enum LiveRequestFailure { /// Request middleware rejected or failed the body. #[error("{reason}")] + #[diagnostic(help("local upstream delivery: {delivery:?}"))] Middleware { + #[source] + kind: Option, + delivery: RequestDelivery, reason: String, denial: Option, failure: Option, }, /// The sandbox stopped sending the request body. #[error("request body client progress timeout")] - ClientTimeout, + #[diagnostic(help("local upstream delivery: {delivery:?}"))] + ClientTimeout { delivery: RequestDelivery }, } /// The upstream stopped accepting the request body. It may have answered /// before it stopped reading, for example with 413. #[derive(Debug, thiserror::Error, miette::Diagnostic)] -#[error("upstream stopped accepting the request body: {detail}")] +#[error("{detail}")] +#[diagnostic(help("local upstream delivery: {delivery:?}"))] pub struct UpstreamWriteFailed { + #[source] + kind: HttpRequestFailureKind, detail: String, + delivery: RequestDeliveryState, } /// Upstream write half that records whether a write failed. @@ -565,6 +575,7 @@ struct UpstreamWrites<'a, W> { failed: &'a AtomicBool, correlation: Option<&'a RequestCorrelation>, request_span: Option, + delivery: &'a RequestDelivery, } impl UpstreamWrites<'_, W> { @@ -586,6 +597,9 @@ impl AsyncWrite for UpstreamWrites<'_, W> { buf: &[u8], ) -> std::task::Poll> { let this = self.get_mut(); + if !buf.is_empty() { + this.delivery.start(); + } let span = this.request_span.get_or_insert_with(|| { this.correlation .map_or_else(tracing::Span::none, |correlation| { @@ -748,7 +762,7 @@ where } return Err(error); } - upstream_writer.flush().await.into_diagnostic()?; + flush_live_upload(&mut upstream_writer, &body.delivery).await?; response.await } responded = response.as_mut() => { @@ -789,11 +803,13 @@ where U: AsyncWrite + Unpin, { let failed = AtomicBool::new(false); + let delivery = body.delivery.clone(); let mut upstream = UpstreamWrites { inner: upstream, failed: &failed, correlation, request_span: None, + delivery: &delivery, }; let uploaded = upload_live_body( head, @@ -808,13 +824,32 @@ where match uploaded { Err(error) if failed.load(Ordering::Acquire) => { Err(miette::Report::new(UpstreamWriteFailed { - detail: error.to_string(), + kind: HttpRequestFailureKind::Io, + detail: format!("upstream stopped accepting the request body: {error}"), + delivery: delivery.state(), })) } uploaded => uploaded, } } +// Keep the final flush after the upload wins the race against the response. +async fn flush_live_upload( + upstream: &mut U, + delivery: &RequestDelivery, +) -> Result<()> { + upstream + .flush() + .await + .map_err(|error| UpstreamWriteFailed { + kind: HttpRequestFailureKind::Io, + detail: error.to_string(), + delivery: delivery.state(), + })?; + delivery.complete(); + Ok(()) +} + async fn upload_live_body( head: &[u8], body: &mut crate::l7::middleware::RequestBodyStream, @@ -1013,20 +1048,73 @@ mod tests { #[tokio::test] async fn upstream_writes_record_a_failed_write() { - let (mut upstream, peer) = tokio::io::duplex(16); - drop(peer); - let failed = AtomicBool::new(false); - let mut writes = UpstreamWrites { - inner: &mut upstream, - failed: &failed, - correlation: None, - request_span: None, - }; - writes - .write_all(b"body") - .await - .expect_err("the upstream closed"); - assert!(failed.load(Ordering::Acquire)); + for write_prefix in [false, true] { + let (mut upstream, mut peer) = tokio::io::duplex(2); + let failed = AtomicBool::new(false); + let delivery = RequestDelivery::default(); + let mut writes = UpstreamWrites { + inner: &mut upstream, + failed: &failed, + correlation: None, + request_span: None, + delivery: &delivery, + }; + assert_eq!(delivery.state(), RequestDeliveryState::NotStarted); + let mut write = std::pin::pin!(writes.write_all(b"POST / HTTP/1.1\r\n\r\n")); + if write_prefix { + assert!(write.as_mut().now_or_never().is_none()); + let mut prefix = [0; 2]; + peer.read_exact(&mut prefix) + .now_or_never() + .expect("the first two bytes are ready") + .unwrap(); + assert_eq!(&prefix, b"PO"); + } + drop(peer); + write.await.expect_err("the upstream closed"); + assert!(failed.load(Ordering::Acquire)); + assert_eq!(delivery.state(), RequestDeliveryState::Started); + } + } + + #[tokio::test] + async fn live_delivery_completes_only_after_the_buffered_writer_flushes() { + for close_before_flush in [true, false] { + let (upstream, peer) = tokio::io::duplex(32); + let mut upstream = tokio::io::BufWriter::new(upstream); + let delivery = RequestDelivery::default(); + let failed = AtomicBool::new(false); + // The body runner can time out while an output frame is still queued. + let failure = LiveRequestFailure::ClientTimeout { + delivery: delivery.clone(), + }; + let mut writes = UpstreamWrites { + inner: &mut upstream, + failed: &failed, + correlation: None, + request_span: None, + delivery: &delivery, + }; + writes.write_all(b"queued head").await.unwrap(); + assert_eq!( + miette::Diagnostic::help(&failure).unwrap().to_string(), + "local upstream delivery: Started" + ); + + if close_before_flush { + drop(peer); + let error = flush_live_upload(&mut upstream, &delivery) + .await + .unwrap_err(); + let error = error.downcast_ref::().unwrap(); + assert_eq!(error.kind, HttpRequestFailureKind::Io); + assert_eq!(error.delivery, RequestDeliveryState::Started); + assert_eq!(delivery.state(), RequestDeliveryState::Started); + } else { + flush_live_upload(&mut upstream, &delivery).await.unwrap(); + assert_eq!(delivery.state(), RequestDeliveryState::Completed); + } + } } #[tokio::test] diff --git a/docs/extensibility/supervisor-middleware/operations.mdx b/docs/extensibility/supervisor-middleware/operations.mdx index b89fe5a51a..89ddc84f72 100644 --- a/docs/extensibility/supervisor-middleware/operations.mdx +++ b/docs/extensibility/supervisor-middleware/operations.mdx @@ -148,6 +148,8 @@ Denials include the policy entry's `middleware` name and the validated `reason_c | `middleware_hook_versions_mixed` | The chain mixed HTTP hook versions. | No free-form service error text reaches the sandbox. If evaluation capacity remains full for the chain budget, OpenShell returns `503 Service Unavailable`. A stalled request upload receives `408 Request Timeout` with `error: request_timeout`. +The runtime distinguishes local request deadlines from remote gRPC status codes. +For live uploads, it records the first upstream write attempt and final flush.