//! Hostile input for the HTTP side (`docs/PROTOCOL.md` 1.1-1.4): the XML reader, serverinfo, applist, launch and
//! status answers, and the request builders. Every case asserts a specific result.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use common::{param, parse_query, xml_padded_to, xml_root};
use domistream::Error;
use domistream::http::xml::{
self, MAX_XML_ATTRIBUTES, MAX_XML_BYTES, MAX_XML_DEPTH, MAX_XML_ELEMENTS, MAX_XML_TEXT_BYTES,
};
use domistream::http::{self, Scheme};
use proptest::prelude::*;
/// Asserts `Err(TooLarge { max, .. })` for caps where `actual` is a count the parser chooses how to report.
macro_rules! assert_cap {
($e:expr, $max:expr) => {
match $e {
Err(Error::TooLarge { max, .. }) => assert_eq!(max, $max, "TooLarge.max"),
other => panic!("expected Err(TooLarge {{ max: {} }}), got {:?}", $max, other),
}
};
}
// ================================================================================================ XML
#[test]
fn xml_minimal_documents() {
let d = xml::parse(br#""#).unwrap();
assert_eq!(d.status_code, 200);
assert_eq!(d.status_message, None);
assert_eq!(d.root.name, "root");
assert!(d.root.children.is_empty());
let d = xml::parse(br#""#).unwrap();
assert_eq!(d.status_code, 200);
let d = xml::parse(br#""#).unwrap();
assert_eq!(d.status_code, 401, "xml::parse reports the status; refusing it is the callers' job");
assert_eq!(d.status_message.as_deref(), Some("The client is not authorized"));
}
#[test]
fn xml_tree_text_and_attributes() {
let d = xml::parse(br#"t1t2<>&"'AB"#)
.unwrap();
assert_eq!(d.root.attributes, vec![("status_code".into(), "200".into()), ("a".into(), "1".into())]);
let x = &d.root.children[0];
assert_eq!(x.name, "x");
assert_eq!(x.attributes, vec![("k".into(), "v&w".into())]);
assert_eq!(x.text, "t1t2", "text is concatenated around child elements");
assert_eq!(x.children[0].name, "y");
assert_eq!(d.root.children[1].text, "<>&\"'AB");
}
#[test]
fn xml_text_is_not_trimmed() {
let d = xml::parse(b" x \n").unwrap();
assert_eq!(d.root.children[0].text, " x \n");
}
#[test]
fn xml_empty_and_tiny_inputs() {
assert_err!(xml::parse(b""), Error::Malformed { .. });
assert_err!(xml::parse(b"<"), Error::Malformed { .. });
assert_err!(xml::parse(b"x"), Error::Malformed { .. });
assert_err!(xml::parse(b""), Error::Malformed { .. }, "unclosed root");
}
#[test]
fn xml_refuses_non_documents() {
for (bad, why) in [
(&br#""#[..], "root must be `root`"),
(br#""#, "no status_code"),
(br#""#, "status_code not decimal"),
(br#""#, "empty status_code"),
(br#""#, "status_code over u32"),
(br#""#, "negative status_code"),
(br#""#, "unquoted attribute"),
(br#""#, "duplicate attribute"),
(br#""#, "mismatched end tag"),
(br#""#, "unclosed child"),
(br#""#, "two roots"),
(br#"garbage"#, "text after the root"),
(br#"&unknown;"#, "unknown entity"),
(br#"&"#, "entity without ;"),
(br#"a & b"#, "bare &"),
(br#""#, "NUL character reference"),
(br#""#, "surrogate character reference"),
(br#""#, "character reference past Unicode"),
(br#""#, "overflowing character reference"),
(br#"ZZ;"#, "bad hex reference"),
(br#""#, "< in attribute value"),
(br#""#, "DTD"),
(
br#"]>&a;"#,
"entity declaration",
),
(br#""#, "processing instruction in the body"),
(br#" "#, "XML declaration not at the start"),
(br#""#, "namespaces"),
(b"\xff\xfe", "not UTF-8"),
(b"\xc3", "truncated UTF-8"),
(br#"<1root status_code="200"/>"#, "bad name"),
] {
assert_err!(xml::parse(bad), Error::Malformed { .. }, "{why}");
}
}
#[test]
fn xml_billion_laughs_is_refused_without_expansion() {
let mut doc = String::from("");
for i in 1..10 {
doc.push_str(&format!("", format!("&lol{};", i - 1).repeat(10)));
}
doc.push_str("]>&lol9;");
assert_err!(xml::parse(doc.as_bytes()), Error::Malformed { .. });
}
#[test]
fn xml_size_boundaries() {
// max-1 and max are fine (a valid document of exactly that size), max+1 is refused before parsing.
for len in [MAX_XML_BYTES - 1, MAX_XML_BYTES] {
let d = xml::parse(&xml_padded_to("", len)).unwrap_or_else(|e| panic!("{len} bytes: {e:?}"));
assert_eq!(d.status_code, 200);
}
let over = xml_padded_to("", MAX_XML_BYTES + 1);
assert_too_large!(xml::parse(&over), MAX_XML_BYTES, MAX_XML_BYTES + 1);
// Huge: refused on size alone, whatever the content.
let huge = vec![b'<'; 4 * MAX_XML_BYTES];
assert_too_large!(xml::parse(&huge), MAX_XML_BYTES, 4 * MAX_XML_BYTES);
}
fn nested(depth: usize) -> Vec {
// root is depth 1
let mut s = String::from("");
for _ in 1..depth {
s.push_str("");
}
for _ in 1..depth {
s.push_str("");
}
s.push_str("");
s.into_bytes()
}
#[test]
fn xml_depth_cap() {
let d = xml::parse(&nested(MAX_XML_DEPTH)).unwrap();
let mut e = &d.root;
let mut depth = 1;
while let Some(c) = e.children.first() {
e = c;
depth += 1;
}
assert_eq!(depth, MAX_XML_DEPTH);
assert_cap!(xml::parse(&nested(MAX_XML_DEPTH + 1)), MAX_XML_DEPTH);
}
#[test]
fn xml_depth_bomb_does_not_recurse() {
// 300 000 open tags in under 1 MiB: a recursive parser overflows the stack; a strict one stops at depth 9.
let mut s = String::from("");
s.push_str(&"".repeat(300_000));
assert!(s.len() < MAX_XML_BYTES);
assert_cap!(xml::parse(s.as_bytes()), MAX_XML_DEPTH);
// Same with the closing tags present.
s.push_str(&"".repeat(300_000));
s.push_str("");
assert!(s.len() < MAX_XML_BYTES * 2);
if s.len() <= MAX_XML_BYTES {
assert_cap!(xml::parse(s.as_bytes()), MAX_XML_DEPTH);
}
}
#[test]
fn xml_element_cap() {
let ok = xml_root(200, &"".repeat(MAX_XML_ELEMENTS - 1));
assert_eq!(xml::parse(&ok).unwrap().root.children.len(), MAX_XML_ELEMENTS - 1);
let over = xml_root(200, &"".repeat(MAX_XML_ELEMENTS));
assert_cap!(xml::parse(&over), MAX_XML_ELEMENTS);
}
#[test]
fn xml_attribute_cap() {
let attrs = |n: usize| (1..n).map(|i| format!(" a{i}=\"{i}\"")).collect::();
let ok = format!("", attrs(MAX_XML_ATTRIBUTES));
assert_eq!(xml::parse(ok.as_bytes()).unwrap().root.attributes.len(), MAX_XML_ATTRIBUTES);
let over = format!("", attrs(MAX_XML_ATTRIBUTES + 1));
assert_cap!(xml::parse(over.as_bytes()), MAX_XML_ATTRIBUTES);
}
#[test]
fn xml_text_cap_counts_unescaped_bytes() {
let ok = xml_root(200, &format!("{}", "a".repeat(MAX_XML_TEXT_BYTES)));
assert_eq!(xml::parse(&ok).unwrap().root.children[0].text.len(), MAX_XML_TEXT_BYTES);
let over = xml_root(200, &format!("{}", "a".repeat(MAX_XML_TEXT_BYTES + 1)));
assert_cap!(xml::parse(&over), MAX_XML_TEXT_BYTES);
// 5 raw bytes per unescaped byte: the cap is on the result, not the input.
let ok = xml_root(200, &format!("{}", "&".repeat(MAX_XML_TEXT_BYTES)));
assert_eq!(xml::parse(&ok).unwrap().root.children[0].text.len(), MAX_XML_TEXT_BYTES);
let over = xml_root(200, &format!("{}", "&".repeat(MAX_XML_TEXT_BYTES + 1)));
assert_cap!(xml::parse(&over), MAX_XML_TEXT_BYTES);
}
// ------------------------------------------------------------------------------------------------ XML properties
#[derive(Clone, Debug)]
struct Tree {
name: String,
attrs: Vec<(String, String)>,
text: String,
children: Vec,
}
fn escape(s: &str) -> String {
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'")
}
fn serialize(t: &Tree, out: &mut String) {
out.push('<');
out.push_str(&t.name);
for (k, v) in &t.attrs {
out.push_str(&format!(" {k}=\"{}\"", escape(v)));
}
out.push('>');
out.push_str(&escape(&t.text));
for c in &t.children {
serialize(c, out);
}
out.push_str(&format!("{}>", t.name));
}
fn same(e: &xml::Element, t: &Tree) -> bool {
e.name == t.name
&& e.attributes == t.attrs
&& e.text == t.text
&& e.children.len() == t.children.len()
&& e.children.iter().zip(&t.children).all(|(a, b)| same(a, b))
}
fn tree(depth: u32) -> impl Strategy {
// No leading x/X: names starting with "xml" are reserved, and `xmlns` would be a namespace declaration.
let name = "[a-wA-W][a-zA-Z0-9_]{0,6}";
let text = "[ -~&<>\"'é]{0,12}";
let attrs = proptest::collection::btree_map("[a-w][a-z0-9]{0,4}", text, 0..3)
.prop_map(|m| m.into_iter().filter(|(k, _)| k != "status_code").collect::>());
let leaf = (name, attrs.clone(), text).prop_map(|(name, attrs, text)| Tree {
name: name.to_string(),
attrs,
text,
children: vec![],
});
leaf.prop_recursive(depth, 24, 4, move |inner| {
("[a-wA-W][a-zA-Z0-9_]{0,6}", attrs.clone(), "[ -~]{0,8}", proptest::collection::vec(inner, 0..4))
.prop_map(|(name, attrs, text, children)| Tree { name, attrs, text, children })
})
}
proptest! {
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
/// Serialize a random tree (depth <= MAX_XML_DEPTH - 1 under root), parse it back, get the same tree.
#[test]
fn xml_round_trips_generated_trees(children in proptest::collection::vec(tree(5), 0..4), code in 100u32..600) {
let root = Tree {
name: "root".into(),
attrs: vec![("status_code".into(), code.to_string())],
text: String::new(),
children,
};
let mut s = String::new();
serialize(&root, &mut s);
let d = xml::parse(s.as_bytes()).map_err(|e| TestCaseError::fail(format!("{e:?} for {s}")))?;
prop_assert_eq!(d.status_code, code);
prop_assert!(same(&d.root, &root), "tree differs for {}", s);
}
/// Arbitrary bytes: never panics; any success respects every cap.
#[test]
fn xml_never_panics_and_respects_caps(data in proptest::collection::vec(any::(), 0..2048)) {
if let Ok(d) = xml::parse(&data) {
fn walk(e: &xml::Element, depth: usize, count: &mut usize) -> bool {
*count += 1;
depth <= MAX_XML_DEPTH
&& e.attributes.len() <= MAX_XML_ATTRIBUTES
&& e.text.len() <= MAX_XML_TEXT_BYTES
&& e.children.iter().all(|c| walk(c, depth + 1, count))
}
let mut count = 0;
prop_assert!(walk(&d.root, 1, &mut count));
prop_assert!(count <= MAX_XML_ELEMENTS);
prop_assert_eq!(d.root.name.as_str(), "root");
}
}
/// Mutating a valid document (one byte flipped, truncated) never panics, and truncation is always an error.
#[test]
fn xml_truncation_is_an_error(cut in 0usize..60) {
let doc = br#"text&"#;
let cut = cut.min(doc.len() - 1);
prop_assert!(xml::parse(&doc[..cut]).is_err());
}
}
// ================================================================================================ serverinfo
const SERVERINFO: &str = "\n\n\
LAB-PC\n7.1.431.-1\n3.23.0.74\n\
0123456789ABCDEF0123456789ABCDEF\n47984\n\
47989\n00:11:22:aa:BB:ff\n192.0.2.10\n\
1869449984\n259\n\
\n0\n0\n\
SUNSHINE_SERVER_FREE\n\n";
fn serverinfo_with(field: &str, value: Option<&str>) -> Vec {
let open = format!("<{field}>");
let close = format!("{field}>");
let start = SERVERINFO.find(&open).unwrap_or_else(|| panic!("{field} in sample"));
let end = SERVERINFO[start..].find(&close).unwrap() + start + close.len();
let replacement = value.map(|v| format!("{open}{v}{close}")).unwrap_or_default();
format!("{}{}{}", &SERVERINFO[..start], replacement, &SERVERINFO[end..]).into_bytes()
}
#[test]
fn serverinfo_sample() {
let s = http::parse_server_info(SERVERINFO.as_bytes()).unwrap();
assert_eq!(s.hostname, "LAB-PC");
assert_eq!(s.app_version, "7.1.431.-1");
assert_eq!(s.gfe_version.as_deref(), Some("3.23.0.74"));
assert_eq!(s.unique_id, "0123456789ABCDEF0123456789ABCDEF");
assert_eq!(s.https_port, 47984);
assert_eq!(s.http_port, Some(47989));
assert_eq!(s.mac, Some([0x00, 0x11, 0x22, 0xAA, 0xBB, 0xFF]));
assert_eq!(s.local_ip.as_deref(), Some("192.0.2.10"));
assert_eq!(s.max_luma_pixels_hevc, Some(1_869_449_984));
assert_eq!(s.codec_mode_support, Some(259));
assert!(!s.paired);
assert_eq!(s.current_game, 0);
assert_eq!(s.state, "SUNSHINE_SERVER_FREE");
assert!(!s.is_busy().unwrap());
}
#[test]
fn serverinfo_optional_fields() {
let s = http::parse_server_info(&serverinfo_with("mac", Some(""))).unwrap();
assert_eq!(s.mac, None, "empty mac is None");
let s = http::parse_server_info(&serverinfo_with("GfeVersion", None)).unwrap();
assert_eq!(s.gfe_version, None);
let s = http::parse_server_info(&serverinfo_with("ExternalPort", None)).unwrap();
assert_eq!(s.http_port, None);
let s = http::parse_server_info(&serverinfo_with("PairStatus", Some("1"))).unwrap();
assert!(s.paired);
}
#[test]
fn serverinfo_busy() {
let s = http::parse_server_info(&serverinfo_with("state", Some("SUNSHINE_SERVER_BUSY"))).unwrap();
assert!(s.is_busy().unwrap());
let s = http::parse_server_info(&serverinfo_with("currentgame", Some("881448767"))).unwrap();
assert_eq!(s.current_game, 881_448_767);
assert!(s.is_busy().unwrap());
}
#[test]
fn serverinfo_refuses_bad_fields() {
for field in ["hostname", "uniqueid", "HttpsPort"] {
assert_err!(http::parse_server_info(&serverinfo_with(field, None)), Error::Malformed { .. }, "missing {field}");
}
for (field, value) in [
("HttpsPort", "70000"),
("HttpsPort", "-1"),
("HttpsPort", ""),
("HttpsPort", "0x1F"),
("HttpsPort", " 47984"),
("ExternalPort", "65536"),
("currentgame", "abc"),
("currentgame", "4294967296"),
("MaxLumaPixelsHEVC", "1e9"),
("ServerCodecModeSupport", "-3"),
("mac", "00:11:22:33:44"),
("mac", "00:11:22:33:44:55:66"),
("mac", "zz:11:22:33:44:55"),
] {
assert_err!(
http::parse_server_info(&serverinfo_with(field, Some(value))),
Error::Malformed { .. },
"{field}={value:?}"
);
}
}
#[test]
fn serverinfo_field_cap() {
use domistream::http::serverinfo::MAX_SERVERINFO_FIELD_BYTES as MAX;
let ok = "h".repeat(MAX);
assert_eq!(http::parse_server_info(&serverinfo_with("hostname", Some(&ok))).unwrap().hostname, ok);
assert_cap!(http::parse_server_info(&serverinfo_with("hostname", Some(&"h".repeat(MAX + 1)))), MAX);
assert_cap!(http::parse_server_info(&serverinfo_with("state", Some(&"s".repeat(MAX + 1)))), MAX);
}
#[test]
fn serverinfo_status_and_sizes() {
use domistream::http::serverinfo::MAX_SERVERINFO_BYTES as MAX;
assert_err!(http::parse_server_info(&xml_root(503, "")), Error::HostStatus { code: 503 });
assert_err!(http::parse_server_info(b""), Error::Malformed { .. });
assert_err!(http::parse_server_info(b"<"), Error::Malformed { .. });
let inner = SERVERINFO
.trim_start_matches("\n")
.trim_end_matches("\n");
for len in [MAX - 1, MAX] {
let s = http::parse_server_info(&xml_padded_to(inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
assert_eq!(s.hostname, "LAB-PC");
}
assert_too_large!(http::parse_server_info(&xml_padded_to(inner, MAX + 1)), MAX, MAX + 1);
assert_too_large!(http::parse_server_info(&vec![b' '; 64 * MAX]), MAX, 64 * MAX);
}
// ================================================================================================ applist
#[test]
fn applist_sample() {
let body = xml_root(
200,
"1Desktop881448767\
Steam & Friends20\
No HDR field3",
);
let apps = http::parse_app_list(&body).unwrap();
assert_eq!(
apps,
vec![
http::App { id: 881_448_767, title: "Desktop".into(), hdr_supported: true },
http::App { id: 2, title: "Steam & Friends".into(), hdr_supported: false },
http::App { id: 3, title: "No HDR field".into(), hdr_supported: false },
]
);
assert_eq!(http::parse_app_list(&xml_root(200, "")).unwrap(), vec![]);
}
#[test]
fn applist_refuses_bad_apps() {
for (inner, why) in [
("A", "no ID"),
("1", "no AppTitle"),
("A-1", "negative ID"),
("Aabc", "ID not decimal"),
("A4294967296", "ID over u32"),
("A1B1", "duplicate ID"),
] {
assert_err!(http::parse_app_list(&xml_root(200, inner)), Error::Malformed { .. }, "{why}");
}
assert_err!(http::parse_app_list(&xml_root(401, "")), Error::HostStatus { code: 401 });
}
#[test]
fn applist_caps() {
use domistream::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPLIST_BYTES, MAX_APPS};
let app = |i: usize, title: &str| format!("{title}{i}");
let t = "t".repeat(MAX_APP_TITLE_BYTES);
assert_eq!(http::parse_app_list(&xml_root(200, &app(1, &t))).unwrap()[0].title, t);
assert_cap!(
http::parse_app_list(&xml_root(200, &app(1, &"t".repeat(MAX_APP_TITLE_BYTES + 1)))),
MAX_APP_TITLE_BYTES
);
// Multi-byte titles: the cap is in bytes.
assert_cap!(
http::parse_app_list(&xml_root(200, &app(1, &"é".repeat(MAX_APP_TITLE_BYTES / 2 + 1)))),
MAX_APP_TITLE_BYTES
);
let list = |n: usize| (0..n).map(|i| app(i, "g")).collect::();
assert_eq!(http::parse_app_list(&xml_root(200, &list(MAX_APPS))).unwrap().len(), MAX_APPS);
assert_cap!(http::parse_app_list(&xml_root(200, &list(MAX_APPS + 1))), MAX_APPS);
let inner = app(1, "Desktop");
for len in [MAX_APPLIST_BYTES - 1, MAX_APPLIST_BYTES] {
let apps = http::parse_app_list(&xml_padded_to(&inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
assert_eq!(apps.len(), 1, "unknown elements are ignored");
}
assert_too_large!(
http::parse_app_list(&xml_padded_to(&inner, MAX_APPLIST_BYTES + 1)),
MAX_APPLIST_BYTES,
MAX_APPLIST_BYTES + 1
);
assert_too_large!(
http::parse_app_list(&vec![b'<'; 3 * MAX_APPLIST_BYTES]),
MAX_APPLIST_BYTES,
3 * MAX_APPLIST_BYTES
);
}
// ================================================================================================ launch
#[test]
fn launch_response_sample() {
let r = http::parse_launch_response(&xml_root(
200,
"rtsp://192.0.2.10:480101",
))
.unwrap();
assert!(r.game_session);
assert_eq!(r.session_url.as_deref(), Some("rtsp://192.0.2.10:48010"));
let r = http::parse_launch_response(&xml_root(200, "1")).unwrap();
assert_eq!(r.session_url, None, "missing sessionUrl0 is None (UNKNOWN U4)");
let r = http::parse_launch_response(&xml_root(200, "0")).unwrap();
assert!(!r.game_session);
}
#[test]
fn launch_response_refuses_bad_urls() {
for url in [
"http://192.0.2.10:48010",
"rtsp://192.0.2.10",
"rtsp://192.0.2.10:",
"rtsp://192.0.2.10:99999",
"rtsp://192.0.2.10:-1",
"rtsp://:48010",
"rtsp://192.0.2.10:48010\r\nCSeq: 9",
"rtsp://192.0.2.10:48a",
"",
] {
let body = xml_root(200, &format!("{url}1"));
assert_err!(http::parse_launch_response(&body), Error::Malformed { .. }, "{url:?}");
}
}
#[test]
fn launch_response_caps() {
use domistream::http::launch::{MAX_LAUNCH_RESPONSE_BYTES as MAX, MAX_SESSION_URL_BYTES as URL};
let prefix = "rtsp://";
let suffix = ":48010";
// A host name of DNS labels of 9 letters, so only the length is unusual.
let host = |n: usize| {
let len = n - prefix.len() - suffix.len();
(0..len).map(|i| if i % 10 == 9 && i + 1 < len { '.' } else { 'h' }).collect::()
};
let ok = format!("{prefix}{}{suffix}", host(URL));
let r = http::parse_launch_response(&xml_root(200, &format!("{ok}"))).unwrap();
assert_eq!(r.session_url.as_deref(), Some(ok.as_str()));
let over = format!("{prefix}{}{suffix}", host(URL + 1));
assert_cap!(http::parse_launch_response(&xml_root(200, &format!("{over}"))), URL);
let inner = "1";
for len in [MAX - 1, MAX] {
assert!(http::parse_launch_response(&xml_padded_to(inner, len)).unwrap().game_session);
}
assert_too_large!(http::parse_launch_response(&xml_padded_to(inner, MAX + 1)), MAX, MAX + 1);
assert_too_large!(http::parse_launch_response(&vec![0u8; 1 << 20]), MAX, 1 << 20);
assert_err!(http::parse_launch_response(&xml_root(503, "")), Error::HostStatus { code: 503 });
assert_err!(http::parse_launch_response(b""), Error::Malformed { .. });
}
#[test]
fn status_response() {
assert_eq!(http::parse_status_response(&xml_root(200, "")), Ok(()));
assert_err!(http::parse_status_response(&xml_root(404, "")), Error::HostStatus { code: 404 });
assert_err!(http::parse_status_response(b"OK"), Error::Malformed { .. });
assert_err!(http::parse_status_response(b""), Error::Malformed { .. });
assert_too_large!(http::parse_status_response(&vec![b' '; MAX_XML_BYTES + 1]), MAX_XML_BYTES, MAX_XML_BYTES + 1);
}
// ================================================================================================ requests
const UID: &str = "0123456789ABCDEF";
#[test]
fn simple_requests() {
let r = http::server_info_request(Scheme::Http, UID).unwrap();
assert_eq!(r.scheme, Scheme::Http);
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, "/serverinfo");
assert_eq!(param(&q, "uniqueid"), UID);
assert_eq!(http::server_info_request(Scheme::Https, UID).unwrap().scheme, Scheme::Https);
for (r, want) in [
(http::app_list_request(UID).unwrap(), "/applist"),
(http::cancel_request(UID).unwrap(), "/cancel"),
(http::unpair_request(UID).unwrap(), "/unpair"),
] {
assert_eq!(r.scheme, Scheme::Https, "{want} goes over HTTPS");
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, want);
assert_eq!(param(&q, "uniqueid"), UID);
}
}
#[test]
fn requests_refuse_bad_unique_ids() {
use domistream::http::MAX_UNIQUE_ID_BYTES as MAX;
for bad in [String::new(), "a".repeat(MAX + 1)] {
assert_err!(http::server_info_request(Scheme::Http, &bad), Error::Malformed { .. });
assert_err!(http::app_list_request(&bad), Error::Malformed { .. });
assert_err!(http::cancel_request(&bad), Error::Malformed { .. });
assert_err!(http::unpair_request(&bad), Error::Malformed { .. });
}
assert!(http::server_info_request(Scheme::Http, &"a".repeat(MAX)).is_ok());
}
#[test]
fn requests_cannot_be_injected() {
// A unique id with query syntax is refused or encoded; it never adds a parameter.
for evil in ["a&uniqueid=b", "a#frag", "a b", "a\r\nX: y", "a=b", "%26"] {
match http::server_info_request(Scheme::Http, evil) {
Err(Error::Malformed { .. }) => {}
Ok(r) => {
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, "/serverinfo");
assert_eq!(param(&q, "uniqueid"), evil);
assert!(!r.path_and_query.contains(['\r', '\n', ' ', '#']), "{:?}", r.path_and_query);
}
other => panic!("{evil:?}: {other:?}"),
}
}
}
fn launch_params() -> http::LaunchParams {
http::LaunchParams {
app_id: 881_448_767,
width: 1920,
height: 1080,
fps: 60,
keys: domistream::SessionKeys {
rikey: *b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff",
rikeyid: 1_234_567,
},
hdr: false,
audio: http::launch::AudioLayout::Stereo,
}
}
#[test]
fn launch_request_parameters() {
let r = http::launch::launch_request(&launch_params(), UID).unwrap();
assert_eq!(r.scheme, Scheme::Https);
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, "/launch");
assert_eq!(param(&q, "uniqueid"), UID);
assert_eq!(param(&q, "appid"), "881448767");
assert_eq!(param(&q, "mode"), "1920x1080x60");
assert_eq!(param(&q, "rikey").to_lowercase(), "00112233445566778899aabbccddeeff");
assert_eq!(param(&q, "rikeyid"), "1234567");
assert_eq!(param(&q, "hdrMode"), "0");
assert_eq!(param(&q, "surroundAudioInfo"), "196610", "stereo = 0x30002");
let mut p = launch_params();
p.hdr = true;
let (_, q) = parse_query(&http::launch::launch_request(&p, UID).unwrap().path_and_query);
assert_eq!(param(&q, "hdrMode"), "1");
for broken in [
http::LaunchParams { width: 0, ..launch_params() },
http::LaunchParams { height: 0, ..launch_params() },
http::LaunchParams { fps: 0, ..launch_params() },
] {
assert_err!(http::launch::launch_request(&broken, UID), Error::Malformed { .. });
}
assert_err!(http::launch::launch_request(&launch_params(), ""), Error::Malformed { .. });
}
#[test]
fn resume_request_parameters() {
let keys = launch_params().keys;
let r = http::launch::resume_request(&keys, UID).unwrap();
assert_eq!(r.scheme, Scheme::Https);
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, "/resume");
assert_eq!(param(&q, "rikey").to_lowercase(), "00112233445566778899aabbccddeeff");
assert_eq!(param(&q, "rikeyid"), "1234567");
assert_err!(http::launch::resume_request(&keys, ""), Error::Malformed { .. });
}
#[test]
fn session_keys_are_fresh() {
let a = domistream::SessionKeys::generate(&mut common::SeqRng::new(1)).unwrap();
let b = domistream::SessionKeys::generate(&mut common::SeqRng::new(2)).unwrap();
let a2 = domistream::SessionKeys::generate(&mut common::SeqRng::new(1)).unwrap();
assert_eq!(a, a2, "keys come only from the caller's randomness");
assert_ne!(a.rikey, b.rikey);
assert_ne!(a.rikey, [0; 16]);
}