Skip to content

Commit 408382a

Browse files
committed
fix(middleware): honor fail-open for unrepresentable responses
Signed-off-by: Piotr Mlocek <pmlocek@nvidia.com>
1 parent 150ae32 commit 408382a

4 files changed

Lines changed: 172 additions & 17 deletions

File tree

‎architecture/sandbox.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,12 @@ middleware registry validates implementation-owned config. The generic
192192
registry and chain runner live in `openshell-supervisor-middleware`; first-party
193193
implementations live in `openshell-supervisor-middleware-builtins`.
194194

195+
Valid HTTP that cannot fit the response middleware protocol, including non-UTF-8
196+
header values or an oversized preflight envelope, fails each selected stage
197+
according to its `on_error` policy. An all-fail-open chain relays the original
198+
bytes; a fail-closed stage prevents delivery. The relay validates HTTP syntax
199+
and protected trailer declarations before allowing this bypass.
200+
195201
The same selected chain can inspect the matching final HTTP response before it
196202
returns to the workload. Response stages select header-only, whole-body, or
197203
streaming mode independently. The relay preserves upstream framing for a

‎crates/openshell-supervisor-middleware/src/response.rs‎

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -835,6 +835,15 @@ impl HttpResponseSession {
835835
}
836836

837837
impl ChainRunner {
838+
/// Apply selected stages' failure policies when valid HTTP cannot be encoded
839+
/// in the middleware protocol. The caller must validate HTTP safety first.
840+
pub fn http_response_input_unrepresentable(
841+
&self,
842+
entries: &[DescribedChainEntry],
843+
) -> HttpResponsePreflightOutcome {
844+
response_preflight_input_failure(entries, Vec::new(), "response_input_unrepresentable")
845+
}
846+
838847
pub async fn preflight_http_response(
839848
&self,
840849
entries: &[ChainEntry],
@@ -844,7 +853,13 @@ impl ChainRunner {
844853
if described.is_empty() {
845854
return Ok(empty_preflight_outcome(input.headers));
846855
}
847-
validate_preflight_input(&input)?;
856+
if validate_preflight_input(&input).is_err() {
857+
return Ok(response_preflight_input_failure(
858+
&described,
859+
input.headers,
860+
"response_input_over_capacity",
861+
));
862+
}
848863
let session_admission = match self.try_reserve_middleware_session() {
849864
MiddlewareSessionAdmission::Admitted(admission) => admission,
850865
MiddlewareSessionAdmission::AtCapacity => {
@@ -1730,6 +1745,7 @@ fn response_failure_category(reason: &str) -> &'static str {
17301745
} else if matches!(
17311746
reason,
17321747
"bodyless_response"
1748+
| "response_input_unrepresentable"
17331749
| "partial_response"
17341750
| "content_coding_not_identity"
17351751
| "cache_control_no_transform"
@@ -1794,6 +1810,22 @@ fn blocked_preflight_outcome(
17941810
}
17951811
}
17961812

1813+
fn response_preflight_input_failure(
1814+
entries: &[DescribedChainEntry],
1815+
headers: Vec<HttpHeader>,
1816+
reason: &str,
1817+
) -> HttpResponsePreflightOutcome {
1818+
let mut outcome = empty_preflight_outcome(headers);
1819+
for entry in entries {
1820+
if let Some(reason) = collect_preflight_failure(entry, reason, &mut outcome.invocations) {
1821+
outcome.allowed = false;
1822+
outcome.reason = reason;
1823+
break;
1824+
}
1825+
}
1826+
outcome
1827+
}
1828+
17971829
fn response_session_capacity_exhausted(
17981830
entries: Vec<DescribedChainEntry>,
17991831
headers: Vec<HttpHeader>,
@@ -2288,6 +2320,53 @@ mod tests {
22882320
}
22892321
}
22902322

2323+
#[tokio::test]
2324+
async fn response_preflight_envelope_limits_obey_selected_stage_policies() {
2325+
let runner = ChainRunner::new(Arc::new(ResponseService {
2326+
script: Script::HeadersOnly,
2327+
}));
2328+
for limit in 0..4 {
2329+
let mut input = input(200);
2330+
match limit {
2331+
0 => input.context.request_id = "x".repeat(MAX_MIDDLEWARE_CONTEXT_BYTES + 1),
2332+
1 => input.target.path = "x".repeat(MAX_MIDDLEWARE_TARGET_BYTES + 1),
2333+
2 => input.headers = vec![input.headers[0].clone(); MAX_MIDDLEWARE_HEADERS + 1],
2334+
_ => input.headers[0].value = "x".repeat(MAX_MIDDLEWARE_HEADER_BYTES + 1),
2335+
}
2336+
for last_policy in [OnError::FailOpen, OnError::FailClosed] {
2337+
let entries = [entry(OnError::FailOpen), entry(last_policy)];
2338+
let outcome = runner
2339+
.preflight_http_response(&entries, input.clone())
2340+
.await
2341+
.unwrap();
2342+
assert_eq!(outcome.allowed, last_policy == OnError::FailOpen);
2343+
assert_eq!(outcome.headers, input.headers);
2344+
assert!(outcome.session.is_none());
2345+
assert_eq!(outcome.invocations.len(), 2);
2346+
assert!(
2347+
outcome
2348+
.invocations
2349+
.iter()
2350+
.all(|invocation| invocation.failed && invocation.stage_disabled)
2351+
);
2352+
assert_eq!(
2353+
outcome.invocations[1].failure_category.as_deref(),
2354+
Some("payload_capacity")
2355+
);
2356+
}
2357+
}
2358+
let described = runner
2359+
.describe_http_response_chain(&[entry(OnError::FailOpen), entry(OnError::FailClosed)])
2360+
.await
2361+
.unwrap();
2362+
let outcome = runner.http_response_input_unrepresentable(&described);
2363+
assert!(!outcome.allowed);
2364+
assert_eq!(outcome.invocations.len(), 2);
2365+
assert!(outcome.invocations.iter().all(|invocation| {
2366+
invocation.failure_category.as_deref() == Some("response_not_inspectable")
2367+
}));
2368+
}
2369+
22912370
#[test]
22922371
fn stream_mode_requires_only_one_byte_of_payload_capacity() {
22932372
let mut described = DescribedChainEntry {

‎crates/openshell-supervisor-network/src/l7/rest.rs‎

Lines changed: 84 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3393,10 +3393,12 @@ where
33933393
.await
33943394
{
33953395
Ok(described) if described.is_empty() => return Ok(None),
3396-
Ok(_) => parse_response_head_for_middleware(header_bytes),
3396+
Ok(described) => {
3397+
parse_response_head_for_middleware(header_bytes).map(|parsed| (described, parsed))
3398+
}
33973399
Err(error) => Err(error),
33983400
};
3399-
let parsed = match parsed {
3401+
let (described, parsed) = match parsed {
34003402
Ok(parsed) => parsed,
34013403
Err(error) => {
34023404
debug!(error = %error, "HTTP response head normalization failed");
@@ -3430,11 +3432,17 @@ where
34303432
headers: parsed.headers,
34313433
connection_nominated_headers: parsed.connection_nominated,
34323434
};
3433-
let preflight = match middleware
3434-
.runner
3435-
.preflight_http_response(middleware.chain, input)
3436-
.await
3437-
{
3435+
let preflight_result = if parsed.representable {
3436+
middleware
3437+
.runner
3438+
.preflight_http_response(middleware.chain, input)
3439+
.await
3440+
} else {
3441+
Ok(middleware
3442+
.runner
3443+
.http_response_input_unrepresentable(&described))
3444+
};
3445+
let preflight = match preflight_result {
34383446
Ok(preflight) => preflight,
34393447
Err(error) => {
34403448
debug!(error = %error, "HTTP response middleware preflight failed");
@@ -3503,11 +3511,11 @@ where
35033511
&preflight.invocations,
35043512
);
35053513

3506-
let status_line = response_status_line(header_bytes)?;
35073514
let Some(mut session) = preflight.session else {
35083515
if preflight.headers == original_headers {
35093516
return Ok(None);
35103517
}
3518+
let status_line = response_status_line(header_bytes)?;
35113519
let outcome = relay_headers_only_response(
35123520
request_method,
35133521
upstream,
@@ -3525,6 +3533,7 @@ where
35253533
return Ok(Some(outcome));
35263534
};
35273535

3536+
let status_line = response_status_line(header_bytes)?;
35283537
let supports_chunked_response = !status_line.starts_with("HTTP/1.0 ");
35293538
let bodiless = is_bodiless_response(request_method, status_code);
35303539
if bodiless {
@@ -4127,15 +4136,18 @@ fn emit_http_response_middleware_failure(
41274136

41284137
#[derive(Debug)]
41294138
struct ParsedResponseHead {
4139+
representable: bool,
41304140
headers: Vec<HttpHeader>,
41314141
connection_nominated: Vec<String>,
41324142
declared_trailers: Vec<String>,
41334143
}
41344144

41354145
fn parse_response_head_for_middleware(header_bytes: &[u8]) -> Result<ParsedResponseHead> {
4136-
let header = std::str::from_utf8(header_bytes)
4137-
.map_err(|_| miette!("HTTP response headers contain invalid UTF-8"))?;
4138-
if parse_status_code(header).is_none() {
4146+
// Lossy decoding preserves ASCII syntax and control bytes for validation.
4147+
// Never pass replacement text to middleware or use it for delivery.
4148+
let header = String::from_utf8_lossy(header_bytes);
4149+
let representable = std::str::from_utf8(header_bytes).is_ok();
4150+
if parse_status_code(&header).is_none() {
41394151
return Err(miette!("HTTP response status line is malformed"));
41404152
}
41414153
let mut nominated = HashSet::new();
@@ -4187,7 +4199,8 @@ fn parse_response_head_for_middleware(header_bytes: &[u8]) -> Result<ParsedRespo
41874199
let mut connection_nominated: Vec<_> = nominated.into_iter().collect();
41884200
connection_nominated.sort();
41894201
Ok(ParsedResponseHead {
4190-
headers,
4202+
representable,
4203+
headers: if representable { headers } else { Vec::new() },
41914204
connection_nominated,
41924205
declared_trailers,
41934206
})
@@ -7634,7 +7647,7 @@ mod tests {
76347647
}
76357648

76367649
async fn run_response_middleware_relay(
7637-
response: &'static [u8],
7650+
response: &[u8],
76387651
method: &str,
76397652
script: ResponseRelayScript,
76407653
) -> (Result<RelayOutcome>, Vec<u8>) {
@@ -7648,7 +7661,7 @@ mod tests {
76487661
}
76497662

76507663
async fn run_response_middleware_relay_with_error(
7651-
response: &'static [u8],
7664+
response: &[u8],
76527665
method: &str,
76537666
script: ResponseRelayScript,
76547667
on_error: openshell_supervisor_middleware::OnError,
@@ -7664,7 +7677,7 @@ mod tests {
76647677
}
76657678

76667679
async fn run_response_middleware_relay_with_timeout(
7667-
response: &'static [u8],
7680+
response: &[u8],
76687681
method: &str,
76697682
script: ResponseRelayScript,
76707683
on_error: openshell_supervisor_middleware::OnError,
@@ -7673,8 +7686,9 @@ mod tests {
76737686
let (runner, chain) = response_middleware_fixture_with_error(script, on_error);
76747687
let (mut upstream_read, mut upstream_write) = tokio::io::duplex(16 * 1024);
76757688
let (mut client_read, mut client_write) = tokio::io::duplex(16 * 1024);
7689+
let response = response.to_vec();
76767690
tokio::spawn(async move {
7677-
upstream_write.write_all(response).await.unwrap();
7691+
upstream_write.write_all(&response).await.unwrap();
76787692
upstream_write.shutdown().await.unwrap();
76797693
});
76807694
let mut middleware = response_middleware_context(&runner, &chain, method);
@@ -8253,6 +8267,60 @@ mod tests {
82538267
assert!(!delivered.contains("502 Bad Gateway"), "{delivered}");
82548268
}
82558269

8270+
#[tokio::test]
8271+
async fn response_middleware_unrepresentable_input_obeys_failure_policy() {
8272+
let mut many_headers = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n".to_vec();
8273+
for _ in 0..=openshell_supervisor_middleware::MAX_MIDDLEWARE_HEADERS {
8274+
many_headers.extend_from_slice(b"X-Extra: value\r\n");
8275+
}
8276+
many_headers.extend_from_slice(b"\r\nok");
8277+
for response in [
8278+
b"HTTP/1.1 200 OK\r\nX-Legacy: \xff\r\nContent-Length: 2\r\n\r\nok".as_slice(),
8279+
many_headers.as_slice(),
8280+
] {
8281+
for on_error in [
8282+
openshell_supervisor_middleware::OnError::FailOpen,
8283+
openshell_supervisor_middleware::OnError::FailClosed,
8284+
] {
8285+
let (outcome, delivered) = run_response_middleware_relay_with_error(
8286+
response,
8287+
"GET",
8288+
ResponseRelayScript::HeadersOnly,
8289+
on_error,
8290+
)
8291+
.await;
8292+
if on_error == openshell_supervisor_middleware::OnError::FailOpen {
8293+
assert!(matches!(outcome.unwrap(), RelayOutcome::Reusable));
8294+
assert_eq!(delivered, response);
8295+
} else {
8296+
assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed));
8297+
assert!(delivered.starts_with(b"HTTP/1.1 502 Bad Gateway\r\n"));
8298+
assert!(
8299+
String::from_utf8(delivered)
8300+
.unwrap()
8301+
.contains("response_delivery_failed")
8302+
);
8303+
}
8304+
}
8305+
}
8306+
}
8307+
8308+
#[tokio::test]
8309+
async fn response_middleware_obs_text_does_not_bypass_unsafe_headers() {
8310+
for response in [
8311+
b"HTTP/1.1 200 OK\r\nX-Legacy: \xff\r\nBad Name: value\r\nContent-Length: 2\r\n\r\nok".as_slice(),
8312+
b"HTTP/1.1 200 OK\r\nX-Legacy: \xff\x00\r\nContent-Length: 2\r\n\r\nok".as_slice(),
8313+
b"HTTP/1.1 200 OK\r\nX-Legacy: \xff\r\nTrailer: content-length\r\nContent-Length: 2\r\n\r\nok".as_slice(),
8314+
] {
8315+
let (outcome, delivered) = run_response_middleware_relay_with_error(
8316+
response, "GET", ResponseRelayScript::HeadersOnly,
8317+
openshell_supervisor_middleware::OnError::FailOpen,
8318+
).await;
8319+
assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed));
8320+
assert!(delivered.starts_with(b"HTTP/1.1 502 Bad Gateway\r\n"));
8321+
}
8322+
}
8323+
82568324
#[tokio::test]
82578325
async fn response_middleware_fail_open_preserves_input_before_and_after_commit() {
82588326
for (script, expected_framing) in [

‎docs/extensibility/supervisor-middleware.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,8 @@ See [Policy Schema](/reference/policy-schema#network-middleware) for the complet
144144
| `fail_closed` | Denies the HTTP request or closes the WebSocket when the stage fails. This is the default. |
145145
| `fail_open` | Skips the failed HTTP stage. For a broken WebSocket stage stream, disables that stage for the rest of the connection and continues the remaining chain. |
146146

147+
A valid upstream response can exceed the middleware envelope limits or contain header bytes that the middleware protocol cannot represent. OpenShell relays the original response when every selected response stage uses `fail_open`; any selected `fail_closed` stage causes the canonical 502 delivery failure. Malformed or unsafe HTTP does not qualify for this bypass.
148+
147149
Use `fail_open` only when bypassing the middleware preserves the intended security policy. OpenShell emits a detection finding when a failed stage is bypassed and a separate state-change finding when a WebSocket stage is disabled for the session.
148150

149151
Capability coverage is separate from failure handling. A host-matched HTTP-only attachment does not join the WebSocket chain, regardless of `on_error`. Binary messages are outside the V1 text-message binding and pass through even when a selected stage is `fail_closed`. OpenShell records both states as informational coverage events so operators do not mistake pass-through traffic for inspected traffic. If a deployment requires all WebSocket message classes to be inspected, V1 cannot express that requirement.

0 commit comments

Comments
 (0)