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
423
424
425
//! The profile document: the gate's exact matcher (E3a.12, E3a.13), the
//! document and ACL the client writes (E3a.11), and `profile init`'s check.

use proptest::prelude::*;
use stratum_node_core::{
    card_names_owner, profile_acl, profile_card, profile_card_path, profile_owner, DidNostr,
    NostrSecretKey, PodPath, PROFILE_CARD_RELATIVE,
};

fn key(byte: u8) -> DidNostr {
    NostrSecretKey::from_hex(&format!("{byte:02x}").repeat(32))
        .expect("fixed key")
        .public()
}

fn path(owner: &DidNostr) -> String {
    profile_card_path(owner).as_str().to_owned()
}

#[test]
fn the_profile_path_is_fixed() {
    let owner = key(7);
    let hex = owner.to_hex();
    assert_eq!(path(&owner), format!("/pods/{hex}/profile/card"), "path");
    assert_eq!(
        PodPath::pod_root(&owner)
            .join(PROFILE_CARD_RELATIVE)
            .expect("join")
            .as_str(),
        path(&owner),
        "relative form"
    );
    assert_eq!(
        profile_owner(path(&owner).as_bytes()),
        Some(owner),
        "matcher accepts it"
    );
}

/// E3a.13's raw-byte list, and the spellings the pod server is known to
/// serve as the card (profile-spike Q3), each refused by the matcher.
#[test]
fn the_refusal_table_is_refused_byte_for_byte() {
    let hex = key(7).to_hex();
    let upper = hex.to_uppercase();
    let base = format!("/pods/{hex}");
    let refused: Vec<Vec<u8>> = [
        format!("{base}/profile/card.acl"),
        format!("{base}/profile/card/"),
        format!("{base}/profile/Card"),
        format!("{base}/profile/"),
        format!("{base}/profile"),
        format!("{base}/profile/card.meta"),
        format!("{base}/profile/card.meta.json"),
        format!("{base}/profile//card"),
        format!("{base}//profile/card"),
        format!("{base}/profile/./card"),
        format!("{base}/./profile/card"),
        format!("{base}/profile/x/../card"),
        format!("{base}/profile/%2e/card"),
        format!("{base}/profile/%63ard"),
        format!("{base}/profile/card%00"),
        format!("/pods/{upper}/profile/card"),
        format!("{base}/profile/card?"),
        format!("{base}/profile/card?x=1"),
        format!("{base}/profile/card#me"),
        format!("{base}/profile/card "),
        format!(" {base}/profile/card"),
        format!("{base}/PROFILE/card"),
        format!("{base}.acl"),
        format!("{base}/"),
        format!("/pods/{hex}0/profile/card"),
        format!("/pods/{}/profile/card", &hex[1..]),
        format!("/Pods/{hex}/profile/card"),
        format!("//pods/{hex}/profile/card"),
        format!("http://h/pods/{hex}/profile/card"),
        format!("/pods/did:nostr:{hex}/profile/card"),
        String::new(),
    ]
    .into_iter()
    .map(String::into_bytes)
    .chain([
        [base.as_bytes(), b"/profile/card\0"].concat(),
        [base.as_bytes(), b"/profile/card\r\n"].concat(),
        [base.as_bytes(), b"/profile/c\xc3\xa1rd"].concat(),
    ])
    .collect();
    for target in refused {
        assert_eq!(
            profile_owner(&target),
            None,
            "{:?}",
            String::from_utf8_lossy(&target)
        );
    }
}

#[test]
fn a_key_that_is_not_a_point_is_refused() {
    // x = 0 is not the x-coordinate of a point on secp256k1.
    let target = format!("/pods/{}/profile/card", "0".repeat(64));
    assert!(DidNostr::from_hex(&"0".repeat(64)).is_err(), "not a key");
    assert_eq!(profile_owner(target.as_bytes()), None, "refused");
}

proptest! {
    /// Accepting a target implies it is byte for byte the canonical path of
    /// the key it names, for arbitrary bytes.
    #[test]
    fn arbitrary_bytes_are_accepted_only_when_exact(target in proptest::collection::vec(any::<u8>(), 0..96)) {
        if let Some(owner) = profile_owner(&target) {
            prop_assert_eq!(target, path(&owner).into_bytes());
        }
    }

    /// One edit (insert, delete or replace a byte) of a valid path is
    /// accepted only when the result is itself exactly a valid path; an edit
    /// outside the key is always refused.
    #[test]
    fn single_edits_of_a_valid_path_are_refused(
        byte in 1u8..=0xfe,
        at in 0usize..83,
        edit in 0u8..3,
        insert in any::<u8>(),
    ) {
        let owner = key(byte);
        let valid = path(&owner).into_bytes();
        let mut edited = valid.clone();
        let at = at.min(valid.len() - 1);
        match edit {
            0 => edited.insert(at, insert),
            1 => { edited.remove(at); }
            _ => edited[at] = insert,
        }
        if let Some(found) = profile_owner(&edited) {
            prop_assert_eq!(&edited, &path(&found).into_bytes());
            // Only a replacement inside the key can name another key.
            prop_assert_eq!(edit, 2);
            prop_assert!((6..70).contains(&at));
        } else {
            prop_assert_ne!(edited, valid);
        }
    }

    /// Every valid key's path is accepted and names that key.
    #[test]
    fn every_key_is_matched(byte in 1u8..=0xfe) {
        let owner = key(byte);
        prop_assert_eq!(profile_owner(path(&owner).as_bytes()), Some(owner));
    }
}

#[test]
fn the_card_is_one_subject_and_two_statements() {
    let owner = key(9);
    let card = profile_card(&owner);
    assert_eq!(
        card,
        format!(
            "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n\
             @prefix owl: <http://www.w3.org/2002/07/owl#> .\n\
             \n\
             <#me> a foaf:Person ;\n    owl:sameAs <did:nostr:{}> .\n",
            owner.to_hex()
        ),
        "exact card"
    );
    assert!(card_names_owner(card.as_bytes(), &owner), "names its owner");
    assert!(
        !card_names_owner(card.as_bytes(), &key(10)),
        "and no one else"
    );
}

#[test]
fn the_acl_has_exactly_the_two_measured_rules() {
    let owner = key(9);
    let hex = owner.to_hex();
    let acl = profile_acl(&owner);
    assert_eq!(
        acl,
        format!(
            "@prefix acl: <http://www.w3.org/ns/auth/acl#> .\n\
             @prefix foaf: <http://xmlns.com/foaf/0.1/> .\n\
             \n\
             <#owner> a acl:Authorization ;\n    \
                 acl:agent <did:nostr:{hex}> ;\n    \
                 acl:accessTo </pods/{hex}/profile/card> ;\n    \
                 acl:mode acl:Read, acl:Write, acl:Control .\n\
             \n\
             <#public> a acl:Authorization ;\n    \
                 acl:agentClass foaf:Agent ;\n    \
                 acl:accessTo </pods/{hex}/profile/card> ;\n    \
                 acl:mode acl:Read .\n"
        ),
        "exact acl"
    );
    assert!(!acl.contains("default"), "no acl:default");
}

fn prefixes() -> &'static str {
    "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n@prefix owl: <http://www.w3.org/2002/07/owl#> .\n"
}

#[test]
fn customised_cards_that_name_the_owner_are_accepted() {
    let owner = key(11);
    let did = owner.to_string();
    let accepted = [
        format!("{}<#me> a foaf:Person ; foaf:name \"Ada; owl:sameAs\" ; owl:sameAs <{did}> .\n", prefixes()),
        format!("{}<#me> owl:sameAs <{did}> .", prefixes()),
        format!("{}<#me> owl:sameAs <https://example.org/ada>, <{did}> .\n", prefixes()),
        format!("<#me> <http://www.w3.org/2002/07/owl#sameAs> <{did}> .\n"),
        format!("PREFIX owl: <http://www.w3.org/2002/07/owl#>\n<#me> owl:sameAs <{did}> .\n"),
        format!("{}# a comment <did:nostr:x> is not an IRI\n<#me> a foaf:Person.\n<#me> owl:sameAs <{did}>.\n", prefixes()),
        format!("{}<#other> foaf:name \"x\" .\n<#me> a foaf:Person ;\n  owl:sameAs <{did}> ;\n  foaf:nick '''multi\nline''' .\n", prefixes()),
    ];
    for card in accepted {
        assert!(
            card_names_owner(card.as_bytes(), &owner),
            "accepted:\n{card}"
        );
    }
}

/// The check fails toward "conflict": each of these must be `false`.
#[test]
fn cards_that_do_not_clearly_name_the_owner_are_refused() {
    let owner = key(11);
    let did = owner.to_string();
    let stranger = key(12).to_string();
    let refused = [
        // The identifier only in a comment or a literal.
        format!("{}<#me> a foaf:Person . # owl:sameAs <{did}>\n", prefixes()),
        format!(
            "{}<#me> foaf:name \"<#me> owl:sameAs <{did}> .\" .\n",
            prefixes()
        ),
        format!(
            "{}<#me> foaf:name '''\n<#me> owl:sameAs <{did}> .\n''' .\n",
            prefixes()
        ),
        // Another subject, or another predicate.
        format!("{}<#other> owl:sameAs <{did}> .\n", prefixes()),
        format!("{}<#me> foaf:knows <{did}> .\n", prefixes()),
        format!("{}<{did}> owl:sameAs <#me> .\n", prefixes()),
        // Another key beside the owner's, or instead of it.
        format!("{}<#me> owl:sameAs <{did}>, <{stranger}> .\n", prefixes()),
        format!(
            "{}<#me> owl:sameAs <{did}> .\n<#x> foaf:knows <{stranger}> .\n",
            prefixes()
        ),
        format!("{}<#me> owl:sameAs <{stranger}> .\n", prefixes()),
        format!(
            "{}<#me> owl:sameAs <DID:NOSTR:{}> .\n",
            prefixes(),
            owner.to_hex()
        ),
        // owl: unbound, rebound, or the base changed.
        format!("@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n<#me> owl:sameAs <{did}> .\n"),
        format!(
            "{}@prefix owl: <http://example.org/> .\n<#me> owl:sameAs <{did}> .\n",
            prefixes()
        ),
        format!(
            "{}@base <https://elsewhere.example/> .\n<#me> owl:sameAs <{did}> .\n",
            prefixes()
        ),
        format!(
            "BASE <https://elsewhere.example/>\n{}<#me> owl:sameAs <{did}> .\n",
            prefixes()
        ),
        // A prefix that builds a DID is not followed, and refuses the card.
        format!(
            "{}@prefix d: <did:nostr:> .\n<#me> owl:sameAs d:{} .\n",
            prefixes(),
            owner.to_hex()
        ),
        format!(
            "{}@prefix d: <did:> .\n<#me> owl:sameAs <{did}>, d:nostr:{} .\n",
            prefixes(),
            key(12).to_hex()
        ),
        // Any other DID, of any method, beside the owner's.
        format!(
            "{}<#me> owl:sameAs <{did}>, <did:web:example.org> .\n",
            prefixes()
        ),
        // Blank nodes or collections in the naming statement.
        format!("{}<#me> owl:sameAs [ owl:sameAs <{did}> ] .\n", prefixes()),
        format!("{}<#me> owl:sameAs ( <{did}> ) .\n", prefixes()),
        // Malformed or truncated input.
        format!("{}<#me> owl:sameAs <{did}", prefixes()),
        format!(
            "{}<#me> foaf:name \"open ; owl:sameAs <{did}> .\n",
            prefixes()
        ),
        String::new(),
    ];
    for card in refused {
        assert!(
            !card_names_owner(card.as_bytes(), &owner),
            "refused:\n{card}"
        );
    }
    assert!(!card_names_owner(b"\xff\xfe<#me>", &owner), "not utf-8");
}

/// Review R37 and R38, and the further holes found while fixing them: each
/// card below is not valid Turtle, or hides a directive from a reader that
/// does not follow Turtle exactly, yet the earlier check said it named the
/// owner. The check reads the whole document and must say `false`.
#[test]
fn cards_that_hide_a_directive_or_break_the_grammar_are_refused() {
    let owner = key(11);
    let did = owner.to_string();
    let p = prefixes();
    let naming = format!("<#me> owl:sameAs <{did}> .\n");
    let refused = [
        // R37: a comment ends at CR as well as LF, so the base is live.
        format!("{p}# c\r@base <https://other.example/card> .\n{naming}"),
        // R38: no first predicate.
        format!("{p}<#me> ; owl:sameAs <{did}> .\n"),
        // R38: the naming statement, or a later one, has no closing `.`.
        format!("{p}<#me> owl:sameAs <{did}>\n"),
        format!("{p}{naming}<#x> a foaf:Person\n"),
        // A syntax error after the naming statement.
        format!("{p}{naming}<#x> foaf:name .\n"),
        format!("{p}{naming}\"x\" foaf:name \"y\" .\n"),
        // Valid Turtle: `\#` escapes the `#` inside a prefixed name, so no
        // comment starts there and the base is live. A reader that ends
        // the name at `#` sees one statement `<#s> foaf:name foaf:o\
        // foaf:o .` and misses the base.
        format!(
            "{p}<#s> foaf:name foaf:o\\# . @base <https://other.example/> . <#t> foaf:name\nfoaf:o .\n{naming}"
        ),
        // An invalid escape that would carry a short string over a line.
        format!("{p}<#s> foaf:name \"a\\\n@base <https://other.example/> . \" .\n{naming}"),
        // A raw CR inside a short string.
        format!("{p}<#me> foaf:name \"a\r\" ; owl:sameAs <{did}> .\n"),
        // A byte-order mark, a form feed, or an unknown `@` keyword.
        format!("\u{feff}@base <https://other.example/> .\n{p}{naming}"),
        format!("{p}<#me>\x0cowl:sameAs <{did}> .\n"),
        format!("@BASE <https://other.example/> .\n{p}{naming}"),
        format!("{p}@keywords a .\n{naming}"),
        // An escaped character in an IRI hides another DID.
        format!("{p}<#me> owl:sameAs <{did}>, <\\u0064id:web:example.org> .\n"),
        // An undeclared prefix.
        format!("{p}{naming}<#x> ex:p <#y> .\n"),
        // A prefix bound to the owner's own DID builds another identifier.
        format!("{p}@prefix d: <{did}> .\n<#me> owl:sameAs <{did}>, d:x .\n"),
        format!("{p}PREFIX d: <{did}>\n<#me> owl:sameAs <{did}>, d:x .\n"),
    ];
    let wrongly_accepted: Vec<(usize, &String)> = refused
        .iter()
        .enumerate()
        .filter(|(_, card)| card_names_owner(card.as_bytes(), &owner))
        .collect();
    assert!(
        wrongly_accepted.is_empty(),
        "accepted, should be refused: {wrongly_accepted:#?}"
    );
}

/// Valid Turtle the stricter reading still accepts: CRLF line ends, a
/// comment ended by CR, language tags and datatypes, a trailing `;`,
/// blank nodes and collections in another statement, labels, numbers and
/// booleans.
#[test]
fn valid_turtle_around_the_naming_statement_is_still_accepted() {
    let owner = key(11);
    let did = owner.to_string();
    let p = prefixes();
    let xsd = "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n";
    let accepted = [
        format!("{}\r\n<#me> owl:sameAs <{did}> .\r\n", p.replace('\n', "\r\n")),
        format!("{p}# a comment\r<#me> owl:sameAs <{did}> .\n"),
        format!("{p}{xsd}<#me> foaf:name \"Ada\"@en-GB ; foaf:age \"36\"^^xsd:int ; owl:sameAs <{did}> .\n"),
        format!("{p}<#me> foaf:nick \"x\"^^<http://www.w3.org/2001/XMLSchema#string> ; owl:sameAs <{did}> ; .\n"),
        format!("{p}<#me> a foaf:Person ;; owl:sameAs <{did}> .\n"),
        format!("{p}<#me> foaf:knows [ foaf:name \"Bob\" ; foaf:knows ( <#a> _:b0 ) ] .\n<#me> owl:sameAs <{did}> .\n"),
        format!("{p}[] foaf:name \"anon\" .\n_:b1 foaf:age 42, -1.5e3, true .\n<#me> owl:sameAs <{did}> .\n"),
        format!("{p}[ foaf:name \"subject list\" ] .\n( 1 2 ) foaf:name \"collection\" .\n<#me> owl:sameAs <{did}> .\n"),
        format!("{p}<#me> foaf:name 'single', \"\"\"long \"quoted\" \\u00e9 text\"\"\" ; owl:sameAs <{did}> .\n"),
    ];
    let wrongly_refused: Vec<(usize, &String)> = accepted
        .iter()
        .enumerate()
        .filter(|(_, card)| !card_names_owner(card.as_bytes(), &owner))
        .collect();
    assert!(
        wrongly_refused.is_empty(),
        "refused, should be accepted: {wrongly_refused:#?}"
    );
}

proptest! {
    /// The check never panics, and never accepts a card that lacks the
    /// owner's identifier, whatever the bytes.
    #[test]
    fn arbitrary_cards_never_panic(card in proptest::collection::vec(any::<u8>(), 0..512)) {
        let owner = key(11);
        let accepted = card_names_owner(&card, &owner);
        let names = card
            .windows(owner.to_string().len())
            .any(|window| window == owner.to_string().as_bytes());
        prop_assert!(!accepted || names);
    }

    /// Text built from Turtle's own pieces never panics either, and is
    /// accepted only when the naming statement is present.
    #[test]
    fn turtle_like_cards_never_panic(parts in proptest::collection::vec(
        prop::sample::select(vec![
            "<#me>", "<#x>", " ", "\n", "\r", ".", ";", ",", "[", "]", "(", ")", "a", "owl:sameAs",
            "foaf:name", "\"s\"", "'''l'''", "@en", "^^", "_:b", "1.5", "# c", "@prefix", "owl:",
            "<http://www.w3.org/2002/07/owl#>", "PREFIX", "@base", "\\",
        ]),
        0..40,
    )) {
        let owner = key(11);
        let card = parts.concat();
        prop_assert!(!card_names_owner(card.as_bytes(), &owner));
    }
}