1
0
Fork 0
forked from TWS/kalkutago

Compare commits

..

3 commits

13 changed files with 339 additions and 3 deletions

View file

@ -65,6 +65,8 @@ services:
secrets:
postgres-password:
file: ./server/postgres.pw
cookie-secret:
file: ./server/cookie-secret.pw
networks:
internal:

View file

@ -32,6 +32,8 @@ services:
secrets:
postgres-password:
file: ./server/postgres.pw
cookie-secret:
file: ./server/cookie-secret.pw
networks:
internal:

138
server/Cargo.lock generated
View file

@ -8,6 +8,41 @@ version = "0.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3"
[[package]]
name = "aead"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
dependencies = [
"crypto-common",
"generic-array",
]
[[package]]
name = "aes"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "433cfd6710c9986c576a25ca913c39d66a6474107b406f34f91d4a8923395241"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
]
[[package]]
name = "aes-gcm"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "209b47e8954a928e1d72e86eca7000ebb6655fe1436d33eefc2201cad027e237"
dependencies = [
"aead",
"aes",
"cipher",
"ctr",
"ghash",
"subtle",
]
[[package]]
name = "ahash"
version = "0.7.6"
@ -142,6 +177,19 @@ version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d"
[[package]]
name = "bcrypt"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9df288bec72232f78c1ec5fe4e8f1d108aa0265476e93097593c803c8c02062a"
dependencies = [
"base64 0.21.2",
"blowfish",
"getrandom",
"subtle",
"zeroize",
]
[[package]]
name = "bigdecimal"
version = "0.3.1"
@ -192,6 +240,16 @@ dependencies = [
"generic-array",
]
[[package]]
name = "blowfish"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7"
dependencies = [
"byteorder",
"cipher",
]
[[package]]
name = "borsh"
version = "0.10.3"
@ -305,6 +363,16 @@ dependencies = [
"winapi",
]
[[package]]
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "clap"
version = "3.2.25"
@ -347,7 +415,13 @@ version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7efb37c3e1ccb1ff97164ad95ac1606e8ccd35b3fa0a7d99a304c7f4a428cc24"
dependencies = [
"aes-gcm",
"base64 0.21.2",
"hkdf",
"percent-encoding",
"rand",
"sha2",
"subtle",
"time 0.3.22",
"version_check",
]
@ -393,9 +467,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
"rand_core",
"typenum",
]
[[package]]
name = "ctr"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
dependencies = [
"cipher",
]
[[package]]
name = "darling"
version = "0.14.4"
@ -756,6 +840,16 @@ dependencies = [
"wasi 0.11.0+wasi-snapshot-preview1",
]
[[package]]
name = "ghash"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d930750de5717d2dd0b8c0d42c076c0e884c81a73e6cab859bbd2339c71e3e40"
dependencies = [
"opaque-debug",
"polyval",
]
[[package]]
name = "glob"
version = "0.3.1"
@ -989,6 +1083,15 @@ version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb"
[[package]]
name = "inout"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5"
dependencies = [
"generic-array",
]
[[package]]
name = "instant"
version = "0.1.12"
@ -1049,6 +1152,7 @@ dependencies = [
name = "kalkutago-server"
version = "0.1.0"
dependencies = [
"bcrypt",
"chrono",
"derive_builder",
"either",
@ -1249,6 +1353,12 @@ version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
[[package]]
name = "opaque-debug"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"
[[package]]
name = "os_str_bytes"
version = "6.5.1"
@ -1379,6 +1489,18 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "polyval"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ef234e08c11dfcb2e56f79fd70f6f2eb7f025c0ce2333e82f4f0518ecad30c6"
dependencies = [
"cfg-if",
"cpufeatures",
"opaque-debug",
"universal-hash",
]
[[package]]
name = "ppv-lite86"
version = "0.2.17"
@ -2699,6 +2821,16 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"
[[package]]
name = "universal-hash"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
dependencies = [
"crypto-common",
"subtle",
]
[[package]]
name = "untrusted"
version = "0.7.1"
@ -3010,3 +3142,9 @@ name = "yansi"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec"
[[package]]
name = "zeroize"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a0956f1ba7c7909bfb66c2e9e4124ab6f6482560f6628b5aaeba39207c9aad9"

View file

@ -13,6 +13,7 @@ path = "src/main.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bcrypt = "0.14.0"
chrono = "0.4.26"
femme = "2.2.1"
log = { version = "0.4.19", features = ["kv_unstable", "kv_unstable_serde"] }
@ -40,7 +41,7 @@ features = [
[dependencies.rocket]
git = "https://github.com/SergioBenitez/Rocket"
rev = "v0.5.0-rc.3"
features = ["json"]
features = ["json", "secrets"]
[dependencies.serde]
version = "1.0.163"

73
server/src/api/auth.rs Normal file
View file

@ -0,0 +1,73 @@
use log::warn;
use rocket::{
http::{Cookie, CookieJar, Status},
outcome::IntoOutcome,
request::{self, FromRequest},
serde::json::Json,
Request, State,
};
use sea_orm::{prelude::*, DatabaseConnection};
use serde::Deserialize;
use crate::{
api::error::ApiResult,
entities::{prelude::*, *},
error::Error,
};
#[derive(Clone, Deserialize)]
pub(super) struct LoginData {
name: String,
password: String,
}
#[put("/", data = "<user_data>", format = "application/json")]
pub(super) async fn login(
db: &State<DatabaseConnection>,
user_data: Json<LoginData>,
cookies: &CookieJar<'_>,
) -> ApiResult<Status> {
let users = User::find()
.filter(user::Column::Name.eq(&user_data.name))
.all(db as &DatabaseConnection)
.await
.map_err(Error::from)?;
if users.len() > 1 {
warn!(count = users.len(), name = &user_data.name; "multiple entries found in database for user");
}
let Some(user) = users.get(0) else {
return Ok(Status::Unauthorized);
};
cookies.add_private(Cookie::new("user_id", user.id.to_string()));
Ok(Status::Ok)
}
#[post("/", data = "<user_data>", format = "application/json")]
pub(super) async fn sign_up(
db: &State<DatabaseConnection>,
user_data: Json<LoginData>,
cookies: &CookieJar<'_>,
) -> ApiResult<()> {
let user_data = user::ActiveModel::new(&user_data.name, &user_data.password)?
.insert(db as &DatabaseConnection)
.await
.map_err(Error::from)?;
cookies.add_private(Cookie::new("user_id", user_data.id.to_string()));
Ok(())
}
/// Authentication guard
struct Auth(i32);
#[rocket::async_trait]
impl<'r> FromRequest<'r> for Auth {
type Error = ();
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
request
.cookies()
.get_private("user_id")
.and_then(|val| val.value().parse().ok())
.map(|id| Auth(id))
.into_outcome((Status::Unauthorized, ()))
}
}

View file

@ -2,11 +2,11 @@ use crate::error::Error;
#[derive(Responder)]
#[response(status = 500, content_type = "json")]
pub(crate) struct ErrorResponder {
pub struct ErrorResponder {
message: String,
}
pub(crate) type ApiResult<T> = Result<T, ErrorResponder>;
pub type ApiResult<T> = Result<T, ErrorResponder>;
// The following impl's are for easy conversion of error types.

View file

@ -1,3 +1,4 @@
mod auth;
mod error;
mod groups;
#[cfg(feature = "unsafe_import")]
@ -8,11 +9,13 @@ pub(crate) mod update;
use std::{
default::default,
env, fs,
net::{IpAddr, Ipv4Addr},
};
use crate::error::Error;
use rocket::{
config::SecretKey,
fs::{FileServer, NamedFile},
response::stream::EventStream,
routes, Build, Config, Rocket, State,
@ -61,6 +64,16 @@ async fn spa_index_redirect() -> ApiResult<NamedFile> {
.map_err(Error::from)?)
}
fn get_secret() -> [u8; 32] {
let path =
env::var("COOKIE_SECRET_FILE").unwrap_or_else(|_| "/run/secrets/cookie-secret".into());
let file_contents =
fs::read(&path).unwrap_or_else(|err| panic!("failed to read from {path:?}: {err:?}"));
let mut data = [0u8; 32];
data.copy_from_slice(&file_contents);
data
}
pub(crate) fn start_server(db: DatabaseConnection) -> Rocket<Build> {
use groups::*;
use ticks::*;
@ -69,6 +82,7 @@ pub(crate) fn start_server(db: DatabaseConnection) -> Rocket<Build> {
let it = rocket::build()
.configure(Config {
address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
secret_key: SecretKey::derive_from(&get_secret()),
..default()
})
.register("/", catchers![spa_index_redirect])
@ -98,6 +112,7 @@ pub(crate) fn start_server(db: DatabaseConnection) -> Rocket<Build> {
"/api/v1/groups",
routes![all_groups, group, insert_group, update_group, delete_group],
)
.mount("/api/v1/auth", routes![auth::login, auth::sign_up])
.mount("/", FileServer::from("/src/public"));
#[cfg(feature = "unsafe_import")]

View file

@ -6,3 +6,4 @@ pub mod groups;
pub mod ticks;
pub mod track2_groups;
pub mod tracks;
pub mod user;

View file

@ -4,3 +4,4 @@ pub use super::groups::Entity as Groups;
pub use super::ticks::Entity as Ticks;
pub use super::track2_groups::Entity as Track2Groups;
pub use super::tracks::Entity as Tracks;
pub use super::user::Entity as User;

View file

@ -0,0 +1,56 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.3
use std::default::default;
use bcrypt::*;
// TODO Add option for argon2 https://docs.rs/argon2/latest/argon2/
use either::Either::{self, Left, Right};
use rocket::response::status::Unauthorized;
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{
api::ErrorResponder,
error::{self, Error},
};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "user")]
pub struct Model {
#[sea_orm(primary_key)]
#[serde(skip_deserializing)]
pub id: i32,
pub name: String,
pub password_hash: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
impl ActiveModel {
pub fn new(name: impl AsRef<str>, password: impl AsRef<str>) -> error::Result<Self> {
use sea_orm::ActiveValue::Set;
let name = Set(name.as_ref().to_string());
let password_hash = Set(hash(password.as_ref(), DEFAULT_COST + 2)?);
Ok(Self {
name,
password_hash,
..default()
})
}
}
impl Model {
pub fn check_password(
self,
password: String,
) -> std::result::Result<Self, Either<Unauthorized<()>, ErrorResponder>> {
match verify(password, &self.password_hash) {
Ok(true) => Ok(self),
Ok(false) => Err(Left(Unauthorized(None))),
Err(err) => Err(Right(Error::from(err).into())),
}
}
}

View file

@ -1,5 +1,6 @@
use std::string;
use bcrypt::BcryptError;
use derive_builder::UninitializedFieldError;
#[derive(Debug, thiserror::Error)]
@ -18,6 +19,8 @@ pub enum Error {
Utf8(#[from] string::FromUtf8Error),
#[error(transparent)]
ChannelSendError(#[from] tokio::sync::broadcast::error::SendError<crate::api::update::Update>),
#[error(transparent)]
Bcrypt(#[from] BcryptError),
}
pub type Result<T> = std::result::Result<T, Error>;

View file

@ -0,0 +1,42 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(User::Table)
.if_not_exists()
.col(
ColumnDef::new(User::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(User::Name).string().not_null())
.col(ColumnDef::new(User::PasswordHash).string().not_null())
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(User::Table).to_owned())
.await
}
}
/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
enum User {
Table,
Id,
Name,
PasswordHash,
}

View file

@ -2,6 +2,7 @@ mod m20230606_000001_create_tracks_table;
mod m20230606_000002_create_ticks_table;
mod m20230606_000003_create_groups_table;
mod m20230606_000004_create_track2groups_table;
mod m20230626_083036_create_users_table;
use sea_orm_migration::prelude::*;
@ -15,6 +16,7 @@ impl MigratorTrait for Migrator {
Box::new(m20230606_000002_create_ticks_table::Migration),
Box::new(m20230606_000003_create_groups_table::Migration),
Box::new(m20230606_000004_create_track2groups_table::Migration),
Box::new(m20230626_083036_create_users_table::Migration),
]
}
}