Skip to content

Commit 3402183

Browse files
committed
fix(app-listener): preserve polling freshness and HTTP keepalive
Signed-off-by: Taylor Mutch <taylormutch@gmail.com>
1 parent 6925a44 commit 3402183

5 files changed

Lines changed: 152 additions & 25 deletions

File tree

‎crates/openshell-supervisor/README.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,9 @@ poll and push application installs that allowlist; rejected configuration
272272
suspends it. Polling renews a 30-second freshness lease. In push mode, an accepted
273273
live supervisor session renews already installed, unexpired routes even when no
274274
configuration changes. Rejection or a lease lapse cannot revive an old stream.
275-
Ending the configuration loop suspends routes.
275+
With the listener enabled, both polling and push maintenance cap their sleep at
276+
five seconds, even if the configured polling interval is longer. Failed polls
277+
do not renew routes. Ending the configuration loop suspends routes.
276278

277279
`OPENSHELL_APP_LISTENER_ENABLED=true` explicitly enables the process listener.
278280
`OPENSHELL_APP_LISTEN_ADDRESS`, `OPENSHELL_APP_SERVICE_DOMAIN`,
@@ -285,7 +287,10 @@ supervisor to reload application certificates.
285287
This path uses application or trusted-edge authentication independently from
286288
gateway authentication. It validates Host against SNI, preserves public
287289
Host/Origin and application cookies, strips gateway/edge identity material, and
288-
retains service-specific bearer passthrough. It has no discovery API or public
290+
retains service-specific bearer passthrough. Hop-by-hop headers are removed from
291+
requests and responses, preserving successful WebSocket upgrades. An application
292+
closing its upstream HTTP connection does not close the client connection.
293+
It has no discovery API or public
289294
URL selection. Dedicated and shared supervisors expose the app listener on their
290295
Pod IPs without app Services. Clients must select the member owning their
291296
sandbox. HA takeover may preserve the workload generation; existing ingress streams

‎crates/openshell-supervisor/src/app_listener.rs‎

Lines changed: 91 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,30 @@ fn hop_header(name: &str) -> bool {
704704
)
705705
}
706706

707+
fn strip_hop_headers(headers: &mut http::HeaderMap, websocket: bool) {
708+
let connection_headers: Vec<String> = headers
709+
.get_all(header::CONNECTION)
710+
.iter()
711+
.filter_map(|value| value.to_str().ok())
712+
.flat_map(|value| value.split(','))
713+
.map(|value| value.trim().to_ascii_lowercase())
714+
.collect();
715+
let remove: Vec<_> = headers
716+
.keys()
717+
.filter(|name| {
718+
(hop_header(name.as_str())
719+
|| connection_headers
720+
.iter()
721+
.any(|value| value == name.as_str()))
722+
&& !(websocket && matches!(name.as_str(), "connection" | "upgrade"))
723+
})
724+
.cloned()
725+
.collect();
726+
for name in remove {
727+
headers.remove(name);
728+
}
729+
}
730+
707731
fn sanitize_headers(headers: &mut http::HeaderMap, passthrough: bool, websocket: bool) -> bool {
708732
if passthrough {
709733
let values: Vec<_> = headers.get_all(header::AUTHORIZATION).iter().collect();
@@ -730,23 +754,10 @@ fn sanitize_headers(headers: &mut http::HeaderMap, passthrough: bool, websocket:
730754
} else {
731755
headers.remove(header::AUTHORIZATION);
732756
}
733-
let connection_headers: Vec<String> = headers
734-
.get_all(header::CONNECTION)
735-
.iter()
736-
.filter_map(|value| value.to_str().ok())
737-
.flat_map(|value| value.split(','))
738-
.map(|value| value.trim().to_ascii_lowercase())
739-
.collect();
757+
strip_hop_headers(headers, websocket);
740758
let remove: Vec<_> = headers
741759
.keys()
742-
.filter(|name| {
743-
gateway_header(name.as_str())
744-
|| ((hop_header(name.as_str())
745-
|| connection_headers
746-
.iter()
747-
.any(|value| value == name.as_str()))
748-
&& !(websocket && matches!(name.as_str(), "connection" | "upgrade")))
749-
})
760+
.filter(|name| gateway_header(name.as_str()))
750761
.cloned()
751762
.collect();
752763
for name in remove {
@@ -831,7 +842,9 @@ async fn proxy(
831842
upstream_task.abort();
832843
return Ok(error(StatusCode::BAD_GATEWAY));
833844
};
834-
if response.status() == StatusCode::SWITCHING_PROTOCOLS && websocket {
845+
let upgraded = response.status() == StatusCode::SWITCHING_PROTOCOLS && websocket;
846+
strip_hop_headers(response.headers_mut(), upgraded);
847+
if upgraded {
835848
let upstream = hyper::upgrade::on(&mut response);
836849
let downstream = downstream.expect("websocket upgrade");
837850
tokio::spawn(async move {
@@ -980,6 +993,16 @@ mod tests {
980993
.unwrap(),
981994
);
982995
}
996+
if req.uri().path() == "/close" {
997+
return Ok(Response::builder()
998+
.header(header::CONNECTION, "close, X-Upstream-Only")
999+
.header("x-upstream-only", "private")
1000+
.header("keep-alive", "timeout=1")
1001+
.header(header::CONTENT_TYPE, "text/plain")
1002+
.header(header::SET_COOKIE, "app=session; HttpOnly")
1003+
.body(Body::from("upstream closed"))
1004+
.unwrap());
1005+
}
9831006
let body = format!(
9841007
"{} {} {} {}",
9851008
req.uri(),
@@ -1103,6 +1126,58 @@ mod tests {
11031126
String::from_utf8(response).unwrap()
11041127
}
11051128

1129+
#[tokio::test]
1130+
async fn upstream_connection_close_preserves_client_keepalive() {
1131+
use http_body_util::BodyExt as _;
1132+
1133+
let f = fixture();
1134+
let stream = openshell_core::net::connect_tcp_nodelay_best_effort(&[f.address])
1135+
.await
1136+
.unwrap();
1137+
let tls = tokio_rustls::TlsConnector::from(f.tls.clone())
1138+
.connect(
1139+
rustls::pki_types::ServerName::try_from(HOST).unwrap(),
1140+
stream,
1141+
)
1142+
.await
1143+
.unwrap();
1144+
let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(tls))
1145+
.await
1146+
.unwrap();
1147+
let client_task = tokio::spawn(connection);
1148+
for _ in 0..2 {
1149+
let response = tokio::time::timeout(
1150+
Duration::from_secs(3),
1151+
sender.send_request(
1152+
Request::builder()
1153+
.uri("/close")
1154+
.header(header::HOST, HOST)
1155+
.body(Body::empty())
1156+
.unwrap(),
1157+
),
1158+
)
1159+
.await
1160+
.unwrap()
1161+
.expect("upstream close must not close the client connection");
1162+
assert_eq!(response.status(), StatusCode::OK);
1163+
assert!(!response.headers().contains_key(header::CONNECTION));
1164+
assert!(!response.headers().contains_key("x-upstream-only"));
1165+
assert!(!response.headers().contains_key("keep-alive"));
1166+
assert_eq!(response.headers()[header::CONTENT_TYPE], "text/plain");
1167+
assert_eq!(
1168+
response.headers()[header::SET_COOKIE],
1169+
"app=session; HttpOnly"
1170+
);
1171+
let body = tokio::time::timeout(Duration::from_secs(3), response.into_body().collect())
1172+
.await
1173+
.unwrap()
1174+
.unwrap();
1175+
assert_eq!(body.to_bytes(), "upstream closed");
1176+
}
1177+
assert_eq!(f.connector.calls.load(Ordering::SeqCst), 2);
1178+
client_task.abort();
1179+
}
1180+
11061181
#[tokio::test]
11071182
async fn browser_post_preserves_public_authority_and_origin() {
11081183
let f = fixture();

‎crates/openshell-supervisor/src/config_runtime.rs‎

Lines changed: 46 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1370,7 +1370,13 @@ async fn run_policy_poll_loop_with_client<C: PolicyGatewayClient>(
13701370
}
13711371
}
13721372

1373-
let interval = Duration::from_secs(ctx.interval_secs);
1373+
// Accepted configurations must renew app routes before their freshness
1374+
// lease expires, including when a gateway uses polling instead of push.
1375+
let interval = if ctx.app_routes.is_some() {
1376+
Duration::from_secs(ctx.interval_secs).min(Duration::from_secs(5))
1377+
} else {
1378+
Duration::from_secs(ctx.interval_secs)
1379+
};
13741380
loop {
13751381
if let Some(updates) = config_push_updates.as_ref() {
13761382
config_push_enabled = *updates.borrow();
@@ -1388,11 +1394,6 @@ async fn run_policy_poll_loop_with_client<C: PolicyGatewayClient>(
13881394
routes.renew();
13891395
}
13901396
let delay = next_poll_delay(&ctx.extension_credentials, interval);
1391-
let delay = if ctx.app_routes.is_some() {
1392-
delay.min(Duration::from_secs(5))
1393-
} else {
1394-
delay
1395-
};
13961397
tokio::select! {
13971398
changed = async {
13981399
match config_push_updates.as_mut() {
@@ -3512,6 +3513,45 @@ mod tests {
35123513
handle.abort();
35133514
}
35143515

3516+
#[tokio::test(start_paused = true)]
3517+
async fn app_listener_caps_polling_interval_without_changing_disabled_behavior() {
3518+
for listener_enabled in [false, true] {
3519+
let initial = settings_poll_result(
3520+
Some(proto_policy_fixture()),
3521+
1,
3522+
openshell_core::proto::PolicySource::Sandbox,
3523+
);
3524+
let (mut ctx, _config_apply_tx, push_tx) = push_session_poll_loop(&initial);
3525+
push_tx.send_replace(false);
3526+
ctx.interval_secs = 60;
3527+
ctx.app_routes = listener_enabled.then(app_listener::Routes::default);
3528+
let (client, polls, mut reports) = scripted_policy_gateway();
3529+
let poll_calls = Arc::clone(&client.poll_calls);
3530+
for _ in 0..16 {
3531+
polls.send(initial.clone()).unwrap();
3532+
}
3533+
let task = tokio::spawn(run_policy_poll_loop_with_client(ctx, client));
3534+
expect_policy_report(&mut reports, 1).await;
3535+
for step in 1..=13 {
3536+
tokio::time::advance(Duration::from_secs(5)).await;
3537+
// Let the poll reconcile its ready scripted response and
3538+
// register the next sleep before advancing virtual time.
3539+
for _ in 0..8 {
3540+
tokio::task::yield_now().await;
3541+
}
3542+
let expected = 1 + if listener_enabled { step } else { step / 12 };
3543+
assert_eq!(
3544+
poll_calls.load(Ordering::SeqCst),
3545+
expected,
3546+
"listener enabled={listener_enabled}, elapsed={}s",
3547+
step * 5
3548+
);
3549+
}
3550+
task.abort();
3551+
let _ = task.await;
3552+
}
3553+
}
3554+
35153555
#[tokio::test]
35163556
async fn pushed_policy_status_is_reported_only_in_results() {
35173557
use openshell_core::proto::{ConfigApplyOutcome, PolicySource};

‎docs/how-it-works/gateways/configuration.mdx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1777,6 +1777,11 @@ or driver options alone do not enable it. Use an unprivileged port distinct from
17771777
the supervisor runtime and health ports. The common `port` controls both the
17781778
listener and its Kubernetes endpoint.
17791779

1780+
With the listener enabled, supervisors cap configuration polling delays at five
1781+
seconds so healthy routes retain their 30-second freshness lease. Failed polls
1782+
do not renew the lease; expiry closes affected application connections. Disabling
1783+
the listener preserves the configured polling interval.
1784+
17801785
On Kubernetes, provide a TLS Secret with `tls.crt` and `tls.key` matching
17811786
`*.services.example.com` in each supervisor namespace, and allow your ingress
17821787
clients to reach the app port through NetworkPolicy. The driver mounts the Secret

‎skills/debug-openshell-cluster/SKILL.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1643,6 +1643,8 @@ configuration until restarted.
16431643
Service changes arrive through polling or push configuration. Only admitted
16441644
service declarations are installed. Polling and accepted live push sessions
16451645
renew a 30-second lease; rejected configuration or expired freshness closes
1646-
routes. App traffic uses application/edge authentication independently of gateway
1646+
routes. When the listener is enabled, polling delays are capped at five seconds
1647+
even if the configured interval is longer; failed polls do not renew the lease.
1648+
App traffic uses application/edge authentication independently of gateway
16471649
user authentication. This listener stage does not add service discovery or
16481650
change the public URLs printed by the CLI.

0 commit comments

Comments
 (0)