P1 items #6 (JWT expiry) and #7 (refresh/logout routes) were already delivered in the P0 pass. This commit covers the two remaining P1 items: #9 — Replace dangerous handler-level .unwrap() calls (13 sites): * handlers/users.rs: 5x ObjectId::parse_str(&claims.sub).unwrap() in get_profile/update_profile/delete_account/get_settings/update_settings now return 401 on a malformed subject instead of panicking (matches the guard already used in change_password). * handlers/auth.rs: the login user.id.ok_or_else(..).unwrap() was a latent panic bug — the crafted 500 response was discarded. Now returns the clean 500 via match. * handlers/health_stats.rs: 6x state.health_stats_repo.as_ref().unwrap() now return 503 SERVICE_UNAVAILABLE if the feature is unconfigured, mirroring the interactions.rs pattern. * Left untouched: 14 test/boot-time unwraps and 7 infallible ones (header literal parsing, infallible TryFrom). The 3 borderline model-layer inserted_id unwraps are flagged for later. #8 — Rewrite the broken integration tests against a real test DB: * Split the crate into bin+lib: new src/lib.rs + src/app.rs (build_app), with main.rs now a thin entrypoint. Tests build the exact production router in-process instead of hitting a live server on a hardcoded port. * tests/common/mod.rs: helpers that connect to Mongo, build a fresh AppState against a unique per-process DB (normogen_test_<uuid>), and tear it down. A 1s connectivity probe makes tests skip gracefully when Mongo is absent, so 'cargo test' stays green without Mongo — CI runs them for real. * Rewrote tests/auth_tests.rs and tests/medication_tests.rs with the ACTUAL API contracts (POST /register {email,username,password}; response has token + refresh_token, not access_token; register returns 201). Covers register, login (right/wrong password), auth enforcement, refresh rotation + reuse detection, logout, and password-change invalidating old tokens. * Added a 'test' CI job with a mongo:7 service container running cargo test --all-targets. * Synced scripts/test-ci-locally.sh: fixed the stale -D warnings (CI is non-strict) and the reverted 'Docker Buildx' claims; added unit + integration test steps with a Mongo skip note. Verified: cargo fmt --check clean, build + clippy --all-targets clean. Full 'cargo test': 18 unit + 9 auth + 4 medication = 31 passed, 0 failed (integration tests skip cleanly when MongoDB is unreachable).
148 lines
5.2 KiB
Rust
148 lines
5.2 KiB
Rust
//! Binary entrypoint: loads config, connects to MongoDB, wires services into
|
|
//! [`config::AppState`], builds the router via [`app::build_app`], and serves.
|
|
//!
|
|
//! All module wiring and route/middleware composition lives in the library
|
|
//! (`lib.rs` + `app.rs`) so integration tests can reuse them.
|
|
|
|
use std::sync::Arc;
|
|
|
|
use normogen_backend::{
|
|
app::build_app,
|
|
auth::{JwtService, TokenVersionCache},
|
|
config::{self, Config, Environment},
|
|
db,
|
|
models::{health_stats::HealthStatisticsRepository, refresh_token::RefreshTokenRepository},
|
|
security, services,
|
|
};
|
|
|
|
#[tokio::main]
|
|
async fn main() -> anyhow::Result<()> {
|
|
eprintln!("NORMOGEN BACKEND STARTING...");
|
|
eprintln!("Loading environment variables...");
|
|
|
|
match dotenv::dotenv() {
|
|
Ok(path) => eprintln!("Loaded .env from: {:?}", path),
|
|
Err(e) => eprintln!("No .env file found (this is OK in Docker): {}", e),
|
|
}
|
|
|
|
eprintln!("Initializing logging...");
|
|
tracing_subscriber::fmt::init();
|
|
|
|
tracing::info!("Starting Normogen backend server");
|
|
|
|
// Load configuration
|
|
let config = Config::from_env()?;
|
|
if config.environment == Environment::Production {
|
|
eprintln!("Running in PRODUCTION mode");
|
|
} else {
|
|
eprintln!("Running in DEVELOPMENT mode");
|
|
}
|
|
eprintln!("Configuration loaded successfully");
|
|
|
|
// Connect to MongoDB
|
|
tracing::info!("Connecting to MongoDB at {}", config.database.uri);
|
|
eprintln!("Connecting to MongoDB...");
|
|
let db = match db::MongoDb::new(&config.database.uri, &config.database.database).await {
|
|
Ok(db) => {
|
|
tracing::info!(
|
|
"Connected to MongoDB database: {}",
|
|
config.database.database
|
|
);
|
|
eprintln!("MongoDB connection successful");
|
|
db
|
|
}
|
|
Err(e) => {
|
|
eprintln!("FATAL: Failed to connect to MongoDB: {}", e);
|
|
return Err(e);
|
|
}
|
|
};
|
|
|
|
match db.health_check().await {
|
|
Ok(_) => {
|
|
tracing::info!("MongoDB health check: OK");
|
|
eprintln!("MongoDB health check: OK");
|
|
}
|
|
Err(e) => {
|
|
tracing::warn!("MongoDB health check failed: {}", e);
|
|
eprintln!("WARNING: MongoDB health check failed: {}", e);
|
|
}
|
|
}
|
|
|
|
// Create JWT service
|
|
let jwt_service = JwtService::new(config.jwt.clone());
|
|
|
|
// Get the underlying MongoDB database for security services
|
|
let database = db.get_database();
|
|
|
|
// Ensure collections/indexes exist (best-effort; failures are logged, not
|
|
// fatal). Includes the refresh_tokens tokenHash-unique + expiresAt TTL
|
|
// indexes and the previously-never-run users.email unique index.
|
|
if let Err(e) = db::DatabaseInitializer::new(database.clone())
|
|
.initialize()
|
|
.await
|
|
{
|
|
tracing::warn!("Database index initialization skipped: {}", e);
|
|
}
|
|
|
|
// Short-TTL cache of token_version, so the JWT middleware can reject stale
|
|
// access tokens without a Mongo lookup per request.
|
|
let token_version_cache = Arc::new(TokenVersionCache::with_default_ttl());
|
|
|
|
// Persisted refresh tokens (hashed) for rotation/revocation.
|
|
let refresh_token_repo = Arc::new(RefreshTokenRepository::new(&database));
|
|
|
|
// Initialize security services (Phase 2.6)
|
|
let audit_logger = security::AuditLogger::new(&database);
|
|
let session_manager = security::SessionManager::new(&database);
|
|
|
|
// Create account lockout service with reasonable defaults
|
|
let user_collection = database.collection("users");
|
|
let account_lockout = security::AccountLockout::new(
|
|
user_collection,
|
|
5, // max_attempts
|
|
15, // base_duration_minutes
|
|
1440, // max_duration_minutes (24 hours)
|
|
);
|
|
|
|
// Initialize health stats repository (Phase 2.7) - using Database pattern
|
|
let health_stats_repo = HealthStatisticsRepository::new(&database);
|
|
|
|
// Initialize interaction service (Phase 2.8)
|
|
let interaction_service = Arc::new(services::InteractionService::new());
|
|
eprintln!("Interaction service initialized (Phase 2.8)");
|
|
|
|
// Create application state
|
|
let state = config::AppState {
|
|
db,
|
|
jwt_service,
|
|
config: config.clone(),
|
|
audit_logger: Some(audit_logger),
|
|
session_manager: Some(session_manager),
|
|
account_lockout: Some(account_lockout),
|
|
health_stats_repo: Some(health_stats_repo),
|
|
mongo_client: None,
|
|
interaction_service: Some(interaction_service),
|
|
token_version_cache,
|
|
refresh_token_repo: Some(refresh_token_repo),
|
|
};
|
|
|
|
eprintln!("Building router with security middleware...");
|
|
let app = build_app(state);
|
|
|
|
let addr = format!("{}:{}", config.server.host, config.server.port);
|
|
eprintln!("Binding to {}...", addr);
|
|
let listener = tokio::net::TcpListener::bind(&addr).await?;
|
|
eprintln!("Server listening on {}", &addr);
|
|
tracing::info!("Server listening on {}", &addr);
|
|
|
|
// into_make_service_with_connect_info makes ConnectInfo<SocketAddr> available
|
|
// to the client_ip_middleware so we can fall back to the peer address when no
|
|
// proxy header (X-Forwarded-For / X-Real-IP) is present.
|
|
axum::serve(
|
|
listener,
|
|
app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
|
|
)
|
|
.await?;
|
|
|
|
Ok(())
|
|
}
|