stratum-node-core 0.1.0-alpha.4

Zero-I/O core types for Stratum pod nodes: did:nostr principals, typed identifiers, a strict NIP-98 signed-request verifier and bootstrap claim bodies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Pod request paths: the allow-list, the shape rules, the helpers and
//! properties over generated paths.

use proptest::prelude::*;
use stratum_node_core::{
    is_acl_path, is_valid_pod_query, DidNostr, NostrSecretKey, ParsePodPathError, PodPath,
};

/// A valid owner key, the public key of the secret key `[n; 32]` for `n` in
/// `1..=254` (`[255; 32]` is above the group order).
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();
    // E2.11's list, less `/pods/<pk>.acl/y` (see the next test).
    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:?}");
    }
}

/// Segments that keep a path valid.
fn good_segment() -> impl Strategy<Value = String> {
    "[A-Za-z0-9._~-]{1,8}".prop_filter("not a dot segment", |s| s != "." && s != "..")
}

/// Segments that may break a path: forbidden characters, dot segments,
/// empty segments, controls and percent-encoding.
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"),
    ]
}

/// A structured path built from parts, most of them pod-like, so that the
/// "accepted implies" properties are tested on many accepted paths.
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));
    }
}

/// Step 3b contract ("The ACL test"): `.acl`, `a.acl`, `a.acl/`, `a.ACL`,
/// `profile/card.acl`, `reports.acl` and the root ACL, both directly and
/// parsed as `PodPath`.
#[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:?})"
        );
    }
}