securitydept-utils 0.3.0-beta.2

Utils of SecurityDept, a layered authentication and authorization toolkit built as reusable Rust crates.
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
use std::{
    fmt::{self, Display},
    str::FromStr,
    sync::OnceLock,
};

use rfc7239::parse as parse_forwarded;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Parsed representation of the `oidc_redirect_url_base` config value.
#[derive(Debug, Clone, Default)]
pub enum ExternalBaseUrl {
    /// Infer from request headers at runtime.
    #[default]
    Auto,
    /// Use this fixed URL.
    Fixed(String),
}

impl FromStr for ExternalBaseUrl {
    type Err = std::io::Error;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        if value.trim().eq_ignore_ascii_case("auto") {
            Ok(Self::Auto)
        } else {
            Ok(Self::Fixed(value.trim_end_matches('/').to_string()))
        }
    }
}

impl Display for ExternalBaseUrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ExternalBaseUrl::Auto => write!(f, "auto"),
            ExternalBaseUrl::Fixed(url) => write!(f, "{}", url),
        }
    }
}

impl<'de> Deserialize<'de> for ExternalBaseUrl {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(serde::de::Error::custom)
    }
}

impl Serialize for ExternalBaseUrl {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl ExternalBaseUrl {
    /// Resolve the external base URL from config + HTTP request headers.
    ///
    /// When config is `Auto`, the priority is:
    ///   1. `Forwarded` header (RFC 7239) — extract `host` and `proto`
    ///   2. `X-Forwarded-Host` / `X-Forwarded-Proto` (common non-standard)
    ///   3. `Host` / `:authority` (standard HTTP header)
    ///   4. Fallback to `http://{bind_host}:{bind_port}`
    ///
    /// When config is `Fixed(url)`, just return that URL.
    pub fn resolve_url(
        &self,
        headers: &http::HeaderMap,
        fallback_host: &str,
        fallback_port: u16,
    ) -> Result<url::Url, url::ParseError> {
        match self {
            ExternalBaseUrl::Fixed(url) => url::Url::parse(url),
            ExternalBaseUrl::Auto => url::Url::parse(&infer_external_base_url_from_headers(
                headers,
                fallback_host,
                fallback_port,
            )),
        }
    }
}

/// HTTP/2 `:authority` pseudo-header name. Only present when the `http` crate
/// accepts it.
static AUTHORITY_HEADER_NAME: OnceLock<Option<http::HeaderName>> = OnceLock::new();

fn authority_header_name() -> Option<&'static http::HeaderName> {
    AUTHORITY_HEADER_NAME
        .get_or_init(|| http::HeaderName::from_bytes(b":authority").ok())
        .as_ref()
}

pub fn resolve_external_base_url(
    config: &ExternalBaseUrl,
    headers: &http::HeaderMap,
    fallback_host: &str,
    fallback_port: u16,
) -> String {
    match config {
        ExternalBaseUrl::Fixed(url) => url.clone(),
        ExternalBaseUrl::Auto => {
            infer_external_base_url_from_headers(headers, fallback_host, fallback_port)
        }
    }
}

/// Infer external base URL from request headers.
///
/// Each source yields (host, protocol) independently; we take the first
/// non-None host and first non-None protocol by priority, then infer protocol
/// from host if still missing, then fallback to bind address.
fn infer_external_base_url_from_headers(
    headers: &http::HeaderMap,
    fallback_host: &str,
    fallback_port: u16,
) -> String {
    let sources: [(Option<String>, Option<String>); 3] = [
        try_forwarded(headers),
        try_x_forwarded(headers),
        try_host_header(headers),
    ];

    let host_from_headers = sources.iter().find_map(|(h, _)| h.clone());
    let host = host_from_headers
        .clone()
        .unwrap_or_else(|| format_fallback_host(fallback_host, fallback_port));

    let protocol = sources
        .iter()
        .find_map(|(_, p)| p.clone())
        .or_else(|| {
            host_from_headers
                .as_ref()
                .map(|h| infer_protocol_from_host(h).to_string())
        })
        .unwrap_or_else(|| "http".to_string());

    format!("{}://{}", protocol, host)
}

/// Forwarded (RFC 7239): (host, protocol). Uses first node; strips quotes per
/// §4.
fn try_forwarded(headers: &http::HeaderMap) -> (Option<String>, Option<String>) {
    let value = match headers
        .get(http::header::FORWARDED)
        .and_then(|v| v.to_str().ok())
    {
        Some(v) => v,
        None => return (None, None),
    };
    let mut nodes = parse_forwarded(value);
    let node = match nodes.next().and_then(|r| r.ok()) {
        Some(n) => n,
        None => return (None, None),
    };
    let host = node.host.map(|s| s.trim_matches('"').to_string());
    let protocol = node.protocol.map(|s| s.trim_matches('"').to_string());
    (host, protocol)
}

/// X-Forwarded-Host / X-Forwarded-Proto: (host, protocol). Proto is None if
/// header missing.
fn try_x_forwarded(headers: &http::HeaderMap) -> (Option<String>, Option<String>) {
    let host = headers
        .get("x-forwarded-host")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty());
    let protocol = headers
        .get("x-forwarded-proto")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty());
    (host, protocol)
}

/// Host / :authority: (host, None). Host is HTTP/1.1; :authority is the HTTP/2
/// pseudo-header. Protocol cannot be inferred from these alone.
fn try_host_header(headers: &http::HeaderMap) -> (Option<String>, Option<String>) {
    let host = headers
        .get(http::header::HOST)
        .or_else(|| authority_header_name().and_then(|name| headers.get(name)))
        .and_then(|v| v.to_str().ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty());
    (host, None)
}

/// When protocol is missing (e.g. only Host header), infer from host: loopback
/// → http, else https.
fn infer_protocol_from_host(host: &str) -> &'static str {
    if is_loopback_host(host) {
        "http"
    } else {
        "https"
    }
}

fn format_fallback_host(host: &str, port: u16) -> String {
    if is_default_port("http", port) {
        host.to_string()
    } else {
        format!("{}:{}", host, port)
    }
}

fn is_default_port(proto: &str, port: u16) -> bool {
    matches!((proto, port), ("http", 80) | ("https", 443))
}

fn is_loopback_host(host: &str) -> bool {
    // Strip port if present
    let hostname = host.split(':').next().unwrap_or(host);
    matches!(hostname, "localhost" | "127.0.0.1" | "::1" | "[::1]")
}

#[cfg(test)]
mod tests {
    use http::HeaderMap;

    use super::*;

    fn make_fallback() -> (&'static str, u16) {
        ("0.0.0.0", 7021)
    }

    #[test]
    fn fixed_config_ignores_headers() {
        let config = ExternalBaseUrl::Fixed("https://fixed.example.com".to_string());
        let headers = HeaderMap::new();
        let (host, port) = make_fallback();
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "https://fixed.example.com"
        );
    }

    #[test]
    fn auto_with_forwarded_header() {
        let config = ExternalBaseUrl::Auto;
        let mut headers = HeaderMap::new();
        headers.insert(
            "forwarded",
            "for=192.0.2.60;proto=https;host=example.com"
                .parse()
                .unwrap(),
        );
        let (host, port) = make_fallback();
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "https://example.com"
        );
    }

    #[test]
    fn auto_with_forwarded_header_custom_port() {
        let config = ExternalBaseUrl::Auto;
        let mut headers = HeaderMap::new();
        headers.insert(
            "forwarded",
            "proto=https;host=example.com:8443".parse().unwrap(),
        );
        let (host, port) = make_fallback();
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "https://example.com:8443"
        );
    }

    #[test]
    fn auto_with_forwarded_header_no_proto() {
        let config = ExternalBaseUrl::Auto;
        let mut headers = HeaderMap::new();
        headers.insert("forwarded", "host=example.com".parse().unwrap());
        let (host, port) = make_fallback();
        // Default to https when proto is missing
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "https://example.com"
        );
    }

    #[test]
    fn auto_with_x_forwarded_headers() {
        let config = ExternalBaseUrl::Auto;
        let mut headers = HeaderMap::new();
        headers.insert("x-forwarded-host", "proxy.example.com".parse().unwrap());
        headers.insert("x-forwarded-proto", "https".parse().unwrap());
        let (host, port) = make_fallback();
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "https://proxy.example.com"
        );
    }

    #[test]
    fn auto_with_x_forwarded_host_only() {
        let config = ExternalBaseUrl::Auto;
        let mut headers = HeaderMap::new();
        headers.insert("x-forwarded-host", "proxy.example.com".parse().unwrap());
        let (host, port) = make_fallback();
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "https://proxy.example.com"
        );
    }

    #[test]
    fn auto_with_host_header() {
        let config = ExternalBaseUrl::Auto;
        let mut headers = HeaderMap::new();
        headers.insert(http::header::HOST, "myhost.example.com".parse().unwrap());
        let (host, port) = make_fallback();
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "https://myhost.example.com"
        );
    }

    #[test]
    fn auto_with_localhost_host_header() {
        let config = ExternalBaseUrl::Auto;
        let mut headers = HeaderMap::new();
        headers.insert(http::header::HOST, "localhost:3000".parse().unwrap());
        let (host, port) = make_fallback();
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "http://localhost:3000"
        );
    }

    #[test]
    fn auto_fallback_to_bind_address() {
        let config = ExternalBaseUrl::Auto;
        let headers = HeaderMap::new();
        assert_eq!(
            resolve_external_base_url(&config, &headers, "0.0.0.0", 7021),
            "http://0.0.0.0:7021"
        );
    }

    #[test]
    fn auto_fallback_default_port() {
        let config = ExternalBaseUrl::Auto;
        let headers = HeaderMap::new();
        assert_eq!(
            resolve_external_base_url(&config, &headers, "0.0.0.0", 80),
            "http://0.0.0.0"
        );
    }

    #[test]
    fn forwarded_takes_priority_over_x_forwarded() {
        let config = ExternalBaseUrl::Auto;
        let mut headers = HeaderMap::new();
        headers.insert(
            "forwarded",
            "proto=https;host=rfc.example.com".parse().unwrap(),
        );
        headers.insert(
            "x-forwarded-host",
            "nonstandard.example.com".parse().unwrap(),
        );
        let (host, port) = make_fallback();
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "https://rfc.example.com"
        );
    }

    #[test]
    fn x_forwarded_takes_priority_over_host() {
        let config = ExternalBaseUrl::Auto;
        let mut headers = HeaderMap::new();
        headers.insert("x-forwarded-host", "proxy.example.com".parse().unwrap());
        headers.insert("x-forwarded-proto", "https".parse().unwrap());
        headers.insert(http::header::HOST, "internal.example.com".parse().unwrap());
        let (host, port) = make_fallback();
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "https://proxy.example.com"
        );
    }

    #[test]
    fn forwarded_with_quoted_values() {
        let config = ExternalBaseUrl::Auto;
        let mut headers = HeaderMap::new();
        headers.insert(
            "forwarded",
            "for=\"192.0.2.60\";proto=https;host=\"quoted.example.com\""
                .parse()
                .unwrap(),
        );
        let (host, port) = make_fallback();
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "https://quoted.example.com"
        );
    }

    #[test]
    fn forwarded_chain_uses_first_entry() {
        let config = ExternalBaseUrl::Auto;
        let mut headers = HeaderMap::new();
        headers.insert(
            "forwarded",
            "proto=https;host=first.example.com, proto=http;host=second.example.com"
                .parse()
                .unwrap(),
        );
        let (host, port) = make_fallback();
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "https://first.example.com"
        );
    }

    #[test]
    fn authority_used_when_host_absent_if_supported() {
        let name = match authority_header_name() {
            Some(n) => n.clone(),
            None => return, // http crate does not accept :authority
        };
        let config = ExternalBaseUrl::Auto;
        let mut headers = HeaderMap::new();
        headers.insert(name, "h2.example.com".parse().unwrap());
        let (host, port) = make_fallback();
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "https://h2.example.com"
        );
    }

    #[test]
    fn host_takes_priority_over_authority() {
        let config = ExternalBaseUrl::Auto;
        let mut headers = HeaderMap::new();
        headers.insert(http::header::HOST, "host.example.com".parse().unwrap());
        if let Some(name) = authority_header_name() {
            headers.insert(name.clone(), "authority.example.com".parse().unwrap());
        }
        let (host, port) = make_fallback();
        assert_eq!(
            resolve_external_base_url(&config, &headers, host, port),
            "https://host.example.com"
        );
    }
}