utoipa_swagger_ui/
axum.rs

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
#![cfg(feature = "axum")]

use std::sync::Arc;

use axum::{
    body::Body,
    extract::Path,
    http::{HeaderMap, Request, Response, StatusCode},
    middleware::{self, Next},
    response::IntoResponse,
    routing, Extension, Json, Router,
};
use base64::{prelude::BASE64_STANDARD, Engine};

use crate::{ApiDoc, BasicAuth, Config, SwaggerUi, Url};

impl<S> From<SwaggerUi> for Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    fn from(swagger_ui: SwaggerUi) -> Self {
        let urls_capacity = swagger_ui.urls.len();
        let external_urls_capacity = swagger_ui.external_urls.len();

        let (router, urls) = swagger_ui.urls.into_iter().fold(
            (
                Router::<S>::new(),
                Vec::<Url>::with_capacity(urls_capacity + external_urls_capacity),
            ),
            |router_and_urls, (url, openapi)| {
                add_api_doc_to_urls(router_and_urls, (url, ApiDoc::Utoipa(openapi)))
            },
        );
        let (router, urls) = swagger_ui.external_urls.into_iter().fold(
            (router, urls),
            |router_and_urls, (url, openapi)| {
                add_api_doc_to_urls(router_and_urls, (url, ApiDoc::Value(openapi)))
            },
        );

        let config = if let Some(config) = swagger_ui.config {
            if config.url.is_some() || !config.urls.is_empty() {
                config
            } else {
                config.configure_defaults(urls)
            }
        } else {
            Config::new(urls)
        };

        let handler = routing::get(serve_swagger_ui).layer(Extension(Arc::new(config.clone())));
        let path: &str = swagger_ui.path.as_ref();

        let mut router = if path == "/" {
            router
                .route(path, handler.clone())
                .route(&format!("{}{{*rest}}", path), handler)
        } else {
            let path = if path.ends_with('/') {
                &path[..path.len() - 1]
            } else {
                path
            };
            debug_assert!(!path.is_empty());

            let slash_path = format!("{}/", path);
            router
                .route(
                    path,
                    routing::get(|| async move { axum::response::Redirect::to(&slash_path) }),
                )
                .route(&format!("{}/", path), handler.clone())
                .route(&format!("{}/{{*rest}}", path), handler)
        };

        if let Some(BasicAuth { username, password }) = config.basic_auth {
            let username = Arc::new(username);
            let password = Arc::new(password);
            let basic_auth_middleware =
                move |headers: HeaderMap, req: Request<Body>, next: Next| {
                    let username = username.clone();
                    let password = password.clone();
                    async move {
                        if let Some(header) = headers.get("Authorization") {
                            if let Ok(header_str) = header.to_str() {
                                let base64_encoded_credentials =
                                    BASE64_STANDARD.encode(format!("{}:{}", &username, &password));
                                if header_str == format!("Basic {}", base64_encoded_credentials) {
                                    return Ok::<Response<Body>, StatusCode>(next.run(req).await);
                                }
                            }
                        }
                        Ok::<Response<Body>, StatusCode>(
                            (
                                StatusCode::UNAUTHORIZED,
                                [("WWW-Authenticate", "Basic realm=\":\"")],
                            )
                                .into_response(),
                        )
                    }
                };
            router = router.layer(middleware::from_fn(basic_auth_middleware));
        }

        router
    }
}

fn add_api_doc_to_urls<S>(
    router_and_urls: (Router<S>, Vec<Url<'static>>),
    url: (Url<'static>, ApiDoc),
) -> (Router<S>, Vec<Url<'static>>)
where
    S: Clone + Send + Sync + 'static,
{
    let (router, mut urls) = router_and_urls;
    let (url, openapi) = url;
    (
        router.route(
            url.url.as_ref(),
            routing::get(move || async { Json(openapi) }),
        ),
        {
            urls.push(url);
            urls
        },
    )
}

async fn serve_swagger_ui(
    path: Option<Path<String>>,
    Extension(state): Extension<Arc<Config<'static>>>,
) -> impl IntoResponse {
    let tail = match path.as_ref() {
        Some(tail) => tail,
        None => "",
    };

    match super::serve(tail, state) {
        Ok(file) => file
            .map(|file| {
                (
                    StatusCode::OK,
                    [("Content-Type", file.content_type)],
                    file.bytes,
                )
                    .into_response()
            })
            .unwrap_or_else(|| StatusCode::NOT_FOUND.into_response()),
        Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::header::AUTHORIZATION;
    use http::HeaderValue;
    use tower::util::ServiceExt;

    #[tokio::test]
    async fn mount_onto_root() {
        let app = Router::<()>::from(SwaggerUi::new("/"));
        let response = app.clone().oneshot(get("/")).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let response = app.clone().oneshot(get("/swagger-ui.css")).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn mount_onto_path_ends_with_slash() {
        let app = Router::<()>::from(SwaggerUi::new("/swagger-ui/"));
        let response = app.clone().oneshot(get("/swagger-ui")).await.unwrap();
        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        let response = app.clone().oneshot(get("/swagger-ui/")).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let request = get("/swagger-ui/swagger-ui.css");
        let response = app.clone().oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn mount_onto_path_not_end_with_slash() {
        let app = Router::<()>::from(SwaggerUi::new("/swagger-ui"));
        let response = app.clone().oneshot(get("/swagger-ui")).await.unwrap();
        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        let response = app.clone().oneshot(get("/swagger-ui/")).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let request = get("/swagger-ui/swagger-ui.css");
        let response = app.clone().oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn basic_auth() {
        let swagger_ui =
            SwaggerUi::new("/swagger-ui").config(Config::default().basic_auth(BasicAuth {
                username: "admin".to_string(),
                password: "password".to_string(),
            }));
        let app = Router::<()>::from(swagger_ui);
        let response = app.clone().oneshot(get("/swagger-ui")).await.unwrap();
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        let encoded_credentials = BASE64_STANDARD.encode("admin:password");
        let authorization = format!("Basic {}", encoded_credentials);
        let request = authorized_get("/swagger-ui", &authorization);
        let response = app.clone().oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        let request = authorized_get("/swagger-ui/", &authorization);
        let response = app.clone().oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let request = authorized_get("/swagger-ui/swagger-ui.css", &authorization);
        let response = app.clone().oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    fn get(url: &str) -> Request<Body> {
        Request::builder().uri(url).body(Body::empty()).unwrap()
    }

    fn authorized_get(url: &str, authorization: &str) -> Request<Body> {
        Request::builder()
            .uri(url)
            .header(AUTHORIZATION, HeaderValue::from_str(authorization).unwrap())
            .body(Body::empty())
            .unwrap()
    }
}