factoriauth/src/main.rs

111 lines
3 KiB
Rust

/*
factoriauth - An unofficial authentication server for Factorio
Copyright (C) 2024 lambda@xiretza.xyz
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#![warn(clippy::pedantic, clippy::as_conversions)]
#![forbid(unsafe_code)]
mod auth;
mod config;
mod db;
mod secrets;
mod server;
use std::sync::Arc;
use auth::{
AuthenticationBackend, ServerPadlockGenerator, UserAuthenticator, UserServerKeyGenerator,
};
use clap::Parser;
use color_eyre::Result;
use config::Config;
use db::{Database, SqliteDatabase};
use tokio::sync::Mutex;
use tracing::{event, instrument, Level};
use tracing_error::ErrorLayer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
#[instrument]
fn init() -> Result<()> {
color_eyre::install()?;
let filter_layer = EnvFilter::try_from_default_env()
.or_else(|_| EnvFilter::try_new("info"))
.unwrap();
let fmt_layer = tracing_subscriber::fmt::layer().with_target(true);
tracing_subscriber::registry()
.with(filter_layer)
.with(fmt_layer)
.with(ErrorLayer::default())
.init();
Ok(())
}
#[instrument]
async fn load_config(path: &str) -> Result<Config> {
event!(Level::DEBUG, "Loading config");
let content = tokio::fs::read_to_string(path).await?;
Ok(toml::from_str(&content)?)
}
#[derive(Debug, Clone, Parser)]
struct Args {
/// Path to the configuration file.
#[arg(short, long, default_value = "config.toml")]
config: String,
}
#[tokio::main]
#[instrument]
async fn main() -> Result<()> {
let args = Args::parse();
init()?;
let config = load_config(&args.config).await?;
let database: Arc<Mutex<Box<dyn Database + Send>>> = Arc::new(Mutex::new(Box::new(
SqliteDatabase::open(&config.database.connection_string).await,
)));
let mut auth_backends = vec![];
for c in config.auth_backends {
auth_backends.push(AuthenticationBackend::new(c).await?);
}
let user_authenticator = Arc::new(UserAuthenticator::new(database, auth_backends));
let padlock_generator = Arc::new(ServerPadlockGenerator::new(config.padlock_secret));
let user_server_key_generator = Arc::new(UserServerKeyGenerator::new(
Arc::clone(&user_authenticator),
Arc::clone(&padlock_generator),
));
tokio::spawn(server::run(
config.listen,
user_authenticator,
padlock_generator,
user_server_key_generator,
))
.await??;
Ok(())
}