Compare commits

...

5 Commits

Author SHA1 Message Date
Matthew Gordon fbb320507a Add tests and improve error handling 2024-02-27 22:39:13 -04:00
Matthew Gordon 841b16986b Move admin module into app module 2024-02-26 15:10:09 -04:00
Matthew Gordon 1fab78ff96 Make a trait to allow dependence injection 2024-02-26 13:12:31 -04:00
Matthew Gordon af2fb99ad9 Alphabetize dependencies in Cargo.toml 2024-02-26 11:53:47 -04:00
Matthew Gordon 95362c8a99 Setup and authentication WIP
- Add page for creating intial admin user
- Add JWT for authentication of logged-in users
- Add tracing
- Some improvements to error handling
2024-02-26 11:13:32 -04:00
18 changed files with 957 additions and 246 deletions

View File

@ -1,2 +1,3 @@
[env]
LOCALITY_STATIC_FILE_PATH = { value = "static", relative = true }
LOCALITY_HMAC_SECRET = "Not-secret testing secret"

View File

@ -6,13 +6,27 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tokio = { version = "1", features = ["rt-multi-thread"]}
axum = { version = "0.7", default_features = false, features = ["http1", "form", "tokio"] }
argon2 = { version = "0.5", features = ["password-hash", "std"] }
askama = "0.12"
askama_axum = "0.4"
tower-http = { version = "0.5", features = ["fs"] }
axum = { version = "0.7", default_features = false, features = ["http1", "form", "tokio"] }
axum-extra = { version = "0.9", features = ["cookie"] }
base64 = "0.21"
chrono = { version = "0.4.34", features = ["serde"] }
deadpool-postgres = { version = "0.12", features = ["rt_tokio_1"] }
tokio-postgres = { version = "0.7", features = ["with-chrono-0_4"] }
digest = "0.10"
hmac = "0.12"
http = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sha2 = "0.10"
thiserror = "1.0"
argon2 = { version = "0.5", features = ["password-hash", "std"] }
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1", features = ["rt-multi-thread"]}
tokio-postgres = { version = "0.7", features = ["with-chrono-0_4"] }
tower = { version = "0.4", features = ["util"] }
tower-http = { version = "0.5", features = ["fs", "trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", default_features = false, features = ["std", "fmt", "ansi"] }
[dev-dependencies]
scraper = "0.18"

View File

@ -1,69 +0,0 @@
use {
crate::{
authentication::{authenticate_user, Password},
db::Database,
error::Error,
},
askama::Template,
askama_axum::{IntoResponse, Response},
axum::{
extract::State,
routing::{get, post},
Form, Router,
},
serde::Deserialize,
};
pub fn routes() -> Router<Database> {
Router::new()
.route("/", get(root))
.route("/create_initial_admin_user", post(create_first_admin_user))
}
#[derive(Template)]
#[template(path = "admin/create_first_user.html")]
struct CreateFirstUserTemplate {}
#[derive(Template)]
#[template(path = "admin/first_login.html")]
struct FirstLoginTemplate {}
#[derive(Template)]
#[template(path = "admin/index.html")]
struct IndexTemplate {}
async fn root(State(db): State<Database>) -> Result<Response, Error> {
Ok(if !db.has_admin_users().await? {
CreateFirstUserTemplate {}.into_response()
} else {
IndexTemplate {}.into_response()
})
}
#[derive(Deserialize)]
struct CreateFirstUserParameters {
real_name: String,
email: String,
password: String,
}
async fn create_first_admin_user(
State(db): State<Database>,
Form(params): Form<CreateFirstUserParameters>,
) -> Result<FirstLoginTemplate, Error> {
let user = db
.create_first_admin_user(
&params.real_name,
&params.email,
&Password::new(&params.password)?.into(),
)
.await?;
if let Some(_user) = authenticate_user(&db, user, &params.password).await? {
// Store cookie and display configuration page
todo!();
} else {
// Report failure
todo!();
}
Ok(FirstLoginTemplate {})
}

238
src/app/admin.rs Normal file
View File

@ -0,0 +1,238 @@
use {
crate::{
authentication::{
authenticate_user_with_jwt, authenticate_user_with_password, check_if_user_is_admin,
create_jwt_for_user, AuthenticatedAdminUser, ParsedJwt, Password,
},
db::Database,
error::Error,
},
askama::Template,
askama_axum::{IntoResponse, Response},
axum::{
extract::{NestedPath, State},
response::Redirect,
routing::{get, post},
Form, Router,
},
axum_extra::extract::{
cookie::{Cookie, SameSite},
CookieJar,
},
serde::Deserialize,
};
use super::AppState;
pub fn routes<D: Database>() -> Router<AppState<D>> {
Router::new()
.route("/", get(root))
.route("/create_first_admin_user", get(get_create_first_admin_user))
.route(
"/create_first_admin_user",
post(post_create_first_admin_user),
)
}
#[derive(Template)]
#[template(path = "admin/create_first_user.html")]
struct CreateFirstUserTemplate {}
#[derive(Template)]
#[template(path = "admin/first_login.html")]
struct FirstLoginTemplate {}
#[derive(Template)]
#[template(path = "admin/index.html")]
struct IndexTemplate<'a> {
admin_user_name: &'a str,
}
async fn check_jwt<D: Database>(
db: &D,
cookie_jar: &CookieJar,
) -> Result<AuthenticatedAdminUser, Error> {
match authenticate_user_with_jwt(
db,
cookie_jar
.get("jwt")
.map(|cookie| cookie.value_trimmed())
.ok_or(Error::Forbidden)?,
)
.await?
{
ParsedJwt::Valid(user) => check_if_user_is_admin(db, &user)
.await?
.ok_or(Error::Forbidden),
ParsedJwt::InvalidSignature => Err(Error::Forbidden),
ParsedJwt::UserNotFound => Err(Error::Forbidden),
ParsedJwt::Expired(user) => Err(Error::JwtExpired(user)),
}
}
#[tracing::instrument]
async fn root<D: Database>(
cookie_jar: CookieJar,
State(AppState { db, .. }): State<AppState<D>>,
path: NestedPath,
) -> Result<Response, Error> {
Ok(if !db.has_admin_users().await? {
Redirect::temporary(&format!("{}/create_first_admin_user", path.as_str())).into_response()
} else {
let admin_user = check_jwt(&db, &cookie_jar).await?;
IndexTemplate {
admin_user_name: &admin_user.real_name,
}
.into_response()
})
}
#[tracing::instrument]
async fn get_create_first_admin_user() -> CreateFirstUserTemplate {
CreateFirstUserTemplate {}
}
#[derive(Deserialize, Debug)]
struct CreateFirstUserParameters {
real_name: String,
email: String,
password: String,
}
#[tracing::instrument]
async fn post_create_first_admin_user<D: Database>(
cookie_jar: CookieJar,
State(AppState::<D> { db, .. }): State<AppState<D>>,
Form(params): Form<CreateFirstUserParameters>,
) -> Result<(CookieJar, FirstLoginTemplate), Error> {
let user = db
.create_first_admin_user(
&params.real_name,
&params.email,
&Password::new(&params.password)?.into(),
)
.await?;
let user = authenticate_user_with_password(&db, user, &params.password)
.await?
.ok_or(Error::Unexpected(
"Could not authenticate newly-created user.".to_string(),
))?;
Ok((
cookie_jar
.add(Cookie::build(("jwt", create_jwt_for_user(&user)?)).same_site(SameSite::Strict)),
FirstLoginTemplate {},
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{app::AppState, db::fake::FakeDatabase};
use {
axum::{
body,
body::Body,
http::{Request, StatusCode},
},
scraper::{Html, Selector},
tower::{Service, ServiceExt},
};
#[tokio::test]
async fn root_redirects_when_no_admin_users() {
let app = Router::new()
.nest("/test_admin", routes())
.with_state(AppState {
db: FakeDatabase::new_empty(),
});
let response = app
.oneshot(
Request::builder()
.method(http::Method::GET)
.uri("/test_admin")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::TEMPORARY_REDIRECT);
assert!(response.headers().contains_key("location"));
assert_eq!(
"/test_admin/create_first_admin_user",
response.headers()["location"]
);
}
#[tokio::test]
async fn create_first_admin_user() {
let mut app = Router::new()
.nest("/test_admin", routes())
.with_state(AppState {
db: FakeDatabase::new_empty(),
})
.into_service();
let request = Request::get("/test_admin/create_first_admin_user")
.body(Body::empty())
.unwrap();
let response = ServiceExt::<Request<Body>>::ready(&mut app)
.await
.unwrap()
.call(request)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = body::to_bytes(response.into_body(), 10000).await.unwrap();
let html = Html::parse_document(&String::from_utf8(body.into()).unwrap());
let form_selector = Selector::parse("form").unwrap();
let mut form_elements = html.select(&form_selector);
let form_element = form_elements.next().unwrap();
assert_eq!(0, form_elements.count());
assert_eq!(Some("create_first_admin_user"), form_element.attr("action"));
assert_eq!(Some("post"), form_element.attr("method"));
let input_selector = Selector::parse("input").unwrap();
let inputs: Vec<_> = form_element.select(&input_selector).collect();
assert_eq!(
1,
inputs
.iter()
.filter(|elem| elem.attr("name") == Some("real_name"))
.count()
);
assert_eq!(
1,
inputs
.iter()
.filter(|elem| elem.attr("name") == Some("email"))
.count()
);
assert_eq!(
1,
inputs
.iter()
.filter(|elem| elem.attr("name") == Some("password"))
.filter(|elem| elem.attr("type") == Some("password"))
.count()
);
let request = Request::post("/test_admin/create_first_admin_user")
.header(
http::header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.body(Body::from(
"real_name=Joe%20User&email=joe%40user.com&password=abc123",
))
.unwrap();
let response = ServiceExt::<Request<Body>>::ready(&mut app)
.await
.unwrap()
.call(request)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
}

View File

@ -4,8 +4,17 @@ use {
axum::{routing::get, Router},
};
pub fn routes() -> Router<Database> {
Router::new().route("/", get(root))
pub mod admin;
#[derive(Clone)]
pub struct AppState<D: Database> {
pub db: D,
}
pub fn routes<D: Database>() -> Router<AppState<D>> {
Router::new()
.route("/", get(root))
.nest("/admin", admin::routes())
}
#[derive(Template)]

View File

@ -1,95 +0,0 @@
use {
crate::{db, db::Database},
argon2::{
password_hash::{
rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString,
},
Argon2,
},
std::ops::Deref,
};
#[derive(thiserror::Error, Debug)]
pub enum AuthenticationError {
#[error("Could not get password hash from database: {}", .0.to_string())]
DatabaseError(#[from] db::Error),
#[error("{}", .0.to_string())]
HashError(#[from] argon2::password_hash::Error),
}
#[derive(Debug)]
pub struct AuthenticatedUser {
user: db::User,
}
impl Deref for AuthenticatedUser {
type Target = db::User;
fn deref(&self) -> &db::User {
&self.user
}
}
#[derive(Debug)]
pub struct AuthenticatedAdminUser {
user: db::User,
}
impl Deref for AuthenticatedAdminUser {
type Target = db::User;
fn deref(&self) -> &db::User {
&self.user
}
}
pub struct Password {
hash: String,
}
impl Password {
pub fn new(password: &str) -> Result<Password, AuthenticationError> {
let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
Ok(Password {
hash: argon2
.hash_password(password.as_bytes(), &salt)?
.to_string(),
})
}
pub fn check(&self, password: &str) -> Result<bool, AuthenticationError> {
let hash = PasswordHash::new(&self.hash)?;
Ok(Argon2::default()
.verify_password(password.as_bytes(), &hash)
.is_ok())
}
}
impl From<db::PasswordHash> for Password {
fn from(password: db::PasswordHash) -> Self {
Password {
hash: password.to_string(),
}
}
}
impl From<Password> for db::PasswordHash {
fn from(password: Password) -> Self {
db::PasswordHash(password.hash)
}
}
pub async fn authenticate_user(
db: &Database,
user: db::User,
supplied_password: &str,
) -> Result<Option<AuthenticatedUser>, AuthenticationError> {
let password: Password = db.get_password_for_user(&user).await?.into();
Ok(if password.check(supplied_password)? {
Some(AuthenticatedUser { user })
} else {
None
})
}

176
src/authentication/jwt.rs Normal file
View File

@ -0,0 +1,176 @@
use {
base64::engine::{general_purpose::STANDARD as base64_encoder, Engine as _},
chrono::{DateTime, Duration, Utc},
hmac::{Hmac, Mac},
serde::{Deserialize, Serialize},
sha2::Sha256,
tracing::{error, warn},
};
use {
super::AuthenticatedUser,
crate::config::get_config,
crate::db::{Database, User, UserId},
};
const COOKIE_EXPIRY_TIME: Duration = Duration::weeks(1);
#[derive(Debug)]
pub enum Error {
BadJwt,
#[allow(clippy::enum_variant_names)]
DatabaseError,
#[allow(clippy::enum_variant_names)]
HmacError,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Error::BadJwt => "BadJwt",
Error::DatabaseError => "DatabaseError",
Error::HmacError => "HmacError",
}
)
}
}
impl std::error::Error for Error {}
impl From<serde_json::Error> for Error {
fn from(value: serde_json::Error) -> Self {
warn!(details = value.to_string(), "JWT contained invalid JSON");
Error::BadJwt
}
}
impl From<base64::DecodeError> for Error {
fn from(value: base64::DecodeError) -> Self {
warn!(details = value.to_string(), "JWT contained invalid BASE64");
Error::BadJwt
}
}
impl From<std::string::FromUtf8Error> for Error {
fn from(value: std::string::FromUtf8Error) -> Self {
warn!(details = value.to_string(), "JWT contained invalid UTF-8");
Error::BadJwt
}
}
impl From<crate::db::Error> for Error {
fn from(value: crate::db::Error) -> Self {
error!(details = value.to_string(), "Database error");
Error::DatabaseError
}
}
impl From<digest::MacError> for Error {
fn from(_value: digest::MacError) -> Self {
error!("Bug in JWT HMAC code.");
Error::HmacError
}
}
type Result<T> = std::result::Result<T, Error>;
/// Result type for [authenticate_user_with_jwt()].
#[derive(Debug)]
pub enum ParsedJwt {
/// JWT is a valid JWT, here is the [AuthenticatedUser].
Valid(AuthenticatedUser),
/// JWT was valid but is expired
Expired(User),
/// JWT signature does not match contents
InvalidSignature,
/// JWT is valid, but the user id is not in the database
UserNotFound,
}
#[derive(Serialize, Deserialize)]
struct Header<'a> {
#[serde(rename = "alg")]
algorithm: &'a str,
#[serde(rename = "typ")]
token_type: &'a str,
}
#[derive(Serialize, Deserialize)]
struct Payload {
#[serde(rename = "sub")]
user_id: UserId,
#[serde(rename = "exp")]
expiry: DateTime<Utc>,
}
fn mac() -> Hmac<Sha256> {
Hmac::new_from_slice(&get_config().unwrap().hmac_secret)
.expect("HMAC can take key of any size.")
}
/// Given an [AuthenticatedUser], create a JWT for use as a cookie to
/// keep that user logged in.
#[tracing::instrument]
pub fn create_jwt_for_user(user: &AuthenticatedUser) -> Result<String> {
let header = base64_encoder.encode(
serde_json::to_string(&Header {
algorithm: "HS256",
token_type: "JWT",
})?
.as_bytes(),
);
let payload = base64_encoder.encode(
serde_json::to_string(&Payload {
user_id: user.get_id(),
expiry: Utc::now() + COOKIE_EXPIRY_TIME,
})?
.as_bytes(),
);
let mut mac = mac();
mac.update(format!("{}.{}", header, payload).as_bytes());
let signature = base64_encoder.encode(mac.finalize().into_bytes());
Ok(format!("{}.{}.{}", header, payload, signature))
}
/// Given JWT string created by [create_jwt_for_user()], check if the
/// JWT is valid and return an [AuthenticatedUser] if it is.
#[tracing::instrument]
pub async fn authenticate_user_with_jwt<D: Database>(db: &D, jwt: &str) -> Result<ParsedJwt> {
if let [header, payload, signature] = jwt.split('.').collect::<Vec<_>>().as_slice() {
let mut mac = mac();
mac.update(format!("{}.{}", header, payload).as_bytes());
if mac.verify_slice(signature.as_bytes()).is_err() {
Ok(ParsedJwt::InvalidSignature)
} else {
let header_json = String::from_utf8(base64_encoder.decode(header)?)?;
let header: Header = serde_json::from_str(&header_json)?;
if header.algorithm != "HS256" || header.token_type != "JWT" {
warn!("JWT does not have expected algorithm or type.");
Err(Error::BadJwt)
} else {
let payload: Payload =
serde_json::from_str(&String::from_utf8(base64_encoder.decode(payload)?)?)?;
Ok(dbg!(
if let Some(user) = db.get_user_with_id(payload.user_id).await? {
if payload.expiry < Utc::now() {
ParsedJwt::Valid(AuthenticatedUser(user))
} else {
ParsedJwt::Expired(user)
}
} else {
ParsedJwt::UserNotFound
},
))
}
}
} else {
warn!("Invalid JWT");
Err(Error::BadJwt)
}
}

140
src/authentication/mod.rs Normal file
View File

@ -0,0 +1,140 @@
use {
crate::{db, db::Database},
argon2::{
password_hash::{
rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString,
},
Argon2,
},
std::ops::Deref,
tracing::{error, warn},
};
mod jwt;
pub use jwt::{authenticate_user_with_jwt, create_jwt_for_user, Error as JwtError, ParsedJwt};
#[derive(Debug)]
pub enum AuthenticationError {
DatabaseError(db::Error),
HashError(argon2::password_hash::Error),
}
impl std::fmt::Display for AuthenticationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AuthenticationError::HashError(e) => write!(f, "{}", e),
AuthenticationError::DatabaseError(e) => {
write!(f, "Could not get password hash from database: {}", e)
}
}
}
}
impl std::error::Error for AuthenticationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
AuthenticationError::HashError(_) => None,
AuthenticationError::DatabaseError(e) => Some(e),
}
}
}
impl From<db::Error> for AuthenticationError {
fn from(value: db::Error) -> Self {
warn!(details = value.to_string(), "Database error");
AuthenticationError::DatabaseError(value)
}
}
impl From<argon2::password_hash::Error> for AuthenticationError {
fn from(value: argon2::password_hash::Error) -> Self {
error!(details = value.to_string(), "Error hashing password.");
AuthenticationError::HashError(value)
}
}
#[derive(Debug, Clone)]
pub struct AuthenticatedUser(db::User);
impl Deref for AuthenticatedUser {
type Target = db::User;
fn deref(&self) -> &db::User {
&self.0
}
}
#[derive(Debug)]
pub struct AuthenticatedAdminUser(db::User);
impl Deref for AuthenticatedAdminUser {
type Target = db::User;
fn deref(&self) -> &db::User {
&self.0
}
}
pub struct Password {
hash: String,
}
impl Password {
pub fn new(password: &str) -> Result<Password, AuthenticationError> {
let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
Ok(Password {
hash: argon2
.hash_password(password.as_bytes(), &salt)?
.to_string(),
})
}
pub fn check(&self, password: &str) -> Result<bool, AuthenticationError> {
let hash = PasswordHash::new(&self.hash)?;
Ok(Argon2::default()
.verify_password(password.as_bytes(), &hash)
.is_ok())
}
}
impl From<db::PasswordHash> for Password {
fn from(password: db::PasswordHash) -> Self {
Password {
hash: password.to_string(),
}
}
}
impl From<Password> for db::PasswordHash {
fn from(password: Password) -> Self {
db::PasswordHash(password.hash)
}
}
#[tracing::instrument]
pub async fn authenticate_user_with_password<D: Database>(
db: &D,
user: db::User,
supplied_password: &str,
) -> Result<Option<AuthenticatedUser>, AuthenticationError> {
let password: Password = db.get_password_for_user(&user).await?.into();
Ok(if password.check(supplied_password)? {
Some(AuthenticatedUser(user))
} else {
None
})
}
#[tracing::instrument]
pub async fn check_if_user_is_admin<D: Database>(
db: &D,
user: &AuthenticatedUser,
) -> Result<Option<AuthenticatedAdminUser>, db::Error> {
if db.is_user_admin(user).await? {
Ok(Some(AuthenticatedAdminUser(user.0.clone())))
} else {
Ok(None)
}
}

View File

@ -11,6 +11,7 @@ pub enum Error {
pub struct Config {
pub database_url: String,
pub static_file_path: String,
pub hmac_secret: Vec<u8>,
}
fn get_config_string(variable: &str) -> Result<String, Error> {
@ -22,5 +23,6 @@ pub fn get_config() -> Result<Config, Error> {
Ok(Config {
database_url: get_config_string("DATABASE_URL")?,
static_file_path: get_config_string("STATIC_FILE_PATH")?,
hmac_secret: get_config_string("HMAC_SECRET")?.into_bytes(),
})
}

128
src/db/fake.rs Normal file
View File

@ -0,0 +1,128 @@
use super::*;
use {
std::collections::HashSet,
std::sync::{Arc, Mutex},
};
#[derive(Debug)]
struct UserRow {
real_name: String,
email: String,
password_hash: String,
}
#[derive(Debug, Clone)]
pub struct FakeDatabase {
users: Arc<Mutex<Vec<UserRow>>>,
admin_users: Arc<Mutex<std::collections::HashSet<usize>>>,
}
impl FakeDatabase {
pub fn new_empty() -> Self {
FakeDatabase {
users: Arc::new(Mutex::new(Vec::new())),
admin_users: Arc::new(Mutex::new(HashSet::new())),
}
}
}
impl Database for FakeDatabase {
async fn migrate_to_current_version(&self) -> Result<()> {
Ok(())
}
async fn has_admin_users(&self) -> Result<bool> {
Ok(self.admin_users.lock().unwrap().len() > 0)
}
async fn create_user(
&self,
real_name: &str,
email: &str,
password: &PasswordHash,
) -> Result<User> {
let mut users = self.users.lock().unwrap();
users.push(UserRow {
real_name: real_name.to_string(),
email: email.to_string(),
password_hash: password.to_string(),
});
Ok(User {
id: UserId((users.len() - 1) as i32),
real_name: real_name.to_string(),
})
}
async fn get_password_for_user(&self, user: &User) -> Result<PasswordHash> {
let users = self.users.lock().unwrap();
if let Some(UserRow { password_hash, .. }) = users.get(user.id.0 as usize) {
Ok(PasswordHash(password_hash.clone()))
} else {
Err(Error::Database)
}
}
async fn create_first_admin_user(
&self,
real_name: &str,
email: &str,
password: &PasswordHash,
) -> Result<User> {
let user = self.create_user(real_name, email, password).await?;
let mut admin_users = self.admin_users.lock().unwrap();
admin_users.insert(user.id.0 as usize);
Ok(user)
}
async fn is_user_admin(&self, user: &User) -> Result<bool> {
let admin_users = self.admin_users.lock().unwrap();
Ok(admin_users.contains(&(user.id.0 as usize)))
}
async fn get_user_with_id(&self, user_id: UserId) -> Result<Option<User>> {
let users = self.users.lock().unwrap();
Ok(users
.get(user_id.0 as usize)
.map(|UserRow { real_name, .. }| User {
id: user_id,
real_name: real_name.clone(),
}))
}
}
mod tests {
use super::*;
#[tokio::test]
async fn store_user() {
let target = FakeDatabase::new_empty();
let user = target
.create_user(
"Jane Doe",
"jane.doe@example.com",
&PasswordHash("iamjane!".to_string()),
)
.await
.unwrap();
let saved_user = target.get_user_with_id(user.id).await.unwrap().unwrap();
assert_eq!(user.id, saved_user.id);
assert_eq!(user.real_name, saved_user.real_name);
}
#[tokio::test]
async fn store_user_password() {
let target = FakeDatabase::new_empty();
let user = target
.create_user(
"Jane Doe",
"jane.doe@example.com",
&PasswordHash("iamjane!".to_string()),
)
.await
.unwrap();
let saved_password = target.get_password_for_user(&user).await.unwrap();
assert_eq!("iamjane!", saved_password.0);
}
}

View File

@ -12,7 +12,7 @@
//! needed to that the database schema version (as returned by
//! [get_db_version()]) matches [CURRENT_VERSION].
use super::{Database, Error};
use super::{Error, PostgresDatabase};
/// Defines a database schema migration
#[derive(Debug)]
@ -72,8 +72,8 @@ static MIGRATIONS: &[Migration] = &[
ALTER TABLE users DROP COLUMN IF EXISTS password_salt;
ALTER TABLE users DROP COLUMN IF EXISTS password_hash;
ALTER TABLE users ADD COLUMN password TEXT NOT NULL;"#,
down: "ALTER TABLE users DROP COLUMN password;"
}
down: "ALTER TABLE users DROP COLUMN password;",
},
];
/// The current schema version. Normally this will be the
@ -92,7 +92,7 @@ static CURRENT_VERSION: i32 = 2;
/// E.g. If [CURRENT_VERSION] is 10 but the database is on version 4,
/// then running this function will apply [Migration] 5 to bring the
/// database up to schema version 5.
async fn migrate_up(db: &Database) -> Result<i32, Error> {
async fn migrate_up(db: &PostgresDatabase) -> Result<i32, Error> {
let current_version = get_db_version(db).await?;
if let Some(migration) = MIGRATIONS.iter().find(|m| m.version > current_version) {
let client = db.connection_pool.get().await?;
@ -114,7 +114,7 @@ async fn migrate_up(db: &Database) -> Result<i32, Error> {
/// Revert back to the previous schema version by running the
/// [down](Migration::down) SQL of the current `Migration`
async fn migrate_down(db: &Database) -> Result<i32, Error> {
async fn migrate_down(db: &PostgresDatabase) -> Result<i32, Error> {
let current_version = get_db_version(db).await?;
let mut migration_iter = MIGRATIONS
.iter()
@ -141,7 +141,7 @@ async fn migrate_down(db: &Database) -> Result<i32, Error> {
/// Apply whatever migrations are necessary to bring the database
/// schema to the same version is [CURRENT_VERSION].
pub async fn migrate_to_current_version(db: &Database) -> Result<(), Error> {
pub async fn migrate_to_current_version(db: &PostgresDatabase) -> Result<(), Error> {
migrate_to_version(db, CURRENT_VERSION).await
}
@ -149,7 +149,7 @@ pub async fn migrate_to_current_version(db: &Database) -> Result<(), Error> {
/// schema to the same version as `target_version`.
///
/// This may migrate up or down as required.
async fn migrate_to_version(db: &Database, target_version: i32) -> Result<(), Error> {
async fn migrate_to_version(db: &PostgresDatabase, target_version: i32) -> Result<(), Error> {
let mut version = get_db_version(db).await?;
while version != target_version {
if version < target_version {
@ -162,7 +162,7 @@ async fn migrate_to_version(db: &Database, target_version: i32) -> Result<(), Er
}
/// Get the current schema version of the database.
pub async fn get_db_version(db: &Database) -> Result<i32, Error> {
pub async fn get_db_version(db: &PostgresDatabase) -> Result<i32, Error> {
let client = db.connection_pool.get().await?;
client
.execute(
@ -195,12 +195,12 @@ pub async fn get_db_version(db: &Database) -> Result<i32, Error> {
#[cfg(test)]
mod tests {
use super::super::Database;
use super::super::PostgresDatabase;
use super::*;
async fn test_db() -> Database {
async fn test_db() -> PostgresDatabase {
let url = std::env::var("LOCALITY_TEST_DATABASE_URL").unwrap();
Database::new(&url)
PostgresDatabase::new(&url)
.unwrap()
.connection_pool
.get()
@ -217,7 +217,7 @@ mod tests {
)
.await
.unwrap();
Database::new(&url).unwrap()
PostgresDatabase::new(&url).unwrap()
}
#[test]

View File

@ -5,49 +5,140 @@
mod migrations;
#[cfg(test)]
pub mod fake;
use {
deadpool_postgres::{CreatePoolError, Pool, Runtime},
serde::{Deserialize, Serialize},
std::{future::Future, ops::Deref},
tokio_postgres::NoTls,
std::ops::Deref
tracing::error,
};
/// Errors that may occur during module initialization
#[derive(thiserror::Error, Debug)]
#[derive(Debug)]
pub enum InitialisationError {
#[error("Could not initialize DB connection pool: {}", .0.to_string())]
ConnectionPoolError(#[from] CreatePoolError),
ConnectionPoolError(CreatePoolError),
}
impl std::fmt::Display for InitialisationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
InitialisationError::ConnectionPoolError(e) => {
write!(f, "Could not initialise DB connection pool: {}", e)
}
}
}
}
impl std::error::Error for InitialisationError {}
impl From<CreatePoolError> for InitialisationError {
fn from(value: CreatePoolError) -> Self {
InitialisationError::ConnectionPoolError(value)
}
}
pub type InitialisationResult<T> = std::result::Result<T, InitialisationError>;
/// Errors that may occur during normal app operation
#[derive(thiserror::Error, Debug)]
#[derive(Debug)]
pub enum Error {
#[error("{}", .0.to_string())]
Pool(#[from] deadpool_postgres::PoolError),
Pool(deadpool_postgres::PoolError),
Database,
NotAllowed,
}
#[error("{}", .0.to_string())]
Postgres(#[from] tokio_postgres::Error),
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Pool(e) => e.fmt(f),
Error::Database => write!(f, "Database Error"),
Error::NotAllowed => write!(f, "Not Allowed"),
}
}
}
#[error("Not allowed.")]
NotAllowed
impl std::error::Error for Error {}
impl From<deadpool_postgres::PoolError> for Error {
fn from(value: deadpool_postgres::PoolError) -> Self {
error!(
details = value.to_string(),
"Error with deadpool_postgress connection pool"
);
Self::Pool(value)
}
}
impl From<tokio_postgres::Error> for Error {
fn from(value: tokio_postgres::Error) -> Self {
error!(
details = value
.as_db_error()
.and_then(|db_error| db_error.detail())
.unwrap_or(&value.to_string()),
"PostgreSQL error"
);
Error::Database
}
}
pub type Result<T> = std::result::Result<T, Error>;
pub trait Database: std::fmt::Debug + Clone + Send + Sync + 'static {
/// Run migrations as needed to ensure the database schema version
/// match the one used by the current version of the application.
fn migrate_to_current_version(&self) -> impl Future<Output = Result<()>> + Send;
fn has_admin_users(&self) -> impl Future<Output = Result<bool>> + Send;
fn create_user(
&self,
real_name: &str,
email: &str,
password: &PasswordHash,
) -> impl Future<Output = Result<User>> + Send;
fn get_password_for_user(
&self,
user: &User,
) -> impl Future<Output = Result<PasswordHash>> + Send;
fn create_first_admin_user(
&self,
real_name: &str,
email: &str,
password: &PasswordHash,
) -> impl Future<Output = Result<User>> + Send;
fn is_user_admin(&self, user: &User) -> impl Future<Output = Result<bool>> + Send;
fn get_user_with_id(
&self,
user_id: UserId,
) -> impl Future<Output = Result<Option<User>>> + Send;
}
/// Object that manages the database.
///
/// All database access happens through this struct.
#[derive(Clone, Debug)]
pub struct Database {
pub struct PostgresDatabase {
connection_pool: Pool,
}
#[derive(Debug)]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct UserId(i32);
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct User {
id: UserId,
pub real_name: String,
}
impl User {
pub fn get_id(&self) -> UserId {
self.id
}
}
#[derive(Debug)]
pub struct PasswordHash(pub String);
impl Deref for PasswordHash {
@ -58,28 +149,31 @@ impl Deref for PasswordHash {
}
}
impl Database {
impl PostgresDatabase {
/// Create a connection pool and return the [Database].
pub fn new(connection_url: &str) -> Result<Database, InitialisationError> {
pub fn new(connection_url: &str) -> InitialisationResult<PostgresDatabase> {
let mut config = deadpool_postgres::Config::new();
config.url = Some(connection_url.to_string());
let pg_pool = config.create_pool(Some(Runtime::Tokio1), NoTls)?;
Ok(Database {
Ok(PostgresDatabase {
connection_pool: pg_pool,
})
}
async fn get_client(&self) -> Result<deadpool_postgres::Client> {
Ok(self.connection_pool.get().await?)
}
}
impl Database for PostgresDatabase {
/// Run migrations as needed to ensure the database schema version
/// match the one used by the current version of the application.
pub async fn migrate_to_current_version(&self) -> Result<(), Error> {
async fn migrate_to_current_version(&self) -> Result<()> {
migrations::migrate_to_current_version(self).await
}
async fn get_client(&self) -> Result<deadpool_postgres::Client, Error> {
Ok(self.connection_pool.get().await?)
}
pub async fn has_admin_users(&self) -> Result<bool, Error> {
#[tracing::instrument]
async fn has_admin_users(&self) -> Result<bool> {
let client = self.get_client().await?;
Ok(client
.query_one("SELECT EXISTS(SELECT 1 FROM admin_users);", &[])
@ -87,19 +181,20 @@ impl Database {
.get(0))
}
pub async fn create_user(
#[tracing::instrument]
async fn create_user(
&self,
real_name: &str,
email: &str,
password: &PasswordHash,
) -> Result<User, Error> {
) -> Result<User> {
let client = self.get_client().await?;
let id = client
.query_one(
r#"
INSERT INTO users
(real_name, email, password)
VALUES $1, $1, $3, $4
VALUES ($1, $2, $3)
RETURNING id;"#,
&[&real_name, &email, &password.0],
)
@ -111,34 +206,56 @@ impl Database {
})
}
pub async fn get_password_for_user(&self, user: &User) -> Result<PasswordHash, Error> {
#[tracing::instrument]
async fn get_password_for_user(&self, user: &User) -> Result<PasswordHash> {
let client = self.get_client().await?;
let row = client
.query_one(
"SELECT password FROM users WHERE id = $1;",
&[&user.id.0],
)
.query_one("SELECT password FROM users WHERE id = $1;", &[&user.id.0])
.await?;
Ok(PasswordHash(row.get(0)))
}
pub async fn create_first_admin_user(
#[tracing::instrument]
async fn create_first_admin_user(
&self,
real_name: &str,
email: &str,
password: &PasswordHash,
) -> Result<User, Error> {
) -> Result<User> {
if self.has_admin_users().await? {
return Err(Error::NotAllowed)
return Err(Error::NotAllowed);
}
let user = self.create_user(real_name, email, password).await?;
let client = self.get_client().await?;
client
.execute("INSERT INTO admin_users (id) VALUES $1", &[&user.id.0])
.execute("INSERT INTO admin_users (id) VALUES ($1)", &[&user.id.0])
.await?;
Ok(User {
id: user.id,
real_name: user.real_name,
})
}
#[tracing::instrument]
async fn is_user_admin(&self, user: &User) -> Result<bool> {
Ok(self
.get_client()
.await?
.query_opt("SELECT 1 FROM admin_users WHERE id = $1;", &[&user.id.0])
.await?
.is_some())
}
#[tracing::instrument]
async fn get_user_with_id(&self, user_id: UserId) -> Result<Option<User>> {
Ok(self
.get_client()
.await?
.query_opt("SELECT real_name FROM users WHERE id = $1;", &[&user_id.0])
.await?
.map(|row| User {
id: user_id,
real_name: row.get(0),
}))
}
}

View File

@ -1,34 +1,69 @@
use {
crate::{authentication, db},
askama::Template,
askama_axum::{IntoResponse, Response},
http::status::StatusCode,
tracing::{error, warn},
};
#[allow(clippy::enum_variant_names)]
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Database Error: {}", 0.to_string())]
DatabaseError(#[from] db::Error),
#[error("Authentication error")]
AuthenticationError(#[from] authentication::AuthenticationError)
AuthenticationError(#[from] authentication::AuthenticationError),
#[error("Unexpected error: {}", .0)]
Unexpected(String),
#[error("Forbidden")]
Forbidden,
#[error("JWT Expired")]
JwtExpired(db::User),
#[error("JWT Error")]
JwtError(#[from] authentication::JwtError),
}
#[derive(Template)]
#[template(path = "error.html")]
struct ErrorTemplate<'a> {
title: &'a str,
}
impl IntoResponse for Error {
fn into_response(self) -> Response {
match self {
Error::DatabaseError(db::Error::Pool(pool_error)) => {
eprintln!("Database connection pool error: {}", pool_error);
todo!()
}
Error::DatabaseError(db::Error::Postgres(postgres_error)) => {
eprintln!("Database error: {}", postgres_error);
todo!()
}
Error::DatabaseError(db::Error::NotAllowed) => {
todo!()
Error::DatabaseError(_) => {
error!("Uncaught database error producing HTTP 500.");
(
StatusCode::INTERNAL_SERVER_ERROR,
ErrorTemplate { title: "Error" },
)
.into_response()
}
Error::AuthenticationError(_) => {
error!("Uncaught authentication error producing HTTP 500.");
(
StatusCode::INTERNAL_SERVER_ERROR,
ErrorTemplate { title: "Error" },
)
.into_response()
}
Error::Unexpected(_) => {
todo!()
}
Error::Forbidden => (StatusCode::UNAUTHORIZED, "User not authorized.").into_response(),
Error::JwtExpired(_) => {
todo!()
}
Error::JwtError(jwt_error) => {
warn!(detail = jwt_error.to_string(), "Checking JWT");
(StatusCode::UNAUTHORIZED, ErrorTemplate { title: "Error" }).into_response()
}
}
}
}

View File

@ -1,14 +1,17 @@
use {thiserror::Error, tower_http::services::ServeDir};
use {
thiserror::Error,
tower_http::{services::ServeDir, trace::TraceLayer},
tracing::Level,
};
mod admin;
mod authentication;
mod app;
mod authentication;
mod config;
mod db;
mod error;
use config::get_config;
use db::Database;
use db::{Database, PostgresDatabase};
#[derive(Error, Debug)]
pub enum Error {
@ -20,6 +23,9 @@ pub enum Error {
#[error("{0}")]
IOError(#[from] std::io::Error),
#[error("{0}")]
TracingError(#[from] tracing::subscriber::SetGlobalDefaultError),
}
fn main() {
@ -36,14 +42,20 @@ fn main() {
async fn locality_main() -> Result<(), Error> {
let config = get_config()?;
let db_pool = Database::new(&config.database_url)?;
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.pretty()
.with_max_level(Level::DEBUG)
.finish();
tracing::subscriber::set_global_default(subscriber)?;
let db_pool = PostgresDatabase::new(&config.database_url)?;
db_pool.migrate_to_current_version().await.unwrap();
let app = app::routes()
.nest("/admin", admin::routes())
.with_state(db_pool)
.nest_service("/static", ServeDir::new(&config.static_file_path));
.with_state(app::AppState { db: db_pool })
.nest_service("/static", ServeDir::new(&config.static_file_path))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
axum::serve(listener, app).await?;

View File

@ -4,7 +4,7 @@
{% block content %}
<h1>Please create an administrator account:</h1>
<form action="/create-initial-admin-user" method="post">>
<form action="create_first_admin_user" method="post">>
<ul>
<li>
<label for="real_name">Name:</label>

View File

@ -2,4 +2,4 @@
{% block title %}Locality Administration{% endblock %}
{% block content %}admin{% endblock %}
{% block content %}{{admin_user_name}}{% endblock %}

View File

@ -5,15 +5,15 @@
<meta name="viewport" content="width=device-width" />
<title>{% block title %}{{title}} - Locality{% endblock %}</title>
<link rel="icon" type="image/png" sizes="32x32" href="static/favicon-32.png">
<link rel="icon" type="image/png" sizes="16x16" href="static/favicon-16.png">
<link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16.png">
<!-- For Google and Android -->
<link rel="icon" type="image/png" sizes="48x48" href="static/favicon-48.png">
<link rel="icon" type="image/png" sizes="192x192" href="static/favicon-192.png">
<link rel="icon" type="image/png" sizes="48x48" href="/static/favicon-48.png">
<link rel="icon" type="image/png" sizes="192x192" href="/static/favicon-192.png">
<!-- For iPad -->
<link rel="apple-touch-icon" type="image/png" sizes="167x167" href="static/favicon-167.png">
<link rel="apple-touch-icon" type="image/png" sizes="167x167" href="/static/favicon-167.png">
<!-- For iPhone -->
<link rel="apple-touch-icon" type="image/png" sizes="180x180" href="static/favicon-180.png">
<link rel="apple-touch-icon" type="image/png" sizes="180x180" href="/static/favicon-180.png">
{% block head %}{% endblock %}
</head>

3
templates/error.html Normal file
View File

@ -0,0 +1,3 @@
{% extends "base.html" %}
{% block content %}Something went wrong. Please try again later.{% endblock %}