cairn-mod 1.2.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
//! `cairn audit list` (#6) and `cairn audit show <id>` (#26) —
//! admin-side audit log queries.
//!
//! Wrap `tools.cairn.admin.listAuditLog`
//! (src/server/admin/list_audit_log.rs) and
//! `tools.cairn.admin.getAuditLog` (src/server/admin/get_audit_log.rs).
//! **Admin role only** — the server's auth check uses
//! `verify_and_authorize_admin_only`, so a moderator-role session
//! file produces a 403 surfaced as `CliError::CairnStatus { status: 403, .. }`.
//!
//! `list` query parameters mirror the handler's `Params`: optional
//! `actor`, `action`, `outcome`, `since` (RFC-3339, server parses
//! to ms via `parse_rfc3339_ms`), `until` (same), `limit`, `cursor`.
//! The CLI passes RFC-3339 strings through; no client-side
//! conversion. `outcome` is `"success"` or `"failure"`.
//!
//! `show` takes a single `id` query param and returns the bare
//! `auditEntry` shape (no envelope). On an unknown id the server
//! returns `AuditEntryNotFound` 404, which surfaces as
//! `CliError::CairnStatus { status: 404, body: "{\"error\":\"AuditEntryNotFound\",..}" }`
//! — distinct from the 403 mod-role posture.
//!
//! Pattern matches `cli/report.rs` exactly: typed `Input` →
//! `list()` / `show()` orchestrator → typed `Response` → pure
//! `format_*` functions.

use std::path::Path;
use std::time::Duration;

use reqwest::Client;
use serde::{Deserialize, Serialize};

use super::auth::acquire_service_auth;
use super::error::CliError;
use super::output::truncate;
use super::pds::PdsClient;
use super::session::SessionFile;

const LIST_AUDIT_LOG_LXM: &str = "tools.cairn.admin.listAuditLog";
const GET_AUDIT_LOG_LXM: &str = "tools.cairn.admin.getAuditLog";

/// Wire-shape of one row in a `listAuditLog` response. Mirrors
/// the server's `AuditEntry` projection.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuditEntry {
    /// Audit row primary key (monotonic, also the cursor unit).
    pub id: i64,
    /// RFC-3339 UTC timestamp the row was committed.
    #[serde(rename = "createdAt")]
    pub created_at: String,
    /// Audit action discriminator (e.g. `"label_applied"`,
    /// `"report_resolved"`, `"reporter_flagged"`).
    pub action: String,
    /// DID of the moderator/admin/operator that triggered the
    /// action.
    #[serde(rename = "actorDid")]
    pub actor_did: String,
    /// Optional target identifier (DID or AT-URI; depends on
    /// action).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub target: Option<String>,
    /// Optional CID pin on the target (for record-targeted
    /// actions like label-apply with strongRef).
    #[serde(rename = "targetCid", skip_serializing_if = "Option::is_none", default)]
    pub target_cid: Option<String>,
    /// `"success"` or `"failure"`.
    pub outcome: String,
    /// Free-text or JSON payload describing the action; schema
    /// per-action (see `crate::writer::AUDIT_REASON_*`).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub reason: Option<String>,
}

/// `listAuditLog` response envelope.
#[derive(Debug, Deserialize, Serialize)]
pub struct AuditListResponse {
    /// Matched entries, newest first.
    pub entries: Vec<AuditEntry>,
    /// Opaque next-page cursor. Present iff more results
    /// available.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub cursor: Option<String>,
}

/// Input to `cairn audit list`.
#[derive(Debug, Clone, Default)]
pub struct AuditListInput {
    /// Filter by actor DID. Server matches exact equality.
    pub actor: Option<String>,
    /// Filter by action discriminator (e.g. `"label_applied"`).
    /// Server validates against `AUDIT_ACTION_VALUES`.
    pub action: Option<String>,
    /// Filter by outcome (`"success"` or `"failure"`). Server
    /// validates against `AUDIT_OUTCOME_VALUES`.
    pub outcome: Option<String>,
    /// RFC-3339 inclusive lower bound on `created_at`.
    pub since: Option<String>,
    /// RFC-3339 inclusive upper bound on `created_at`.
    pub until: Option<String>,
    /// Max rows to return. Server clamps to [1, 250]; default 50.
    pub limit: Option<i64>,
    /// Opaque pagination cursor from a prior response.
    pub cursor: Option<String>,
    /// Per-invocation override of the session's stored Cairn URL.
    pub cairn_server_override: Option<String>,
}

/// Query the audit log via the admin HTTP endpoint.
///
/// Wraps the `tools.cairn.admin.listAuditLog` handler at
/// [src/server/admin/list_audit_log.rs](..) — GET with
/// query-string filters; server enforces ADMIN role
/// (`verify_and_authorize_admin_only`), validates the
/// `action` / `outcome` enums, parses `since` / `until` from
/// RFC-3339, and returns a newest-first page with optional
/// `cursor` for the next call.
pub async fn list(
    session: &mut SessionFile,
    session_path: &Path,
    input: AuditListInput,
) -> Result<AuditListResponse, CliError> {
    let cairn_server = input
        .cairn_server_override
        .as_deref()
        .unwrap_or(&session.cairn_server_url)
        .trim_end_matches('/')
        .to_string();
    let pds = PdsClient::new(&session.pds_url)?;
    let token = acquire_service_auth(&pds, session, session_path, LIST_AUDIT_LOG_LXM).await?;

    let url = format!("{cairn_server}/xrpc/{LIST_AUDIT_LOG_LXM}");
    let limit_owned = input.limit.map(|n| n.to_string());
    let mut query: Vec<(&str, &str)> = Vec::new();
    if let Some(a) = &input.actor {
        query.push(("actor", a.as_str()));
    }
    if let Some(a) = &input.action {
        query.push(("action", a.as_str()));
    }
    if let Some(o) = &input.outcome {
        query.push(("outcome", o.as_str()));
    }
    if let Some(s) = &input.since {
        query.push(("since", s.as_str()));
    }
    if let Some(u) = &input.until {
        query.push(("until", u.as_str()));
    }
    if let Some(n) = &limit_owned {
        query.push(("limit", n.as_str()));
    }
    if let Some(c) = &input.cursor {
        query.push(("cursor", c.as_str()));
    }

    let client = Client::builder()
        .timeout(Duration::from_secs(30))
        .build()
        .expect("reqwest build");
    let resp = client
        .get(&url)
        .bearer_auth(&token)
        .query(&query)
        .send()
        .await
        .map_err(|source| CliError::Http {
            url: url.clone(),
            source,
        })?;
    if !resp.status().is_success() {
        let status = resp.status().as_u16();
        let body = resp.text().await.unwrap_or_default();
        return Err(CliError::CairnStatus { url, status, body });
    }
    let bytes = resp.bytes().await.map_err(|source| CliError::Http {
        url: url.clone(),
        source,
    })?;
    serde_json::from_slice::<AuditListResponse>(&bytes)
        .map_err(|source| CliError::MalformedResponse { url, source })
}

/// Tabular human output for `cairn audit list`. Columns: id,
/// created_at, action, actor_did (truncated), outcome. Trailing
/// `next cursor: …` line when a next page exists. Reason
/// payloads are not included in the table — they're often
/// multi-line JSON; use `--json` for full inspection.
pub fn format_list_human(resp: &AuditListResponse) -> String {
    use std::fmt::Write;
    if resp.entries.is_empty() {
        let mut s = "(no audit entries)".to_string();
        if let Some(c) = &resp.cursor {
            let _ = write!(s, "\nnext cursor: {c}");
        }
        return s;
    }
    let id_w = resp
        .entries
        .iter()
        .map(|e| e.id.to_string().len())
        .max()
        .unwrap_or(2)
        .max(2);
    let action_w = resp
        .entries
        .iter()
        .map(|e| e.action.len().min(28))
        .max()
        .unwrap_or(6)
        .max(6);
    let actor_w = resp
        .entries
        .iter()
        .map(|e| e.actor_did.len().min(40))
        .max()
        .unwrap_or(8)
        .max(8);
    let mut s = String::new();
    let _ = writeln!(
        s,
        "{:>id_w$}  {:<24}  {:<action_w$}  {:<actor_w$}  {:<7}",
        "ID",
        "CREATED_AT",
        "ACTION",
        "ACTOR_DID",
        "OUTCOME",
        id_w = id_w,
        action_w = action_w,
        actor_w = actor_w,
    );
    for e in &resp.entries {
        let action = truncate(&e.action, 28);
        let actor = truncate(&e.actor_did, 40);
        let _ = writeln!(
            s,
            "{:>id_w$}  {:<24}  {:<action_w$}  {:<actor_w$}  {:<7}",
            e.id,
            e.created_at,
            action,
            actor,
            e.outcome,
            id_w = id_w,
            action_w = action_w,
            actor_w = actor_w,
        );
    }
    if let Some(c) = &resp.cursor {
        let _ = write!(s, "next cursor: {c}");
    } else if s.ends_with('\n') {
        s.pop();
    }
    s
}

/// JSON envelope for `cairn audit list`.
pub fn format_list_json(resp: &AuditListResponse) -> String {
    serde_json::to_string_pretty(resp).expect("AuditListResponse serializes")
}

// ============================================================
// `cairn audit show <id>` — wraps tools.cairn.admin.getAuditLog
// (src/server/admin/get_audit_log.rs). Admin role required.
// Returns the bare auditEntry shape (no envelope).
// ============================================================

/// Input to `cairn audit show`.
#[derive(Debug, Clone)]
pub struct AuditShowInput {
    /// Audit row primary key to fetch.
    pub id: i64,
    /// Per-invocation override of the session's stored Cairn URL.
    pub cairn_server_override: Option<String>,
}

/// Fetch a single audit log entry by id via the admin HTTP endpoint.
///
/// Wraps the `tools.cairn.admin.getAuditLog` handler at
/// [src/server/admin/get_audit_log.rs](..) — GET with `id` query
/// param; server enforces ADMIN role
/// (`verify_and_authorize_admin_only`) and returns
/// `AuditEntryNotFound` 404 on unknown id, surfaced here as
/// `CliError::CairnStatus { status: 404, body: ... }` with the
/// server's typed error name in the body.
pub async fn show(
    session: &mut SessionFile,
    session_path: &Path,
    input: AuditShowInput,
) -> Result<AuditEntry, CliError> {
    let cairn_server = input
        .cairn_server_override
        .as_deref()
        .unwrap_or(&session.cairn_server_url)
        .trim_end_matches('/')
        .to_string();
    let pds = PdsClient::new(&session.pds_url)?;
    let token = acquire_service_auth(&pds, session, session_path, GET_AUDIT_LOG_LXM).await?;

    let url = format!("{cairn_server}/xrpc/{GET_AUDIT_LOG_LXM}");
    let id_str = input.id.to_string();
    let client = Client::builder()
        .timeout(Duration::from_secs(30))
        .build()
        .expect("reqwest build");
    let resp = client
        .get(&url)
        .bearer_auth(&token)
        .query(&[("id", id_str.as_str())])
        .send()
        .await
        .map_err(|source| CliError::Http {
            url: url.clone(),
            source,
        })?;
    if !resp.status().is_success() {
        let status = resp.status().as_u16();
        let body = resp.text().await.unwrap_or_default();
        return Err(CliError::CairnStatus { url, status, body });
    }
    let bytes = resp.bytes().await.map_err(|source| CliError::Http {
        url: url.clone(),
        source,
    })?;
    serde_json::from_slice::<AuditEntry>(&bytes)
        .map_err(|source| CliError::MalformedResponse { url, source })
}

/// Multi-line field/value output for `cairn audit show`. Includes
/// every field present on the entry; omits absent optionals (target,
/// targetCid, reason). `reason` is rendered as-is — when it's
/// structured JSON, use `--json` to pipe through `jq`.
pub fn format_show_human(entry: &AuditEntry) -> String {
    use std::fmt::Write;
    let mut s = String::new();
    let _ = writeln!(s, "Audit entry {}", entry.id);
    let _ = writeln!(s, "  created_at:  {}", entry.created_at);
    let _ = writeln!(s, "  action:      {}", entry.action);
    let _ = writeln!(s, "  actor_did:   {}", entry.actor_did);
    let _ = writeln!(s, "  outcome:     {}", entry.outcome);
    if let Some(t) = &entry.target {
        let _ = writeln!(s, "  target:      {t}");
    }
    if let Some(c) = &entry.target_cid {
        let _ = writeln!(s, "  target_cid:  {c}");
    }
    if let Some(r) = &entry.reason {
        let _ = writeln!(s, "  reason:      {r}");
    }
    if s.ends_with('\n') {
        s.pop();
    }
    s
}

/// JSON output for `cairn audit show`. Pretty-printed for shell
/// readability; `jq` consumers see the canonical wire shape.
pub fn format_show_json(entry: &AuditEntry) -> String {
    serde_json::to_string_pretty(entry).expect("AuditEntry serializes")
}

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

    fn sample(reason: Option<&str>) -> AuditEntry {
        AuditEntry {
            id: 42,
            created_at: "2026-04-23T00:00:00.000Z".into(),
            action: "label_applied".into(),
            actor_did: "did:plc:moderator0000000000000000".into(),
            target: Some("at://did:plc:target/col/rec".into()),
            target_cid: Some("bafytest".into()),
            outcome: "success".into(),
            reason: reason.map(str::to_string),
        }
    }

    #[test]
    fn format_show_human_includes_all_present_fields() {
        let s = format_show_human(&sample(Some(r#"{"val":"spam"}"#)));
        assert!(s.contains("Audit entry 42"));
        assert!(s.contains("created_at:  2026-04-23T00:00:00.000Z"));
        assert!(s.contains("action:      label_applied"));
        assert!(s.contains("actor_did:   did:plc:moderator0000000000000000"));
        assert!(s.contains("outcome:     success"));
        assert!(s.contains("target:      at://did:plc:target/col/rec"));
        assert!(s.contains("target_cid:  bafytest"));
        assert!(s.contains(r#"reason:      {"val":"spam"}"#));
    }

    #[test]
    fn format_show_human_omits_absent_optionals() {
        let mut e = sample(None);
        e.target = None;
        e.target_cid = None;
        let s = format_show_human(&e);
        assert!(!s.contains("target:"));
        assert!(!s.contains("target_cid:"));
        assert!(!s.contains("reason:"));
    }

    #[test]
    fn format_show_json_round_trips() {
        let e = sample(Some(r#"{"val":"spam","neg":false}"#));
        let json = format_show_json(&e);
        let parsed: AuditEntry = serde_json::from_str(&json).expect("round trip");
        assert_eq!(parsed.id, 42);
        assert_eq!(parsed.action, "label_applied");
        assert_eq!(
            parsed.target.as_deref(),
            Some("at://did:plc:target/col/rec")
        );
        assert_eq!(
            parsed.reason.as_deref(),
            Some(r#"{"val":"spam","neg":false}"#)
        );
    }
}