arcature 2026.1.0

Arcature application framework: a high-level Application facade over the certified Arcature subsystems, with the low-level Axum/Tower escape hatch preserved.
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Pre-routing proxy integration tests — real HTTP over TCP.
//!
//! The headline test is `pre_routing_rewrite_hits_registered_target`: it
//! registers `/new` only, requests `/old`, and the proxy rewrites `/old →
//! /new` *before* route selection. `/new` runs. This is impossible with a
//! post-routing middleware (`Router::layer`) — there the route table is
//! already matched against `/old` before the middleware sees the request, so
//! a 404 is returned. This test is the architectural proof for engine spec
//! §3/§4.
//!
//! All other proxy variants (redirect, short-circuit, header mutation,
//! validation rejections) are exercised here too. Each uses a real TCP server
//! on `127.0.0.1:0` and a raw HTTP/1.1 client (no heavyweight dev-dependency).

use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;

use arcature::prelude::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};

const HANG_GUARD: Duration = Duration::from_secs(10);

/// A running `Application` server on an ephemeral address with graceful
/// shutdown.
struct RunningApp {
    addr: SocketAddr,
    shutdown: tokio::sync::oneshot::Sender<()>,
    join: tokio::task::JoinHandle<()>,
}

impl RunningApp {
    async fn start(app: Application<()>) -> RunningApp {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind ephemeral listener");
        let addr = listener.local_addr().expect("read bound address");
        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
        let join = tokio::spawn(async move {
            app.serve_with_shutdown(listener, async {
                let _ = shutdown_rx.await;
            })
            .await
            .expect("application served without engine error");
        });
        RunningApp {
            addr,
            shutdown: shutdown_tx,
            join,
        }
    }

    fn addr(&self) -> SocketAddr {
        self.addr
    }

    async fn stop(self) {
        self.shutdown
            .send(())
            .expect("server task still alive to receive shutdown");
        tokio::time::timeout(HANG_GUARD, self.join)
            .await
            .expect("server did not hang on shutdown")
            .expect("server task did not panic");
    }
}

/// Send a raw HTTP request over TCP and return the full response text.
/// `extra_headers` is appended verbatim (each line `Name: Value\r\n`).
async fn http_request(
    addr: SocketAddr,
    method: &str,
    path: &str,
    extra_headers: &[(&str, &str)],
) -> String {
    let mut stream = tokio::time::timeout(HANG_GUARD, TcpStream::connect(addr))
        .await
        .expect("connect did not hang")
        .expect("connect succeeds");
    let mut request = format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\n");
    for (name, value) in extra_headers {
        request.push_str(&format!("{name}: {value}\r\n"));
    }
    request.push_str("Connection: close\r\n\r\n");
    stream
        .write_all(request.as_bytes())
        .await
        .expect("write request");
    let mut buffer = Vec::new();
    tokio::time::timeout(HANG_GUARD, stream.read_to_end(&mut buffer))
        .await
        .expect("read did not hang")
        .expect("read succeeds");
    String::from_utf8_lossy(&buffer).into_owned()
}

/// Extract the status line from a raw HTTP response.
fn status_line(response: &str) -> &str {
    response.split("\r\n").next().unwrap_or(response)
}

/// Extract the body (everything after the blank line) from a raw HTTP response.
fn body(response: &str) -> &str {
    response
        .split_once("\r\n\r\n")
        .map(|(_, b)| b)
        .unwrap_or("")
}

/// Extract a header value from a raw HTTP response (first occurrence).
fn header<'a>(response: &'a str, name: &str) -> Option<&'a str> {
    let lower = name.to_ascii_lowercase();
    for line in response.split("\r\n") {
        if let Some((k, v)) = line.split_once(": ")
            && k.to_ascii_lowercase() == lower
        {
            return Some(v.trim());
        }
    }
    None
}

// ── The architectural proof: pre-routing rewrite ─────────────────────────

#[tokio::test]
async fn pre_routing_rewrite_hits_registered_target() {
    // Register `/new` only. The proxy rewrites `/old → /new` *before* route
    // selection, so `/old` (unregistered) reaches `/new`. A post-routing
    // middleware cannot do this: by the time it runs, the router has already
    // matched `/old` against the route table and returned 404.
    let app = Application::new()
        .routes(Routes::new().route("/new", get(|| async { "rewritten" })))
        .proxy(|req| {
            if req.uri().path() == "/old" {
                ProxyAction::Rewrite {
                    uri: "/new".to_owned(),
                }
            } else {
                ProxyAction::continue_default()
            }
        })
        .build();

    let server = RunningApp::start(app).await;

    // `/old` is not registered, but the proxy rewrites it to `/new` before
    // routing — so we get 200 + "rewritten", not 404.
    let response = http_request(server.addr(), "GET", "/old", &[]).await;
    assert!(
        response.starts_with("HTTP/1.1 200 OK"),
        "expected 200 OK after rewrite, got: {}",
        status_line(&response)
    );
    assert_eq!(body(&response), "rewritten");

    // `/new` still works directly (proxy continues it unchanged).
    let response = http_request(server.addr(), "GET", "/new", &[]).await;
    assert!(
        response.starts_with("HTTP/1.1 200 OK"),
        "direct /new: {}",
        status_line(&response)
    );

    server.stop().await;
}

#[tokio::test]
async fn pre_routing_rewrite_with_query_string() {
    // The rewrite URI can include a query string; the router matches the path
    // and the handler reads the query from the URI.
    async fn echo_query(uri: Uri) -> String {
        uri.query().unwrap_or("no query").to_owned()
    }

    let app = Application::new()
        .routes(Routes::new().route("/search", get(echo_query)))
        .proxy(|req| {
            if req.uri().path() == "/find" {
                ProxyAction::Rewrite {
                    uri: "/search?q=hello".to_owned(),
                }
            } else {
                ProxyAction::continue_default()
            }
        })
        .build();

    let server = RunningApp::start(app).await;
    let response = http_request(server.addr(), "GET", "/find", &[]).await;
    assert!(
        response.starts_with("HTTP/1.1 200 OK"),
        "{}",
        status_line(&response)
    );
    assert_eq!(body(&response), "q=hello");
    server.stop().await;
}

// ── Redirect ─────────────────────────────────────────────────────────────

#[tokio::test]
async fn proxy_redirect_302_found() {
    let app = Application::new()
        .routes(Routes::new().route("/here", get(|| async { "here" })))
        .proxy(|_req| ProxyAction::Redirect {
            location: "/here".to_owned(),
            permanent: false,
        })
        .build();

    let server = RunningApp::start(app).await;
    let response = http_request(server.addr(), "GET", "/anything", &[]).await;
    assert!(
        response.starts_with("HTTP/1.1 302 Found"),
        "expected 302, got: {}",
        status_line(&response)
    );
    assert_eq!(header(&response, "location"), Some("/here"));
    server.stop().await;
}

#[tokio::test]
async fn proxy_redirect_301_moved_permanently() {
    let app = Application::new()
        .routes(Routes::new().route("/here", get(|| async { "here" })))
        .proxy(|_req| ProxyAction::Redirect {
            location: "/here".to_owned(),
            permanent: true,
        })
        .build();

    let server = RunningApp::start(app).await;
    let response = http_request(server.addr(), "GET", "/anything", &[]).await;
    assert!(
        response.starts_with("HTTP/1.1 301 Moved Permanently"),
        "expected 301, got: {}",
        status_line(&response)
    );
    assert_eq!(header(&response, "location"), Some("/here"));
    server.stop().await;
}

// ── Short-circuit ────────────────────────────────────────────────────────

#[tokio::test]
async fn proxy_short_circuit_with_status() {
    let handler_called = Arc::new(AtomicUsize::new(0));
    let counter = handler_called.clone();

    let app = Application::new()
        .routes(Routes::new().route(
            "/",
            get(move || {
                let c = counter.clone();
                async move {
                    c.fetch_add(1, Ordering::SeqCst);
                    "handler ran"
                }
            }),
        ))
        .proxy(|_req| ProxyAction::ShortCircuit {
            status: StatusCode::NOT_FOUND,
            response: None,
        })
        .build();

    let server = RunningApp::start(app).await;
    let response = http_request(server.addr(), "GET", "/", &[]).await;
    assert!(
        response.starts_with("HTTP/1.1 404 Not Found"),
        "expected 404, got: {}",
        status_line(&response)
    );
    // The handler must NOT have run — the short-circuit skips routing.
    assert_eq!(
        handler_called.load(Ordering::SeqCst),
        0,
        "handler must not run on short-circuit"
    );
    server.stop().await;
}

#[tokio::test]
async fn proxy_short_circuit_with_custom_response() {
    let app = Application::new()
        .routes(Routes::new().route("/", get(|| async { "handler" })))
        .proxy(|_req| ProxyAction::ShortCircuit {
            status: StatusCode::OK,
            response: Some(("short-circuited").into_response()),
        })
        .build();

    let server = RunningApp::start(app).await;
    let response = http_request(server.addr(), "GET", "/", &[]).await;
    assert!(
        response.starts_with("HTTP/1.1 200 OK"),
        "{}",
        status_line(&response)
    );
    assert_eq!(body(&response), "short-circuited");
    server.stop().await;
}

// ── Continue with header mutation ───────────────────────────────────────

#[tokio::test]
async fn proxy_continue_with_set_headers() {
    // The proxy sets a request header; the handler reads it via HeaderMap.
    async fn echo_header(headers: HeaderMap) -> String {
        headers
            .get("x-proxy-marker")
            .map(|v| v.to_str().unwrap_or_default().to_owned())
            .unwrap_or_else(|| "no marker".to_owned())
    }

    let app = Application::new()
        .routes(Routes::new().route("/", get(echo_header)))
        .proxy(|_req| {
            let mut headers = HeaderMap::new();
            headers.insert("x-proxy-marker", "set-by-proxy".parse().unwrap());
            ProxyAction::Continue {
                set_headers: headers,
            }
        })
        .build();

    let server = RunningApp::start(app).await;
    let response = http_request(server.addr(), "GET", "/", &[]).await;
    assert!(
        response.starts_with("HTTP/1.1 200 OK"),
        "{}",
        status_line(&response)
    );
    assert_eq!(body(&response), "set-by-proxy");
    server.stop().await;
}

// ── Validation rejections ────────────────────────────────────────────────

#[tokio::test]
async fn proxy_invalid_rewrite_uri_rejected_400() {
    let app = Application::new()
        .routes(Routes::new().route("/new", get(|| async { "ok" })))
        .proxy(|_req| ProxyAction::Rewrite {
            uri: "not a valid uri }}}".to_owned(),
        })
        .build();

    let server = RunningApp::start(app).await;
    let response = http_request(server.addr(), "GET", "/old", &[]).await;
    assert!(
        response.starts_with("HTTP/1.1 400 Bad Request"),
        "expected 400 for invalid rewrite URI, got: {}",
        status_line(&response)
    );
    server.stop().await;
}

#[tokio::test]
async fn proxy_rewrite_with_scheme_rejected_400() {
    // A rewrite URI with a scheme is a redirect, not a rewrite. The engine
    // rejects it with 400 — it must not silently redirect to an external host.
    let app = Application::new()
        .routes(Routes::new().route("/new", get(|| async { "ok" })))
        .proxy(|_req| ProxyAction::Rewrite {
            uri: "https://evil.example.com/new".to_owned(),
        })
        .build();

    let server = RunningApp::start(app).await;
    let response = http_request(server.addr(), "GET", "/old", &[]).await;
    assert!(
        response.starts_with("HTTP/1.1 400 Bad Request"),
        "expected 400 for scheme-injected rewrite, got: {}",
        status_line(&response)
    );
    server.stop().await;
}

#[tokio::test]
async fn proxy_redirect_crlf_injection_rejected_400() {
    // CRLF in the redirect location is header injection — reject with 400.
    let app = Application::new()
        .routes(Routes::new().route("/here", get(|| async { "here" })))
        .proxy(|_req| ProxyAction::Redirect {
            location: "/here\r\nSet-Cookie: stolen=1".to_owned(),
            permanent: false,
        })
        .build();

    let server = RunningApp::start(app).await;
    let response = http_request(server.addr(), "GET", "/anything", &[]).await;
    assert!(
        response.starts_with("HTTP/1.1 400 Bad Request"),
        "expected 400 for CRLF in redirect, got: {}",
        status_line(&response)
    );
    // The injected header must NOT appear in the response.
    assert!(
        !response.contains("stolen"),
        "CRLF-injected header must not appear in response"
    );
    server.stop().await;
}

#[tokio::test]
async fn proxy_set_headers_crlf_rejected_by_headervalue() {
    // `HeaderValue` itself rejects CR/LF bytes at construction — this is the
    // first line of defense against CRLF injection in `SetHeaders`. The
    // `merge_headers` function in the proxy service adds defense-in-depth on
    // top, but `HeaderValue` makes it impossible to construct a value with
    // CRLF in the first place. This test proves that defense holds.
    let result = "value\r\nInjected: yes".parse::<arcature::axum::http::HeaderValue>();
    assert!(
        result.is_err(),
        "HeaderValue must reject CRLF in its value — CRLF injection defense"
    );
}

// ── No proxy: pass-through ───────────────────────────────────────────────

#[tokio::test]
async fn no_proxy_passes_through_unchanged() {
    // When no proxy is installed, the pipeline is a pure pass-through — the
    // router sees the original request URI.
    let app = Application::new()
        .routes(Routes::new().route("/", get(|| async { "no proxy" })))
        .build();

    let server = RunningApp::start(app).await;
    let response = http_request(server.addr(), "GET", "/", &[]).await;
    assert!(
        response.starts_with("HTTP/1.1 200 OK"),
        "{}",
        status_line(&response)
    );
    assert_eq!(body(&response), "no proxy");
    server.stop().await;
}

#[tokio::test]
async fn proxy_continue_default_passes_through() {
    // A proxy that always returns `continue_default()` is a no-op — the
    // request proceeds to routing unchanged.
    let app = Application::new()
        .routes(Routes::new().route("/", get(|| async { "continued" })))
        .proxy(|_req| ProxyAction::continue_default())
        .build();

    let server = RunningApp::start(app).await;
    let response = http_request(server.addr(), "GET", "/", &[]).await;
    assert!(
        response.starts_with("HTTP/1.1 200 OK"),
        "{}",
        status_line(&response)
    );
    assert_eq!(body(&response), "continued");
    server.stop().await;
}