solid-pod-rs 0.4.0-alpha.2

Rust-native Solid Pod server library — LDP, WAC, WebID, Solid-OIDC, Solid Notifications, NIP-98. Framework-agnostic.
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
//! NIP-98 HTTP authentication: structural verification.
//!
//! Reference: <https://github.com/nostr-protocol/nips/blob/master/98.md>
//!
//! Wire format: `Authorization: Nostr <base64(json(event))>` where
//! the event is a kind-27235 Nostr event with tags `u` (URL),
//! `method`, and optional `payload` (SHA-256 of request body).
//!
//! This Phase 1 implementation performs all structural checks.
//! Cryptographic signature verification (Schnorr over secp256k1) is
//! the Phase 2 deliverable.

use std::time::{SystemTime, UNIX_EPOCH};

use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use serde::Deserialize;
use sha2::{Digest, Sha256};

use crate::error::PodError;

const HTTP_AUTH_KIND: u64 = 27235;
const TIMESTAMP_TOLERANCE: u64 = 60;
const MAX_EVENT_SIZE: usize = 64 * 1024;
const NOSTR_PREFIX: &str = "Nostr ";

#[derive(Debug, Clone, Deserialize)]
pub struct Nip98Event {
    pub id: String,
    pub pubkey: String,
    pub created_at: u64,
    pub kind: u64,
    pub tags: Vec<Vec<String>>,
    pub content: String,
    pub sig: String,
}

#[derive(Debug, Clone)]
pub struct Nip98Verified {
    pub pubkey: String,
    pub url: String,
    pub method: String,
    pub payload_hash: Option<String>,
    pub created_at: u64,
}

/// Verify a NIP-98 `Authorization` header against expected URL,
/// method, and optional body.
///
/// Returns the signer pubkey on success.
pub async fn verify(
    header: &str,
    url: &str,
    method: &str,
    body_hash: Option<&[u8]>,
) -> Result<String, PodError> {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    verify_at(header, url, method, body_hash, now).map(|v| v.pubkey)
}

/// `verify` with an explicit timestamp (for deterministic testing).
pub fn verify_at(
    header: &str,
    expected_url: &str,
    expected_method: &str,
    body: Option<&[u8]>,
    now: u64,
) -> Result<Nip98Verified, PodError> {
    let token = header
        .strip_prefix(NOSTR_PREFIX)
        .ok_or_else(|| PodError::Nip98("missing 'Nostr ' prefix".into()))?
        .trim();

    if token.len() > MAX_EVENT_SIZE {
        return Err(PodError::Nip98("token too large".into()));
    }
    let json_bytes = BASE64.decode(token)?;
    if json_bytes.len() > MAX_EVENT_SIZE {
        return Err(PodError::Nip98("decoded token too large".into()));
    }
    let event: Nip98Event = serde_json::from_slice(&json_bytes)?;

    if event.kind != HTTP_AUTH_KIND {
        return Err(PodError::Nip98(format!(
            "wrong kind: expected {HTTP_AUTH_KIND}, got {}",
            event.kind
        )));
    }
    if event.pubkey.len() != 64 || hex::decode(&event.pubkey).is_err() {
        return Err(PodError::Nip98("invalid pubkey".into()));
    }
    if now.abs_diff(event.created_at) > TIMESTAMP_TOLERANCE {
        return Err(PodError::Nip98(format!(
            "timestamp outside tolerance: event={}, now={now}",
            event.created_at
        )));
    }

    let token_url = get_tag(&event, "u")
        .ok_or_else(|| PodError::Nip98("missing 'u' tag".into()))?;
    if normalize_url(&token_url) != normalize_url(expected_url) {
        return Err(PodError::Nip98(format!(
            "URL mismatch: token={token_url}, expected={expected_url}"
        )));
    }

    let token_method = get_tag(&event, "method")
        .ok_or_else(|| PodError::Nip98("missing 'method' tag".into()))?;
    if token_method.to_uppercase() != expected_method.to_uppercase() {
        return Err(PodError::Nip98(format!(
            "method mismatch: token={token_method}, expected={expected_method}"
        )));
    }

    let payload_tag = get_tag(&event, "payload");
    let verified_payload_hash = match body {
        Some(b) if !b.is_empty() => {
            let expected = payload_tag
                .as_ref()
                .ok_or_else(|| PodError::Nip98("body provided but no payload tag".into()))?;
            let actual = hex::encode(Sha256::digest(b));
            if expected.to_lowercase() != actual.to_lowercase() {
                return Err(PodError::Nip98("payload hash mismatch".into()));
            }
            Some(expected.clone())
        }
        _ => payload_tag,
    };

    // Schnorr signature verification is available under the
    // `nip98-schnorr` feature. Structural checks always run.
    #[cfg(feature = "nip98-schnorr")]
    {
        verify_schnorr_signature(&event)?;
    }

    Ok(Nip98Verified {
        pubkey: event.pubkey,
        url: token_url,
        method: token_method,
        payload_hash: verified_payload_hash,
        created_at: event.created_at,
    })
}

/// Canonical serialisation of a Nostr event per NIP-01 §"Serialization".
/// Returns `sha256(json([0, pubkey, created_at, kind, tags, content]))`
/// as lowercase hex.
pub fn compute_event_id(event: &Nip98Event) -> String {
    let canonical = serde_json::json!([
        0,
        event.pubkey,
        event.created_at,
        event.kind,
        event.tags,
        event.content,
    ]);
    let serialized = serde_json::to_string(&canonical).unwrap_or_default();
    hex::encode(Sha256::digest(serialized.as_bytes()))
}

/// Schnorr signature verification (feature-gated).
///
/// This validates:
/// 1. `event.id` matches the canonical NIP-01 hash.
/// 2. `event.sig` is a valid BIP-340 Schnorr signature by `event.pubkey`
///    over the event id bytes.
#[cfg(feature = "nip98-schnorr")]
pub fn verify_schnorr_signature(event: &Nip98Event) -> Result<(), PodError> {
    use k256::schnorr::{signature::Verifier, Signature, VerifyingKey};

    let computed_id = compute_event_id(event);
    if computed_id.to_lowercase() != event.id.to_lowercase() {
        return Err(PodError::Nip98(format!(
            "event id mismatch: computed={computed_id}, claimed={}",
            event.id
        )));
    }
    let pub_bytes = hex::decode(&event.pubkey)
        .map_err(|e| PodError::Nip98(format!("pubkey hex decode: {e}")))?;
    let sig_bytes = hex::decode(&event.sig)
        .map_err(|e| PodError::Nip98(format!("sig hex decode: {e}")))?;
    if sig_bytes.len() != 64 {
        return Err(PodError::Nip98(format!(
            "sig wrong length: {}",
            sig_bytes.len()
        )));
    }
    let id_bytes = hex::decode(&computed_id)
        .map_err(|e| PodError::Nip98(format!("id hex decode: {e}")))?;

    let vk = VerifyingKey::from_bytes(&pub_bytes)
        .map_err(|e| PodError::Nip98(format!("pubkey parse: {e}")))?;
    let sig = Signature::try_from(sig_bytes.as_slice())
        .map_err(|e| PodError::Nip98(format!("sig parse: {e}")))?;
    vk.verify(&id_bytes, &sig)
        .map_err(|e| PodError::Nip98(format!("schnorr verify: {e}")))?;
    Ok(())
}

/// No-op stub when the `nip98-schnorr` feature is not enabled.
#[cfg(not(feature = "nip98-schnorr"))]
pub fn verify_schnorr_signature(_event: &Nip98Event) -> Result<(), PodError> {
    Err(PodError::Unsupported(
        "nip98-schnorr feature not enabled".into(),
    ))
}

fn get_tag(event: &Nip98Event, name: &str) -> Option<String> {
    event
        .tags
        .iter()
        .find(|t| t.first().map(|s| s.as_str()) == Some(name))
        .and_then(|t| t.get(1).cloned())
}

fn normalize_url(u: &str) -> &str {
    u.trim_end_matches('/')
}

pub fn authorization_header(token_b64: &str) -> String {
    format!("{NOSTR_PREFIX}{token_b64}")
}

// ---------------------------------------------------------------------------
// Sprint 11 row 152: SelfSignedVerifier adapter.
//
// Wraps `verify_at` in the CID verifier contract so NIP-98 is one of
// the proof formats a `CidVerifier` can dispatch. The wire format is
// the `Nostr <base64>` header exactly as produced by clients today —
// the adapter strips the `Nostr ` prefix if the caller supplied the
// raw header, or accepts the bare token otherwise.
// ---------------------------------------------------------------------------

use crate::auth::self_signed::{
    ProofEnvelope, SelfSignedError, SelfSignedVerifier, VerifiedSubject,
};

/// [`SelfSignedVerifier`] adapter for NIP-98.
///
/// Accepts either `Nostr <b64>` (raw header) or `<b64>` (already-stripped
/// token). On success the returned subject is `urn:nip98:<pubkey>` with
/// a `verification_method` of `urn:nip98:<pubkey>#key-0`.
#[derive(Debug, Default, Clone, Copy)]
pub struct Nip98Verifier;

#[async_trait::async_trait]
impl SelfSignedVerifier for Nip98Verifier {
    async fn verify(
        &self,
        envelope: &ProofEnvelope<'_>,
    ) -> Result<Option<VerifiedSubject>, SelfSignedError> {
        // Decide whether this looks like NIP-98. We accept either the
        // full `Nostr <b64>` header OR a bare token that begins with a
        // base64-ish byte — so the CID dispatcher can hand us either.
        let looks_like_header = envelope.proof.starts_with(NOSTR_PREFIX);
        let header = if looks_like_header {
            envelope.proof.to_string()
        } else {
            format!("{NOSTR_PREFIX}{}", envelope.proof)
        };

        match verify_at(&header, envelope.uri, envelope.method, None, envelope.now_unix) {
            Ok(v) => Ok(Some(VerifiedSubject {
                did: format!("urn:nip98:{}", v.pubkey),
                verification_method: format!("urn:nip98:{}#key-0", v.pubkey),
            })),
            // Header-shaped proof (`Nostr …`) that fails to parse — the
            // client clearly intended a NIP-98 event, so surface the
            // failure verbatim so the dispatcher stops.
            Err(crate::error::PodError::Nip98(msg)) if looks_like_header => {
                if msg.contains("timestamp") {
                    Err(SelfSignedError::OutOfTimeWindow(msg))
                } else if msg.contains("URL mismatch") || msg.contains("method mismatch") {
                    Err(SelfSignedError::ScopeMismatch(msg))
                } else if msg.contains("schnorr") || msg.contains("id mismatch") {
                    Err(SelfSignedError::InvalidSignature(msg))
                } else {
                    Err(SelfSignedError::Malformed(msg))
                }
            }
            // Bare (non-header) input — treat any structural failure as
            // "not NIP-98, try the next verifier". Only surface errors
            // for the well-formed-event-but-bad-signature case.
            Err(_) if !looks_like_header => Ok(None),
            Err(e) => Err(SelfSignedError::Malformed(e.to_string())),
        }
    }

    fn name(&self) -> &'static str {
        "nip98"
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn encode_event(event: &serde_json::Value) -> String {
        BASE64.encode(serde_json::to_string(event).unwrap().as_bytes())
    }

    /// Deterministic test keypair. Under `nip98-schnorr` this returns a
    /// real BIP-340 signing key whose x-only pubkey is returned as hex.
    /// Without the feature, returns the legacy `"a".repeat(64)` placeholder.
    #[cfg(feature = "nip98-schnorr")]
    fn test_signing_key() -> (k256::schnorr::SigningKey, String) {
        // Deterministic 32-byte seed — not all seeds produce a valid
        // Schnorr key, but this one does (secp256k1 is ~99.9% acceptance).
        let seed = [0x42u8; 32];
        let sk = k256::schnorr::SigningKey::from_bytes(&seed)
            .expect("seed produces valid Schnorr signing key");
        let pubkey_hex = hex::encode(sk.verifying_key().to_bytes());
        (sk, pubkey_hex)
    }

    #[cfg(not(feature = "nip98-schnorr"))]
    fn test_pubkey() -> String {
        "a".repeat(64)
    }

    #[cfg(feature = "nip98-schnorr")]
    fn test_pubkey() -> String {
        test_signing_key().1
    }

    /// Build a canonically-hashed, properly-signed (when feature on) event.
    ///
    /// - `id` is always computed from the NIP-01 canonical serialisation.
    /// - `sig` is a real BIP-340 Schnorr signature when `nip98-schnorr` is
    ///   enabled, otherwise a 128-hex-zero placeholder (not verified).
    fn valid_event(url: &str, method: &str, ts: u64, body: Option<&[u8]>) -> serde_json::Value {
        let mut tags = vec![
            vec!["u".to_string(), url.to_string()],
            vec!["method".to_string(), method.to_string()],
        ];
        if let Some(b) = body {
            tags.push(vec!["payload".to_string(), hex::encode(Sha256::digest(b))]);
        }

        let pubkey = test_pubkey();
        let kind = 27235u64;
        let content = String::new();

        // Build a Nip98Event purely to reuse `compute_event_id` —
        // that's the canonical NIP-01 hash and the single source of truth.
        let skeleton = Nip98Event {
            id: String::new(),
            pubkey: pubkey.clone(),
            created_at: ts,
            kind,
            tags: tags.clone(),
            content: content.clone(),
            sig: String::new(),
        };
        let id = compute_event_id(&skeleton);

        let sig = {
            #[cfg(feature = "nip98-schnorr")]
            {
                // Match the verifier: `verify_schnorr_signature` calls
                // `VerifyingKey::verify(id_bytes, sig)`, and k256's
                // `Verifier` impl hashes the input via
                // `Sha256::new_with_prefix`. The paired `Signer::try_sign`
                // does the same, so signing over `id_bytes` with that
                // trait produces a matching signature.
                use k256::schnorr::signature::Signer;
                let (sk, _) = test_signing_key();
                let id_bytes: Vec<u8> = hex::decode(&id).expect("id is valid hex");
                let signature: k256::schnorr::Signature =
                    sk.sign(&id_bytes);
                hex::encode(signature.to_bytes())
            }
            #[cfg(not(feature = "nip98-schnorr"))]
            {
                "0".repeat(128)
            }
        };

        serde_json::json!({
            "id": id,
            "pubkey": pubkey,
            "created_at": ts,
            "kind": kind,
            "tags": tags,
            "content": content,
            "sig": sig,
        })
    }

    #[test]
    fn rejects_missing_prefix() {
        let err = verify_at("Bearer xyz", "https://a/b", "GET", None, 0).unwrap_err();
        assert!(matches!(err, PodError::Nip98(_)));
    }

    #[test]
    fn accepts_well_formed_event_no_body() {
        let ts = 1_700_000_000u64;
        let ev = valid_event("https://api.example.com/x", "GET", ts, None);
        let hdr = authorization_header(&encode_event(&ev));
        let r = verify_at(&hdr, "https://api.example.com/x", "GET", None, ts).unwrap();
        assert_eq!(r.pubkey, test_pubkey());
        assert_eq!(r.url, "https://api.example.com/x");
    }

    #[test]
    fn accepts_trailing_slash_variation() {
        let ts = 1_700_000_000u64;
        let ev = valid_event("https://api.example.com/x/", "GET", ts, None);
        let hdr = authorization_header(&encode_event(&ev));
        verify_at(&hdr, "https://api.example.com/x", "GET", None, ts).unwrap();
    }

    #[test]
    fn rejects_url_mismatch() {
        let ts = 1_700_000_000u64;
        let ev = valid_event("https://good/x", "GET", ts, None);
        let hdr = authorization_header(&encode_event(&ev));
        let err = verify_at(&hdr, "https://evil/x", "GET", None, ts).unwrap_err();
        assert!(matches!(err, PodError::Nip98(_)));
    }

    #[test]
    fn rejects_payload_mismatch() {
        let ts = 1_700_000_000u64;
        let ev = valid_event("https://a/b", "POST", ts, Some(b"original"));
        let hdr = authorization_header(&encode_event(&ev));
        let err = verify_at(&hdr, "https://a/b", "POST", Some(b"tampered"), ts).unwrap_err();
        assert!(matches!(err, PodError::Nip98(_)));
    }

    #[test]
    fn rejects_body_without_payload_tag() {
        let ts = 1_700_000_000u64;
        let ev = valid_event("https://a/b", "POST", ts, None);
        let hdr = authorization_header(&encode_event(&ev));
        let err = verify_at(&hdr, "https://a/b", "POST", Some(b"sneaky"), ts).unwrap_err();
        assert!(matches!(err, PodError::Nip98(_)));
    }

    #[test]
    fn rejects_expired_timestamp() {
        let ts = 1_700_000_000u64;
        let ev = valid_event("https://a/b", "GET", ts, None);
        let hdr = authorization_header(&encode_event(&ev));
        let err = verify_at(&hdr, "https://a/b", "GET", None, ts + 120).unwrap_err();
        assert!(matches!(err, PodError::Nip98(_)));
    }

    #[test]
    fn rejects_wrong_kind() {
        let ts = 1_700_000_000u64;
        let mut ev = valid_event("https://a/b", "GET", ts, None);
        ev["kind"] = serde_json::json!(1);
        let hdr = authorization_header(&encode_event(&ev));
        let err = verify_at(&hdr, "https://a/b", "GET", None, ts).unwrap_err();
        assert!(matches!(err, PodError::Nip98(_)));
    }

    #[test]
    fn compute_event_id_matches_canonical_hash() {
        let event = Nip98Event {
            id: String::new(),
            pubkey: "a".repeat(64),
            created_at: 1_700_000_000,
            kind: 27235,
            tags: vec![
                vec!["u".into(), "https://api.example.com/x".into()],
                vec!["method".into(), "GET".into()],
            ],
            content: String::new(),
            sig: "0".repeat(128),
        };
        // Stable canonical hash — recomputing produces the same value.
        let id1 = compute_event_id(&event);
        let id2 = compute_event_id(&event);
        assert_eq!(id1, id2);
        assert_eq!(id1.len(), 64);
    }
}