1
#![recursion_limit = "256"]
2

            
3
#[macro_use]
4
extern crate rust_i18n;
5

            
6
i18n!("locales", fallback = "en");
7

            
8
mod assets;
9
mod auth_keys;
10
mod client_ip;
11
mod config;
12
mod error_render;
13
mod form_invalid;
14
mod form_render;
15
mod handler;
16
mod jwt_auth;
17
mod login;
18
mod model;
19
mod pages;
20
mod parse;
21
mod rate_limit;
22
mod register;
23
mod response;
24
mod route;
25
mod session;
26
mod telemetry;
27
mod token;
28

            
29
use anyhow::Context as _;
30
use axum::{
31
    Router,
32
    extract::{MatchedPath, Request},
33
    middleware::{self, Next},
34
    response::IntoResponse,
35
    routing::get,
36
};
37

            
38
use axum::http::{
39
    HeaderValue, Method,
40
    header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE},
41
};
42

            
43
use redis::Client;
44
use std::sync::Arc;
45
use std::time::Duration;
46
use std::{future::ready, time::Instant};
47
use tower_http::cors::CorsLayer;
48

            
49
use config::Config;
50
use route::create_scripts_router;
51
use route::{
52
    create_accounts_router, create_admin_pages_router, create_api_router, create_pages_router,
53
    create_reports_router, create_tags_router, create_transactions_router,
54
};
55

            
56
pub struct AppState {
57
    conf: Config,
58
    redis_client: Client,
59
}
60

            
61
/// The metrics listener. Fails rather than panics: a recorder that cannot be
62
/// installed is a startup fault, and `main` already reports those.
63
fn metrics_app() -> anyhow::Result<Router> {
64
    let recorder_handle = server::telemetry::recorder::install_recorder()?;
65
    Ok(Router::new().route("/metrics", get(move || ready(recorder_handle.render()))))
66
}
67

            
68
async fn track_metrics(req: Request, next: Next) -> impl IntoResponse {
69
    let start = Instant::now();
70
    let path = if let Some(matched_path) = req.extensions().get::<MatchedPath>() {
71
        matched_path.as_str().to_owned()
72
    } else {
73
        req.uri().path().to_owned()
74
    };
75
    let method = req.method().clone();
76

            
77
    let response = next.run(req).await;
78

            
79
    let latency = start.elapsed().as_secs_f64();
80
    let status = response.status().as_u16().to_string();
81

            
82
    let labels = [
83
        ("method", method.to_string()),
84
        ("path", path),
85
        ("status", status),
86
    ];
87

            
88
    metrics::counter!(telemetry::HTTP_REQUESTS, &labels).increment(1);
89
    metrics::histogram!(telemetry::HTTP_REQUEST_DURATION, &labels).record(latency);
90

            
91
    response
92
}
93

            
94
/// How long the session store may take to accept a connection at startup.
95
///
96
/// Redis runs beside web in the same pod and the two start together, so a
97
/// refused connection here means "not listening yet", not "misconfigured".
98
/// Bounded rather than infinite: a Redis that is genuinely absent must fail the
99
/// process, not leave it waiting and reported healthy.
100
const REDIS_WAIT: Duration = Duration::from_secs(30);
101

            
102
/// Pause between connection attempts.
103
const REDIS_RETRY_PAUSE: Duration = Duration::from_secs(1);
104

            
105
/// Whether an error means "not up yet" rather than "wrong".
106
///
107
/// Only the store being absent is worth waiting out. A refused password or a
108
/// bad database number will be refused just as firmly in thirty seconds, so
109
/// retrying one buries a configuration error under a startup delay.
110
///
111
/// Deliberately narrower than `is_io_error`, which is every `io::Error` the
112
/// crate wraps — a name that does not resolve included. That is a wrong
113
/// address, not a slow one, and it should fail at once.
114
fn redis_not_up_yet(e: &redis::RedisError) -> bool {
115
    // Refusal covers the case this exists for: the sidecar has not bound its
116
    // port yet. On unix it also covers a socket file that is not there yet.
117
    e.is_connection_refusal() || e.is_timeout()
118
}
119

            
120
/// Opens the session store, waiting for it to come up.
121
///
122
/// Reports the address rather than the configured URL: that URL may carry
123
/// credentials, and this error reaches the logs.
124
async fn connect_redis(url: &str) -> anyhow::Result<Client> {
125
    let client =
126
        Client::open(url.to_string()).map_err(|e| anyhow::anyhow!("redis url unusable: {e}"))?;
127
    let addr = client.get_connection_info().addr().to_string();
128
    let deadline = Instant::now() + REDIS_WAIT;
129
    let mut last = "no attempt completed".to_string();
130

            
131
    loop {
132
        let remaining = deadline.saturating_duration_since(Instant::now());
133
        if remaining.is_zero() {
134
            return Err(anyhow::anyhow!(
135
                "redis at {addr} did not accept a connection within {REDIS_WAIT:?}: {last}"
136
            ));
137
        }
138

            
139
        // Each attempt carries the remaining budget: the connect future has no
140
        // timeout of its own, so a half-open socket would hang past REDIS_WAIT
141
        // and make the bound a fiction.
142
        //
143
        // The multiplexed async connection, not `get_connection`: the blocking
144
        // one stalls the runtime this is awaited on.
145
        match tokio::time::timeout(remaining, client.get_multiplexed_async_connection()).await {
146
            Ok(Ok(_)) => {
147
                tracing::info!("connected to redis at {addr}");
148
                return Ok(client);
149
            }
150
            Ok(Err(e)) if !redis_not_up_yet(&e) => {
151
                return Err(anyhow::anyhow!(
152
                    "redis at {addr} refused the connection: {e}"
153
                ));
154
            }
155
            Ok(Err(e)) => last = e.to_string(),
156
            Err(_) => last = "the connection attempt timed out".to_string(),
157
        }
158
        tracing::warn!("redis at {addr} not ready ({last}); retrying");
159

            
160
        let left = deadline.saturating_duration_since(Instant::now());
161
        tokio::time::sleep(REDIS_RETRY_PAUSE.min(left)).await;
162
    }
163
}
164

            
165
#[tokio::main]
166
async fn main() -> anyhow::Result<()> {
167
    server::telemetry::init_logging(None, tracing::level_filters::LevelFilter::INFO)?;
168

            
169
    // Migrate + seed the admin DB before reading config: seeding moved out of
170
    // the migration set into the `seed_complete`-guarded bootstrap, so a fresh
171
    // DB has no `site_url` until `boot` runs. Idempotent on an already-booted
172
    // DB. Without this, `Config::init` panics with NoConfig("site_url").
173
    server::boot().await.context("server boot failed")?;
174
    tracing::debug!("Server boot complete");
175

            
176
    let conf = Config::init()
177
        .await
178
        .map_err(|e| anyhow::anyhow!("config init failed: {e:?}"))?;
179
    tracing::debug!("Config ready");
180

            
181
    let redis_client = connect_redis(&conf.redis_url).await?;
182

            
183
    let cors = CorsLayer::new()
184
        .allow_origin(conf.site_url.parse::<HeaderValue>()?)
185
        .allow_methods([Method::GET, Method::POST, Method::PATCH, Method::DELETE])
186
        .allow_credentials(true)
187
        .allow_headers([AUTHORIZATION, ACCEPT, CONTENT_TYPE]);
188

            
189
    let state = Arc::new(AppState {
190
        conf,
191
        redis_client: redis_client.clone(),
192
    });
193

            
194
    // Validated before anything serves: getting this wrong either throttles
195
    // every user into one shared budget or lets them forge their identity, and
196
    // both failures are quiet.
197
    let limiter = Arc::new(rate_limit::AuthLimiter::new(
198
        client_ip::TrustedProxies::from_env()?,
199
    ));
200

            
201
    let router = Router::new()
202
        .route("/", get(pages::index))
203
        .route("/login", get(pages::login))
204
        .merge(create_admin_pages_router(state.clone()))
205
        .merge(create_pages_router(state.clone()))
206
        .merge(create_accounts_router(state.clone()))
207
        .merge(create_transactions_router(state.clone()))
208
        .merge(create_tags_router(state.clone()))
209
        .merge(create_reports_router(state.clone()));
210

            
211
    let router = router.merge(create_scripts_router(state.clone()));
212

            
213
    let router = router
214
        .nest(
215
            "/api",
216
            create_api_router(state.clone(), Arc::clone(&limiter)),
217
        )
218
        // Every authenticated request decodes a JWT, and decoding reads the
219
        // claimed subject's key from the directory before anything is verified.
220
        // Applied here so it covers every page and API route; static assets are
221
        // nested below and need no database.
222
        .route_layer(middleware::from_fn_with_state(
223
            limiter,
224
            rate_limit::throttle_verification,
225
        ))
226
        .merge(assets::static_files(
227
            &std::env::var("STATIC_PATH").unwrap_or("web/static".to_string()),
228
        ))
229
        .with_state(state)
230
        .layer(middleware::from_fn(error_render::render_web_error))
231
        .layer(cors)
232
        .route_layer(middleware::from_fn(track_metrics));
233

            
234
    let router = assets::with_cache_policy(router);
235

            
236
    let app = metrics_app()?;
237
    tokio::spawn(server::telemetry::pools::run_pool_sampler());
238

            
239
    let listener =
240
        tokio::net::TcpListener::bind(listen_address("WEB_LISTEN", "0.0.0.0:3000")).await?;
241
    let metrics_listener =
242
        tokio::net::TcpListener::bind(listen_address("METRICS_LISTEN", "0.0.0.0:3001")).await?;
243
    // Either listener dying is fatal: a live app port with a dead metrics port
244
    // (or vice versa) is a half-running process that k8s cannot see is broken.
245
    let (metrics_server, main_server) = tokio::join!(
246
        run_server(metrics_listener, app),
247
        run_server(listener, router)
248
    );
249
    metrics_server?;
250
    main_server?;
251
    Ok(())
252
}
253

            
254
/// The address `variable` names, else `default`.
255
fn listen_address(variable: &str, default: &str) -> String {
256
    config::env_override(std::env::var(variable).ok()).unwrap_or_else(|| default.to_string())
257
}
258

            
259
async fn run_server(listener: tokio::net::TcpListener, app: Router) -> std::io::Result<()> {
260
    // `with_connect_info` is what makes the peer address reachable from a
261
    // handler. Without it the throttle has nothing trustworthy to key on.
262
    axum::serve(
263
        listener,
264
        app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
265
    )
266
    .await
267
}