soaprs-http 0.3.0

Transport-neutral HTTP contracts and policies for soaprs
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
//! Framework-neutral response effects used by auth and HTTP extension packages.

use std::{fmt, time::Duration};

use http::{
    HeaderMap, HeaderName, HeaderValue, StatusCode, Uri,
    header::{LOCATION, WWW_AUTHENTICATE},
};
use soaprs_core::{SoapError, SoapResult};

/// Browser SameSite cookie behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SameSite {
    /// Cookie is withheld from cross-site requests.
    Strict,
    /// Cookie is available to safe top-level cross-site navigation.
    Lax,
    /// Cookie is available cross-site and therefore must also be secure.
    None,
}

/// Transport-neutral cookie mutation returned by HTTP modules.
#[derive(Clone, PartialEq, Eq)]
pub struct ResponseCookie {
    /// Cookie name.
    pub name: String,
    /// Opaque cookie value.
    pub value: String,
    /// Optional path scope.
    pub path: Option<String>,
    /// Optional domain scope.
    pub domain: Option<String>,
    /// Optional relative lifetime.
    pub max_age: Option<Duration>,
    /// Restricts transmission to secure transports.
    pub secure: bool,
    /// Hides the cookie from browser scripting APIs.
    pub http_only: bool,
    /// Browser cross-site behavior.
    pub same_site: Option<SameSite>,
}

impl fmt::Debug for ResponseCookie {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ResponseCookie")
            .field("name", &self.name)
            .field("value", &"[REDACTED]")
            .field("path", &self.path)
            .field("domain", &self.domain)
            .field("max_age", &self.max_age)
            .field("secure", &self.secure)
            .field("http_only", &self.http_only)
            .field("same_site", &self.same_site)
            .finish()
    }
}

impl ResponseCookie {
    /// Creates a validated cookie with secure HTTP-only defaults.
    pub fn new(name: impl Into<String>, value: impl Into<String>) -> SoapResult<Self> {
        let name = name.into();
        let value = value.into();
        validate_cookie(&name, &value)?;
        Ok(Self {
            name,
            value,
            path: Some("/".to_owned()),
            domain: None,
            max_age: None,
            secure: true,
            http_only: true,
            same_site: Some(SameSite::Lax),
        })
    }

    /// Creates a secure cookie deletion effect using `Max-Age=0`.
    pub fn remove(name: impl Into<String>) -> SoapResult<Self> {
        let mut cookie = Self::new(name, "")?;
        cookie.max_age = Some(Duration::ZERO);
        Ok(cookie)
    }

    /// Sets the cookie path.
    pub fn path(mut self, path: impl Into<String>) -> SoapResult<Self> {
        let path = path.into();
        if !path.starts_with('/') || path.chars().any(char::is_control) || path.contains(';') {
            return Err(SoapError::validation("invalid cookie path"));
        }
        self.path = Some(path);
        Ok(self)
    }

    /// Sets the cookie domain.
    pub fn domain(mut self, domain: impl Into<String>) -> SoapResult<Self> {
        let domain = domain.into();
        validate_cookie_domain(&domain)?;
        self.domain = Some(domain);
        Ok(self)
    }

    /// Sets a relative lifetime. Zero represents immediate deletion.
    #[must_use]
    pub const fn max_age(mut self, max_age: Duration) -> Self {
        self.max_age = Some(max_age);
        self
    }

    /// Changes browser cross-site behavior.
    pub fn same_site(mut self, same_site: SameSite) -> SoapResult<Self> {
        if same_site == SameSite::None && !self.secure {
            return Err(SoapError::validation(
                "SameSite=None cookies must be secure",
            ));
        }
        self.same_site = Some(same_site);
        Ok(self)
    }

    /// Allows transmission over insecure transport for local development.
    ///
    /// This is rejected while `SameSite=None` is selected.
    pub fn insecure(mut self) -> SoapResult<Self> {
        if self.same_site == Some(SameSite::None) {
            return Err(SoapError::validation(
                "SameSite=None cookies must be secure",
            ));
        }
        self.secure = false;
        Ok(self)
    }

    /// Makes the cookie visible to browser scripts.
    #[must_use]
    pub const fn script_accessible(mut self) -> Self {
        self.http_only = false;
        self
    }

    /// Validates cookie attributes after direct public-field mutation.
    pub fn validate(&self) -> SoapResult<()> {
        validate_cookie(&self.name, &self.value)?;
        if self.path.as_ref().is_some_and(|path| {
            !path.starts_with('/') || path.chars().any(char::is_control) || path.contains(';')
        }) {
            return Err(SoapError::validation("invalid cookie path"));
        }
        if let Some(domain) = &self.domain {
            validate_cookie_domain(domain)?;
        }
        if self.same_site == Some(SameSite::None) && !self.secure {
            return Err(SoapError::validation(
                "SameSite=None cookies must be secure",
            ));
        }
        Ok(())
    }
}

/// Structured `WWW-Authenticate` challenge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthChallenge {
    scheme: String,
    parameters: Vec<(String, String)>,
}

impl AuthChallenge {
    /// Creates a challenge for a validated authentication scheme.
    pub fn new(scheme: impl Into<String>) -> SoapResult<Self> {
        let scheme = scheme.into();
        if !valid_token(&scheme) {
            return Err(SoapError::validation(format!(
                "invalid authentication scheme `{scheme}`"
            )));
        }
        Ok(Self {
            scheme,
            parameters: Vec::new(),
        })
    }

    /// Adds or replaces the challenge realm.
    pub fn realm(self, realm: impl Into<String>) -> SoapResult<Self> {
        self.parameter("realm", realm)
    }

    /// Adds or replaces one quoted challenge parameter.
    pub fn parameter(
        mut self,
        name: impl Into<String>,
        value: impl Into<String>,
    ) -> SoapResult<Self> {
        let name = name.into();
        let value = value.into();
        if !valid_token(&name) || value.chars().any(char::is_control) {
            return Err(SoapError::validation(
                "invalid authentication challenge parameter",
            ));
        }
        if let Some(existing) = self
            .parameters
            .iter_mut()
            .find(|(existing, _)| existing.eq_ignore_ascii_case(&name))
        {
            *existing = (name, value);
        } else {
            self.parameters.push((name, value));
        }
        Ok(self)
    }

    /// Returns the authentication scheme.
    pub fn scheme(&self) -> &str {
        &self.scheme
    }

    /// Encodes the challenge as a valid HTTP header value.
    pub fn to_header_value(&self) -> SoapResult<HeaderValue> {
        let mut encoded = self.scheme.clone();
        for (index, (name, value)) in self.parameters.iter().enumerate() {
            if index == 0 {
                encoded.push(' ');
            } else {
                encoded.push_str(", ");
            }
            encoded.push_str(name);
            encoded.push_str("=\"");
            for character in value.chars() {
                if matches!(character, '\\' | '"') {
                    encoded.push('\\');
                }
                encoded.push(character);
            }
            encoded.push('"');
        }
        HeaderValue::from_str(&encoded)
            .map_err(|_| SoapError::validation("authentication challenge cannot be encoded"))
    }
}

impl fmt::Display for AuthChallenge {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.to_header_value() {
            Ok(value) => formatter.write_str(value.to_str().unwrap_or(self.scheme())),
            Err(_) => formatter.write_str(self.scheme()),
        }
    }
}

/// Validated redirect response effect.
#[derive(Clone, PartialEq, Eq)]
pub struct Redirect {
    /// Redirect status code.
    pub status: StatusCode,
    /// Absolute or relative redirect target.
    pub location: Uri,
}

impl fmt::Debug for Redirect {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Redirect")
            .field("status", &self.status)
            .field("location", &"[REDACTED]")
            .finish()
    }
}

impl Redirect {
    /// Creates a redirect using one of 301, 302, 303, 307, or 308.
    pub fn new(status: StatusCode, location: Uri) -> SoapResult<Self> {
        if !matches!(
            status,
            StatusCode::MOVED_PERMANENTLY
                | StatusCode::FOUND
                | StatusCode::SEE_OTHER
                | StatusCode::TEMPORARY_REDIRECT
                | StatusCode::PERMANENT_REDIRECT
        ) {
            return Err(SoapError::validation(
                "redirect status must be 301, 302, 303, 307, or 308",
            ));
        }
        Ok(Self { status, location })
    }

    /// Validates redirect status after direct public-field mutation.
    pub fn validate(&self) -> SoapResult<()> {
        if matches!(
            self.status,
            StatusCode::MOVED_PERMANENTLY
                | StatusCode::FOUND
                | StatusCode::SEE_OTHER
                | StatusCode::TEMPORARY_REDIRECT
                | StatusCode::PERMANENT_REDIRECT
        ) {
            Ok(())
        } else {
            Err(SoapError::validation(
                "redirect status must be 301, 302, 303, 307, or 308",
            ))
        }
    }
}

/// Headers, cookies, status, and redirects emitted by a transport-neutral module.
#[derive(Clone, Default)]
pub struct HttpResponseEffects {
    /// Optional response status override.
    pub status: Option<StatusCode>,
    /// Response headers to insert or append.
    pub headers: HeaderMap,
    /// Structured cookie mutations.
    pub cookies: Vec<ResponseCookie>,
    /// Optional redirect instruction.
    pub redirect: Option<Redirect>,
}

impl fmt::Debug for HttpResponseEffects {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("HttpResponseEffects")
            .field("status", &self.status)
            .field("header_names", &self.headers.keys().collect::<Vec<_>>())
            .field("cookies", &self.cookies)
            .field("redirect", &self.redirect)
            .finish_non_exhaustive()
    }
}

impl HttpResponseEffects {
    /// Creates empty response effects.
    pub fn new() -> Self {
        Self::default()
    }

    /// Overrides the response status.
    #[must_use]
    pub const fn status(mut self, status: StatusCode) -> Self {
        self.status = Some(status);
        self
    }

    /// Inserts or replaces one response header.
    #[must_use]
    pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
        self.headers.insert(name, value);
        self
    }

    /// Appends a response header without replacing existing values.
    #[must_use]
    pub fn append_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
        self.headers.append(name, value);
        self
    }

    /// Appends one structured response cookie.
    pub fn cookie(mut self, cookie: ResponseCookie) -> SoapResult<Self> {
        cookie.validate()?;
        self.cookies.push(cookie);
        Ok(self)
    }

    /// Appends one structured authentication challenge.
    pub fn challenge(mut self, challenge: &AuthChallenge) -> SoapResult<Self> {
        self.headers
            .append(WWW_AUTHENTICATE, challenge.to_header_value()?);
        Ok(self)
    }

    /// Applies a validated redirect and matching `Location` header.
    pub fn redirect(mut self, redirect: Redirect) -> SoapResult<Self> {
        redirect.validate()?;
        let location = HeaderValue::from_str(&redirect.location.to_string())
            .map_err(|_| SoapError::validation("redirect URI cannot be encoded"))?;
        self.status = Some(redirect.status);
        self.headers.insert(LOCATION, location);
        self.redirect = Some(redirect);
        Ok(self)
    }

    /// Validates structured effects after direct public-field mutation.
    pub fn validate(&self) -> SoapResult<()> {
        self.cookies.iter().try_for_each(ResponseCookie::validate)?;
        if let Some(redirect) = &self.redirect {
            redirect.validate()?;
            if self.status != Some(redirect.status) {
                return Err(SoapError::validation(
                    "redirect effect status does not match redirect status",
                ));
            }
            let expected = HeaderValue::from_str(&redirect.location.to_string())
                .map_err(|_| SoapError::validation("redirect URI cannot be encoded"))?;
            if self.headers.get(LOCATION) != Some(&expected) {
                return Err(SoapError::validation(
                    "redirect effect is missing its matching Location header",
                ));
            }
        }
        Ok(())
    }
}

fn validate_cookie(name: &str, value: &str) -> SoapResult<()> {
    if !valid_token(name) || !value.bytes().all(valid_cookie_value_byte) {
        return Err(SoapError::validation("invalid HTTP cookie name or value"));
    }
    Ok(())
}

fn valid_cookie_value_byte(byte: u8) -> bool {
    matches!(byte, 0x21 | 0x23..=0x2b | 0x2d..=0x3a | 0x3c..=0x5b | 0x5d..=0x7e)
}

fn validate_cookie_domain(domain: &str) -> SoapResult<()> {
    let domain = domain.strip_prefix('.').unwrap_or(domain);
    if domain.is_empty()
        || domain.contains("..")
        || domain.split('.').any(|label| {
            label.is_empty()
                || label.starts_with('-')
                || label.ends_with('-')
                || !label
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
        })
    {
        return Err(SoapError::validation("invalid cookie domain"));
    }
    Ok(())
}

fn valid_token(value: &str) -> bool {
    !value.is_empty()
        && value.chars().all(|character| {
            character.is_ascii_alphanumeric()
                || matches!(
                    character,
                    '!' | '#'
                        | '$'
                        | '%'
                        | '&'
                        | '\''
                        | '*'
                        | '+'
                        | '-'
                        | '.'
                        | '^'
                        | '_'
                        | '`'
                        | '|'
                        | '~'
                )
        })
}

#[cfg(test)]
mod tests {
    use http::{StatusCode, Uri, header::WWW_AUTHENTICATE};

    use super::{AuthChallenge, HttpResponseEffects, Redirect, ResponseCookie, SameSite};

    #[test]
    fn auth_challenges_are_structured_and_escape_quoted_values() {
        let challenge = AuthChallenge::new("Bearer")
            .and_then(|value| value.realm("api\"users"))
            .and_then(|value| value.parameter("error", "invalid_token"));
        let Some(challenge) = challenge.ok() else {
            panic!("valid challenge");
        };
        let effects = HttpResponseEffects::new().challenge(&challenge);
        let encoded = effects.ok().and_then(|value| {
            value
                .headers
                .get(WWW_AUTHENTICATE)
                .and_then(|header| header.to_str().ok())
                .map(str::to_owned)
        });
        assert_eq!(
            encoded.as_deref(),
            Some("Bearer realm=\"api\\\"users\", error=\"invalid_token\"")
        );
    }

    #[test]
    fn cookies_use_secure_defaults_and_reject_insecure_same_site_none() {
        let cookie = ResponseCookie::new("access_token", "opaque");
        assert_eq!(
            cookie
                .as_ref()
                .ok()
                .map(|value| (value.secure, value.http_only, value.same_site)),
            Some((true, true, Some(SameSite::Lax)))
        );
        assert!(
            cookie
                .and_then(ResponseCookie::insecure)
                .and_then(|value| value.same_site(SameSite::None))
                .is_err()
        );
        assert_eq!(
            ResponseCookie::remove("access_token")
                .ok()
                .and_then(|value| value.max_age),
            Some(std::time::Duration::ZERO)
        );
    }

    #[test]
    fn redirects_require_redirect_status_and_emit_location() {
        let location = Uri::from_static("/login");
        assert!(Redirect::new(StatusCode::OK, location.clone()).is_err());
        let redirect = Redirect::new(StatusCode::SEE_OTHER, location);
        assert!(
            redirect
                .and_then(|value| HttpResponseEffects::new().redirect(value))
                .is_ok()
        );
    }

    #[test]
    fn response_effects_revalidate_public_cookie_and_redirect_fields() {
        let Some(mut cookie) = ResponseCookie::new("session", "opaque").ok() else {
            panic!("valid cookie fixture");
        };
        cookie.value = "invalid value".to_owned();
        assert!(HttpResponseEffects::new().cookie(cookie.clone()).is_err());

        let mut effects = HttpResponseEffects::new();
        effects.cookies.push(cookie);
        assert!(effects.validate().is_err());

        let Some(mut redirect) =
            Redirect::new(StatusCode::SEE_OTHER, Uri::from_static("/login")).ok()
        else {
            panic!("valid redirect fixture");
        };
        redirect.status = StatusCode::OK;
        assert!(HttpResponseEffects::new().redirect(redirect).is_err());
    }

    #[test]
    fn response_debug_output_redacts_cookie_and_header_values() {
        let Some(cookie) = ResponseCookie::new("session", "cookie-secret").ok() else {
            panic!("valid cookie fixture");
        };
        let effects = HttpResponseEffects::new()
            .header(
                http::header::AUTHORIZATION,
                http::HeaderValue::from_static("Bearer header-secret"),
            )
            .cookie(cookie);
        let Some(effects) = effects.ok() else {
            panic!("valid response effects");
        };
        let debug = format!("{effects:?}");

        assert!(debug.contains("authorization"));
        assert!(debug.contains("session"));
        assert!(!debug.contains("header-secret"));
        assert!(!debug.contains("cookie-secret"));
    }
}