#![cfg(all(
feature = "api",
feature = "apikeys",
feature = "oauth-server",
feature = "csrf",
feature = "sqlite",
feature = "inertia",
feature = "auth",
feature = "openapi"
))]
use axum::{
Json,
body::Body,
extract::FromRef,
http::{Request, StatusCode, header},
response::Response,
};
use ryuk::{
api::{ApiAuth, ApiError},
apikey::ApiKeys,
app::App,
auth::Auth,
inertia::InertiaConfig,
oauth_server::OAuthServer,
};
use serde_json::{Value, json};
use std::time::Duration;
use tower::ServiceExt;
use utoipa_axum::{router::OpenApiRouter, routes};
#[derive(Clone)]
struct St {
oauth: OAuthServer,
inertia: InertiaConfig,
}
impl FromRef<St> for OAuthServer {
fn from_ref(s: &St) -> Self {
s.oauth.clone()
}
}
impl FromRef<St> for InertiaConfig {
fn from_ref(s: &St) -> Self {
s.inertia.clone()
}
}
#[utoipa::path(get, path = "/me", responses((status = 200, body = Value)))]
async fn me(ApiAuth(p): ApiAuth) -> Json<Value> {
Json(json!({ "id": p.id, "kind": format!("{:?}", p.kind), "scopes": p.scopes }))
}
#[utoipa::path(post, path = "/things", responses((status = 200, body = Value)))]
async fn make_thing(ApiAuth(p): ApiAuth) -> Result<Json<Value>, ApiError> {
p.require("things:write")?;
Ok(Json(json!({ "created": true })))
}
#[utoipa::path(get, path = "/dashboard", responses((status = 200, body = String)))]
async fn dashboard(Auth(uid): Auth) -> String {
format!("user {uid}")
}
#[utoipa::path(post, path = "/web/echo", responses((status = 200, body = String)))]
async fn web_echo() -> &'static str {
"echo"
}
#[utoipa::path(get, path = "/api-user", responses((status = 200, body = String)))]
async fn session_on_api(Auth(uid): Auth) -> String {
format!("user {uid}")
}
struct Env {
router: axum::Router,
key: String,
narrow_key: String,
client_id: String,
client_secret: String,
}
async fn env() -> Env {
let mut o = sea_orm::ConnectOptions::new("sqlite::memory:");
o.max_connections(1);
let db = sea_orm::Database::connect(o).await.unwrap();
let (keys, oauth) = (ApiKeys::new(db.clone()), OAuthServer::new(db));
keys.ensure_tables().await.unwrap();
oauth.ensure_tables().await.unwrap();
let key = keys
.issue(Some(1), "full", &["things:write"], None)
.await
.unwrap();
let narrow = keys
.issue(Some(1), "read only", &["things:read"], None)
.await
.unwrap();
let client = oauth
.create_client("worker", &[], &["things:write"], true)
.await
.unwrap();
let state = St {
oauth: oauth.clone(),
inertia: ryuk::inertia::Config::dev(5173, "src/main.js", false, "t"),
};
let router = App::new(state)
.title("Test")
.web(
OpenApiRouter::new()
.routes(routes!(dashboard))
.routes(routes!(web_echo)),
)
.web(OAuthServer::web_routes())
.api(
OpenApiRouter::new()
.routes(routes!(me))
.routes(routes!(make_thing))
.routes(routes!(session_on_api)),
)
.public(OAuthServer::token_routes())
.api_verifier(keys)
.api_verifier(oauth)
.api_rate_limit(1000, Duration::from_secs(60))
.into_router();
Env {
router,
key: key.plaintext,
narrow_key: narrow.plaintext,
client_id: client.client_id,
client_secret: client.client_secret.unwrap(),
}
}
async fn send(r: &axum::Router, req: Request<Body>) -> Response {
r.clone().oneshot(req).await.unwrap()
}
fn get(uri: &str, bearer: Option<&str>) -> Request<Body> {
let mut b = Request::get(uri).header(header::ACCEPT, "application/json");
if let Some(t) = bearer {
b = b.header(header::AUTHORIZATION, format!("Bearer {t}"));
}
b.body(Body::empty()).unwrap()
}
fn post(uri: &str, bearer: Option<&str>, form: &str) -> Request<Body> {
let mut b = Request::post(uri)
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(header::ACCEPT, "application/json");
if let Some(t) = bearer {
b = b.header(header::AUTHORIZATION, format!("Bearer {t}"));
}
b.body(Body::from(form.to_string())).unwrap()
}
async fn body(res: Response) -> (StatusCode, axum::http::HeaderMap, Value) {
let (parts, b) = res.into_parts();
let bytes = axum::body::to_bytes(b, 1 << 20).await.unwrap();
let v = serde_json::from_slice(&bytes)
.unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into_owned()));
(parts.status, parts.headers, v)
}
#[tokio::test]
async fn api_key_authenticates_and_scopes_are_enforced() {
let e = env().await;
let (s, h, v) = body(send(&e.router, get("/api/me", Some(&e.key))).await).await;
assert_eq!(s, StatusCode::OK);
assert_eq!(v["kind"], "ApiKey");
assert!(
h.get(header::SET_COOKIE).is_none(),
"api routes never set cookies"
);
let (s, h, v) = body(send(&e.router, get("/api/me", None)).await).await;
assert_eq!(s, StatusCode::UNAUTHORIZED);
assert_eq!(v["error"]["code"], "unauthorized");
assert!(h.contains_key(header::WWW_AUTHENTICATE));
let (s, ..) = body(send(&e.router, get("/api/me", Some("ryk_nope_nothing"))).await).await;
assert_eq!(s, StatusCode::UNAUTHORIZED);
let (s, ..) = body(send(&e.router, post("/api/things", Some(&e.key), "")).await).await;
assert_eq!(s, StatusCode::OK);
let (s, _, v) = body(send(&e.router, post("/api/things", Some(&e.narrow_key), "")).await).await;
assert_eq!(s, StatusCode::FORBIDDEN);
assert_eq!(v["error"]["code"], "insufficient_scope");
}
#[tokio::test]
async fn groups_are_isolated_in_both_directions() {
let e = env().await;
let browser = Request::get("/dashboard")
.header(header::AUTHORIZATION, format!("Bearer {}", e.key))
.body(Body::empty())
.unwrap();
let res = send(&e.router, browser).await;
assert_eq!(res.status(), StatusCode::SEE_OTHER, "key is not a session");
let (s, ..) = body(send(&e.router, get("/dashboard", Some(&e.key))).await).await;
assert_eq!(s, StatusCode::UNAUTHORIZED);
let (s, ..) = body(send(&e.router, post("/web/echo", None, "")).await).await;
assert_eq!(s.as_u16(), 419, "web POST without a CSRF token");
let (s, _, v) = body(send(&e.router, get("/api/api-user", Some(&e.key))).await).await;
assert_eq!(s, StatusCode::UNAUTHORIZED);
assert!(v["error"]["message"].as_str().unwrap().contains("session"));
let (s, _, v) = body(send(&e.router, get("/api/nope", Some(&e.key))).await).await;
assert_eq!(s, StatusCode::NOT_FOUND);
assert_eq!(v["error"]["code"], "not_found");
}
#[tokio::test]
async fn oauth_client_credentials_token_works_on_api_routes() {
let e = env().await;
let form = format!(
"grant_type=client_credentials&scope=things%3Awrite&client_id={}&client_secret={}",
e.client_id, e.client_secret
);
let (s, h, v) = body(send(&e.router, post("/oauth/token", None, &form)).await).await;
assert_eq!(s, StatusCode::OK, "{v}");
assert_eq!(h.get(header::CACHE_CONTROL).unwrap(), "no-store");
assert!(h.get(header::SET_COOKIE).is_none());
let token = v["access_token"].as_str().unwrap().to_string();
assert!(token.starts_with("ryo_"));
let (s, _, v) = body(send(&e.router, get("/api/me", Some(&token))).await).await;
assert_eq!(s, StatusCode::OK);
assert_eq!(v["kind"], "OAuthClient");
let (s, ..) = body(send(&e.router, post("/api/things", Some(&token), "")).await).await;
assert_eq!(s, StatusCode::OK, "token carries things:write");
let bad = format!(
"grant_type=client_credentials&client_id={}&client_secret=wrong",
e.client_id
);
let (s, _, v) = body(send(&e.router, post("/oauth/token", None, &bad)).await).await;
assert_eq!(s, StatusCode::UNAUTHORIZED);
assert_eq!(v["error"], "invalid_client");
}
#[tokio::test]
async fn api_docs_describe_only_the_api_with_security_schemes() {
let e = env().await;
let (s, _, spec) = body(send(&e.router, get("/api/openapi.json", None)).await).await;
assert_eq!(s, StatusCode::OK);
assert!(spec["paths"]["/api/me"].is_object());
assert!(
spec["paths"]["/dashboard"].is_null(),
"web routes are not API docs"
);
assert_eq!(
spec["components"]["securitySchemes"]["api_key"]["scheme"],
"bearer"
);
let (s, ..) = body(send(&e.router, get("/api/docs", None)).await).await;
assert_eq!(s, StatusCode::OK);
}