ostrya_server/event.rs
1//! The events that a server reports to its host.
2
3use std::collections::HashSet;
4use std::fmt;
5use std::sync::{Arc, Mutex, PoisonError};
6
7use ostrya::Checksum;
8use ostrya::access::AuthItem;
9
10/// The callback that receives each [`ServerEvent`].
11pub(crate) type EventSink = Arc<dyn Fn(&ServerEvent) + Send + Sync>;
12
13/// An event of a server, which
14/// [`ServeOptions::on_event`](crate::ServeOptions::on_event) receives.
15///
16/// [`Display`](fmt::Display) writes one line for the log of the host. It
17/// writes each control character of a text from the client as an escape
18/// sequence, for example `\n`, so the line holds no line break.
19#[derive(Debug, Clone, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum ServerEvent {
22 /// The server refused a request because the claims of its client
23 /// certificate do not parse.
24 ///
25 /// For a `session` request, the selected client group has
26 /// `tls-accept-claim=true`. For a read, a group with
27 /// `tls-accept-claim=true` carries the item of the certificate. The
28 /// request got 403.
29 #[non_exhaustive]
30 BadClaims {
31 /// The SHA-256 digest of the DER bytes of the certificate, as a
32 /// `tls-sha256:HEX` item names it.
33 digest: Checksum,
34 /// The URI SAN that is no claim, or `None` when no one URI is at
35 /// fault, for example when the certificate holds too many claims.
36 san: Option<String>,
37 /// Why the claims do not parse.
38 reason: String,
39 },
40 /// A ref listing left out a directory under `refs/mirrors/` whose name
41 /// fails the collection-id rule
42 /// ([`ostrya::is_collection_id`]).
43 ///
44 /// The server reports each name one time for each [`Server`](crate::Server)
45 /// value, at the first listing that finds it. Only a listing whose query
46 /// holds a `collection` pair reads the directories under
47 /// `refs/mirrors/`. The listing itself goes on. The server reports the
48 /// event also with no receive policies.
49 #[non_exhaustive]
50 InvalidCollectionDir {
51 /// The name of the directory.
52 name: String,
53 },
54 /// The server answered `summary` or `summary.sig` with 404, because the
55 /// `.access` file of the auth item of the client does not hold the
56 /// access digest of the item
57 /// ([`ArchiveAnswer::StaleSummary`](ostrya::ArchiveAnswer::StaleSummary)).
58 ///
59 /// The summary of the item does not match the client groups that the
60 /// server read at start. `ostrya summary -u` writes the summaries again.
61 /// The server reports each item one time for each
62 /// [`Server`](crate::Server) value, at the first request that finds it.
63 #[non_exhaustive]
64 StaleSummary {
65 /// The text of the auth item.
66 item: String,
67 },
68 /// The server answered a request with 500, because the read of the
69 /// answer failed, for example with `EACCES` on an object.
70 ///
71 /// The server reports the event one time for each such request: a `GET`
72 /// or a `HEAD` of the archive view, and a ref listing. A body that fails
73 /// after the server sent the status 200 gives no event.
74 #[non_exhaustive]
75 ReadFailed {
76 /// The method of the request.
77 method: String,
78 /// The path of the request as the client sent it, with no query.
79 path: String,
80 /// The text of the error of the read.
81 error: String,
82 },
83}
84
85impl ServerEvent {
86 /// Returns `true` if the event is a warning: the server served the
87 /// request. Each other event is an error of a request that the server
88 /// refused.
89 ///
90 /// [`InvalidCollectionDir`](ServerEvent::InvalidCollectionDir) is a
91 /// warning. [`BadClaims`](ServerEvent::BadClaims),
92 /// [`StaleSummary`](ServerEvent::StaleSummary), and
93 /// [`ReadFailed`](ServerEvent::ReadFailed) are errors.
94 pub fn is_warning(&self) -> bool {
95 match self {
96 ServerEvent::BadClaims { .. }
97 | ServerEvent::StaleSummary { .. }
98 | ServerEvent::ReadFailed { .. } => false,
99 ServerEvent::InvalidCollectionDir { .. } => true,
100 }
101 }
102}
103
104impl fmt::Display for ServerEvent {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 match self {
107 ServerEvent::BadClaims {
108 digest,
109 san,
110 reason,
111 } => {
112 write!(f, "refused the client certificate tls-sha256:{digest}: ")?;
113 if let Some(san) = san {
114 write!(f, "malformed claim '{}': ", Escaped(san))?;
115 }
116 write!(f, "{}", Escaped(reason))
117 }
118 ServerEvent::InvalidCollectionDir { name } => write!(
119 f,
120 "refs/mirrors/{}: the directory name is not a collection id, and the ref \
121 listing leaves out the directory",
122 Escaped(name)
123 ),
124 ServerEvent::StaleSummary { item } => write!(
125 f,
126 "the summary of the auth item {} does not match the client groups, and the \
127 server answers 404 for it; run `ostrya summary -u`",
128 Escaped(item)
129 ),
130 ServerEvent::ReadFailed {
131 method,
132 path,
133 error,
134 } => write!(
135 f,
136 "{} {}: the read failed, and the server answers 500: {}",
137 Escaped(method),
138 Escaped(path),
139 Escaped(error)
140 ),
141 }
142 }
143}
144
145/// Reports a [`ServerEvent::ReadFailed`] for a request of `method` and
146/// `path` whose read failed with `error`, if the server has the callback
147/// `on_event`.
148pub(crate) fn report_read_failed(
149 on_event: Option<&EventSink>,
150 method: &str,
151 path: &str,
152 error: &ostrya::Error,
153) {
154 if let Some(on_event) = on_event {
155 on_event(&ServerEvent::ReadFailed {
156 method: method.to_owned(),
157 path: path.to_owned(),
158 error: error.to_string(),
159 });
160 }
161}
162
163/// The stale summaries that one server reported.
164pub(crate) struct StaleSummaries {
165 /// The text of each item that the server reported.
166 reported: Mutex<HashSet<String>>,
167 /// The callback of the events of the server.
168 on_event: Option<EventSink>,
169}
170
171impl StaleSummaries {
172 /// Returns the record of a server that reported no stale summary, which
173 /// reports its events to `on_event`.
174 pub(crate) fn new(on_event: Option<EventSink>) -> StaleSummaries {
175 StaleSummaries {
176 reported: Mutex::new(HashSet::new()),
177 on_event,
178 }
179 }
180
181 /// Returns the callback of the events of the server, or `None`.
182 pub(crate) fn on_event(&self) -> Option<&EventSink> {
183 self.on_event.as_ref()
184 }
185
186 /// Reports `item` as a [`ServerEvent::StaleSummary`] if the server did
187 /// not report it before.
188 pub(crate) fn report(&self, item: &AuthItem) {
189 let Some(on_event) = &self.on_event else {
190 return;
191 };
192 let item = item.to_string();
193 let new = self
194 .reported
195 .lock()
196 .unwrap_or_else(PoisonError::into_inner)
197 .insert(item.clone());
198 if new {
199 on_event(&ServerEvent::StaleSummary { item });
200 }
201 }
202}
203
204/// A text with each ASCII control character as its escape sequence.
205pub(crate) struct Escaped<'a>(pub(crate) &'a str);
206
207impl fmt::Display for Escaped<'_> {
208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209 for c in self.0.chars() {
210 if c.is_ascii_control() {
211 write!(f, "{}", c.escape_default())?;
212 } else {
213 write!(f, "{c}")?;
214 }
215 }
216 Ok(())
217 }
218}
219
220#[cfg(test)]
221mod tests {
222 use super::*;
223
224 /// The line names the digest, the URI SAN, and the reason, and escapes
225 /// each control character.
226 #[test]
227 fn the_line_names_the_digest_and_the_san() {
228 let digest = Checksum::sha256(b"cert");
229 let event = ServerEvent::BadClaims {
230 digest,
231 san: Some("ostrya:ref:x:a\nforged line\t\u{7f}".to_owned()),
232 reason: "the modes are one or more of r, w, c, t, and d".to_owned(),
233 };
234 assert_eq!(
235 event.to_string(),
236 format!(
237 "refused the client certificate tls-sha256:{}: malformed claim \
238 'ostrya:ref:x:a\\nforged line\\t\\u{{7f}}': the modes are one or more of r, w, \
239 c, t, and d",
240 digest.to_hex()
241 )
242 );
243 let event = ServerEvent::BadClaims {
244 digest,
245 san: None,
246 reason: "the certificate holds more than 256 claims\r".to_owned(),
247 };
248 assert_eq!(
249 event.to_string(),
250 format!(
251 "refused the client certificate tls-sha256:{}: the certificate holds more \
252 than 256 claims\\r",
253 digest.to_hex()
254 )
255 );
256 assert!(!event.is_warning());
257 }
258
259 /// The line of an invalid collection directory names its path and
260 /// escapes each control character. The event is a warning.
261 #[test]
262 fn the_line_of_an_invalid_collection_dir_escapes_its_name() {
263 let event = ServerEvent::InvalidCollectionDir {
264 name: "bad\nforged line\t\u{7f}".to_owned(),
265 };
266 assert_eq!(
267 event.to_string(),
268 "refs/mirrors/bad\\nforged line\\t\\u{7f}: the directory name is not a \
269 collection id, and the ref listing leaves out the directory"
270 );
271 assert!(event.is_warning());
272 }
273
274 /// The line of a stale summary names the item, escapes each control
275 /// character, and names the command that writes the summaries. The event
276 /// is an error.
277 #[test]
278 fn the_line_of_a_stale_summary_names_the_item() {
279 let event = ServerEvent::StaleSummary {
280 item: "tls:a\nb".to_owned(),
281 };
282 assert_eq!(
283 event.to_string(),
284 "the summary of the auth item tls:a\\nb does not match the client groups, and \
285 the server answers 404 for it; run `ostrya summary -u`"
286 );
287 assert!(!event.is_warning());
288 }
289
290 /// The line of a failed read names the method, the path, and the error,
291 /// and escapes each control character. The event is an error.
292 #[test]
293 fn the_line_of_a_failed_read_escapes_the_path() {
294 let event = ServerEvent::ReadFailed {
295 method: "GET".to_owned(),
296 path: "/objects/ab/c\nforged line.filez".to_owned(),
297 error: "i/o error: Permission denied (os error 13)".to_owned(),
298 };
299 assert_eq!(
300 event.to_string(),
301 "GET /objects/ab/c\\nforged line.filez: the read failed, and the server answers \
302 500: i/o error: Permission denied (os error 13)"
303 );
304 assert!(!event.is_warning());
305 }
306
307 /// The record reports each item one time.
308 #[test]
309 fn a_stale_summary_is_reported_one_time_for_each_item() {
310 let seen = Arc::new(Mutex::new(Vec::new()));
311 let sink = seen.clone();
312 let stale = StaleSummaries::new(Some(Arc::new(move |event: &ServerEvent| {
313 sink.lock().unwrap().push(event.to_string());
314 })));
315 let ssh = AuthItem::parse("ssh:u").unwrap();
316 for item in [&AuthItem::Anonymous, &ssh, &AuthItem::Anonymous, &ssh] {
317 stale.report(item);
318 }
319 let seen = seen.lock().unwrap();
320 assert_eq!(seen.len(), 2, "{seen:?}");
321 assert!(seen[0].contains(" anonymous "), "{}", seen[0]);
322 assert!(seen[1].contains(" ssh:u "), "{}", seen[1]);
323 }
324}