chadtmiller.com/monolith
An atproto PDS
0
0
The largest blob is PDS_BLOB_UPLOAD_LIMIT, as the reference's
crates/pds-server/src/scopes/tests.rs+1−1
| @@ -675,7 +675,7 @@ async fn blob_uploads() { | ||
"com.atproto.repo.uploadBlob", | ||
"", | ||
Some("image/png"), | ||
vec![0; crate::blobs::UPLOAD_LIMIT as usize + 1], | ||
vec![0; crate::blobs::DEFAULT_UPLOAD_LIMIT as usize + 1], | ||
) | ||
.await; | ||
assert_eq!(answer(&big).1, "PayloadTooLarge"); | ||
crates/pds-server/src/blobs.rs+18−12
| @@ -64,8 +64,9 @@ use std::pin::Pin; | ||
use std::sync::{Arc, LazyLock, OnceLock}; | ||
use std::task::{Context, Poll}; | ||
| ||
/// The largest body `uploadBlob` takes, as `describeServer` answers it. | ||
pub(crate) const UPLOAD_LIMIT: u64 = 5 * 1024 * 1024; | ||
/// The largest body `uploadBlob` takes unless `PDS_BLOB_UPLOAD_LIMIT` sets | ||
/// another (`Config::blob_upload_limit`): the reference's default. | ||
pub(crate) const DEFAULT_UPLOAD_LIMIT: u64 = 5 * 1024 * 1024; | ||
| ||
const UPLOAD: &str = "com.atproto.repo.uploadBlob"; | ||
| ||
| @@ -1390,14 +1391,15 @@ async fn upload_blob( | ||
.collect(); | ||
crate::scopes::may(call.bearer, &crate::scopes::Need::Blob(&latin1))?; | ||
let too_large = || err(413, "PayloadTooLarge", "request entity too large"); | ||
let limit = svc.config.blob_upload_limit; | ||
let length = headers | ||
.get(header::CONTENT_LENGTH) | ||
.and_then(|v| v.to_str().ok()?.trim().parse::<u64>().ok()); | ||
if length.is_some_and(|n| n > UPLOAD_LIMIT) { | ||
if length.is_some_and(|n| n > limit) { | ||
return too_large(); | ||
} | ||
if let Some(bucket) = svc.ctx.bucket.clone() { | ||
let bytes = read_whole(body, length).await?; | ||
let bytes = read_whole(body, length, limit).await?; | ||
crate::limits::guard(&svc, call, Some(&did), None)?; | ||
let cid = cid_string(&cid_of(0x55, &bytes)); | ||
let head = &bytes[..bytes.len().min(16)]; | ||
| @@ -1436,7 +1438,7 @@ async fn upload_blob( | ||
continue; | ||
}; | ||
size += data.len() as u64; | ||
if size > UPLOAD_LIMIT { | ||
if size > limit { | ||
return too_large(); | ||
} | ||
hash.update(&data); | ||
| @@ -1464,8 +1466,12 @@ async fn upload_blob( | ||
Ok(Resp::Json(answer)) | ||
} | ||
| ||
/// An upload's body, whole, in memory: at most `UPLOAD_LIMIT` bytes. | ||
async fn read_whole(body: &mut Body, length: Option<u64>) -> Result<Vec<u8>, XrpcError> { | ||
/// An upload's body, whole, in memory: at most `limit` bytes. | ||
async fn read_whole( | ||
body: &mut Body, | ||
length: Option<u64>, | ||
limit: u64, | ||
) -> Result<Vec<u8>, XrpcError> { | ||
let mut bytes = Vec::with_capacity(length.unwrap_or(0) as usize); | ||
while let Some(frame) = next_frame(body).await { | ||
let Ok(frame) = frame else { | ||
| @@ -1474,7 +1480,7 @@ async fn read_whole(body: &mut Body, length: Option<u64>) -> Result<Vec<u8>, Xrp | ||
let Ok(data) = frame.into_data() else { | ||
continue; | ||
}; | ||
if (bytes.len() + data.len()) as u64 > UPLOAD_LIMIT { | ||
if (bytes.len() + data.len()) as u64 > limit { | ||
return err(413, "PayloadTooLarge", "request entity too large"); | ||
} | ||
bytes.extend_from_slice(&data); | ||
| @@ -2112,7 +2118,7 @@ mod tests { | ||
let (did, token) = create(&s, "alice").await; | ||
let t = Some(token.as_str()); | ||
// The token, then the Content-Type, then the size. | ||
let big = vec![0u8; UPLOAD_LIMIT as usize + 1]; | ||
let big = vec![0u8; DEFAULT_UPLOAD_LIMIT as usize + 1]; | ||
assert_eq!( | ||
test_upload(&s, None, None, big.clone(), false).await, | ||
Err((401, "AuthMissing".into())) | ||
| @@ -2161,7 +2167,7 @@ mod tests { | ||
assert_eq!(files(&dir, &did), Vec::<String>::new()); | ||
// Exactly the limit is taken, chunked or not, and so is nothing. | ||
for chunked in [false, true] { | ||
let exact = vec![7u8; UPLOAD_LIMIT as usize]; | ||
let exact = vec![7u8; DEFAULT_UPLOAD_LIMIT as usize]; | ||
let got = test_upload( | ||
&s, | ||
t, | ||
| @@ -2173,7 +2179,7 @@ mod tests { | ||
.unwrap(); | ||
assert_eq!( | ||
got, | ||
json!({ "blob": bref(&raw_cid(&exact), "application/octet-stream", UPLOAD_LIMIT as i64) }) | ||
json!({ "blob": bref(&raw_cid(&exact), "application/octet-stream", DEFAULT_UPLOAD_LIMIT as i64) }) | ||
); | ||
} | ||
let got = test_upload(&s, t, Some("image/png"), vec![], false) | ||
| @@ -2793,7 +2799,7 @@ mod tests { | ||
serde_json::from_slice::<Json>(&res.bytes().unwrap()).unwrap()["error"].clone(), | ||
) | ||
}; | ||
let big = || vec![b'a'; UPLOAD_LIMIT as usize + 1]; | ||
let big = || vec![b'a'; DEFAULT_UPLOAD_LIMIT as usize + 1]; | ||
vec![ | ||
send(&token, big().into()), | ||
send(&token, reqwest::blocking::Body::new(io::Cursor::new(big()))), | ||
crates/pds-server/src/lib.rs+9−0
| @@ -141,6 +141,10 @@ pub(crate) struct Config { | ||
/// The bytes of the CAR file `com.atproto.repo.importRepo` takes | ||
/// (`PDS_MAX_REPO_IMPORT_SIZE`, `spec/LIMITS.md`). | ||
pub max_import: u64, | ||
/// The bytes of a blob `uploadBlob` takes, and of a space repo's archive | ||
/// `com.atproto.space.importRepo` takes (`PDS_BLOB_UPLOAD_LIMIT`, | ||
/// `spec/LIMITS.md`); `describeServer` answers it. | ||
pub blob_upload_limit: u64, | ||
/// How long, in seconds, a DID document fetched from the directory is served. | ||
pub did_cache: u64, | ||
/// How long after its input is checked `createSession` answers, at the soonest. | ||
| @@ -258,6 +262,10 @@ impl Config { | ||
blob_ttl: limits::env_u64("PDS_BLOB_TTL_SECS", 3600)?, | ||
min_free: limits::env_u64("PDS_MIN_FREE_BYTES", 256 << 20)?, | ||
max_import: limits::env_u64("PDS_MAX_REPO_IMPORT_SIZE", 300 << 20)?, | ||
blob_upload_limit: limits::env_u64( | ||
"PDS_BLOB_UPLOAD_LIMIT", | ||
blobs::DEFAULT_UPLOAD_LIMIT, | ||
)?, | ||
did_cache: limits::env_u64("PDS_DID_CACHE_SECS", 3600)?, | ||
login_floor: std::time::Duration::from_millis(350), | ||
sign_in_floor: std::time::Duration::from_millis(400), | ||
| @@ -1470,6 +1478,7 @@ mod testing { | ||
blob_ttl: 3600, | ||
min_free: 0, | ||
max_import: 5 << 20, | ||
blob_upload_limit: crate::blobs::DEFAULT_UPLOAD_LIMIT, | ||
did_cache: 0, | ||
login_floor: std::time::Duration::ZERO, | ||
sign_in_floor: std::time::Duration::ZERO, | ||
crates/pds-server/src/limits.rs+14−5
| @@ -23,8 +23,6 @@ pub(crate) const MAX_RECORD_BODY: usize = 1_000_000; | ||
pub(crate) const MAX_BODY: usize = 153_600; | ||
/// The longest space meta archive `importSpaceMeta` reads. | ||
pub(crate) const MAX_ARCHIVE_BODY: usize = 16 * 1024 * 1024; | ||
/// The longest space repo archive `importRepo` reads, as an upload's. | ||
pub(crate) const MAX_REPO_ARCHIVE_BODY: usize = 5 * 1024 * 1024; | ||
/// The longest body `POST /mcp` takes. | ||
pub(crate) const MAX_MCP_BODY: usize = 1_048_576; | ||
/// The most writes one `applyWrites` may make. | ||
| @@ -101,8 +99,6 @@ pub(crate) fn body_limit(nsid: &str) -> usize { | ||
"com.atproto.space.applyWrites", | ||
]) { | ||
MAX_RECORD_BODY | ||
} else if is(&["com.atproto.space.importRepo"]) { | ||
MAX_REPO_ARCHIVE_BODY | ||
} else if is(&["com.atproto.space.importSpaceMeta"]) { | ||
MAX_ARCHIVE_BODY | ||
} else { | ||
| @@ -112,16 +108,29 @@ pub(crate) fn body_limit(nsid: &str) -> usize { | ||
| ||
/// How much of a request's body is read before it is refused as too long: | ||
/// `importRepo`'s CAR file up to `PDS_MAX_REPO_IMPORT_SIZE`, which it | ||
/// checks itself (`migration`), and any other method's as `body_limit` says. | ||
/// checks itself (`migration`), a space repo's archive up to | ||
/// `PDS_BLOB_UPLOAD_LIMIT` (`archive_limit`), and any other method's as | ||
/// `body_limit` says. | ||
pub(crate) fn read_limit(s: &Service, nsid: &str) -> usize { | ||
let nsid = nsid.strip_suffix('/').unwrap_or(nsid); | ||
if nsid.eq_ignore_ascii_case(crate::migration::IMPORT_REPO) { | ||
usize::try_from(s.config.max_import).map_or(usize::MAX - 1, |n| n.min(usize::MAX - 1)) | ||
} else if nsid.eq_ignore_ascii_case(SPACE_IMPORT_REPO) { | ||
archive_limit(s) | ||
} else { | ||
body_limit(nsid) | ||
} | ||
} | ||
| ||
/// The space `importRepo`, whose archive is bounded as an upload is. | ||
const SPACE_IMPORT_REPO: &str = "com.atproto.space.importRepo"; | ||
| ||
/// The longest space repo archive `importRepo` takes: `PDS_BLOB_UPLOAD_LIMIT` | ||
/// bytes, as an upload (`spec/LIMITS.md`, "Request size"). | ||
pub(crate) fn archive_limit(s: &Service) -> usize { | ||
usize::try_from(s.config.blob_upload_limit).map_or(usize::MAX - 1, |n| n.min(usize::MAX - 1)) | ||
} | ||
| ||
/// A body too big for its method. | ||
pub(crate) fn too_large<T>() -> Result<T, XrpcError> { | ||
err(413, "PayloadTooLargeError", "request entity too large") | ||
crates/pds-server/src/server.rs+1−1
| @@ -35,7 +35,7 @@ fn describe_server( | ||
"did": format!("did:web:{}", s.config.hostname), | ||
"availableUserDomains": s.config.handle_domains, | ||
"inviteCodeRequired": s.config.invite_required, | ||
"blobUploadLimit": crate::blobs::UPLOAD_LIMIT, | ||
"blobUploadLimit": s.config.blob_upload_limit, | ||
"spacesAlpha": true, | ||
}))) | ||
} | ||
crates/pds-server/src/space_repo.rs+1−1
| @@ -2097,7 +2097,7 @@ async fn import_repo(svc: &Shared, call: &Call<'_>) -> Result<Resp, XrpcError> { | ||
if !media.is_some_and(|t| t.eq_ignore_ascii_case("application/octet-stream")) { | ||
return invalid("Wrong request encoding (Content-Type): expected application/octet-stream"); | ||
} | ||
if call.body.len() > crate::limits::body_limit(call.nsid) { | ||
if call.body.len() > crate::limits::archive_limit(svc) { | ||
return err(413, "PayloadTooLarge", "request entity too large"); | ||
} | ||
crate::limits::guard(svc, call, Some(&a.did), None)?; | ||
docs/guide/comparing.md+2−1
| @@ -103,7 +103,8 @@ node compare.mjs --steps 400 --seed 1 --limits -- ../target/release/pds serve | ||
| ||
`--invites` runs the reference and the server with invite codes required. | ||
`--limits` turns the rate limits on and compares each with the | ||
reference's, with password sessions and OAuth tokens, then holds the | ||
reference's, with password sessions and OAuth tokens, and starts both with | ||
an upload limit of their own, compared at its edge; then holds the | ||
server alone to the rest of [LIMITS.md](../../spec/LIMITS.md): file modes, | ||
the session and app-password caps, firehose messages and subscribers, | ||
calls to the PLC directory, timeouts, the free-space floor, the blob quota | ||
docs/guide/deploying.md+1−0
| @@ -54,6 +54,7 @@ says the rest. | ||
| `PDS_CRAWLERS` | the relays told of it, as `https://bsky.network` | | ||
| `PDS_BSKY_APP_VIEW_URL`, `PDS_BSKY_APP_VIEW_DID`, `PDS_BSKY_APP_VIEW_CDN_URL_PATTERN` | `https://api.bsky.app`, `did:web:api.bsky.app` and `https://cdn.bsky.app/img/%s/plain/%s/%s@jpeg`, for the Bluesky app | | ||
| `PDS_MAX_REPO_IMPORT_SIZE` | the largest repository an account may bring when it moves here ([MIGRATION.md](../../spec/MIGRATION.md)), 300 MiB unless set | | ||
| `PDS_BLOB_UPLOAD_LIMIT` | the largest blob an account may upload, 5 MiB unless set ([LIMITS.md](../../spec/LIMITS.md)); at least as large as the old server's when accounts move here from one that takes larger blobs, as for video, else theirs cannot all be brought | | ||
| `PDS_HANDLE_DNS_SERVER` | optionally, the DNS server asked for a handle's `_atproto` TXT record when an account takes a handle of its own domain ([IDENTITY.md](../../spec/IDENTITY.md#resolving-a-handle)); unset, the machine's resolver | | ||
| `PDS_BLOBSTORE_S3_BUCKET` and the rest of [BLOBS.md](../../spec/BLOBS.md#where-blobs-are-kept)'s | optionally, a bucket of an S3-compatible store to keep blobs in, rather than the data directory (below) | | ||
| ||
harness/checks/limits.mjs+48−3
| @@ -10,7 +10,7 @@ import { connect } from 'node:net' | ||
import { join } from 'node:path' | ||
import { isDeepStrictEqual } from 'node:util' | ||
import { ONLY } from '../lib/args.mjs' | ||
import { ADMIN_PASSWORD, REFERENCE_TRUSTED_PROXIES } from '../lib/env.mjs' | ||
import { ADMIN_PASSWORD, LIMITS_UPLOAD_LIMIT, REFERENCE_TRUSTED_PROXIES } from '../lib/env.mjs' | ||
import { Dpop, form, fresh, newKey, pkce, signInCall } from '../lib/oauth.mjs' | ||
import { checkDidDoc } from '../lib/plc.mjs' | ||
import { below, chance, goodRecord, pick, rand, subset } from '../lib/random.mjs' | ||
| @@ -642,6 +642,51 @@ async function uploadLimit() { | ||
await limited('uploadBlob, the 1001st', UPLOAD, blob(null, 1000)) | ||
} | ||
| ||
/// The default upload limit, which the run's is past. | ||
const DEFAULT_UPLOAD_LIMIT = 5242880 | ||
| ||
/// A body of `n` bytes that begins `spec-pds blob `, so that its type is | ||
/// the request's (spec/BLOBS.md, "uploadBlob"). | ||
function blobOf(n) { | ||
const b = Buffer.alloc(n, 0x61) | ||
b.write(`spec-pds blob limit ${++serial} `) | ||
return b | ||
} | ||
| ||
/// The upload limit set, both sides started with PDS_BLOB_UPLOAD_LIMIT | ||
/// (spec/LIMITS.md, "Environment", "Request size"; spec/BLOBS.md, | ||
/// "uploadBlob"): `describeServer`'s `blobUploadLimit`, then uploadBlob of | ||
/// a body a byte past the default, of one at the limit and of one a byte | ||
/// past it, each with its length or chunked, compared whole. | ||
async function uploadSize() { | ||
const [da, db] = await pair(DESCRIBE_SERVER, { ip: freshIp() }) | ||
if (da.body?.blobUploadLimit !== LIMITS_UPLOAD_LIMIT) throw new Error(`the reference's blobUploadLimit is ${da.body?.blobUploadLimit}, not ${LIMITS_UPLOAD_LIMIT}: it was not started with it`) | ||
if (db.body?.blobUploadLimit !== LIMITS_UPLOAD_LIMIT) await differ(DESCRIBE_SERVER, { PDS_BLOB_UPLOAD_LIMIT: LIMITS_UPLOAD_LIMIT }, LIMITS_UPLOAD_LIMIT, db.body?.blobUploadLimit ?? null, 'spec/LIMITS.md: describeServer answers PDS_BLOB_UPLOAD_LIMIT as blobUploadLimit') | ||
count('describeServer blobUploadLimit, set', true) | ||
const acct = await freshAccount() | ||
for (const n of [DEFAULT_UPLOAD_LIMIT + 1, LIMITS_UPLOAD_LIMIT, LIMITS_UPLOAD_LIMIT + 1]) { | ||
const raw = blobOf(n) | ||
const chunked = chance(0.5) | ||
const request = { raw, contentType: 'application/octet-stream', token: acct, ip: freshIp(), chunked } | ||
await compared(`uploadBlob of ${n} bytes, the limit ${LIMITS_UPLOAD_LIMIT}`, UPLOAD, { body: `${n} bytes`, chunked, token: acct }, await pair(UPLOAD, request)) | ||
} | ||
} | ||
| ||
/// A space importRepo under the upload limit set (spec/LIMITS.md, | ||
/// "Request size"; spec/SPACES-EXPORT.md, "importRepo"), which the | ||
/// reference here does not serve: a body a byte past the default, no | ||
/// archive, `400 InvalidRequest`; one a byte past the limit, `413 | ||
/// PayloadTooLarge`. | ||
async function spaceImportSize() { | ||
const acct = await freshAccount() | ||
const nsid = 'com.atproto.space.importRepo' | ||
for (const [n, want] of [[DEFAULT_UPLOAD_LIMIT + 1, { status: 400, error: 'InvalidRequest' }], [LIMITS_UPLOAD_LIMIT + 1, { status: 413, error: 'PayloadTooLarge' }]]) { | ||
const r = await send(cand, nsid, { raw: blobOf(n), contentType: 'application/octet-stream', token: acct, ip: freshIp() }) | ||
if (r.status !== want.status || r.body?.error !== want.error) await broke(nsid, { body: `${n} bytes`, PDS_BLOB_UPLOAD_LIMIT: LIMITS_UPLOAD_LIMIT }, want, { status: r.status, error: r.body?.error }) | ||
} | ||
count('space importRepo under the upload limit set', false) | ||
} | ||
| ||
/// Writes: applyWrites of 200 creates, 600 points each, past the hour's | ||
/// 5000; a createRecord before, and a deleteRecord after (spec/LIMITS.md, | ||
/// "Rate limits"). | ||
| @@ -1432,8 +1477,8 @@ async function fileModes() { | ||
/// --limits: the reference's rate limits, then what the server holds. | ||
export async function limitsRun() { | ||
const checks = [ | ||
signupLimit, loginLimit, handleLimit, uploadLimit, writeLimit, forwardedLimit, globalLimit, emailRequestLimits, passwordResetLimit, resetLimit, accountDeleteRequestLimit, deleteLimit, ...OAUTH_LIMIT_CHECKS, | ||
sessionCap, appPasswordCap, ...OAUTH_SERVER_CHECKS, clientAddress, adminUnset, spacesPayFirst, didWebApart, outboundCaps, requestsOut, | ||
signupLimit, loginLimit, handleLimit, uploadLimit, uploadSize, writeLimit, forwardedLimit, globalLimit, emailRequestLimits, passwordResetLimit, resetLimit, accountDeleteRequestLimit, deleteLimit, ...OAUTH_LIMIT_CHECKS, | ||
sessionCap, appPasswordCap, ...OAUTH_SERVER_CHECKS, clientAddress, adminUnset, spacesPayFirst, didWebApart, outboundCaps, requestsOut, spaceImportSize, | ||
firehoseMessages, firehoseSubscribers, plcDocuments, plcAtOnce, timeouts, diskFloor, blobQuota, blobTtl, openFiles, writesTogether, fileModes, | ||
] | ||
for (const check of checks) { | ||
harness/lib/env.mjs+10−2
| @@ -16,6 +16,12 @@ export const ADMIN_PASSWORD = 'admin-pass' | ||
/// to send. | ||
export const MAX_REPO_IMPORT = 1048576 | ||
| ||
/// The upload limit both sides are started with in --limits | ||
/// (spec/LIMITS.md, PDS_BLOB_UPLOAD_LIMIT): past the default 5 MiB, and | ||
/// not a round number, so that a server keeping the default, or rounding, | ||
/// is seen. | ||
export const LIMITS_UPLOAD_LIMIT = 6291459 | ||
| ||
/// The proxies the reference trusts in `X-Forwarded-For` (Express's | ||
/// `loopback`, `linklocal` and `uniquelocal`), which the server is told to | ||
/// trust too, so that both read the harness's headers alike | ||
| @@ -30,7 +36,8 @@ export const REFERENCE_TRUSTED_PROXIES = '127.0.0.0/8,::1/128,169.254.0.0/16,fe8 | ||
/// `clientFetch`, if given; with either, without SSRF protection, as the | ||
/// reference runs. Answers it, and the rotation key's `did:key`. It trusts | ||
/// the proxies the reference trusts. With | ||
/// `limits`, its rate limits are on and its DID documents kept as long as | ||
/// `limits`, its rate limits are on, its uploads limited to | ||
/// `LIMITS_UPLOAD_LIMIT` bytes, and its DID documents kept as long as | ||
/// it likes; without, as the reference runs, off, and every `describeRepo` | ||
/// asks the directory. With `invites`, invite codes are required. With | ||
/// `backfillMs`, the firehose's backfill window is that, and with | ||
| @@ -60,7 +67,8 @@ export async function serverEnv({ port, dataDir, plc, recoveryKey, crawlers, app | ||
PDS_TRUSTED_PROXIES: REFERENCE_TRUSTED_PROXIES, | ||
PDS_MAX_REPO_IMPORT_SIZE: String(MAX_REPO_IMPORT), | ||
} | ||
if (!limits) env.PDS_DID_CACHE_SECS = '0' | ||
if (limits) env.PDS_BLOB_UPLOAD_LIMIT = String(LIMITS_UPLOAD_LIMIT) | ||
else env.PDS_DID_CACHE_SECS = '0' | ||
if (recoveryKey) env.PDS_RECOVERY_DID_KEY = recoveryKey | ||
if (crawlers?.length) env.PDS_CRAWLERS = crawlers.join(',') | ||
if (appView) { | ||