boatramp-server 0.3.15

boatramp HTTP server + API library (streaming static-site publishing)
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Differential test for the serve hot-path bypass (`FastServe`): the security-critical
//! proof that dispatching an eligible request straight to `serve_by_host` is
//! **byte-identical** to routing it through the full axum router, and that the classifier
//! never steals a request an explicit route (or the console) owns.
//!
//! Two halves:
//! 1. **Classifier** — `FastServe::eligible` must return `false` for every reserved route
//!    (`/api*`, `/_*`, `/.well-known/*`, `/healthz`, `/readyz`, `/mcp*`) and every non
//!    GET/HEAD method, and `true` only for a plain site GET/HEAD. Excluding too much only
//!    forgoes the speedup; excluding too little would route a control-plane request into
//!    `serve_by_host` — this is the guard against that.
//! 2. **Byte-identity** — for every eligible request, `router.oneshot(req)` and
//!    `fast.dispatch(req)` produce the same status, headers, and body. Includes a
//!    gateway-upstream GET under a **permissive** posture: it passes only if the bypass
//!    re-inserts the security posture the SSRF gate reads (a missing posture would fail
//!    closed to the strict default and 502 the private upstream the router allows).

#![cfg(test)]

use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::sync::Arc;

use axum::body::{to_bytes, Body};
use axum::extract::ConnectInfo;
use axum::http::{header, Method, Request, StatusCode};
use axum::response::Response;
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
use tokio::net::TcpListener;
use tower::ServiceExt as _;

use boatramp_core::config::{DeployConfig, DomainConfig, HeaderRule, Redirect, SiteConfig};
use boatramp_core::deploy::{sha256_hex, DeployStore, FileEntry, Manifest};
use boatramp_core::gateway::{GatewayConfig, GatewayRoute, Upstream};
use boatramp_core::kv::MemoryKv;
use boatramp_core::project::ProjectRef;
use boatramp_core::security::SecurityProfile;
use boatramp_core::ByteStream;
use futures::StreamExt as _;

use crate::{Auth, FastServe, HandlerRuntime, ServerOptions};

const PEER: SocketAddr =
    SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), 40000);

/// A file entry + its content, ready to `put_blob`.
fn file(bytes: &'static [u8], content_type: &str) -> FileEntry {
    FileEntry {
        hash: sha256_hex(bytes),
        size: bytes.len() as u64,
        content_type: Some(content_type.to_string()),
        variants: BTreeMap::new(),
    }
}

async fn put_blob(deploy: &DeployStore, bytes: &'static [u8]) {
    let hash = sha256_hex(bytes);
    let stream: ByteStream =
        futures::stream::once(async move { Ok(bytes::Bytes::from(bytes)) }).boxed();
    deploy.put_blob(&hash, stream).await.unwrap();
}

/// Build a request identical for both paths: a `Host`, method, path, and the peer as
/// `ConnectInfo` (the router extracts it; the fast path passes `PEER` explicitly — both
/// resolve to the same peer). An explicit `x-request-id` keeps the id deterministic.
fn mk(host: &str, method: Method, path: &str) -> Request<Body> {
    let mut req = Request::builder()
        .method(method)
        .uri(path)
        .body(Body::empty())
        .unwrap();
    req.headers_mut()
        .insert(header::HOST, host.parse().unwrap());
    req.headers_mut()
        .insert("x-request-id", "fixed-test-id".parse().unwrap());
    req.extensions_mut().insert(ConnectInfo(PEER));
    req
}

/// Collect a response into `(status, sorted headers, body)` for structural comparison.
/// `content-length` / `transfer-encoding` are excluded: those are transport-framing
/// headers the `boatramp_http` codec derives from the body at the wire (both paths pass
/// through it in production), and axum's `Router` service auto-adds `content-length: 0`
/// to an empty-body response as a courtesy the fast path leaves to the codec. The body
/// bytes are compared separately, so the effective length is still validated exactly.
async fn collect(resp: Response) -> (StatusCode, Vec<(String, Vec<u8>)>, Vec<u8>) {
    let status = resp.status();
    let mut headers: Vec<(String, Vec<u8>)> = resp
        .headers()
        .iter()
        .filter(|(k, _)| !matches!(k.as_str(), "content-length" | "transfer-encoding"))
        .map(|(k, v)| (k.as_str().to_string(), v.as_bytes().to_vec()))
        .collect();
    headers.sort();
    let body = to_bytes(resp.into_body(), usize::MAX)
        .await
        .unwrap()
        .to_vec();
    (status, headers, body)
}

/// A tiny keep-alive upstream returning a fixed `Content-Length` body, for the gateway
/// site. Returns its address.
async fn spawn_upstream() -> SocketAddr {
    let up = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = up.local_addr().unwrap();
    tokio::spawn(async move {
        while let Ok((mut s, _)) = up.accept().await {
            tokio::spawn(async move {
                let mut buf = [0u8; 4096];
                loop {
                    match s.read(&mut buf).await {
                        Ok(0) | Err(_) => return,
                        Ok(n) if !buf[..n].windows(4).any(|w| w == b"\r\n\r\n") => continue,
                        Ok(_) => {}
                    }
                    let body = b"hello-from-upstream";
                    let head = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body.len());
                    if s.write_all(head.as_bytes()).await.is_err()
                        || s.write_all(body).await.is_err()
                    {
                        return;
                    }
                }
            });
        }
    });
    addr
}

/// A store with a static site on `app.local` (clean URLs, custom 404, a redirect, a JS
/// header rule) and a gateway site on `gw.local` proxying to `up_addr`. Both hosts are
/// `.local`, so the domain-verification gate passes without a challenge.
async fn seed(up_addr: SocketAddr) -> DeployStore {
    let deploy = DeployStore::new(
        Arc::new(boatramp_storage::FsStorage::new(std::env::temp_dir())),
        Arc::new(MemoryKv::new()),
    );

    // Static site content.
    const INDEX: &[u8] = b"<h1>home</h1>";
    const ABOUT: &[u8] = b"<h1>about</h1>";
    const NF: &[u8] = b"<h1>nope</h1>";
    const BIG: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz-the-big-file-body-x";
    const JS: &[u8] = b"export const id = (x) => x;";
    for b in [INDEX, ABOUT, NF, BIG, JS] {
        put_blob(&deploy, b).await;
    }
    let mut files = BTreeMap::new();
    files.insert("index.html".to_string(), file(INDEX, "text/html"));
    files.insert("about.html".to_string(), file(ABOUT, "text/html"));
    files.insert("404.html".to_string(), file(NF, "text/html"));
    files.insert("big.txt".to_string(), file(BIG, "text/plain"));
    files.insert("app.js".to_string(), file(JS, "text/javascript"));
    let config = DeployConfig {
        clean_urls: true,
        error_documents: BTreeMap::from([(404, "/404.html".to_string())]),
        redirects: vec![Redirect {
            from: "/old".to_string(),
            to: "/new".to_string(),
            status: 301,
            when: None,
        }],
        headers: vec![HeaderRule {
            matches: "**.js".to_string(),
            set: BTreeMap::from([("Cache-Control".to_string(), "immutable".to_string())]),
            unset: vec![],
        }],
        ..DeployConfig::default()
    };
    let manifest = Manifest {
        files,
        config,
        ..Default::default()
    };
    deploy
        .set_site_config(
            ProjectRef::DEFAULT,
            "static",
            &SiteConfig {
                domains: DomainConfig {
                    primary: Some("app.local".into()),
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .await
        .unwrap();
    let id = deploy.put_manifest(&manifest).await.unwrap();
    deploy
        .activate(ProjectRef::DEFAULT, "static", &id)
        .await
        .unwrap();

    // Gateway site → the loopback upstream (a private address the permissive Dev posture
    // allows; the strict default would refuse it — that is the posture-parity probe).
    deploy
        .set_site_config(
            ProjectRef::DEFAULT,
            "gw",
            &SiteConfig {
                domains: DomainConfig {
                    primary: Some("gw.local".into()),
                    ..Default::default()
                },
                gateway: Some(GatewayConfig {
                    upstreams: std::iter::once((
                        "backend".to_string(),
                        Upstream {
                            target: format!("http://{up_addr}"),
                            ..Default::default()
                        },
                    ))
                    .collect(),
                    routes: vec![GatewayRoute {
                        matches: "/**".into(),
                        upstream: "backend".into(),
                    }],
                }),
                ..Default::default()
            },
        )
        .await
        .unwrap();
    let gw_id = deploy.put_manifest(&Manifest::default()).await.unwrap();
    deploy
        .activate(ProjectRef::DEFAULT, "gw", &gw_id)
        .await
        .unwrap();

    deploy
}

/// Build the router + fast handle from one shared state (the exact `serve_with` wiring),
/// under a permissive Dev posture.
fn build(deploy: DeployStore) -> (axum::Router, FastServe) {
    crate::router_with_fast(
        deploy,
        Auth::disabled(),
        HandlerRuntime::disabled(),
        ServerOptions {
            posture: SecurityProfile::Dev.preset(),
            ..Default::default()
        },
    )
}

#[tokio::test]
async fn classifier_excludes_every_reserved_route_and_non_read_method() {
    let up = spawn_upstream().await;
    let deploy = seed(up).await;
    let (_router, fast) = build(deploy);

    // Eligible: a plain site GET/HEAD the router would send to its `serve_by_host` fallback.
    for (method, path) in [
        (Method::GET, "/"),
        (Method::GET, "/about"),
        (Method::GET, "/app.js"),
        (Method::GET, "/big.txt"),
        (Method::GET, "/old"),
        (Method::GET, "/deep/nested/path"),
        (Method::HEAD, "/"),
    ] {
        assert!(
            fast.eligible(&mk("app.local", method.clone(), path)),
            "expected eligible: {method} {path}"
        );
    }

    // Reserved routes — the router owns these; the bypass must defer.
    for path in [
        "/api",
        "/api/",
        "/api/sites",
        "/api/projects/acme/sites/blog",
        "/_sites/static/",
        "/_deploy/abc/",
        "/_webhooks/x",
        "/.well-known/acme-challenge/tok",
        "/.well-known/boatramp-bootstrap-identity",
        "/healthz",
        "/readyz",
        "/mcp",
        "/mcp/messages",
    ] {
        assert!(
            !fast.eligible(&mk("app.local", Method::GET, path)),
            "reserved route must not be eligible: {path}"
        );
    }

    // Non-read methods are never eligible (even on a site path).
    for method in [
        Method::POST,
        Method::PUT,
        Method::DELETE,
        Method::PATCH,
        Method::OPTIONS,
    ] {
        assert!(
            !fast.eligible(&mk("app.local", method.clone(), "/")),
            "non-read method must not be eligible: {method}"
        );
    }
}

#[tokio::test]
async fn fast_path_is_byte_identical_to_the_router_for_every_eligible_request() {
    let up = spawn_upstream().await;
    let deploy = seed(up).await;
    let (router, fast) = build(deploy);

    // Static-site requests: full status + headers + body must match exactly.
    for (host, method, path) in [
        ("app.local", Method::GET, "/"),
        ("app.local", Method::GET, "/about"),  // clean URL
        ("app.local", Method::GET, "/app.js"), // header rule (Cache-Control)
        ("app.local", Method::GET, "/big.txt"),
        ("app.local", Method::GET, "/old"), // 301 redirect
        ("app.local", Method::GET, "/does-not-exist"), // custom 404
        ("app.local", Method::HEAD, "/"),
        // An unmatched public host — both paths return the same verification/holding
        // outcome (there is no default site), exercised through one implementation.
        ("nope.local", Method::GET, "/"),
    ] {
        let probe = mk(host, method.clone(), path);
        assert!(
            fast.eligible(&probe),
            "test bug: {method} {host}{path} should be eligible"
        );
        let via_router = collect(
            router
                .clone()
                .oneshot(mk(host, method.clone(), path))
                .await
                .unwrap(),
        )
        .await;
        let via_fast = collect(fast.dispatch(mk(host, method.clone(), path), PEER).await).await;
        assert_eq!(
            via_router, via_fast,
            "fast path diverged from router for {method} {host}{path}"
        );
    }

    // Gateway-upstream GET under the permissive posture: the response must match, and in
    // particular must be a 200 proxied from the upstream (a bypass that dropped the
    // posture would fail closed to the strict default and 502 the private upstream).
    let via_router = collect(
        router
            .clone()
            .oneshot(mk("gw.local", Method::GET, "/anything"))
            .await
            .unwrap(),
    )
    .await;
    let via_fast = collect(
        fast.dispatch(mk("gw.local", Method::GET, "/anything"), PEER)
            .await,
    )
    .await;
    assert_eq!(
        via_router.0,
        StatusCode::OK,
        "router should proxy the private upstream under the permissive posture"
    );
    assert_eq!(via_router.0, via_fast.0, "gateway status diverged");
    assert_eq!(via_router.2, via_fast.2, "gateway body diverged");
    assert_eq!(
        via_fast.2, b"hello-from-upstream",
        "fast path did not proxy"
    );
}

/// Under a TLS listener paired with an HTTP/3 endpoint, the bypass must (a) derive the
/// `https` scheme + HSTS from `served_over_tls` and (b) carry the `Alt-Svc` advertisement
/// the `advertise_http3` router layer adds — both byte-identical to the router.
#[cfg(feature = "http3")]
#[tokio::test]
async fn tls_http3_fast_path_matches_router_with_alt_svc() {
    let up = spawn_upstream().await;
    let deploy = seed(up).await;
    let (router, fast) = crate::router_with_fast(
        deploy,
        Auth::disabled(),
        HandlerRuntime::disabled(),
        ServerOptions {
            posture: SecurityProfile::Dev.preset(),
            served_over_tls: true,
            ..Default::default()
        },
    );
    // Pair with an h3 endpoint on :8443 — the router layer + the bypass both advertise it.
    let port = 8443u16;
    let router = crate::advertise_http3(router, port);
    let fast = fast.advertise_http3(port);

    for (host, path) in [
        ("app.local", "/"),
        ("app.local", "/about"),
        ("app.local", "/app.js"),
        ("app.local", "/old"),
    ] {
        let probe = mk(host, Method::GET, path);
        assert!(fast.eligible(&probe), "should be eligible: {host}{path}");
        let via_router = collect(
            router
                .clone()
                .oneshot(mk(host, Method::GET, path))
                .await
                .unwrap(),
        )
        .await;
        let via_fast = collect(fast.dispatch(mk(host, Method::GET, path), PEER).await).await;
        assert_eq!(
            via_router, via_fast,
            "TLS+h3 fast path diverged for {host}{path}"
        );
        // Positive check: the Alt-Svc advertisement is actually present (not both-absent).
        assert!(
            via_fast.1.iter().any(|(k, _)| k == "alt-svc"),
            "Alt-Svc missing on the fast path for {host}{path}"
        );
    }
}