ryuk 0.1.1

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
//! Outbound HTTP client, shaped like Laravel's `Http` facade, over `reqwest`.
//!
//! ```no_run
//! use ryuk::http::Http;
//!
//! # async fn demo() -> Result<(), ryuk::http::HttpError> {
//! let res = Http::post("https://api.example.com/orders")
//!     .bearer_token("secret")
//!     .json(&serde_json::json!({ "sku": "abc", "qty": 2 }))
//!     .timeout(std::time::Duration::from_secs(5))
//!     .retry(3, std::time::Duration::from_millis(200))
//!     .send()
//!     .await?;
//! if res.successful() {
//!     let body: serde_json::Value = res.json()?;
//!     println!("{body}");
//! }
//! # Ok(()) }
//! ```

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::{Arc, OnceLock};
use std::time::Duration;

use reqwest::{Method, StatusCode};
use serde::Serialize;
use serde::de::DeserializeOwned;

/// Transport or decoding failure. HTTP error statuses are NOT errors: inspect [`Response`].
#[derive(Debug, thiserror::Error)]
pub enum HttpError {
    /// Connection, timeout, TLS, or invalid request.
    #[error("http request failed: {0}")]
    Request(#[from] reqwest::Error),
    /// A header name or value was invalid, or the body could not be serialized.
    #[error("invalid request: {0}")]
    Invalid(String),
    /// [`PendingRequest::public_only`]: the target is a loopback, private, link-local or otherwise internal address.
    #[error("blocked: {0} is not a public address")]
    Blocked(String),
    /// The response body was not valid JSON for the requested type.
    #[error("invalid json response: {0}")]
    Json(#[from] serde_json::Error),
}

/// Entry points: one per verb.
pub struct Http;

impl Http {
    /// Start a GET request.
    pub fn get(url: &str) -> PendingRequest {
        PendingRequest::new(Method::GET, url)
    }
    /// Start a POST request.
    pub fn post(url: &str) -> PendingRequest {
        PendingRequest::new(Method::POST, url)
    }
    /// Start a PUT request.
    pub fn put(url: &str) -> PendingRequest {
        PendingRequest::new(Method::PUT, url)
    }
    /// Start a PATCH request.
    pub fn patch(url: &str) -> PendingRequest {
        PendingRequest::new(Method::PATCH, url)
    }
    /// Start a DELETE request.
    pub fn delete(url: &str) -> PendingRequest {
        PendingRequest::new(Method::DELETE, url)
    }
}

enum Body {
    None,
    Json(serde_json::Value),
    Form(serde_json::Value),
}

/// A request being built; finish with [`PendingRequest::send`].
pub struct PendingRequest {
    method: Method,
    url: String,
    headers: Vec<(String, String)>,
    body: Body,
    bearer: Option<String>,
    timeout: Option<Duration>,
    attempts: u32,
    delay: Duration,
    err: Option<String>,
    redirects: bool,
    public_only: bool,
}

/// Per-attempt timeout when none is set. A request that can wait forever pins a handler or a queue
/// worker for as long as the other side stays silent; override it with [`PendingRequest::timeout`].
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

impl PendingRequest {
    fn new(method: Method, url: &str) -> Self {
        Self {
            method,
            url: url.into(),
            headers: Vec::new(),
            body: Body::None,
            bearer: None,
            timeout: Some(DEFAULT_TIMEOUT),
            attempts: 1,
            delay: Duration::ZERO,
            err: None,
            redirects: false,
            public_only: false,
        }
    }

    /// Follow redirects (at most 5) **within the same origin** (scheme, host and port). By default a redirect is
    /// returned as the 3xx response and never followed: a redirect to `http://169.254.169.254/` or to an attacker's
    /// host would otherwise carry your `x-api-key`-style headers and a replayed body with it. A redirect to another
    /// origin is still returned to you; follow it yourself after deciding it is allowed.
    pub fn follow_redirects(mut self) -> Self {
        self.redirects = true;
        self
    }

    /// Refuse to connect to internal addresses: loopback, private (RFC 1918), link-local (cloud metadata),
    /// carrier-grade NAT, unique-local and multicast ranges, including IPv4-mapped IPv6 and numeric forms such as
    /// `2130706433` or `0x7f.1`. Use it whenever the URL, or part of it, comes from a user (SSRF).
    ///
    /// Names are checked **where they are resolved**, on the address the connection will actually use, so
    /// DNS rebinding cannot swap in an internal address afterwards. Environment proxies (`HTTP_PROXY`) are ignored
    /// for these requests: a proxy would resolve the name itself and bypass the check.
    ///
    /// ```no_run
    /// # async fn f() {
    /// use ryuk::http::{Http, HttpError};
    /// let r = Http::get("http://127.0.0.1:8080/admin").public_only().send().await;
    /// assert!(matches!(r, Err(HttpError::Blocked(_))));
    /// # }
    /// ```
    pub fn public_only(mut self) -> Self {
        self.public_only = true;
        self
    }

    /// `Authorization: Bearer <token>`.
    pub fn bearer_token(mut self, token: &str) -> Self {
        self.bearer = Some(token.into());
        self
    }

    /// Add a header.
    pub fn with_header(mut self, name: &str, value: &str) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// JSON body (sets `Content-Type: application/json`).
    pub fn json<T: Serialize>(mut self, body: &T) -> Self {
        match serde_json::to_value(body) {
            Ok(v) => self.body = Body::Json(v),
            Err(e) => self.err = Some(e.to_string()),
        }
        self
    }

    /// URL-encoded form body; `body` must serialize to a flat map of scalars.
    pub fn form<T: Serialize>(mut self, body: &T) -> Self {
        match serde_json::to_value(body) {
            Ok(v) => self.body = Body::Form(v),
            Err(e) => self.err = Some(e.to_string()),
        }
        self
    }

    /// Per-attempt timeout (default [`DEFAULT_TIMEOUT`], 30 seconds).
    pub fn timeout(mut self, d: Duration) -> Self {
        self.timeout = Some(d);
        self
    }

    /// Try up to `times` attempts in total, waiting `delay` between them. Only connection errors and 5xx
    /// responses are retried; timeouts and 4xx are not (a retried POST that timed out may have run).
    pub fn retry(mut self, times: u32, delay: Duration) -> Self {
        self.attempts = times.max(1);
        self.delay = delay;
        self
    }

    /// Send the request and buffer the response.
    pub async fn send(self) -> Result<Response, HttpError> {
        if let Some(e) = self.err {
            return Err(HttpError::Invalid(e));
        }
        if self.public_only {
            check_literal(&self.url)?;
        }
        let client = client(self.redirects, self.public_only);
        let mut attempt = 1;
        loop {
            let mut rb = client.request(self.method.clone(), &self.url);
            for (k, v) in &self.headers {
                rb = rb.header(k, v);
            }
            if let Some(t) = &self.bearer {
                rb = rb.bearer_auth(t);
            }
            if let Some(t) = self.timeout {
                rb = rb.timeout(t);
            }
            rb = match &self.body {
                Body::None => rb,
                Body::Json(v) => rb.json(v),
                Body::Form(v) => rb
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(urlencode(v)),
            };
            let last = attempt >= self.attempts;
            match rb.send().await {
                Ok(res) if res.status().is_server_error() && !last => {}
                Ok(res) => {
                    let status = res.status();
                    let headers = res.headers().clone();
                    let body = res.bytes().await?.to_vec();
                    return Ok(Response {
                        status,
                        headers,
                        body,
                    });
                }
                Err(e) if e.is_connect() && !last => {}
                Err(e) => return Err(e.into()),
            }
            attempt += 1;
            tokio::time::sleep(self.delay).await;
        }
    }
}

/// One shared client per (redirects, public_only) combination.
fn client(redirects: bool, public_only: bool) -> &'static reqwest::Client {
    static CLIENTS: [OnceLock<reqwest::Client>; 4] = [
        OnceLock::new(),
        OnceLock::new(),
        OnceLock::new(),
        OnceLock::new(),
    ];
    CLIENTS[redirects as usize * 2 + public_only as usize].get_or_init(|| {
        let mut b = reqwest::Client::builder().redirect(if redirects {
            // Same origin only: scheme, host and port must all match the previous hop.
            reqwest::redirect::Policy::custom(|a| {
                let same = a.previous().last().is_some_and(|p| {
                    p.scheme() == a.url().scheme()
                        && p.host_str() == a.url().host_str()
                        && p.port_or_known_default() == a.url().port_or_known_default()
                });
                if a.previous().len() >= 5 || !same {
                    a.stop()
                } else {
                    a.follow()
                }
            })
        } else {
            reqwest::redirect::Policy::none()
        });
        if public_only {
            b = b.no_proxy().dns_resolver(Arc::new(PublicOnly));
        }
        b.build().expect("http client")
    })
}

/// Resolver that drops every internal address, so the connection can only go to a public one.
struct PublicOnly;

impl reqwest::dns::Resolve for PublicOnly {
    fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
        Box::pin(async move {
            let host = name.as_str().to_string();
            let all = tokio::net::lookup_host((host.as_str(), 0)).await?;
            let public: Vec<SocketAddr> = all.filter(|a| is_public(a.ip())).collect();
            if public.is_empty() {
                return Err(format!("{host} resolves only to internal addresses").into());
            }
            Ok(Box::new(public.into_iter()) as reqwest::dns::Addrs)
        })
    }
}

/// An IP literal in the URL never reaches the resolver; check it here. `Url` already turns
/// `2130706433`, `0x7f.1` and `127.1` into `127.0.0.1`.
fn check_literal(url: &str) -> Result<(), HttpError> {
    let u = reqwest::Url::parse(url).map_err(|e| HttpError::Invalid(e.to_string()))?;
    let ip = u.host_str().and_then(|h| {
        h.trim_matches(|c| c == '[' || c == ']')
            .parse::<IpAddr>()
            .ok()
    });
    match ip {
        Some(ip) if !is_public(ip) => Err(HttpError::Blocked(ip.to_string())),
        _ => Ok(()),
    }
}

/// Whether `ip` is a globally routable unicast address (and not loopback, private, link-local, ...).
pub fn is_public(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(a) => public_v4(a),
        IpAddr::V6(a) => public_v6(a),
    }
}

fn public_v4(a: Ipv4Addr) -> bool {
    let o = a.octets();
    !(a.is_unspecified()
        || a.is_loopback()
        || a.is_private()
        || a.is_link_local()
        || a.is_broadcast()
        || a.is_multicast()
        || a.is_documentation()
        || o[0] == 0 // "this network"
        || (o[0] == 100 && (64..128).contains(&o[1])) // carrier-grade NAT
        || (o[0] == 198 && (o[1] == 18 || o[1] == 19)) // benchmarking
        || o[0] >= 240) // reserved
}

fn public_v6(a: Ipv6Addr) -> bool {
    if let Some(v4) = a.to_ipv4_mapped() {
        return public_v4(v4);
    }
    let s = a.segments();
    // NAT64 (64:ff9b::/96) and 6to4 (2002::/16) carry an IPv4 address that decides where the packet ends up.
    if s[0] == 0x64 && s[1] == 0xff9b && s[2..6] == [0; 4] {
        return public_v4(Ipv4Addr::new(
            (s[6] >> 8) as u8,
            s[6] as u8,
            (s[7] >> 8) as u8,
            s[7] as u8,
        ));
    }
    if s[0] == 0x2002 {
        return public_v4(Ipv4Addr::new(
            (s[1] >> 8) as u8,
            s[1] as u8,
            (s[2] >> 8) as u8,
            s[2] as u8,
        ));
    }
    !(a.is_unspecified()
        || a.is_loopback()
        || a.is_multicast()
        || (s[0] & 0xfe00) == 0xfc00 // unique local
        || (s[0] & 0xffc0) == 0xfe80 // link local
        || (s[0] == 0x2001 && s[1] == 0x0db8)) // documentation
}

/// A fully buffered response.
#[derive(Debug, Clone)]
pub struct Response {
    status: StatusCode,
    headers: reqwest::header::HeaderMap,
    body: Vec<u8>,
}

impl Response {
    /// Status code.
    pub fn status(&self) -> StatusCode {
        self.status
    }
    /// Status is exactly 200.
    pub fn ok(&self) -> bool {
        self.status == StatusCode::OK
    }
    /// Status is 2xx.
    pub fn successful(&self) -> bool {
        self.status.is_success()
    }
    /// Status is 4xx or 5xx.
    pub fn failed(&self) -> bool {
        self.status.is_client_error() || self.status.is_server_error()
    }
    /// Header value, if present and valid UTF-8.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers.get(name)?.to_str().ok()
    }
    /// Raw body.
    pub fn bytes(&self) -> &[u8] {
        &self.body
    }
    /// Body as (lossy) UTF-8 text.
    pub fn text(&self) -> String {
        String::from_utf8_lossy(&self.body).into_owned()
    }
    /// Body decoded as JSON.
    pub fn json<T: DeserializeOwned>(&self) -> Result<T, HttpError> {
        Ok(serde_json::from_slice(&self.body)?)
    }
}

/// `application/x-www-form-urlencoded` for a flat JSON object (nested values are sent as their JSON text).
fn urlencode(v: &serde_json::Value) -> String {
    fn enc(s: &str) -> String {
        let mut o = String::new();
        for b in s.bytes() {
            match b {
                b' ' => o.push('+'),
                b if b.is_ascii_alphanumeric() || b"-._~".contains(&b) => o.push(b as char),
                b => o.push_str(&format!("%{b:02X}")),
            }
        }
        o
    }
    let Some(map) = v.as_object() else {
        return String::new();
    };
    map.iter()
        .filter(|(_, v)| !v.is_null())
        .map(|(k, v)| {
            let val = v
                .as_str()
                .map(str::to_owned)
                .unwrap_or_else(|| v.to_string());
            format!("{}={}", enc(k), enc(&val))
        })
        .collect::<Vec<_>>()
        .join("&")
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{
        Json, Router,
        http::HeaderMap,
        routing::{get, post},
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU32, Ordering};

    async fn serve(app: Router) -> String {
        let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = l.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(l, app).await.unwrap() });
        format!("http://{addr}")
    }

    #[tokio::test]
    async fn verbs_headers_json_form() {
        let app = Router::new()
            .route(
                "/echo",
                post(
                    |h: HeaderMap, Json(b): Json<serde_json::Value>| async move {
                        Json(serde_json::json!({
                            "auth": h["authorization"].to_str().unwrap(),
                            "x": h["x-test"].to_str().unwrap(),
                            "body": b,
                        }))
                    },
                )
                .get(|| async { "plain" })
                .delete(|| async { axum::http::StatusCode::NOT_FOUND }),
            )
            .route("/form", post(|body: String| async move { body }));
        let base = serve(app).await;

        let r = Http::post(&format!("{base}/echo"))
            .bearer_token("tok")
            .with_header("x-test", "1")
            .json(&serde_json::json!({"a": 1}))
            .send()
            .await
            .unwrap();
        assert!(r.ok() && r.successful() && !r.failed());
        let v: serde_json::Value = r.json().unwrap();
        assert_eq!(v["auth"], "Bearer tok");
        assert_eq!(v["x"], "1");
        assert_eq!(v["body"]["a"], 1);

        let r = Http::get(&format!("{base}/echo")).send().await.unwrap();
        assert_eq!(r.text(), "plain");
        let r = Http::delete(&format!("{base}/echo")).send().await.unwrap();
        assert!(r.failed() && !r.successful() && r.status() == 404);

        let r = Http::post(&format!("{base}/form"))
            .form(&serde_json::json!({"k": "a b"}))
            .send()
            .await
            .unwrap();
        assert_eq!(r.text(), "k=a+b");
    }

    #[tokio::test]
    async fn retries_5xx_but_not_4xx() {
        let n = Arc::new(AtomicU32::new(0));
        let (n1, n2) = (n.clone(), n.clone());
        let app = Router::new()
            .route(
                "/flaky",
                get(move || {
                    let n = n1.clone();
                    async move {
                        if n.fetch_add(1, Ordering::SeqCst) < 2 {
                            axum::http::StatusCode::BAD_GATEWAY
                        } else {
                            axum::http::StatusCode::OK
                        }
                    }
                }),
            )
            .route(
                "/bad",
                get(move || {
                    let n = n2.clone();
                    async move {
                        n.fetch_add(100, Ordering::SeqCst);
                        axum::http::StatusCode::BAD_REQUEST
                    }
                }),
            );
        let base = serve(app).await;
        let r = Http::get(&format!("{base}/flaky"))
            .retry(3, Duration::from_millis(1))
            .send()
            .await
            .unwrap();
        assert!(r.ok());
        assert_eq!(n.load(Ordering::SeqCst), 3);

        n.store(0, Ordering::SeqCst);
        let r = Http::get(&format!("{base}/bad"))
            .retry(3, Duration::from_millis(1))
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 400);
        assert_eq!(n.load(Ordering::SeqCst), 100);

        // retries exhausted on 5xx: the last response is returned, not an error
        n.store(0, Ordering::SeqCst);
        let r = Http::get(&format!("{base}/flaky"))
            .retry(2, Duration::ZERO)
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 502);
    }

    #[test]
    fn requests_have_a_default_timeout() {
        assert_eq!(DEFAULT_TIMEOUT, Duration::from_secs(30));
        assert_eq!(
            PendingRequest::new(Method::GET, "http://x.test").timeout,
            Some(DEFAULT_TIMEOUT)
        );
        assert_eq!(
            PendingRequest::new(Method::GET, "http://x.test")
                .timeout(Duration::from_secs(2))
                .timeout,
            Some(Duration::from_secs(2))
        );
    }

    #[tokio::test]
    async fn connect_error_is_error_after_retries_and_timeout_applies() {
        let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = l.local_addr().unwrap();
        drop(l);
        let e = Http::get(&format!("http://{addr}/"))
            .retry(2, Duration::from_millis(1))
            .send()
            .await;
        assert!(matches!(e, Err(HttpError::Request(_))));

        let base = serve(Router::new().route(
            "/slow",
            get(|| async {
                tokio::time::sleep(Duration::from_secs(5)).await;
            }),
        ))
        .await;
        let e = Http::get(&format!("{base}/slow"))
            .timeout(Duration::from_millis(50))
            .send()
            .await;
        assert!(matches!(e, Err(HttpError::Request(ref e)) if e.is_timeout()));
    }

    #[test]
    fn internal_addresses_are_not_public() {
        for ip in [
            "127.0.0.1",
            "10.1.2.3",
            "172.16.0.1",
            "192.168.1.1",
            "169.254.169.254",
            "0.0.0.0",
            "100.64.0.1",
            "255.255.255.255",
            "224.0.0.1",
            "::1",
            "::",
            "fe80::1",
            "fc00::1",
            "fd12::1",
            "::ffff:127.0.0.1",
            "::ffff:10.0.0.1",
            "64:ff9b::7f00:1",
            "2002:7f00:1::1",
            "ff02::1",
        ] {
            assert!(!is_public(ip.parse().unwrap()), "{ip} must be blocked");
        }
        for ip in [
            "8.8.8.8",
            "93.184.216.34",
            "2606:4700:4700::1111",
            "::ffff:8.8.8.8",
        ] {
            assert!(is_public(ip.parse().unwrap()), "{ip} must be allowed");
        }
    }

    #[tokio::test]
    async fn public_only_blocks_every_spelling_of_an_internal_address() {
        for url in [
            "http://127.0.0.1:1/",
            "http://2130706433:1/",
            "http://0x7f.1:1/",
            "http://0177.0.0.1:1/",
            "http://127.1:1/",
            "http://[::ffff:127.0.0.1]:1/",
            "http://user@127.0.0.1:1/",
            "http://169.254.169.254/latest/meta-data/",
            "http://[::1]:1/",
        ] {
            let r = Http::get(url).public_only().send().await;
            assert!(matches!(r, Err(HttpError::Blocked(_))), "{url}: {r:?}");
        }
        // A name is checked at resolution: `localhost` resolves to loopback only, so it never connects.
        let base = serve(Router::new().route("/", get(|| async { "internal" }))).await;
        let port = base.rsplit(':').next().unwrap();
        let r = Http::get(&format!("http://localhost:{port}/"))
            .public_only()
            .send()
            .await;
        assert!(matches!(r, Err(HttpError::Request(_))), "{r:?}");
        // Without the flag the same request works.
        assert_eq!(
            Http::get(&format!("{base}/")).send().await.unwrap().text(),
            "internal"
        );
    }

    #[tokio::test]
    async fn redirects_are_not_followed_unless_asked_and_never_across_origins() {
        let secret = serve(Router::new().route(
            "/x",
            get(|h: HeaderMap| async move { format!("{:?}", h.get("x-api-key")) }),
        ))
        .await;
        let to = format!("{secret}/x");
        let hop = Router::new()
            .route(
                "/other",
                get(move || {
                    let to = to.clone();
                    async move { axum::response::Redirect::temporary(&to) }
                }),
            )
            .route(
                "/a",
                get(|| async { axum::response::Redirect::temporary("/b") }),
            )
            .route("/b", get(|| async { "landed" }));
        let base = serve(hop).await;

        let r = Http::get(&format!("{base}/other"))
            .with_header("x-api-key", "K")
            .send()
            .await
            .unwrap();
        assert_eq!(
            r.status(),
            307,
            "default: the redirect is returned, not followed"
        );
        let r = Http::get(&format!("{base}/other"))
            .with_header("x-api-key", "K")
            .follow_redirects()
            .send()
            .await
            .unwrap();
        assert_eq!(
            r.status(),
            307,
            "another origin (port) is never followed, so the header never leaves"
        );
        let r = Http::get(&format!("{base}/a")).send().await.unwrap();
        assert_eq!(r.status(), 307);
        let r = Http::get(&format!("{base}/a"))
            .follow_redirects()
            .send()
            .await
            .unwrap();
        assert_eq!(r.text(), "landed", "same origin is followed");
    }
}