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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use crate::templates::page::Page;
use crate::templates::{jumbotron, Template};
use actix_web::dev::HttpResponseBuilder;
use actix_web::error::Error as ActixError;
use actix_web::http::header::CONTENT_TYPE;
use actix_web::http::StatusCode;
use actix_web::rt::blocking::BlockingError;
use actix_web::{HttpRequest, HttpResponse, ResponseError};
use graphql_client::Error as GraphQlError;
use handlebars::RenderError;
use reqwest::Error as ReqwestError;
use std::error::Error;
use std::fmt;
pub const TELESCOPE_ERROR_MIME: &'static str = "application/prs.telescope.error+json";
#[derive(Debug, From, Error, Display, Serialize, Deserialize)]
pub enum TelescopeError {
#[display(fmt = "Page Not Found")]
PageNotFound,
#[display(fmt = "{}: {}", header, message)]
ResourceNotFound {
header: String,
message: String,
},
#[display(fmt = "{}: {}", header, message)]
GatewayError {
header: String,
message: String,
},
#[from]
#[display(fmt = "Error rendering handlebars template: {}", _0)]
RenderingError(#[serde(with = "RenderErrorDef")] RenderError),
#[display(fmt = "Internal future canceled")]
FutureCanceled,
#[error(ignore)]
#[display(fmt = "Internal server error: {}", _0)]
InternalServerError(String),
#[display(fmt = "Bad Request - {}: {}", header, message)]
BadRequest {
header: String,
message: String,
show_status_code: bool,
},
#[display(fmt = "Not Implemented")]
NotImplemented,
#[display(fmt = "Could not extract IP address from HTTP request")]
IpExtractionError,
#[display(fmt = "Could not find CSRF token")]
CsrfTokenNotFound,
#[display(fmt = "CSRF token mismatch")]
CsrfTokenMismatch,
#[error(ignore)]
#[display(fmt = "Error interacting with RCOS API: {}", _0)]
RcosApiError(String),
#[error(ignore)]
#[display(fmt = "Error interacting with GitHub API: {}", _0)]
GitHubApiError(String),
#[error(ignore)]
#[display(fmt = "Error interacting with Discord API: {}", _0)]
SerenityError(String),
#[error(ignore)]
#[display(fmt = "{} returned error(s) :{:?}", platform, errors)]
GraphQLError {
platform: String,
errors: Vec<GraphQlError>,
},
#[error(ignore)]
#[display(fmt = "Invalid form submission")]
InvalidForm(Page),
#[display(fmt = "Request not properly authenticated")]
NotAuthenticated,
#[display(fmt = "Authenticated Request Forbidden")]
Forbidden,
#[error(ignore)]
#[display(fmt = "RPI CAS error: {}", _0)]
RpiCasError(String),
}
impl TelescopeError {
pub fn resource_not_found(header: impl Into<String>, message: impl Into<String>) -> Self {
Self::ResourceNotFound {
header: header.into(),
message: message.into(),
}
}
pub fn ise(message: impl Into<String>) -> Self {
Self::InternalServerError(message.into())
}
pub fn rcos_api_error(err: ReqwestError) -> Self {
error!("Error querying RCOS API: {}", err);
Self::RcosApiError(err.to_string())
}
pub fn github_api_error(err: ReqwestError) -> Self {
error!("Error querying GitHub API: {}", err);
Self::GitHubApiError(err.to_string())
}
pub fn serenity_error(err: serenity::Error) -> Self {
error!("Serenity Error: {}", err);
Self::SerenityError(err.to_string())
}
pub fn rpi_cas_error(err: ReqwestError) -> Self {
error!("Error querying RPI CAS endpoint: {}", err);
TelescopeError::RpiCasError(err.to_string())
}
pub async fn render_error_page(&self, req: &HttpRequest) -> Result<String, ActixError> {
let status_code: u16 = self.status_code().as_u16();
let canonical_reason: &'static str = self
.status_code()
.canonical_reason()
.unwrap_or("Unknown Error");
let inner_template: Template = match self {
TelescopeError::PageNotFound => jumbotron::new(
format!("{} - Page Not Found", status_code),
"We could not find the page you are looking for. If you think this is in \
error, please reach out to a coordinator or make an issue on the Github repo.",
),
TelescopeError::NotImplemented => jumbotron::new(
format!("{} - {}", status_code, canonical_reason),
"The telescope developers have not finished implementing this page. Please \
contact a coordinator AND open a GitHub issue.",
),
TelescopeError::ResourceNotFound { header, message } => {
jumbotron::new(format!("{} - {}", status_code, header), message)
}
TelescopeError::GatewayError { header, message } => jumbotron::new(
format!("{} - {}", status_code, header),
format!("{} Please contact a coordinator or faculty advisor.", message)
),
TelescopeError::FutureCanceled => jumbotron::new(
format!("{} - {}", status_code, canonical_reason),
"An internal future was canceled unexpectedly. Please try again. If you \
keep seeing this error message, contact a coordinator and open an issue on the \
Telescope GitHub repository.",
),
TelescopeError::RenderingError(err) => jumbotron::new(
format!("{} - Internal Server Template Error", status_code),
format!(
"{}. Please create an issue on Telescope's GitHub and contact a \
coordinator.",
err
),
),
TelescopeError::BadRequest { header, message, show_status_code} => {
jumbotron::new(
show_status_code
.then(|| format!("{} - {}", status_code, header))
.unwrap_or(header.clone()),
message)
}
TelescopeError::IpExtractionError => jumbotron::new(
format!("{} - {}", status_code, canonical_reason),
"Could not determine remote IP address of this request for CSRF purposes. \
Please contact a coordinator and create a GitHub issue.",
),
TelescopeError::CsrfTokenNotFound => jumbotron::new(
format!("{} - CSRF Token Not Found", status_code),
"Could not find the CSRF token for this request. Please try again. If this \
error continues, please contact a coordinator and create a GitHub issue.",
),
TelescopeError::CsrfTokenMismatch => jumbotron::new(
format!("{} - Bad CSRF Token", status_code),
"The CSRF token supplied to the server by this request does not match the \
one the server generated for this identity provider for this IP. If you believe \
this is in error, please contact a coordinator and file a GitHub issue.",
),
TelescopeError::RcosApiError(err) => jumbotron::new(
format!("{} - Internal API Query Error", status_code),
format!(
"Could not query the central RCOS API. Please contact a coordinator and file a \
GitHub issue. Internal error description: {}", err),
),
TelescopeError::GitHubApiError(err) => jumbotron::new(
format!("{} - GitHub API V4 Query Error", status_code),
format!("Could not query the GitHub API. Please contact a coordinator and \
file a GitHub issue on the Telescope repository. Internal error description: {}",
err),
),
TelescopeError::SerenityError(err) => jumbotron::new(
format!("{} - Discord Error", status_code),
format!("Error interacting with the Discord API. Please contact a \
coordinator and file a GitHub issue if this error persists. Internal error \
description: {}", err)
),
TelescopeError::RpiCasError(err) => jumbotron::new(
format!("{} - RPI CAS Error", status_code),
format!("Issue communicating with the RPI CAS service. Please try again. \
If the error persists, please contact a coordinator and create an issue on the \
Telescope GitHub. Internal Error: {}", err)
),
TelescopeError::GraphQLError { platform, errors } => {
let errs: Vec<String> = errors.iter().map(|e| format!("{}", e)).collect();
jumbotron::new(
format!("{} - {} Error", status_code, platform),
format!("The {} returned at least one error. Please \
contact a coordinator and create an issue on the telescope GitHub. Internal error \
description(s): {:?}", platform, errs)
)
}
TelescopeError::InternalServerError(message) => jumbotron::new(
format!("{} - {}", status_code, canonical_reason),
format!(
"Telescope had an internal server error. Please contact a \
coordinator and file a GitHub issue. Error description: {}",
message
),
),
TelescopeError::InvalidForm(page) => {
return page
.render()
.map_err(ActixError::from);
}
TelescopeError::NotAuthenticated => jumbotron::new(
format!("{} - {}", status_code, canonical_reason),
"You need to sign in to access this page. If you are trying to create an \
account, please restart. Otherwise please sign in. If you have logged in, and this \
page is unexpected, please contact a coordinator and create a GitHub issue.",
),
TelescopeError::Forbidden => jumbotron::new(
format!("{} - {}", status_code, canonical_reason),
"You do not have the necessary permissions to access this page. If you \
think this is in error, please contact a coordinator or faculty advisor."
),
};
return Page::new(req, "RCOS - Error", inner_template)
.await
.map_err(ActixError::from)?
.render()
.map_err(ActixError::from);
}
}
impl<E> From<BlockingError<E>> for TelescopeError
where
E: Into<TelescopeError> + fmt::Debug,
{
fn from(error: BlockingError<E>) -> TelescopeError {
match error {
BlockingError::Canceled => TelescopeError::FutureCanceled,
BlockingError::Error(e) => e.into(),
}
}
}
impl ResponseError for TelescopeError {
fn status_code(&self) -> StatusCode {
match self {
TelescopeError::BadRequest { .. } => StatusCode::BAD_REQUEST,
TelescopeError::ResourceNotFound { .. } => StatusCode::NOT_FOUND,
TelescopeError::PageNotFound => StatusCode::NOT_FOUND,
TelescopeError::NotImplemented => StatusCode::NOT_IMPLEMENTED,
TelescopeError::CsrfTokenNotFound => StatusCode::NOT_FOUND,
TelescopeError::CsrfTokenMismatch => StatusCode::BAD_REQUEST,
TelescopeError::InvalidForm(_) => StatusCode::BAD_REQUEST,
TelescopeError::NotAuthenticated => StatusCode::UNAUTHORIZED,
TelescopeError::Forbidden => StatusCode::FORBIDDEN,
TelescopeError::RpiCasError(_) => StatusCode::BAD_GATEWAY,
TelescopeError::GatewayError { .. } => StatusCode::BAD_GATEWAY,
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn error_response(&self) -> HttpResponse {
error!("Service generated error: {}", self);
let json_str: String =
serde_json::to_string(self).expect("Could not serialize self to JSON.");
HttpResponseBuilder::new(self.status_code())
.set_header(CONTENT_TYPE, TELESCOPE_ERROR_MIME)
.body(json_str)
}
}
#[derive(Serialize, Deserialize)]
#[serde(remote = "RenderError")]
struct RenderErrorDef {
desc: String,
template_name: Option<String>,
line_no: Option<usize>,
column_no: Option<usize>,
#[serde(skip)]
#[serde(getter = "Option::None")]
cause: Option<Box<dyn Error + Send + Sync + 'static>>,
}
impl From<RenderErrorDef> for RenderError {
fn from(err: RenderErrorDef) -> Self {
let mut new: RenderError = RenderError::new(err.desc);
new.column_no = err.column_no;
new.line_no = err.line_no;
new.template_name = err.template_name;
return new;
}
}