Improve error handling

main
Elnu 2 years ago
parent 1253539efa
commit f68f2155c3

@ -5,7 +5,7 @@ pub use comment::*;
mod database; mod database;
pub use database::Database; pub use database::Database;
use actix_web::{get, post, web, App, HttpRequest, HttpResponse, HttpServer, Responder}; use actix_web::{get, post, web, App, HttpRequest, HttpResponse, HttpServer};
use clap::Parser; use clap::Parser;
use sanitize_html::{errors::SanitizeError, rules::predefined::DEFAULT, sanitize_str}; use sanitize_html::{errors::SanitizeError, rules::predefined::DEFAULT, sanitize_str};
use scraper::{Html, Selector}; use scraper::{Html, Selector};
@ -19,69 +19,68 @@ struct AppState {
arguments: Arguments, arguments: Arguments,
} }
// TODO: Make error handling system not bad. enum Error {
// Currently, it's a horrible mix of custom error types a direct HttpResponses, InvalidOrigin,
// due to not being able to pass HttpResponse out of web::block... InvalidBody,
// Well, it works, at least. InvalidUrl,
InvalidFields,
enum DatabaseAccessError { InvalidContentId,
BadOrigin, InvalidParent,
AccessError, EmailRequired,
DatabaseError, NameRequired,
} DatabaseAccessError,
DatabaseInternalError,
enum CommentCreationError { SanitizationError,
DatabaseAccessError(DatabaseAccessError), PageFetchError,
BadParent,
}
impl DatabaseAccessError {
fn to_http_response(&self) -> HttpResponse {
match self {
Self::BadOrigin => HttpResponse::BadRequest().reason("bad origin").finish(),
Self::AccessError => HttpResponse::InternalServerError()
.reason("database access error")
.finish(), // e.g. PoisonError
Self::DatabaseError => HttpResponse::InternalServerError()
.reason("database error")
.finish(),
}
}
} }
impl CommentCreationError { impl Error {
fn to_http_response(&self) -> HttpResponse { fn to_http_response(&self) -> HttpResponse {
match self { match self {
Self::DatabaseAccessError(error) => error.to_http_response(), Self::InvalidOrigin |
Self::BadParent => HttpResponse::BadRequest() Self::InvalidBody |
.reason("invalid comment parent") Self::InvalidUrl |
.finish(), Self::InvalidFields |
} Self::InvalidContentId |
Self::InvalidParent |
Self::EmailRequired |
Self::NameRequired => HttpResponse::BadRequest(),
Self::DatabaseAccessError |
Self::DatabaseInternalError |
Self::SanitizationError |
Self::PageFetchError => HttpResponse::InternalServerError(),
}.reason(match self {
Self::InvalidOrigin => "invalid request origin",
Self::InvalidBody => "invalid request body",
Self::InvalidUrl => "invalid request url",
Self::InvalidFields => "invalid request field",
Self::InvalidContentId => "invalid request content id",
Self::InvalidParent => "invalid comment parent",
Self::EmailRequired => "comment email required",
Self::NameRequired => "comment name required",
Self::DatabaseAccessError => "database access error",
Self::DatabaseInternalError => "database internal error",
Self::SanitizationError => "comment sanitization error",
Self::PageFetchError => "page fetch error",
}).finish()
} }
} }
impl AppState { impl AppState {
fn get_db<'a>( fn get_db<'a>(
&'a self,
request: &HttpRequest,
) -> Result<MutexGuard<'a, Database>, DatabaseAccessError> {
self.get_db_with_origin(get_request_origin(request))
}
fn get_db_with_origin<'a>(
&'a self, &'a self,
origin: Option<String>, origin: Option<String>,
) -> Result<MutexGuard<'a, Database>, DatabaseAccessError> { ) -> Result<MutexGuard<'a, Database>, Error> {
let origin = match origin { let origin = match origin {
Some(origin) => origin, Some(origin) => origin,
None => return Err(DatabaseAccessError::BadOrigin), None => return Err(Error::InvalidOrigin),
}; };
match self.databases.get(&origin) { match self.databases.get(&origin) {
Some(database) => Ok(match database.lock() { Some(database) => Ok(match database.lock() {
Ok(database) => database, Ok(database) => database,
Err(_) => return Err(DatabaseAccessError::AccessError), Err(_) => return Err(Error::DatabaseAccessError),
}), }),
None => return Err(DatabaseAccessError::AccessError), None => return Err(Error::InvalidOrigin),
} }
} }
} }
@ -124,35 +123,40 @@ struct Arguments {
email_required: bool, email_required: bool,
} }
#[get("/{content_id}")] async fn _get_comments(
async fn get_comments(
data: web::Data<AppState>, data: web::Data<AppState>,
request: HttpRequest, request: HttpRequest,
content_id: web::Path<String>, content_id: web::Path<String>,
) -> impl Responder { ) -> Result<Vec<Comment>, Error> {
let origin = get_request_origin(&request); let origin = get_request_origin(&request);
let comments = match web::block(move || { match web::block(move || {
Ok( Ok(
match match data.get_db_with_origin(origin) { match match data.get_db(origin) {
Ok(database) => database, Ok(database) => database,
Err(err) => return Err(err), Err(err) => return Err(err),
} }
.get_comments(&content_id) .get_comments(&content_id)
{ {
Ok(comments) => comments, Ok(comments) => comments,
Err(_) => return Err(DatabaseAccessError::DatabaseError), Err(_) => return Err(Error::DatabaseInternalError),
}, },
) )
}) }).await {
.await Ok(result) => result,
{ Err(_) => Err(Error::DatabaseAccessError),
Ok(comments) => match comments { }
Ok(comments) => comments, }
Err(err) => return err.to_http_response(),
}, #[get("/{content_id}")]
Err(_) => return DatabaseAccessError::AccessError.to_http_response(), async fn get_comments(
}; data: web::Data<AppState>,
HttpResponse::Ok().json(comments) request: HttpRequest,
content_id: web::Path<String>,
) -> HttpResponse {
match _get_comments(data, request, content_id).await {
Ok(comments) => HttpResponse::Ok().json(comments),
Err(err) => err.to_http_response(),
}
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -161,12 +165,11 @@ struct PostCommentsRequest {
comment: Comment, comment: Comment,
} }
#[post("/")] async fn _post_comment(
async fn post_comment(
data: web::Data<AppState>, data: web::Data<AppState>,
request: HttpRequest, request: HttpRequest,
bytes: web::Bytes, bytes: web::Bytes,
) -> impl Responder { ) -> Result<(), Error> {
match String::from_utf8(bytes.to_vec()) { match String::from_utf8(bytes.to_vec()) {
Ok(text) => { Ok(text) => {
let PostCommentsRequest { url, comment } = let PostCommentsRequest { url, comment } =
@ -181,32 +184,26 @@ async fn post_comment(
Ok(()) Ok(())
}; };
if let Err(_) = sanitize_req() { if let Err(_) = sanitize_req() {
return HttpResponse::InternalServerError() return Err(Error::SanitizationError);
.reason("failed to sanitize request")
.finish();
} }
req req
} }
Err(_) => { Err(_) => {
return HttpResponse::BadRequest() return Err(Error::InvalidBody);
.reason("invalid request body")
.finish()
} }
}; };
if comment.validate().is_err() { if comment.validate().is_err() {
return HttpResponse::BadRequest() return Err(Error::InvalidFields);
.reason("invalid comment field(s)")
.finish();
} }
if comment.author.is_none() && data.arguments.name_required { if comment.author.is_none() && data.arguments.name_required {
return HttpResponse::BadRequest().reason("name required").finish(); return Err(Error::NameRequired);
} }
if comment.email.is_none() && data.arguments.email_required { if comment.email.is_none() && data.arguments.email_required {
return HttpResponse::BadRequest().reason("email required").finish(); return Err(Error::EmailRequired);
} }
let origin = match get_request_origin(&request) { let origin = match get_request_origin(&request) {
Some(origin) => origin, Some(origin) => origin,
None => return HttpResponse::BadRequest().reason("bad origin").finish(), None => return Err(Error::InvalidOrigin),
}; };
// Check to see if provided URL is in scope. // Check to see if provided URL is in scope.
// This is to prevent malicious requests that try to get server to fetch external websites. // This is to prevent malicious requests that try to get server to fetch external websites.
@ -218,31 +215,25 @@ async fn post_comment(
break 'outer; break 'outer;
} }
} }
return HttpResponse::BadRequest() return Err(Error::InvalidUrl);
.reason("url out of scope")
.finish();
} }
match get_page_data(&url).await { match get_page_data(&url).await {
Ok(page_data_option) => match page_data_option { Ok(page_data_option) => match page_data_option {
Some(page_data) => { Some(page_data) => {
if page_data.content_id != comment.content_id { if page_data.content_id != comment.content_id {
return HttpResponse::BadRequest() return Err(Error::InvalidContentId)
.reason("content ids don't match")
.finish();
} }
} }
None => return HttpResponse::BadRequest().reason("url invalid").finish(), // e.g. 404 None => return Err(Error::InvalidUrl), // e.g. 404
}, },
Err(_) => { Err(_) => {
return HttpResponse::InternalServerError() return Err(Error::PageFetchError);
.reason("failed to get page data")
.finish()
} }
}; };
match web::block(move || { match web::block(move || {
let database = match data.get_db_with_origin(Some(origin)) { let database = match data.get_db(Some(origin)) {
Ok(database) => database, Ok(database) => database,
Err(err) => return Err(CommentCreationError::DatabaseAccessError(err)), Err(err) => return Err(err),
}; };
if let Some(parent) = comment.parent { if let Some(parent) = comment.parent {
'outer2: loop { 'outer2: loop {
@ -256,35 +247,38 @@ async fn post_comment(
break; break;
} }
} }
} },
Err(_) => { Err(_) => {
return Err(CommentCreationError::DatabaseAccessError( return Err(Error::DatabaseInternalError);
DatabaseAccessError::DatabaseError,
))
} }
}; };
return Err(CommentCreationError::BadParent); return Err(Error::InvalidParent);
} }
} }
if let Err(_) = database.create_comment(&comment) { if let Err(_) = database.create_comment(&comment) {
return Err(CommentCreationError::DatabaseAccessError( return Err(Error::DatabaseInternalError);
DatabaseAccessError::DatabaseError,
));
} }
Ok(()) Ok(())
}) })
.await .await
{ {
Ok(result) => match result { Ok(result) => result,
Ok(_) => HttpResponse::Ok().into(), Err(_) => Err(Error::DatabaseAccessError),
Err(error) => error.to_http_response(),
},
Err(_) => DatabaseAccessError::AccessError.to_http_response(),
} }
} }
Err(_) => HttpResponse::BadRequest() Err(_) => Err(Error::InvalidBody),
.reason("failed to parse request body") }
.finish(), }
#[post("/")]
async fn post_comment(
data: web::Data<AppState>,
request: HttpRequest,
bytes: web::Bytes,
) -> HttpResponse {
match _post_comment(data, request, bytes).await {
Ok(_) => HttpResponse::Ok().finish(),
Err(err) => err.to_http_response(),
} }
} }

Loading…
Cancel
Save