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
use crate::{types, Error};
use http::HeaderValue;

pub struct Context {
    pub request_id: String,
    pub correlation_id: String,
    pub credentials_token: types::CredentialsToken,
}

#[derive(Clone, Copy)]
pub struct ExtendedContext<'a, 'b> {
    pub request_id: &'a str,
    pub correlation_id: &'a str,
    pub credentials_token: &'b types::CredentialsToken,
}

impl Context {
    pub fn extend<'a, 'b>(&'a self, token: &'b types::CredentialsToken) -> ExtendedContext<'a, 'b> {
        ExtendedContext {
            request_id: &self.request_id,
            correlation_id: &self.correlation_id,
            credentials_token: token,
        }
    }
}

#[cfg(feature = "warp")]
pub mod warp_extensions {
    use super::Context;
    use http::HeaderValue;
    use warp::{filters::header, reject::Rejection, Filter};

    pub fn context() -> impl Filter<Extract = (Context,), Error = Rejection> {
        header::optional("x-request-id")
            .and(header::optional("x-correlation-id"))
            .and(header::optional("authorization"))
            .and_then(
                |req_id: Option<HeaderValue>,
                 corr_id: Option<HeaderValue>,
                 auth: Option<HeaderValue>| async move {
                    super::extract_context(req_id.as_ref(), corr_id.as_ref(), auth.as_ref())
                        .map_err(warp::reject::custom)
                },
            )
    }
}

#[cfg(feature = "axum")]
pub mod axum_extensions {
    use super::Context;
    use axum::extract::{FromRequest, RequestParts};

    #[async_trait::async_trait]
    impl<B> FromRequest<B> for Context
    where
        B: Send, // required by `async_trait`
    {
        type Rejection = super::Error;

        async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
            let headers = req.headers();

            super::extract_context(
                headers.get("x-request-id"),
                headers.get("x-correlation-id"),
                headers.get("authorization"),
            )
        }
    }
}

#[cfg(any(feature = "axum", feature = "warp"))]
fn extract_context(
    request_id_header: Option<&HeaderValue>,
    correlation_id_header: Option<&HeaderValue>,
    authorization_header: Option<&HeaderValue>,
) -> Result<Context, Error> {
    let request_id = extract_str(request_id_header, "x-request-id")?.into();
    let correlation_id = extract_str(correlation_id_header, "x-correlation-id")?.into();
    let authorization = extract_str(authorization_header, "authorization")?;

    if !authorization.starts_with("Token ") {
        return Err(Error::unauthorized(
            "Malformed Authorization header. Must start with `Token `",
        ));
    }

    let credentials_token = base64::decode(authorization.trim_start_matches("Token "))
        .map_err(|_| Error::unauthorized("Authorization header contained invalid base64"))
        .and_then(|bs| {
            String::from_utf8(bs).map_err(|_| {
                Error::unauthorized("Decoded Authorzation token contained Invalid UTF-8")
            })
        })
        .and_then(|s| {
            types::CredentialsToken::try_from(s).map_err(|err| {
                Error::unauthorized(format!("Invalid CredentialsToken provided: {err}"))
            })
        })?;

    Ok(Context {
        request_id,
        correlation_id,
        credentials_token,
    })
}

#[cfg(any(feature = "axum", feature = "warp"))]
fn extract_str<'a>(header_value: Option<&'a HeaderValue>, header: &str) -> Result<&'a str, Error> {
    header_value
        .ok_or_else(|| Error::client_generic(format!("Missing header `{header}`")))
        .and_then(|s| {
            s.to_str().map_err(|err| {
                Error::client_generic(format!("Header `{header}` contains non-ASCII: {err}"))
            })
        })
}

#[cfg(all(test, any(feature = "axum", feature = "warp")))]
mod tests {

    #[cfg(feature = "axum")]
    #[test]
    fn test_extract_context() {
        use http::HeaderValue;

        let request_id = HeaderValue::from_static("123");
        let correlation_id = HeaderValue::from_static("456");
        let b64_auth = base64::encode("IMATOKEN");
        let authorization =
            HeaderValue::from_str(&format!("Token {b64_auth}")).expect("Authorization header");

        let ctx = super::extract_context(
            Some(&request_id),
            Some(&correlation_id),
            Some(&authorization),
        )
        .expect("Extracting context");

        assert_eq!(ctx.request_id, "123");
        assert_eq!(ctx.correlation_id, "456");
        assert_eq!(ctx.credentials_token, "IMATOKEN");
    }
}

#[cfg(test)]
pub fn test_ctx() -> Context {
    use once_cell::sync::OnceCell;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static COUNTER: OnceCell<AtomicUsize> = OnceCell::new();

    let c = COUNTER.get_or_init(|| AtomicUsize::new(1));

    let req_id = c.fetch_add(1, Ordering::Relaxed);
    let corr_id = c.fetch_add(1, Ordering::Relaxed);

    Context {
        request_id: format!("{req_id}"),
        correlation_id: format!("{corr_id}"),
        credentials_token: "TOKENBYTESTCTX".parse().unwrap(),
    }
}