diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index bc624aa604..d070d0659a 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -20,7 +20,9 @@ use openshell_bootstrap::{ use openshell_cli::completers; use openshell_cli::run; use openshell_cli::tls::TlsOptions; -use openshell_core::proto::{GpuResourceRequirements, ServiceAuthorizationMode}; +use openshell_core::proto::{ + GpuResourceRequirements, ServiceAuthorizationMode, ServiceBackendHttpVersion, +}; /// Resolved gateway context: name + gateway endpoint. struct GatewayContext { @@ -806,6 +808,24 @@ impl From for ServiceAuthorizationMode { } } +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)] +enum CliServiceBackendHttpVersion { + #[default] + #[value(name = "1.1")] + Http1, + #[value(name = "2")] + Http2, +} + +impl From for ServiceBackendHttpVersion { + fn from(value: CliServiceBackendHttpVersion) -> Self { + match value { + CliServiceBackendHttpVersion::Http1 => Self::Http1, + CliServiceBackendHttpVersion::Http2 => Self::Http2, + } + } +} + #[derive(Clone, Debug, ValueEnum)] enum CliProviderRefreshStrategy { Oauth2RefreshToken, @@ -2505,6 +2525,10 @@ enum ServiceCommands { /// Handling for an incoming application Authorization header. #[arg(long, value_enum, default_value_t)] authorization_mode: CliServiceAuthorizationMode, + + /// HTTP version on the sandbox loopback port. HTTP/2 requires the supervisor application listener. + #[arg(long, value_enum, default_value_t)] + backend_http_version: CliServiceBackendHttpVersion, }, /// List exposed sandbox service endpoints. @@ -3157,6 +3181,7 @@ async fn run_async() -> Result<()> { service, target_port, authorization_mode, + backend_http_version, } => { let service = service.unwrap_or_default(); run::service_expose( @@ -3165,6 +3190,7 @@ async fn run_async() -> Result<()> { &service, target_port, authorization_mode.into(), + backend_http_version.into(), &cli.workspace, &tls, ) @@ -7394,12 +7420,14 @@ mod tests { target_port, service, authorization_mode, + backend_http_version, }), }) => { assert_eq!(sandbox, "my-sandbox"); assert_eq!(target_port, 8080); assert_eq!(service.as_deref(), Some("api")); assert_eq!(authorization_mode, CliServiceAuthorizationMode::Strip); + assert_eq!(backend_http_version, CliServiceBackendHttpVersion::Http1); } other => panic!("expected service expose command, got: {other:?}"), } @@ -7418,6 +7446,7 @@ mod tests { target_port, service, authorization_mode, + .. }), }) => { assert_eq!(sandbox, "my-sandbox"); @@ -7430,7 +7459,7 @@ mod tests { } #[test] - fn service_expose_parses_bearer_passthrough() { + fn service_expose_parses_bearer_passthrough_and_http2_backend() { let cli = Cli::try_parse_from([ "openshell", "service", @@ -7439,19 +7468,26 @@ mod tests { "4500", "--authorization-mode", "bearer-passthrough", + "--backend-http-version", + "2", ]) - .expect("service authorization mode should parse"); + .expect("service authorization mode and backend HTTP version should parse"); match cli.command { Some(Commands::Service { command: Some(ServiceCommands::Expose { - authorization_mode, .. + authorization_mode, + backend_http_version, + .. }), - }) => assert_eq!( - authorization_mode, - CliServiceAuthorizationMode::BearerPassthrough - ), + }) => { + assert_eq!( + authorization_mode, + CliServiceAuthorizationMode::BearerPassthrough + ); + assert_eq!(backend_http_version, CliServiceBackendHttpVersion::Http2); + } other => panic!("expected service expose command, got: {other:?}"), } } diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 507c649617..8ec612317b 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -65,9 +65,9 @@ use openshell_core::proto::{ SandboxPolicy, SandboxResources, SandboxRestartPolicy, SandboxServiceExposure, SandboxServiceLevel, SandboxSpec, SandboxStartup, SandboxTemplate, SandboxWorkloadConfig, SandboxWorkloadTemplate, SandboxWorkloadTemplateSpec, ServiceAuthorizationMode, - ServiceEndpointResponse, SettingScope, StartSandboxRequest, StopSandboxRequest, - SuspendSandboxRequest, TcpForwardFrame, TcpForwardInit, TcpRelayTarget, UpdateConfigRequest, - WatchSandboxRequest, exec_sandbox_event, tcp_forward_init, + ServiceBackendHttpVersion, ServiceEndpointResponse, SettingScope, StartSandboxRequest, + StopSandboxRequest, SuspendSandboxRequest, TcpForwardFrame, TcpForwardInit, TcpRelayTarget, + UpdateConfigRequest, WatchSandboxRequest, exec_sandbox_event, tcp_forward_init, }; use openshell_core::settings; use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; @@ -4351,25 +4351,44 @@ async fn wait_for_lifecycle_phase( } } +#[allow(clippy::too_many_arguments)] // user-facing CLI command pub async fn service_expose( server: &str, sandbox: &str, service: &str, target_port: u16, authorization_mode: ServiceAuthorizationMode, + backend_http_version: ServiceBackendHttpVersion, workspace: &str, tls: &TlsOptions, ) -> Result<()> { - let response = expose_service_endpoint( - server, - sandbox, - service, - target_port, - authorization_mode, - workspace, - tls, - ) - .await?; + let mut client = grpc_client(server, tls).await?; + let response = client + .expose_service(ExposeServiceRequest { + request_id: String::new(), + sandbox: sandbox.to_string(), + name: service.to_string(), + target_port: u32::from(target_port), + domain: true, + authorization_mode: authorization_mode as i32, + backend_http_version: backend_http_version as i32, + workspace_scope: Some(openshell_core::proto::workspace_selector( + workspace.to_string(), + )), + }) + .await + .map_err(|status| service_status_error("expose service", "sandbox:write", sandbox, status))? + .into_inner(); + + if backend_http_version == ServiceBackendHttpVersion::Http2 + && response.endpoint.as_ref().is_none_or(|endpoint| { + endpoint.backend_http_version() != ServiceBackendHttpVersion::Http2 + }) + { + return Err(miette!( + "the gateway did not confirm the HTTP/2 backend and may have saved an HTTP/1.1 declaration. Upgrade the gateway and expose the service again" + )); + } if service.is_empty() { println!( @@ -4396,33 +4415,6 @@ pub async fn service_expose( Ok(()) } -async fn expose_service_endpoint( - server: &str, - sandbox: &str, - service: &str, - target_port: u16, - authorization_mode: ServiceAuthorizationMode, - workspace: &str, - tls: &TlsOptions, -) -> Result { - let mut client = grpc_client(server, tls).await?; - client - .expose_service(ExposeServiceRequest { - request_id: String::new(), - sandbox: sandbox.to_string(), - name: service.to_string(), - target_port: u32::from(target_port), - domain: true, - authorization_mode: authorization_mode as i32, - workspace_scope: Some(openshell_core::proto::workspace_selector( - workspace.to_string(), - )), - }) - .await - .map_err(|status| service_status_error("expose service", "sandbox:write", sandbox, status)) - .map(tonic::Response::into_inner) -} - #[allow(clippy::too_many_arguments)] // user-facing CLI command pub async fn service_list( server: &str, diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index 7ff796ac56..90eadf908f 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -25,9 +25,10 @@ use openshell_core::proto::{ ListSandboxesResponse, PlatformEvent, Provider, ProviderResponse, RevokeSshSessionRequest, RevokeSshSessionResponse, Sandbox, SandboxCondition, SandboxLogLine, SandboxPhase, SandboxResponse, SandboxStatus, SandboxStreamEvent, SandboxTemplateResponse, - SandboxWorkloadTemplate, ServiceStatus, SettingValue, TcpForwardFrame, TcpForwardInit, - TcpRelayTarget, UpdateProviderRequest, WatchSandboxRequest, sandbox_stream_event, - tcp_forward_frame, tcp_forward_init, + SandboxWorkloadTemplate, ServiceAuthorizationMode, ServiceBackendHttpVersion, ServiceEndpoint, + ServiceStatus, SettingValue, TcpForwardFrame, TcpForwardInit, TcpRelayTarget, + UpdateProviderRequest, WatchSandboxRequest, sandbox_stream_event, tcp_forward_frame, + tcp_forward_init, }; use openshell_server::test_support::grpc::open_shell_server::{OpenShell, OpenShellServer}; use std::collections::HashMap; @@ -69,6 +70,7 @@ struct SandboxState { /// The policy `GetSandboxConfig` returns. sandbox_config_policy: Arc>>, expose_service_requests: Arc>>, + expose_service_supports_http2: Arc, fail_delete_sandbox_message: Arc>>, stop_response: Arc>>, vm_error_after_started: Arc, @@ -449,17 +451,26 @@ impl OpenShell for TestOpenShell { &self, request: tonic::Request, ) -> Result, Status> { + let request = request.into_inner(); + let mut endpoint = ServiceEndpoint::default(); + if self + .state + .expose_service_supports_http2 + .load(Ordering::SeqCst) + { + endpoint.backend_http_version = request.backend_http_version; + } self.state .expose_service_requests .lock() .await - .push(request.into_inner()); + .push(request); Ok(Response::new( openshell_core::proto::ServiceEndpointResponse { application_url: String::new(), gateway_url: String::new(), url: "https://default--sandbox.openshell.localhost:17670/".to_string(), - ..Default::default() + endpoint: Some(endpoint), }, )) } @@ -2862,8 +2873,7 @@ async fn sandbox_create_exposes_service_after_ready_and_keeps_sandbox() { name: Some("sandbox"), keep: false, expose: Some(4500), - expose_authorization_mode: - openshell_core::proto::ServiceAuthorizationMode::BearerPassthrough, + expose_authorization_mode: ServiceAuthorizationMode::BearerPassthrough, detach: true, ..test_config() }, @@ -2881,7 +2891,7 @@ async fn sandbox_create_exposes_service_after_ready_and_keeps_sandbox() { assert_eq!(create_requests[0].service_exposures[0].target_port, 4500); assert_eq!( create_requests[0].service_exposures[0].authorization_mode(), - openshell_core::proto::ServiceAuthorizationMode::BearerPassthrough + ServiceAuthorizationMode::BearerPassthrough ); assert!(expose_service_requests(&server).await.is_empty()); }) @@ -2898,7 +2908,8 @@ async fn service_expose_forwards_bearer_passthrough_mode() { "sandbox", "codex", 4500, - openshell_core::proto::ServiceAuthorizationMode::BearerPassthrough, + ServiceAuthorizationMode::BearerPassthrough, + ServiceBackendHttpVersion::Http1, "default", &tls, ) @@ -2909,7 +2920,46 @@ async fn service_expose_forwards_bearer_passthrough_mode() { assert_eq!(requests.len(), 1); assert_eq!( requests[0].authorization_mode(), - openshell_core::proto::ServiceAuthorizationMode::BearerPassthrough + ServiceAuthorizationMode::BearerPassthrough + ); +} + +#[tokio::test] +async fn service_expose_requires_gateway_confirmation_for_http2() { + let server = run_server().await; + let tls = test_tls(&server); + let expose = || { + run::service_expose( + &server.endpoint, + "sandbox", + "agent", + 50051, + ServiceAuthorizationMode::Strip, + ServiceBackendHttpVersion::Http2, + "default", + &tls, + ) + }; + + let error = expose().await.unwrap_err(); + assert!( + error + .to_string() + .contains("did not confirm the HTTP/2 backend") + ); + + server + .openshell + .state + .expose_service_supports_http2 + .store(true, Ordering::SeqCst); + expose().await.expect("gateway confirmed HTTP/2"); + + let requests = expose_service_requests(&server).await; + assert_eq!(requests.len(), 2); + assert_eq!( + requests[0].backend_http_version(), + ServiceBackendHttpVersion::Http2 ); } diff --git a/crates/openshell-sandbox-backend/src/runtime/test_support.rs b/crates/openshell-sandbox-backend/src/runtime/test_support.rs index 0db379981f..418891ae65 100644 --- a/crates/openshell-sandbox-backend/src/runtime/test_support.rs +++ b/crates/openshell-sandbox-backend/src/runtime/test_support.rs @@ -596,7 +596,7 @@ async fn relay_io( } writer.shutdown().await }; - let read = async { + let read = async move { let mut b = vec![0; 16384]; loop { let n = reader.read(&mut b).await?; @@ -613,7 +613,12 @@ async fn relay_io( } Ok::<_, std::io::Error>(()) }; - let _ = tokio::join!(write, read); + tokio::pin!(read); + tokio::select! { + // Backend EOF ends the response even while the request remains open. + _ = &mut read => {}, + _ = write => { let _ = read.await; }, + } } struct TestTlsIo(BoundaryDuplexStream); diff --git a/crates/openshell-sandbox/src/boundary_server.rs b/crates/openshell-sandbox/src/boundary_server.rs index 038708c654..90f55f3ee8 100644 --- a/crates/openshell-sandbox/src/boundary_server.rs +++ b/crates/openshell-sandbox/src/boundary_server.rs @@ -1820,10 +1820,12 @@ mod linux { // Do not retain the response sender while the client request direction // stays open: finite exchanges must still observe the server's EOF. let invalid_frames = outbound.downgrade(); + let (cancel_inbound, inbound_cancelled) = tokio::sync::oneshot::channel(); let mut inbound_closed = connection_closed.clone(); tokio::spawn(async move { tokio::select! { _ = inbound_closed.changed() => {}, + Ok(()) = inbound_cancelled => {}, () = async { let mut mode = openshell_sandbox_backend::stream_adapter::Mode::Request; loop { @@ -1860,6 +1862,7 @@ mod linux { tokio::spawn(async move { tokio::select! { _ = outbound_closed.changed() => {}, + () = outbound.closed() => {}, () = async { let mut mode = openshell_sandbox_backend::stream_adapter::Mode::Response; loop { @@ -1871,6 +1874,11 @@ mod linux { } } => {}, } + // A reset must release both halves even if the inbound pump is + // blocked writing to the local stream. Backend EOF keeps it open. + if outbound.is_closed() { + let _ = cancel_inbound.send(()); + } }); (application, ReceiverStream::new(outbound_rx)) } diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index da516927a6..b1fcea30bb 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -12389,6 +12389,7 @@ mod tests { target_port: 8080, domain: true, authorization_mode: ServiceAuthorizationMode::Strip as i32, + backend_http_version: 0, } } diff --git a/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs b/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs index 07a45aff92..6765171975 100644 --- a/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs +++ b/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs @@ -622,7 +622,9 @@ sandbox_scoped_mutation!( Ok(ServiceEndpointResponse { application_url, gateway_url: gateway_url.unwrap_or_else(|| url.clone()), - endpoint: Some(reference.restore(store).await?), + endpoint: Some(service::service_response_endpoint( + reference.restore(store).await?, + )), url, }) } diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 0ef35327d6..7caff43df4 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -42,7 +42,7 @@ use openshell_core::proto::{ }; use openshell_core::proto::{ BeginRootfsTarStagingRequest, BeginRootfsTarStagingResponse, Sandbox, SandboxPhase, - SandboxRestartPolicy, SandboxTemplate, SshSession, + SandboxRestartPolicy, SandboxTemplate, ServiceBackendHttpVersion, SshSession, }; use openshell_core::telemetry::{ LifecycleOperation, LifecycleResource, SandboxTemplateSource, TelemetryOutcome, @@ -842,6 +842,7 @@ async fn handle_create_sandbox_inner( exposure.target_port, exposure.authorization_mode, )?, + ServiceBackendHttpVersion::Unspecified, ) .await { diff --git a/crates/openshell-server/src/grpc/service.rs b/crates/openshell-server/src/grpc/service.rs index f01f2cf005..5c95fef3b0 100644 --- a/crates/openshell-server/src/grpc/service.rs +++ b/crates/openshell-server/src/grpc/service.rs @@ -7,8 +7,8 @@ use std::sync::Arc; use openshell_core::proto::datamodel::v1::ObjectMeta; use openshell_core::proto::{ DeleteServiceRequest, DeleteServiceResponse, ExposeServiceRequest, GetServiceRequest, - ListServicesRequest, ListServicesResponse, Sandbox, ServiceAuthorizationMode, ServiceEndpoint, - ServiceEndpointResponse, + ListServicesRequest, ListServicesResponse, Sandbox, ServiceAuthorizationMode, + ServiceBackendHttpVersion, ServiceEndpoint, ServiceEndpointResponse, }; use openshell_core::{GetResourceVersion, ObjectId, ObjectName, ObjectWorkspace}; use prost::Message as _; @@ -54,6 +54,21 @@ pub(super) async fn handle_expose_service( .ensure_active()?; let authorization_mode = validate_service_exposure_request(&req.name, req.target_port, req.authorization_mode)?; + let backend_http_version = match ServiceBackendHttpVersion::try_from(req.backend_http_version) { + Ok(ServiceBackendHttpVersion::Unspecified | ServiceBackendHttpVersion::Http1) => { + // Older supervisors omit zero-valued fields in their installation reports. + ServiceBackendHttpVersion::Unspecified + } + Ok(ServiceBackendHttpVersion::Http2) if state.config.supervisor_app_listener.enabled => { + ServiceBackendHttpVersion::Http2 + } + Ok(ServiceBackendHttpVersion::Http2) => { + return Err(Status::failed_precondition( + "HTTP/2 backends require the supervisor application listener", + )); + } + Err(_) => return Err(Status::invalid_argument("backend_http_version is invalid")), + }; expose_service_endpoint( state, &workspace, @@ -61,6 +76,7 @@ pub(super) async fn handle_expose_service( &req.name, req.target_port, authorization_mode, + backend_http_version, ) .await } @@ -92,6 +108,7 @@ pub(super) async fn expose_service_endpoint( service: &str, target_port: u32, authorization_mode: ServiceAuthorizationMode, + backend_http_version: ServiceBackendHttpVersion, ) -> Result, Status> { // Hold the hardening guard across sandbox validation, route counting and // persistence. Acquisition is unconditional because advertisements also @@ -186,6 +203,7 @@ pub(super) async fn expose_service_endpoint( target_port, domain: true, authorization_mode: authorization_mode as i32, + backend_http_version: backend_http_version as i32, }; let route_reserved = state @@ -452,6 +470,7 @@ pub(super) fn configured_app_routes_from_endpoints( name: ep.name.clone(), target_port: ep.target_port, authorization_mode: ep.authorization_mode, + backend_http_version: ep.backend_http_version, resource_version: ep.metadata.as_ref().map_or(0, |m| m.resource_version), application_hostname: state .config @@ -511,10 +530,7 @@ async fn get_service_endpoint( .map_err(|e| Status::internal(format!("fetch endpoint failed: {e}"))) } -fn service_endpoint_response( - state: &Arc, - mut endpoint: ServiceEndpoint, -) -> ServiceEndpointResponse { +pub(super) fn service_response_endpoint(mut endpoint: ServiceEndpoint) -> ServiceEndpoint { endpoint.authorization_mode = match ServiceAuthorizationMode::try_from(endpoint.authorization_mode) { Ok(ServiceAuthorizationMode::BearerPassthrough) => { @@ -523,8 +539,18 @@ fn service_endpoint_response( Ok(ServiceAuthorizationMode::Unspecified | ServiceAuthorizationMode::Strip) | Err(_) => ServiceAuthorizationMode::Strip as i32, }; + if endpoint.backend_http_version == ServiceBackendHttpVersion::Unspecified as i32 { + endpoint.backend_http_version = ServiceBackendHttpVersion::Http1 as i32; + } + endpoint +} + +fn service_endpoint_response( + state: &Arc, + endpoint: ServiceEndpoint, +) -> ServiceEndpointResponse { let mut response = ServiceEndpointResponse { - endpoint: Some(endpoint), + endpoint: Some(service_response_endpoint(endpoint)), ..Default::default() }; refresh_response_urls(state, &mut response); @@ -541,13 +567,17 @@ fn refresh_response_urls(state: &ServerState, response: &mut ServiceEndpointResp let Some(endpoint) = response.endpoint.as_ref() else { return; }; - response.gateway_url = service_routing::endpoint_url( - &state.config, - endpoint.object_workspace(), - &endpoint.sandbox, - &endpoint.name, - ) - .unwrap_or_default(); + response.gateway_url = if endpoint.backend_http_version() == ServiceBackendHttpVersion::Http2 { + String::new() + } else { + service_routing::endpoint_url( + &state.config, + endpoint.object_workspace(), + &endpoint.sandbox, + &endpoint.name, + ) + .unwrap_or_default() + }; response.application_url = state .config .supervisor_app_listener @@ -660,6 +690,7 @@ mod tests { target_port: 8080, domain: true, authorization_mode: ServiceAuthorizationMode::Strip as i32, + backend_http_version: 0, }) .await .unwrap(); @@ -781,6 +812,10 @@ mod tests { .await .unwrap() .into_inner(); + assert_eq!( + created.endpoint.as_ref().unwrap().backend_http_version(), + ServiceBackendHttpVersion::Http1 + ); assert_eq!(!created.gateway_url.is_empty(), gateway_enabled); assert_eq!(!created.application_url.is_empty(), application_enabled); if application_enabled { @@ -816,6 +851,70 @@ mod tests { } } + #[tokio::test] + async fn http2_service_requires_application_ingress_and_reaches_its_route() { + let mut state = test_server_state().await; + seed_sandbox(&state, "demo").await; + let mut request = ExposeServiceRequest { + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + sandbox: "demo".into(), + name: "agent".into(), + target_port: 50051, + backend_http_version: ServiceBackendHttpVersion::Http2 as i32, + ..Default::default() + }; + + let error = handle_expose_service(&state, authed_request(request.clone())) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + + let config = &mut Arc::get_mut(&mut state).unwrap().config; + config.service_routing.enabled = true; + config.supervisor_app_listener = openshell_core::app_listener::AppListenerConfig { + enabled: true, + port: 9443, + base_url: Some("https://services.example.com:10443".into()), + }; + + let response = handle_expose_service(&state, authed_request(request.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!( + response.url, + "https://default--demo--agent.services.example.com:10443/" + ); + assert!(response.gateway_url.is_empty()); + let endpoint = response.endpoint.unwrap(); + assert_eq!( + endpoint.backend_http_version(), + ServiceBackendHttpVersion::Http2 + ); + + request.backend_http_version = 99; + let error = handle_expose_service(&state, authed_request(request)) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + + let stored = get_service_endpoint(&state, "default", "demo", "agent") + .await + .unwrap() + .unwrap(); + let sandbox = state + .store + .get_message::(&stored.sandbox_id) + .await + .unwrap() + .unwrap(); + let routes = configured_app_routes_from_endpoints(&state, &sandbox, vec![stored]).unwrap(); + assert_eq!( + routes[0].backend_http_version, + ServiceBackendHttpVersion::Http2 as i32 + ); + } + #[tokio::test] async fn hashed_gateway_url_keeps_the_independent_application_origin() { let mut state = test_server_state().await; @@ -1156,6 +1255,7 @@ mod tests { target_port: 8080, domain: true, authorization_mode: ServiceAuthorizationMode::Unspecified as i32, + backend_http_version: 0, }), ) .await @@ -1352,6 +1452,7 @@ mod tests { target_port: 8080, domain: true, authorization_mode: ServiceAuthorizationMode::Strip as i32, + backend_http_version: 0, }), ) .await @@ -1371,6 +1472,7 @@ mod tests { target_port: 9090, domain: true, authorization_mode: ServiceAuthorizationMode::Strip as i32, + backend_http_version: 0, }), ) .await @@ -1424,6 +1526,7 @@ mod tests { target_port: 7070, domain: true, authorization_mode: ServiceAuthorizationMode::Strip as i32, + backend_http_version: 0, }), ) .await @@ -1444,6 +1547,7 @@ mod tests { target_port: 8080, domain: true, authorization_mode: ServiceAuthorizationMode::Strip as i32, + backend_http_version: 0, }), ) .await @@ -1463,6 +1567,7 @@ mod tests { target_port: 9090, domain: true, authorization_mode: ServiceAuthorizationMode::Strip as i32, + backend_http_version: 0, }), ) .await @@ -1554,6 +1659,7 @@ mod tests { target_port: 8080, domain: true, authorization_mode: ServiceAuthorizationMode::Strip as i32, + backend_http_version: 0, }), ) .await @@ -1571,6 +1677,7 @@ mod tests { target_port: 9090, domain: true, authorization_mode: ServiceAuthorizationMode::Strip as i32, + backend_http_version: 0, }), ) .await @@ -1715,6 +1822,7 @@ mod tests { target_port: 3000, domain: true, authorization_mode: ServiceAuthorizationMode::Strip as i32, + backend_http_version: 0, }), ) .await diff --git a/crates/openshell-server/src/grpc/service_advertisement.rs b/crates/openshell-server/src/grpc/service_advertisement.rs index b69ae07ac2..77dd8895a9 100644 --- a/crates/openshell-server/src/grpc/service_advertisement.rs +++ b/crates/openshell-server/src/grpc/service_advertisement.rs @@ -1002,6 +1002,7 @@ mod tests { name: "web".into(), target_port: 8080, authorization_mode: 1, + backend_http_version: 0, resource_version: 2, application_hostname: String::new(), } @@ -1177,6 +1178,10 @@ mod tests { ..Default::default() }; validate_routes(&report, std::slice::from_ref(&declared)).unwrap(); + report.routes[0].backend_http_version = + openshell_core::proto::ServiceBackendHttpVersion::Http2 as i32; + assert!(validate_routes(&report, std::slice::from_ref(&declared)).is_err()); + report.routes[0] = declared.clone(); report.routes[0].target_port = 9090; assert!(validate_routes(&report, std::slice::from_ref(&declared)).is_err()); report.routes = vec![declared.clone(), declared.clone()]; @@ -1273,6 +1278,7 @@ pub(super) mod test_support { target_port: 8080, domain: true, authorization_mode: 1, + backend_http_version: 0, }; state.store.put_message(&endpoint).await.unwrap(); let owner = SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL) diff --git a/crates/openshell-server/src/service_routing.rs b/crates/openshell-server/src/service_routing.rs index 86a793bb5a..dfd84ff9d6 100644 --- a/crates/openshell-server/src/service_routing.rs +++ b/crates/openshell-server/src/service_routing.rs @@ -13,7 +13,8 @@ pub use openshell_core::app_listener::service_route_hash_label; use openshell_core::app_listener::service_route_label; use openshell_core::config::ServiceRoutingConfig; use openshell_core::proto::{ - Sandbox, SandboxPhase, ServiceAuthorizationMode, ServiceEndpoint, TcpRelayTarget, relay_open, + Sandbox, SandboxPhase, ServiceAuthorizationMode, ServiceBackendHttpVersion, ServiceEndpoint, + TcpRelayTarget, relay_open, }; use openshell_core::{ObjectId, ObjectWorkspace}; use openshell_ocsf::{ @@ -633,7 +634,11 @@ async fn proxy_to_endpoint( return Err(err); } }; - if !endpoint.domain || endpoint.target_port == 0 || endpoint.target_port > u32::from(u16::MAX) { + if !endpoint.domain + || endpoint.target_port == 0 + || endpoint.target_port > u32::from(u16::MAX) + || endpoint.backend_http_version() == ServiceBackendHttpVersion::Http2 + { let err = ServiceRouteError::endpoint_unavailable(); emit_service_http_failure( &state, @@ -1483,6 +1488,7 @@ mod tests { target_port: 8080, domain: true, authorization_mode: ServiceAuthorizationMode::Strip as i32, + backend_http_version: 0, } } @@ -2374,6 +2380,7 @@ mod tests { target_port: 8080, domain: true, authorization_mode: ServiceAuthorizationMode::Strip as i32, + backend_http_version: 0, }; store.put_message(&ep).await.unwrap(); diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index f20bbbd3cb..e01957faa0 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -249,14 +249,16 @@ mod tests { // Discovery RPCs move to ServiceDiscovery. Application URL maps add two // public-only messages alongside main's public APIs; durable schemas // and the public/durable overlap remain unchanged. + // The service backend HTTP version is part of both schemas. Legacy + // endpoint records omit it and continue to use HTTP/1.1. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "dc96b55350209d252c8eb22a697fede2abf26d6bcb80223774c5fa093dca885b"; + "3c1c932ec40e0c29a8c844f84d936178c19aec8f233ae0fcb2f7980dc13a70a0"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = - "1005cf2557d49ea54a302cc76d837cc1a6c637adb0db73ec9444569e8d39fd71"; + "ca31950286327bc385fae933bbb9e34d3c9191214f9b549c558bba40957fcc65"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = - "c7a66485b85999c0227d1eef52b159b3be5c05d68c0a900f5f6303021a46d75f"; + "d0eead2cd403f6f52ecd9b7df73ca7db15e84dd847e11bc9d50469970204e589"; // Encoded with the schema that omitted stable_placeholder. Keep these // bytes fixed so the current encoder cannot hide a compatibility change. const LEGACY_STATIC_PROFILE: &str = "0a240a116c65676163792d70726f66696c652d6964120d6c65676163792d737461746963280712510a0d6c65676163792d73746174696312184c6567616379207374617469632063726564656e7469616c2a260a076170695f6b65791a1153594e5448455449435f4150495f4b455920012a06626561726572"; @@ -800,9 +802,9 @@ mod tests { overlap_hash.as_str(), ), ( - (369, 31), - (104, 22), - (88, 22), + (369, 32), + (104, 23), + (88, 23), PUBLIC_RPC_SCHEMA_SHA256, DURABLE_SCHEMA_SHA256, PUBLIC_DURABLE_OVERLAP_SHA256 @@ -813,7 +815,9 @@ mod tests { #[test] fn service_endpoint_without_authorization_mode_decodes_as_strip() { - use openshell_core::proto::{ServiceAuthorizationMode, ServiceEndpoint}; + use openshell_core::proto::{ + ServiceAuthorizationMode, ServiceBackendHttpVersion, ServiceEndpoint, + }; let endpoint = ServiceEndpoint::decode( legacy_bytes(SERVICE_ENDPOINT_WITHOUT_AUTHORIZATION_MODE).as_slice(), @@ -833,6 +837,10 @@ mod tests { crate::service_routing::effective_authorization_mode(endpoint.authorization_mode), ServiceAuthorizationMode::Strip ); + assert_eq!( + endpoint.backend_http_version(), + ServiceBackendHttpVersion::Unspecified + ); } #[test] diff --git a/crates/openshell-supervisor/src/app_listener.rs b/crates/openshell-supervisor/src/app_listener.rs index f6912c1784..455e0c810e 100644 --- a/crates/openshell-supervisor/src/app_listener.rs +++ b/crates/openshell-supervisor/src/app_listener.rs @@ -11,13 +11,15 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use axum::body::Body; -use http::{Request, Response, StatusCode, header}; +use http::{Method, Request, Response, StatusCode, Version, header}; +use http_body_util::BodyExt as _; use hyper::body::Incoming; -use hyper_util::rt::{TokioIo, TokioTimer}; +use hyper::rt::Executor as _; +use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer}; use miette::{IntoDiagnostic, Result}; use openshell_core::grpc_client::SettingsPollResult; -use openshell_core::proto::SandboxServiceRoute; -use openshell_isolation_interface::contract::LoopbackTarget; +use openshell_core::proto::{SandboxServiceRoute, ServiceBackendHttpVersion}; +use openshell_isolation_interface::contract::{BoundaryDuplexStream, LoopbackTarget}; use openshell_ocsf::{ ActionId, ActivityId, AppLifecycleBuilder, ConfigStateChangeBuilder, DispositionId, HttpActivityBuilder, HttpResponse, NetworkActivityBuilder, SeverityId, StatusId, ocsf_emit, @@ -25,7 +27,7 @@ use openshell_ocsf::{ use openshell_sandbox_backend::BoundaryLoopbackConnector; use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject}; use std::sync::Mutex; -use tokio::sync::{Semaphore, mpsc, watch}; +use tokio::sync::{Notify, OwnedSemaphorePermit, Semaphore, mpsc, watch}; use tokio::task::JoinSet; use tokio::time::Instant; use tokio_rustls::TlsAcceptor; @@ -33,6 +35,8 @@ use tokio_rustls::TlsAcceptor; const FRESHNESS: Duration = Duration::from_secs(30); const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10); const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); +const MAX_INSTANCE_CONNECTIONS: usize = 64; +const MAX_HTTP2_STREAMS: u32 = 16; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum InstallRejection { @@ -134,7 +138,7 @@ impl Config { .with_no_client_auth() .with_single_cert(certificates, key) .into_diagnostic()?; - tls.alpn_protocols = vec![b"http/1.1".to_vec()]; + tls.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; let socket = std::net::TcpListener::bind(self.address).into_diagnostic()?; socket.set_nonblocking(true).into_diagnostic()?; let listener = tokio::net::TcpListener::from_std(socket).into_diagnostic()?; @@ -305,6 +309,7 @@ impl Routes { || route.target_port == 0 || route.target_port > 65535 || !matches!(route.authorization_mode, 0..=2) + || ServiceBackendHttpVersion::try_from(route.backend_http_version).is_err() || (!route.name.is_empty() && (!openshell_core::app_listener::valid_dns_label(&route.name) || route.name.contains("--"))) @@ -512,7 +517,7 @@ pub struct Router { struct Accepted { tls: tokio_rustls::server::TlsStream, - permit: tokio::sync::OwnedSemaphorePermit, + permit: OwnedSemaphorePermit, } struct Registration { @@ -745,8 +750,9 @@ impl BoundListener { } struct Permits { - _host: tokio::sync::OwnedSemaphorePermit, - _instance: tokio::sync::OwnedSemaphorePermit, + _host: OwnedSemaphorePermit, + _instance: OwnedSemaphorePermit, + relays: Arc, } impl InstanceListener { @@ -757,7 +763,9 @@ impl InstanceListener { let retained_routes = self.routes.clone(); let task = tokio::spawn(async move { let routes = self.routes.clone(); - let permits = Arc::new(Semaphore::new(64)); + let permits = Arc::new(Semaphore::new(MAX_INSTANCE_CONNECTIONS)); + // Multiplexed requests share the previous per-instance relay budget. + let relays = Arc::new(Semaphore::new(MAX_INSTANCE_CONNECTIONS)); let mut connections = JoinSet::new(); ocsf_emit!( AppLifecycleBuilder::new(crate::ocsf_ctx()) @@ -780,17 +788,40 @@ impl InstanceListener { }; let routes = routes.clone(); let connector = connector.clone(); + let relays = relays.clone(); connections.spawn(async move { let connection_routes = routes.clone(); let connection_route = route.clone(); - let permit = Arc::new(Permits { _host: host_permit, _instance: instance_permit }); - let service = hyper::service::service_fn(move |req| { + let permit = Arc::new(Permits { _host: host_permit, _instance: instance_permit, relays }); + let service = move |req| { proxy(req, sni.clone(), route.clone(), routes.clone(), connector.clone(), permit.clone(), token) - }); - let connection = hyper::server::conn::http1::Builder::new() - .timer(TokioTimer::new()).header_read_timeout(HANDSHAKE_TIMEOUT) - .max_buf_size(65536).max_headers(64) - .serve_connection(TokioIo::new(tls), service).with_upgrades(); + }; + let connection = async { + if tls.get_ref().1.alpn_protocol() == Some(b"h2") { + let first_request = Arc::new(Notify::new()); + let started = first_request.clone(); + let service = hyper::service::service_fn(move |req| { + started.notify_one(); + service(req) + }); + let connection = hyper::server::conn::http2::Builder::new(TokioExecutor::new()) + .max_concurrent_streams(MAX_HTTP2_STREAMS) + .max_header_list_size(65536) + .serve_connection(TokioIo::new(tls), service); + tokio::pin!(connection); + tokio::select! { + result = &mut connection => return result, + () = first_request.notified() => {}, + () = tokio::time::sleep(HANDSHAKE_TIMEOUT) => return Ok(()), + } + connection.await + } else { + hyper::server::conn::http1::Builder::new() + .timer(TokioTimer::new()).header_read_timeout(HANDSHAKE_TIMEOUT) + .max_buf_size(65536).max_headers(64) + .serve_connection(TokioIo::new(tls), hyper::service::service_fn(service)).with_upgrades().await + } + }; tokio::select! { _ = connection => {}, () = connection_routes.revoked(&connection_route, token) => {}, @@ -858,31 +889,33 @@ fn emit_denial(message: &str) { ); } -fn authority_matches(req: &Request, sni: &str) -> bool { +fn request_authority(req: &Request, sni: &str) -> Option { let mut values = req.headers().get_all(header::HOST).iter(); - let Some(value) = values.next() else { - return false; - }; - if values.next().is_some() { - return false; - } - let Ok(value) = value.to_str() else { - return false; + let host = values + .next() + .map(header::HeaderValue::to_str) + .transpose() + .ok()?; + let uri_authority = req.uri().authority().map(http::uri::Authority::as_str); + let value = if req.version() == Version::HTTP_2 { + uri_authority? + } else { + host? }; - if value.contains('@') { - return false; + if values.next().is_some() + || host.is_some_and(|host| !host.eq_ignore_ascii_case(value)) + || uri_authority.is_some_and(|uri| !uri.eq_ignore_ascii_case(value)) + || value.contains('@') + { + return None; } - let Ok(authority) = value.parse::() else { - return false; - }; - if authority.port().is_some() && authority.port_u16().is_none() { - return false; + let authority = value.parse::().ok()?; + if !authority.host().eq_ignore_ascii_case(sni) + || (authority.port().is_some() && authority.port_u16().is_none()) + { + return None; } - authority.host().eq_ignore_ascii_case(sni) - && req - .uri() - .authority() - .is_none_or(|uri| uri.as_str().eq_ignore_ascii_case(value)) + value.parse().ok() } fn gateway_header(name: &str) -> bool { @@ -1008,20 +1041,34 @@ async fn proxy( if !routes.valid(&route, token) { return Ok(error(StatusCode::SERVICE_UNAVAILABLE)); } - if !authority_matches(&req, &sni) { + let Some(authority) = request_authority(&req, &sni) else { return Ok(error(StatusCode::MISDIRECTED_REQUEST)); + }; + let downstream_http2 = req.version() == Version::HTTP_2; + let backend_http2 = route.backend_http_version == ServiceBackendHttpVersion::Http2 as i32; + if backend_http2 && !downstream_http2 { + return Ok(error(StatusCode::HTTP_VERSION_NOT_SUPPORTED)); } - // Keep the public authority after validating it against SNI. The dial target - // is loopback, but rewriting Host would break application same-origin checks. - let authority = req.headers()[header::HOST].clone(); - let websocket = req + if downstream_http2 && req.method() == Method::CONNECT { + return Ok(error(StatusCode::METHOD_NOT_ALLOWED)); + } + let websocket = !downstream_http2 + && req + .headers() + .get(header::UPGRADE) + .is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"websocket")); + let te_trailers = req .headers() - .get(header::UPGRADE) - .is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"websocket")); + .get(header::TE) + .is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"trailers")); if !sanitize_headers(req.headers_mut(), route.authorization_mode == 2, websocket) { return Ok(error(StatusCode::BAD_REQUEST)); } - let downstream = websocket.then(|| hyper::upgrade::on(&mut req)); + // Preserve the validated public authority for application same-origin checks. + req.headers_mut().insert(header::HOST, authority); + let Ok(relay_permit) = permit.relays.clone().try_acquire_owned() else { + return Ok(error(StatusCode::SERVICE_UNAVAILABLE)); + }; let target = LoopbackTarget::new( "127.0.0.1".parse().expect("loopback"), u16::try_from(route.target_port).expect("validated route port"), @@ -1031,25 +1078,37 @@ async fn proxy( else { return Ok(error(StatusCode::BAD_GATEWAY)); }; + let (active, receiver) = watch::channel(()); + let executor = RelayExecutor { + active: receiver, + permit: Arc::new(relay_permit), + }; + if backend_http2 { + if te_trailers { + req.headers_mut() + .insert(header::TE, header::HeaderValue::from_static("trailers")); + } + return Ok(proxy_http2(req, stream, executor, active).await); + } + let downstream = websocket.then(|| hyper::upgrade::on(&mut req)); let Ok((mut sender, connection)) = hyper::client::conn::http1::handshake(TokioIo::new(stream)).await else { return Ok(error(StatusCode::BAD_GATEWAY)); }; - let upstream_task = tokio::spawn(async move { - let _ = connection.with_upgrades().await; - }); + executor.execute(connection.with_upgrades()); let (mut parts, body) = req.into_parts(); + if downstream_http2 { + parts.version = Version::HTTP_11; + } parts.uri = parts .uri .path_and_query() .map_or("/", |path| path.as_str()) .parse() .expect("valid path"); - parts.headers.insert(header::HOST, authority); let response = sender.send_request(Request::from_parts(parts, body)).await; let Ok(mut response) = response else { - upstream_task.abort(); return Ok(error(StatusCode::BAD_GATEWAY)); }; let upgraded = response.status() == StatusCode::SWITCHING_PROTOCOLS && websocket; @@ -1058,7 +1117,8 @@ async fn proxy( let upstream = hyper::upgrade::on(&mut response); let downstream = downstream.expect("websocket upgrade"); tokio::spawn(async move { - let _permit = permit; + let _connection_permits = permit; + let _relay = (active, executor); tokio::select! { () = async { if let (Ok(upstream), Ok(downstream)) = tokio::join!(upstream, downstream) { @@ -1067,17 +1127,76 @@ async fn proxy( } => {}, () = routes.revoked(&route, token) => {}, } - upstream_task.abort(); }); let (parts, _) = response.into_parts(); return Ok(Response::from_parts(parts, Body::empty())); } - let (parts, body) = response.into_parts(); - Ok(Response::from_parts(parts, Body::new(body))) + Ok(response.map(|body| relay_body(body, active))) +} + +#[derive(Clone)] +struct RelayExecutor { + active: watch::Receiver<()>, + permit: Arc, +} + +impl hyper::rt::Executor for RelayExecutor +where + F: Future + Send + 'static, +{ + fn execute(&self, future: F) { + let mut active = self.active.clone(); + let permit = self.permit.clone(); + tokio::spawn(async move { + let _permit = permit; + tokio::select! { + _ = future => {}, + _ = active.changed() => {}, + } + }); + } +} + +fn relay_body(body: Incoming, active: watch::Sender<()>) -> Body { + Body::new(body.map_frame(move |frame| { + // Dropping the downstream body releases this request's loopback connection. + let _active = &active; + frame + })) +} + +async fn proxy_http2( + req: Request, + stream: BoundaryDuplexStream, + executor: RelayExecutor, + active: watch::Sender<()>, +) -> Response { + let handshake = hyper::client::conn::http2::handshake(executor.clone(), TokioIo::new(stream)); + let Ok(Ok((mut sender, connection))) = tokio::time::timeout(CONNECT_TIMEOUT, handshake).await + else { + return error(StatusCode::BAD_GATEWAY); + }; + executor.execute(connection); + let req = req.map(|body| { + body.map_frame(|mut frame| { + if let Some(trailers) = frame.trailers_mut() { + // Credentials are allowed only in the initial request headers. + sanitize_headers(trailers, false, false); + } + frame + }) + }); + let Ok(mut response) = sender.send_request(req).await else { + return error(StatusCode::BAD_GATEWAY); + }; + strip_hop_headers(response.headers_mut(), false); + response.map(|body| relay_body(body, active)) } #[cfg(test)] mod tests { + mod http2; + use super::*; use futures::{SinkExt as _, StreamExt as _}; use openshell_isolation_interface::contract::{BackendError, BoundaryDuplexStream}; @@ -1098,6 +1217,7 @@ mod tests { authorization_mode: 1, resource_version: 1, application_hostname: String::new(), + backend_http_version: 0, }; let mut config = installed(vec![route.clone()]); config.config_revision = 42; @@ -1140,6 +1260,7 @@ mod tests { authorization_mode: 1, resource_version: 1, application_hostname: String::new(), + backend_http_version: 0, }; routes.install(&installed(vec![route.clone()])); let source = routes.installation_source(); @@ -1175,6 +1296,7 @@ mod tests { authorization_mode: 1, resource_version: 1, application_hostname: String::new(), + backend_http_version: 0, }; routes.install(&installed(vec![route.clone()])); assert!( @@ -1466,6 +1588,13 @@ mod tests { .body(Body::from("upstream closed")) .unwrap()); } + if req.uri().path() == "/stream" { + return Ok(Response::new(Body::from_stream( + futures::stream::pending::< + Result, + >(), + ))); + } let body = format!( "{} {} {} {}", req.uri(), @@ -1491,7 +1620,7 @@ mod tests { } struct Fixture { - _directory: tempfile::TempDir, + directory: tempfile::TempDir, handle: Handle, address: SocketAddr, tls: Arc, @@ -1537,6 +1666,7 @@ mod tests { authorization_mode: 1, resource_version: 1, application_hostname: String::new(), + backend_http_version: 0, }; routes.install(&installed(vec![route.clone()])); let connector = Arc::new(Connector { @@ -1544,7 +1674,7 @@ mod tests { }); let handle = instance.start(rpc_test::loopback(connector.clone())); Fixture { - _directory: directory, + directory, handle, address, tls, @@ -1899,6 +2029,7 @@ mod tests { authorization_mode: 1, resource_version: 1, application_hostname: String::new(), + backend_http_version: 0, }; routes.install(&installed(vec![route.clone()])); for _ in 0..10 { diff --git a/crates/openshell-supervisor/src/app_listener/tests/http2.rs b/crates/openshell-supervisor/src/app_listener/tests/http2.rs new file mode 100644 index 0000000000..c8f93ce716 --- /dev/null +++ b/crates/openshell-supervisor/src/app_listener/tests/http2.rs @@ -0,0 +1,268 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use http_body_util::BodyExt as _; +use hyper_util::rt::TokioExecutor; +use tonic::codegen::{BoxFuture, BoxStream}; + +async fn http2_tls(f: &Fixture) -> tokio_rustls::client::TlsStream { + let stream = openshell_core::net::connect_tcp_nodelay_best_effort(f.address) + .await + .unwrap(); + let mut config = (*f.tls).clone(); + config.alpn_protocols = vec![b"h2".to_vec()]; + let tls = tokio_rustls::TlsConnector::from(Arc::new(config)) + .connect( + rustls::pki_types::ServerName::try_from(HOST).unwrap(), + stream, + ) + .await + .unwrap(); + assert_eq!(tls.get_ref().1.alpn_protocol(), Some(b"h2".as_slice())); + tls +} + +async fn http2_client(f: &Fixture) -> hyper::client::conn::http2::SendRequest { + let tls = http2_tls(f).await; + let (sender, connection) = + hyper::client::conn::http2::handshake(TokioExecutor::new(), TokioIo::new(tls)) + .await + .unwrap(); + tokio::spawn(connection); + sender +} + +#[tokio::test] +async fn http2_frontend_closes_if_no_request_arrives() { + let f = fixture(); + let mut tls = http2_tls(&f).await; + let mut frames = Vec::new(); + let result = tokio::time::timeout( + HANDSHAKE_TIMEOUT + Duration::from_secs(3), + tls.read_to_end(&mut frames), + ) + .await + .expect("listener closed the idle HTTP/2 connection"); + if let Err(error) = result { + assert_eq!(error.kind(), std::io::ErrorKind::UnexpectedEof); + } + assert_eq!(f.connector.calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn http2_frontend_limits_concurrent_relays_across_connections() { + let f = fixture(); + let request = || { + Request::get(format!("https://{HOST}/stream")) + .body(Body::empty()) + .unwrap() + }; + let mut clients = Vec::new(); + let mut responses = Vec::new(); + let max_streams = MAX_HTTP2_STREAMS as usize; + for _ in 0..MAX_INSTANCE_CONNECTIONS.div_ceil(max_streams) { + let mut client = http2_client(&f).await; + for _ in 0..max_streams.min(MAX_INSTANCE_CONNECTIONS - responses.len()) { + let response = client.send_request(request()).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + responses.push(response); + } + clients.push(client); + } + + let response = http2_client(&f) + .await + .send_request(request()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + assert!(clients.iter().all(|client| !client.is_closed())); + assert_eq!( + f.connector.calls.load(Ordering::SeqCst), + MAX_INSTANCE_CONNECTIONS + ); +} + +#[tokio::test] +async fn http2_frontend_preserves_http1_routes_and_checks_authority_before_dialing() { + let f = fixture(); + let mut client = http2_client(&f).await; + let request = |host: &str| { + Request::get(format!("https://{host}/hello?x=1")) + .header(header::AUTHORIZATION, "Bearer app-token") + .body(Body::empty()) + .unwrap() + }; + let mismatch = client + .send_request(request("default--sandbox-b--web.svc.openshell.internal")) + .await + .unwrap(); + assert_eq!(mismatch.status(), StatusCode::MISDIRECTED_REQUEST); + assert_eq!(f.connector.calls.load(Ordering::SeqCst), 0); + + let response = client.send_request(request(HOST)).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.into_body().collect().await.unwrap().to_bytes(), + format!("/hello?x=1 {HOST} stripped absent") + ); + assert_eq!(f.connector.calls.load(Ordering::SeqCst), 1); + + f.routes.install(&installed(vec![SandboxServiceRoute { + backend_http_version: 2, + ..f.route.clone() + }])); + let response = http2_client(&f) + .await + .send_request(request(HOST)) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_GATEWAY); + assert_eq!(f.connector.calls.load(Ordering::SeqCst), 2); +} + +#[derive(Clone, PartialEq, prost::Message)] +struct Message { + #[prost(string, tag = "1")] + text: String, +} + +struct Echo(Arc); + +struct NotifyOnDrop(Arc); + +impl Drop for NotifyOnDrop { + fn drop(&mut self) { + self.0.notify_one(); + } +} + +impl tonic::server::StreamingService for Echo { + type Response = Message; + type ResponseStream = BoxStream; + type Future = BoxFuture, tonic::Status>; + + fn call(&mut self, request: tonic::Request>) -> Self::Future { + let probe = NotifyOnDrop(self.0.clone()); + Box::pin(async move { + let output = request.into_inner().map(|message| { + let message = message?; + if message.text == "finish" { + return Err(tonic::Status::failed_precondition("echo finished")); + } + Ok(message) + }); + // A half-close alone leaves the response open. Only a reset drops it. + let output = output + .chain(futures::stream::pending()) + .map(move |message| { + let _probe = &probe; + message + }); + let output: Self::ResponseStream = Box::pin(output); + Ok(tonic::Response::new(output)) + }) + } +} + +struct GrpcBackend(Arc); + +#[tonic::async_trait] +impl rpc_test::BoundaryLoopbackConnector for GrpcBackend { + async fn connect(&self, target: LoopbackTarget) -> Result { + assert_eq!(target.port(), 50051); + let (client, server) = tokio::io::duplex(8192); + let cancelled = self.0.clone(); + tokio::spawn(async move { + let service = hyper::service::service_fn(move |request: Request| { + let cancelled = cancelled.clone(); + async move { + assert_eq!(request.version(), Version::HTTP_2); + assert_eq!(request.headers()[header::TE], "trailers"); + assert_eq!(request.headers()["grpc-timeout"], "30000000u"); + let response = tonic::server::Grpc::new(tonic_prost::ProstCodec::default()) + .streaming(Echo(cancelled), request) + .await; + Ok::<_, std::convert::Infallible>(response) + } + }); + let _ = hyper::server::conn::http2::Builder::new(TokioExecutor::new()) + .serve_connection(TokioIo::new(server), service) + .await; + }); + Ok(Box::new(client)) + } +} + +#[tokio::test] +async fn native_grpc_streams_preserve_deadlines_status_and_per_stream_cancellation() { + use tonic::transport::{Certificate, ClientTlsConfig, Endpoint}; + + const GRPC_HOST: &str = "default--sandbox-b--web.svc.openshell.internal"; + let f = fixture(); + let instance = f.host.router().instance("sandbox-b").unwrap(); + let routes = instance.routes.clone(); + let cancelled = Arc::new(Notify::new()); + let _handle = instance.start(rpc_test::loopback(Arc::new(GrpcBackend(cancelled.clone())))); + routes.install(&installed(vec![SandboxServiceRoute { + endpoint_id: "endpoint-b".into(), + target_port: 50051, + backend_http_version: 2, + ..f.route.clone() + }])); + + let ca = Certificate::from_pem(std::fs::read(f.directory.path().join("cert.pem")).unwrap()); + let channel = Endpoint::from_shared(format!("https://{}", f.address)) + .unwrap() + .origin(format!("https://{GRPC_HOST}").parse().unwrap()) + .tls_config( + ClientTlsConfig::new() + .domain_name(GRPC_HOST) + .ca_certificate(ca), + ) + .unwrap() + .connect() + .await + .unwrap(); + let mut grpc = tonic::client::Grpc::new(channel); + let mut calls = Vec::new(); + for _ in 0..2 { + let (tx, rx) = mpsc::channel(1); + tx.send(Message { + text: "hello".into(), + }) + .await + .unwrap(); + let mut request = tonic::Request::new(tokio_stream::wrappers::ReceiverStream::new(rx)); + request.set_timeout(Duration::from_secs(30)); + grpc.ready().await.unwrap(); + let mut response = grpc + .streaming( + request, + http::uri::PathAndQuery::from_static("/test.Echo/Stream"), + tonic_prost::ProstCodec::::default(), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(response.message().await.unwrap().unwrap().text, "hello"); + calls.push((tx, response)); + } + + let (cancel_tx, cancel_response) = calls.pop().unwrap(); + drop(cancel_tx); + drop(cancel_response); + tokio::time::timeout(Duration::from_secs(3), cancelled.notified()) + .await + .expect("the cancelled stream was released at the backend"); + let (tx, mut response) = calls.pop().unwrap(); + tx.send(Message { + text: "finish".into(), + }) + .await + .unwrap(); + let status = response.message().await.unwrap_err(); + assert_eq!(status.code(), tonic::Code::FailedPrecondition); + assert_eq!(status.message(), "echo finished"); +} diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index e4608bcbeb..4b85917ac9 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2321,6 +2321,11 @@ WebSocket services. Application traffic reaches the supervisor directly and uses authentication supplied by your application or ingress edge. Gateway service ingress remains available independently. +The listener negotiates HTTP/2 and HTTP/1.1 through TLS ALPN. WebSocket upgrades +use HTTP/1.1. The listener uses HTTP/1.1 to reach the sandbox service by default. +Set `--backend-http-version 2` when exposing a service to use HTTP/2 on the +sandbox connection. [Expose long-running services](/how-it-works/sandboxes/overview#expose-long-running-services) + ```toml [openshell.supervisor.app_listener] enabled = true @@ -2374,6 +2379,11 @@ unnamed service on sandbox `demo` in workspace `default` uses SNI and Host `default--demo--web.services.example.com`. Configure DNS or your ingress to reach the owning supervisor while preserving that hostname. +For a service with an HTTP/2 backend, any ingress that terminates client TLS +must connect to the supervisor using HTTP/2 over TLS. Use the service hostname +for both TLS SNI and HTTP/2 `:authority`. The supervisor checks this match +per request and applies the service's authorization mode. + Both ingress paths use `[openshell.gateway].service_hostname_format`; the app listener has no separate naming mode. Keeping the same installation name and public HTTPS domain/port preserves the URL when switching between gateway and @@ -2454,7 +2464,8 @@ the listener; configuring `base_url` alone does not enable routing or create DNS certificates, or ingress. When configured, service responses return the application address as `url` and -`application_url`, with `gateway_url` available as a separate alternative. +`application_url`. For HTTP/1.1 backends, `gateway_url` is also available when +gateway service routing is enabled. Create-time exposure returns corresponding preferred, application, and gateway URL maps. CLI and SDK callers preserve the application origin, including its port, when the gateway is reached through a port-forward. With the listener diff --git a/docs/how-it-works/sandboxes/overview.mdx b/docs/how-it-works/sandboxes/overview.mdx index 259e0c8585..2b082d9cdd 100644 --- a/docs/how-it-works/sandboxes/overview.mdx +++ b/docs/how-it-works/sandboxes/overview.mdx @@ -584,6 +584,17 @@ Pass an optional service name to create a named service URL: openshell service expose my-sandbox 8080 web ``` +For a native gRPC server or another service that needs HTTP/2 on loopback, +enable the supervisor application listener and expose the service with +`--backend-http-version 2`. [Supervisor application listener setup](/how-it-works/gateways/configuration#supervisor-application-listener) + +```shell +openshell service expose demo 50051 agent --backend-http-version 2 +``` + +Use the printed HTTPS URL with an HTTP/2 client. The sandbox server must accept +cleartext HTTP/2 with prior knowledge on the declared loopback port. + OpenShell strips the incoming `Authorization` header by default. Opt a service into forwarding one valid bearer credential unchanged when the application performs its own authentication: @@ -612,9 +623,7 @@ edge authentication cookies remain stripped. Bearer passthrough delivers the caller's credential to the sandbox service. -Enable it only when that service is trusted to receive the credential. Exposed -services still use the gateway listener and its TLS configuration in this -release. +Enable it only when that service is trusted to receive the credential. For example, Codex App Server can keep the raw capability outside the sandbox diff --git a/proto/openshell.proto b/proto/openshell.proto index c01e88daf3..e67b74cd6b 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -2044,6 +2044,8 @@ message ExposeServiceRequest { string request_id = 6; // Application authorization behavior. Omission resolves to STRIP. ServiceAuthorizationMode authorization_mode = 7; + // HTTP version on the loopback hop. Omission uses HTTP/1.1. + ServiceBackendHttpVersion backend_http_version = 8; } // Request to fetch an exposed sandbox service endpoint. @@ -2112,6 +2114,8 @@ message ServiceEndpoint { bool domain = 6; // Effective application authorization behavior for ingress requests. ServiceAuthorizationMode authorization_mode = 7; + // HTTP version on the loopback hop. Omission uses HTTP/1.1. + ServiceBackendHttpVersion backend_http_version = 8; } // Service addresses. A configured address does not establish readiness. @@ -4597,3 +4601,13 @@ message DiscoveredServiceRoute { uint64 declaration_revision = 7; google.protobuf.Timestamp expires_at = 8; } + +// HTTP version the supervisor uses to connect to a sandbox service. +enum ServiceBackendHttpVersion { + // Omission uses HTTP/1.1. + SERVICE_BACKEND_HTTP_VERSION_UNSPECIFIED = 0; + // Cleartext HTTP/1.1. + SERVICE_BACKEND_HTTP_VERSION_HTTP1 = 1; + // Cleartext HTTP/2 with prior knowledge, via the supervisor app listener. + SERVICE_BACKEND_HTTP_VERSION_HTTP2 = 2; +} diff --git a/proto/sandbox.proto b/proto/sandbox.proto index 491cc73f12..4699ee244d 100644 --- a/proto/sandbox.proto +++ b/proto/sandbox.proto @@ -531,6 +531,8 @@ message SandboxServiceRoute { // Includes the application domain, without a scheme or port. An empty value // from an older gateway retains readable workspace--sandbox[--service] routing. string application_hostname = 6; + // ServiceBackendHttpVersion from the public service declaration. + int32 backend_http_version = 7; } // Connection details for one operator-registered supervisor middleware service. diff --git a/skills/openshell-cli/SKILL.md b/skills/openshell-cli/SKILL.md index b4d72fbe9f..fb8926c1b5 100644 --- a/skills/openshell-cli/SKILL.md +++ b/skills/openshell-cli/SKILL.md @@ -1065,13 +1065,16 @@ openshell sandbox create \ --detach \ -- ./start-server.sh -# Expose and manage an HTTP service through the gateway. +# Expose and manage a named HTTP service. openshell service expose my-app 8080 web \ --authorization-mode bearer-passthrough openshell service list my-app openshell service list my-app --output json openshell service get my-app web openshell service delete my-app web + +# Expose a service that listens for cleartext HTTP/2, such as native gRPC. +openshell service expose my-app 50051 agent --backend-http-version 2 ``` Use `openshell service list --all-workspaces` for a Platform Admin view across @@ -1081,6 +1084,8 @@ workspaces. A sandbox name and `--all-workspaces` are mutually exclusive. request and keeps the sandbox running. Add `--output json` for automation; the result contains a `service_urls` map whose empty key is the unnamed endpoint. Use `openshell service expose` after creation to add or update named endpoints. +An HTTP/2 backend requires the supervisor application listener. Clients use the +application URL with HTTP/2 over TLS. Exposed services strip `Authorization` by default. Select `bearer-passthrough` only when the application inside the sandbox authenticates @@ -1089,9 +1094,10 @@ one non-empty Bearer credential and forwards that value unchanged. It rejects duplicate, malformed, or non-Bearer authorization before contacting the application. The application remains responsible for validating the token, and the raw token reaches the sandbox process, so never log it. Service routes -bypass control-plane RPC authorization, but they still use the gateway's -existing listener, domain routing, and TLS configuration, including any client -certificate requirement. See the published +bypass control-plane RPC authorization. Gateway service URLs use the gateway's +listener and TLS configuration, including any client certificate requirement. +The supervisor application listener uses application or ingress authentication. +See the published [sandbox service documentation](https://docs.nvidia.com/openshell/latest/how-it-works/sandboxes/overview.md) for the complete security contract.