moreinlaw-kernel 0.3.0

The MoreInLaw federation protocol: what every instance must agree on to stay on the network.
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! The kind-4777 lawyer-verification manifest: the event a lawyer signs in the phone app naming
//! the three encrypted evidence files, their hashes and the wrapped file key. Every Host takes
//! submissions from the same phone app, so every Host must accept and refuse the same manifests.
//! It is never put on a relay.
//!
//! This checks everything about a submission that needs no database or storage; the Host then
//! fetches and decrypts each object itself. A refusal's reason string is what the phone shows,
//! so the strings are part of the contract.

use std::collections::HashSet;

use nostr::hashes::{sha256, Hash};
use nostr::{Event, PublicKey};
use serde::Deserialize;

pub use crate::params::MANIFEST_KIND;

/// How far ahead of the Host's clock a manifest may be stamped.
pub const FUTURE_SKEW_SECS: i64 = 60;
pub const MAX_NAME_LEN: usize = 200;
pub const MAX_COUNTRY_LEN: usize = 100;
pub const MAX_ADDRESS_LEN: usize = 500;
pub const MAX_CONTENT_LEN: usize = 16 * 1024;
pub const MAX_WRAPPED_KEY_LEN: usize = 4096;
pub const CIPHER: &str = "AES-256-GCM";
/// The three objects, in the order `VerifiedManifest::objects` holds them.
pub const KINDS: [&str; 3] = ["affidavit", "id_card", "selfie"];

#[derive(Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
#[serde(rename_all = "snake_case")]
enum ObjectKind {
    Affidavit,
    IdCard,
    Selfie,
}

#[derive(Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct ManifestObject {
    kind: ObjectKind,
    pub key: String,
    pub sha256_ciphertext: String,
    pub sha256_plaintext: String,
    pub mime: String,
}

/// The phone's own screening of the affidavit. Signed with the manifest but never re-run by a
/// Host, so it is shown as reported and not relied on for any decision.
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct ClientScreening {
    label: String,
    confidence: Option<f64>,
}

/// Must match the labels the phone sends: a label outside this list refuses the whole
/// submission, so a phone that renames one fails every application until the kernel follows.
pub const SCREENING_LABELS: [&str; 4] = [
    "affidavit_compliant",
    "affidavit_non_compliant",
    "affidavit_unreadable",
    "stamp_recognised",
];

impl ClientScreening {
    fn is_valid(&self) -> bool {
        SCREENING_LABELS.contains(&self.label.as_str())
            && self.confidence.is_none_or(|c| (0.0..=1.0).contains(&c))
    }
}

#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct ManifestContent {
    version: i64,
    full_name: String,
    country: String,
    address: String,
    objects: Vec<ManifestObject>,
    cipher: String,
    wrapped_file_key_sha256: String,
    wrap_pubkey: String,
    service_key_version: i64,
    /// Absent from older phones, which must keep submitting.
    #[serde(default)]
    client_screening: Option<ClientScreening>,
}

/// Why a manifest was refused; the slug is what the phone is told.
#[derive(Debug, PartialEq, Eq)]
pub struct ManifestRejection(pub &'static str);

/// A manifest whose signature, signer, age and content have all been checked.
#[derive(Debug)]
pub struct VerifiedManifest {
    pub event: Event,
    pub full_name: String,
    pub country: String,
    pub address: String,
    /// In `KINDS` order: affidavit, id_card, selfie.
    pub objects: [ManifestObject; 3],
    pub wrap_pubkey: String,
    pub service_key_version: i64,
}

fn is_lower_hex64(s: &str) -> bool {
    s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}

/// Lowercase hex SHA-256, the form every hash in a manifest takes.
pub fn sha256_hex(bytes: &[u8]) -> String {
    sha256::Hash::hash(bytes).to_string()
}

fn text_ok(s: &str, max: usize) -> bool {
    !s.trim().is_empty() && s.len() <= max
}

/// Checks a submitted manifest. `key_prefix` is where this caller's uploads must sit in the
/// Host's storage; `max_age_secs` is the Host's own tolerance for a slow upload.
pub fn verify_manifest(
    event_json: &serde_json::Value,
    wrapped_file_key: &str,
    caller_pubkey: &PublicKey,
    key_prefix: &str,
    now_unix: i64,
    max_age_secs: i64,
) -> Result<VerifiedManifest, ManifestRejection> {
    let bad = ManifestRejection;
    if wrapped_file_key.len() > MAX_WRAPPED_KEY_LEN {
        return Err(bad("too_large"));
    }
    let event = Event::from_value(event_json.clone()).map_err(|_| bad("bad_event"))?;
    if event.verify().is_err() {
        return Err(bad("bad_signature"));
    }
    if event.kind.as_u64() != MANIFEST_KIND {
        return Err(bad("wrong_kind"));
    }
    if &event.pubkey != caller_pubkey {
        return Err(bad("wrong_signer"));
    }
    let created = event.created_at.as_u64() as i64;
    if created < now_unix - max_age_secs || created > now_unix + FUTURE_SKEW_SECS {
        return Err(bad("stale"));
    }
    if event.content.len() > MAX_CONTENT_LEN {
        return Err(bad("too_large"));
    }
    let c: ManifestContent =
        serde_json::from_str(&event.content).map_err(|_| bad("bad_content"))?;
    if c.version != 1 {
        return Err(bad("bad_version"));
    }
    if c.cipher != CIPHER {
        return Err(bad("bad_cipher"));
    }
    if !text_ok(&c.full_name, MAX_NAME_LEN)
        || !text_ok(&c.country, MAX_COUNTRY_LEN)
        || !text_ok(&c.address, MAX_ADDRESS_LEN)
        || !is_lower_hex64(&c.wrapped_file_key_sha256)
        || !is_lower_hex64(&c.wrap_pubkey)
        || PublicKey::from_hex(&c.wrap_pubkey).is_err()
        || c.client_screening.as_ref().is_some_and(|s| !s.is_valid())
    {
        return Err(bad("bad_content"));
    }
    if c.objects.len() != 3 {
        return Err(bad("bad_objects"));
    }
    let wanted = [
        ObjectKind::Affidavit,
        ObjectKind::IdCard,
        ObjectKind::Selfie,
    ];
    let mut slots: [Option<ManifestObject>; 3] = [None, None, None];
    for o in c.objects {
        if !is_lower_hex64(&o.sha256_ciphertext) || !is_lower_hex64(&o.sha256_plaintext) {
            return Err(bad("bad_content"));
        }
        let i = wanted
            .iter()
            .position(|k| *k == o.kind)
            .ok_or(bad("bad_objects"))?;
        if slots[i].replace(o).is_some() {
            return Err(bad("bad_objects"));
        }
    }
    let [Some(a), Some(i), Some(s)] = slots else {
        return Err(bad("bad_objects"));
    };
    let objects = [a, i, s];

    if sha256_hex(wrapped_file_key.as_bytes()) != c.wrapped_file_key_sha256 {
        return Err(bad("wrapped_key_mismatch"));
    }
    let mut seen = HashSet::new();
    for o in &objects {
        let ok = o.key.strip_prefix(key_prefix).is_some_and(|rest| {
            !rest.is_empty()
                && rest.len() <= 128
                && rest
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
                && !rest.starts_with('.')
        });
        if !ok || !seen.insert(o.key.as_str()) {
            return Err(bad("bad_object_key"));
        }
    }
    Ok(VerifiedManifest {
        event,
        full_name: c.full_name.trim().to_string(),
        country: c.country.trim().to_string(),
        address: c.address.trim().to_string(),
        objects,
        wrap_pubkey: c.wrap_pubkey,
        service_key_version: c.service_key_version,
    })
}

/// SHA-256 over the three plaintext hashes, concatenated as lowercase hex in kind order. This is
/// the value a badge's `x` tag carries when the Host has no stamped copy.
pub fn reviewed_hash(objects: &[ManifestObject; 3]) -> String {
    let joined: String = objects
        .iter()
        .map(|o| o.sha256_plaintext.as_str())
        .collect();
    sha256_hex(joined.as_bytes())
}

#[cfg(test)]
mod tests {
    use super::*;
    use nostr::{EventBuilder, Keys, Kind, Timestamp};
    use serde_json::{json, Value};

    const NOW: i64 = 1_800_000_000;
    const WRAPPED: &str = "wrapped-key-payload";
    const UID: i32 = 42;

    fn prefix(uid: i32) -> String {
        format!("identity-uploads/{uid}/verification/")
    }

    fn obj(kind: &str, uid: i32, n: u8) -> Value {
        json!({
            "kind": kind,
            "key": format!("{}obj{n}.bin", prefix(uid)),
            "sha256_ciphertext": "a".repeat(64),
            "sha256_plaintext": "b".repeat(64),
            "mime": "application/pdf",
        })
    }

    fn content(objects: Vec<Value>) -> Value {
        json!({
            "version": 1,
            "full_name": "Ana Reyes",
            "country": "PH",
            "address": "1 Rizal St",
            "objects": objects,
            "cipher": "AES-256-GCM",
            "wrapped_file_key_sha256": sha256_hex(WRAPPED.as_bytes()),
            "wrap_pubkey": Keys::generate().public_key().to_hex(),
            "service_key_version": 1,
        })
    }

    fn default_objects() -> Vec<Value> {
        vec![
            obj("affidavit", UID, 1),
            obj("id_card", UID, 2),
            obj("selfie", UID, 3),
        ]
    }

    fn sign_str(keys: &Keys, kind: u16, at: i64, content: &str) -> Value {
        let ev = EventBuilder::new(Kind::Custom(kind), content, [])
            .custom_created_at(Timestamp::from(at as u64))
            .to_event(keys)
            .unwrap();
        serde_json::to_value(&ev).unwrap()
    }

    fn sign(keys: &Keys, kind: u16, at: i64, content: &Value) -> Value {
        sign_str(keys, kind, at, &content.to_string())
    }

    fn check(ev: &Value, keys: &Keys) -> Result<VerifiedManifest, ManifestRejection> {
        verify_manifest(ev, WRAPPED, &keys.public_key(), &prefix(UID), NOW, 900)
    }

    fn reason(r: Result<VerifiedManifest, ManifestRejection>) -> &'static str {
        r.unwrap_err().0
    }

    #[test]
    fn limits_are_frozen() {
        assert_eq!(
            (
                FUTURE_SKEW_SECS,
                MAX_NAME_LEN,
                MAX_COUNTRY_LEN,
                MAX_ADDRESS_LEN
            ),
            (60, 200, 100, 500)
        );
        assert_eq!((MAX_CONTENT_LEN, MAX_WRAPPED_KEY_LEN), (16384, 4096));
        assert_eq!(
            (CIPHER, KINDS),
            ("AES-256-GCM", ["affidavit", "id_card", "selfie"])
        );
    }

    #[test]
    fn valid_manifest_passes() {
        let k = Keys::generate();
        let m = check(&sign(&k, 4777, NOW, &content(default_objects())), &k).unwrap();
        assert_eq!(m.objects[1].key, format!("{}obj2.bin", prefix(UID)));
        assert_eq!(m.country, "PH");
    }

    #[test]
    fn objects_are_reordered_into_kind_order() {
        let k = Keys::generate();
        let objs = vec![
            obj("selfie", UID, 3),
            obj("affidavit", UID, 1),
            obj("id_card", UID, 2),
        ];
        let m = check(&sign(&k, 4777, NOW, &content(objs)), &k).unwrap();
        assert!(m.objects[0].key.ends_with("obj1.bin"));
        assert!(m.objects[2].key.ends_with("obj3.bin"));
    }

    #[test]
    fn envelope_failures() {
        let k = Keys::generate();
        let mut ev = sign(&k, 4777, NOW, &content(default_objects()));
        let tampered = ev["content"].as_str().unwrap().replace("Ana", "Eve");
        ev["content"] = Value::String(tampered);
        assert_eq!(reason(check(&ev, &k)), "bad_signature");
        assert_eq!(reason(check(&json!({"nope": 1}), &k)), "bad_event");
        let c = content(default_objects());
        assert_eq!(reason(check(&sign(&k, 1, NOW, &c), &k)), "wrong_kind");
        assert_eq!(
            reason(check(&sign(&Keys::generate(), 4777, NOW, &c), &k)),
            "wrong_signer"
        );
        let r = verify_manifest(
            &sign(&k, 4777, NOW, &c),
            &"x".repeat(MAX_WRAPPED_KEY_LEN + 1),
            &k.public_key(),
            &prefix(UID),
            NOW,
            900,
        );
        assert_eq!(reason(r), "too_large");
        let big = sign_str(&k, 4777, NOW, &"x".repeat(MAX_CONTENT_LEN + 1));
        assert_eq!(reason(check(&big, &k)), "too_large");
    }

    #[test]
    fn stale_and_future() {
        let k = Keys::generate();
        let c = content(default_objects());
        assert_eq!(reason(check(&sign(&k, 4777, NOW - 901, &c), &k)), "stale");
        assert!(check(&sign(&k, 4777, NOW - 900, &c), &k).is_ok());
        assert_eq!(reason(check(&sign(&k, 4777, NOW + 61, &c), &k)), "stale");
        assert!(check(&sign(&k, 4777, NOW + 60, &c), &k).is_ok());
    }

    #[test]
    fn unknown_field_and_bad_schema() {
        let k = Keys::generate();
        let edits: [fn(&mut Value); 4] = [
            |c| c["extra"] = json!(1),
            |c| c["objects"][0]["extra"] = json!(1),
            |c| c["full_name"] = json!("   "),
            |c| c["objects"][0]["sha256_plaintext"] = json!("B".repeat(64)),
        ];
        for edit in edits {
            let mut c = content(default_objects());
            edit(&mut c);
            assert_eq!(reason(check(&sign(&k, 4777, NOW, &c), &k)), "bad_content");
        }
    }

    #[test]
    fn version_and_cipher() {
        let k = Keys::generate();
        let mut c = content(default_objects());
        c["version"] = json!(2);
        assert_eq!(reason(check(&sign(&k, 4777, NOW, &c), &k)), "bad_version");
        let mut c = content(default_objects());
        c["cipher"] = json!("AES-128-CBC");
        assert_eq!(reason(check(&sign(&k, 4777, NOW, &c), &k)), "bad_cipher");
    }

    fn with_screening(screening: Value) -> Value {
        let mut c = content(default_objects());
        c["client_screening"] = screening;
        c
    }

    #[test]
    fn client_screening_rules() {
        let k = Keys::generate();
        for s in [
            json!({"label": "affidavit_compliant", "confidence": 0.92}),
            json!({"label": "affidavit_non_compliant", "confidence": 0}),
            json!({"label": "affidavit_unreadable", "confidence": 1}),
            json!({"label": "stamp_recognised"}),
        ] {
            let ev = sign(&k, 4777, NOW, &with_screening(s.clone()));
            assert!(check(&ev, &k).is_ok(), "should accept {s}");
        }
        for s in [
            json!({"label": "approved", "confidence": 0.5}),
            json!({"label": "", "confidence": 0.5}),
            json!({"confidence": 0.5}),
            json!({"label": "affidavit_compliant", "confidence": 1.5}),
            json!({"label": "affidavit_compliant", "confidence": -0.1}),
            json!({"label": "affidavit_compliant", "confidence": "0.9"}),
            json!({"label": "affidavit_compliant", "confidence": 0.9, "model": "x"}),
        ] {
            let ev = sign(&k, 4777, NOW, &with_screening(s.clone()));
            assert_eq!(reason(check(&ev, &k)), "bad_content", "should refuse {s}");
        }
        // serde_json cannot build a NaN Value, so the raw text is spliced in; the phone's
        // JSON encoder could emit it and the parser must still turn it away.
        let raw = with_screening(json!({"label": "affidavit_compliant", "confidence": "NAN"}))
            .to_string()
            .replace("\"NAN\"", "NaN");
        assert_eq!(
            reason(check(&sign_str(&k, 4777, NOW, &raw), &k)),
            "bad_content"
        );
    }

    #[test]
    fn missing_or_duplicate_kind() {
        let k = Keys::generate();
        let missing = vec![obj("affidavit", UID, 1), obj("id_card", UID, 2)];
        assert_eq!(
            reason(check(&sign(&k, 4777, NOW, &content(missing)), &k)),
            "bad_objects"
        );
        let dup = vec![
            obj("affidavit", UID, 1),
            obj("affidavit", UID, 2),
            obj("selfie", UID, 3),
        ];
        assert_eq!(
            reason(check(&sign(&k, 4777, NOW, &content(dup)), &k)),
            "bad_objects"
        );
    }

    #[test]
    fn wrapped_key_hash_mismatch() {
        let k = Keys::generate();
        let ev = sign(&k, 4777, NOW, &content(default_objects()));
        let r = verify_manifest(
            &ev,
            "another-payload",
            &k.public_key(),
            &prefix(UID),
            NOW,
            900,
        );
        assert_eq!(reason(r), "wrapped_key_mismatch");
    }

    #[test]
    fn object_keys_must_sit_under_the_callers_prefix() {
        let k = Keys::generate();
        let other = vec![
            obj("affidavit", 7, 1),
            obj("id_card", UID, 2),
            obj("selfie", UID, 3),
        ];
        assert_eq!(
            reason(check(&sign(&k, 4777, NOW, &content(other)), &k)),
            "bad_object_key"
        );
        let mut objs = default_objects();
        objs[0]["key"] = json!(format!("{}../x.bin", prefix(UID)));
        assert_eq!(
            reason(check(&sign(&k, 4777, NOW, &content(objs)), &k)),
            "bad_object_key"
        );
        let mut objs = default_objects();
        objs[1]["key"] = objs[0]["key"].clone();
        assert_eq!(
            reason(check(&sign(&k, 4777, NOW, &content(objs)), &k)),
            "bad_object_key"
        );
    }

    #[test]
    fn reviewed_hash_is_sha256_of_concatenated_hex() {
        // Known vector: sha256("abc") pins the helper, including its byte order.
        assert_eq!(
            sha256_hex(b"abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
        let mk = |kind: &str, n: u8, plain: char| {
            let mut o: ManifestObject = serde_json::from_value(obj(kind, UID, n)).unwrap();
            o.sha256_plaintext = plain.to_string().repeat(64);
            o
        };
        let objs = [
            mk("affidavit", 1, '1'),
            mk("id_card", 2, '2'),
            mk("selfie", 3, '3'),
        ];
        let joined = format!("{}{}{}", "1".repeat(64), "2".repeat(64), "3".repeat(64));
        assert_eq!(reviewed_hash(&objs), sha256_hex(joined.as_bytes()));
    }
}