Skip to main content

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}
69
70impl ServerEvent {
71    /// Returns `true` if the event is a warning: the server served the
72    /// request. Each other event is an error of a request that the server
73    /// refused.
74    ///
75    /// [`InvalidCollectionDir`](ServerEvent::InvalidCollectionDir) is a
76    /// warning. [`BadClaims`](ServerEvent::BadClaims) and
77    /// [`StaleSummary`](ServerEvent::StaleSummary) are errors.
78    pub fn is_warning(&self) -> bool {
79        match self {
80            ServerEvent::BadClaims { .. } | ServerEvent::StaleSummary { .. } => false,
81            ServerEvent::InvalidCollectionDir { .. } => true,
82        }
83    }
84}
85
86impl fmt::Display for ServerEvent {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        match self {
89            ServerEvent::BadClaims {
90                digest,
91                san,
92                reason,
93            } => {
94                write!(f, "refused the client certificate tls-sha256:{digest}: ")?;
95                if let Some(san) = san {
96                    write!(f, "malformed claim '{}': ", Escaped(san))?;
97                }
98                write!(f, "{}", Escaped(reason))
99            }
100            ServerEvent::InvalidCollectionDir { name } => write!(
101                f,
102                "refs/mirrors/{}: the directory name is not a collection id, and the ref \
103                 listing leaves out the directory",
104                Escaped(name)
105            ),
106            ServerEvent::StaleSummary { item } => write!(
107                f,
108                "the summary of the auth item {} does not match the client groups, and the \
109                 server answers 404 for it; run `ostrya summary -u`",
110                Escaped(item)
111            ),
112        }
113    }
114}
115
116/// The stale summaries that one server reported.
117pub(crate) struct StaleSummaries {
118    /// The text of each item that the server reported.
119    reported: Mutex<HashSet<String>>,
120    /// The callback of the events of the server.
121    on_event: Option<EventSink>,
122}
123
124impl StaleSummaries {
125    /// Returns the record of a server that reported no stale summary, which
126    /// reports its events to `on_event`.
127    pub(crate) fn new(on_event: Option<EventSink>) -> StaleSummaries {
128        StaleSummaries {
129            reported: Mutex::new(HashSet::new()),
130            on_event,
131        }
132    }
133
134    /// Reports `item` as a [`ServerEvent::StaleSummary`] if the server did
135    /// not report it before.
136    pub(crate) fn report(&self, item: &AuthItem) {
137        let Some(on_event) = &self.on_event else {
138            return;
139        };
140        let item = item.to_string();
141        let new = self
142            .reported
143            .lock()
144            .unwrap_or_else(PoisonError::into_inner)
145            .insert(item.clone());
146        if new {
147            on_event(&ServerEvent::StaleSummary { item });
148        }
149    }
150}
151
152/// A text with each ASCII control character as its escape sequence.
153pub(crate) struct Escaped<'a>(pub(crate) &'a str);
154
155impl fmt::Display for Escaped<'_> {
156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157        for c in self.0.chars() {
158            if c.is_ascii_control() {
159                write!(f, "{}", c.escape_default())?;
160            } else {
161                write!(f, "{c}")?;
162            }
163        }
164        Ok(())
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    /// The line names the digest, the URI SAN, and the reason, and escapes
173    /// each control character.
174    #[test]
175    fn the_line_names_the_digest_and_the_san() {
176        let digest = Checksum::sha256(b"cert");
177        let event = ServerEvent::BadClaims {
178            digest,
179            san: Some("ostrya:ref:x:a\nforged line\t\u{7f}".to_owned()),
180            reason: "the modes are one or more of r, w, c, t, and d".to_owned(),
181        };
182        assert_eq!(
183            event.to_string(),
184            format!(
185                "refused the client certificate tls-sha256:{}: malformed claim \
186                 'ostrya:ref:x:a\\nforged line\\t\\u{{7f}}': the modes are one or more of r, w, \
187                 c, t, and d",
188                digest.to_hex()
189            )
190        );
191        let event = ServerEvent::BadClaims {
192            digest,
193            san: None,
194            reason: "the certificate holds more than 256 claims\r".to_owned(),
195        };
196        assert_eq!(
197            event.to_string(),
198            format!(
199                "refused the client certificate tls-sha256:{}: the certificate holds more \
200                 than 256 claims\\r",
201                digest.to_hex()
202            )
203        );
204        assert!(!event.is_warning());
205    }
206
207    /// The line of an invalid collection directory names its path and
208    /// escapes each control character. The event is a warning.
209    #[test]
210    fn the_line_of_an_invalid_collection_dir_escapes_its_name() {
211        let event = ServerEvent::InvalidCollectionDir {
212            name: "bad\nforged line\t\u{7f}".to_owned(),
213        };
214        assert_eq!(
215            event.to_string(),
216            "refs/mirrors/bad\\nforged line\\t\\u{7f}: the directory name is not a \
217             collection id, and the ref listing leaves out the directory"
218        );
219        assert!(event.is_warning());
220    }
221
222    /// The line of a stale summary names the item, escapes each control
223    /// character, and names the command that writes the summaries. The event
224    /// is an error.
225    #[test]
226    fn the_line_of_a_stale_summary_names_the_item() {
227        let event = ServerEvent::StaleSummary {
228            item: "tls:a\nb".to_owned(),
229        };
230        assert_eq!(
231            event.to_string(),
232            "the summary of the auth item tls:a\\nb does not match the client groups, and \
233             the server answers 404 for it; run `ostrya summary -u`"
234        );
235        assert!(!event.is_warning());
236    }
237
238    /// The record reports each item one time.
239    #[test]
240    fn a_stale_summary_is_reported_one_time_for_each_item() {
241        let seen = Arc::new(Mutex::new(Vec::new()));
242        let sink = seen.clone();
243        let stale = StaleSummaries::new(Some(Arc::new(move |event: &ServerEvent| {
244            sink.lock().unwrap().push(event.to_string());
245        })));
246        let ssh = AuthItem::parse("ssh:u").unwrap();
247        for item in [&AuthItem::Anonymous, &ssh, &AuthItem::Anonymous, &ssh] {
248            stale.report(item);
249        }
250        let seen = seen.lock().unwrap();
251        assert_eq!(seen.len(), 2, "{seen:?}");
252        assert!(seen[0].contains(" anonymous "), "{}", seen[0]);
253        assert!(seen[1].contains(" ssh:u "), "{}", seen[1]);
254    }
255}