factoriauth/src/main.rs

149 lines
4.4 KiB
Rust
Raw Normal View History

2024-02-09 21:22:29 +01:00
/*
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/>.
*/
2024-02-15 21:45:10 +01:00
#![warn(
clippy::pedantic,
clippy::as_conversions,
clippy::unwrap_used, // allow case by case, add comment explaining why panic can't happen
clippy::expect_used // allow case by case, expect message should be self-explanatory
)]
2024-02-10 10:20:44 +01:00
#![forbid(unsafe_code)]
2024-02-10 10:51:56 +01:00
mod auth;
2024-02-10 14:11:19 +01:00
mod config;
2024-02-10 12:06:53 +01:00
mod db;
2024-02-10 12:32:01 +01:00
mod secrets;
2024-02-10 11:13:11 +01:00
mod server;
2024-02-10 10:51:56 +01:00
2024-02-15 21:45:10 +01:00
use std::{env, path::PathBuf, sync::Arc};
2024-02-10 14:11:19 +01:00
2024-02-10 22:44:43 +01:00
use auth::{
AuthenticationBackend, ServerPadlockGenerator, UserAuthenticator, UserServerKeyGenerator,
};
2024-02-10 14:20:13 +01:00
use clap::Parser;
2024-02-15 21:14:07 +01:00
use color_eyre::{eyre::Context, Result};
2024-02-10 14:11:19 +01:00
use config::Config;
2024-02-11 16:48:03 +01:00
use db::{Database, SqliteDatabase};
2024-02-10 14:35:51 +01:00
use tokio::sync::Mutex;
2024-02-15 21:45:10 +01:00
use tracing::{event, instrument, level_filters::LevelFilter, Level};
2024-02-10 11:13:27 +01:00
use tracing_error::ErrorLayer;
2024-02-10 10:53:28 +01:00
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
#[instrument]
fn init() -> Result<()> {
2024-02-15 21:45:10 +01:00
const FILTER_ENV_VAR: &str = EnvFilter::DEFAULT_ENV;
2024-02-10 10:53:28 +01:00
color_eyre::install()?;
2024-02-15 21:45:10 +01:00
let mut filter_error = None;
let filter_layer = EnvFilter::builder()
.with_env_var(FILTER_ENV_VAR)
.try_from_env()
.unwrap_or_else(|e| {
// sure would be nice if the error type was useful
if env::var_os(FILTER_ENV_VAR).is_some() {
filter_error = Some(e);
}
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.parse_lossy("")
});
2024-02-10 10:53:28 +01:00
let fmt_layer = tracing_subscriber::fmt::layer().with_target(true);
tracing_subscriber::registry()
.with(filter_layer)
.with(fmt_layer)
2024-02-10 11:13:27 +01:00
.with(ErrorLayer::default())
2024-02-10 10:53:28 +01:00
.init();
2024-02-15 21:45:10 +01:00
if let Some(e) = filter_error {
event!(
Level::WARN,
error = %e,
r#"Tracing filter env variable `{FILTER_ENV_VAR}` contained invalid data, falling back to "info""#
);
}
2024-02-10 10:53:28 +01:00
Ok(())
}
2024-02-10 14:11:19 +01:00
#[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)?)
}
2024-02-10 14:20:13 +01:00
#[derive(Debug, Clone, Parser)]
struct Args {
/// Path to the configuration file.
#[arg(short, long, default_value = "config.toml")]
config: String,
}
2024-02-10 10:53:28 +01:00
#[tokio::main]
#[instrument]
async fn main() -> Result<()> {
2024-02-10 14:20:13 +01:00
let args = Args::parse();
2024-02-10 10:53:28 +01:00
2024-02-15 21:14:07 +01:00
init().context("Failed to initialize tracing")?;
2024-02-10 10:53:28 +01:00
2024-02-15 21:14:07 +01:00
let config = load_config(&args.config).await.with_context(|| {
if let Ok(path) = PathBuf::from(&args.config).canonicalize() {
format!("Failed to load config from {path:?}")
} else {
format!("Failed to load config from invalid path {}", &args.config)
}
})?;
2024-02-10 14:11:19 +01:00
2024-02-11 16:48:03 +01:00
let database: Arc<Mutex<Box<dyn Database + Send>>> = Arc::new(Mutex::new(Box::new(
2024-02-15 21:14:07 +01:00
SqliteDatabase::open(&config.database.connection_string)
.await
.context("Failed to open database")?,
2024-02-11 16:48:03 +01:00
)));
2024-02-10 14:35:51 +01:00
2024-02-10 22:44:43 +01:00
let mut auth_backends = vec![];
2024-02-15 21:14:07 +01:00
for (i, c) in config.auth_backends.into_iter().enumerate() {
auth_backends.push(
AuthenticationBackend::new(c)
.await
.with_context(|| format!("Failed to initialize backend {i}"))?,
);
2024-02-10 22:44:43 +01:00
}
let user_authenticator = Arc::new(UserAuthenticator::new(database, auth_backends));
2024-02-10 14:35:51 +01:00
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),
));
2024-02-10 19:34:07 +01:00
tokio::spawn(server::run(
config.listen,
2024-02-10 19:34:07 +01:00
user_authenticator,
padlock_generator,
user_server_key_generator,
))
.await??;
2024-02-10 11:04:10 +01:00
2024-02-10 10:53:28 +01:00
Ok(())
2024-02-09 21:22:29 +01:00
}