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

pds-server: a body left unread is read after the answer, its connection kept

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:limits/refused-body-connection
.changeset/refused-body-connection-close.mdnew+9−0
@@ -0,0 +1,9 @@
---
default: patch
---
# A request answered before its body is read keeps its connection
When the server answers a request before reading its whole body, the connection now stays usable for the next request. Examples are an OAuth sign-in or PAR body past 100 KiB, a sign-in refused for its CSRF token, an upload past its limit, or a path not served. If at most 4 MiB of the body is left, the server reads and discards the rest after answering. If more is left, or the body is chunked, the answer says `Connection: close`.
Before, the server closed such connections without saying so. A client that keeps connections open could then send its next request on the closed connection and get "socket hang up" or a reset instead of an answer.
crates/pds-server/src/limits.rs+82−18
@@ -38,7 +38,9 @@ const HEADER_TIMEOUT: Duration = Duration::from_secs(10);
/// How long a request's body may send nothing.
const BODY_IDLE: Duration = Duration::from_secs(30);
/// How much of a body past its limit is read and thrown away before the
/// refusal is answered, so that a client still sending reads it.
/// refusal is answered, so that a client still sending reads it; and how
/// much of a body left unread is read and thrown away after its answer, so
/// that its connection is kept (`serve`).
const DRAIN: usize = 4 * 1024 * 1024;
/// The methods that keep something: each is refused below the free space
@@ -840,18 +842,28 @@ impl std::fmt::Display for BodyTimedOut {
impl std::error::Error for BodyTimedOut {}
/// A request's body, which fails once it has sent nothing for `BODY_IDLE`
/// while it is read, and says so.
struct Idle<B> {
inner: B,
/// while it is read, and says so; says, in `ended`, once it was read to its
/// end; and, dropped before that, leaves the rest of it in `left`, for
/// `serve` to read and throw away after the answer.
struct Idle {
inner: Option<hyper::body::Incoming>,
sleep: Option<Pin<Box<tokio::time::Sleep>>>,
timed_out: Arc<AtomicBool>,
ended: Arc<AtomicBool>,
left: Arc<Mutex<Option<hyper::body::Incoming>>>,
}
impl<B> HttpBody for Idle<B>
where
B: HttpBody<Data = Bytes> + Unpin,
B::Error: Into<axum::BoxError>,
{
impl Drop for Idle {
fn drop(&mut self) {
if !self.ended.load(Ordering::SeqCst)
&& let Some(rest) = self.inner.take()
{
*self.left.lock().unwrap_or_else(PoisonError::into_inner) = Some(rest);
}
}
}
impl HttpBody for Idle {
type Data = Bytes;
type Error = axum::BoxError;
@@ -860,9 +872,15 @@ where
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Bytes>, axum::BoxError>>> {
let this = self.get_mut();
match Pin::new(&mut this.inner).poll_frame(cx) {
let Some(inner) = this.inner.as_mut() else {
return Poll::Ready(None);
};
match Pin::new(&mut *inner).poll_frame(cx) {
Poll::Ready(frame) => {
this.sleep = None;
if frame.is_none() || inner.is_end_stream() {
this.ended.store(true, Ordering::SeqCst);
}
Poll::Ready(frame.map(|f| f.map_err(Into::into)))
}
Poll::Pending => {
@@ -879,20 +897,39 @@ where
}
fn is_end_stream(&self) -> bool {
self.inner.is_end_stream()
self.inner.as_ref().is_none_or(HttpBody::is_end_stream)
}
fn size_hint(&self) -> SizeHint {
self.inner.size_hint()
self.inner
.as_ref()
.map_or_else(|| SizeHint::with_exact(0), HttpBody::size_hint)
}
}
/// Read the rest of a body its request was answered without, and throw it
/// away, so that its connection takes the next request; given up, and the
/// connection closed, once it sends nothing for `BODY_IDLE`.
async fn drain(mut rest: hyper::body::Incoming) {
loop {
let frame = std::future::poll_fn(|cx| Pin::new(&mut rest).poll_frame(cx));
match tokio::time::timeout(BODY_IDLE, frame).await {
Ok(Some(Ok(_))) => {}
_ => return,
}
}
}
/// Serve `app` on `listener` until `stop` is ready: HTTP/1.1, upgrades for
/// the firehose, a connection closed that sends no whole request head within
/// `HEADER_TIMEOUT` of opening or of its last answer, and a request closed,
/// with no answer, whose body sends nothing for `BODY_IDLE`. Each request
/// is seen through `ops::Seen`. Once `stop` is ready, no connection is
/// taken, and those open finish the requests they have, for up to
/// with no answer, whose body sends nothing for `BODY_IDLE`. A request
/// answered before its body was read to its end has the rest read and thrown
/// away after the answer when its `Content-Length` leaves at most `DRAIN`
/// bytes of it, and is otherwise answered with `Connection: close`, its
/// connection closed after it (`spec/LIMITS.md`, "Request size"). Each
/// request is seen through `ops::Seen`. Once `stop` is ready, no connection
/// is taken, and those open finish the requests they have, for up to
/// `ops::DRAIN`; answers what `stop` did.
pub(crate) async fn serve<T>(
listener: tokio::net::TcpListener,
@@ -931,16 +968,20 @@ pub(crate) async fn serve<T>(
async move {
let seen = crate::ops::Seen::new(&req);
let timed_out = Arc::new(AtomicBool::new(false));
let flag = timed_out.clone();
let ended = Arc::new(AtomicBool::new(req.body().is_end_stream()));
let left = Arc::new(Mutex::new(None));
let (flag, read, rest) = (timed_out.clone(), ended.clone(), left.clone());
let mut req = req.map(move |inner| {
Body::new(Idle {
inner,
inner: Some(inner),
sleep: None,
timed_out: flag,
ended: read,
left: rest,
})
});
req.extensions_mut().insert(Peer(peer));
let res = match caught(seen.run(app.call(req))).await {
let mut res = match caught(seen.run(app.call(req))).await {
Ok(Ok(res)) => seen.answer(res),
Ok(Err(never)) => match never {},
// Its account's store was not held, and none is
@@ -950,6 +991,29 @@ pub(crate) async fn serve<T>(
}
Err(panic) => std::panic::resume_unwind(panic),
};
// A body left unread: hyper gives up on it, and closes
// the connection after the answer, but only once it has
// written the answer's head, saying nothing of it, and a
// client sends its next request on a connection being
// closed. So the rest is read here, as hyper writes the
// answer, or, too long or of no known length, the answer
// says the connection closes.
if !ended.load(Ordering::SeqCst) {
let rest = left.lock().unwrap_or_else(PoisonError::into_inner).take();
match rest
.filter(|r| r.size_hint().exact().is_some_and(|n| n <= DRAIN as u64))
{
Some(rest) => {
tokio::spawn(drain(rest));
}
None => {
res.headers_mut().insert(
axum::http::header::CONNECTION,
HeaderValue::from_static("close"),
);
}
}
}
// An error closes the connection, and nothing is answered.
if timed_out.load(Ordering::SeqCst) {
Err(BodyTimedOut)
harness/checks/limits.mjs+142−0
@@ -14,6 +14,7 @@ import { ADMIN_PASSWORD, LIMITS_UPLOAD_LIMIT, REFERENCE_TRUSTED_PROXIES } from '
import { Browser, Dpop, form, fresh, newKey, pkce, signInCall } from '../lib/oauth.mjs'
import { assertion, b64u, newPasskey, registration } from '../lib/webauthn.mjs'
import { checkDidDoc } from '../lib/plc.mjs'
import { reach } from '../lib/front.mjs'
import { below, chance, goodRecord, pick, rand, subset } from '../lib/random.mjs'
import { cand, dataDir, metricsUrl, plcProxy, ref, server, wait } from '../lib/processes.mjs'
import { begin, end, now } from '../lib/observe.mjs'
@@ -452,6 +453,147 @@ export async function oauthSignInTiming(acct) {
count('OAuth sign-in, a body past 100 KiB', false)
}
// ------------------------------------------- the connection after a refusal
/// One answer read off a connection: `{status, headers}`, headers
/// lowercased, once its body is whole; null until then.
function answerIn(buf) {
const at = buf.indexOf('\r\n\r\n')
if (at < 0) return null
const [line, ...rest] = buf.subarray(0, at).toString('latin1').split('\r\n')
const headers = {}
for (const h of rest) {
const i = h.indexOf(':')
const k = h.slice(0, i).trim().toLowerCase()
headers[k] = headers[k] === undefined ? h.slice(i + 1).trim() : `${headers[k]}, ${h.slice(i + 1).trim()}`
}
const status = Number(line.split(' ')[1])
let end = at + 4
if (/chunked/i.test(headers['transfer-encoding'] ?? '')) {
for (;;) {
const nl = buf.indexOf('\r\n', end)
if (nl < 0) return null
const size = parseInt(buf.subarray(end, nl).toString('latin1'), 16)
end = nl + 2 + size + 2
if (buf.length < end) return null
if (size === 0) break
}
} else {
end += Number(headers['content-length'] ?? 0)
if (buf.length < end) return null
}
return { status, headers, used: end }
}
/// A connection to `url`'s host, kept open between requests: `ask` writes
/// one whole and answers its answer, or `{status: 0, error}` once the
/// connection ends, or 5 s pass, with none.
function connection(url) {
const u = new URL(reach(url))
const socket = connect(Number(u.port || 80), u.hostname)
let buf = Buffer.alloc(0)
let ended = null
let wake = () => {}
socket.on('data', (c) => {
buf = Buffer.concat([buf, c])
wake()
})
socket.on('error', (err) => {
ended ??= err.message
wake()
})
socket.on('close', () => {
ended ??= 'the connection closed'
wake()
})
return {
host: u.host,
async ask(head, body) {
socket.write(head)
if (body) socket.write(body)
const deadline = Date.now() + 5000
for (;;) {
const res = answerIn(buf)
if (res) {
buf = buf.subarray(res.used)
return { status: res.status, headers: res.headers }
}
if (ended) return { status: 0, error: ended }
const left = deadline - Date.now()
if (left <= 0) return { status: 0, error: 'no answer within 5 s' }
await new Promise((ok) => {
const timer = setTimeout(ok, left)
wake = () => {
clearTimeout(timer)
ok()
}
})
}
},
end: () => socket.destroy(),
}
}
/// A request whose body is refused: OAuth's sign-in and PAR one byte past
/// 100 KiB, which may be refused before the body is read, a sign-in of a
/// few bytes refused for its CSRF token, and createRecord one byte past its
/// cap, sent with a `Content-Length` on a connection of its own. Each
/// leaves at most 4 MiB unread, so on the server the connection takes the
/// next request, sent 100 ms later, as a client that keeps connections open
/// sends it; on the reference, that, or an answer saying `Connection:
/// close` (spec/LIMITS.md, "Request size"). Statuses compared.
export async function refusedBodies(acct) {
const csrf = 'c'.repeat(24)
const signIn = JSON.stringify({ locale: 'en', identifier: acct.handle ?? 'nobody.test', password: 'x' })
const [kind, request] = pick([
['OAuth sign-in, a body one byte past 100 KiB', (side) => {
const origin = new URL(side.publicUrl).origin
const page = `${origin}/oauth/authorize?client_id=${encodeURIComponent('http://localhost')}&request_uri=${encodeURIComponent(`urn:ietf:params:oauth:request_uri:req-${'0'.repeat(32)}`)}`
const headers = { origin, referer: page, 'sec-fetch-mode': 'same-origin', 'sec-fetch-site': 'same-origin', 'sec-fetch-dest': 'empty', 'x-csrf-token': csrf, cookie: `csrf-token=${csrf}`, 'content-type': 'application/json' }
return { url: `${origin}/@atproto/oauth-provider/~api/sign-in`, headers, body: `${signIn.slice(0, -1)},"pad":"${'x'.repeat(102401 - signIn.length - 9)}"}` }
}],
['OAuth sign-in refused for its CSRF token, a body of a few bytes', (side) => {
const origin = new URL(side.publicUrl).origin
const page = `${origin}/oauth/authorize?client_id=${encodeURIComponent('http://localhost')}&request_uri=${encodeURIComponent(`urn:ietf:params:oauth:request_uri:req-${'0'.repeat(32)}`)}`
const headers = { origin, referer: page, 'sec-fetch-mode': 'same-origin', 'sec-fetch-site': 'same-origin', 'sec-fetch-dest': 'empty', 'x-csrf-token': csrf, cookie: `csrf-token=${'d'.repeat(24)}`, 'content-type': 'application/json' }
return { url: `${origin}/@atproto/oauth-provider/~api/sign-in`, headers, body: signIn }
}],
['PAR, a body one byte past 100 KiB', (side) => {
const start = `client_id=${encodeURIComponent('http://localhost')}&response_type=code&pad=`
return { url: `${new URL(side.publicUrl).origin}/oauth/par`, headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: `${start}${'x'.repeat(102401 - start.length)}` }
}],
['createRecord, a body one byte past its cap', (side) => {
const body = sized(1000001, (pad) => ({ repo: acct.handle, collection: 'com.example.big', record: { $type: 'com.example.big', pad } }))
return { url: `${side.url}/xrpc/${CREATE_RECORD}`, headers: { authorization: `Bearer ${tokenOf(side, acct)}`, 'content-type': 'application/json' }, body }
}],
])
const after = await Promise.all(sides().map(async (side) => {
const { url, headers, body } = request(side)
const c = connection(url)
const u = new URL(url)
const head = [`POST ${u.pathname}${u.search} HTTP/1.1`, `Host: ${c.host}`, ...Object.entries(headers).map(([k, v]) => `${k}: ${v}`), `Content-Length: ${Buffer.byteLength(body)}`, '', ''].join('\r\n')
const first = await c.ask(head, body)
let then
if (first.status === 0) then = `no answer: ${first.error}`
else if (/(^|,)\s*close\s*(,|$)/i.test(first.headers.connection ?? '')) then = 'Connection: close'
else {
await wait(100)
const next = await c.ask(`GET /xrpc/_health HTTP/1.1\r\nHost: ${c.host}\r\n\r\n`)
then = next.status === 200 ? 'the next request answered on it' : `the next request on it ${next.status ? `answered ${next.status}` : `not answered: ${next.error}`}`
}
c.end()
return { status: first.status, then }
}))
const shownRequest = { kind, chunked: false }
for (const [side, res] of sides().map((s, i) => [s, after[i]])) {
const kept = res.then === 'the next request answered on it'
if (side === cand ? !kept : !kept && res.then !== 'Connection: close')
await differ(`the ${side.name}'s connection after a body refused`, shownRequest, side === cand ? 'the connection taking the next request' : 'an answer saying Connection: close, or the connection taking the next request', res, side === ref ? 'the reference fails the check it is held to' : kind)
}
if (after[0].status !== after[1].status) await differ(kind, shownRequest, after[0].status, after[1].status)
count(`${kind}, the connection after`, after[0].status < 400)
}
// ------------------------------------------------- invite codes required
/// --invites: the reference with codes required, and the server with
harness/compare.mjs+2−2
@@ -115,7 +115,7 @@ import { oauthAssertionRefused, oauthClientCache, oauthClientDepartures, oauthCl
import { applyWrites, concurrent, createRecord, createWithTid, deleteRecord, describeRepo, getRecord, listRecords, putRecord } from './checks/records.mjs'
import { checkRepos } from './checks/repository.mjs'
import { describeServer, getSession } from './checks/session.mjs'
import { appPasswordScopes, bigBatch, bodyCaps, inviteCodes, invitesRequired, limitsRun, loginTiming, oauthSignInTiming } from './checks/limits.mjs'
import { appPasswordScopes, bigBatch, bodyCaps, inviteCodes, invitesRequired, limitsRun, loginTiming, oauthSignInTiming, refusedBodies } from './checks/limits.mjs'
import { appPasswords, deleteSession, refreshSession, sessionRace, wrongTokens } from './checks/sessions.mjs'
import { checkOperations, outage } from './checks/operations.mjs'
import { movesRun } from './checks/moves.mjs'
@@ -224,7 +224,7 @@ const STEPS_BY_WEIGHT = [
[oauthClientDocument, 4], [oauthClientCache, 1], [oauthClientLogin, 3], [oauthAssertionRefused, 3], [oauthConfidentialSession, 2], [oauthSilentSignIn, 2], [oauthClientDepartures, 1],
[oauthAccountAuth, 1], [oauthAccountSessions, 1], [oauthAccountDevices, 1],
[passkeyAuth, 1], [passkeyAdding, 1], [passkeySigningIn, 1], [passkeySignInRefused, 1], [passkeyRemoving, 1], [passkeyStates, 1],
[bigBatch, 1], [bodyCaps, 1], [inviteCodes, 4], [appPasswordScopes, 1], [loginTiming, 1], [oauthSignInTiming, 1],
[bigBatch, 1], [bodyCaps, 1], [refusedBodies, 2], [inviteCodes, 4], [appPasswordScopes, 1], [loginTiming, 1], [oauthSignInTiming, 1],
[requestEmailConfirmation, 2], [confirmEmail, 3], [requestEmailUpdate, 2], [updateEmail, 3], [emailFactor, 1], [passwordReset, 3], [appPasswordEmail, 1],
[forwarded, 4], [refused, 3], [serviceAuth, 3], [chatCase, 1], [preferences, 4], [readAfterWrite, 3], [foreignRecord, 1], [feedAndPush, 2],
[validatedWrite, 10], [duplicates, 5], [validatedBatch, 4], [validatedElsewhere, 1],
spec/LIMITS.md+19−0
@@ -68,6 +68,19 @@ the reference's.
`POST /mcp` refuses a body longer than 1048576 bytes with HTTP `413`, before
it reads it as JSON-RPC.
A request answered before its body was read to its end, whatever the
answer (an OAuth body refused by its `Content-Length`, `OAUTH.md`; a
request refused for its CSRF token or its origin; an upload past its limit;
a path not served), keeps its connection when its `Content-Length` leaves
at most 4 MiB of the body unread: the server reads the rest after the
answer and throws it away, and then takes the next request. A body with
more left than that, or sent chunked, is not
read on: its answer says `Connection: close`, and the connection is
closed after it. A JSON body refused for its size is read too, up to 4 MiB
past its limit, before it is answered. A client that keeps its
connections open (HTTP/1.1) so never sends its next request on a
connection the server is closing unless the answer said so.
## Commits
- An `applyWrites` of more than 200 writes is `400 InvalidRequest`. It is
@@ -519,6 +532,12 @@ again after each change. In every run, against the reference:
the right one: each answer, on each side, no sooner than 350 ms after it
was sent; and OAuth's sign-in likewise, no sooner than 400 ms, and with a
body one byte past 100 KiB, `413` (`OAUTH.md`).
- OAuth's sign-in and PAR with a body one byte past 100 KiB, a sign-in of
a few bytes refused for its CSRF token, and `createRecord` one byte past
its cap, each sent with a `Content-Length` on a connection of its own:
on the server the connection answers `/xrpc/_health` sent on it 100 ms
later; on the reference, that, or the answer says `Connection: close`.
Statuses compared.
With `--crash-every`, after each restart, the codes each account lists, and
a code made before the kill, used after it.