rama-http-headers 0.3.0-rc1

typed http headers for rama
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
//! Authorization header and types.

use std::ops::{Deref, DerefMut};

use base64::Engine;
use base64::engine::general_purpose::STANDARD as ENGINE;

use rama_core::extensions::Extensions;
use rama_core::telemetry::tracing;
use rama_core::username::{UsernameLabelParser, parse_username};
use rama_http_types::{HeaderName, HeaderValue};
use rama_net::user::{Basic, Bearer, RawToken, UserId};

use crate::{Error, HeaderDecode, HeaderEncode, TypedHeader};

/// `Authorization` header, defined in [RFC7235](https://tools.ietf.org/html/rfc7235#section-4.2)
///
/// The `Authorization` header field allows a user agent to authenticate
/// itself with an origin server -- usually, but not necessarily, after
/// receiving a 401 (Unauthorized) response.  Its value consists of
/// credentials containing the authentication information of the user
/// agent for the realm of the resource being requested.
///
/// # ABNF
///
/// ```text
/// Authorization = credentials
/// ```
///
/// # Example values
/// * `Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==`
/// * `Bearer fpKL54jvWmEGVoRdCNjG`
///
/// # Examples
///
/// ```
/// use rama_http_headers::Authorization;
/// use rama_net::user::credentials::{basic, bearer};
///
/// let basic = Authorization::new(basic!("Aladdin", "open sesame"));
/// let bearer = Authorization::new(bearer!("some-opaque-token"));
/// ```
///
#[derive(Clone, PartialEq, Debug)]
pub struct Authorization<C>(pub C);

impl<C> Authorization<C> {
    /// Create a new authorization header.
    pub fn new(credentials: C) -> Self {
        Self(credentials)
    }

    pub fn credentials(&self) -> &C {
        &self.0
    }

    pub fn into_inner(self) -> C {
        self.0
    }
}

impl<C> AsRef<C> for Authorization<C> {
    fn as_ref(&self) -> &C {
        &self.0
    }
}

impl<C> Deref for Authorization<C> {
    type Target = C;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<C> DerefMut for Authorization<C> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<C: Credentials> TypedHeader for Authorization<C> {
    fn name() -> &'static HeaderName {
        &::rama_http_types::header::AUTHORIZATION
    }
}

impl<C: Credentials> HeaderDecode for Authorization<C> {
    fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, Error> {
        values
            .next()
            .and_then(|val| {
                // Scheme-less credential types (e.g. `RawToken`) declare an
                // empty `SCHEME` and treat the whole header value as the
                // token. Skip the `<scheme> SP …` prefix check entirely so
                // those types don't have to lie about their shape.
                if C::SCHEME.is_empty() {
                    return C::decode(val).map(Authorization);
                }
                let slice = val.as_bytes();
                if slice.len() > C::SCHEME.len()
                    && slice[C::SCHEME.len()] == b' '
                    && slice[..C::SCHEME.len()].eq_ignore_ascii_case(C::SCHEME.as_bytes())
                {
                    C::decode(val).map(Authorization)
                } else {
                    None
                }
            })
            .ok_or_else(Error::invalid)
    }
}

impl<C: Credentials> HeaderEncode for Authorization<C> {
    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
        values.extend(self.0.encode().map(|mut value| {
            value.set_sensitive(true);
            debug_assert!(
                // Scheme-less credentials (empty `SCHEME`) encode as a bare
                // token with no prefix; `starts_with` on an empty slice
                // is trivially true, so the assertion below covers them.
                value.as_bytes().starts_with(C::SCHEME.as_bytes()),
                "Credentials::encode should include its scheme: scheme = {:?}, encoded = {:?}",
                C::SCHEME,
                value,
            );
            value
        }));
    }
}

/// Credentials to be used in the `Authorization` header.
pub trait Credentials: Sized {
    /// The scheme identify the format of these credentials.
    ///
    /// This is the static string that always prefixes the actual credentials,
    /// like `"Basic"` in basic authorization.
    const SCHEME: &'static str;

    /// Try to decode the credentials from the `HeaderValue`.
    ///
    /// The `SCHEME` will be the first part of the `value`.
    fn decode(value: &HeaderValue) -> Option<Self>;

    /// Encode the credentials to a `HeaderValue`.
    ///
    /// The `SCHEME` must be the first part of the `value`.
    fn encode(&self) -> Option<HeaderValue>;
}

impl Credentials for Basic {
    const SCHEME: &'static str = "Basic";

    fn decode(value: &HeaderValue) -> Option<Self> {
        let value = value.as_ref();

        if value.len() <= Self::SCHEME.len() + 1 {
            tracing::trace!(
                "Basic credentials failed to decode: invalid scheme length in basic str"
            );
            return None;
        }
        if !value[..Self::SCHEME.len()].eq_ignore_ascii_case(Self::SCHEME.as_bytes()) {
            tracing::trace!("Basic credentials failed to decode: invalid scheme in basic str");
            return None;
        }

        let bytes = &value[Self::SCHEME.len() + 1..];
        let Some(non_space_pos) = bytes.iter().position(|b| *b != b' ') else {
            tracing::trace!(
                "Basic credentials failed to decode: missing space separator in basic str"
            );
            return None;
        };

        let bytes = &bytes[non_space_pos..];

        let bytes = ENGINE
            .decode(bytes)
            .inspect_err(|err| {
                tracing::trace!("Basic credentials failed to decode: base64 decode: {err:?}");
            })
            .ok()?;

        let decoded = String::from_utf8(bytes)
            .inspect_err(|err| {
                tracing::trace!("Basic credentials failed to decode: utf8 validation: {err:?}");
            })
            .ok()?;

        decoded
            .parse()
            .inspect_err(|err| {
                tracing::trace!("Basic credentials failed to decode: str parse: {err:?}");
            })
            .ok()
    }

    fn encode(&self) -> Option<HeaderValue> {
        let mut encoded = format!("{} ", Self::SCHEME);
        ENGINE.encode_string(self.to_string(), &mut encoded);
        HeaderValue::try_from(encoded)
            .inspect_err(|err| {
                tracing::debug!("failed to encode basic value as header value: {err}");
            })
            .ok()
    }
}

impl Credentials for Bearer {
    const SCHEME: &'static str = "Bearer";

    fn decode(value: &HeaderValue) -> Option<Self> {
        let value = value.as_ref();

        if value.len() <= Self::SCHEME.len() + 1 {
            tracing::trace!("Bearer credentials failed to decode: invalid bearer scheme length");
            return None;
        }
        if !value[..Self::SCHEME.len()].eq_ignore_ascii_case(Self::SCHEME.as_bytes()) {
            tracing::trace!("Bearer credentials failed to decode: invalid bearer scheme");
            return None;
        }

        let bytes = &value[Self::SCHEME.len() + 1..];

        let Some(non_space_pos) = bytes.iter().position(|b| *b != b' ') else {
            tracing::trace!("Bearer credentials failed to decode: no token found");
            return None;
        };

        let bytes = &bytes[non_space_pos..];

        let s = std::str::from_utf8(bytes)
            .inspect_err(|err| {
                tracing::trace!("Bearer credentials failed to decode: {err:?}");
            })
            .ok()?;

        Self::try_from(s.to_owned())
            .inspect_err(|err| {
                tracing::trace!("Bearer credentials failed to decode: {err:?}");
            })
            .ok()
    }

    fn encode(&self) -> Option<HeaderValue> {
        HeaderValue::try_from(format!("{} {}", Self::SCHEME, self.token()))
            .inspect_err(|err| {
                tracing::debug!("failed to encode bearer auth as header value: {err}");
            })
            .ok()
    }
}

impl Credentials for RawToken {
    /// Scheme-less: the entire `Authorization` header value is the token,
    /// with no leading `Bearer ` / `Basic ` prefix.
    const SCHEME: &'static str = "";

    fn decode(value: &HeaderValue) -> Option<Self> {
        let s = std::str::from_utf8(value.as_bytes())
            .inspect_err(|err| {
                tracing::trace!("RawToken credentials failed to decode: {err:?}");
            })
            .ok()?;
        Self::try_from(s.to_owned())
            .inspect_err(|err| {
                tracing::trace!("RawToken credentials failed to decode: {err}");
            })
            .ok()
    }

    fn encode(&self) -> Option<HeaderValue> {
        HeaderValue::try_from(self.token().to_owned())
            .inspect_err(|err| {
                tracing::debug!("failed to encode raw token as header value: {err}");
            })
            .ok()
    }
}

/// The `Authority` trait is used to determine if a set of [`Credentials`] are authorized.
pub trait Authority<C, L>: Send + Sync + 'static {
    /// Returns `true` if the credentials are authorized, otherwise `false`.
    fn authorized(&self, credentials: C) -> impl Future<Output = Option<Extensions>> + Send + '_;
}

/// A synchronous version of [`Authority`], to be used for primitive implementations.
pub trait AuthoritySync<C, L>: Send + Sync + 'static {
    /// Returns `true` if the credentials are authorized, otherwise `false`.
    fn authorized(&self, ext: &Extensions, credentials: &C) -> bool;
}

impl<A, C, L> Authority<C, L> for A
where
    A: AuthoritySync<C, L>,
    C: Credentials + Send + 'static,
    L: 'static,
{
    async fn authorized(&self, credentials: C) -> Option<Extensions> {
        let ext = Extensions::new();
        if self.authorized(&ext, &credentials) {
            Some(ext)
        } else {
            None
        }
    }
}

impl<T: UsernameLabelParser> AuthoritySync<Self, T> for Basic {
    fn authorized(&self, ext: &Extensions, credentials: &Self) -> bool {
        let username = credentials.username();
        let password = credentials.password();

        if password != self.password() {
            return false;
        }

        let parser_ext = Extensions::new();
        let username = match parse_username(&parser_ext, T::default(), username) {
            Ok(t) => t,
            Err(err) => {
                tracing::trace!("failed to parse username: {:?}", err);
                return if self == credentials {
                    ext.insert(UserId::Username(username.to_owned()));
                    true
                } else {
                    false
                };
            }
        };

        if username != self.username() {
            return false;
        }

        ext.extend(&parser_ext);
        ext.insert(UserId::Username(username));
        true
    }
}

impl<C, L, T, const N: usize> AuthoritySync<C, L> for [T; N]
where
    C: Credentials + Send + 'static,
    T: AuthoritySync<C, L>,
{
    fn authorized(&self, ext: &Extensions, credentials: &C) -> bool {
        self.iter().any(|t| t.authorized(ext, credentials))
    }
}

impl<C, L, T> AuthoritySync<C, L> for Vec<T>
where
    C: Credentials + Send + 'static,
    T: AuthoritySync<C, L>,
{
    fn authorized(&self, ext: &Extensions, credentials: &C) -> bool {
        self.iter().any(|t| t.authorized(ext, credentials))
    }
}

#[cfg(test)]
mod tests {
    use rama_http_types::header::HeaderMap;
    use rama_net::user::credentials::bearer;
    use rama_utils::str::non_empty_str;

    use super::super::{test_decode, test_encode};
    use super::{Authorization, Basic, Bearer};
    use crate::HeaderMapExt;

    #[test]
    fn basic_encode() {
        let auth = Authorization::new(Basic::new(
            non_empty_str!("Aladdin"),
            non_empty_str!("open sesame"),
        ));
        let headers = test_encode(auth);

        assert_eq!(
            headers["authorization"],
            "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
        );
    }

    #[test]
    fn basic_username_encode() {
        let auth = Authorization::new(Basic::new_insecure(non_empty_str!("Aladdin")));
        let headers = test_encode(auth);

        assert_eq!(headers["authorization"], "Basic QWxhZGRpbjo=",);
    }

    #[test]
    fn basic_roundtrip() {
        let auth = Authorization::new(Basic::new(
            non_empty_str!("Aladdin"),
            non_empty_str!("open sesame"),
        ));
        let mut h = HeaderMap::new();
        h.typed_insert(&auth);
        assert_eq!(h.typed_get(), Some(auth));
    }

    #[test]
    fn basic_decode() {
        let auth: Authorization<Basic> =
            test_decode(&["Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="]).unwrap();
        assert_eq!(auth.0.username(), "Aladdin");
        assert_eq!(auth.0.password(), Some("open sesame"));
    }

    #[test]
    fn basic_decode_case_insensitive() {
        let auth: Authorization<Basic> =
            test_decode(&["basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="]).unwrap();
        assert_eq!(auth.0.username(), "Aladdin");
        assert_eq!(auth.0.password(), Some("open sesame"));
    }

    #[test]
    fn basic_decode_extra_whitespaces() {
        let auth: Authorization<Basic> =
            test_decode(&["Basic  QWxhZGRpbjpvcGVuIHNlc2FtZQ=="]).unwrap();
        assert_eq!(auth.0.username(), "Aladdin");
        assert_eq!(auth.0.password(), Some("open sesame"));
    }

    #[test]
    fn basic_decode_no_password() {
        let auth: Authorization<Basic> = test_decode(&["Basic QWxhZGRpbjo="]).unwrap();
        assert_eq!(auth.0.username(), "Aladdin");
        assert_eq!(auth.0.password(), None);
    }

    #[test]
    fn bearer_encode() {
        let auth = Authorization::new(bearer!("fpKL54jvWmEGVoRdCNjG"));

        let headers = test_encode(auth);

        assert_eq!(headers["authorization"], "Bearer fpKL54jvWmEGVoRdCNjG",);
    }

    #[test]
    fn bearer_decode() {
        let auth: Authorization<Bearer> = test_decode(&["Bearer fpKL54jvWmEGVoRdCNjG"]).unwrap();
        assert_eq!(auth.0.token().as_bytes(), b"fpKL54jvWmEGVoRdCNjG");
    }

    #[test]
    fn bearer_decode_case_insensitive() {
        let auth: Authorization<Bearer> = test_decode(&["bearer fpKL54jvWmEGVoRdCNjG"]).unwrap();
        assert_eq!(auth.0.token().as_bytes(), b"fpKL54jvWmEGVoRdCNjG");
    }

    #[test]
    fn bearer_decode_extra_whitespaces() {
        let auth: Authorization<Bearer> = test_decode(&["Bearer   fpKL54jvWmEGVoRdCNjG"]).unwrap();
        assert_eq!(auth.0.token().as_bytes(), b"fpKL54jvWmEGVoRdCNjG");
    }

    /// Regression: `RawToken` is a scheme-less credential — the header
    /// value is the token, no `Bearer ` / `Basic ` prefix. This pins both
    /// the encoded form (bare token) and the empty-scheme escape hatch in
    /// `Authorization::decode`.
    #[test]
    fn regression_authorization_raw_token_roundtrip() {
        use rama_net::user::RawToken;

        let token = RawToken::try_from("fpKL54jvWmEGVoRdCNjG").unwrap();
        let auth = Authorization::new(token.clone());

        // Encode: header value is the bare token, no scheme prefix.
        let headers = test_encode(auth);
        assert_eq!(headers["authorization"], "fpKL54jvWmEGVoRdCNjG");

        // Decode: the same bare value round-trips back.
        let decoded: Authorization<RawToken> = test_decode(&["fpKL54jvWmEGVoRdCNjG"]).unwrap();
        assert_eq!(decoded.0, token);
    }

    /// Regression: a `RawToken` header may contain characters that
    /// `Bearer` rejects (`,`, `:`, `=`, SP) because real-world API keys
    /// do.
    #[test]
    fn regression_authorization_raw_token_accepts_loose_alphabet() {
        use rama_net::user::RawToken;

        let decoded: Authorization<RawToken> =
            test_decode(&["sk-live_abc=xyz,scope:read"]).unwrap();
        assert_eq!(decoded.0.token(), "sk-live_abc=xyz,scope:read");
    }
}

//bench_header!(raw, Authorization<String>, { vec![b"foo bar baz".to_vec()] });
//bench_header!(basic, Authorization<Basic>, { vec![b"Basic QWxhZGRpbjpuIHNlc2FtZQ==".to_vec()] });
//bench_header!(bearer, Authorization<Bearer>, { vec![b"Bearer fpKL54jvWmEGVoRdCNjG".to_vec()] });

#[cfg(test)]
mod test_auth {
    use super::*;
    use rama_core::username::{UsernameLabels, UsernameOpaqueLabelParser};
    use rama_net::user::credentials::basic;

    #[tokio::test]
    async fn basic_authorization() {
        let auth = basic!("Aladdin", "open sesame");
        let auths = vec![basic!("foo", "bar"), auth.clone()];
        let ext = Authority::<_, ()>::authorized(&auths, auth).await.unwrap();
        let user: &UserId = ext.get_ref().unwrap();
        assert_eq!(user, "Aladdin");
    }

    #[tokio::test]
    async fn basic_authorization_with_labels_found() {
        let auths = vec![basic!("foo", "bar"), basic!("john", "secret")];

        let ext = Authority::<_, UsernameOpaqueLabelParser>::authorized(
            &auths,
            basic!("john-green-red", "secret"),
        )
        .await
        .unwrap();

        let c: &UserId = ext.get_ref().unwrap();
        assert_eq!(c, "john");

        let labels: &UsernameLabels = ext.get_ref().unwrap();
        assert_eq!(&labels.0, &vec!["green".to_owned(), "red".to_owned()]);
    }

    #[tokio::test]
    async fn basic_authorization_with_labels_not_found() {
        let auth = basic!("john", "secret");
        let auths = vec![basic!("foo", "bar"), auth.clone()];

        let ext = Authority::<_, UsernameOpaqueLabelParser>::authorized(&auths, auth)
            .await
            .unwrap();

        let c: &UserId = ext.get_ref().unwrap();
        assert_eq!(c, "john");

        assert!(ext.get_ref::<UsernameLabels>().is_none());
    }
}