Skip to main content

kasl_server/
app.rs

1use axum::{
2    Json, Router,
3    extract::{DefaultBodyLimit, State},
4    http::StatusCode,
5    response::{IntoResponse, Response},
6    routing::{delete, get, patch, post, put},
7};
8use serde_json::json;
9use sqlx::PgPool;
10use tower_http::trace::TraceLayer;
11
12use crate::{admin, config::Config, department, ingest, login};
13
14#[derive(Clone)]
15pub struct AppState {
16    pub pool: PgPool,
17    /// Days one batch may carry; enforced by the batch handler.
18    pub max_batch_days: usize,
19    /// Whether session cookies carry `Secure`.
20    pub secure_cookies: bool,
21}
22
23/// Builds the router with the operator's limits applied.
24pub fn router_with(pool: PgPool, config: &Config) -> Router {
25    // `/api/v1` from the very first endpoint: kasl agents update on their own
26    // schedule, so the path a working agent calls must keep meaning what it
27    // meant when that agent shipped (ADR 0001).
28    let api_v1 = Router::new()
29        .route("/days", post(ingest::upload_day))
30        .route("/days/batch", post(ingest::upload_batch))
31        // People, not agents: these carry a session cookie rather than a
32        // bearer token, and the two never mix.
33        .route("/auth/login", post(login::login))
34        .route("/auth/logout", post(login::logout))
35        .route("/auth/logout-everywhere", post(login::logout_everywhere))
36        .route("/auth/me", get(login::me))
37        .route("/auth/password", post(admin::change_own_password))
38        // Administration. Reading the team is a manager's; changing it is not,
39        // until departments give a manager something to be in charge of.
40        .route("/users", get(admin::list_users).post(admin::create_user))
41        .route("/users/{id}", patch(admin::update_user))
42        .route("/users/{id}/agents", get(admin::list_agents).post(admin::create_agent))
43        .route("/agents/{id}", delete(admin::revoke_agent))
44        // Departments: what gives a manager a boundary to be in charge of.
45        .route("/departments", get(department::list).post(department::create))
46        .route("/departments/{id}", patch(department::update).delete(department::delete))
47        .route("/users/{id}/department", put(department::assign));
48
49    Router::new()
50        .route("/health", get(health))
51        .nest("/api/v1", api_v1)
52        .with_state(AppState {
53            pool,
54            max_batch_days: config.max_batch_days,
55            secure_cookies: config.secure_cookies,
56        })
57        // A body larger than this is refused before it is buffered: backfilling
58        // a year and attacking the server look identical up to the size.
59        .layer(DefaultBodyLimit::max(config.max_body_bytes))
60        .layer(TraceLayer::new_for_http())
61}
62
63/// The router with default limits - what the tests and `/health` callers want
64/// when the limits are not what is under test.
65pub fn router(pool: PgPool) -> Router {
66    router_with(pool, &Config::defaults_for_database(String::new()))
67}
68
69/// Liveness + readiness in one place: the process answers, and the database
70/// round-trip tells whether the server can actually do its job.
71async fn health(State(state): State<AppState>) -> Response {
72    match sqlx::query("SELECT 1").execute(&state.pool).await {
73        Ok(_) => (
74            StatusCode::OK,
75            Json(json!({
76                "status": "ok",
77                "version": env!("CARGO_PKG_VERSION"),
78                "database": "ok",
79            })),
80        )
81            .into_response(),
82        Err(error) => {
83            tracing::error!(%error, "health check: database unreachable");
84            (
85                StatusCode::SERVICE_UNAVAILABLE,
86                Json(json!({
87                    "status": "degraded",
88                    "version": env!("CARGO_PKG_VERSION"),
89                    "database": "unavailable",
90                })),
91            )
92                .into_response()
93        }
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use axum::{body::Body, http::Request};
100    use http_body_util::BodyExt;
101    use sqlx::postgres::PgPoolOptions;
102    use tower::ServiceExt;
103
104    use super::*;
105
106    /// A pool pointing nowhere: `connect_lazy` never dials until a query runs,
107    /// so the router can be exercised without a live database.
108    fn dead_pool() -> PgPool {
109        PgPoolOptions::new()
110            // Keep the failure fast: the default acquire timeout is 30 s.
111            .acquire_timeout(std::time::Duration::from_secs(1))
112            .connect_lazy("postgres://nobody:nowhere@127.0.0.1:1/kasl")
113            .expect("lazy pool creation does not touch the network")
114    }
115
116    #[tokio::test]
117    async fn health_reports_degraded_without_a_database() {
118        let response = router(dead_pool()).oneshot(Request::get("/health").body(Body::empty()).unwrap()).await.unwrap();
119        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
120
121        let body = response.into_body().collect().await.unwrap().to_bytes();
122        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
123        assert_eq!(body["status"], "degraded");
124        assert_eq!(body["database"], "unavailable");
125        assert_eq!(body["version"], env!("CARGO_PKG_VERSION"));
126    }
127
128    #[tokio::test]
129    async fn unknown_routes_return_404() {
130        let response = router(dead_pool()).oneshot(Request::get("/nope").body(Body::empty()).unwrap()).await.unwrap();
131        assert_eq!(response.status(), StatusCode::NOT_FOUND);
132    }
133}