pulled out tests and validated them

This commit is contained in:
ari committed 2026-10-20 21:58:33 -04:00
1 parent dc8d62da30
commit 435a54a02d
67 files changed
+6927 -6957

No files matched your search

+2 -513
View File
@@ -421,516 +421,5 @@ fn route_is_follow(route: &str, query: &[(String, String)]) -> bool {
}
#[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<PeerResponse, AppError> {
get(
fake,
peer,
path,
query,
ProxyOpts::default(),
Duration::from_secs(1),
)
.await
}
fn forwarded(fake: &FakeTransport) -> Vec<String> {
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![
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, PeerError>(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());
}
}
#[path = "proxy_tests.rs"]
mod tests;