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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//! Integration tests for `tools.cairn.admin.listAuditLog` (#17).
//!
//! Admin-role-only endpoint. Tests cover role gating, all filters
//! (actor, action, outcome, since, until), bound-swap 400, unknown
//! action/outcome 400, DESC pagination across 60 rows, no-auth 401,
//! CORS reject-any-origin 403, reason-passthrough of writer-produced
//! rows, and the `labels.created_at == audit_log.created_at` join
//! invariant for actor filtering used by list_labels.

use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use async_trait::async_trait;
use base64::Engine as _;
use cairn_mod::auth::did::{DidDocument, DidResolver, ResolveError, VerificationMethod};
use cairn_mod::auth::{AuthConfig, AuthContext};
use cairn_mod::{
    AdminConfig, ApplyLabelRequest, admin_router, spawn_writer, storage,
    writer::{AUDIT_ACTION_VALUES, AUDIT_OUTCOME_VALUES},
};
use proto_blue_crypto::{K256Keypair, Keypair as _, Signer as _, format_multikey};
use serde_json::Value;
use sqlx::{Pool, Sqlite};
use tempfile::TempDir;
use tokio::net::TcpListener;

const TEST_PRIV_HEX: &str = "b7e3f1c9a2d84ef50712436589bc1d8f023147b68cafed94a8b603c7159d4e2a";
const SERVICE_DID: &str = "did:plc:cairn0000000000000000000000";
const ADMIN_DID: &str = "did:plc:admin00000000000000000000";
const MOD_DID: &str = "did:plc:moderator0000000000000000";

// ---------- JWT + resolver helpers (same pattern as admin_reports.rs) ----------

fn test_keypair() -> K256Keypair {
    K256Keypair::from_private_key(&hex::decode(TEST_PRIV_HEX).unwrap()).unwrap()
}

fn did_doc(did: &str) -> DidDocument {
    DidDocument {
        id: did.to_string(),
        verification_method: vec![VerificationMethod {
            id: format!("{did}#atproto"),
            r#type: "Multikey".into(),
            public_key_multibase: format_multikey(
                "ES256K",
                &test_keypair().public_key_compressed(),
            ),
        }],
    }
}

fn build_jwt(iss: &str, lxm: &str) -> String {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;
    let claims = serde_json::json!({
        "iss": iss,
        "aud": SERVICE_DID,
        "exp": now + 60,
        "iat": now,
        "jti": format!("jti-{}", uuid::Uuid::new_v4()),
        "lxm": lxm,
    });
    let header = serde_json::json!({"alg": "ES256K", "typ": "JWT"});
    let engine = base64::engine::general_purpose::URL_SAFE_NO_PAD;
    let h = engine.encode(header.to_string());
    let p = engine.encode(claims.to_string());
    let input = format!("{h}.{p}");
    let sig = test_keypair().sign(input.as_bytes()).unwrap();
    format!("{h}.{p}.{}", engine.encode(sig))
}

struct MockResolver(Mutex<HashMap<String, DidDocument>>);

#[async_trait]
impl DidResolver for MockResolver {
    async fn resolve(&self, did: &str) -> Result<DidDocument, ResolveError> {
        self.0
            .lock()
            .unwrap()
            .get(did)
            .cloned()
            .ok_or(ResolveError::BadStatus(404))
    }
}

fn auth_ctx() -> Arc<AuthContext> {
    let resolver = Arc::new(MockResolver(Mutex::new(
        [
            (ADMIN_DID.to_string(), did_doc(ADMIN_DID)),
            (MOD_DID.to_string(), did_doc(MOD_DID)),
        ]
        .into(),
    )));
    Arc::new(AuthContext::with_resolver(
        AuthConfig {
            service_did: SERVICE_DID.to_string(),
            ..AuthConfig::default()
        },
        resolver,
    ))
}

// ---------- Harness ----------

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

async fn spawn() -> Harness {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("cairn.db");
    let pool = storage::open(&path).await.unwrap();
    let writer = spawn_writer(
        pool.clone(),
        cairn_mod::SigningKey::from_bytes(hex::decode(TEST_PRIV_HEX).unwrap().try_into().unwrap()),
        SERVICE_DID.to_string(),
    )
    .await
    .unwrap();

    let router = admin_router(
        pool.clone(),
        writer.clone(),
        auth_ctx(),
        AdminConfig::default(),
    );
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        axum::serve(listener, router.into_make_service()).await.ok();
    });
    Harness {
        _dir: dir,
        pool,
        writer,
        addr,
    }
}

async fn grant_role(pool: &Pool<Sqlite>, did: &str, role: &str) {
    sqlx::query!(
        "INSERT INTO moderators (did, role, added_at) VALUES (?1, ?2, ?3)",
        did,
        role,
        0_i64,
    )
    .execute(pool)
    .await
    .unwrap();
}

/// Seed a raw audit_log row. Uses direct SQL so tests can pin
/// filter/pagination behavior without running through the writer.
/// Returns (id, created_at_ms) — the id is needed for pagination
/// assertions; created_at lets tests compute since/until bounds.
async fn seed_audit(
    pool: &Pool<Sqlite>,
    created_at_ms: i64,
    action: &str,
    actor_did: &str,
    target: Option<&str>,
    outcome: &str,
    reason: Option<&str>,
) -> i64 {
    sqlx::query_scalar!(
        "INSERT INTO audit_log
             (created_at, action, actor_did, target, target_cid, outcome, reason)
         VALUES (?1, ?2, ?3, ?4, NULL, ?5, ?6)
         RETURNING id",
        created_at_ms,
        action,
        actor_did,
        target,
        outcome,
        reason,
    )
    .fetch_one(pool)
    .await
    .unwrap()
}

// ---------- HTTP helper ----------

async fn get_query(addr: SocketAddr, path_with_query: &str, auth: Option<&str>) -> (u16, Value) {
    use http_body_util::{BodyExt as _, Empty};
    use hyper::body::Bytes;
    use hyper_util::rt::TokioIo;
    use tokio::net::TcpStream;

    let io = TokioIo::new(TcpStream::connect(addr).await.unwrap());
    let (mut send, conn) = hyper::client::conn::http1::handshake(io).await.unwrap();
    tokio::spawn(async move {
        let _ = conn.await;
    });
    let mut req = hyper::Request::builder()
        .method("GET")
        .uri(path_with_query)
        .header("host", "127.0.0.1");
    if let Some(t) = auth {
        req = req.header("authorization", format!("Bearer {t}"));
    }
    let req = req.body(Empty::<Bytes>::new()).unwrap();
    let resp = tokio::time::timeout(Duration::from_secs(5), send.send_request(req))
        .await
        .unwrap()
        .unwrap();
    let status = resp.status().as_u16();
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    let json = if body.is_empty() {
        Value::Null
    } else {
        serde_json::from_slice(&body).unwrap()
    };
    (status, json)
}

async fn get_with_origin(
    addr: SocketAddr,
    path_with_query: &str,
    auth: Option<&str>,
    origin: &str,
) -> u16 {
    use http_body_util::{BodyExt as _, Empty};
    use hyper::body::Bytes;
    use hyper_util::rt::TokioIo;
    use tokio::net::TcpStream;

    let io = TokioIo::new(TcpStream::connect(addr).await.unwrap());
    let (mut send, conn) = hyper::client::conn::http1::handshake(io).await.unwrap();
    tokio::spawn(async move {
        let _ = conn.await;
    });
    let mut req = hyper::Request::builder()
        .method("GET")
        .uri(path_with_query)
        .header("host", "127.0.0.1")
        .header("origin", origin);
    if let Some(t) = auth {
        req = req.header("authorization", format!("Bearer {t}"));
    }
    let req = req.body(Empty::<Bytes>::new()).unwrap();
    let resp = tokio::time::timeout(Duration::from_secs(5), send.send_request(req))
        .await
        .unwrap()
        .unwrap();
    let status = resp.status().as_u16();
    let _ = resp.into_body().collect().await.unwrap();
    status
}

// ========== auth + role ==========

#[tokio::test]
async fn no_auth_returns_401() {
    let h = spawn().await;
    let (status, body) = get_query(h.addr, "/xrpc/tools.cairn.admin.listAuditLog", None).await;
    assert_eq!(status, 401);
    assert_eq!(body["error"], "AuthenticationRequired");
    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn mod_role_rejected_403() {
    let h = spawn().await;
    grant_role(&h.pool, MOD_DID, "mod").await;
    let jwt = build_jwt(MOD_DID, "tools.cairn.admin.listAuditLog");
    let (status, body) =
        get_query(h.addr, "/xrpc/tools.cairn.admin.listAuditLog", Some(&jwt)).await;
    assert_eq!(status, 403);
    assert_eq!(body["error"], "Forbidden");
    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn admin_role_accepted() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;
    let jwt = build_jwt(ADMIN_DID, "tools.cairn.admin.listAuditLog");
    let (status, _) = get_query(h.addr, "/xrpc/tools.cairn.admin.listAuditLog", Some(&jwt)).await;
    assert_eq!(status, 200);
    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn cors_any_origin_rejected_403() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;
    let jwt = build_jwt(ADMIN_DID, "tools.cairn.admin.listAuditLog");
    let status = get_with_origin(
        h.addr,
        "/xrpc/tools.cairn.admin.listAuditLog",
        Some(&jwt),
        "https://evil.example",
    )
    .await;
    assert_eq!(status, 403);
    h.writer.shutdown().await.unwrap();
}

// ========== basic listing ==========

#[tokio::test]
async fn no_filters_returns_desc_by_id() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;
    // Three rows in insertion order — SQLite AUTOINCREMENT assigns
    // ascending ids.
    let a = seed_audit(
        &h.pool,
        1_777_104_000_000,
        "label_applied",
        MOD_DID,
        Some("at://did:plc:t/col/r"),
        "success",
        None,
    )
    .await;
    let b = seed_audit(
        &h.pool,
        1_777_104_001_000,
        "label_negated",
        MOD_DID,
        Some("at://did:plc:t/col/r"),
        "success",
        None,
    )
    .await;
    let c = seed_audit(
        &h.pool,
        1_777_104_002_000,
        "report_resolved",
        ADMIN_DID,
        Some("42"),
        "success",
        None,
    )
    .await;

    let jwt = build_jwt(ADMIN_DID, "tools.cairn.admin.listAuditLog");
    let (status, body) =
        get_query(h.addr, "/xrpc/tools.cairn.admin.listAuditLog", Some(&jwt)).await;
    assert_eq!(status, 200);
    let entries = body["entries"].as_array().unwrap();
    assert_eq!(entries.len(), 3);
    // DESC: newest first (c, b, a).
    assert_eq!(entries[0]["id"].as_i64().unwrap(), c);
    assert_eq!(entries[1]["id"].as_i64().unwrap(), b);
    assert_eq!(entries[2]["id"].as_i64().unwrap(), a);
    // Required fields present per lexicon.
    for e in entries {
        for k in ["id", "createdAt", "action", "actorDid", "outcome"] {
            assert!(e.get(k).is_some(), "required field {k} missing: {e}");
        }
    }
    h.writer.shutdown().await.unwrap();
}

// ========== filters ==========

#[tokio::test]
async fn actor_filter_narrows() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;
    seed_audit(
        &h.pool,
        1_777_104_000_000,
        "label_applied",
        MOD_DID,
        None,
        "success",
        None,
    )
    .await;
    seed_audit(
        &h.pool,
        1_777_104_001_000,
        "label_applied",
        ADMIN_DID,
        None,
        "success",
        None,
    )
    .await;

    let jwt = build_jwt(ADMIN_DID, "tools.cairn.admin.listAuditLog");
    let (_, body) = get_query(
        h.addr,
        &format!("/xrpc/tools.cairn.admin.listAuditLog?actor={MOD_DID}"),
        Some(&jwt),
    )
    .await;
    let entries = body["entries"].as_array().unwrap();
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0]["actorDid"], MOD_DID);
    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn action_filter_narrows_known_value() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;
    seed_audit(
        &h.pool,
        1_777_104_000_000,
        "label_applied",
        MOD_DID,
        None,
        "success",
        None,
    )
    .await;
    seed_audit(
        &h.pool,
        1_777_104_001_000,
        "label_negated",
        MOD_DID,
        None,
        "success",
        None,
    )
    .await;

    let jwt = build_jwt(ADMIN_DID, "tools.cairn.admin.listAuditLog");
    let (_, body) = get_query(
        h.addr,
        "/xrpc/tools.cairn.admin.listAuditLog?action=label_negated",
        Some(&jwt),
    )
    .await;
    let entries = body["entries"].as_array().unwrap();
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0]["action"], "label_negated");
    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn unknown_action_rejected_400() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;
    let jwt = build_jwt(ADMIN_DID, "tools.cairn.admin.listAuditLog");
    let (status, body) = get_query(
        h.addr,
        "/xrpc/tools.cairn.admin.listAuditLog?action=banana",
        Some(&jwt),
    )
    .await;
    assert_eq!(status, 400);
    assert_eq!(body["error"], "InvalidRequest");
    // Anti-leak: message must NOT enumerate the allowed values.
    let msg = body["message"].as_str().unwrap();
    for v in AUDIT_ACTION_VALUES {
        assert!(
            !msg.contains(v),
            "error message leaks allowed value {v}: {msg}"
        );
    }
    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn outcome_filter_narrows() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;
    seed_audit(
        &h.pool,
        1_777_104_000_000,
        "label_applied",
        MOD_DID,
        None,
        "success",
        None,
    )
    .await;
    seed_audit(
        &h.pool,
        1_777_104_001_000,
        "label_applied",
        MOD_DID,
        None,
        "failure",
        None,
    )
    .await;

    let jwt = build_jwt(ADMIN_DID, "tools.cairn.admin.listAuditLog");
    let (_, body) = get_query(
        h.addr,
        "/xrpc/tools.cairn.admin.listAuditLog?outcome=failure",
        Some(&jwt),
    )
    .await;
    let entries = body["entries"].as_array().unwrap();
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0]["outcome"], "failure");
    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn invalid_outcome_rejected_400() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;
    let jwt = build_jwt(ADMIN_DID, "tools.cairn.admin.listAuditLog");
    let (status, body) = get_query(
        h.addr,
        "/xrpc/tools.cairn.admin.listAuditLog?outcome=maybe",
        Some(&jwt),
    )
    .await;
    assert_eq!(status, 400);
    assert_eq!(body["error"], "InvalidRequest");
    let msg = body["message"].as_str().unwrap();
    for v in AUDIT_OUTCOME_VALUES {
        assert!(
            !msg.contains(v),
            "error message leaks allowed outcome {v}: {msg}"
        );
    }
    h.writer.shutdown().await.unwrap();
}

// ========== since / until bounds ==========

#[tokio::test]
async fn since_until_bounds_applied() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;
    // Base = 2026-04-23T00:00:00.000Z.
    const BASE_MS: i64 = 1_776_902_400_000;
    // t1 at 00:00, t2 at 00:10, t3 at 00:30 — window (00:05, 00:20) brackets only t2.
    let t1 = BASE_MS;
    let t2 = BASE_MS + 10 * 60 * 1000;
    let t3 = BASE_MS + 30 * 60 * 1000;
    seed_audit(&h.pool, t1, "label_applied", MOD_DID, None, "success", None).await;
    let inside = seed_audit(&h.pool, t2, "label_applied", MOD_DID, None, "success", None).await;
    seed_audit(&h.pool, t3, "label_applied", MOD_DID, None, "success", None).await;

    let jwt = build_jwt(ADMIN_DID, "tools.cairn.admin.listAuditLog");
    let (_, body) = get_query(
        h.addr,
        "/xrpc/tools.cairn.admin.listAuditLog\
         ?since=2026-04-23T00:05:00.000Z\
         &until=2026-04-23T00:20:00.000Z",
        Some(&jwt),
    )
    .await;
    let entries = body["entries"].as_array().unwrap();
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0]["id"].as_i64().unwrap(), inside);
    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn since_greater_than_until_rejected_400() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;
    let jwt = build_jwt(ADMIN_DID, "tools.cairn.admin.listAuditLog");
    let (status, body) = get_query(
        h.addr,
        "/xrpc/tools.cairn.admin.listAuditLog\
         ?since=2026-04-24T00:00:00.000Z\
         &until=2026-04-23T00:00:00.000Z",
        Some(&jwt),
    )
    .await;
    assert_eq!(status, 400);
    assert_eq!(body["error"], "InvalidRequest");
    h.writer.shutdown().await.unwrap();
}

#[tokio::test]
async fn malformed_since_rejected_400() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;
    let jwt = build_jwt(ADMIN_DID, "tools.cairn.admin.listAuditLog");
    let (status, _) = get_query(
        h.addr,
        "/xrpc/tools.cairn.admin.listAuditLog?since=yesterday",
        Some(&jwt),
    )
    .await;
    assert_eq!(status, 400);
    h.writer.shutdown().await.unwrap();
}

// ========== pagination ==========

#[tokio::test]
async fn pagination_desc_no_gaps_no_dupes() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;
    for i in 0..60 {
        seed_audit(
            &h.pool,
            1_777_104_000_000 + i,
            "label_applied",
            MOD_DID,
            None,
            "success",
            None,
        )
        .await;
    }

    let mut seen_ids: Vec<i64> = Vec::new();
    let mut cursor: Option<String> = None;
    for _ in 0..10 {
        let jwt = build_jwt(ADMIN_DID, "tools.cairn.admin.listAuditLog");
        let mut url = "/xrpc/tools.cairn.admin.listAuditLog?limit=25".to_string();
        if let Some(c) = &cursor {
            url.push_str(&format!("&cursor={}", urlencoding::encode(c)));
        }
        let (_, body) = get_query(h.addr, &url, Some(&jwt)).await;
        for e in body["entries"].as_array().unwrap() {
            seen_ids.push(e["id"].as_i64().unwrap());
        }
        cursor = body
            .get("cursor")
            .and_then(|c| c.as_str())
            .map(|s| s.to_string());
        if cursor.is_none() {
            break;
        }
    }
    assert_eq!(seen_ids.len(), 60);
    let mut sorted = seen_ids.clone();
    sorted.sort_by(|a, b| b.cmp(a));
    assert_eq!(sorted, seen_ids, "pages should concatenate in DESC order");
    let mut uniq = seen_ids.clone();
    uniq.sort();
    uniq.dedup();
    assert_eq!(uniq.len(), 60, "no duplicates across pages");
    h.writer.shutdown().await.unwrap();
}

// ========== writer-produced rows: reason passthrough + cross-module invariant ==========

#[tokio::test]
async fn writer_produced_row_reason_is_exact_passthrough() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;

    // Go through the writer for a real label_applied audit row.
    let req = ApplyLabelRequest {
        actor_did: MOD_DID.into(),
        uri: "at://did:plc:target/col/rec".into(),
        cid: Some("bafytest".into()),
        val: "spam".into(),
        exp: None,
        moderator_reason: Some("caught by heuristic #7".into()),
    };
    h.writer.apply_label(req).await.unwrap();

    let jwt = build_jwt(ADMIN_DID, "tools.cairn.admin.listAuditLog");
    let (_, body) = get_query(
        h.addr,
        "/xrpc/tools.cairn.admin.listAuditLog?action=label_applied",
        Some(&jwt),
    )
    .await;
    let entries = body["entries"].as_array().unwrap();
    assert_eq!(entries.len(), 1);
    let reason = entries[0]["reason"].as_str().unwrap();

    // Reason is opaque JSON — we parse only in the test to verify the
    // schema documented on AUDIT_REASON_SCHEMA round-trips intact.
    let parsed: Value = serde_json::from_str(reason).unwrap();
    assert_eq!(parsed["val"], "spam");
    assert_eq!(parsed["neg"], false);
    assert_eq!(parsed["moderator_reason"], "caught by heuristic #7");

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

/// Cross-module invariant (documented at src/server/admin/list_labels.rs):
/// listLabels filters by moderator actor by joining `labels` to
/// `audit_log` on `(uri, created_at)` — the audit row supplies the
/// `actor_did` because `labels` itself has no moderator column. This
/// requires `labels.created_at == audit_log.created_at` for the same
/// operation. Lock that invariant here so a future writer refactor
/// that timestamps label row and audit row separately breaks this
/// test instead of silently breaking listLabels' actor filter.
#[tokio::test]
async fn label_applied_audit_shares_created_at_with_labels_row() {
    let h = spawn().await;
    grant_role(&h.pool, ADMIN_DID, "admin").await;

    let req = ApplyLabelRequest {
        actor_did: MOD_DID.into(),
        uri: "at://did:plc:target/col/rec".into(),
        cid: Some("bafytest".into()),
        val: "spam".into(),
        exp: None,
        moderator_reason: None,
    };
    let event = h.writer.apply_label(req).await.unwrap();

    let uri = "at://did:plc:target/col/rec";
    let label_row = sqlx::query!("SELECT created_at FROM labels WHERE seq = ?1", event.seq,)
        .fetch_one(&h.pool)
        .await
        .unwrap();

    let audit_row = sqlx::query!(
        "SELECT created_at, actor_did FROM audit_log
         WHERE action = 'label_applied' AND target = ?1
         ORDER BY id DESC LIMIT 1",
        uri,
    )
    .fetch_one(&h.pool)
    .await
    .unwrap();

    assert_eq!(
        label_row.created_at, audit_row.created_at,
        "labels.created_at must equal audit_log.created_at (listLabels join key)"
    );
    assert_eq!(
        audit_row.actor_did, MOD_DID,
        "audit_log.actor_did must be the moderator DID supplied to apply_label"
    );

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