use proptest::prelude::*;
use stratum_node_core::{
is_acl_path, is_valid_pod_query, DidNostr, NostrSecretKey, ParsePodPathError, PodPath,
};
fn owner(n: u8) -> DidNostr {
NostrSecretKey::from_bytes(&[n; 32])
.expect("1..=254 repeated is a valid secret key")
.public()
}
fn pk() -> String {
owner(1).to_hex()
}
fn parse(path: &str) -> Result<PodPath, ParsePodPathError> {
PodPath::parse(path)
}
#[test]
fn forwarded_shapes_are_accepted_inside_the_owners_pod() {
let pk = pk();
let cases = [
(format!("/pods/{pk}/private/x.txt"), false, false),
(format!("/pods/{pk}/private/"), true, false),
(format!("/pods/{pk}/private/.acl"), false, false),
(format!("/pods/{pk}/private/x.txt.acl"), false, false),
(format!("/pods/{pk}.acl"), false, true),
(format!("/pods/{pk}/name-ending-in-a-dot."), false, false),
(format!("/pods/{pk}/tilde~name"), false, false),
(format!("/pods/{pk}/..."), false, false),
(format!("/pods/{pk}/"), true, false),
];
for (path, container, root_acl) in cases {
let parsed = parse(&path).unwrap_or_else(|e| panic!("{path}: {e}"));
assert_eq!(parsed.owner(), owner(1), "{path}: owner");
assert_eq!(parsed.is_container(), container, "{path}: container");
assert_eq!(parsed.is_root_acl(), root_acl, "{path}: root acl");
assert_eq!(parsed.as_str(), path, "{path}: text kept");
}
}
#[test]
fn paths_outside_the_allow_list_are_not_pod_paths() {
let pk = pk();
let off_curve = "eefdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34";
let cases = [
format!("/_admin/provision/{pk}"),
"/.pods".to_owned(),
"/api/accounts/new".to_owned(),
"/pods/check/name".to_owned(),
"/login/password".to_owned(),
"/pay/x".to_owned(),
"/proxy".to_owned(),
"/.well-known/solid".to_owned(),
"/.notifications".to_owned(),
"/pods/".to_owned(),
"/pods/x.txt".to_owned(),
"/pods.acl".to_owned(),
"/.acl".to_owned(),
format!("/pods/{}/x", pk.to_uppercase()),
format!("/pods/{}/x", &pk[..63]),
format!("/pods/{pk}0/x"),
format!("/pods/{pk}"),
format!("/pods/{pk}x"),
format!("/pods/{pk}.acl/y"),
format!("/pods/{pk}.acl/"),
format!("/pods/{pk}.aclx"),
format!("/pods/{off_curve}/x"),
format!("/Pods/{pk}/x"),
format!("pods/{pk}/x"),
format!("//pods/{pk}/x"),
format!("/pods/{}é/x", &pk[..62]),
String::new(),
];
for path in cases {
let err = parse(&path).expect_err(&path);
assert_eq!(err, ParsePodPathError::NotAPodPath, "{path}");
assert!(err.is_not_a_pod_path(), "{path}: 404 class");
}
}
#[test]
fn forbidden_shapes_are_pod_paths_refused_with_a_reason() {
let pk = pk();
let cases = [
(
format!("/pods/{pk}/a%2fb"),
ParsePodPathError::ForbiddenCharacter,
),
(
format!("/pods/{pk}/a b"),
ParsePodPathError::ForbiddenCharacter,
),
(
format!("/pods/{pk}/a\\b"),
ParsePodPathError::ForbiddenCharacter,
),
(
format!("/pods/{pk}/a;b"),
ParsePodPathError::ForbiddenCharacter,
),
(
format!("/pods/{pk}/a?b"),
ParsePodPathError::ForbiddenCharacter,
),
(
format!("/pods/{pk}/a\u{0}b"),
ParsePodPathError::ForbiddenCharacter,
),
(
format!("/pods/{pk}/a\nb"),
ParsePodPathError::ForbiddenCharacter,
),
(
format!("/pods/{pk}/é"),
ParsePodPathError::ForbiddenCharacter,
),
(format!("/pods/{pk}/../x"), ParsePodPathError::DotSegment),
(format!("/pods/{pk}/a/./x"), ParsePodPathError::DotSegment),
(format!("/pods/{pk}/a/.."), ParsePodPathError::DotSegment),
(format!("/pods/{pk}/./"), ParsePodPathError::DotSegment),
(format!("/pods/{pk}//x"), ParsePodPathError::EmptySegment),
(format!("/pods/{pk}/a//b"), ParsePodPathError::EmptySegment),
(format!("/pods/{pk}/a//"), ParsePodPathError::EmptySegment),
(format!("/pods/{pk}//"), ParsePodPathError::EmptySegment),
];
for (path, want) in cases {
let err = parse(&path).expect_err(&path);
assert_eq!(err, want, "{path:?}");
assert!(!err.is_not_a_pod_path(), "{path:?}: 400 class");
}
}
#[test]
fn acl_paths_are_siblings() {
let pk = pk();
let acl = |path: &str| {
parse(path)
.expect("valid")
.acl_path()
.map(|p| p.as_str().to_owned())
};
assert_eq!(
acl(&format!("/pods/{pk}/")),
Some(format!("/pods/{pk}.acl")),
"pod root"
);
assert_eq!(
acl(&format!("/pods/{pk}/a/")),
Some(format!("/pods/{pk}/a.acl")),
"container"
);
assert_eq!(
acl(&format!("/pods/{pk}/a/x.txt")),
Some(format!("/pods/{pk}/a/x.txt.acl")),
"resource"
);
assert_eq!(
acl(&format!("/pods/{pk}/a.acl/")),
Some(format!("/pods/{pk}/a.acl.acl")),
"a container named like an acl is still a container"
);
assert_eq!(acl(&format!("/pods/{pk}.acl")), None, "root acl");
assert_eq!(acl(&format!("/pods/{pk}/a.acl")), None, "acl resource");
assert_eq!(acl(&format!("/pods/{pk}/.acl")), None, "inner acl");
}
#[test]
fn join_appends_to_containers_only() {
let root = PodPath::pod_root(&owner(2));
let pk = owner(2).to_hex();
assert_eq!(root.as_str(), format!("/pods/{pk}/"), "pod root");
assert_eq!(root.owner(), owner(2), "pod root owner");
assert!(root.is_container(), "pod root is a container");
let file = root.join("a/b.txt").expect("joins");
assert_eq!(file.as_str(), format!("/pods/{pk}/a/b.txt"), "nested join");
let dir = root.join("a/").expect("joins");
assert!(dir.is_container(), "trailing slash");
assert_eq!(
file.join("x"),
Err(ParsePodPathError::NotAContainer),
"resource"
);
let root_acl = root.acl_path().expect("root has an acl");
assert_eq!(
root_acl.join("x"),
Err(ParsePodPathError::NotAContainer),
"root acl"
);
assert_eq!(root.join(""), Err(ParsePodPathError::EmptySegment), "empty");
assert_eq!(
root.join("/x"),
Err(ParsePodPathError::EmptySegment),
"absolute child"
);
assert_eq!(
root.join(".."),
Err(ParsePodPathError::DotSegment),
"parent"
);
assert_eq!(
root.join("a%2f"),
Err(ParsePodPathError::ForbiddenCharacter),
"encoded"
);
assert!(
!ParsePodPathError::NotAContainer.is_not_a_pod_path(),
"not a container is a shape error"
);
}
#[test]
fn text_forms_round_trip() {
let path = format!("/pods/{}/a/b.txt", pk());
let parsed: PodPath = path.parse().expect("parses");
assert_eq!(parsed.to_string(), path, "display");
assert_eq!(parsed.as_ref(), path.as_str(), "as_ref");
assert_eq!(format!("{parsed:?}"), format!("PodPath({path})"), "debug");
let json = serde_json::to_string(&parsed).expect("serialises");
assert_eq!(json, format!("\"{path}\""), "serialises as the path");
let back: PodPath = serde_json::from_str(&json).expect("deserialises");
assert_eq!(back, parsed, "round trip");
let bad = format!("\"/pods/{}/../x\"", pk());
assert!(
serde_json::from_str::<PodPath>(&bad).is_err(),
"deserialisation validates"
);
}
#[test]
fn query_strings_use_the_path_set_plus_four() {
assert!(is_valid_pod_query(""), "empty");
assert!(is_valid_pod_query("a=1&b=x%20y+z/~._-"), "full set");
for bad in [
"a=1;b", "a#b", "a b", "a?b", "a\\b", "a\u{0}", "é", "a\"b", "<",
] {
assert!(!is_valid_pod_query(bad), "{bad:?}");
}
}
fn good_segment() -> impl Strategy<Value = String> {
"[A-Za-z0-9._~-]{1,8}".prop_filter("not a dot segment", |s| s != "." && s != "..")
}
fn any_segment() -> impl Strategy<Value = String> {
prop_oneof![
4 => good_segment(),
1 => Just(String::new()),
1 => Just(".".to_owned()),
1 => Just("..".to_owned()),
1 => Just("%2e%2e".to_owned()),
1 => "[A-Za-z0-9%;\\\\ .\u{0}-\u{1f}\u{7f}é/]{1,6}",
]
}
fn key_text() -> impl Strategy<Value = String> {
prop_oneof![
6 => (1u8..=254).prop_map(|n| owner(n).to_hex()),
1 => (1u8..=254).prop_map(|n| owner(n).to_hex().to_uppercase()),
1 => (1u8..=254).prop_map(|n| owner(n).to_hex()[..63].to_owned()),
1 => "[0-9a-g]{64}",
]
}
fn prefix() -> impl Strategy<Value = &'static str> {
prop_oneof![
8 => Just("/pods/"),
1 => Just("/Pods/"),
1 => Just("/pods"),
1 => Just("/pod/"),
1 => Just(""),
]
}
fn after_key() -> impl Strategy<Value = &'static str> {
prop_oneof![
8 => Just("/"),
2 => Just(".acl"),
1 => Just(".acl/"),
1 => Just(""),
1 => Just("x"),
]
}
fn structured_path() -> impl Strategy<Value = String> {
(
prefix(),
key_text(),
after_key(),
prop::collection::vec(any_segment(), 0..5),
any::<bool>(),
)
.prop_map(|(prefix, key, after, segments, trailing)| {
let mut path = format!("{prefix}{key}{after}");
if after == "/" {
path.push_str(&segments.join("/"));
if trailing && !segments.is_empty() {
path.push('/');
}
}
path
})
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(2048))]
#[test]
fn accepted_paths_are_confined_and_clean(path in structured_path()) {
if let Ok(parsed) = PodPath::parse(&path) {
let second = path.split('/').nth(2).unwrap_or_default();
let hex = parsed.owner().to_hex();
let root_acl = format!("{hex}.acl");
prop_assert!(
second == hex || second == root_acl,
"second segment {second:?} is the owner"
);
prop_assert!(!path.contains('%'), "percent");
prop_assert!(!path.contains('\\'), "backslash");
prop_assert!(!path.contains(';'), "semicolon");
prop_assert!(!path.contains("//"), "empty segment");
prop_assert!(!path.chars().any(char::is_control), "control character");
prop_assert!(
!path.split('/').any(|s| s == "." || s == ".."),
"dot segment"
);
prop_assert_eq!(parsed.as_str(), path.as_str());
}
}
#[test]
fn arbitrary_strings_accepted_are_confined(path in "\\PC{0,90}") {
if let Ok(parsed) = PodPath::parse(&path) {
let second = path.split('/').nth(2).unwrap_or_default();
let hex = parsed.owner().to_hex();
let root_acl = format!("{hex}.acl");
prop_assert!(second == hex || second == root_acl);
prop_assert!(!path.contains('%') && !path.contains("//"));
}
}
#[test]
fn well_formed_paths_are_accepted(
n in 1u8..=254,
segments in prop::collection::vec(good_segment(), 0..6),
trailing in any::<bool>(),
) {
let mut path = format!("/pods/{}/{}", owner(n).to_hex(), segments.join("/"));
if trailing && !segments.is_empty() {
path.push('/');
}
let parsed = PodPath::parse(&path);
prop_assert!(parsed.is_ok(), "{path} refused: {parsed:?}");
let parsed = parsed.unwrap_or_else(|_| PodPath::pod_root(&owner(n)));
prop_assert_eq!(parsed.owner(), owner(n));
prop_assert_eq!(parsed.is_container(), segments.is_empty() || trailing);
if let Some(acl) = parsed.acl_path() {
prop_assert_eq!(PodPath::parse(acl.as_str()), Ok(acl.clone()));
prop_assert_eq!(acl.owner(), owner(n));
prop_assert!(acl.acl_path().is_none(), "an acl has no acl");
}
}
#[test]
fn wrong_prefix_or_key_is_not_a_pod_path(
prefix in prop_oneof![Just("/Pods/"), Just("/pod/"), Just("/pods"), Just("")],
n in 1u8..=254,
rest in "[a-z/]{0,10}",
) {
let path = format!("{prefix}{}/{rest}", owner(n).to_hex());
prop_assert_eq!(PodPath::parse(&path), Err(ParsePodPathError::NotAPodPath));
let upper = format!("/pods/{}/{rest}", owner(n).to_hex().to_uppercase());
prop_assert_eq!(PodPath::parse(&upper), Err(ParsePodPathError::NotAPodPath));
}
}
#[test]
fn acl_test_matches_every_contract_case() {
let pk = pk();
let root_acl = format!("/pods/{pk}.acl");
let cases = [
(".acl", true),
("a.acl", true),
("a.acl/", false),
("a.ACL", false),
("profile/card.acl", true),
("reports.acl", true),
(root_acl.as_str(), true),
];
for (path, expected) in cases {
assert_eq!(is_acl_path(path), expected, "is_acl_path({path:?})");
let full = if path.starts_with("/pods/") {
path.to_owned()
} else {
format!("/pods/{pk}/{path}")
};
let parsed = parse(&full).unwrap_or_else(|e| panic!("{full}: {e}"));
assert_eq!(parsed.is_acl(), expected, "PodPath::is_acl({full:?})");
assert_eq!(
parsed.acl_path().is_none(),
expected,
"acl_path agrees with is_acl({full:?})"
);
}
}