solid-pod-rs-activitypub 0.4.0-alpha.4

ActivityPub Actor, inbox, outbox, HTTP Signatures, NodeInfo 2.1 for solid-pod-rs (JSS src/ap parity)
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
//! Integration tests for HTTP Signature signing and verification.
//!
//! These tests exercise the draft-cavage-http-signatures-12
//! implementation used for ActivityPub federation: RSA-SHA256 signing,
//! Digest header computation, round-trip sign-then-verify, and
//! rejection of tampered or mismatched signatures.

use async_trait::async_trait;
use solid_pod_rs_activitypub::{
    actor::generate_actor_keypair,
    digest_header,
    error::SigError,
    http_sig::{
        sign_request, verify_request_signature, ActorKeyResolver, OutboundRequest, SignedRequest,
        VerifiedActor,
    },
};

// ---------------------------------------------------------------------------
// Test resolver: returns a static public key for any keyId
// ---------------------------------------------------------------------------

struct StaticResolver {
    pem: String,
}

#[async_trait]
impl ActorKeyResolver for StaticResolver {
    async fn resolve(&self, key_id: &str) -> Result<VerifiedActor, SigError> {
        Ok(VerifiedActor {
            key_id: key_id.to_string(),
            actor_url: key_id
                .split_once('#')
                .map(|(u, _)| u.to_string())
                .unwrap_or_else(|| key_id.to_string()),
            public_key_pem: self.pem.clone(),
        })
    }
}

/// Build a properly signed inbound request using the raw crypto
/// primitives, matching the production `sign_request` flow but
/// constructing a `SignedRequest` for the verifier.
fn build_signed_inbound(
    method: &str,
    path: &str,
    body: &[u8],
    priv_pem: &str,
    key_id: &str,
) -> SignedRequest {
    use base64::{engine::general_purpose::STANDARD as B64, Engine as _};
    use rsa::pkcs1v15::SigningKey;
    use rsa::pkcs8::DecodePrivateKey;
    use rsa::signature::{SignatureEncoding, Signer};
    use rsa::RsaPrivateKey;
    use sha2::Sha256;

    let host = "pod.example";
    let date = httpdate::fmt_http_date(std::time::SystemTime::now());
    let digest = digest_header(body);
    let base = format!(
        "(request-target): {} {}\nhost: {}\ndate: {}\ndigest: {}",
        method.to_ascii_lowercase(),
        path,
        host,
        date,
        digest
    );
    let sk = RsaPrivateKey::from_pkcs8_pem(priv_pem).unwrap();
    let signer = SigningKey::<Sha256>::new(sk);
    let sig: rsa::pkcs1v15::Signature = signer.sign(base.as_bytes());
    let sig_b64 = B64.encode(sig.to_bytes());
    let sig_header = format!(
        "keyId=\"{key_id}\",algorithm=\"rsa-sha256\",headers=\"(request-target) host date digest\",signature=\"{sig_b64}\""
    );

    SignedRequest::new(method, path, body.to_vec())
        .with_header("host", host)
        .with_header("date", date)
        .with_header("digest", digest)
        .with_header("signature", sig_header)
}

// ===========================================================================
// Digest computation
// ===========================================================================

#[test]
fn digest_header_sha256_format() {
    let d = digest_header(b"hello world");
    assert!(
        d.starts_with("SHA-256="),
        "digest should start with SHA-256=, got: {d}"
    );
}

#[test]
fn digest_header_empty_body() {
    let d = digest_header(b"");
    assert!(d.starts_with("SHA-256="));
    // SHA-256 of empty string is well-known.
    assert_eq!(
        d,
        "SHA-256=47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="
    );
}

#[test]
fn digest_header_deterministic() {
    let a = digest_header(b"same content");
    let b = digest_header(b"same content");
    assert_eq!(a, b);
}

#[test]
fn digest_header_differs_for_different_content() {
    let a = digest_header(b"content-a");
    let b = digest_header(b"content-b");
    assert_ne!(a, b);
}

// ===========================================================================
// Sign + Verify round-trip
// ===========================================================================

#[tokio::test]
async fn sign_then_verify_roundtrip() {
    let (priv_pem, pub_pem) = generate_actor_keypair().unwrap();
    let key_id = "https://pod.example/profile/card.jsonld#main-key";
    let body = br#"{"type":"Create","object":{"type":"Note","content":"test"}}"#.to_vec();

    let mut out = OutboundRequest {
        method: "POST".into(),
        url: "https://remote.example/inbox".into(),
        headers: vec![("Content-Type".into(), "application/activity+json".into())],
        body: body.clone(),
    };
    sign_request(&mut out, &priv_pem, key_id).unwrap();

    // Verify the outbound now carries Host, Date, Digest, Signature.
    let header_names: Vec<String> = out
        .headers
        .iter()
        .map(|(k, _)| k.to_ascii_lowercase())
        .collect();
    assert!(header_names.contains(&"host".to_string()));
    assert!(header_names.contains(&"date".to_string()));
    assert!(header_names.contains(&"digest".to_string()));
    assert!(header_names.contains(&"signature".to_string()));

    // Convert to inbound shape and verify.
    let url = url::Url::parse(&out.url).unwrap();
    let path = url.path().to_string();
    let mut inbound = SignedRequest::new("POST", &path, body);
    for (k, v) in &out.headers {
        inbound.headers.insert(k.to_ascii_lowercase(), v.clone());
    }
    let resolver = StaticResolver { pem: pub_pem };
    let actor = verify_request_signature(&inbound, &resolver)
        .await
        .unwrap();
    assert_eq!(actor.key_id, key_id);
    assert_eq!(
        actor.actor_url,
        "https://pod.example/profile/card.jsonld"
    );
}

// ===========================================================================
// Verification failures
// ===========================================================================

#[tokio::test]
async fn verify_rejects_tampered_body() {
    let (priv_pem, pub_pem) = generate_actor_keypair().unwrap();
    let key_id = "https://remote.example/actor#main-key";
    let mut req = build_signed_inbound("POST", "/inbox", b"{}", &priv_pem, key_id);
    // Tamper the body after signing.
    req.body = b"{\"tampered\":true}".to_vec();
    let resolver = StaticResolver { pem: pub_pem };
    let result = verify_request_signature(&req, &resolver).await;
    assert!(
        matches!(result, Err(SigError::DigestMismatch)),
        "expected DigestMismatch, got {result:?}"
    );
}

#[tokio::test]
async fn verify_rejects_tampered_header() {
    let (priv_pem, pub_pem) = generate_actor_keypair().unwrap();
    let key_id = "https://remote.example/actor#main-key";
    let mut req = build_signed_inbound("POST", "/inbox", b"{}", &priv_pem, key_id);
    // Tamper the Date header after signing — this invalidates the
    // signature base string without affecting the digest.
    req.headers.insert(
        "date".to_string(),
        "Sat, 01 Jan 2000 00:00:00 GMT".to_string(),
    );
    let resolver = StaticResolver { pem: pub_pem };
    let result = verify_request_signature(&req, &resolver).await;
    assert!(
        matches!(result, Err(SigError::VerifyFailed(_))),
        "expected VerifyFailed, got {result:?}"
    );
}

#[tokio::test]
async fn verify_rejects_wrong_public_key() {
    let (priv_pem, _pub_pem) = generate_actor_keypair().unwrap();
    let (_other_priv, other_pub) = generate_actor_keypair().unwrap();
    let key_id = "https://remote.example/actor#main-key";
    let req = build_signed_inbound("POST", "/inbox", b"{}", &priv_pem, key_id);
    let resolver = StaticResolver { pem: other_pub };
    let result = verify_request_signature(&req, &resolver).await;
    assert!(
        matches!(result, Err(SigError::VerifyFailed(_))),
        "expected VerifyFailed, got {result:?}"
    );
}

#[tokio::test]
async fn verify_rejects_missing_signature_header() {
    let req = SignedRequest::new("POST", "/inbox", b"{}".to_vec())
        .with_header("host", "pod.example")
        .with_header("date", "Mon, 06 May 2026 12:00:00 GMT");
    let (_priv_pem, pub_pem) = generate_actor_keypair().unwrap();
    let resolver = StaticResolver { pem: pub_pem };
    let result = verify_request_signature(&req, &resolver).await;
    assert!(
        matches!(result, Err(SigError::MissingHeader("signature"))),
        "expected MissingHeader(signature), got {result:?}"
    );
}

// ===========================================================================
// sign_request header mechanics
// ===========================================================================

#[test]
fn sign_request_adds_four_headers() {
    let (priv_pem, _pub_pem) = generate_actor_keypair().unwrap();
    let key_id = "https://pod.example/key#main-key";
    let mut req = OutboundRequest {
        method: "POST".into(),
        url: "https://remote.example/inbox".into(),
        headers: vec![("Content-Type".into(), "application/activity+json".into())],
        body: b"{}".to_vec(),
    };
    sign_request(&mut req, &priv_pem, key_id).unwrap();

    let names: Vec<String> = req.headers.iter().map(|(k, _)| k.clone()).collect();
    assert!(names.contains(&"Host".to_string()));
    assert!(names.contains(&"Date".to_string()));
    assert!(names.contains(&"Digest".to_string()));
    assert!(names.contains(&"Signature".to_string()));
    // Content-Type should still be present.
    assert!(names.contains(&"Content-Type".to_string()));
}

#[test]
fn sign_request_deduplicates_existing_headers() {
    let (priv_pem, _pub_pem) = generate_actor_keypair().unwrap();
    let key_id = "https://pod.example/key#main-key";
    let mut req = OutboundRequest {
        method: "POST".into(),
        url: "https://remote.example/inbox".into(),
        headers: vec![
            ("Host".into(), "old-host".into()),
            ("Date".into(), "old-date".into()),
            ("Digest".into(), "old-digest".into()),
            ("Signature".into(), "old-sig".into()),
        ],
        body: b"{}".to_vec(),
    };
    sign_request(&mut req, &priv_pem, key_id).unwrap();

    // Each of Host, Date, Digest, Signature should appear exactly once.
    for name in &["Host", "Date", "Digest", "Signature"] {
        let count = req
            .headers
            .iter()
            .filter(|(k, _)| k.eq_ignore_ascii_case(name))
            .count();
        assert_eq!(count, 1, "{name} should appear exactly once, found {count}");
    }
}

#[test]
fn sign_request_host_matches_url() {
    let (priv_pem, _pub_pem) = generate_actor_keypair().unwrap();
    let key_id = "https://pod.example/key#main-key";
    let mut req = OutboundRequest {
        method: "POST".into(),
        url: "https://specific-host.example:8443/inbox".into(),
        headers: vec![],
        body: b"{}".to_vec(),
    };
    sign_request(&mut req, &priv_pem, key_id).unwrap();

    let host = req
        .headers
        .iter()
        .find(|(k, _)| k == "Host")
        .map(|(_, v)| v.as_str())
        .unwrap();
    assert_eq!(host, "specific-host.example");
}

#[test]
fn sign_request_digest_matches_body() {
    let (priv_pem, _pub_pem) = generate_actor_keypair().unwrap();
    let key_id = "https://pod.example/key#main-key";
    let body = b"{\"type\":\"Follow\"}";
    let mut req = OutboundRequest {
        method: "POST".into(),
        url: "https://remote.example/inbox".into(),
        headers: vec![],
        body: body.to_vec(),
    };
    sign_request(&mut req, &priv_pem, key_id).unwrap();

    let digest_val = req
        .headers
        .iter()
        .find(|(k, _)| k == "Digest")
        .map(|(_, v)| v.clone())
        .unwrap();
    let expected = digest_header(body);
    assert_eq!(digest_val, expected);
}

#[test]
fn sign_request_signature_header_contains_key_id() {
    let (priv_pem, _pub_pem) = generate_actor_keypair().unwrap();
    let key_id = "https://pod.example/profile/card.jsonld#main-key";
    let mut req = OutboundRequest {
        method: "POST".into(),
        url: "https://remote.example/inbox".into(),
        headers: vec![],
        body: b"{}".to_vec(),
    };
    sign_request(&mut req, &priv_pem, key_id).unwrap();

    let sig_header = req
        .headers
        .iter()
        .find(|(k, _)| k == "Signature")
        .map(|(_, v)| v.clone())
        .unwrap();
    assert!(
        sig_header.contains(key_id),
        "Signature header should contain the keyId"
    );
    assert!(sig_header.contains("algorithm=\"rsa-sha256\""));
    assert!(sig_header.contains("headers=\"(request-target) host date digest\""));
}

#[test]
fn sign_request_rejects_invalid_url() {
    let (priv_pem, _pub_pem) = generate_actor_keypair().unwrap();
    let key_id = "https://pod.example/key#main-key";
    let mut req = OutboundRequest {
        method: "POST".into(),
        url: "not-a-valid-url".into(),
        headers: vec![],
        body: b"{}".to_vec(),
    };
    let result = sign_request(&mut req, &priv_pem, key_id);
    assert!(
        matches!(result, Err(SigError::Url(_))),
        "expected Url error, got {result:?}"
    );
}

// ===========================================================================
// Verify with different body sizes
// ===========================================================================

#[tokio::test]
async fn sign_verify_large_body() {
    let (priv_pem, pub_pem) = generate_actor_keypair().unwrap();
    let key_id = "https://pod.example/key#main-key";
    // 10 KB body.
    let body = vec![b'x'; 10_000];
    let mut out = OutboundRequest {
        method: "POST".into(),
        url: "https://remote.example/inbox".into(),
        headers: vec![],
        body: body.clone(),
    };
    sign_request(&mut out, &priv_pem, key_id).unwrap();

    let url = url::Url::parse(&out.url).unwrap();
    let mut inbound = SignedRequest::new("POST", url.path(), body);
    for (k, v) in &out.headers {
        inbound.headers.insert(k.to_ascii_lowercase(), v.clone());
    }
    let resolver = StaticResolver { pem: pub_pem };
    let actor = verify_request_signature(&inbound, &resolver)
        .await
        .unwrap();
    assert_eq!(actor.key_id, key_id);
}