uxum 0.9.4

Opinionated backend service framework based on axum
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
//! AAA - extractors.

#[cfg(feature = "jwt")]
use std::collections::HashMap;
use std::{borrow::Cow, collections::BTreeMap, str::FromStr};

use axum::{
    body::Body,
    http::{
        header::{AUTHORIZATION, WWW_AUTHENTICATE},
        HeaderName, HeaderValue, Request, Response, StatusCode,
    },
    response::IntoResponse,
};
use base64::{engine::general_purpose::STANDARD as B64, Engine};
#[cfg(feature = "jwt")]
use deboog::Deboog;
use dyn_clone::{clone_box, DynClone};
#[cfg(feature = "jwt")]
use jsonwebtoken as jwt;
use okapi::{openapi3, Map};
#[cfg(feature = "jwt")]
use serde_json::Value;
use tracing::error;

use crate::{
    auth::{errors::AuthError, token::AuthToken, user::UserId},
    errors,
};

/// Authentication extractor (front-end) trait.
pub trait AuthExtractor: std::fmt::Debug + DynClone + Send + Sync + 'static {
    /// Extract user ID and authentication data from request.
    ///
    /// # Errors
    ///
    /// Returns `Err` if any preconditions for auth data extraction have not been met.
    fn extract_auth(&self, req: &Request<Body>) -> Result<(Option<UserId>, AuthToken), AuthError>;

    /// Format error response from [`AuthError`].
    ///
    /// Passed to auth provider (back-end) for authentication and authorization.
    #[must_use]
    fn error_response(&self, err: AuthError) -> Response<Body>;

    /// Get schema objects corresponding to authentication methods.
    #[must_use]
    fn security_schemes(&self) -> BTreeMap<String, openapi3::SecurityScheme> {
        BTreeMap::new()
    }

    /// Additional list of HTTP headers to hide in logs and traces.
    fn sensitive_headers(&self) -> Vec<HeaderName> {
        vec![]
    }
}

/// Authentication extractor (front-end) which does nothing.
#[derive(Clone, Debug, Default)]
pub struct NoOpAuthExtractor;

impl AuthExtractor for NoOpAuthExtractor {
    fn extract_auth(&self, _req: &Request<Body>) -> Result<(Option<UserId>, AuthToken), AuthError> {
        Ok((None, AuthToken::Absent))
    }

    fn error_response(&self, err: AuthError) -> Response<Body> {
        // This shuld never get executed for a NoOp extractor
        error!("tried to generate auth error response for NoOpAuthExtractor");
        problemdetails::new(StatusCode::INTERNAL_SERVER_ERROR)
            .with_type(errors::TAG_UXUM_AUTH)
            .with_title(err.to_string())
            .into_response()
    }
}

/// Authentication extractor (front-end) for HTTP Basic authentication.
#[derive(Clone, Debug)]
pub struct BasicAuthExtractor {
    /// Value to use for `WWW-Authenticate` header.
    ///
    /// Default value uses "auth" string as a realm.
    www_auth: Cow<'static, str>,
}

impl Default for BasicAuthExtractor {
    fn default() -> Self {
        Self {
            www_auth: Cow::Borrowed(r#"Basic realm="auth", charset="UTF-8""#),
        }
    }
}

impl AuthExtractor for BasicAuthExtractor {
    fn extract_auth(&self, req: &Request<Body>) -> Result<(Option<UserId>, AuthToken), AuthError> {
        match req.headers().get(AUTHORIZATION) {
            Some(header) => {
                Self::parse_header(header).map(|(user, pwd)| (Some(user.into()), pwd.into()))
            }
            None => Err(AuthError::NoAuthProvided),
        }
    }

    fn error_response(&self, err: AuthError) -> Response<Body> {
        let status = match err {
            AuthError::NoAuthProvided | AuthError::UserNotFound | AuthError::AuthFailed => {
                StatusCode::UNAUTHORIZED
            }
            AuthError::NoPermission(_) => StatusCode::FORBIDDEN,
            _ => StatusCode::BAD_REQUEST,
        };
        let mut resp = problemdetails::new(status)
            .with_type(errors::TAG_UXUM_AUTH)
            .with_title(err.to_string())
            .into_response();
        if status == StatusCode::UNAUTHORIZED {
            let header_value = match HeaderValue::from_str(&self.www_auth) {
                Ok(val) => val,
                Err(err) => {
                    return problemdetails::new(StatusCode::INTERNAL_SERVER_ERROR)
                        .with_type(errors::TAG_UXUM_AUTH)
                        .with_title("Invalid HTTP Basic realm value")
                        .with_detail(err.to_string())
                        .into_response()
                }
            };
            let _ = resp.headers_mut().insert(WWW_AUTHENTICATE, header_value);
        }
        resp
    }

    fn security_schemes(&self) -> BTreeMap<String, openapi3::SecurityScheme> {
        maplit::btreemap! {
            "basic".into() => openapi3::SecurityScheme {
                description: Some("HTTP Basic authentication".into()),
                data: openapi3::SecuritySchemeData::Http {
                    scheme: "basic".into(),
                    bearer_format: None,
                },
                extensions: Map::default(),
            },
        }
    }
}

impl BasicAuthExtractor {
    /// Name of authentication scheme.
    const SCHEME: &'static str = "Basic";

    /// Create new extractor, passing optional parameters.
    pub fn new(realm: Option<impl AsRef<str>>) -> Self {
        match realm {
            Some(realm) => Self {
                www_auth: Cow::Owned(Self::format_www_authenticate(realm)),
            },
            None => Default::default(),
        }
    }

    /// Format value of `WWW-Authenticate` header.
    fn format_www_authenticate(realm: impl AsRef<str>) -> String {
        // TODO: escape realm
        format!(
            r#"{} realm="{}", charset="UTF-8""#,
            Self::SCHEME,
            realm.as_ref()
        )
    }

    /// Parse `Authorization` header into plaintext username and password.
    fn parse_header(header: &HeaderValue) -> Result<(String, String), AuthError> {
        let Ok(header) = header.to_str() else {
            return Err(AuthError::InvalidAuthHeader);
        };
        match header.split_once(' ') {
            Some((scheme, payload)) if scheme.eq_ignore_ascii_case(Self::SCHEME) => {
                Self::parse_payload(payload)
            }
            Some((scheme, _)) => Err(AuthError::UnknownAuthScheme(scheme.to_string())),
            None => Err(AuthError::InvalidAuthHeader),
        }
    }

    /// Parse base64-encoded credentials into plaintext username and password.
    fn parse_payload(payload: &str) -> Result<(String, String), AuthError> {
        let raw = String::from_utf8(B64.decode(payload)?)?;
        raw.split_once(':')
            .map(|(user, pwd)| (user.to_string(), pwd.to_string()))
            .ok_or(AuthError::InvalidAuthPayload)
    }

    /// Set realm used for HTTP authentication challenge.
    pub fn set_realm(&mut self, realm: impl AsRef<str>) {
        self.www_auth = Cow::Owned(Self::format_www_authenticate(realm));
    }
}

/// Authentication extractor (front-end) that gets user and password from HTTP headers.
#[derive(Clone, Debug)]
pub struct HeaderAuthExtractor {
    /// Header name for user identifier.
    ///
    /// Default is "X-API-Name".
    user_header: Cow<'static, str>,
    /// Header name for user authentication info.
    ///
    /// Default is "X-API-Key".
    token_header: Cow<'static, str>,
}

impl Default for HeaderAuthExtractor {
    fn default() -> Self {
        Self {
            user_header: Cow::Borrowed("X-API-Name"),
            token_header: Cow::Borrowed("X-API-Key"),
        }
    }
}

impl AuthExtractor for HeaderAuthExtractor {
    fn extract_auth(&self, req: &Request<Body>) -> Result<(Option<UserId>, AuthToken), AuthError> {
        let headers = req.headers();
        let user = match headers.get(self.user_header.as_ref()) {
            Some(header) => match header.to_str() {
                Ok(user) => user.into(),
                Err(_) => return Err(AuthError::InvalidAuthPayload),
            },
            None => return Err(AuthError::NoAuthProvided),
        };
        let token = match headers.get(self.token_header.as_ref()) {
            Some(header) => match header.to_str() {
                Ok(user) => user.to_string(),
                Err(_) => return Err(AuthError::InvalidAuthPayload),
            },
            None => return Err(AuthError::NoAuthProvided),
        };
        Ok((Some(user), token.into()))
    }

    fn error_response(&self, err: AuthError) -> Response<Body> {
        let status = match err {
            AuthError::NoAuthProvided
            | AuthError::UserNotFound
            | AuthError::AuthFailed
            | AuthError::NoPermission(_) => StatusCode::FORBIDDEN,
            _ => StatusCode::BAD_REQUEST,
        };
        problemdetails::new(status)
            .with_type(errors::TAG_UXUM_AUTH)
            .with_title(err.to_string())
            .into_response()
    }

    fn security_schemes(&self) -> BTreeMap<String, openapi3::SecurityScheme> {
        maplit::btreemap! {
            "api-name".into() => openapi3::SecurityScheme {
                description: Some("API user name".into()),
                data: openapi3::SecuritySchemeData::ApiKey {
                    name: self.user_header.to_string(),
                    location: "header".into(),
                },
                extensions: Map::default(),
            },
            "api-key".into() => openapi3::SecurityScheme {
                description: Some("API key".into()),
                data: openapi3::SecuritySchemeData::ApiKey {
                    name: self.token_header.to_string(),
                    location: "header".into(),
                },
                extensions: Map::default(),
            },
        }
    }

    fn sensitive_headers(&self) -> Vec<HeaderName> {
        match HeaderName::from_str(self.token_header.as_ref()) {
            Ok(hdr) => vec![hdr],
            _ => vec![],
        }
    }
}

impl HeaderAuthExtractor {
    /// Create new extractor, passing optional parameters.
    pub fn new(
        user_header: Option<impl AsRef<str>>,
        token_header: Option<impl AsRef<str>>,
    ) -> Self {
        let mut extractor = Self::default();
        if let Some(header) = user_header {
            extractor.user_header = Cow::Owned(header.as_ref().to_string());
        }
        if let Some(header) = token_header {
            extractor.token_header = Cow::Owned(header.as_ref().to_string());
        }
        extractor
    }

    /// Set user ID header name.
    pub fn set_user_header(&mut self, name: impl AsRef<str>) {
        self.user_header = Cow::Owned(name.as_ref().into());
    }

    /// Set authenticating token header name.
    pub fn set_token_header(&mut self, name: impl AsRef<str>) {
        self.token_header = Cow::Owned(name.as_ref().into());
    }
}

/// Authentication extractor (front-end) for HTTP Bearer authentication using signed JWT.
#[cfg(feature = "jwt")]
#[derive(Clone, Deboog)]
pub struct JwtAuthExtractor {
    /// Decoding key.
    #[deboog(skip)]
    key: jwt::DecodingKey,
    /// JWT validation configuration.
    validation: jwt::Validation,
    /// Value to use for `WWW-Authenticate` header.
    ///
    /// Default value uses "auth" string as a realm.
    www_auth: Cow<'static, str>,
}

#[cfg(feature = "jwt")]
impl AuthExtractor for JwtAuthExtractor {
    fn extract_auth(&self, req: &Request<Body>) -> Result<(Option<UserId>, AuthToken), AuthError> {
        match req.headers().get(AUTHORIZATION) {
            Some(header) => {
                let claims = self.parse_header(header)?;
                // TODO: customize user ID location inside claims.
                // TODO: parse user ID from formatted field, stripping out prefixes/suffixes.
                let user = claims.get("sub").and_then(|v| match v {
                    Value::String(s) => Some(s.as_str().into()),
                    Value::Number(n) => Some(n.to_string().into()),
                    _ => None,
                });
                Ok((user, AuthToken::ExternallyVerified))
            }
            None => Err(AuthError::NoAuthProvided),
        }
    }

    fn error_response(&self, err: AuthError) -> Response<Body> {
        let status = match err {
            AuthError::NoAuthProvided | AuthError::UserNotFound | AuthError::AuthFailed => {
                StatusCode::UNAUTHORIZED
            }
            AuthError::NoPermission(_) => StatusCode::FORBIDDEN,
            _ => StatusCode::BAD_REQUEST,
        };
        let mut resp = problemdetails::new(status)
            .with_type(errors::TAG_UXUM_AUTH)
            .with_title(err.to_string())
            .into_response();
        if status == StatusCode::UNAUTHORIZED {
            let header_value = match HeaderValue::from_str(&self.www_auth) {
                Ok(val) => val,
                Err(err) => {
                    return problemdetails::new(StatusCode::INTERNAL_SERVER_ERROR)
                        .with_type(errors::TAG_UXUM_AUTH)
                        .with_title("Invalid HTTP Basic realm value")
                        .with_detail(err.to_string())
                        .into_response()
                }
            };
            let _ = resp.headers_mut().insert(WWW_AUTHENTICATE, header_value);
        }
        resp
    }

    fn security_schemes(&self) -> BTreeMap<String, openapi3::SecurityScheme> {
        maplit::btreemap! {
            "bearer".into() => openapi3::SecurityScheme {
                description: Some("HTTP Bearer authentication".into()),
                data: openapi3::SecuritySchemeData::Http {
                    scheme: "bearer".into(),
                    bearer_format: Some("JWT".into()),
                },
                extensions: Map::default(),
            },
        }
    }
}

#[cfg(feature = "jwt")]
impl JwtAuthExtractor {
    /// Name of authentication scheme.
    const SCHEME: &'static str = "Bearer";

    /// Create new extractor.
    pub fn new(
        realm: Option<impl AsRef<str>>,
        key: jwt::DecodingKey,
        validation: jwt::Validation,
    ) -> Self {
        let www_auth = match realm {
            Some(realm) => Cow::Owned(Self::format_www_authenticate(realm)),
            None => Cow::Borrowed(r#"Bearer realm="auth", charset="UTF-8""#),
        };
        Self {
            key,
            validation,
            www_auth,
        }
    }

    /// Format value of `WWW-Authenticate` header.
    fn format_www_authenticate(realm: impl AsRef<str>) -> String {
        // TODO: escape realm
        format!(
            r#"{} realm="{}", charset="UTF-8""#,
            Self::SCHEME,
            realm.as_ref()
        )
    }

    /// Parse `Authorization` header into token value.
    fn parse_header(&self, header: &HeaderValue) -> Result<HashMap<String, Value>, AuthError> {
        let Ok(header) = header.to_str() else {
            return Err(AuthError::InvalidAuthHeader);
        };
        match header.split_once(' ') {
            Some((scheme, payload)) if scheme.eq_ignore_ascii_case(Self::SCHEME) => {
                self.parse_payload(payload)
            }
            Some((scheme, _)) => Err(AuthError::UnknownAuthScheme(scheme.to_string())),
            None => Err(AuthError::InvalidAuthHeader),
        }
    }

    /// Parse base64-encoded credentials into plaintext username and password.
    fn parse_payload(&self, payload: &str) -> Result<HashMap<String, Value>, AuthError> {
        use jwt::errors::ErrorKind;
        // TODO: maybe use spawn_blocking? crypto can be resource-intensive.
        match jwt::decode(payload, &self.key, &self.validation) {
            Ok(token) => Ok(token.claims),
            // TODO: maybe add more AuthError variants?
            Err(err) => match err.kind() {
                ErrorKind::InvalidSignature => Err(AuthError::AuthFailed),
                ErrorKind::ExpiredSignature => Err(AuthError::AuthFailed),
                _ => Err(AuthError::InvalidAuthPayload),
            },
        }
    }

    /// Set realm used for HTTP authentication challenge.
    pub fn set_realm(&mut self, realm: impl AsRef<str>) {
        self.www_auth = Cow::Owned(Self::format_www_authenticate(realm));
    }

    /// Set JWT decoding key.
    ///
    /// See [`jsonwebtoken::DecodingKey`].
    pub fn set_key(&mut self, key: jwt::DecodingKey) {
        self.key = key;
    }

    /// Set JWT validation parameters.
    ///
    /// See [`jsonwebtoken::Validation`].
    pub fn set_validation(&mut self, valid: jwt::Validation) {
        self.validation = valid;
    }
}

/// Authentication extractor (front-end) which encapsulates several different extractors at once..
#[derive(Debug)]
pub struct StackedAuthExtractor {
    /// List of extractors to use.
    extractors: Vec<Box<dyn AuthExtractor>>,
}

impl Clone for StackedAuthExtractor {
    fn clone(&self) -> Self {
        let extractors = self
            .extractors
            .iter()
            .map(|ex| clone_box(ex.as_ref()))
            .collect();
        Self { extractors }
    }
}

impl AuthExtractor for StackedAuthExtractor {
    fn extract_auth(&self, req: &Request<Body>) -> Result<(Option<UserId>, AuthToken), AuthError> {
        let mut first_error = None;
        for ex in &self.extractors {
            match ex.extract_auth(req) {
                Ok(pair) => return Ok(pair),
                Err(err) => {
                    if first_error.is_none() {
                        first_error = Some(err);
                    }
                }
            }
        }
        // SAFETY: first_error is always `Some`, as we check that self.extractors is not empty.
        Err(first_error.unwrap())
    }

    fn error_response(&self, err: AuthError) -> Response<Body> {
        // TODO: make error responses smarter, i.e. multiple WWW-Authenticate headers.
        self.extractors[0].error_response(err)
    }

    fn security_schemes(&self) -> BTreeMap<String, openapi3::SecurityScheme> {
        let mut map = BTreeMap::new();
        for ex in &self.extractors {
            map.append(&mut ex.security_schemes());
        }
        map
    }

    fn sensitive_headers(&self) -> Vec<HeaderName> {
        let mut list = Vec::new();
        for ex in &self.extractors {
            list.append(&mut ex.sensitive_headers());
        }
        list
    }
}

impl StackedAuthExtractor {
    /// Create new extractor, passing a stack of effective extractors.
    pub fn new(mut extractors: Vec<Box<dyn AuthExtractor>>) -> Self {
        // Ensure that extractor list is not empty.
        if extractors.is_empty() {
            extractors.push(Box::new(NoOpAuthExtractor));
        }
        Self { extractors }
    }
}