//! Proxy one GET to a peer. //! //! REST and MCP both call [`get`]. The allowlist is the peer's documented //! read routes; `ping` and `peers` are excluded so this cannot chain or //! become an open proxy. Caller credentials are never copied: the transport //! attaches the peer token itself. //! //! Callers may name a route with or without the `/api/v1` prefix; validation //! works on the route alone (`/systemd/units`) and forwards the canonical peer //! path (`/api/v1/systemd/units`), which is what a peer serves. use std::time::Duration; use tokio::time::Instant; use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode}; use bytes::Bytes; use futures::stream::{BoxStream, Stream, StreamExt}; use tokio_util::sync::CancellationToken; use super::error::{peer_error_to_app, PeerError}; use super::registry::ProxyOpts; use super::transport::{PeerBody, PeerRequest, PeerResponse, PeerTransport}; use super::types::{PeerConfig, PeerName}; use crate::error::AppError; use crate::sources::systemd::validate_unit_name; const HOP_HEADER: &str = "x-slinuxm-hop"; const TRACEPARENT: &str = "traceparent"; /// Response header naming the peer a proxied response came from. pub(crate) const PEER_HEADER: &str = "x-slinuxm-peer"; /// Reject an inbound hop marker. Any value counts: a consolidator must not /// forward a request that has already been proxied. pub(crate) fn reject_inbound_hop(peer: &str, headers: &HeaderMap) -> Result<(), AppError> { if headers.contains_key(HOP_HEADER) { return Err(chained(peer)); } Ok(()) } fn chained(peer: &str) -> AppError { AppError::BadRequest(format!("peer {peer}: chained requests are not allowed")) } fn path_rejected(peer: &PeerName) -> AppError { AppError::BadRequest(format!("peer {peer}: path not allowed")) } fn query_rejected(peer: &str) -> AppError { AppError::BadRequest(format!("peer {peer}: unsupported query parameter")) } /// Parse a raw query string. Bad encodings are rejected before the pairs are /// handed to [`get`], which checks the allowlist again. pub(crate) fn query_from_raw( peer: &str, raw: Option<&str>, ) -> Result, AppError> { let Some(raw) = raw.filter(|s| !s.is_empty()) else { return Ok(Vec::new()); }; if raw.len() > 4096 || encoding_forbidden(raw) || raw.chars().any(|c| c.is_control()) { return Err(query_rejected(peer)); } Ok(url::form_urlencoded::parse(raw.as_bytes()) .map(|(k, v)| (k.into_owned(), v.into_owned())) .collect()) } fn header(name: &'static str, value: &str) -> (HeaderName, HeaderValue) { let name = HeaderName::from_static(name); let value = HeaderValue::from_str(value).expect("static header value"); (name, value) } pub(crate) async fn get( transport: &dyn PeerTransport, peer: &PeerConfig, path: &str, query: &[(String, String)], opts: ProxyOpts, timeout: Duration, ) -> Result { let Validated { path, query, sse } = validate(&peer.name, path, query, opts.accept_sse)?; // Marks the hop so a peer refuses chained consolidation. let mut headers = vec![header(HOP_HEADER, "1")]; if let Some(traceparent) = opts.traceparent.as_deref() { if let Ok(value) = HeaderValue::from_str(traceparent) { if !value.as_bytes().contains(&b' ') { headers.push((HeaderName::from_static(TRACEPARENT), value)); } } } let req = PeerRequest { path, query, headers, accept: sse.then(|| "text/event-stream".to_owned()), }; let result = tokio::time::timeout(timeout, transport.get(peer, req, timeout)).await; match result { Ok(Ok(resp)) => Ok(resp), Ok(Err(e)) => Err(peer_error_to_app(&peer.name, &e)), Err(_elapsed) => Err(peer_error_to_app(&peer.name, &PeerError::Timeout)), } } /// A peer response shaped for a surface: status already classified, the /// peer's content type checked, body bounded. REST and MCP both build their /// response from this so neither owns a second copy of the limits. pub(crate) struct PreparedResponse { pub status: StatusCode, pub content_type: Option, pub body: PreparedBody, } /// One table for peer statuses: the transport classifies a live response with /// it and [`prepare_response`] checks again, so neither side can drift. pub(crate) fn classify_status(status: u16) -> PeerError { match status { 404 => PeerError::NotFound, 401 | 403 => PeerError::Rejected, code => PeerError::Http(code), } } /// The contract promises pass-through only for 2xx, so anything else is /// classified here rather than relayed: a transport that forgot to map a /// redirect or the peer's own error body must not reach the caller. pub(crate) fn prepare_response( peer: &PeerName, resp: PeerResponse, max_bytes: u64, deadline: Instant, shutdown: CancellationToken, ) -> Result { let status = match StatusCode::from_u16(resp.status) { Ok(status) if status.is_success() => status, _ => return Err(peer_error_to_app(peer, &classify_status(resp.status))), }; let content_type = content_type(peer, resp.content_type.as_deref())?; let body = prepare_body(peer, resp.body, max_bytes, deadline, shutdown)?; Ok(PreparedResponse { status, content_type, body, }) } fn content_type(peer: &PeerName, value: Option<&str>) -> Result, AppError> { match value { None => Ok(None), Some(value) => HeaderValue::from_str(value) .map(Some) .map_err(|_| peer_error_to_app(peer, &PeerError::Malformed(String::new()))), } } /// Buffered bodies over the cap become `Oversize`. Streams are cut off at the /// cap, at `deadline`, or when `shutdown` fires, because a follow holds a /// connection until the peer closes it. pub(crate) fn prepare_body( peer: &PeerName, body: PeerBody, max_bytes: u64, deadline: Instant, shutdown: CancellationToken, ) -> Result { match body { PeerBody::Bytes(bytes) if bytes.len() as u64 > max_bytes => { Err(peer_error_to_app(peer, &PeerError::Oversize)) } PeerBody::Bytes(bytes) => Ok(PreparedBody::Bytes(bytes)), PeerBody::Stream(stream) => Ok(PreparedBody::Stream(Box::pin(bound_stream( stream, max_bytes, deadline, shutdown, )))), } } pub(crate) enum PreparedBody { Bytes(Bytes), Stream(BoxStream<'static, Result>), } fn bound_stream( stream: BoxStream<'static, Result>, max_bytes: u64, deadline: Instant, shutdown: CancellationToken, ) -> impl Stream> + Send { futures::stream::unfold((stream, 0u64), move |(mut stream, sent)| { let shutdown = shutdown.clone(); async move { let next = tokio::select! { biased; () = shutdown.cancelled() => return None, () = tokio::time::sleep_until(deadline) => return None, item = stream.next() => item, }; let bytes = match next? { Ok(bytes) => bytes, // Headers are already sent. Dropping the chunk keeps a // token-file path or peer URL out of the body. Err(_) => return None, }; if sent.saturating_add(bytes.len() as u64) > max_bytes { return None; } let sent = sent + bytes.len() as u64; Some((Ok(bytes), (stream, sent))) } }) } struct Validated { path: String, query: Vec<(String, String)>, sse: bool, } fn validate( peer: &PeerName, path: &str, query: &[(String, String)], accept_sse: bool, ) -> Result { let route = canonical_route(path).ok_or_else(|| path_rejected(peer))?; let query = allow_query(peer, &route, query)?; let sse = accept_sse || route_is_follow(&route, &query); Ok(Validated { // The allowlist and the query rules work on the route; the peer only // serves it below its own API prefix. path: format!("/api/v1/{route}"), query, sse, }) } fn canonical_route(path: &str) -> Option { if path.len() > 512 || encoding_forbidden(path) { return None; } let mut rel = path.trim_start_matches('/'); if let Some(rest) = rel.strip_prefix("api/v1/") { rel = rest; } if rel.is_empty() { return None; } let mut decoded = Vec::new(); let mut forward = Vec::new(); for raw in rel.split('/') { let segment = percent_encoding::percent_decode_str(raw) .decode_utf8() .ok()?; if !segment_ok(&segment) { return None; } forward.push(percent_encoding::utf8_percent_encode(&segment, SEGMENT_SET).to_string()); decoded.push(segment.into_owned()); } if !route_allowed(&decoded.join("/")) { return None; } // The forward path is re-encoded rather than the caller's text reused so // a backslash from an escaped unit name cannot be read as a separator by // the HTTP client. Some(forward.join("/")) } /// Characters that must stay percent-encoded in a forwarded segment. const SEGMENT_SET: &percent_encoding::AsciiSet = &percent_encoding::CONTROLS .add(b' ') .add(b'"') .add(b'#') .add(b'%') .add(b'/') .add(b'<') .add(b'>') .add(b'?') .add(b'[') .add(b'\\') .add(b']') .add(b'^') .add(b'`') .add(b'{') .add(b'|') .add(b'}'); /// Segment-level rules only; the allowlist below decides which characters a /// segment may carry for its route. fn segment_ok(segment: &str) -> bool { !segment.is_empty() && segment != "." && segment != ".." && !segment .chars() .any(|c| c.is_control() || matches!(c, '%' | '?' | '#' | '/')) } /// Encoded slash, dot-dot, NUL and CRLF, including a second layer of encoding /// (`%252f`, `%255c`). A single `%5c` is not listed: systemd escapes names /// such as `dev-disk-by\x2did.device`, and the local route accepts them, so /// the allowlist decides where a backslash is legal. fn encoding_forbidden(raw: &str) -> bool { let lower = raw.to_ascii_lowercase(); ["%2f", "%00", "%0a", "%0d", "%2e%2e", "%252f", "%255c"] .iter() .any(|needle| lower.contains(needle)) } fn route_allowed(route: &str) -> bool { matches!( route, "systemd/units" | "systemd/timers" | "journal" | "journal/follow" | "docker/ps" ) || unit_path(route) || container_path(route) } /// Unit names go through the same validation as the local route. fn unit_path(route: &str) -> bool { route .strip_prefix("systemd/units/") .is_some_and(|name| validate_unit_name(name).is_ok()) } fn container_path(route: &str) -> bool { let Some(rest) = route.strip_prefix("docker/containers/") else { return false; }; match rest.strip_suffix("/logs") { Some(name) => resource_segment(name), None => resource_segment(rest), } } fn resource_segment(name: &str) -> bool { let mut chars = name.chars(); let Some(first) = chars.next() else { return false; }; first.is_ascii_alphanumeric() && name .chars() .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '@' | ':')) } fn allowed_keys(route: &str) -> &'static [&'static str] { match route { "systemd/units" => &["state"], "journal" | "journal/follow" => &["unit", "priority", "lines", "since"], "docker/ps" => &["all"], logs if logs.starts_with("docker/containers/") && logs.ends_with("/logs") => { &["tail", "since", "follow"] } _ => &[], } } fn allow_query( peer: &PeerName, route: &str, query: &[(String, String)], ) -> Result, AppError> { if query.len() > 8 { return Err(query_rejected(peer.as_str())); } let allowed = allowed_keys(route); let mut seen = Vec::new(); let mut out = Vec::with_capacity(query.len()); for (key, value) in query { let known = allowed.iter().any(|name| *name == key); if !known || !query_key_ok(key) || !query_value_ok(key, value) || seen.contains(&key.as_str()) { return Err(query_rejected(peer.as_str())); } seen.push(key.as_str()); out.push((key.clone(), value.clone())); } Ok(out) } fn query_key_ok(key: &str) -> bool { !key.is_empty() && key.len() <= 32 && key .chars() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') } /// Values arrive decoded and leave as encoded query pairs, so only control /// characters and a second encoding layer are unsafe here. The journal `unit` /// filter is a unit name, so it gets the local route's unit check verbatim: /// that is where a backslash (systemd's escape) is legal. fn query_value_ok(key: &str, value: &str) -> bool { if value.len() > 1024 || encoding_forbidden(value) { return false; } if key == "unit" { return validate_unit_name(value).is_ok(); } !value .chars() .any(|c| c.is_control() || c == '\\' || c == '/') && !value.contains("..") } fn route_is_follow(route: &str, query: &[(String, String)]) -> bool { if route == "journal/follow" { return true; } route.ends_with("/logs") && query .iter() .any(|(key, value)| key == "follow" && matches!(value.as_str(), "1" | "true")) } #[cfg(test)] mod tests { use super::*; use crate::peers::testing::{fake_peers_config, FakeTransport}; use futures::StreamExt; fn peer_cfg() -> PeerConfig { fake_peers_config(&["beta"]).peer.remove(0) } fn header_of<'a>(req: &'a PeerRequest, name: &str) -> Option<&'a str> { req.headers .iter() .find(|(k, _)| k.as_str() == name) .map(|(_, v)| v.to_str().unwrap()) } async fn get_with( fake: &FakeTransport, peer: &PeerConfig, path: &str, query: &[(String, String)], ) -> Result { get( fake, peer, path, query, ProxyOpts::default(), Duration::from_secs(1), ) .await } fn forwarded(fake: &FakeTransport) -> Vec { fake.calls().into_iter().map(|(_, req)| req.path).collect() } #[tokio::test] async fn adds_hop_and_trace_context_but_no_credentials() { let fake = FakeTransport::new(); let peer = peer_cfg(); let opts = ProxyOpts { traceparent: Some("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01".into()), accept_sse: true, }; get( fake.as_ref(), &peer, "/journal/follow", &[("lines".into(), "10".into())], opts, Duration::from_secs(1), ) .await .unwrap(); let calls = fake.calls(); assert_eq!(calls.len(), 1); let req = &calls[0].1; assert_eq!(req.path, "/api/v1/journal/follow"); assert_eq!(req.query, vec![("lines".to_owned(), "10".to_owned())]); assert_eq!(req.accept.as_deref(), Some("text/event-stream")); assert_eq!(header_of(req, "x-slinuxm-hop"), Some("1")); assert!(header_of(req, "traceparent").unwrap().starts_with("00-")); assert_eq!(header_of(req, "authorization"), None); assert_eq!(header_of(req, "cookie"), None); } #[tokio::test] async fn maps_rejected_with_peer_name() { let fake = FakeTransport::new(); fake.peer("beta") .respond_err("/api/v1/systemd/units", PeerError::Rejected); let err = get_with(fake.as_ref(), &peer_cfg(), "/systemd/units", &[]) .await .unwrap_err(); assert_eq!(err.code(), "unavailable"); assert_eq!(err.message(), "peer beta: peer rejected credentials"); } #[tokio::test] async fn allowlist_forwards_documented_routes_only() { let fake = FakeTransport::new(); let peer = peer_cfg(); let ok = [ "/systemd/units", "systemd/units/nginx.service", "/systemd/timers", "/journal", "/journal/follow", "/docker/ps", "/docker/containers/web", "/docker/containers/web/logs", "/api/v1/systemd/units", "systemd/units/user@100.service", // Names the local route accepts must pass here too: `-` roots and // escaped unit names, as text and percent-encoded. "systemd/units/-.mount", "/systemd/units/-.slice", "systemd/units/foo\\x2dbar.mount", "systemd/units/mnt-data%5Cx2dbackup.mount", "systemd/units/dev-disk-by%5cx2did.device", // A `..` inside a name is not traversal: segments cannot contain // a slash and the forwarded path is re-encoded from them. "systemd/units/foo..bar.mount", "/docker/containers/foo..bar", ]; for path in ok { get_with(fake.as_ref(), &peer, path, &[]).await.unwrap(); } assert_eq!( forwarded(&fake), vec![ "/api/v1/systemd/units", "/api/v1/systemd/units/nginx.service", "/api/v1/systemd/timers", "/api/v1/journal", "/api/v1/journal/follow", "/api/v1/docker/ps", "/api/v1/docker/containers/web", "/api/v1/docker/containers/web/logs", "/api/v1/systemd/units", "/api/v1/systemd/units/user@100.service", "/api/v1/systemd/units/-.mount", "/api/v1/systemd/units/-.slice", "/api/v1/systemd/units/foo%5Cx2dbar.mount", "/api/v1/systemd/units/mnt-data%5Cx2dbackup.mount", "/api/v1/systemd/units/dev-disk-by%5Cx2did.device", "/api/v1/systemd/units/foo..bar.mount", "/api/v1/docker/containers/foo..bar", ] ); } #[tokio::test] async fn unit_names_are_forwarded_in_one_normalised_form() { let fake = FakeTransport::new(); let peer = peer_cfg(); for path in [ "systemd/units/-.mount", "systemd/units/foo\\x2dbar.mount", "systemd/units/foo%5cx2dbar.mount", "/api/v1/systemd/units/mnt-data%5Cx2dbackup.mount", ] { get_with(fake.as_ref(), &peer, path, &[]).await.unwrap(); } assert_eq!( forwarded(&fake), vec![ "/api/v1/systemd/units/-.mount", "/api/v1/systemd/units/foo%5Cx2dbar.mount", "/api/v1/systemd/units/foo%5Cx2dbar.mount", "/api/v1/systemd/units/mnt-data%5Cx2dbackup.mount", ] ); } #[test] fn prepared_response_maps_status_and_checks_the_body() { let name = PeerName::parse("beta").unwrap(); let deadline = Instant::now() + Duration::from_secs(5); let prepare = |status: u16, content_type: Option<&str>, body: &'static [u8]| { prepare_response( &name, PeerResponse { status, content_type: content_type.map(str::to_owned), body: PeerBody::Bytes(Bytes::from_static(body)), }, 4, deadline, CancellationToken::new(), ) }; let ok = prepare(200, Some("application/json"), b"{}").unwrap(); assert_eq!(ok.status, StatusCode::OK); assert_eq!(ok.content_type.unwrap(), "application/json"); let rows = [ (404, "not_found", "peer beta: not found on peer"), (401, "unavailable", "peer beta: peer rejected credentials"), (403, "unavailable", "peer beta: peer rejected credentials"), (500, "unavailable", "peer beta: http_500"), (302, "unavailable", "peer beta: http_302"), (999, "unavailable", "peer beta: http_999"), ]; for (status, code, message) in rows { let err = match prepare(status, None, b"") { Err(err) => err, Ok(_) => panic!("status {status} must not pass through"), }; assert_eq!(err.code(), code, "{status}"); assert_eq!(err.message(), message, "{status}"); } let err = match prepare(200, None, b"0123456789") { Err(err) => err, Ok(_) => panic!("oversize body must not pass through"), }; assert_eq!(err.message(), "peer beta: oversize"); let err = match prepare(200, Some("application/json\r\nX-Injected: 1"), b"{}") { Err(err) => err, Ok(_) => panic!("smuggled content type must not pass through"), }; assert_eq!(err.message(), "peer beta: malformed response"); } #[tokio::test] async fn rejects_traversal_excluded_routes_and_bad_query_without_calling() { let fake = FakeTransport::new(); fake.peer("beta") .respond("/api/v1/systemd/units", 200, "application/json", "{}") .respond("/api/v1/journal/follow", 200, "application/json", "{}"); let peer = peer_cfg(); let bad_paths = [ "/ping", "/api/v1/ping", "/peers/gamma/systemd/units", "/healthz", "/systemd", "/systemd/units/../timers", "/systemd/../docker/ps", "systemd/units/%2e%2e", "journal%2ffollow", "systemd/units/foo%2Fbar", "/systemd/units//nginx.service", "/docker/containers/a/b", "/journal/follow/extra", "", "/", "/systemd/units/%2e.", "systemd\\units", // A second encoding layer and control characters. "systemd%252ffollow", "systemd/units/foo%255cbar.mount", "systemd/units/nginx.service%00", "systemd/units/nginx.service%0a", "systemd/units/nginx%0d.service", "systemd/units/foo%25.service", "systemd/units/foo%zz.service", // An encoded `..` anywhere is a second encoding layer, even when // it sits inside one segment rather than being the segment. "systemd/units/foo%2e%2ebar.mount", // A backslash is only a legal character inside a unit name. "systemd%5cunits", "journal%5cfollow", "docker/containers/web%5cx2d1", ]; for path in bad_paths { let err = get_with(fake.as_ref(), &peer, path, &[]).await.unwrap_err(); assert_eq!(err.code(), "bad_request", "{path}"); assert_eq!(err.message(), "peer beta: path not allowed", "{path}"); } let bad_queries = [ vec![("token".into(), "abc".into())], vec![ ("state".into(), "failed".into()), ("lines".into(), "1".into()), ], vec![ ("state".into(), "failed".into()), ("state".into(), "active".into()), ], vec![("State".into(), "failed".into())], vec![("state".into(), "a/b".into())], vec![("state".into(), "a%2fb".into())], vec![("state".into(), "..".into())], vec![("state".into(), "a%252fb".into())], vec![("state".into(), "a%255cb".into())], vec![("state".into(), "a%00b".into())], vec![("state".into(), "a%0ab".into())], vec![("state".into(), "a%0db".into())], ]; for query in bad_queries { let err = get_with(fake.as_ref(), &peer, "/systemd/units", &query) .await .unwrap_err(); assert_eq!(err.code(), "bad_request", "{query:?}"); assert_eq!(err.message(), "peer beta: unsupported query parameter"); } assert!(fake.calls().is_empty()); } #[tokio::test] async fn forwards_only_allowlisted_query_and_follow_accept() { let fake = FakeTransport::new(); let peer = peer_cfg(); get( fake.as_ref(), &peer, "/systemd/units", &[("state".into(), "failed".into())], ProxyOpts::default(), Duration::from_secs(1), ) .await .unwrap(); get( fake.as_ref(), &peer, "/docker/containers/web/logs", &[("tail".into(), "10".into()), ("follow".into(), "1".into())], ProxyOpts::default(), Duration::from_secs(1), ) .await .unwrap(); get( fake.as_ref(), &peer, "/docker/containers/web/logs", &[("follow".into(), "0".into())], ProxyOpts::default(), Duration::from_secs(1), ) .await .unwrap(); let calls = fake.calls(); assert_eq!(calls[0].1.query, vec![("state".into(), "failed".into())]); assert!(calls[0].1.accept.is_none()); assert_eq!(calls[1].1.accept.as_deref(), Some("text/event-stream")); assert!(calls[2].1.accept.is_none()); } #[tokio::test] async fn journal_unit_values_are_forwarded_like_the_local_route() { let fake = FakeTransport::new(); let peer = peer_cfg(); // Raw text as an MCP caller would pass it, and the same values in a // request target: `%5C` and a literal backslash both decode to one // backslash, which is what systemd uses to escape a unit name. let raw_queries = [ "unit=mnt-data%5Cx2dbackup.mount", "unit=mnt-data%5cx2dbackup.mount", "unit=mnt-data\\x2dbackup.mount", "unit=dev-disk-by%5Cx2did.device&priority=err", "unit=-.mount", "unit=user@100.service", ]; for raw in raw_queries { let query = query_from_raw("beta", Some(raw)).unwrap(); get_with(fake.as_ref(), &peer, "/journal", &query) .await .unwrap(); } get_with( fake.as_ref(), &peer, "/journal/follow", &[("unit".into(), "mnt-data\\x2dbackup.mount".into())], ) .await .unwrap(); assert_eq!( fake.calls() .into_iter() .map(|(_, req)| req.query) .collect::>(), vec![ vec![("unit".into(), "mnt-data\\x2dbackup.mount".into())], vec![("unit".into(), "mnt-data\\x2dbackup.mount".into())], vec![("unit".into(), "mnt-data\\x2dbackup.mount".into())], vec![ ("unit".into(), "dev-disk-by\\x2did.device".into()), ("priority".into(), "err".into()), ], vec![("unit".into(), "-.mount".into())], vec![("unit".into(), "user@100.service".into())], vec![("unit".into(), "mnt-data\\x2dbackup.mount".into())], ] ); } #[tokio::test] async fn journal_unit_values_still_reject_unsafe_text() { let fake = FakeTransport::new(); let peer = peer_cfg(); let bad = [ // Not a unit name, so the local unit rule rejects it. "unit=../x", "unit=a/b", "unit=nginx", "unit=nginx.service%2fx", "unit=mnt-data%5Cx2d.mount%2e", "unit=mnt-data%0ax2d.mount", "unit=a%255cb.mount", ]; for raw in bad { // Some values are stopped while the raw query is parsed and the // rest by the allowlist; both are the same 400. let err = match query_from_raw("beta", Some(raw)) { Ok(query) => get_with(fake.as_ref(), &peer, "/journal", &query) .await .unwrap_err(), Err(err) => err, }; assert_eq!(err.code(), "bad_request", "{raw}"); assert_eq!( err.message(), "peer beta: unsupported query parameter", "{raw}" ); } // Values that reach the check already decoded (the MCP path) are // rejected there rather than by the raw parser. for value in [ "mnt-data\u{0}x2d.mount", "mnt-data\nx2d.mount", "mnt-data\rx2d.mount", "mnt-data\x2d.mount/../../etc/passwd", ] { let err = get_with( fake.as_ref(), &peer, "/journal", &[("unit".into(), value.into())], ) .await .unwrap_err(); assert_eq!(err.code(), "bad_request", "{value:?}"); } assert!(fake.calls().is_empty()); } #[test] fn status_classification_is_one_table() { assert!(matches!(classify_status(404), PeerError::NotFound)); assert!(matches!(classify_status(401), PeerError::Rejected)); assert!(matches!(classify_status(403), PeerError::Rejected)); assert!(matches!(classify_status(302), PeerError::Http(302))); assert!(matches!(classify_status(200), PeerError::Http(200))); } #[tokio::test] async fn slow_peer_is_a_timeout() { let fake = FakeTransport::new(); fake.peer("beta").delay(Duration::from_secs(30)); let err = get( fake.as_ref(), &peer_cfg(), "/systemd/units", &[], ProxyOpts::default(), Duration::from_millis(20), ) .await .unwrap_err(); assert_eq!(err.message(), "peer beta: timeout"); } #[tokio::test] async fn inbound_hop_is_rejected() { let mut headers = HeaderMap::new(); headers.insert(HOP_HEADER, HeaderValue::from_static("1")); let err = reject_inbound_hop("beta", &headers).unwrap_err(); assert_eq!(err.code(), "bad_request"); assert_eq!(err.message(), "peer beta: chained requests are not allowed"); headers.insert(HOP_HEADER, HeaderValue::from_static("0")); assert!(reject_inbound_hop("beta", &headers).is_err()); assert!(reject_inbound_hop("beta", &HeaderMap::new()).is_ok()); } #[tokio::test] async fn query_raw_rejects_encoded_slash() { let err = query_from_raw("beta", Some("state=failed&unit=a%2Fb")).unwrap_err(); assert_eq!(err.message(), "peer beta: unsupported query parameter"); let pairs = query_from_raw("beta", Some("state=failed")).unwrap(); assert_eq!(pairs, vec![("state".into(), "failed".into())]); } #[tokio::test] async fn body_cap_and_stream_stop_on_shutdown() { let name = PeerName::parse("beta").unwrap(); let err = match prepare_body( &name, PeerBody::Bytes(Bytes::from_static(b"0123456789")), 4, Instant::now() + Duration::from_secs(5), CancellationToken::new(), ) { Err(err) => err, Ok(_) => panic!("expected an oversize error"), }; assert_eq!(err.message(), "peer beta: oversize"); let shutdown = CancellationToken::new(); let stream = futures::stream::unfold(0u32, |n| async move { if n > 0 { tokio::time::sleep(Duration::from_secs(30)).await; } Some(( Ok::(Bytes::from(format!("data: {n}\n\n"))), n + 1, )) }); let PreparedBody::Stream(mut body) = prepare_body( &name, PeerBody::Stream(Box::pin(stream)), 1024, Instant::now() + Duration::from_secs(30), shutdown.clone(), ) .unwrap() else { panic!("expected a stream"); }; let first = body.next().await.unwrap().unwrap(); assert_eq!(&first[..], b"data: 0\n\n"); shutdown.cancel(); assert!(body.next().await.is_none()); } }