use axum::{Json, Router, response::Html, routing::get};
use utoipa::openapi::OpenApi;
#[cfg(feature = "api")]
use utoipa::openapi::security::{
AuthorizationCode, Flow, Http, HttpAuthScheme, OAuth2, Scopes, SecurityScheme,
};
use utoipa_axum::router::OpenApiRouter;
use utoipa_scalar::Scalar;
pub fn mount<S: Clone + Send + Sync + 'static>(
router: OpenApiRouter<S>,
title: &str,
version: &str,
) -> Router<S> {
let (router, api) = router.split_for_parts();
router.merge(docs(api, title, version, true))
}
pub(crate) fn docs_enabled(explicit: Option<bool>, env: Option<&str>, production: bool) -> bool {
explicit
.or_else(|| env.and_then(|v| v.trim().parse::<bool>().ok()))
.unwrap_or(!production)
}
pub(crate) fn docs<S: Clone + Send + Sync + 'static>(
mut api: OpenApi,
title: &str,
version: &str,
enabled: bool,
) -> Router<S> {
if !enabled {
return Router::new();
}
api.info.title = title.into();
api.info.version = version.into();
(api.info.description, api.info.contact, api.info.license) = (None, None, None);
let html = Scalar::new(api.clone()).title(title.to_string()).to_html();
Router::new()
.route("/openapi.json", get(move || async move { Json(api) }))
.route("/docs", get(move || async move { Html(html) }))
}
#[cfg(feature = "api")]
pub(crate) fn add_security(api: &mut OpenApi, oauth2: Option<&OAuth2Cfg>) {
let c = api.components.get_or_insert_with(Default::default);
let mut bearer = Http::new(HttpAuthScheme::Bearer);
bearer.bearer_format = Some("API key".into());
c.add_security_scheme("api_key", SecurityScheme::Http(bearer));
if let Some(o) = oauth2 {
let scopes = Scopes::from_iter(o.scopes.iter().cloned());
c.add_security_scheme(
"oauth2",
SecurityScheme::OAuth2(OAuth2::new([Flow::AuthorizationCode(
AuthorizationCode::new(&o.authorize_url, &o.token_url, scopes),
)])),
);
}
}
#[cfg(feature = "api")]
pub(crate) struct OAuth2Cfg {
pub authorize_url: String,
pub token_url: String,
pub scopes: Vec<(String, String)>,
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{body::Body, http::Request};
use tower::ServiceExt;
use utoipa_axum::routes;
#[utoipa::path(get, path = "/ping", responses((status = 200, body = String)))]
async fn ping() -> &'static str {
"pong"
}
#[test]
fn docs_are_off_in_production_unless_asked_for() {
for (explicit, env, production, want) in [
(None, None, false, true),
(None, None, true, false),
(None, Some("true"), true, true),
(None, Some(" TRUE "), true, false), (None, Some("false"), false, false),
(None, Some("yes"), true, false),
(Some(true), Some("false"), true, true),
(Some(false), Some("true"), false, false),
] {
assert_eq!(
docs_enabled(explicit, env, production),
want,
"{explicit:?} {env:?} production={production}"
);
}
}
#[tokio::test]
async fn serves_spec_and_docs() {
let app: Router = mount(OpenApiRouter::new().routes(routes!(ping)), "T", "9.9.9");
let get = |u: &'static str| Request::get(u).body(Body::empty()).unwrap();
let res = app.clone().oneshot(get("/openapi.json")).await.unwrap();
let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["paths"]["/ping"].is_object());
assert_eq!(v["info"]["title"], "T");
assert_eq!(v["info"]["version"], "9.9.9");
let res = app.oneshot(get("/docs")).await.unwrap();
assert_eq!(res.status(), 200);
assert!(
res.headers()["content-type"]
.to_str()
.unwrap()
.contains("text/html")
);
}
}