//! What a browser needs to call the server from an app's own origin //! (`spec/PDS.md`, "Browsers"): CORS on every path but OAuth's, whose //! cross-origin answers are its own (`oauth.rs`). use axum::body::Body; use axum::extract::Request; use axum::http::{HeaderValue, Method, Response, StatusCode, header}; use axum::middleware::Next; /// Whether `path` is OAuth's, which answers cross-origin requests itself. fn oauth(path: &str) -> bool { path.starts_with("/.well-known/oauth-") || path.starts_with("/oauth/") || path.starts_with("/@atproto/oauth-provider/") } /// Answer an `OPTIONS` as a preflight, and let every other answer be read /// from any origin. pub(crate) async fn layer(req: Request, next: Next) -> Response { if oauth(req.uri().path()) { return next.run(req).await; } if req.method() == Method::OPTIONS { return preflight(&req); } let mut res = next.run(req).await; res.headers_mut().insert( header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"), ); res } /// `204`, allowing any origin, the methods an app calls, and the headers /// the browser asked for. fn preflight(req: &Request) -> Response { let mut res = Response::new(Body::empty()); *res.status_mut() = StatusCode::NO_CONTENT; let h = res.headers_mut(); h.insert( header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"), ); h.insert( header::ACCESS_CONTROL_ALLOW_METHODS, HeaderValue::from_static("GET,HEAD,PUT,PATCH,POST,DELETE"), ); if let Some(asked) = req.headers().get(header::ACCESS_CONTROL_REQUEST_HEADERS) { h.insert(header::ACCESS_CONTROL_ALLOW_HEADERS, asked.clone()); } h.insert( header::ACCESS_CONTROL_MAX_AGE, HeaderValue::from_static("86400"), ); h.insert( header::VARY, HeaderValue::from_static("Access-Control-Request-Headers"), ); res }