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, alerts, audit, auth, calendar, config::Config, demo, department, heartbeat, heatmap, ingest, login, me, privacy, signals, team, web};
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        // What a person can read about themselves. `/me` rather than their own
39        // id under `/users`: this route consults no role and no department, so
40        // there is no permission here to get wrong.
41        .route("/me/days", get(me::days))
42        // Other people's data, for whoever is entitled to it. Separate routes
43        // from `/me` on purpose: here a permission is checked, and a route that
44        // sometimes checks one is a route where forgetting is invisible.
45        .route("/team/days", get(team::days))
46        // What the team is doing right now, polled on a timer. Split from
47        // `/team/days` on purpose: this one is asked every half minute and
48        // must stay cheap enough to be (ADR 0014).
49        .route("/team/live", get(team::live))
50        // The month as a shape. Its own route rather than a field on
51        // `/team/days`: that one answers a period as totals, and widening it
52        // with a per-day breakdown would change the cost of the query the
53        // dashboard runs on every page load, for numbers it does not draw
54        // (ADR 0015).
55        .route("/team/heatmap", get(heatmap::month))
56        // What the manager did not know to ask about. Every other team route
57        // answers a question; this one says where to look, and a person is
58        // only ever compared with their own history (ADR 0016).
59        .route("/team/signals", get(signals::team))
60        // What the server noticed on its own, before anybody opened a page.
61        // A stored record rather than a computation on read, unlike the
62        // signals beside it: an alert carries when it began and what somebody
63        // decided about it, and neither is derivable from a workday.
64        .route("/alerts", get(alerts::feed))
65        .route("/alerts/{id}/acknowledge", post(alerts::acknowledge))
66        // What this installation is willing to be interrupted about. A
67        // setting, unlike the signal thresholds fixed in code (ADR 0016):
68        // an alert interrupts somebody, and how much silence is worth that
69        // differs between a team in one timezone and a team across four.
70        .route("/alerts/thresholds", put(alerts::put_thresholds))
71        .route("/users/{id}/days", get(team::user_days))
72        // The twelve-week shape behind a signal, next to the days that made it.
73        .route("/users/{id}/trend", get(signals::user_trend))
74        // Administration. Reading the team is a manager's; changing it is not,
75        // until departments give a manager something to be in charge of.
76        .route("/users", get(admin::list_users).post(admin::create_user))
77        .route("/users/{id}", patch(admin::update_user))
78        .route("/users/{id}/agents", get(admin::list_agents).post(admin::create_agent))
79        .route("/agents/{id}", delete(admin::revoke_agent))
80        // Departments: what gives a manager a boundary to be in charge of.
81        .route("/departments", get(department::list).post(department::create))
82        .route("/departments/{id}", patch(department::update).delete(department::delete))
83        .route("/users/{id}/department", put(department::assign))
84        // The production calendar and what a full day is here. Readable by
85        // anyone signed in - which days of the year are worked is not a secret
86        // from the people working them - and written by an administrator, a
87        // year at a time, because that is how a calendar is published
88        // (ADR 0017).
89        .route("/calendar", get(calendar::year).put(calendar::put_year))
90        .route("/calendar/standard-hours", put(calendar::put_standard_hours))
91        // A person's share of a full day. Its own route rather than a field on
92        // the user patch: it changes what every screen says about them, and an
93        // audit entry naming it is easier to find than "user updated".
94        .route("/users/{id}/work-rate", put(calendar::put_work_rate))
95        // The record of who did what. Administrators only, and no way to
96        // delete from it (ADR 0010).
97        .route("/audit", get(audit::list))
98        // What this installation stores about a person. Readable by anyone
99        // signed in; set by an administrator alone (ADR 0011).
100        .route("/privacy", get(privacy::show).put(privacy::update))
101        // The same manifest for an agent's bearer token, so kasl can show it
102        // in the CLI - where the employee already is - rather than requiring a
103        // login to the server that watches them.
104        .route("/privacy/agent", get(privacy::show_to_agent))
105        // Whose token this is. The one question an agent can ask about
106        // itself, and the one `kasl server connect` needs so a token pasted
107        // from the wrong place is caught by a person rather than discovered
108        // in a dashboard weeks later.
109        .route("/agent/whoami", get(auth::whoami))
110        // The pulse. The only route that says anything about now rather than
111        // about a day that is over (ADR 0014).
112        .route("/agent/heartbeat", post(heartbeat::beat))
113        // Who a visitor may sign in as. Answered only on a demo - anywhere
114        // else it is a 404, so no real installation lists its people to
115        // someone who has not signed in (ADR 0013).
116        .route("/demo/accounts", get(demo::accounts));
117
118    Router::new()
119        .route("/health", get(health))
120        // Anything under `/api` that no route matched is a client's mistake and
121        // has to look like one. Without this the web UI's fallback would catch
122        // it and answer a misspelled endpoint with `200` and an HTML page -
123        // which a kasl agent would read as success.
124        .nest("/api", Router::new().nest("/v1", api_v1).fallback(unknown_endpoint))
125        // The web UI, compiled into the binary. Last on purpose: it answers
126        // everything the API did not claim, so a real endpoint always wins
127        // over the single-page app's own routing (ADR 0012).
128        .fallback(web::serve)
129        .with_state(AppState {
130            pool,
131            max_batch_days: config.max_batch_days,
132            secure_cookies: config.secure_cookies,
133        })
134        // A body larger than this is refused before it is buffered: backfilling
135        // a year and attacking the server look identical up to the size.
136        .layer(DefaultBodyLimit::max(config.max_body_bytes))
137        .layer(TraceLayer::new_for_http())
138}
139
140/// The router with default limits - what the tests and `/health` callers want
141/// when the limits are not what is under test.
142pub fn router(pool: PgPool) -> Router {
143    router_with(pool, &Config::defaults_for_database(String::new()))
144}
145
146/// Answers a path under `/api` that no route matched.
147///
148/// JSON, like every other API failure: a client that parses our errors must
149/// not have to special-case the one shape that says "no such endpoint".
150async fn unknown_endpoint() -> Response {
151    (StatusCode::NOT_FOUND, Json(json!({ "error": "no such endpoint" }))).into_response()
152}
153
154/// Liveness + readiness in one place: the process answers, and the database
155/// round-trip tells whether the server can actually do its job.
156///
157/// The round-trip reads the demo flag rather than `SELECT 1`: the web UI asks
158/// this endpoint before anyone signs in, and "is this a demo" is the one
159/// fact it needs at that moment (ADR 0013).
160async fn health(State(state): State<AppState>) -> Response {
161    let demo: Result<bool, sqlx::Error> = sqlx::query_scalar("SELECT demo FROM settings WHERE singleton").fetch_one(&state.pool).await;
162    match demo {
163        Ok(demo) => (
164            StatusCode::OK,
165            Json(json!({
166                "status": "ok",
167                "version": env!("CARGO_PKG_VERSION"),
168                "database": "ok",
169                "demo": demo,
170            })),
171        )
172            .into_response(),
173        Err(error) => {
174            tracing::error!(%error, "health check: database unreachable");
175            (
176                StatusCode::SERVICE_UNAVAILABLE,
177                Json(json!({
178                    "status": "degraded",
179                    "version": env!("CARGO_PKG_VERSION"),
180                    "database": "unavailable",
181                })),
182            )
183                .into_response()
184        }
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use axum::{body::Body, http::Request};
191    use http_body_util::BodyExt;
192    use sqlx::postgres::PgPoolOptions;
193    use tower::ServiceExt;
194
195    use super::*;
196
197    /// A pool pointing nowhere: `connect_lazy` never dials until a query runs,
198    /// so the router can be exercised without a live database.
199    fn dead_pool() -> PgPool {
200        PgPoolOptions::new()
201            // Keep the failure fast: the default acquire timeout is 30 s.
202            .acquire_timeout(std::time::Duration::from_secs(1))
203            .connect_lazy("postgres://nobody:nowhere@127.0.0.1:1/kasl")
204            .expect("lazy pool creation does not touch the network")
205    }
206
207    #[tokio::test]
208    async fn health_reports_degraded_without_a_database() {
209        let response = router(dead_pool()).oneshot(Request::get("/health").body(Body::empty()).unwrap()).await.unwrap();
210        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
211
212        let body = response.into_body().collect().await.unwrap().to_bytes();
213        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
214        assert_eq!(body["status"], "degraded");
215        assert_eq!(body["database"], "unavailable");
216        assert_eq!(body["version"], env!("CARGO_PKG_VERSION"));
217    }
218
219    #[tokio::test]
220    async fn an_unknown_api_path_is_a_json_404() {
221        // Under `/api` a path that matched nothing is a client's mistake. It
222        // must not reach the web UI's fallback, which would answer `200` and
223        // an HTML page - success, as far as a kasl agent can tell.
224        let response = router(dead_pool())
225            .oneshot(Request::get("/api/v1/nope").body(Body::empty()).unwrap())
226            .await
227            .unwrap();
228        assert_eq!(response.status(), StatusCode::NOT_FOUND);
229
230        let body = response.into_body().collect().await.unwrap().to_bytes();
231        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
232        assert_eq!(body["error"], "no such endpoint");
233    }
234
235    #[tokio::test]
236    async fn an_unknown_page_path_belongs_to_the_web_ui() {
237        // Outside `/api` an unmatched path is a client-side route, and only the
238        // app knows whether it exists. This used to be a flat 404; it changed
239        // deliberately when the UI arrived (ADR 0012).
240        let response = router(dead_pool()).oneshot(Request::get("/nope").body(Body::empty()).unwrap()).await.unwrap();
241
242        let content_type = response
243            .headers()
244            .get(axum::http::header::CONTENT_TYPE)
245            .and_then(|v| v.to_str().ok())
246            .unwrap_or_default();
247        assert!(
248            content_type.starts_with("text/html") || content_type.starts_with("text/plain"),
249            "the web UI answers this path, got `{content_type}`",
250        );
251    }
252}