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/diagnostics.rs b/crates/openshell-supervisor-middleware/src/diagnostics.rs index a7d4f0e421..33ae6debe1 100644 --- a/crates/openshell-supervisor-middleware/src/diagnostics.rs +++ b/crates/openshell-supervisor-middleware/src/diagnostics.rs @@ -4,23 +4,28 @@ use crate::{ EXTERNAL_FINDING_LABEL, MAX_MIDDLEWARE_FINDING_BYTES, MAX_MIDDLEWARE_FINDINGS_PER_STAGE, MAX_MIDDLEWARE_METADATA_BYTES, MAX_MIDDLEWARE_METADATA_ENTRIES, MAX_MIDDLEWARE_REASON_BYTES, - MAX_MIDDLEWARE_REASON_CODE_BYTES, MiddlewareDiagnosticPolicy, is_stable_reason_code, + MAX_MIDDLEWARE_REASON_CODE_BYTES, MiddlewareDiagnosticPolicy, PlatformFailure, + is_stable_reason_code, }; use openshell_core::proto::MiddlewareDiagnostics; use prost::Message; pub fn validate_diagnostics( diagnostics: Option<&MiddlewareDiagnostics>, -) -> Result { +) -> Result { let diagnostics = diagnostics.cloned().unwrap_or_default(); if diagnostics.reason.len() > MAX_MIDDLEWARE_REASON_BYTES { - return Err("diagnostics_reason_over_capacity"); + return Err(PlatformFailure::Capacity( + "diagnostics_reason_over_capacity", + )); } if !diagnostics.reason_code.is_empty() && (diagnostics.reason_code.len() > MAX_MIDDLEWARE_REASON_CODE_BYTES || !is_stable_reason_code(&diagnostics.reason_code)) { - return Err("diagnostics_reason_code_invalid"); + return Err(PlatformFailure::InvalidResult( + "diagnostics_reason_code_invalid", + )); } if diagnostics.findings.len() > MAX_MIDDLEWARE_FINDINGS_PER_STAGE || diagnostics @@ -28,7 +33,9 @@ pub fn validate_diagnostics( .iter() .any(|finding| finding.encoded_len() > MAX_MIDDLEWARE_FINDING_BYTES) { - return Err("diagnostics_findings_over_capacity"); + return Err(PlatformFailure::Capacity( + "diagnostics_findings_over_capacity", + )); } if diagnostics.metadata.len() > MAX_MIDDLEWARE_METADATA_ENTRIES || diagnostics @@ -38,7 +45,9 @@ pub fn validate_diagnostics( .fold(0usize, usize::saturating_add) > MAX_MIDDLEWARE_METADATA_BYTES { - return Err("diagnostics_metadata_over_capacity"); + return Err(PlatformFailure::Capacity( + "diagnostics_metadata_over_capacity", + )); } Ok(diagnostics) } diff --git a/crates/openshell-supervisor-middleware/src/http_hooks/mod.rs b/crates/openshell-supervisor-middleware/src/http_hooks/mod.rs index e0a6a671b2..b634e492ca 100644 --- a/crates/openshell-supervisor-middleware/src/http_hooks/mod.rs +++ b/crates/openshell-supervisor-middleware/src/http_hooks/mod.rs @@ -32,6 +32,7 @@ pub use response::{HttpResponseDelivery, HttpResponsePipeline, HttpResponsePipel use crate::{ DescribedChainEntry, HttpHookVersion, MAX_MIDDLEWARE_CONTEXT_BYTES, MAX_MIDDLEWARE_HEADER_BYTES, MAX_MIDDLEWARE_HEADERS, MAX_MIDDLEWARE_TARGET_BYTES, + PlatformFailure, }; /// HTTP hook version a described chain runs on. @@ -95,17 +96,17 @@ fn validate_head_input( context: &RequestContext, target: &HttpRequestTarget, headers: &[HttpHeader], -) -> Result<(), &'static str> { +) -> Result<(), PlatformFailure> { if context.encoded_len() > MAX_MIDDLEWARE_CONTEXT_BYTES || target.encoded_len() > MAX_MIDDLEWARE_TARGET_BYTES { - return Err("head_input_over_capacity"); + return Err(PlatformFailure::HeadInputOverCapacity); } validate_header_input(headers) } /// Platform limits on one header list shown to every stage. -fn validate_header_input(headers: &[HttpHeader]) -> Result<(), &'static str> { +fn validate_header_input(headers: &[HttpHeader]) -> Result<(), PlatformFailure> { if headers.len() > MAX_MIDDLEWARE_HEADERS || headers .iter() @@ -113,7 +114,7 @@ fn validate_header_input(headers: &[HttpHeader]) -> Result<(), &'static str> { .fold(0usize, usize::saturating_add) > MAX_MIDDLEWARE_HEADER_BYTES { - return Err("head_input_over_capacity"); + return Err(PlatformFailure::HeadInputOverCapacity); } 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..e32caa8650 100644 --- a/crates/openshell-supervisor-middleware/src/http_hooks/pipeline.rs +++ b/crates/openshell-supervisor-middleware/src/http_hooks/pipeline.rs @@ -39,12 +39,13 @@ use openshell_core::proto::{ http_response_hook_event, http_whole_body_result, }; +use crate::PlatformFailure::{BodyOverLimit, InvalidResult, StreamClosed}; 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, PlatformFailure, TransformedBodyPolicy, middleware_denial_reason, safe_reason, }; /// Largest normalized body chunk a stage sends or receives. @@ -113,26 +114,6 @@ impl HttpFailureCode { Self::HookVersionsMixed => MIDDLEWARE_HOOK_VERSIONS_MIXED, } } - - /// Code for a platform-owned failure reason that is not an RPC status or - /// a header mutation error. - fn of_reason(reason: &str) -> Self { - match reason { - MIDDLEWARE_CANNOT_INSPECT - | "head_input_over_capacity" - | "response_input_unrepresentable" => Self::CannotInspect, - "middleware_timeout" | "middleware_chain_timeout" | "middleware_body_timeout" => { - Self::Timeout - } - "middleware_stall_timeout" => Self::StreamIdleTimeout, - "binding_not_described" | "session_capacity_exhausted" => Self::Unavailable, - "buffered_input_over_capacity" - | "buffered_output_over_capacity" - | "request_output_over_capacity" => Self::BodyOverLimit, - MIDDLEWARE_HOOK_VERSIONS_MIXED => Self::HookVersionsMixed, - _ => Self::LifecycleViolation, - } - } } /// Why a chain failed closed, as the sandbox sees it. Both fields are @@ -197,6 +178,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 +196,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 +206,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 +234,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 +245,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 +274,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. @@ -704,10 +694,10 @@ pub(super) async fn open_stage( entry: &DescribedChainEntry, preflight: StagePreflight, deadline: Instant, - timeout_reason: &str, + timeout_reason: PlatformFailure, ) -> Result<(StageStream, FirstResult), HttpMiddlewareFailure> { let Some(service) = entry.service.as_ref() else { - return Err(entry_failure(entry, "binding_not_described")); + return Err(entry_failure(entry, PlatformFailure::BindingNotDescribed)); }; let closed = || tonic::Status::unavailable("middleware stage stream closed"); let opened = tokio::time::timeout_at(deadline, async { @@ -764,12 +754,12 @@ pub(super) async fn open_stage( pub(super) fn preflight_deadline( entry: &DescribedChainEntry, chain_deadline: Instant, -) -> (Instant, &'static str) { +) -> (Instant, PlatformFailure) { let stage_deadline = Instant::now() + entry.timeout(); if chain_deadline <= stage_deadline { - (chain_deadline, "middleware_chain_timeout") + (chain_deadline, PlatformFailure::ChainTimeout) } else { - (stage_deadline, "middleware_timeout") + (stage_deadline, PlatformFailure::StageTimeout) } } @@ -815,9 +805,10 @@ async fn prepare_stage( if !entry.is_resolved() { if entry.on_error() == OnError::FailOpen { let mut diagnostics = HttpStageDiagnostics::default(); - diagnostics - .invocations - .push(fail_open_invocation(entry, "binding_not_described")); + diagnostics.invocations.push(fail_open_invocation( + entry, + PlatformFailure::BindingNotDescribed, + )); return Ok(PreparedStage { headers: input_headers.to_vec(), header_mutations: Vec::new(), @@ -825,10 +816,10 @@ async fn prepare_stage( stage: None, }); } - return Err(entry_failure(entry, "binding_not_described")); + return Err(entry_failure(entry, PlatformFailure::BindingNotDescribed)); } if entry.http_hook_version() != Some(HttpHookVersion::Current) { - return Err(entry_failure(entry, MIDDLEWARE_HOOK_VERSIONS_MIXED)); + return Err(entry_failure(entry, PlatformFailure::HookVersionsMixed)); } let offer = head.body_modes(entry, input_headers, declared_body_bytes); let permitted = offer.permitted.clone(); @@ -846,7 +837,12 @@ async fn prepare_stage( let result = match classify_result(entry, first)? { StageResult::PreflightResult(result) => result, StageResult::Deny(deny) => return Err(denial(entry, deny.diagnostics.as_ref())), - _ => return Err(entry_failure(entry, "preflight_result_expected")), + _ => { + return Err(entry_failure( + entry, + InvalidResult("preflight_result_expected"), + )); + } }; let diagnostics = validate_diagnostics(entry, result.diagnostics.as_ref())?; let headers = spec @@ -855,16 +851,20 @@ async fn prepare_stage( let mode = match result.decision { Some(http_preflight_result::Decision::ContinueWithoutBody(_)) => None, Some(http_preflight_result::Decision::Inspect(inspect)) => { - let mode = inspect - .mode - .as_ref() - .ok_or_else(|| entry_failure(entry, "preflight_result_unknown"))?; + let mode = inspect.mode.as_ref().ok_or_else(|| { + entry_failure(entry, InvalidResult("preflight_result_unknown")) + })?; Some( validate_inspect(mode, &permitted, entry.max_payload_bytes()) .map_err(|reason| entry_failure(entry, reason))?, ) } - None => return Err(entry_failure(entry, "preflight_result_unknown")), + None => { + return Err(entry_failure( + entry, + InvalidResult("preflight_result_unknown"), + )); + } }; let mut retained = HttpStageDiagnostics::default(); let reason_code = nonempty(&diagnostics.reason_code); @@ -1293,21 +1293,19 @@ impl Pipeline { for stage in done.into_iter().flatten() { diagnostics.extend(stage.diagnostics); } - match (failure, trailers) { - (Some(mut failure), _) => { - diagnostics.extend(*failure.diagnostics); - failure.diagnostics = Box::new(diagnostics); - Err(failure) + let mut failure = match (failure, trailers) { + (Some(failure), _) => failure, + (None, None) => cancelled("pipeline_incomplete"), + (None, Some(trailers)) => { + return Ok(HttpPipelineFinish { + trailers, + diagnostics, + }); } - (None, None) => Err(HttpMiddlewareFailure { - diagnostics: Box::new(diagnostics), - ..cancelled("pipeline_incomplete") - }), - (None, Some(trailers)) => Ok(HttpPipelineFinish { - trailers, - diagnostics, - }), - } + }; + diagnostics.extend(*failure.diagnostics); + *failure.diagnostics = diagnostics; + Err(failure) } } @@ -1539,16 +1537,16 @@ async fn run_checkpoint( if body.len().saturating_add(data.len()) > MAX_MIDDLEWARE_PAYLOAD_BYTES { return Err(TaskError::Failed(entry_failure( &entry, - "request_output_over_capacity", + BodyOverLimit("request_output_over_capacity"), ))); } body.extend_from_slice(&data); } Some(Frame::End(trailers)) if start.is_some() => break trailers, Some(_) => { - return Err(TaskError::Failed(platform_failure( + return Err(TaskError::Failed(platform_failure(InvalidResult( "pipeline_event_order_invalid", - ))); + )))); } None => return Err(TaskError::Aborted), } @@ -1558,13 +1556,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"); @@ -1621,9 +1623,9 @@ async fn run_sink( return Ok(TaskDone::Sink(trailers)); } Some(_) => { - return Err(TaskError::Failed(platform_failure( + return Err(TaskError::Failed(platform_failure(InvalidResult( "pipeline_event_order_invalid", - ))); + )))); } None => return Err(TaskError::Aborted), }; @@ -1732,7 +1734,9 @@ async fn drive_stage( header_mutations, output_body_bytes, }, - Some(_) => return Err(entry_failure(entry, "stage_input_order_invalid").into()), + Some(_) => { + return Err(entry_failure(entry, InvalidResult("stage_input_order_invalid")).into()); + } None => return Err(StageError::LinkClosed), }; let mut begin_head = shared @@ -1744,13 +1748,12 @@ async fn drive_stage( .head_source .current_headers(&begin_head, upstream.output_body_bytes); let deadline = Instant::now() + MAX_MIDDLEWARE_CHAIN_TIMEOUT; - *permit = Some( - shared - .admission - .acquire(deadline) - .await - .ok_or_else(|| entry_failure(entry, "session_capacity_exhausted"))?, - ); + *permit = + Some( + shared.admission.acquire(deadline).await.ok_or_else(|| { + entry_failure(entry, PlatformFailure::SessionCapacityExhausted) + })?, + ); let prepared = prepare_stage( entry, &shared.spec, @@ -1783,7 +1786,9 @@ async fn drive_stage( return Ok(StageDone::default()); } Some(Frame::Start { .. }) => { - return Err(entry_failure(entry, "stage_input_order_invalid").into()); + return Err( + entry_failure(entry, InvalidResult("stage_input_order_invalid")).into(), + ); } None => return Err(StageError::LinkClosed), } @@ -1825,10 +1830,13 @@ async fn send_until( stream: &mut StageStream, event: StageEvent, deadline: Option, - timeout_reason: &str, + timeout_reason: PlatformFailure, ) -> Result<(), HttpMiddlewareFailure> { let Some(sender) = stream.sender.as_ref() else { - return Err(entry_failure(entry, "middleware_stream_closed")); + return Err(entry_failure( + entry, + StreamClosed("middleware_stream_closed"), + )); }; let sent = match deadline { Some(deadline) => tokio::time::timeout_at(deadline, sender.send(event)) @@ -1853,7 +1861,7 @@ fn closed_stream_failure(entry: &DescribedChainEntry, next: FirstResult) -> Http match next { Some(Ok(Some(StageResult::Deny(deny)))) => denial(entry, deny.diagnostics.as_ref()), Some(Err(status)) => status_failure(entry, &status), - _ => entry_failure(entry, "middleware_stream_closed"), + _ => entry_failure(entry, StreamClosed("middleware_stream_closed")), } } @@ -1893,7 +1901,7 @@ async fn drive_buffered( headers: begin_head.clone(), }), Some(body_deadline), - "middleware_body_timeout", + PlatformFailure::WholeBodyTimeout, ) .await?; @@ -1903,19 +1911,25 @@ async fn drive_buffered( biased; frame = input.recv() => frame, () = tokio::time::sleep_until(body_deadline) => { - return Err(entry_failure(entry, "middleware_body_timeout").into()); + return Err(entry_failure(entry, PlatformFailure::WholeBodyTimeout).into()); } }; match frame { Some(Frame::Chunk(data)) => { if body.len().saturating_add(data.len()) > max_body_bytes { - return Err(entry_failure(entry, "buffered_input_over_capacity").into()); + return Err(entry_failure( + entry, + BodyOverLimit("buffered_input_over_capacity"), + ) + .into()); } body.extend_from_slice(&data); } Some(Frame::End(trailers)) => break trailers, Some(Frame::Start { .. }) => { - return Err(entry_failure(entry, "stage_input_order_invalid").into()); + return Err( + entry_failure(entry, InvalidResult("stage_input_order_invalid")).into(), + ); } None => return Err(StageError::LinkClosed), } @@ -1923,9 +1937,9 @@ async fn drive_buffered( let stage_deadline = Instant::now() + entry.timeout(); let (exchange_deadline, timeout_reason) = if stage_deadline < body_deadline { - (stage_deadline, "middleware_timeout") + (stage_deadline, PlatformFailure::StageTimeout) } else { - (body_deadline, "middleware_body_timeout") + (body_deadline, PlatformFailure::WholeBodyTimeout) }; let input_bytes = body.len(); let event = StageEvent::WholeBody(HttpWholeBody { @@ -1951,7 +1965,9 @@ async fn drive_buffered( StageResult::Deny(deny) => { return Err(denial(entry, deny.diagnostics.as_ref()).into()); } - _ => return Err(entry_failure(entry, "whole_body_result_expected").into()), + _ => { + return Err(entry_failure(entry, InvalidResult("whole_body_result_expected")).into()); + } }; let diagnostics = validate_diagnostics(entry, result.diagnostics.as_ref())?; let late_head = shared @@ -1969,11 +1985,15 @@ async fn drive_buffered( Some(http_whole_body_result::Body::Unchanged(_)) => (body, HttpStageOutcome::Unchanged), Some(http_whole_body_result::Body::Replacement(replacement)) => { if replacement.len() > max_body_bytes { - return Err(entry_failure(entry, "buffered_output_over_capacity").into()); + return Err( + entry_failure(entry, BodyOverLimit("buffered_output_over_capacity")).into(), + ); } (replacement, HttpStageOutcome::Replacement) } - None => return Err(entry_failure(entry, "whole_body_result_unknown").into()), + None => { + return Err(entry_failure(entry, InvalidResult("whole_body_result_unknown")).into()); + } }; let head_changed = late_head != begin_head; let transformed = outcome == HttpStageOutcome::Replacement; @@ -1995,7 +2015,7 @@ async fn drive_buffered( }; tokio::time::timeout_at(body_deadline, delivery) .await - .map_err(|_| entry_failure(entry, "middleware_body_timeout"))??; + .map_err(|_| entry_failure(entry, PlatformFailure::WholeBodyTimeout))??; let mut done = StageDone::default(); let reason_code = nonempty(&diagnostics.reason_code); collect_diagnostics(entry, diagnostics, &mut done.diagnostics); @@ -2009,15 +2029,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), )), } } @@ -2085,11 +2111,11 @@ async fn drive_stream( headers: begin_head.clone(), }), Some(Instant::now() + idle), - "middleware_stall_timeout", + PlatformFailure::StreamIdleTimeout, ) .await?; let Some(sender) = stream.sender.clone() else { - return Err(entry_failure(entry, "middleware_stream_closed").into()); + return Err(entry_failure(entry, StreamClosed("middleware_stream_closed")).into()); }; let chunk_limit = stage_chunk_limit(entry); // Trailers are published before InputEnd is sent: a Finish can race the @@ -2112,7 +2138,7 @@ async fn drive_stream( } Some(Frame::Start { .. }) => { return Err(InputStop::Failed( - entry_failure(entry, "stage_input_order_invalid").into(), + entry_failure(entry, InvalidResult("stage_input_order_invalid")).into(), )); } None => return Err(InputStop::Failed(StageError::LinkClosed)), @@ -2128,7 +2154,7 @@ async fn drive_stream( } Err(StallError::Stalled) => { return Err(InputStop::Failed( - entry_failure(entry, "middleware_stall_timeout").into(), + entry_failure(entry, PlatformFailure::StreamIdleTimeout).into(), )); } } @@ -2149,7 +2175,7 @@ async fn drive_stream( let next = if *input_delivered.borrow_and_update() { tokio::time::timeout(idle, results.next()) .await - .map_err(|_| entry_failure(entry, "middleware_stall_timeout"))? + .map_err(|_| entry_failure(entry, PlatformFailure::StreamIdleTimeout))? } else { // A stage may withhold output until all input arrives, so // there is no result timeout while input is still flowing. @@ -2179,12 +2205,27 @@ async fn drive_stream( held.send_replace(false); } StageResult::OutputChunk(chunk) if started => { - if chunk.data.is_empty() || chunk.data.len() > chunk_limit { - return Err(entry_failure(entry, "stream_output_chunk_invalid").into()); + if chunk.data.len() > chunk_limit { + return Err(entry_failure( + entry, + PlatformFailure::Capacity("stream_output_chunk_invalid"), + ) + .into()); + } + if chunk.data.is_empty() { + return Err(entry_failure( + entry, + InvalidResult("stream_output_chunk_invalid"), + ) + .into()); } output_bytes = output_bytes.saturating_add(chunk.data.len()); if declared.is_some_and(|declared| output_bytes as u64 > declared) { - return Err(entry_failure(entry, "stream_output_length_mismatch").into()); + return Err(entry_failure( + entry, + InvalidResult("stream_output_length_mismatch"), + ) + .into()); } held.send_replace(true); send_body(output, &chunk.data, output_limit).await?; @@ -2192,10 +2233,18 @@ async fn drive_stream( } StageResult::Finish(finish) if started => { let Some(trailers) = input_ended.borrow().clone() else { - return Err(entry_failure(entry, "stream_finish_before_input_end").into()); + return Err(entry_failure( + entry, + InvalidResult("stream_finish_before_input_end"), + ) + .into()); }; if declared.is_some_and(|declared| declared != output_bytes as u64) { - return Err(entry_failure(entry, "stream_output_length_mismatch").into()); + return Err(entry_failure( + entry, + InvalidResult("stream_output_length_mismatch"), + ) + .into()); } let diagnostics = validate_diagnostics(entry, finish.diagnostics.as_ref())?; let trailers = headers::apply( @@ -2211,12 +2260,21 @@ async fn drive_stream( StageResult::Deny(deny) => { return Err(denial(entry, deny.diagnostics.as_ref()).into()); } - _ => return Err(entry_failure(entry, "stream_result_order_invalid").into()), + _ => { + return Err( + entry_failure(entry, InvalidResult("stream_result_order_invalid")).into(), + ); + } } } }; - let closed = || StageError::from(entry_failure(entry, "middleware_stream_closed")); + let closed = || { + StageError::from(entry_failure( + entry, + StreamClosed("middleware_stream_closed"), + )) + }; let mut input_pump = std::pin::pin!(input_pump); let mut output_pump = std::pin::pin!(output_pump); let (input_bytes, (diagnostics, output_bytes)) = tokio::select! { @@ -2257,28 +2315,42 @@ pub(super) fn classify_result( ) -> Result { match next { Some(Ok(Some(result))) => Ok(result), - Some(Ok(None)) => Err(entry_failure(entry, "result_unknown")), + Some(Ok(None)) => Err(entry_failure(entry, InvalidResult("result_unknown"))), Some(Err(status)) => Err(status_failure(entry, &status)), - None => Err(entry_failure(entry, "middleware_result_stream_closed")), + None => Err(entry_failure( + entry, + StreamClosed("middleware_result_stream_closed"), + )), } } /// 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 Some(service) = entry.service.as_ref() else { + return entry_failure(entry, PlatformFailure::BindingNotDescribed); + }; + 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), + ) } fn diagnostic_policy(entry: &DescribedChainEntry) -> MiddlewareDiagnosticPolicy { @@ -2298,6 +2370,7 @@ fn mutation_failure( entry, &diagnostic_policy(entry).header_mutation_error_reason(error), HttpFailureCode::HeaderMutation(error.code()), + HttpRequestFailureKind::HeaderMutation, ) } @@ -2305,7 +2378,7 @@ fn validate_inspect( mode: &http_inspect::Mode, permitted: &[HttpBodyMode], buffered_limit: usize, -) -> Result { +) -> Result { match mode { http_inspect::Mode::WholeBody(mode) if permitted.contains(&HttpBodyMode::WholeBody) @@ -2314,13 +2387,13 @@ fn validate_inspect( { Ok(StageMode::WholeBody { max_body_bytes: usize::try_from(mode.max_body_bytes) - .map_err(|_| "body_mode_not_permitted")?, + .map_err(|_| InvalidResult("body_mode_not_permitted"))?, }) } http_inspect::Mode::Duplex(_) if permitted.contains(&HttpBodyMode::Duplex) => { Ok(StageMode::Duplex) } - _ => Err("body_mode_not_permitted"), + _ => Err(InvalidResult("body_mode_not_permitted")), } } @@ -2413,6 +2486,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, @@ -2422,8 +2496,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)) +pub(super) fn entry_failure( + entry: &DescribedChainEntry, + failure: PlatformFailure, +) -> HttpMiddlewareFailure { + let (reason, code, kind) = failure.details(); + entry_failure_with_code(entry, reason, code, kind) } /// The stage failed with `reason`, which the sandbox sees as `code`. @@ -2431,14 +2509,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 { @@ -2451,23 +2535,33 @@ fn entry_failure_with_code( } /// The exchange failed for a reason no single stage owns. -pub fn platform_failure(reason: &str) -> HttpMiddlewareFailure { +fn platform_failure(failure: PlatformFailure) -> HttpMiddlewareFailure { + let (reason, _, kind) = failure.details(); 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 +2571,7 @@ pub fn invocation( reason_code: Option, ) -> HttpStageInvocation { HttpStageInvocation { + failure_kind: None, config_name: entry.entry.name.clone(), implementation: entry.entry.implementation.clone(), outcome, @@ -2489,8 +2584,13 @@ pub fn invocation( } } -pub fn fail_open_invocation(entry: &DescribedChainEntry, reason: &str) -> HttpStageInvocation { +fn fail_open_invocation( + entry: &DescribedChainEntry, + failure: PlatformFailure, +) -> HttpStageInvocation { + let (reason, _, kind) = failure.details(); HttpStageInvocation { + failure_kind: Some(kind), 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..8fa1d22e01 100644 --- a/crates/openshell-supervisor-middleware/src/http_hooks/request.rs +++ b/crates/openshell-supervisor-middleware/src/http_hooks/request.rs @@ -263,11 +263,18 @@ impl ChainRunner { /// No HTTP hook buffering slot freed up within the chain deadline. fn capacity_exhausted(headers: Vec) -> HttpRequestPreflightOutcome { + let (reason, _, kind) = crate::PlatformFailure::SessionCapacityExhausted.details(); HttpRequestPreflightOutcome { allowed: false, - reason: "middleware_failed: session_capacity_exhausted".into(), + reason: format!("middleware_failed: {reason}"), session_capacity_exhausted: true, - ..outcome(headers, HttpStageDiagnostics::default()) + ..outcome( + headers, + HttpStageDiagnostics { + failure_kind: Some(kind), + ..Default::default() + }, + ) } } diff --git a/crates/openshell-supervisor-middleware/src/http_hooks/response.rs b/crates/openshell-supervisor-middleware/src/http_hooks/response.rs index ac90a04976..867e9fd02b 100644 --- a/crates/openshell-supervisor-middleware/src/http_hooks/response.rs +++ b/crates/openshell-supervisor-middleware/src/http_hooks/response.rs @@ -37,6 +37,7 @@ use super::pipeline::{ Pipeline, PipelineSpec, PipelineTimeouts, PreflightFields, StageHead, StagePreflight, }; use super::{has_content_coding, validate_head_input, validate_header_input}; +use crate::PlatformFailure; use crate::headers::HeaderAuthority; use crate::{ ChainRunner, DescribedChainEntry, HttpResponsePreflightInput, MAX_MIDDLEWARE_CHAIN_TIMEOUT, @@ -397,7 +398,11 @@ impl ChainRunner { &self, described: &[DescribedChainEntry], ) -> HttpResponsePipelinePreflight { - chain_failure(described, Vec::new(), "response_input_unrepresentable") + chain_failure( + described, + Vec::new(), + PlatformFailure::ResponseInputUnrepresentable, + ) } } @@ -421,9 +426,10 @@ fn outcome( fn chain_failure( entries: &[DescribedChainEntry], headers: Vec, - reason: &str, + reason: PlatformFailure, ) -> HttpResponsePipelinePreflight { let Some(entry) = entries.first() else { + let (reason, _, _) = reason.details(); return HttpResponsePipelinePreflight { allowed: false, reason: format!("middleware_failed: {reason}"), @@ -451,7 +457,7 @@ fn capacity_exhausted( config_name: None, code: HttpFailureCode::Unavailable, }), - ..chain_failure(entries, headers, "session_capacity_exhausted") + ..chain_failure(entries, headers, PlatformFailure::SessionCapacityExhausted) } } diff --git a/crates/openshell-supervisor-middleware/src/http_hooks/tests.rs b/crates/openshell-supervisor-middleware/src/http_hooks/tests.rs index 5b2f652398..3310eda662 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,110 @@ 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, + }; + use crate::PlatformFailure as Failure; 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 (cause, code, kind) in [ + (Failure::HeadInputOverCapacity, cannot_inspect, Capacity), ( - "response_input_unrepresentable", - "middleware_cannot_inspect", + Failure::ResponseInputUnrepresentable, + cannot_inspect, + InvalidResult, ), - ("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"), + (Failure::StageTimeout, timeout, StageTimeout), + (Failure::ChainTimeout, timeout, ChainTimeout), + (Failure::WholeBodyTimeout, timeout, WholeBodyTimeout), ( + Failure::StreamIdleTimeout, + "stream_idle_timeout", + StreamIdleTimeout, + ), + (Failure::BindingNotDescribed, unavailable, Unavailable), + (Failure::SessionCapacityExhausted, unavailable, Capacity), + ( + Failure::BodyOverLimit("buffered_input_over_capacity"), + body_limit, + Capacity, + ), + ( + Failure::BodyOverLimit("buffered_output_over_capacity"), + body_limit, + Capacity, + ), + ( + Failure::BodyOverLimit("request_output_over_capacity"), + body_limit, + Capacity, + ), + ( + Failure::HookVersionsMixed, "middleware_hook_versions_mixed", - "middleware_hook_versions_mixed", + InvalidResult, + ), + ( + Failure::StreamClosed("middleware_result_stream_closed"), + lifecycle, + Io, + ), + ( + Failure::InvalidResult("stream_output_length_mismatch"), + lifecycle, + InvalidResult, + ), + ( + Failure::InvalidResult("preflight_result_unknown"), + lifecycle, + InvalidResult, ), - ("middleware_unimplemented", "middleware_lifecycle_violation"), ( - "middleware_result_stream_closed", - "middleware_lifecycle_violation", + Failure::Capacity("diagnostics_reason_over_capacity"), + lifecycle, + Capacity, ), ( - "stream_output_length_mismatch", - "middleware_lifecycle_violation", + Failure::StreamClosed("middleware_stream_closed"), + lifecycle, + Io, ), - ("preflight_result_unknown", "middleware_lifecycle_violation"), ] { - 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], cause); + assert_eq!(failure.failure.unwrap().code.as_str(), code, "{cause:?}"); + assert_eq!(failure.kind, Some(kind), "{cause:?}"); + let mut diagnostics = crate::HttpStageDiagnostics { + failure_kind: Some(crate::HttpRequestFailureKind::RequestBodyTimeout), + ..Default::default() + }; + diagnostics.invocations.push(super::pipeline::invocation( + &described[0], + HttpStageOutcome::Duplex, + None, + )); + diagnostics.extend(*failure.diagnostics); + diagnostics.extend(crate::HttpStageDiagnostics::default()); + assert_eq!(diagnostics.failure_kind, Some(kind), "{cause:?}"); + let applied = diagnostics.applied(); + assert_eq!(applied.len(), 1); + assert!(applied[0].failed); + assert_eq!(applied[0].failure_kind, Some(kind), "{cause:?}"); } } @@ -1517,6 +1582,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,29 +1627,10 @@ 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_eq!(failure.kind, Some(crate::HttpRequestFailureKind::Capacity)); assert!(second.preflights.lock().unwrap().is_empty()); drop(held); assert_eq!( @@ -1696,3 +1766,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 615a7ab43a..9e355209e6 100644 --- a/crates/openshell-supervisor-middleware/src/lib.rs +++ b/crates/openshell-supervisor-middleware/src/lib.rs @@ -8,6 +8,9 @@ mod diagnostics; pub mod headers; mod http_hooks; mod remote; +mod request_failure; +pub use request_failure::HttpRequestFailureKind; +use request_failure::PlatformFailure; mod response; mod websocket; @@ -679,6 +682,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 +715,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 +731,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 +739,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 +756,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 +794,18 @@ enum MiddlewareDispatch { } impl MiddlewareDispatch { + fn status_failure_kind(&self, status: &tonic::Status) -> HttpRequestFailureKind { + match self { + Self::InProcess(_) => HttpRequestFailureKind::InProcessService, + // Tonic preserves the local error source for channel and HTTP/2 failures. + // A gRPC status decoded from the peer carries no Rust error source. + Self::Grpc(_) if std::error::Error::source(status).is_some() => { + HttpRequestFailureKind::Unavailable + } + Self::Grpc(_) => HttpRequestFailureKind::RemoteStatus(status.code()), + } + } + async fn describe( &self, ) -> std::result::Result, tonic::Status> { @@ -904,17 +926,15 @@ enum Unprocessed { Fail, } -async fn call_with_timeout( - timeout: Duration, - operation: &'static str, +/// The outer result tracks the local timer. The inner result preserves the service status. +async fn call_before_deadline( + deadline: tokio::time::Instant, unprocessed: Unprocessed, - mut call: F, -) -> std::result::Result, tonic::Status> + mut call: impl FnMut() -> Fut, +) -> std::result::Result, tokio::time::error::Elapsed> where - F: FnMut() -> Fut, - Fut: Future, tonic::Status>>, + Fut: Future>, { - let deadline = tokio::time::Instant::now() + timeout; tokio::time::timeout_at(deadline, async { match unprocessed { Unprocessed::Retry => { @@ -924,7 +944,23 @@ where } }) .await - .map_err(|_| tonic::Status::deadline_exceeded(format!("middleware {operation} timed out")))? +} + +async fn call_with_timeout( + timeout: Duration, + operation: &'static str, + unprocessed: Unprocessed, + call: F, +) -> std::result::Result, tonic::Status> +where + F: FnMut() -> Fut, + Fut: Future, tonic::Status>>, +{ + call_before_deadline(tokio::time::Instant::now() + timeout, unprocessed, call) + .await + .map_err(|_| { + tonic::Status::deadline_exceeded(format!("middleware {operation} timed out")) + })? } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1295,45 +1331,53 @@ fn normalize_untrusted_diagnostics( } } -fn validate_request_view(request: HttpRequestView<'_>) -> std::result::Result<(), &'static str> { +fn validate_request_view(request: HttpRequestView<'_>) -> std::result::Result<(), PlatformFailure> { if request.body().len() > MAX_MIDDLEWARE_PAYLOAD_BYTES { - return Err("request_body_over_capacity"); + return Err(PlatformFailure::Capacity("request_body_over_capacity")); } if request.config().encoded_len() > MAX_MIDDLEWARE_CONFIG_BYTES { - return Err("request_config_over_capacity"); + return Err(PlatformFailure::Capacity("request_config_over_capacity")); } if request.context().encoded_len() > MAX_MIDDLEWARE_CONTEXT_BYTES { - return Err("request_context_over_capacity"); + return Err(PlatformFailure::Capacity("request_context_over_capacity")); } if request.target().encoded_len() > MAX_MIDDLEWARE_TARGET_BYTES { - return Err("request_target_over_capacity"); + return Err(PlatformFailure::Capacity("request_target_over_capacity")); } if request.headers().len() > MAX_MIDDLEWARE_HEADERS { - return Err("request_header_count_over_capacity"); + return Err(PlatformFailure::Capacity( + "request_header_count_over_capacity", + )); } let header_bytes = request.headers().iter().fold(0usize, |total, header| { total.saturating_add(header.encoded_len()) }); if header_bytes > MAX_MIDDLEWARE_HEADER_BYTES { - return Err("request_header_bytes_over_capacity"); + return Err(PlatformFailure::Capacity( + "request_header_bytes_over_capacity", + )); } Ok(()) } fn validate_response_envelope( result: &openshell_core::proto::HttpRequestResult, -) -> std::result::Result<(), &'static str> { +) -> std::result::Result<(), PlatformFailure> { if result.body.len() > MAX_MIDDLEWARE_PAYLOAD_BYTES { - return Err("response_body_over_capacity"); + return Err(PlatformFailure::Capacity("response_body_over_capacity")); } if result.reason.len() > MAX_MIDDLEWARE_REASON_BYTES { - return Err("response_reason_over_capacity"); + return Err(PlatformFailure::Capacity("response_reason_over_capacity")); } if !result.reason_code.is_empty() && !is_stable_reason_code(&result.reason_code) { - return Err("response_reason_code_invalid"); + return Err(PlatformFailure::InvalidResult( + "response_reason_code_invalid", + )); } if result.header_mutations.len() > headers::MAX_HEADER_MUTATIONS { - return Err("header_mutation_count_over_capacity"); + return Err(PlatformFailure::Capacity( + "header_mutation_count_over_capacity", + )); } let mutation_bytes = result .header_mutations @@ -1342,29 +1386,35 @@ fn validate_response_envelope( total.saturating_add(mutation.encoded_len()) }); if mutation_bytes > MAX_MIDDLEWARE_HEADER_MUTATION_WIRE_BYTES { - return Err("header_mutation_bytes_over_capacity"); + return Err(PlatformFailure::Capacity( + "header_mutation_bytes_over_capacity", + )); } if result.findings.len() > MAX_MIDDLEWARE_FINDINGS_PER_STAGE { - return Err("response_findings_over_capacity"); + return Err(PlatformFailure::Capacity("response_findings_over_capacity")); } if result .findings .iter() .any(|finding| finding.encoded_len() > MAX_MIDDLEWARE_FINDING_BYTES) { - return Err("response_finding_over_capacity"); + return Err(PlatformFailure::Capacity("response_finding_over_capacity")); } if result.metadata.len() > MAX_MIDDLEWARE_METADATA_ENTRIES { - return Err("response_metadata_count_over_capacity"); + return Err(PlatformFailure::Capacity( + "response_metadata_count_over_capacity", + )); } let metadata_bytes = result.metadata.iter().fold(0usize, |total, (key, value)| { total.saturating_add(key.len()).saturating_add(value.len()) }); if metadata_bytes > MAX_MIDDLEWARE_METADATA_BYTES { - return Err("response_metadata_bytes_over_capacity"); + return Err(PlatformFailure::Capacity( + "response_metadata_bytes_over_capacity", + )); } if result.encoded_len() > MIDDLEWARE_GRPC_MESSAGE_BYTES { - return Err("response_envelope_over_capacity"); + return Err(PlatformFailure::Capacity("response_envelope_over_capacity")); } Ok(()) } @@ -2150,6 +2200,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, @@ -2157,6 +2208,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, @@ -2215,10 +2267,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, @@ -2232,10 +2290,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, @@ -2257,11 +2321,13 @@ impl ChainRunner { &body, &entry.entry.implementation, ); - if let Err(reason) = validate_request_view(request) { - match apply_on_error(entry, reason, &mut applied) { + if let Err(failure) = validate_request_view(request) { + let (reason, _, kind) = failure.details(); + match apply_on_error(entry, reason, 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, @@ -2277,12 +2343,19 @@ impl ChainRunner { let Some(service) = entry.service.as_ref() else { unreachable!("described binding always has a service") }; - let remaining = chain_deadline.saturating_duration_since(tokio::time::Instant::now()); + let now = tokio::time::Instant::now(); + let remaining = chain_deadline.saturating_duration_since(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, @@ -2295,9 +2368,8 @@ impl ChainRunner { } } } - let mut result = match call_with_timeout( - entry.timeout.min(remaining), - "EvaluateHttpRequest", + let evaluated = match call_before_deadline( + now + entry.timeout.min(remaining), match entry.on_error() { OnError::FailClosed => Unprocessed::Retry, OnError::FailOpen => Unprocessed::Fail, @@ -2306,17 +2378,32 @@ impl ChainRunner { ) .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))) + } + 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, @@ -2331,11 +2418,13 @@ impl ChainRunner { } }; - if let Err(reason) = validate_response_envelope(&result) { - match apply_on_error(entry, reason, &mut applied) { + if let Err(failure) = validate_response_envelope(&result) { + let (reason, _, kind) = failure.details(); + match apply_on_error(entry, reason, 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, @@ -2356,10 +2445,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, @@ -2394,6 +2489,7 @@ impl ChainRunner { ); } applied.push(MiddlewareInvocation { + failure_kind: None, name: entry.entry.name.clone(), implementation: entry.entry.implementation.clone(), decision, @@ -2401,6 +2497,7 @@ impl ChainRunner { failed: false, }); return Ok(ChainOutcome { + failure_kind: None, allowed: false, reason: middleware_denial_reason( &denial.config_name, @@ -2416,10 +2513,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, @@ -2450,10 +2553,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, @@ -2493,6 +2602,7 @@ impl ChainRunner { ); } applied.push(MiddlewareInvocation { + failure_kind: None, name: entry.entry.name.clone(), implementation: entry.entry.implementation.clone(), decision, @@ -2507,15 +2617,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, @@ -2530,6 +2644,7 @@ impl ChainRunner { } Ok(ChainOutcome { + failure_kind: None, allowed: true, reason: String::new(), body, @@ -3180,37 +3295,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] @@ -3647,6 +3776,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 @@ -4753,6 +4886,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"); } @@ -4812,12 +4949,22 @@ 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_code) = tokio::sync::watch::channel(None); 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<()>| { + let code = *failure_code.borrow(); + if let Some(code) = code { + return Err(tonic::Status::new(code, "service diagnostic")); + } + Ok(request) + }, + )) .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { let _ = shutdown_rx.await; }); @@ -4857,26 +5004,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); @@ -4884,11 +5030,40 @@ mod tests { assert_eq!(outcome.applied[0].implementation, registration.name); assert_eq!(outcome.applied[1].implementation, second_registration.name); + for (code, reason) in [ + ( + tonic::Code::DeadlineExceeded, + "middleware_failed: middleware_timeout", + ), + ( + tonic::Code::Unavailable, + "middleware_failed: external_service_error", + ), + ] { + fail_requests.send_replace(Some(code)); + let failure = runner.evaluate(&entries, input("hello")).await.unwrap(); + assert!(!failure.allowed); + assert_eq!( + failure.failure_kind, + Some(HttpRequestFailureKind::RemoteStatus(code)) + ); + assert_eq!(failure.applied[0].failure_kind, failure.failure_kind); + assert_eq!(failure.reason, reason); + } + let _ = shutdown_tx.send(()); server_task .await .expect("join test middleware") .expect("serve"); + let offline = runner.evaluate(&entries, input("hello")).await.unwrap(); + assert!(!offline.allowed); + assert_eq!( + offline.failure_kind, + Some(HttpRequestFailureKind::Unavailable) + ); + assert_eq!(offline.applied[0].failure_kind, offline.failure_kind); + assert_eq!(offline.reason, "middleware_failed: external_service_error"); } #[tokio::test] @@ -5072,6 +5247,10 @@ mod tests { .expect("evaluate invalid reason code"); assert!(!outcome.allowed); + assert_eq!( + outcome.failure_kind, + Some(HttpRequestFailureKind::InvalidResult) + ); assert_eq!( outcome.reason, "middleware_failed: response_reason_code_invalid" 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..1801b68599 --- /dev/null +++ b/crates/openshell-supervisor-middleware/src/request_failure.rs @@ -0,0 +1,147 @@ +// 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, + /// The relay stopped the request after its policy generation changed. + StalePolicyGeneration, + PolicyEvaluation, +} + +impl HttpRequestFailureKind { + /// 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::StalePolicyGeneration => "stale_policy_generation", + 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 {} + +/// A platform failure identified where it occurs. The sandbox response code +/// and the diagnostic cause can differ for the same failure. +#[derive(Clone, Copy, Debug)] +pub enum PlatformFailure { + StageTimeout, + ChainTimeout, + WholeBodyTimeout, + StreamIdleTimeout, + BindingNotDescribed, + SessionCapacityExhausted, + HeadInputOverCapacity, + ResponseInputUnrepresentable, + HookVersionsMixed, + BodyOverLimit(&'static str), + Capacity(&'static str), + InvalidResult(&'static str), + StreamClosed(&'static str), +} + +impl PlatformFailure { + pub fn details(self) -> (&'static str, crate::HttpFailureCode, HttpRequestFailureKind) { + use crate::HttpFailureCode as Code; + use HttpRequestFailureKind as Kind; + + match self { + Self::StageTimeout => ("middleware_timeout", Code::Timeout, Kind::StageTimeout), + Self::ChainTimeout => ( + "middleware_chain_timeout", + Code::Timeout, + Kind::ChainTimeout, + ), + Self::WholeBodyTimeout => ( + "middleware_body_timeout", + Code::Timeout, + Kind::WholeBodyTimeout, + ), + Self::StreamIdleTimeout => ( + "middleware_stall_timeout", + Code::StreamIdleTimeout, + Kind::StreamIdleTimeout, + ), + Self::BindingNotDescribed => ( + "binding_not_described", + Code::Unavailable, + Kind::Unavailable, + ), + Self::SessionCapacityExhausted => ( + "session_capacity_exhausted", + Code::Unavailable, + Kind::Capacity, + ), + Self::HeadInputOverCapacity => ( + "head_input_over_capacity", + Code::CannotInspect, + Kind::Capacity, + ), + Self::ResponseInputUnrepresentable => ( + "response_input_unrepresentable", + Code::CannotInspect, + Kind::InvalidResult, + ), + Self::HookVersionsMixed => ( + crate::MIDDLEWARE_HOOK_VERSIONS_MIXED, + Code::HookVersionsMixed, + Kind::InvalidResult, + ), + Self::BodyOverLimit(reason) => (reason, Code::BodyOverLimit, Kind::Capacity), + Self::Capacity(reason) => (reason, Code::LifecycleViolation, Kind::Capacity), + Self::InvalidResult(reason) => (reason, Code::LifecycleViolation, Kind::InvalidResult), + Self::StreamClosed(reason) => (reason, Code::LifecycleViolation, Kind::Io), + } + } +} diff --git a/crates/openshell-supervisor-network/src/l7/middleware.rs b/crates/openshell-supervisor-network/src/l7/middleware.rs index 70f6985c1c..7ca0f03654 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}; @@ -1261,8 +1261,8 @@ 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::StalePolicyGeneration + } else { + HttpRequestFailureKind::Io + }; + return Err(BodyRunError::Client { kind, error }); + } }; let Some(unit) = unit else { break; @@ -1562,9 +1576,9 @@ struct RequestEvents { context: L7EvalContext, action: String, target: String, - preflight: HttpStageDiagnostics, - /// Reason the events were emitted with, empty for an allowed request. - terminal_reason: Option, + /// Consumed when the first terminal outcome is recorded. + preflight: Option, + terminal_kind: Option, span: Option, } @@ -1577,12 +1591,11 @@ impl RequestEvents { body: HttpStageDiagnostics, correlation: Option<&super::correlation::RequestCorrelation>, ) { - if self.terminal_reason.is_some() { + let Some(mut diagnostics) = self.preflight.take() else { return; - } - self.terminal_reason = Some(reason.to_string()); - let mut diagnostics = std::mem::take(&mut self.preflight); + }; diagnostics.extend(body); + self.terminal_kind = diagnostics.failure_kind; let events = request_middleware_events( &self.context, &self.action, @@ -1596,6 +1609,20 @@ impl RequestEvents { span.in_scope(|| emit_request_events(correlation, events)); } + fn middleware_failed( + &mut self, + failure: &mut HttpMiddlewareFailure, + correlation: Option<&super::correlation::RequestCorrelation>, + ) { + self.emit( + false, + &failure.reason, + failure.denial.as_ref(), + std::mem::take(&mut *failure.diagnostics), + correlation, + ); + } + /// Record a failed body run and return the result the relay acts on. fn body_failed( &mut self, @@ -1603,14 +1630,8 @@ impl RequestEvents { correlation: Option<&super::correlation::RequestCorrelation>, ) -> Result { match error { - BodyRunError::Middleware(failure) => { - self.emit( - false, - &failure.reason, - failure.denial.as_ref(), - *failure.diagnostics, - correlation, - ); + BodyRunError::Middleware(mut failure) => { + self.middleware_failed(&mut failure, correlation); Ok(MiddlewareApplyResult::Denied { denial: failure.denial, failure: failure.failure.map(|failure| *failure), @@ -1629,17 +1650,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 +1677,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, @@ -1729,37 +1757,45 @@ impl RequestBodyStream { } Err(error) => error, }; - let error = match error { + let failure = match error { BodyRunError::Middleware(failure) 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")); } - error => error, - }; - let failure = match &error { - BodyRunError::Middleware(failure) => crate::l7::rest::LiveRequestFailure::Middleware { - reason: failure.reason.clone(), - denial: failure.denial.clone(), - failure: failure.failure.as_deref().cloned(), - }, - BodyRunError::ClientTimeout => crate::l7::rest::LiveRequestFailure::ClientTimeout, - BodyRunError::Client(_) => { + BodyRunError::Middleware(mut failure) => { + self.events.middleware_failed(&mut failure, correlation); + crate::l7::rest::LiveRequestFailure::Middleware { + kind: self.events.terminal_kind, + delivery: self.delivery.clone(), + reason: failure.reason, + denial: failure.denial, + failure: failure.failure.map(|failure| *failure), + } + } + BodyRunError::ClientTimeout => { + self.events.body_failed(error, correlation)?; + crate::l7::rest::LiveRequestFailure::ClientTimeout { + delivery: self.delivery.clone(), + } + } + BodyRunError::Client { .. } => { return self .events .body_failed(error, correlation) .map(|_| unreachable!()); } }; - self.events.body_failed(error, correlation)?; Err(miette::Report::new(failure)) } @@ -1773,7 +1809,10 @@ impl RequestBodyStream { false, &format!("middleware_cancelled: {reason}"), None, - HttpStageDiagnostics::default(), + HttpStageDiagnostics { + failure_kind: Some(HttpRequestFailureKind::Cancelled), + ..Default::default() + }, correlation, ); } @@ -1790,7 +1829,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(), @@ -1802,13 +1840,14 @@ pub(super) fn request_middleware_events( ctx, &req, &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, + applied: diagnostics.applied(), denial: denial.cloned(), }, ) @@ -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 { @@ -2643,6 +2689,67 @@ mod tests { } } + #[test] + fn request_body_keeps_its_terminal_cause_after_successful_preflight() { + use super::{BodyRunError, MiddlewareApplyResult, RequestBodyStream, RequestEvents}; + use crate::policy_types::generation_guard_for; + use openshell_supervisor_middleware::{ + HttpRequestFailureKind, HttpStageDiagnostics, HttpStageInvocation, HttpStageOutcome, + }; + use std::sync::{Arc, atomic::AtomicU64}; + + let request = + forwarded_request("POST /v1/items HTTP/1.1\r\nHost: api.example.test\r\n\r\n"); + let generation = Arc::new(AtomicU64::new(1)); + let (tx, _) = tokio::sync::watch::channel(1); + let request_events = || RequestEvents { + context: L7EvalContext::default(), + action: request.action.clone(), + target: request.target.clone(), + preflight: Some(HttpStageDiagnostics { + invocations: vec![HttpStageInvocation { + config_name: "guard".into(), + implementation: "test/guard".into(), + outcome: HttpStageOutcome::Duplex, + input_bytes: 0, + output_bytes: None, + transformed: false, + failed: false, + failure_kind: None, + reason_code: None, + failure_reason: None, + }], + ..Default::default() + }), + terminal_kind: None, + span: None, + }; + let mut body = RequestBodyStream { + delivery: crate::l7::request_delivery::RequestDelivery::default(), + reader: crate::l7::rest::RequestBodyReader::None, + session: None, + events: request_events(), + generation_guard: generation_guard_for(1, 1, &generation, &tx).unwrap(), + injected_headers: crate::l7::token_grant_injection::InjectedHeaders::default(), + forwarded_head: super::ForwardedRequestHead::new(&request), + }; + body.cancelled("upstream_response", None); + assert_eq!( + body.events.terminal_kind, + Some(HttpRequestFailureKind::Cancelled) + ); + + let mut events = request_events(); + assert!(matches!( + events.body_failed(BodyRunError::ClientTimeout, None), + Ok(MiddlewareApplyResult::RequestTimeout) + )); + assert_eq!( + events.terminal_kind, + Some(HttpRequestFailureKind::RequestBodyTimeout) + ); + } + fn header_pairs(headers: &[openshell_core::proto::HttpHeader]) -> Vec<(&str, &str)> { headers .iter() @@ -3293,3 +3400,60 @@ 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::StalePolicyGeneration, + "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: Some(HttpStageDiagnostics::default()), + terminal_kind: 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::StalePolicyGeneration + ); + } + } +} 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]