rust-web-server 18.23.2

Single-binary web server and reverse proxy: automatic HTTPS (Let's Encrypt), HTTP/1.1, HTTP/2 and HTTP/3, load balancing, auth and rate limiting, configured in one TOML file. Also a Rust library: routing, middleware, MCP server, ORM, background jobs. No hyper, no Tower; HTTP/2 and HTTP/3 framing via h2 and quinn.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! What the admin API and the `rws` binary's MCP tools both do, as JSON.
//! One implementation, so the two can't drift apart.
//!
//! State that belongs to an application rather than the process (its
//! response cache, its route table) is registered here by whoever builds
//! the application ([`register_cache`], [`register_routes`]).

use std::sync::atomic::Ordering;
use std::sync::{OnceLock, RwLock};

use crate::cache::CacheLayer;
use crate::mcp::json_escape;

fn quoted(s: &str) -> String {
    format!("\"{}\"", json_escape(s))
}

/// Every `RWS_CONFIG_*` setting in effect, sorted; secrets (names with
/// `SECRET`, `PASSWORD` or `TOKEN`) shown as `(hidden)`.
pub fn config_json() -> String {
    let mut pairs: Vec<(String, String)> = std::env::vars().filter(|(k, _)| k.starts_with("RWS_CONFIG_")).collect();
    pairs.sort();
    let members: Vec<String> =
        pairs.iter().map(|(k, v)| format!("{}:{}", quoted(k), quoted(&crate::entry_point::shown(k, v)))).collect();
    format!("{{{}}}", members.join(","))
}

/// Compile-time features as `{"name":bool}`.
pub fn build_features_json() -> String {
    macro_rules! features {
        ($($name:literal),*) => { vec![$( ($name, cfg!(feature = $name)) ),*] };
    }
    let all: Vec<(&str, bool)> = features!(
        "http1", "http2", "http3", "acme", "auth", "serde", "macros", "sso", "sso-saml", "sso-server", "gateway-api",
        "tower", "openapi", "mimalloc", "brotli", "zstd", "wasm-plugins"
    );
    let members: Vec<String> = all.iter().map(|(name, on)| format!("\"{name}\":{on}")).collect();
    format!("{{{}}}", members.join(","))
}

/// The server's counters.
pub fn metrics_json() -> String {
    use crate::metrics;
    format!(
        r#"{{"requests_total":{},"errors_total":{},"active_connections":{},"thread_pool_queued":{},"ready":{}}}"#,
        metrics::REQUESTS_TOTAL.load(Ordering::Relaxed),
        metrics::ERRORS_TOTAL.load(Ordering::Relaxed),
        metrics::ACTIVE_CONNECTIONS.load(Ordering::Relaxed),
        metrics::THREAD_POOL_QUEUED.load(Ordering::Relaxed),
        metrics::SERVER_READY.load(Ordering::Relaxed),
    )
}

pub fn rate_limit_json() -> String {
    let cfg = crate::config_reload::current();
    format!(
        r#"{{"configured":{},"max_requests":{},"window_secs":{}}}"#,
        crate::rate_limit::is_configured(),
        cfg.rate_limit_max_requests,
        cfg.rate_limit_window_secs
    )
}

/// `ip`'s remaining quota under the global limit; counts as one request.
pub fn check_rate_limit_json(ip: &str) -> String {
    let limiter = crate::rate_limit::global();
    let remaining = limiter.remaining(ip);
    let allowed = limiter.check(ip);
    format!(r#"{{"ip":{},"remaining":{remaining},"allowed":{allowed}}}"#, quoted(ip))
}

pub fn cors_json() -> String {
    let cfg = crate::config_reload::current();
    format!(
        r#"{{"allow_all":{},"origins":{},"methods":{},"headers":{},"credentials":{},"expose_headers":{},"max_age":{}}}"#,
        cfg.cors_allow_all,
        quoted(&cfg.cors_allow_origins),
        quoted(&cfg.cors_allow_methods),
        quoted(&cfg.cors_allow_headers),
        quoted(&cfg.cors_allow_credentials.to_string()),
        quoted(&cfg.cors_expose_headers),
        quoted(&cfg.cors_max_age.to_string()),
    )
}

pub fn maintenance_json() -> String {
    format!(r#"{{"active":{}}}"#, crate::maintenance::MAINTENANCE_MODE.load(Ordering::Relaxed))
}

pub fn set_maintenance(active: bool) -> String {
    crate::maintenance::MAINTENANCE_MODE.store(active, Ordering::SeqCst);
    crate::cluster::publish(crate::cluster::Op::Maintenance(active));
    maintenance_json()
}

pub fn blocklist_json() -> String {
    let list: Vec<String> = crate::blocklist::global().list().iter().map(|ip| quoted(ip)).collect();
    format!("[{}]", list.join(","))
}

pub fn block(ip: &str) -> String {
    crate::blocklist::global().block(ip);
    crate::cluster::publish(crate::cluster::Op::Block(ip.to_string()));
    format!(r#"{{"blocked":{}}}"#, quoted(ip))
}

pub fn unblock(ip: &str) -> String {
    crate::blocklist::global().unblock(ip);
    crate::cluster::publish(crate::cluster::Op::Unblock(ip.to_string()));
    format!(r#"{{"unblocked":{}}}"#, quoted(ip))
}

/// Runtime feature flags ([`crate::feature`]).
pub fn flags_json() -> String {
    let flags: Vec<String> =
        crate::feature::global().list().iter().map(|(name, on)| format!(r#"{{"name":{},"enabled":{on}}}"#, quoted(name))).collect();
    format!("[{}]", flags.join(","))
}

pub fn set_flag(name: &str, enabled: bool) -> String {
    crate::feature::global().set(name, enabled);
    crate::cluster::publish(crate::cluster::Op::Flag { name: name.to_string(), enabled });
    format!(r#"{{"name":{},"enabled":{enabled}}}"#, quoted(name))
}

/// The last `n` requests (at most 100), or the last `n` with a 4xx/5xx
/// status.
pub fn recent_json(n: usize, errors_only: bool) -> String {
    let n = n.min(100);
    let log = crate::request_log::global();
    let entries = if errors_only { log.recent_errors(n) } else { log.recent(n) };
    let entries: Vec<String> = entries
        .iter()
        .map(|e| {
            format!(
                r#"{{"ts":{},"method":{},"path":{},"status":{},"ip":{},"latency_ms":{}}}"#,
                e.timestamp,
                quoted(&e.method),
                quoted(&e.path),
                e.status,
                quoted(&e.client_ip),
                e.latency_ms
            )
        })
        .collect();
    format!("[{}]", entries.join(","))
}

fn cache_slot() -> &'static RwLock<Option<CacheLayer>> {
    static SLOT: OnceLock<RwLock<Option<CacheLayer>>> = OnceLock::new();
    SLOT.get_or_init(RwLock::default)
}

fn routes_slot() -> &'static RwLock<Vec<(String, String)>> {
    static SLOT: OnceLock<RwLock<Vec<(String, String)>>> = OnceLock::new();
    SLOT.get_or_init(RwLock::default)
}

/// The response cache the admin API reports on and clears (a clone shares
/// the store).
pub fn register_cache(cache: CacheLayer) {
    crate::cache::registry::register("app", cache.clone());
    *cache_slot().write().unwrap_or_else(|e| e.into_inner()) = Some(cache);
}

/// The application's routes as `(method, pattern)`, for listing.
pub fn register_routes(routes: Vec<(String, String)>) {
    *routes_slot().write().unwrap_or_else(|e| e.into_inner()) = routes;
}

pub fn cache_stats_json(cache: &CacheLayer) -> String {
    format!(r#"{{"hits":{},"misses":{},"size":{}}}"#, cache.hits(), cache.misses(), cache.size())
}

/// Stats of the registered cache; `None` without one.
pub fn registered_cache_json() -> Option<String> {
    cache_slot().read().unwrap_or_else(|e| e.into_inner()).as_ref().map(cache_stats_json)
}

/// Clear the registered cache; `false` without one.
pub fn clear_registered_cache() -> bool {
    match cache_slot().read().unwrap_or_else(|e| e.into_inner()).as_ref() {
        Some(cache) => {
            cache.clear();
            true
        }
        None => false,
    }
}

pub fn routes_json(routes: &[(String, String)]) -> String {
    let entries: Vec<String> =
        routes.iter().map(|(m, p)| format!(r#"{{"method":{},"pattern":{}}}"#, quoted(m), quoted(p))).collect();
    format!("[{}]", entries.join(","))
}

pub fn registered_routes_json() -> String {
    routes_json(&routes_slot().read().unwrap_or_else(|e| e.into_inner()))
}

/// The config file's upstreams: each backend's weight, health, breaker
/// state and whether it is drained.
pub fn upstreams_json() -> String {
    let upstreams: Vec<String> = crate::proxy_config::upstream::snapshot()
        .iter()
        .map(|(name, backends)| {
            let backends: Vec<String> = backends
                .iter()
                .map(|b| {
                    format!(
                        r#"{{"url":{},"weight":{},"healthy":{},"breaker":{},"drained":{}}}"#,
                        quoted(&b.url),
                        b.weight,
                        b.healthy,
                        b.breaker.map_or("null".to_string(), quoted),
                        b.drained
                    )
                })
                .collect();
            format!(r#"{{"name":{},"backends":[{}]}}"#, quoted(name), backends.join(","))
        })
        .collect();
    format!("[{}]", upstreams.join(","))
}

/// Drain or undrain `backend` of `upstream`; `Err` names what doesn't exist.
pub fn set_drained(upstream: &str, backend: &str, drained: bool) -> Result<String, String> {
    let snapshot = crate::proxy_config::upstream::snapshot();
    let Some((_, backends)) = snapshot.iter().find(|(name, _)| name == upstream) else {
        return Err(format!("no upstream {upstream:?}"));
    };
    if !backends.iter().any(|b| b.url == backend) {
        return Err(format!("upstream {upstream:?} has no backend {backend:?}"));
    }
    crate::proxy_config::upstream::set_drained(upstream, backend, drained);
    crate::cluster::publish(crate::cluster::Op::Drain { upstream: upstream.to_string(), backend: backend.to_string(), drained });
    Ok(format!(r#"{{"upstream":{},"backend":{},"drained":{drained}}}"#, quoted(upstream), quoted(backend)))
}

/// The certificates served, soonest expiry first, and the ACME renewal
/// loop's state.
pub fn certificates_json() -> String {
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);
    let mut certificates = crate::metrics::tls::certificates();
    certificates.sort_by_key(|(_, not_after, _)| *not_after);
    let list: Vec<String> = certificates
        .iter()
        .map(|(name, not_after, source)| {
            format!(
                r#"{{"name":{},"not_after":{},"expires":{},"days_left":{},"source":"{source}"}}"#,
                quoted(name),
                not_after,
                quoted(&crate::http::date::format((*not_after).max(0) as u64)),
                (not_after - now).div_euclid(86_400)
            )
        })
        .collect();
    format!(r#"{{"certificates":[{}],"acme":{}}}"#, list.join(","), acme_json())
}

#[cfg(feature = "acme")]
fn acme_json() -> String {
    let (running, last) = crate::acme::renewal_status();
    let last = last.map_or("null".to_string(), |(at, outcome)| format!(r#"{{"at":{at},"outcome":{}}}"#, quoted(&outcome)));
    format!(r#"{{"running":{running},"last_check":{last}}}"#)
}

#[cfg(not(feature = "acme"))]
fn acme_json() -> String {
    r#"{"running":false,"last_check":null}"#.to_string()
}

/// Ask ACME to renew now; `false` when it isn't running.
pub fn request_renewal() -> bool {
    #[cfg(feature = "acme")]
    return crate::acme::request_renewal();
    #[cfg(not(feature = "acme"))]
    false
}

/// The last `n` access-log lines (at most [`crate::log::tail::CAPACITY`]),
/// oldest first, each as a string.
pub fn logs_json(n: usize) -> String {
    let lines: Vec<String> = crate::log::tail::recent(n).iter().map(|l| quoted(l)).collect();
    format!("[{}]", lines.join(","))
}

/// Every named cache (the binary's `app`, `route:<name>` for config-file
/// routes): kind, entries, bytes on disk, hits, misses.
pub fn caches_json() -> String {
    let caches: Vec<String> = crate::cache::registry::list()
        .iter()
        .map(|(name, c)| {
            format!(
                r#"{{"name":{},"kind":"{}","entries":{},"bytes":{},"hits":{},"misses":{}}}"#,
                quoted(name),
                c.kind(),
                c.size(),
                c.stored_bytes().map_or("null".to_string(), |b| b.to_string()),
                c.hits(),
                c.misses()
            )
        })
        .collect();
    format!("[{}]", caches.join(","))
}

/// Purge `name`: everything, one target (`path`) or a `prefix`; `None` for
/// an unknown cache.
pub fn purge_cache(name: &str, path: Option<&str>, prefix: Option<&str>) -> Option<String> {
    let cache = crate::cache::registry::get(name)?;
    let target = match (path, prefix) {
        (Some(p), _) if !p.is_empty() => crate::cache::Purge::Exact(p.to_string()),
        (_, Some(p)) if !p.is_empty() => crate::cache::Purge::Prefix(p.to_string()),
        _ => crate::cache::Purge::All,
    };
    let n = cache.purge(&target);
    crate::cluster::publish(crate::cluster::Op::Purge { cache: name.to_string(), path: path.filter(|p| !p.is_empty()).map(str::to_string), prefix: prefix.filter(|p| !p.is_empty()).map(str::to_string) });
    Some(format!(r#"{{"name":{},"purged":{n}}}"#, quoted(name)))
}

// ── Traffic insights (18.15.0) ────────────────────────────────────────────────

/// Who visited in the last `hours` (1–2160), optionally for one host: the
/// Traffic page's JSON. `Err` when counting is off.
pub fn traffic_json(hours: u64, host: Option<&str>) -> Result<String, String> {
    if !crate::traffic::enabled() {
        return Err("traffic counting is off (on with the admin API unless [traffic] enabled = false)".to_string());
    }
    Ok(crate::traffic::summary::json(hours, host.filter(|h| !h.is_empty()), crate::traffic::record::now()))
}

// ── Authorization (#32) ───────────────────────────────────────────────────────

fn authorizer_slot() -> &'static RwLock<Option<crate::authz::Authorizer>> {
    static SLOT: OnceLock<RwLock<Option<crate::authz::Authorizer>>> = OnceLock::new();
    SLOT.get_or_init(RwLock::default)
}

/// The authorizer the admin API and MCP tools manage, for a library app
/// (the config file's `[authz]` is used otherwise). Since 18.14.0.
pub fn register_authorizer(authorizer: crate::authz::Authorizer) {
    *authorizer_slot().write().unwrap_or_else(|e| e.into_inner()) = Some(authorizer);
}

/// The registered authorizer, else the config file's; `Err` says why there
/// is none.
pub fn authorizer() -> Result<crate::authz::Authorizer, String> {
    if let Some(authorizer) = authorizer_slot().read().unwrap_or_else(|e| e.into_inner()).clone() {
        return Ok(authorizer);
    }
    match crate::authz::config::current() {
        Some(result) => result,
        None => Err("no authorization configured ([authz] in the config file, or admin::ops::register_authorizer)".to_string()),
    }
}

/// The schema: `{"types":{"doc":["owner","viewer"],…}}`.
pub fn authz_schema_json() -> Result<String, String> {
    let authorizer = authorizer()?;
    let schema = authorizer.schema();
    let types: Vec<String> = schema
        .types()
        .iter()
        .map(|kind| format!("{}:[{}]", quoted(kind), schema.relations(kind).iter().map(|r| quoted(r)).collect::<Vec<_>>().join(",")))
        .collect();
    Ok(format!(r#"{{"types":{{{}}}}}"#, types.join(",")))
}

/// Tuples matching the given parts (each optional), at most `limit`.
pub fn authz_tuples_json(object: Option<&str>, relation: Option<&str>, subject: Option<&str>, limit: usize) -> Result<String, String> {
    let authorizer = authorizer()?;
    let filter = crate::authz::TupleFilter {
        object: object.filter(|o| o.contains(':')).map(crate::authz::ObjectRef::parse).transpose().map_err(|e| e.to_string())?,
        object_kind: object.filter(|o| !o.contains(':')).map(str::to_string),
        relation: relation.map(str::to_string),
        subject: subject.map(crate::authz::Subject::parse).transpose().map_err(|e| e.to_string())?,
    };
    let tuples = authorizer.store().list(&filter, limit.clamp(1, 1000)).map_err(|e| e.to_string())?;
    Ok(format!(r#"{{"tuples":[{}]}}"#, tuples.iter().map(|t| quoted(&t.to_string())).collect::<Vec<_>>().join(",")))
}

/// Write `tuple`; `{"tuple":…,"written":true|false}` (false: already there).
pub fn authz_write(tuple: &str) -> Result<String, String> {
    let tuple = crate::authz::Tuple::parse(tuple).map_err(|e| e.to_string())?;
    let written = authorizer()?.write(&tuple).map_err(|e| e.to_string())?;
    Ok(format!(r#"{{"tuple":{},"written":{written}}}"#, quoted(&tuple.to_string())))
}

/// Delete `tuple`; `{"tuple":…,"deleted":true|false}`.
pub fn authz_delete(tuple: &str) -> Result<String, String> {
    let tuple = crate::authz::Tuple::parse(tuple).map_err(|e| e.to_string())?;
    let deleted = authorizer()?.delete(&tuple).map_err(|e| e.to_string())?;
    Ok(format!(r#"{{"tuple":{},"deleted":{deleted}}}"#, quoted(&tuple.to_string())))
}

/// Whether `subject` has `relation` on `object`, with the path that allowed
/// it: `{"allowed":true,"path":[…]}`.
pub fn authz_check(subject: &str, relation: &str, object: &str) -> Result<String, String> {
    let path = authorizer()?.explain(subject, relation, object).map_err(|e| e.to_string())?;
    Ok(match path {
        Some(path) => format!(r#"{{"allowed":true,"path":[{}]}}"#, path.iter().map(|p| quoted(p)).collect::<Vec<_>>().join(",")),
        None => r#"{"allowed":false,"path":[]}"#.to_string(),
    })
}