7.4 KiB · text History 7ce364f
use std::sync::Arc;
use std::time::Duration;

use axum::extract::State;
use axum::http::StatusCode;
use axum::response::Html;
use axum::routing::get;
use axum::Router;
use axum_prometheus::PrometheusMetricLayer;
use log::info;
use metrics_process::Collector;
use minijinja::context;
use tower_http::classify::ServerErrorsFailureClass;
use tower_http::services::ServeDir;
use tower_http::trace::{DefaultMakeSpan, TraceLayer};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;

use recourse::middleware::UserContext;
use recourse::{create_db_connection, middleware, AppState, Config};

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                // INFO by default: tower_http's DEBUG request spans list every
                // header. Cookie/Authorization/Set-Cookie are marked sensitive
                // below either way, so even RUST_LOG=debug prints "Sensitive".
                .unwrap_or_else(|_| "recourse=info,tower_http=info".into()),
        )
        .with(tracing_subscriber::fmt::layer())
        .init();
    info!("Booting recourse webservice");

    let config = Arc::new(Config::from_env());
    info!(
        "Configuration loaded (public_url={}, oidc_enabled={}, oidc_providers={:?}, login_mode={}, password_login={}, mail={})",
        config.public_url,
        config.oidc.master_enabled(),
        config.oidc.enabled().iter().map(|p| p.id.as_str()).collect::<Vec<_>>(),
        config.oidc.login_mode(),
        config.password_login,
        if config.mail_configured() { "mail-prism" } else { "log only" },
    );

    let db = Arc::new(create_db_connection(&config.database_url).await?);
    info!("Database connection established");

    if config.auto_migrate {
        use migration::MigratorTrait;
        info!("Running pending migrations (set AUTO_MIGRATE=false to skip)");
        migration::Migrator::up(db.as_ref(), None).await?;
        info!("Migrations up to date");
    } else {
        info!("AUTO_MIGRATE=false — skipping migrations");
    }

    // Client addresses: forwarding headers believed only from these; old
    // rows purged at start and hourly.
    info!(
        "Client addresses: trusted proxies [{}], kept {} days",
        config.trusted_proxies.0.iter().map(|c| c.to_string()).collect::<Vec<_>>().join(", "),
        config.ip_retention_days
    );
    recourse::ips::spawn_purger(db.clone(), config.ip_retention_days);
    info!(
        "Registration: {} (email verification {}; open sign-ups per address per day {}, min fill {}s, unverified accounts kept {} days)",
        if config.registration_enabled { "open" } else { "invite only" },
        if config.require_email_verification { "required" } else { "off" },
        config.registration.per_ip_per_day,
        config.registration.min_fill_secs,
        config.registration.unverified_ttl_days,
    );
    for w in recourse::registration::boot_warnings(&config) {
        tracing::warn!("{w}");
    }
    recourse::registration::spawn_sweeper(db.clone(), config.clone());
    // Rich links whose fetch a restart interrupted (still `pending`).
    recourse::link_cards::Previewer::new(db.clone(), &config.public_url).spawn_sweep();
    if config.link_secret == recourse::config::DEV_LINK_SECRET {
        if config.secure_cookies() {
            tracing::warn!("LINK_SECRET is unset: /out links are signed with the published development value; set your own");
        } else {
            info!("LINK_SECRET unset: using the development value");
        }
    }
    let trusted_proxies = Arc::new(config.trusted_proxies.clone());

    let collector = Collector::default();
    collector.describe();
    let (prometheus_layer, metric_handle) = PrometheusMetricLayer::pair();

    let jinja = recourse::web::environment(&config);

    let app_state = AppState {
        env: jinja,
        db: db.clone(),
        config: config.clone(),
        view_throttle: recourse::new_view_throttle(),
        mailer: recourse::mailer::build(&config, true),
        live: recourse::live::Hub::new(),
    };

    let api_routes = Router::new()
        .route("/profile", get(api_profile))
        .layer(axum::middleware::from_fn_with_state(
            app_state.db.clone(),
            middleware::auth_middleware,
        ));

    // "Sign in with NEIAM" (neiam-auth): /auth/oidc/{provider}/{login,callback}
    // and /auth/oidc/health. Outside the auth-required router. Inert unless
    // OIDC_ENABLED=true: the login/callback routes 404, /health still answers.
    let oidc = neiam_auth::axum::router(
        config.oidc.clone(),
        recourse::auth::oidc::AppLinker {
            db: db.clone(),
            config: config.clone(),
        },
    );

    let app = Router::new()
        .route("/healthz", get(healthz))
        .route(
            "/metrics",
            get(move || async move {
                collector.collect();
                metric_handle.render()
            }),
        )
        .nest_service("/assets", ServeDir::new("assets/f/"))
        .merge(recourse::web::router(app_state.db.clone()))
        .merge(oidc)
        .nest("/api", api_routes)
        // The Android app's API (docs/api.md): bearer device tokens only.
        .nest("/api/v1", recourse::api::router(db.clone()))
        .with_state(app_state)
        .layer(
            TraceLayer::new_for_http()
                .make_span_with(DefaultMakeSpan::default().include_headers(true))
                .on_failure(
                    |error: ServerErrorsFailureClass, _latency: Duration, _span: &tracing::Span| {
                        tracing::error!("something went wrong {error}")
                    },
                ),
        )
        // Outside the TraceLayer, so the span sees them already marked:
        // session cookies and bearer tokens never reach the logs.
        .layer(recourse::web::sensitive_request_headers())
        .layer(recourse::web::sensitive_response_headers())
        .layer(prometheus_layer)
        // Outermost: the client address, for everything inside.
        .layer(axum::middleware::from_fn_with_state(trusted_proxies, recourse::client_ip::layer));

    let listener = tokio::net::TcpListener::bind(&config.bind_address).await?;
    info!("Server starting on {}", config.bind_address);

    axum::serve(listener, app.into_make_service_with_connect_info::<std::net::SocketAddr>()).await?;
    Ok(())
}

/// Cheap health/readiness probe rendered through the shared template shell.
async fn healthz(State(state): State<AppState>) -> Result<Html<String>, StatusCode> {
    let template = state
        .env
        .get_template("ok.html")
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    let rendered = template
        .render(context! { title => "OK", app_name => state.config.app_name })
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(Html(rendered))
}

/// JSON profile endpoint, authenticated by session cookie or Bearer token.
async fn api_profile(user_context: UserContext) -> axum::Json<serde_json::Value> {
    axum::Json(serde_json::json!({
        "user": {
            "id": user_context.user.id,
            "username": user_context.user.username,
            "email": user_context.user.email,
            "is_active": user_context.user.is_active,
            "created_at": user_context.user.created_at,
            "last_login_at": user_context.user.last_login_at,
        }
    }))
}