cairn-mod 1.0.0

Lightweight, Rust-native ATProto labeler
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
//! Integration tests for `com.atproto.label.queryLabels` (§F3).
//!
//! Like the subscribeLabels suite, each test spins up a real axum server
//! on an ephemeral port and issues live HTTP requests. We use the
//! transport-level behavior as the check — response status, headers, JSON
//! body — instead of calling the handler directly, because the router
//! composition (CORS layer, ConnectInfo, Extensions) is itself part of
//! what #6 is delivering.

use std::net::SocketAddr;
use std::time::Duration;

use cairn_mod::{
    ApplyLabelRequest, NegateLabelRequest, SigningKey, SubscribeConfig, WriterHandle, spawn_writer,
    storage, subscribe_router,
};
use serde_json::Value;
use sqlx::{Pool, Sqlite};
use tempfile::TempDir;
use tokio::net::TcpListener;

const SERVICE_DID: &str = "did:plc:3jzfcijpj2z2a4pdagfkktq6";
const MODERATOR_DID: &str = "did:plc:moderator0000000000000000";
const OTHER_DID: &str = "did:plc:someoneelse00000000000000";
const TEST_KEY_HEX: &str = "b7e3f1c9a2d84ef50712436589bc1d8f023147b68cafed94a8b603c7159d4e2a";

struct Harness {
    _dir: TempDir,
    _pool: Pool<Sqlite>,
    writer: WriterHandle,
    addr: SocketAddr,
}

fn test_key() -> SigningKey {
    let bytes: [u8; 32] = hex::decode(TEST_KEY_HEX)
        .expect("hex")
        .try_into()
        .expect("32 bytes");
    SigningKey::from_bytes(bytes)
}

async fn spawn_harness() -> Harness {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("cairn.db");
    let pool = storage::open(&path).await.expect("open pool");
    let writer = spawn_writer(pool.clone(), test_key(), SERVICE_DID.to_string())
        .await
        .expect("spawn writer");

    let router = subscribe_router(pool.clone(), writer.clone(), SubscribeConfig::default());
    let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
    let addr = listener.local_addr().expect("local_addr");

    tokio::spawn(async move {
        axum::serve(
            listener,
            router.into_make_service_with_connect_info::<SocketAddr>(),
        )
        .await
        .ok();
    });

    Harness {
        _dir: dir,
        _pool: pool,
        writer,
        addr,
    }
}

fn apply(uri: &str, val: &str) -> ApplyLabelRequest {
    ApplyLabelRequest {
        actor_did: MODERATOR_DID.to_string(),
        uri: uri.to_string(),
        cid: None,
        val: val.to_string(),
        exp: None,
        moderator_reason: None,
    }
}

fn negate(uri: &str, val: &str) -> NegateLabelRequest {
    NegateLabelRequest {
        actor_did: MODERATOR_DID.to_string(),
        uri: uri.to_string(),
        val: val.to_string(),
        moderator_reason: None,
    }
}

async fn http_get(addr: SocketAddr, query: &str) -> (u16, Value, hyper::HeaderMap) {
    // Minimal HTTP/1.1 client via hyper. Faster than pulling in reqwest;
    // gives us raw header access for the CORS test.
    use http_body_util::BodyExt as _;
    use http_body_util::Empty;
    use hyper::body::Bytes;
    use hyper_util::rt::TokioIo;
    use tokio::net::TcpStream;

    let stream = TcpStream::connect(addr).await.expect("connect");
    let io = TokioIo::new(stream);
    let (mut send, conn) = hyper::client::conn::http1::handshake(io)
        .await
        .expect("handshake");
    tokio::spawn(async move {
        let _ = conn.await;
    });

    let uri_path = format!("/xrpc/com.atproto.label.queryLabels?{query}");
    let req = hyper::Request::builder()
        .method("GET")
        .uri(&uri_path)
        .header("host", "127.0.0.1")
        .body(Empty::<Bytes>::new())
        .expect("build request");

    let resp = tokio::time::timeout(Duration::from_secs(5), send.send_request(req))
        .await
        .expect("request timeout")
        .expect("request");

    let status = resp.status().as_u16();
    let headers = resp.headers().clone();
    let body = resp.into_body().collect().await.expect("body").to_bytes();
    let json: Value = if body.is_empty() {
        Value::Null
    } else {
        serde_json::from_slice(&body).expect("parse json")
    };
    (status, json, headers)
}

fn labels_array(json: &Value) -> &Vec<Value> {
    json.get("labels").unwrap().as_array().unwrap()
}

fn make_uri(n: usize) -> String {
    format!("at://did:plc:subject{n:026}/app.bsky.feed.post/x")
}

// ========== Tests ==========

#[tokio::test]
async fn single_apply_returns_label() {
    let h = spawn_harness().await;
    let uri = make_uri(1);
    h.writer.apply_label(apply(&uri, "spam")).await.unwrap();

    let query = format!("uriPatterns={}", urlencoding::encode(&uri));
    let (status, body, _) = http_get(h.addr, &query).await;
    assert_eq!(status, 200);
    let labels = labels_array(&body);
    assert_eq!(labels.len(), 1);
    assert_eq!(labels[0]["uri"], uri);
    assert_eq!(labels[0]["val"], "spam");
    // sig is typed-bytes per §16.1.
    assert!(labels[0]["sig"]["$bytes"].is_string());

    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn negated_label_excluded_from_results() {
    let h = spawn_harness().await;
    let uri = make_uri(1);
    h.writer.apply_label(apply(&uri, "spam")).await.unwrap();
    h.writer.negate_label(negate(&uri, "spam")).await.unwrap();

    let query = format!("uriPatterns={}", urlencoding::encode(&uri));
    let (status, body, _) = http_get(h.addr, &query).await;
    assert_eq!(status, 200);
    assert_eq!(labels_array(&body).len(), 0);

    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn reapply_after_negation_appears_again() {
    let h = spawn_harness().await;
    let uri = make_uri(1);
    h.writer.apply_label(apply(&uri, "spam")).await.unwrap();
    h.writer.negate_label(negate(&uri, "spam")).await.unwrap();
    h.writer.apply_label(apply(&uri, "spam")).await.unwrap();

    let query = format!("uriPatterns={}", urlencoding::encode(&uri));
    let (status, body, _) = http_get(h.addr, &query).await;
    assert_eq!(status, 200);
    let labels = labels_array(&body);
    assert_eq!(labels.len(), 1, "latest event is apply, must appear");
    assert_eq!(labels[0]["val"], "spam");

    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn expired_label_excluded_from_results() {
    let h = spawn_harness().await;
    let uri = make_uri(1);
    // `exp` in the past.
    h.writer
        .apply_label(ApplyLabelRequest {
            actor_did: MODERATOR_DID.to_string(),
            uri: uri.clone(),
            cid: None,
            val: "tempban".to_string(),
            exp: Some("2020-01-01T00:00:00.000Z".to_string()),
            moderator_reason: None,
        })
        .await
        .unwrap();

    let query = format!("uriPatterns={}", urlencoding::encode(&uri));
    let (_, body, _) = http_get(h.addr, &query).await;
    assert_eq!(labels_array(&body).len(), 0, "expired label must be hidden");

    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn prefix_pattern_matches_all_under_prefix() {
    let h = spawn_harness().await;
    let a = "at://did:plc:subjectAAAAAAAAAAAAAAAAAAAA/app.bsky.feed.post/x";
    let b = "at://did:plc:subjectAAAAAAAAAAAAAAAAAAAA/app.bsky.feed.post/y";
    let c = "at://did:plc:subjectBBBBBBBBBBBBBBBBBBBB/app.bsky.feed.post/z";
    for uri in [a, b, c] {
        h.writer.apply_label(apply(uri, "spam")).await.unwrap();
    }

    let prefix = "at://did:plc:subjectAAAAAAAAAAAAAAAAAAAA*";
    let query = format!("uriPatterns={}", urlencoding::encode(prefix));
    let (_, body, _) = http_get(h.addr, &query).await;
    let labels = labels_array(&body);
    assert_eq!(labels.len(), 2, "two URIs under the prefix");
    let uris: Vec<String> = labels
        .iter()
        .map(|l| l["uri"].as_str().unwrap().to_string())
        .collect();
    assert!(uris.contains(&a.to_string()));
    assert!(uris.contains(&b.to_string()));
    assert!(!uris.contains(&c.to_string()));

    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn exact_pattern_matches_only_exact_uri() {
    let h = spawn_harness().await;
    let a = "at://did:plc:subjectAAAAAAAAAAAAAAAAAAAA/app.bsky.feed.post/x";
    let b = "at://did:plc:subjectAAAAAAAAAAAAAAAAAAAA/app.bsky.feed.post/y";
    for uri in [a, b] {
        h.writer.apply_label(apply(uri, "spam")).await.unwrap();
    }

    let query = format!("uriPatterns={}", urlencoding::encode(a));
    let (_, body, _) = http_get(h.addr, &query).await;
    let labels = labels_array(&body);
    assert_eq!(labels.len(), 1, "exact-match returns only one");
    assert_eq!(labels[0]["uri"], a);

    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn sources_filter_excludes_when_not_in_list() {
    let h = spawn_harness().await;
    let uri = make_uri(1);
    h.writer.apply_label(apply(&uri, "spam")).await.unwrap();

    // Caller asks for a DID we don't emit as.
    let query = format!(
        "uriPatterns={}&sources={}",
        urlencoding::encode(&uri),
        urlencoding::encode(OTHER_DID)
    );
    let (status, body, _) = http_get(h.addr, &query).await;
    assert_eq!(status, 200, "sources filter returns empty, not error");
    assert_eq!(labels_array(&body).len(), 0);

    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn sources_filter_includes_when_cairn_did_present() {
    let h = spawn_harness().await;
    let uri = make_uri(1);
    h.writer.apply_label(apply(&uri, "spam")).await.unwrap();

    let query = format!(
        "uriPatterns={}&sources={}&sources={}",
        urlencoding::encode(&uri),
        urlencoding::encode(OTHER_DID),
        urlencoding::encode(SERVICE_DID),
    );
    let (_, body, _) = http_get(h.addr, &query).await;
    assert_eq!(
        labels_array(&body).len(),
        1,
        "Cairn's DID in sources → included"
    );

    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn missing_uri_patterns_returns_invalid_request() {
    let h = spawn_harness().await;
    let (status, body, _) = http_get(h.addr, "").await;
    assert_eq!(status, 400);
    assert_eq!(body["error"], "InvalidRequest");

    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn malformed_uri_pattern_returns_invalid_request() {
    let h = spawn_harness().await;
    let query = format!("uriPatterns={}", urlencoding::encode("notanuri"));
    let (status, body, _) = http_get(h.addr, &query).await;
    assert_eq!(status, 400);
    assert_eq!(body["error"], "InvalidRequest");

    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn limit_out_of_range_returns_invalid_request() {
    let h = spawn_harness().await;
    let uri_owned = make_uri(1);
    let uri = urlencoding::encode(&uri_owned);

    for bad in ["0", "251", "-1", "abc"] {
        let query = format!("uriPatterns={uri}&limit={bad}");
        let (status, body, _) = http_get(h.addr, &query).await;
        assert_eq!(status, 400, "limit={bad} must reject");
        assert_eq!(body["error"], "InvalidRequest");
    }

    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn unknown_subject_returns_empty_labels() {
    let h = spawn_harness().await;
    let uri = make_uri(999);
    let query = format!("uriPatterns={}", urlencoding::encode(&uri));
    let (status, body, _) = http_get(h.addr, &query).await;
    assert_eq!(status, 200);
    assert_eq!(labels_array(&body).len(), 0);

    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn cors_header_any_origin_on_get_response() {
    let h = spawn_harness().await;
    let uri_owned = make_uri(1);
    let uri = urlencoding::encode(&uri_owned);
    let query = format!("uriPatterns={uri}");
    let (_, _, headers) = http_get(h.addr, &query).await;

    // §F3: accepts any origin.
    let allow_origin = headers
        .get("access-control-allow-origin")
        .expect("CORS allow-origin header must be present");
    assert_eq!(
        allow_origin.to_str().unwrap(),
        "*",
        "allow-origin should be wildcard for a public read endpoint"
    );
    // Credentials must never be echoed (§F3).
    assert!(
        headers.get("access-control-allow-credentials").is_none(),
        "allow-credentials must not be set"
    );

    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn pagination_across_three_pages_no_gaps_no_dupes() {
    let h = spawn_harness().await;

    // 120 labels under a common prefix so one uriPatterns covers them all.
    let prefix = "at://did:plc:pagination000000000000000000/app.bsky.feed.post/";
    let n = 120;
    for i in 0..n {
        h.writer
            .apply_label(apply(&format!("{prefix}{i:03}"), "spam"))
            .await
            .unwrap();
    }

    let pattern = format!("{prefix}*");
    let mut all_uris: Vec<String> = Vec::new();
    let mut cursor: Option<String> = None;
    for _ in 0..10 {
        let mut query = format!("uriPatterns={}&limit=50", urlencoding::encode(&pattern),);
        if let Some(c) = &cursor {
            query.push_str(&format!("&cursor={}", urlencoding::encode(c)));
        }
        let (status, body, _) = http_get(h.addr, &query).await;
        assert_eq!(status, 200);
        let labels = labels_array(&body);
        for l in labels {
            all_uris.push(l["uri"].as_str().unwrap().to_string());
        }
        cursor = body
            .get("cursor")
            .and_then(|c| c.as_str())
            .map(|s| s.to_string());
        if cursor.is_none() {
            break;
        }
    }

    assert_eq!(
        all_uris.len(),
        n as usize,
        "expected all {n} tuples across pages"
    );
    let mut uniq = all_uris.clone();
    uniq.sort();
    uniq.dedup();
    assert_eq!(uniq.len(), n as usize, "no duplicates across pages");

    h.writer.shutdown().await.unwrap();
}

/// Pagination semantics under concurrent writes (§F3 is best-effort, not
/// snapshot-consistent). The test documents the expected behavior: the
/// cursor prevents re-returning tuples already served, but new labels
/// written mid-traversal may or may not appear depending on their seq
/// relative to the cursor.
#[tokio::test]
async fn pagination_tolerates_interleaved_writes() {
    let h = spawn_harness().await;

    let prefix = "at://did:plc:interleave0000000000000000/app.bsky.feed.post/";
    for i in 0..60 {
        h.writer
            .apply_label(apply(&format!("{prefix}{i:03}"), "spam"))
            .await
            .unwrap();
    }

    let pattern = format!("{prefix}*");

    // Page 1 (limit=50).
    let (_, body, _) = http_get(
        h.addr,
        &format!("uriPatterns={}&limit=50", urlencoding::encode(&pattern)),
    )
    .await;
    let page_one: Vec<String> = labels_array(&body)
        .iter()
        .map(|l| l["uri"].as_str().unwrap().to_string())
        .collect();
    let cursor = body
        .get("cursor")
        .and_then(|c| c.as_str())
        .expect("cursor expected since 60 > 50");

    assert_eq!(page_one.len(), 50);

    // Interleave: write 10 new labels (60..70) between pages.
    for i in 60..70 {
        h.writer
            .apply_label(apply(&format!("{prefix}{i:03}"), "spam"))
            .await
            .unwrap();
    }

    // Page 2 with cursor.
    let (_, body, _) = http_get(
        h.addr,
        &format!(
            "uriPatterns={}&limit=50&cursor={}",
            urlencoding::encode(&pattern),
            urlencoding::encode(cursor)
        ),
    )
    .await;
    let page_two: Vec<String> = labels_array(&body)
        .iter()
        .map(|l| l["uri"].as_str().unwrap().to_string())
        .collect();

    // Invariant 1: no duplicates across pages (cursor prevents them).
    for uri in &page_two {
        assert!(
            !page_one.contains(uri),
            "page 2 must not repeat page 1 entries; duplicate {uri}"
        );
    }

    // Invariant 2: page 2 is non-empty (the remaining 10 originals + some
    // or all of the newly-written 10 should appear; exactly which of the
    // new ones is an implementation detail — the point is queryLabels is
    // point-in-time-per-page, not snapshot-consistent across pages).
    assert!(
        !page_two.is_empty(),
        "page 2 must include the remaining 10 + interleaved writes visible to this page"
    );

    h.writer.shutdown().await.unwrap();
}