forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

audit.rs211 lines, 7.6 KiBHistoryRawDownload
1//! `/admin/audit`: the audit log, newest first, with filters and keyset paging.
2//!
3//! The filters are an action, an actor id, a target id, and a day range. The cursor of the next page is the
4//! position of the last entry (`at|id`), so entries written while an administrator pages do not shift the
5//! pages. The day range is read in UTC: `from` is the first nanosecond of its day, and `to` is the last
6//! nanosecond of its day, so both days are included in full.
7
8use im_core::model::AuditEntry;
9use im_core::store::audit::{AuditCursor, AuditFilter};
10use serde::Deserialize;
11use topcoat::Result;
12use topcoat::context::{Cx, app_context};
13use topcoat::router::content::Form;
14use topcoat::router::page;
15use topcoat::view::{View, component, view};
16
17use crate::auth::require_admin;
18use crate::i18n::Lang;
19use crate::i18n::admin::{A, text};
20use crate::pages::admin::{PAGE_SIZE, Tab, frame_info, tabs};
21use crate::state::AppState;
22use crate::views::{ViewerInfo, shell};
23
24/// The query: the four filters, and the cursor of the page.
25#[derive(Deserialize, Default)]
26struct AuditQuery {
27 #[serde(default)]
28 action: String,
29 #[serde(default)]
30 actor: String,
31 #[serde(default)]
32 target: String,
33 /// A day, `YYYY-MM-DD`.
34 #[serde(default)]
35 from: String,
36 /// A day, `YYYY-MM-DD`, included.
37 #[serde(default)]
38 to: String,
39 /// `at|id` of the last entry of the previous page.
40 #[serde(default)]
41 after: String,
42}
43
44/// `GET /admin/audit`.
45#[page("/admin/audit")]
46async fn audit_page(cx: &Cx, Form(query): Form<AuditQuery>) -> Result<impl View> {
47 let viewer = require_admin(cx).await?;
48 let state = app_context::<AppState>(cx);
49 let (lang, info) = frame_info(cx, &viewer);
50 let filter = AuditFilter {
51 action: non_empty(&query.action),
52 actor_id: non_empty(&query.actor),
53 target_id: non_empty(&query.target),
54 from: day_stamp(&query.from, false),
55 to: day_stamp(&query.to, true),
56 };
57 let cursor = cursor_of(&query.after);
58 let (entries, next) = state
59 .store
60 .list_audit(&filter, cursor.as_ref(), PAGE_SIZE)
61 .await?;
62 let base = filter_query(&query);
63 let next_href = next.map(|next| {
64 format!(
65 "/admin/audit?{base}&after={}",
66 encode(&format!("{}|{}", next.at, next.id))
67 )
68 });
69 Ok(audit_view(cx, lang, info, base, query, entries, next_href))
70}
71
72/// Trimmed text, or `None` when it is empty.
73fn non_empty(text: &str) -> Option<String> {
74 let text = text.trim();
75 (!text.is_empty()).then(|| text.to_owned())
76}
77
78/// The stamp of the first (or, with `end`, the last) nanosecond of a `YYYY-MM-DD` day. A day that is not
79/// well formed is ignored, so the filter is simply not applied.
80fn day_stamp(day: &str, end: bool) -> Option<String> {
81 let bytes = day.trim().as_bytes();
82 let well_formed = bytes.len() == 10
83 && bytes.iter().enumerate().all(|(index, byte)| match index {
84 4 | 7 => *byte == b'-',
85 _ => byte.is_ascii_digit(),
86 });
87 if !well_formed {
88 return None;
89 }
90 let day = day.trim();
91 Some(if end {
92 format!("{day}T23:59:59.999999999Z")
93 } else {
94 format!("{day}T00:00:00.000000000Z")
95 })
96}
97
98/// The cursor of the page, from `at|id`. A cursor that is not well formed starts the first page.
99fn cursor_of(after: &str) -> Option<AuditCursor> {
100 let (at, id) = after.split_once('|')?;
101 (!at.is_empty() && !id.is_empty()).then(|| AuditCursor {
102 at: at.to_owned(),
103 id: id.to_owned(),
104 })
105}
106
107/// The filters as a query string, without the cursor.
108fn filter_query(query: &AuditQuery) -> String {
109 format!(
110 "action={}&actor={}&target={}&from={}&to={}",
111 encode(&query.action),
112 encode(&query.actor),
113 encode(&query.target),
114 encode(&query.from),
115 encode(&query.to),
116 )
117}
118
119/// Percent-encodes everything but the unreserved characters, so a filter value cannot add a parameter.
120fn encode(value: &str) -> String {
121 let mut out = String::with_capacity(value.len());
122 for byte in value.bytes() {
123 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
124 out.push(char::from(byte));
125 } else {
126 out.push_str(&format!("%{byte:02X}"));
127 }
128 }
129 out
130}
131
132/// The audit page: the filters, the entries, and the links to the newest and the next page.
133fn audit_view(
134 cx: &Cx,
135 lang: Lang,
136 info: ViewerInfo,
137 base: String,
138 query: AuditQuery,
139 entries: Vec<AuditEntry>,
140 next_href: Option<String>,
141) -> impl View {
142 let newest = format!("/admin/audit?{base}");
143 view! { cx =>
144 shell(title: text(lang, A::AuditTitle), lang: lang, viewer: Some(info),
145 tabs(lang: lang, current: Tab::Audit)
146 <section class="stack">
147 <h1>(text(lang, A::AuditTitle))</h1>
148 <p class="muted">(text(lang, A::AuditIntro))</p>
149 <form method="get" action="/admin/audit" class="filters">
150 <label class="field"><span class="field-label">(text(lang, A::AuditAction))</span>
151 <input name="action" type="text" autocomplete="off" value=(query.action.clone())></label>
152 <label class="field"><span class="field-label">(text(lang, A::AuditActor))</span>
153 <input name="actor" type="text" autocomplete="off" value=(query.actor.clone())></label>
154 <label class="field"><span class="field-label">(text(lang, A::AuditTarget))</span>
155 <input name="target" type="text" autocomplete="off" value=(query.target.clone())></label>
156 <label class="field"><span class="field-label">(text(lang, A::AuditFrom))</span>
157 <input name="from" type="date" value=(query.from.clone())></label>
158 <label class="field"><span class="field-label">(text(lang, A::AuditTo))</span>
159 <input name="to" type="date" value=(query.to.clone())></label>
160 <button type="submit" class="button ghost">(text(lang, A::Apply))</button>
161 </form>
162 <p><a href=(newest)>(text(lang, A::AuditNewer))</a></p>
163 if entries.is_empty() {
164 <p class="muted">(text(lang, A::AuditNoEntries))</p>
165 } else {
166 <table class="audit">
167 <thead><tr>
168 <th>(text(lang, A::AuditWhen))</th>
169 <th>(text(lang, A::AuditWho))</th>
170 <th>(text(lang, A::AuditAction))</th>
171 <th>(text(lang, A::AuditTarget))</th>
172 <th>(text(lang, A::AuditIp))</th>
173 <th>(text(lang, A::AuditDetails))</th>
174 </tr></thead>
175 <tbody>
176 for entry in entries {
177 audit_row(entry: entry)
178 }
179 </tbody>
180 </table>
181 }
182 if let Some(href) = next_href {
183 <p><a class="button ghost" href=(href)>(text(lang, A::AuditOlder))</a></p>
184 }
185 </section>
186 )
187 }
188}
189
190/// One entry of the log. Its details are text from the store; the view escapes them.
191#[component]
192async fn audit_row(entry: AuditEntry) -> Result<impl View> {
193 let who = entry
194 .actor_id
195 .clone()
196 .unwrap_or_else(|| entry.actor_kind.clone());
197 let target = match (&entry.target_kind, &entry.target_id) {
198 (Some(kind), Some(id)) => format!("{kind}:{id}"),
199 _ => String::new(),
200 };
201 Ok(view! {
202 <tr>
203 <td>(entry.at.clone())</td>
204 <td>(who)</td>
205 <td><code>(entry.action.clone())</code></td>
206 <td>(target)</td>
207 <td>(entry.ip.clone().unwrap_or_default())</td>
208 <td><code>(entry.data.clone().unwrap_or_default())</code></td>
209 </tr>
210 })
211}