dsc-rs 0.10.21

Discourse CLI tool for managing multiple Discourse forums: track installs, run upgrades over SSH, manage emojis, sync topics and categories as Markdown, and more.
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
use crate::api::{DiscourseClient, PmTopicSummary, TopicResponse, UserAction};
use crate::commands::common::{ensure_api_credentials, not_found, select_discourse};
use crate::config::Config;
use crate::utils::{current_utc_iso8601, ensure_dir, normalize_baseurl, slugify, write_markdown};
use anyhow::{Context, Result};
use serde_json::{Value, json};
use std::collections::HashSet;
use std::path::Path;

/// The person a SAR bundle is about, resolved from a username or email.
struct Subject {
    user_id: i64,
    username: String,
    email: Option<String>,
}

/// Item counts for the manifest and the closing summary.
struct SectionCounts {
    posts: usize,
    likes: usize,
    groups: usize,
    messages: usize,
}

/// Discourse user-action type ids we care about for a SAR.
const ACTION_NEW_TOPIC: u32 = 4;
const ACTION_REPLY: u32 = 5;
const ACTION_LIKE: u32 = 1;

/// Produce a one-shot Subject Access Request bundle for `user` on one forum.
/// Collects the admin PII view, authored posts (full raw), likes, and group
/// memberships into a reviewable directory; private messages are included only
/// when `include_messages` is set (they carry third-party data). See
/// spec/subject-access-request.md - this automates the data-gathering, not the
/// controller's legal judgement.
pub fn sar(
    config: &Config,
    discourse_name: &str,
    user: &str,
    output: Option<&Path>,
    include_messages: bool,
    dry_run: bool,
) -> Result<()> {
    let discourse = select_discourse(config, Some(discourse_name))?;
    ensure_api_credentials(discourse)?;
    let client = DiscourseClient::new(discourse)?;
    let base = normalize_baseurl(&discourse.baseurl);

    let subject = resolve_subject(&client, user)?;
    let generated_at = current_utc_iso8601();
    let dir = match output {
        Some(p) => p.to_path_buf(),
        None => std::env::current_dir()?.join(format!(
            "sar-{}-{}",
            slugify(&subject.username),
            date_part(&generated_at)
        )),
    };

    if dry_run {
        println!(
            "[dry-run] would write SAR bundle for {} (user {}) on {} to {}",
            subject.username,
            subject.user_id,
            discourse.name,
            dir.display()
        );
        println!(
            "  sections: profile, posts, activity, groups{}",
            if include_messages { ", messages" } else { "" }
        );
        if !include_messages {
            println!("  (private messages excluded; pass --messages to include them)");
        }
        return Ok(());
    }

    ensure_dir(&dir)?;

    // Profile / PII (admin view) and the group memberships embedded in it.
    let admin_detail = client.fetch_admin_user_detail(subject.user_id)?;
    let profile = admin_detail
        .get("user")
        .cloned()
        .unwrap_or_else(|| admin_detail.clone());
    write_json(&dir.join("profile.json"), &profile)?;
    let groups = profile.get("groups").cloned().unwrap_or_else(|| json!([]));
    write_json(&dir.join("groups.json"), &groups)?;

    // Authored posts, with full raw content fetched per post.
    let post_actions = collect_all_actions(
        &client,
        &subject.username,
        &[ACTION_NEW_TOPIC, ACTION_REPLY],
    )?;
    let posts_dir = dir.join("posts");
    ensure_dir(&posts_dir)?;
    let mut posts_json: Vec<Value> = Vec::with_capacity(post_actions.len());
    for action in &post_actions {
        let raw = action
            .post_id
            .and_then(|pid| client.fetch_post_raw(pid).ok().flatten());
        if let (Some(pid), Some(body)) = (action.post_id, raw.as_deref()) {
            let stem = action
                .slug
                .as_deref()
                .map(slugify)
                .unwrap_or_else(|| "topic".to_string());
            let md = render_post_md(action, body, &base);
            write_markdown(&posts_dir.join(format!("{}-{}.md", stem, pid)), &md)?;
        }
        posts_json.push(json!({
            "post_id": action.post_id,
            "topic_id": action.topic_id,
            "title": action.title,
            "url": post_url(&base, action),
            "created_at": action.created_at,
            "raw": raw,
        }));
    }
    write_json(&dir.join("posts.json"), &Value::Array(posts_json))?;

    // Likes given.
    let likes = collect_all_actions(&client, &subject.username, &[ACTION_LIKE])?;
    let likes_json: Vec<Value> = likes.iter().map(action_to_json).collect();
    write_json(
        &dir.join("activity.json"),
        &json!({ "likes_given": likes_json }),
    )?;

    // Private messages (opt-in; third-party data).
    let message_count = if include_messages {
        collect_messages(&client, &subject.username, &dir)?
    } else {
        0
    };

    let counts = SectionCounts {
        posts: post_actions.len(),
        likes: likes.len(),
        groups: groups.as_array().map(|a| a.len()).unwrap_or(0),
        messages: message_count,
    };
    let has_ip =
        profile.get("ip_address").is_some() || profile.get("registration_ip_address").is_some();
    let manifest = build_manifest(
        &subject,
        &discourse.name,
        &generated_at,
        &counts,
        include_messages,
        has_ip,
    );
    write_json(&dir.join("manifest.json"), &manifest)?;
    write_markdown(
        &dir.join("README.md"),
        &render_readme(&subject, &discourse.name, &generated_at, include_messages),
    )?;

    println!("SAR bundle written to {}", dir.display());
    println!(
        "  {} posts, {} likes, {} group(s){}",
        counts.posts,
        counts.likes,
        counts.groups,
        if include_messages {
            format!(", {} message thread(s)", counts.messages)
        } else {
            String::new()
        }
    );
    println!(
        "This bundle contains personal data. Review it (see README.md), transmit \
         it securely, and delete it once the request is fulfilled."
    );
    Ok(())
}

fn resolve_subject(client: &DiscourseClient, user: &str) -> Result<Subject> {
    if user.contains('@') {
        let matches = client.admin_search_users(user)?;
        let found = matches
            .into_iter()
            .find(|u| {
                u.email
                    .as_deref()
                    .map(|e| e.eq_ignore_ascii_case(user))
                    .unwrap_or(false)
            })
            .ok_or_else(|| not_found("user with email", user))?;
        Ok(Subject {
            user_id: found.id,
            username: found.username,
            email: found.email,
        })
    } else {
        let detail = client.fetch_user_detail(user)?;
        Ok(Subject {
            user_id: detail.id,
            username: detail.username,
            email: detail.email,
        })
    }
}

/// Page through `fetch_user_actions` until a short/empty page is returned.
/// Capped so a misbehaving endpoint cannot loop forever.
fn collect_all_actions(
    client: &DiscourseClient,
    username: &str,
    filters: &[u32],
) -> Result<Vec<UserAction>> {
    const PAGE_HINT: usize = 10; // Discourse returns ~10 per page.
    const MAX_ITEMS: usize = 100_000;
    let mut all = Vec::new();
    let mut offset = 0u32;
    loop {
        let page = client.fetch_user_actions(username, filters, offset)?;
        let n = page.len();
        if n == 0 {
            break;
        }
        all.extend(page);
        offset += n as u32;
        if n < PAGE_HINT || all.len() >= MAX_ITEMS {
            break;
        }
    }
    Ok(all)
}

fn collect_messages(client: &DiscourseClient, username: &str, dir: &Path) -> Result<usize> {
    let msg_dir = dir.join("messages");
    ensure_dir(&msg_dir)?;
    let mut threads = client.list_private_messages(username, "inbox")?;
    threads.extend(client.list_private_messages(username, "sent")?);

    let mut seen = HashSet::new();
    let mut count = 0;
    for pm in threads {
        if !seen.insert(pm.id) {
            continue;
        }
        let topic = client.fetch_topic(pm.id, true)?;
        let stem = pm
            .slug
            .as_deref()
            .map(slugify)
            .unwrap_or_else(|| "message".to_string());
        write_markdown(
            &msg_dir.join(format!("{}-{}.md", stem, pm.id)),
            &render_pm_md(&pm, &topic),
        )?;
        count += 1;
    }
    Ok(count)
}

fn write_json(path: &Path, value: &Value) -> Result<()> {
    if let Some(parent) = path.parent() {
        ensure_dir(parent)?;
    }
    let text = serde_json::to_string_pretty(value)?;
    std::fs::write(path, text).with_context(|| format!("writing {}", path.display()))?;
    Ok(())
}

fn date_part(iso: &str) -> String {
    iso.split('T').next().unwrap_or(iso).to_string()
}

fn post_url(base: &str, action: &UserAction) -> String {
    let slug = action.slug.as_deref().unwrap_or("topic");
    match action.post_number {
        Some(n) if n > 1 => format!("{}/t/{}/{}/{}", base, slug, action.topic_id, n),
        _ => format!("{}/t/{}/{}", base, slug, action.topic_id),
    }
}

fn action_to_json(action: &UserAction) -> Value {
    json!({
        "topic_id": action.topic_id,
        "post_id": action.post_id,
        "title": action.title,
        "created_at": action.created_at,
        "excerpt": action.excerpt,
    })
}

fn render_post_md(action: &UserAction, raw: &str, base: &str) -> String {
    format!(
        "# {}\n\n- URL: {}\n- Posted: {}\n\n---\n\n{}\n",
        action.title.as_deref().unwrap_or("(untitled)"),
        post_url(base, action),
        action.created_at,
        raw.trim_end()
    )
}

fn render_pm_md(pm: &PmTopicSummary, topic: &TopicResponse) -> String {
    let mut out = String::new();
    out.push_str(
        "> REVIEW REQUIRED: this private-message thread contains other people's \
         personal data. Review for third-party information and redact before \
         disclosure.\n\n",
    );
    out.push_str(&format!(
        "# {}\n\n",
        pm.title.as_deref().unwrap_or("(no subject)")
    ));
    for post in &topic.post_stream.posts {
        let who = post.username.as_deref().unwrap_or("(unknown)");
        let when = post.created_at.as_deref().unwrap_or("(no date)");
        let body = post.raw.as_deref().unwrap_or("").trim_end();
        out.push_str(&format!("## {} · {}\n\n{}\n\n---\n\n", who, when, body));
    }
    out
}

fn build_manifest(
    subject: &Subject,
    forum: &str,
    generated_at: &str,
    counts: &SectionCounts,
    include_messages: bool,
    has_ip: bool,
) -> Value {
    let mut review_required: Vec<String> = Vec::new();
    if has_ip {
        review_required
            .push("profile.json includes IP addresses; confirm these should be released".into());
    }
    if include_messages {
        review_required.push(
            "messages/ contains third-party personal data; review and redact before disclosure"
                .into(),
        );
    }
    json!({
        "subject": {
            "username": subject.username,
            "user_id": subject.user_id,
            "email": subject.email,
        },
        "forum": forum,
        "generated_at": generated_at,
        "messages_included": include_messages,
        "sections": {
            "posts": counts.posts,
            "likes_given": counts.likes,
            "groups": counts.groups,
            "messages": counts.messages,
        },
        "review_required": review_required,
    })
}

/// The human-facing cover sheet. Explains what the bundle is, lists the
/// controller's remaining steps, and scaffolds the Article 15 supplementary
/// information for them to complete.
fn render_readme(
    subject: &Subject,
    forum: &str,
    generated_at: &str,
    include_messages: bool,
) -> String {
    let email = subject.email.as_deref().unwrap_or("(not recorded)");
    let messages_line = if include_messages {
        "- `messages/` - private messages (**contains third-party data - review and redact**)\n"
    } else {
        "- (private messages were NOT collected; re-run with `--messages` if the request requires them)\n"
    };
    let messages_checklist = if include_messages {
        "- [ ] Review `messages/` for third-party personal data and redact.\n"
    } else {
        ""
    };
    format!(
        "# Subject Access Request - {username}\n\
\n\
Personal data held about **{username}** ({email}) on the **{forum}** Discourse \
forum, generated by `dsc sar` at {generated_at}.\n\
\n\
This package was assembled automatically from the Discourse admin API. It is a \
**data-gathering aid, not a finished SAR response** - the steps below are the \
data controller's responsibility and have not been done for you.\n\
\n\
## What's included\n\
\n\
- `profile.json` - account and profile data (PII), including IP addresses and emails.\n\
- `posts/` and `posts.json` - every post the subject authored, full text.\n\
- `activity.json` - likes the subject gave.\n\
- `groups.json` - group memberships.\n\
{messages_line}\
- `manifest.json` - machine-readable index, counts, and items flagged for review.\n\
\n\
## Controller checklist (before sending)\n\
\n\
- [ ] Verify the requester is the data subject (or is properly authorised).\n\
- [ ] Confirm IP addresses and technical data in `profile.json` should be released.\n\
{messages_checklist}\
- [ ] Complete the Article 15 supplementary information below.\n\
- [ ] Apply any exemptions (others' rights, legal privilege, etc.).\n\
- [ ] Send via a secure channel within **one calendar month** of the request.\n\
\n\
## Article 15 supplementary information (to complete)\n\
\n\
Under UK/EU GDPR Article 15 the response must also state, in addition to the \
data itself, the following - none of which lives in Discourse, so fill them in \
from your processing records:\n\
\n\
- **Purposes of processing:** [controller to complete]\n\
- **Categories of personal data:** account profile, posts, activity{messages_cat}.\n\
- **Recipients / categories of recipient:** [controller to complete]\n\
- **Retention period (or the criteria for it):** [controller to complete]\n\
- **Source of the data** (if not collected from the subject): [controller to complete]\n\
- **Existence of automated decision-making / profiling:** [controller to complete]\n\
- **The subject's rights** (rectification, erasure, restriction, objection, complaint to the supervisory authority): [controller to complete]\n\
\n\
---\n\
\n\
This bundle is personal data. Store and transmit it securely, and delete it \
once the request has been fulfilled.\n",
        username = subject.username,
        email = email,
        forum = forum,
        generated_at = generated_at,
        messages_line = messages_line,
        messages_checklist = messages_checklist,
        messages_cat = if include_messages {
            ", private messages"
        } else {
            ""
        },
    )
}

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

    fn subject() -> Subject {
        Subject {
            user_id: 412,
            username: "jane-doe".to_string(),
            email: Some("jane@example.com".to_string()),
        }
    }

    #[test]
    fn date_part_takes_the_date() {
        assert_eq!(date_part("2026-06-23T09:00:00Z"), "2026-06-23");
        assert_eq!(date_part("2026-06-23"), "2026-06-23");
    }

    #[test]
    fn manifest_flags_ip_and_messages_when_present() {
        let counts = SectionCounts {
            posts: 84,
            likes: 12,
            groups: 3,
            messages: 7,
        };
        let m = build_manifest(
            &subject(),
            "rcpch",
            "2026-06-23T09:00:00Z",
            &counts,
            true,
            true,
        );
        assert_eq!(m["subject"]["user_id"], 412);
        assert_eq!(m["sections"]["posts"], 84);
        assert_eq!(m["messages_included"], true);
        let review = m["review_required"].as_array().unwrap();
        assert_eq!(review.len(), 2, "expected IP + messages flags");
    }

    #[test]
    fn manifest_has_no_review_flags_when_clean() {
        let counts = SectionCounts {
            posts: 1,
            likes: 0,
            groups: 0,
            messages: 0,
        };
        let m = build_manifest(&subject(), "rcpch", "t", &counts, false, false);
        assert!(m["review_required"].as_array().unwrap().is_empty());
        assert_eq!(m["messages_included"], false);
    }

    #[test]
    fn readme_includes_checklist_and_article_15() {
        let out = render_readme(&subject(), "rcpch", "2026-06-23T09:00:00Z", false);
        assert!(out.contains("Subject Access Request - jane-doe"));
        assert!(out.contains("Verify the requester is the data subject"));
        assert!(out.contains("Article 15 supplementary information"));
        assert!(out.contains("one calendar month"));
        // Messages excluded -> note the opt-in, no message-review checklist line.
        assert!(out.contains("--messages"));
        assert!(!out.contains("Review `messages/`"));
    }

    #[test]
    fn readme_adds_message_review_when_included() {
        let out = render_readme(&subject(), "rcpch", "t", true);
        assert!(out.contains("Review `messages/`"));
        assert!(out.contains("third-party data"));
    }

    #[test]
    fn post_url_includes_post_number_after_first() {
        let action = UserAction {
            action_type: 5,
            created_at: "2026-01-01".into(),
            title: Some("Hi".into()),
            slug: Some("hi-there".into()),
            topic_id: 50,
            post_id: Some(99),
            post_number: Some(3),
            username: Some("jane-doe".into()),
            excerpt: None,
        };
        assert_eq!(
            post_url("https://forum.example.com", &action),
            "https://forum.example.com/t/hi-there/50/3"
        );
    }
}