about summary refs log tree commit diff
path: root/splorm/src/runtime_error.rs
blob: d1e624a8e246e7e0313080cef4cb3c37850a790d (plain)
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
//! error handling
//!
//! The [`RuntimeError`] enum is meant to be able to represent any error
//! that might occur, well, at runtime.
//!
//! [`PresentableRuntimeError`] implements axum's `IntoResponse` so
//! that it can use `fmt::Display` for creating it's error text.
//! [`RuntimeError`] also implements `fmt::Display`, but this is used for
//! logged errors, and it does not implement `IntoResponse` itself

use std::{borrow::Cow, fmt, io::ErrorKind, sync::Arc};

use axum::{
	body::Body,
	response::{IntoResponse, Response},
};
use camino::Utf8PathBuf;
use gny::sternum::Sternum;
use somethings::DatabaseError;
use wikarden::WikError;

use crate::QueryParseError;

#[derive(Copy, Clone, Debug, PartialEq, Sternum)]
pub enum InvalidPathReason {
	OutsideRoot,
	NotFound,
}

#[derive(Copy, Clone, Debug, PartialEq, Sternum)]
pub enum FileErrorReason {
	PermissionDenied,
	NotFound,
	Unknown,
}

#[derive(Copy, Clone, Debug, PartialEq, Sternum)]
pub enum TemplateErrorReason {
	NotATemplate,
	ParseError,
}

#[derive(Debug)]
pub enum RuntimeError {
	/// The requested path was invalid. Often returned by [`RequestPath::verify_safe()`]
	InvalidPath {
		reason: InvalidPathReason,
		request_path: String,
		system_path: Utf8PathBuf,
	},
	/// There was an error reading a file
	FileError {
		reason: FileErrorReason,
		source: std::io::Error,
		system_path: Utf8PathBuf,
	},
	/// There was an error constructing a page from it's template
	TemplateError {
		reason: TemplateErrorReason,
		source: Option<bempline::ParseError>,
		system_path: Utf8PathBuf,
	},
	/// Error parsing query parameters
	QueryParseError { source: QueryParseError },
	/// Some field was missing in a form.
	/// Use [`RuntimeError::GenericBadRequest`] if multiple fields are missing
	IncompleteForm { missing_field: &'static str },
	/// The request was invalid for some `reason`
	GenericBadRequest { reason: Cow<'static, str> },
	/// Error interacting with the database
	DatabaseError { source: DatabaseError },
	/// An error from wikarden
	WikiError { source: WikError },
	/// failed authentication
	AuthenticationFailed { name: String },
	/// A [`SessionID`] was invalid
	InvalidSession,
	/// Generic 403 Authorization Needed
	Generic403,
	/// Generic 404 Not Found
	Generic404,
	/// Some unknown error; 500 Internal Server Error
	Unknown,
}

impl RuntimeError {
	pub fn outside_root(request_path: String, system_path: Utf8PathBuf) -> Self {
		Self::InvalidPath {
			reason: InvalidPathReason::OutsideRoot,
			request_path,
			system_path,
		}
	}

	pub fn not_found(request_path: String, system_path: Utf8PathBuf) -> Self {
		Self::InvalidPath {
			reason: InvalidPathReason::NotFound,
			request_path,
			system_path,
		}
	}

	pub fn file_error(err: std::io::Error, system_path: Utf8PathBuf) -> Self {
		let reason = match err.kind() {
			ErrorKind::PermissionDenied => FileErrorReason::PermissionDenied,
			ErrorKind::NotFound => FileErrorReason::NotFound,
			_ => FileErrorReason::Unknown,
		};

		Self::FileError {
			reason,
			source: err,
			system_path,
		}
	}

	pub fn not_a_template(system_path: Utf8PathBuf) -> Self {
		Self::TemplateError {
			reason: TemplateErrorReason::NotATemplate,
			source: None,
			system_path,
		}
	}

	pub fn template_parse_error(err: bempline::ParseError, system_path: Utf8PathBuf) -> Self {
		Self::TemplateError {
			reason: TemplateErrorReason::ParseError,
			source: Some(err),
			system_path,
		}
	}

	pub fn bad_request<R: Into<Cow<'static, str>>>(reason: R) -> Self {
		Self::GenericBadRequest {
			reason: reason.into(),
		}
	}

	pub fn incomplete_form(field: &'static str) -> Self {
		Self::IncompleteForm {
			missing_field: field,
		}
	}

	pub fn authentication_failed(name: String) -> Self {
		Self::AuthenticationFailed { name }
	}

	pub fn generic_404() -> Self {
		RuntimeError::Generic404
	}

	pub fn unknown() -> Self {
		RuntimeError::Unknown
	}

	pub fn status_code(&self) -> u16 {
		match self {
			Self::InvalidPath { .. } => 404,
			Self::FileError { reason, .. } => match reason {
				FileErrorReason::NotFound => 404,
				FileErrorReason::PermissionDenied => 404,
				FileErrorReason::Unknown => 500,
			},
			Self::TemplateError { .. } => 500,
			Self::QueryParseError { .. } => 400,
			Self::GenericBadRequest { .. } => 400,
			Self::IncompleteForm { .. } => 400,
			Self::DatabaseError { .. } => 500,
			Self::WikiError { source } => match source {
				WikError::IllegalPath { .. } => 404,
				WikError::CanonicalizationFailed { .. } => 404,
				_ => 500,
			},
			Self::AuthenticationFailed { .. } => 403,
			Self::InvalidSession => 403,
			Self::Generic403 => 403,
			Self::Generic404 => 404,
			Self::Unknown => 500,
		}
	}
}

impl fmt::Display for RuntimeError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			RuntimeError::InvalidPath {
				reason,
				request_path,
				system_path,
			} => write!(
				f,
				"invalid path. reason={reason} web={request_path}, system={system_path}"
			),
			RuntimeError::FileError {
				source,
				system_path,
				..
			} => {
				write!(f, "file error: {source}. system={system_path}")
			}
			RuntimeError::TemplateError {
				reason,
				source,
				system_path,
			} => match source {
				Some(pe) => write!(f, "template error: {pe}. system={system_path}"),
				None => write!(f, "template error. reason={reason}, system={system_path}"),
			},
			RuntimeError::QueryParseError { source } => {
				write!(f, "failed to parse query. {source}")
			}
			RuntimeError::GenericBadRequest { reason } => {
				write!(f, "bad request {reason}")
			}
			RuntimeError::IncompleteForm { missing_field } => {
				write!(f, "missing field {missing_field} in form")
			}
			RuntimeError::DatabaseError { source } => {
				write!(f, "database error: {source}")
			}
			RuntimeError::WikiError { source } => {
				write!(f, "wiki error: {source}")
			}
			RuntimeError::AuthenticationFailed { name } => {
				write!(f, "authentication failed for '{name}'")
			}
			RuntimeError::InvalidSession => {
				write!(f, "the session id was invalid")
			}
			RuntimeError::Generic403 => write!(f, "generic 403"),
			RuntimeError::Generic404 => write!(f, "generic 404"),
			RuntimeError::Unknown => write!(f, "unknown error!"),
		}
	}
}

/// Errors users can see
struct PresentableRuntimeError<'re>(&'re RuntimeError);
impl<'re> fmt::Display for PresentableRuntimeError<'re> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		macro_rules! estr {
			(400) => {
				write!(f, "bad request")
			};
			(400 incomplete $missing:ident) => {
				write!(f, "incomplete form. field {} is required", $missing)
			};
			(403) => {
				write!(f, "authenticated failed")
			};
			(404) => {
				write!(f, "the requested file could not be found")
			};
			(404 $webpath:ident) => {
				write!(f, "file not found: '{}'", $webpath)
			};
			(500) => {
				write!(f, "an unknown error occured!")
			};
		}

		match &self.0 {
			RuntimeError::InvalidPath { request_path, .. } => {
				estr!(404 request_path)
			}
			RuntimeError::FileError { reason, .. } => match reason {
				FileErrorReason::NotFound | FileErrorReason::PermissionDenied => estr!(404),
				FileErrorReason::Unknown => estr!(500),
			},
			RuntimeError::TemplateError { .. } => estr!(500),
			RuntimeError::QueryParseError { .. } => estr!(400),
			RuntimeError::GenericBadRequest { .. } => estr!(400),
			RuntimeError::IncompleteForm { missing_field } => estr!(400 incomplete missing_field),
			RuntimeError::DatabaseError { .. } => estr!(500),
			RuntimeError::WikiError { source } => match source {
				WikError::IllegalPath { wik, .. } => estr!(404 wik),
				WikError::CanonicalizationFailed { .. } => estr!(404),
				_ => estr!(500),
			},
			RuntimeError::AuthenticationFailed { .. } => estr!(403),
			RuntimeError::InvalidSession => estr!(403),
			RuntimeError::Generic403 => estr!(403),
			RuntimeError::Generic404 => estr!(404),
			RuntimeError::Unknown => estr!(500),
		}
	}
}

impl IntoResponse for RuntimeError {
	fn into_response(self) -> Response {
		let status = self.status_code();
		let presentable = PresentableRuntimeError(&self);
		let mut response = make_basic_error(status, presentable);
		response.extensions_mut().insert(Arc::new(self));
		response
	}
}

fn make_basic_error<S: std::fmt::Display>(status: u16, msg: S) -> Response {
	let error_str = format!(
		"<html>\n\
		\t<head><title>{status}</title></head>\n\
		\t<body style='width: 20rem; padding: 0px; margin: 2rem;'>\n\
		\t\t<h1>{status}</h1>\n\
		\t\t<hr/>\n\
		\t\t<p>{msg}</p>\n\
		\t</body>\n\
		</html>"
	);

	Response::builder()
		.status(status)
		.header("content-type", "text/html")
		.body(Body::from(error_str))
		.unwrap()
		.into_response()
}

impl From<QueryParseError> for RuntimeError {
	fn from(qpe: QueryParseError) -> Self {
		RuntimeError::QueryParseError { source: qpe }
	}
}

impl From<DatabaseError> for RuntimeError {
	fn from(dbe: DatabaseError) -> Self {
		RuntimeError::DatabaseError { source: dbe }
	}
}

impl From<WikError> for RuntimeError {
	fn from(we: WikError) -> Self {
		RuntimeError::WikiError { source: we }
	}
}