~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

Browsers: CORS on every path but OAuth's, as the reference answers

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:xrpc-cors
crates/pds-server/src/cors.rsnew+60−0
@@ -0,0 +1,60 @@
//! 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<Body> {
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<Body> {
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
}
crates/pds-server/src/lib.rs+4−1
@@ -34,6 +34,7 @@ mod blobs;
mod cache;
mod checkpoint;
mod compact;
mod cors;
mod email;
mod events;
mod federation;
@@ -710,7 +711,8 @@ pub fn run() {
})
}
/// The server's routes. Every path under `/xrpc/` is a method, served or forwarded.
/// The server's routes. Every path under `/xrpc/` is a method, served or
/// forwarded. Each answers browsers as `cors` says.
fn router(svc: Shared) -> Router {
Router::new()
.route(
@@ -725,6 +727,7 @@ fn router(svc: Shared) -> Router {
.route("/.well-known/atproto-did", get(identity::well_known))
.merge(oauth::routes())
.with_state(svc)
.layer(axum::middleware::from_fn(cors::layer))
}
/// A request's `Authorization` header, as text; one that is not is empty, which no scheme is.
harness/checks/cors.mjsnew+72−0
@@ -0,0 +1,72 @@
// Browsers (spec/PDS.md): CORS on every path but OAuth's, held to the
// reference.
import { isDeepStrictEqual } from 'node:util'
import { chance, pick } from '../lib/random.mjs'
import { cand, ref } from '../lib/processes.mjs'
import { count, differ } from '../lib/report.mjs'
/// A DID no server here holds.
const NOBODY = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa'
/// The requests an app in a browser makes, answered 200, 4xx and 404.
const CALLS = (acct) => [
['GET', '/xrpc/com.atproto.server.describeServer'],
['GET', `/xrpc/com.atproto.repo.describeRepo?repo=${encodeURIComponent(acct.did)}`],
['GET', `/xrpc/com.atproto.repo.getRecord?repo=${NOBODY}&collection=com.example.note&rkey=x`],
['GET', '/xrpc/com.example.cors.nothing'],
['POST', '/xrpc/com.atproto.server.createSession', '{}'],
['GET', '/xrpc/_health'],
['GET', '/cors/no/such/path'],
]
/// The paths a preflight is sent to: methods served, one not served,
/// `_health`, a path that is no NSID, and one outside `/xrpc/`.
const PREFLIGHTS = [
'/xrpc/com.atproto.server.createSession',
'/xrpc/com.atproto.repo.getRecord',
'/xrpc/com.atproto.sync.subscribeRepos',
'/xrpc/com.example.cors.nothing',
'/xrpc/_health',
'/xrpc/not%20an%20nsid',
'/cors/no/such/path',
]
/// What a request's answer shows of CORS: its status, every
/// `Access-Control-*` header, and for a preflight whether `Vary` names
/// `Access-Control-Request-Headers` and the body is empty.
async function ask(side, method, path, headers, body) {
const r = await fetch(`${side.url}${path}`, { method, headers, body })
const text = await r.text()
const cors = {}
r.headers.forEach((v, k) => {
if (k.startsWith('access-control-')) cors[k] = v
})
const out = { status: r.status, cors }
if (method === 'OPTIONS') {
out.varies = (r.headers.get('vary') ?? '').split(',').some((v) => v.trim().toLowerCase() === 'access-control-request-headers')
out.empty = text.length === 0
}
return out
}
/// One request an app in a browser would make, or its preflight, on both
/// sides.
export async function cors(acct) {
const headers = chance(0.8) ? { origin: pick(['https://bsky.app', 'https://app.example.com', 'http://localhost:5173']) } : {}
let method, path, body, kind
if (chance(0.5)) {
;[method, path, body] = pick(CALLS(acct))
if (body) headers['content-type'] = 'application/json'
kind = `cors: ${method}`
} else {
method = 'OPTIONS'
path = pick(PREFLIGHTS)
if (chance(0.8)) headers['access-control-request-method'] = pick(['GET', 'POST'])
if (chance(0.7)) headers['access-control-request-headers'] = pick(['content-type', 'authorization,dpop', 'content-type,atproto-accept-labelers,atproto-proxy', 'Content-Type'])
kind = 'cors: preflight'
}
const [a, b] = await Promise.all([ref, cand].map((side) => ask(side, method, path, headers, body)))
if (!isDeepStrictEqual(a, b)) await differ('CORS', { method, path, headers }, a, b)
count(kind, b.status < 400)
}
harness/compare.mjs+2−1
@@ -86,6 +86,7 @@ import { checkCrawls, getBlocks, getGoneBlocks, getRepoStatus, listRepos, noCraw
import { startFirehose } from './checks/firehose.mjs'
import { handleRace, recommendedCredentials, resolveHandle, updateHandle, updateHandleNoToken, updateHandleRefused, wellKnownHandle } from './checks/identity.mjs'
import { oddRequests } from './checks/odd.mjs'
import { cors } from './checks/cors.mjs'
import { checkOAuthMetadata, oauthAuthorizeRefused, oauthClientLibrary, oauthDepartures, oauthDeviceCookies, oauthDpopRefused, oauthGetSession, oauthLogin, oauthParRefused, oauthRefresh, oauthRevoke, oauthRevokeRefused, oauthTokenRefused } from './checks/oauth.mjs'
import { oauthScopedCall, oauthScopedEdges, oauthScopedRefused } from './checks/oauth-scopes.mjs'
import { oauthSetCall, oauthSetLogin, oauthSetPar } from './checks/permission-sets.mjs'
@@ -171,7 +172,7 @@ await checkOAuthMetadata()
const STEPS_BY_WEIGHT = [
[createRecord, 14], [putRecord, 14], [deleteRecord, 8], [applyWrites, 8],
[getRecord, 10], [listRecords, 6], [describeRepo, 2], [getSession, 1],
[createWithTid, 2], [concurrent, 6], [oddRequests, 3], [describeServer, 1],
[createWithTid, 2], [concurrent, 6], [oddRequests, 3], [cors, 3], [describeServer, 1],
[() => createAccount(), 1], [createAccountRefused, 4], [accountRace, 1], [createSession, 3],
[crossWrites, 3], [listRepos, 2], [getRepoStatus, 2], [getBlocks, 3], [getGoneBlocks, 2], [syncGetRecord, 3],
[refreshSession, 3], [deleteSession, 2], [wrongTokens, 2], [appPasswords, 4], [sessionRace, 1],
spec/PDS.md+28−0
@@ -127,6 +127,34 @@ are as `atproto/did.md` and `atproto/handle.md` define them. A session's
A bearer token the server did not give out, sent to a repository write or
to `getSession`, is `400 InvalidToken`, as the reference answers one.
## Browsers
An app in a browser, as bsky.app, calls the server from its own origin, so
every path but OAuth's (`/.well-known/oauth-*`, `/oauth/*` and
`/@atproto/oauth-provider/*`, whose cross-origin answers `OAUTH.md` and
`OAUTH-MCP.md` give) answers as the reference does (CORS, the Fetch
standard):
- Every answer, of any status, carries `Access-Control-Allow-Origin: *`,
whatever `Origin` the request has, or none.
- A request of method `OPTIONS` is a preflight, whatever its path, served
or not, and whatever its headers: `204` with no body, and
`Access-Control-Allow-Origin: *`, `Access-Control-Allow-Methods:
GET,HEAD,PUT,PATCH,POST,DELETE`, `Access-Control-Allow-Headers` the
request's `Access-Control-Request-Headers` as sent (none when it sent
none), `Access-Control-Max-Age: 86400` and `Vary:
Access-Control-Request-Headers`. It reaches no method: it costs no rate
limit, carries no `RateLimit-*` headers, and is not forwarded.
`harness/checks/cors.mjs` holds the server to the reference: `GET`s and
`POST`s answered `200`, `4xx` and `404`, with an `Origin` and without; and
preflights on methods served, a method not served, `_health`, a path that
is no NSID and a path outside `/xrpc/`, with and without
`Access-Control-Request-Method` and `Access-Control-Request-Headers`. It
compares the status and every `Access-Control-*` header, and that a
preflight's `Vary` names `Access-Control-Request-Headers` and its body is
empty.
## What the reference does that the specs leave open
The lexicons and prose specs do not say these, and the reference PDS does