1use std::collections::HashSet;
4use std::fmt;
5use std::sync::{Arc, Mutex, PoisonError};
6
7use ostrya::Checksum;
8use ostrya::access::AuthItem;
9
10pub(crate) type EventSink = Arc<dyn Fn(&ServerEvent) + Send + Sync>;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum ServerEvent {
22 #[non_exhaustive]
30 BadClaims {
31 digest: Checksum,
34 san: Option<String>,
37 reason: String,
39 },
40 #[non_exhaustive]
50 InvalidCollectionDir {
51 name: String,
53 },
54 #[non_exhaustive]
64 StaleSummary {
65 item: String,
67 },
68}
69
70impl ServerEvent {
71 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
116pub(crate) struct StaleSummaries {
118 reported: Mutex<HashSet<String>>,
120 on_event: Option<EventSink>,
122}
123
124impl StaleSummaries {
125 pub(crate) fn new(on_event: Option<EventSink>) -> StaleSummaries {
128 StaleSummaries {
129 reported: Mutex::new(HashSet::new()),
130 on_event,
131 }
132 }
133
134 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
152pub(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 #[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 #[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 #[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 #[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}