diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index 773f80ddf..8c7ff1d08 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -336,6 +336,63 @@ struct EncryptedBlobEntry { oid: String, } +/// How many times one envelope fetch is retried after the node sheds it with a +/// 503 or 429, so a blob gets at most this many attempts plus the first. +const ENVELOPE_SHED_RETRIES: u32 = 3; + +/// The longest a single `Retry-After` on a 503 shed is honored, so a node cannot +/// stall a clone for as long as it likes on one blob. +const ENVELOPE_RETRY_AFTER_CAP_SECS: u64 = 10; + +/// The longest a 429 from the per-IP brake is honored. The brake counts over a +/// one-minute window and its `Retry-After` is the time until that window frees, +/// so a shorter cap would retry inside the same window and skip the blob. +const ENVELOPE_BRAKE_RETRY_AFTER_CAP_SECS: u64 = 60; + +/// The wait used when a shed response has no `Retry-After`, or one that is not +/// an integer number of seconds. +const ENVELOPE_RETRY_AFTER_DEFAULT_SECS: u64 = 2; + +/// Fetch one encrypted-blob envelope, retrying while the node sheds load. +/// +/// The node answers 503 (concurrency cap) or 429 (per-client rate brake) on this +/// route when it is busy, both with `Retry-After` in seconds. That is transient, +/// so skipping the blob on the first one would drop a withheld file from a clone +/// that otherwise succeeds. +async fn fetch_envelope(client: &NodeClient, path: &str) -> Result { + let mut retries_left = ENVELOPE_SHED_RETRIES; + loop { + let resp = client.get_signed(path).await?; + let shed = matches!( + resp.status(), + reqwest::StatusCode::SERVICE_UNAVAILABLE | reqwest::StatusCode::TOO_MANY_REQUESTS + ); + if !shed || retries_left == 0 { + return Ok(resp); + } + retries_left -= 1; + let retry_after = resp + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|v| v.to_str().ok()); + let wait = shed_retry_wait_secs(resp.status(), retry_after); + tokio::time::sleep(std::time::Duration::from_secs(wait)).await; + } +} + +/// How long to wait before retrying a shed envelope fetch. +fn shed_retry_wait_secs(status: reqwest::StatusCode, retry_after: Option<&str>) -> u64 { + let cap = if status == reqwest::StatusCode::TOO_MANY_REQUESTS { + ENVELOPE_BRAKE_RETRY_AFTER_CAP_SECS + } else { + ENVELOPE_RETRY_AFTER_CAP_SECS + }; + retry_after + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(ENVELOPE_RETRY_AFTER_DEFAULT_SECS) + .min(cap) +} + /// After the base clone, recover encrypted blobs the caller is authorized for /// that are missing locally: fetch the envelope, decrypt with the caller's key, /// install as a loose object. Returns the repo-relative paths recovered. @@ -396,11 +453,11 @@ async fn recover_encrypted_blobs( if present { continue; } - let env_resp = match client - .get_signed(&format!( - "/api/v1/repos/{owner}/{name}/encrypted-blob/{oid}" - )) - .await + let env_resp = match fetch_envelope( + &client, + &format!("/api/v1/repos/{owner}/{name}/encrypted-blob/{oid}"), + ) + .await { Ok(r) if r.status().is_success() => r, // The node path has the same silent exit the gateway path had: a 403, a @@ -2284,4 +2341,185 @@ mod tests { let out = child.wait_with_output().unwrap(); assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), oid); } + + /// A partial clone whose `secret/b.txt` blob is absent locally and cannot be + /// lazily fetched (the promisor remote is deleted), so only the node's + /// encrypted-blob route can restore it. Returns the tempdir, the clone, and + /// the withheld blob's oid. + fn clone_missing_secret_blob() -> (TempDir, std::path::PathBuf, String) { + let (td, url) = bare_remote(&[("public/a.txt", b"pub\n"), ("secret/b.txt", b"SECRET\n")]); + let dest = td.path().join("dest"); + let bare = url.strip_prefix("file://").unwrap().to_string(); + assert!(Command::new("git") + .args(["-C", &bare, "config", "uploadpack.allowFilter", "true"]) + .status() + .unwrap() + .success()); + setup_partial_clone(&dest, &url, &["/secret/**".to_string()], &[], None).unwrap(); + let out = Command::new("git") + .args([ + "-C", + dest.to_str().unwrap(), + "rev-parse", + "HEAD:secret/b.txt", + ]) + .output() + .unwrap(); + let oid = String::from_utf8_lossy(&out.stdout).trim().to_string(); + std::fs::remove_dir_all(&bare).unwrap(); + (td, dest, oid) + } + + /// Mock the node's inventory listing the one withheld blob. The envelope + /// route is mocked by each test. + async fn mock_inventory(server: &mut mockito::ServerGuard, oid: &str) -> mockito::Mock { + server + .mock("GET", "/api/v1/repos/alice/myrepo/encrypted-blobs") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(serde_json::json!({ "blobs": [{ "oid": oid }] }).to_string()) + .create_async() + .await + } + + /// A shed (503 or 429 with `Retry-After`) on the envelope fetch is retried, and + /// the next 200 recovers the blob instead of the clone silently dropping it. + async fn envelope_shed_once_then_ok_recovers(shed_status: usize) { + use twigpine_core::encrypt::seal_blob; + use twigpine_core::identity::Keypair; + + let (_td, dest, oid) = clone_missing_secret_blob(); + let reader = Keypair::generate(); + let envelope = seal_blob(b"SECRET\n", &[reader.verifying_key()]).unwrap(); + + let mut server = mockito::Server::new_async().await; + let _inv = mock_inventory(&mut server, &oid).await; + let path = format!("/api/v1/repos/alice/myrepo/encrypted-blob/{oid}"); + let shed = server + .mock("GET", path.as_str()) + .with_status(shed_status) + .with_header("retry-after", "0") + .expect(1) + .create_async() + .await; + let ok = server + .mock("GET", path.as_str()) + .with_status(200) + .with_body(envelope) + .expect(1) + .create_async() + .await; + + let paths = recover_encrypted_blobs(&server.url(), "alice", "myrepo", &dest, &reader) + .await + .unwrap(); + assert_eq!( + paths, + vec!["secret/b.txt".to_string()], + "a {shed_status} shed followed by a 200 must still recover the blob" + ); + shed.assert_async().await; + ok.assert_async().await; + } + + #[tokio::test] + async fn recover_encrypted_blobs_retries_a_503_shed() { + envelope_shed_once_then_ok_recovers(503).await; + } + + #[tokio::test] + async fn recover_encrypted_blobs_retries_a_429_brake() { + envelope_shed_once_then_ok_recovers(429).await; + } + + /// The retry is bounded: a node that keeps shedding gets four attempts in + /// total, then the blob is skipped with the last status, as before. + #[tokio::test] + async fn recover_encrypted_blobs_gives_up_after_bounded_retries() { + use twigpine_core::identity::Keypair; + + let (_td, dest, oid) = clone_missing_secret_blob(); + let reader = Keypair::generate(); + let mut server = mockito::Server::new_async().await; + let _inv = mock_inventory(&mut server, &oid).await; + let shed = server + .mock( + "GET", + format!("/api/v1/repos/alice/myrepo/encrypted-blob/{oid}").as_str(), + ) + .with_status(503) + .with_header("retry-after", "0") + .expect(4) + .create_async() + .await; + + reset_warnings(); + let paths = recover_encrypted_blobs(&server.url(), "alice", "myrepo", &dest, &reader) + .await + .unwrap(); + assert!( + paths.is_empty(), + "a node that never stops shedding recovers nothing" + ); + shed.assert_async().await; + assert!( + warnings().contains("503"), + "the skip must report the last status, got: {:?}", + warnings() + ); + } + + /// Only a shed is retried: a 404 is final and is requested exactly once. + /// The per-IP brake's 429 asks for up to its whole window, so the client must + /// be able to wait that long once, or every retry lands inside the same + /// window and the blob is skipped. A 503 shed stays on the short cap. + #[test] + fn shed_retry_wait_honors_a_brake_window_but_caps_a_shed() { + use reqwest::StatusCode; + assert_eq!( + shed_retry_wait_secs(StatusCode::TOO_MANY_REQUESTS, Some("59")), + 59 + ); + assert_eq!( + shed_retry_wait_secs(StatusCode::TOO_MANY_REQUESTS, Some("600")), + 60 + ); + assert_eq!( + shed_retry_wait_secs(StatusCode::SERVICE_UNAVAILABLE, Some("59")), + 10 + ); + assert_eq!( + shed_retry_wait_secs(StatusCode::SERVICE_UNAVAILABLE, None), + 2 + ); + assert_eq!( + shed_retry_wait_secs(StatusCode::TOO_MANY_REQUESTS, Some("soon")), + 2 + ); + } + + #[tokio::test] + async fn recover_encrypted_blobs_does_not_retry_a_404() { + use twigpine_core::identity::Keypair; + + let (_td, dest, oid) = clone_missing_secret_blob(); + let reader = Keypair::generate(); + let mut server = mockito::Server::new_async().await; + let _inv = mock_inventory(&mut server, &oid).await; + let missing = server + .mock( + "GET", + format!("/api/v1/repos/alice/myrepo/encrypted-blob/{oid}").as_str(), + ) + .with_status(404) + .expect(1) + .create_async() + .await; + + let paths = recover_encrypted_blobs(&server.url(), "alice", "myrepo", &dest, &reader) + .await + .unwrap(); + assert!(paths.is_empty(), "a 404 envelope is not recoverable"); + missing.assert_async().await; + } } diff --git a/crates/twigpine-core/src/encrypt.rs b/crates/twigpine-core/src/encrypt.rs index 07a1fc5c4..a3e62a15e 100644 --- a/crates/twigpine-core/src/encrypt.rs +++ b/crates/twigpine-core/src/encrypt.rs @@ -90,7 +90,7 @@ const VERSION: u8 = 2; /// answer "not a recipient", so the count has to be capped rather than /// optimized (#419). Legitimate envelopes carry a handful of authorized /// readers, so 256 is far above real use. -const MAX_RECIPIENTS: usize = 256; +pub const MAX_RECIPIENTS: usize = 256; #[derive(Serialize, Deserialize)] struct Recipient { diff --git a/crates/twigpine-node/src/api/encrypted.rs b/crates/twigpine-node/src/api/encrypted.rs index 5bc2da6f2..b708dda2b 100644 --- a/crates/twigpine-node/src/api/encrypted.rs +++ b/crates/twigpine-node/src/api/encrypted.rs @@ -7,6 +7,91 @@ use crate::auth::AuthenticatedDid; use crate::error::{AppError, Result}; use crate::state::AppState; +/// Hard ceiling on the envelope bytes this node reads back from IPFS, on the +/// serve route and in the replication loop. An envelope is the sealed plaintext +/// plus a header whose size grows with the recipient list, so the ceiling is the +/// served-object ceiling plus room for a header sealed to the most recipients +/// `seal_blob` accepts. A memory guard, not an operator knob. +pub(crate) const MAX_SERVED_ENVELOPE_BYTES: usize = + crate::api::ipfs::MAX_SERVED_OBJECT_BYTES as usize + ENVELOPE_HEADER_ALLOWANCE; + +/// Node-wide cap on encrypted-blob serves in flight, counted until each response +/// body is fully sent or dropped. +pub(crate) const MAX_CONCURRENT_ENCRYPTED_SERVES: usize = 4; + +/// How many of those serves one client IP may hold at once. +pub(crate) const ENCRYPTED_SERVES_PER_SOURCE: usize = 1; + +/// Per-client-IP requests per minute on the encrypted-blob serve route. +pub(crate) const ENCRYPTED_BLOB_RATE_PER_MINUTE: usize = 120; + +/// Room for the envelope prefix, the JSON header at the maximum recipient +/// count, and the body's AEAD tag. +const ENVELOPE_HEADER_ALLOWANCE: usize = 64 * 1024; + +/// Envelope bytes per body frame. +const SERVE_CHUNK_BYTES: usize = 64 * 1024; + +/// The admission a serve holds. It lives in the envelope allocation owner, so +/// it is released only when the last slice of that allocation is dropped. +struct ServePermits { + _global: tokio::sync::OwnedSemaphorePermit, + _per_source: Option, +} + +/// One served envelope allocation and the admission charged for it. Field order +/// is load-bearing: the buffer drops before the permits, so admission is not +/// released while any slice can still retain the allocation. +struct EnvelopeAllocation { + data: Vec, + _permits: ServePermits, +} + +impl AsRef<[u8]> for EnvelopeAllocation { + fn as_ref(&self) -> &[u8] { + &self.data + } +} + +/// How long a response may take to send. Checked each time the server asks for +/// the next frame, so a reader that keeps pulling slowly is cut off here; a +/// reader that stops pulling entirely holds its slot until the connection +/// closes, and memory stays bounded either way because the slot is still held. +const ENCRYPTED_SERVE_SEND_DEADLINE: std::time::Duration = std::time::Duration::from_secs(60); + +/// The envelope as a streamed body whose allocation owns the serve's admission. +/// Every emitted slice shares that owner, so admission is held until the last +/// slice of the allocation is dropped, including a slice hyper still holds after +/// the body itself is gone. +fn envelope_body( + bytes: Vec, + permits: ServePermits, + deadline: std::time::Duration, +) -> axum::body::Body { + let end = tokio::time::Instant::now() + deadline; + let allocation = bytes::Bytes::from_owner(EnvelopeAllocation { + data: bytes, + _permits: permits, + }); + let frames = futures::stream::unfold(Some(allocation), move |state| async move { + let rest = state?; + if rest.is_empty() { + return None; + } + if tokio::time::Instant::now() >= end { + let late = std::io::Error::new( + std::io::ErrorKind::TimedOut, + "encrypted envelope send deadline passed", + ); + return Some((Err(late), None)); + } + let n = rest.len().min(SERVE_CHUNK_BYTES); + let chunk = rest.slice(..n); + Some((Ok(chunk), Some(rest.slice(n..)))) + }); + axum::body::Body::from_stream(frames) +} + /// GET /api/v1/repos/{owner}/{repo}/encrypted-blobs /// Returns [{oid, cid}] for every encrypted blob in the repo, to any caller who /// can read the repo. Not recipient-scoped: recipient identities are not stored, @@ -37,9 +122,12 @@ pub async fn list_encrypted_blobs( /// crypto still ensures only true recipients can decrypt. pub async fn get_encrypted_blob( State(state): State, + crate::rate_limit::PeerAddr(peer): crate::rate_limit::PeerAddr, + headers: axum::http::HeaderMap, auth: Option>, Path((owner, repo, oid)): Path<(String, String, String)>, -) -> Result> { +) -> Result { + let key = crate::rate_limit::client_key(&headers, peer, state.push_limiter_trust); let caller = auth.as_ref().map(|e| e.0 .0.as_str()); let (record, _rules) = crate::api::authorize_repo_read(&state, &owner, &repo, caller, "/").await?; @@ -48,10 +136,56 @@ pub async fn get_encrypted_blob( .encrypted_blob_cid(&record.id, &oid) .await? .ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{repo}/{oid}")))?; - let bytes = crate::ipfs_pin::cat(&state.config.ipfs_api, &cid) + // Admission is taken after the read gate, so a denied caller never holds a + // slot, and before Kubo, so a full pool sheds without buying a read. A shed + // is retried by clients, so it also refunds the route brake the middleware + // already spent; denials and upstream failures stay debited. + let global = match state.encrypted_serve_semaphore.clone().try_acquire_owned() { + Ok(permit) => permit, + Err(_) => { + tracing::warn!("encrypted-blob serve cap reached; shedding request with 503"); + if let Some(key) = key.as_deref() { + state.encrypted_blob_rate_limiter.refund(key).await; + } + return Err(AppError::Overloaded( + "encrypted blob service at capacity, retry shortly".into(), + )); + } + }; + let per_source = match key.as_deref() { + Some(ip) => match state.encrypted_serve_per_caller.try_acquire(ip) { + Some(permit) => Some(permit), + None => { + tracing::warn!(key = %ip, "encrypted-blob per-source serve cap reached; shedding request with 503"); + state.encrypted_blob_rate_limiter.refund(ip).await; + return Err(AppError::Overloaded( + "encrypted blob service at capacity for this source, retry shortly".into(), + )); + } + }, + None => None, + }; + // Opaque on purpose: the error text names the node's Kubo endpoint and the + // upstream status, neither of which an anonymous caller should see. + let bytes = crate::ipfs_pin::cat(&state.config.ipfs_api, &cid, MAX_SERVED_ENVELOPE_BYTES) .await - .map_err(|e| AppError::Git(e.to_string()))?; - Ok(bytes) + .map_err(|e| AppError::Internal(e.context("fetching encrypted envelope from IPFS")))?; + let len = bytes.len(); + let mut response = axum::response::Response::new(envelope_body( + bytes, + ServePermits { + _global: global, + _per_source: per_source, + }, + ENCRYPTED_SERVE_SEND_DEADLINE, + )); + let headers = response.headers_mut(); + headers.insert(axum::http::header::CONTENT_LENGTH, len.into()); + headers.insert( + axum::http::header::CONTENT_TYPE, + axum::http::HeaderValue::from_static("application/octet-stream"), + ); + Ok(response) } /// GET /api/v1/repos/{owner}/{repo}/encrypted-blobs/replicate @@ -87,7 +221,617 @@ fn replicate_blob_json(oid: String, cid: String) -> serde_json::Value { #[cfg(test)] mod tests { - use super::replicate_blob_json; + use super::{replicate_blob_json, MAX_SERVED_ENVELOPE_BYTES}; + + use axum::body::Body; + use axum::http::{Request, StatusCode}; + use tower::ServiceExt; + + const OWNER: &str = "did:key:zENCSERVEOWNERAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + const OID: &str = "deadbeef"; + + /// A public repo with one encrypted blob recorded, served through a node whose + /// Kubo is the given mock URL. Returns the state and the serve path. + async fn serving_state( + pool: sqlx::PgPool, + ipfs_api: String, + is_public: bool, + ) -> (crate::state::AppState, String) { + let state = crate::test_support::test_state_with(pool, |cfg| cfg.ipfs_api = ipfs_api).await; + let now = chrono::Utc::now(); + let repo = crate::db::RepoRecord { + id: uuid::Uuid::new_v4().to_string(), + name: "enc-serve".to_string(), + owner_did: OWNER.to_string(), + description: None, + is_public, + default_branch: "main".to_string(), + created_at: now, + updated_at: now, + disk_path: "/tmp/enc-serve".to_string(), + forked_from: None, + machine_id: None, + }; + state.db.create_repo(&repo).await.unwrap(); + state + .db + .record_encrypted_blob(&repo.id, OID, "bafkreiservecid", "") + .await + .unwrap(); + let short = OWNER.split(':').next_back().unwrap(); + ( + state, + format!("/api/v1/repos/{short}/enc-serve/encrypted-blob/{OID}"), + ) + } + + fn get_from(path: &str, ip: &str) -> Request { + let mut request = Request::builder().uri(path).body(Body::empty()).unwrap(); + request.extensions_mut().insert(axum::extract::ConnectInfo( + format!("{ip}:5000") + .parse::() + .unwrap(), + )); + request + } + + async fn mock_cat(server: &mut mockito::Server, status: usize, body: Vec) -> mockito::Mock { + server + .mock("POST", mockito::Matcher::Regex(r"^/api/v0/cat".to_string())) + .with_status(status) + .with_body(body) + .create_async() + .await + } + + async fn body_of(resp: axum::response::Response) -> Vec { + axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap() + .to_vec() + } + + #[sqlx::test] + async fn serve_returns_the_envelope_bytes(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let _m = mock_cat(&mut kubo, 200, b"ENVELOPE-BYTES".to_vec()).await; + let (state, path) = serving_state(pool, kubo.url(), true).await; + let resp = crate::server::build_router(state) + .oneshot(get_from(&path, "203.0.113.1")) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + assert_eq!( + resp.headers() + .get(axum::http::header::CONTENT_TYPE) + .unwrap(), + "application/octet-stream", + "the envelope is served as raw bytes, as before" + ); + assert_eq!(body_of(resp).await, b"ENVELOPE-BYTES"); + } + + /// Over the ceiling is a server-side failure, opaque to the caller: no + /// envelope bytes and no trace of where the node's Kubo lives. + #[sqlx::test] + async fn serve_refuses_an_oversized_envelope_opaquely(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let _m = mock_cat(&mut kubo, 200, vec![b'Z'; MAX_SERVED_ENVELOPE_BYTES + 1]).await; + let (state, path) = serving_state(pool, kubo.url(), true).await; + let resp = crate::server::build_router(state) + .oneshot(get_from(&path, "203.0.113.1")) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); + let text = String::from_utf8_lossy(&body_of(resp).await).to_string(); + assert!( + !text.contains("ZZZZ"), + "no envelope bytes in the error body" + ); + assert!( + !text.contains(&kubo.host_with_port()), + "Kubo address leaked: {text}" + ); + assert!(!text.contains("ceiling"), "upstream detail leaked: {text}"); + } + + #[sqlx::test] + async fn serve_hides_a_kubo_failure(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let _m = mock_cat(&mut kubo, 500, b"kubo internal detail".to_vec()).await; + let (state, path) = serving_state(pool, kubo.url(), true).await; + let resp = crate::server::build_router(state) + .oneshot(get_from(&path, "203.0.113.1")) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); + let text = String::from_utf8_lossy(&body_of(resp).await).to_string(); + assert!( + !text.contains(&kubo.host_with_port()), + "Kubo address leaked: {text}" + ); + assert!(!text.contains("500"), "upstream status leaked: {text}"); + } + + /// With every global slot taken the serve sheds before touching Kubo. + #[sqlx::test] + async fn serve_sheds_when_the_global_pool_is_full(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let m = mock_cat(&mut kubo, 200, b"E".to_vec()).await.expect(0); + let (state, path) = serving_state(pool, kubo.url(), true).await; + let _held = state + .encrypted_serve_semaphore + .clone() + .acquire_many_owned(super::MAX_CONCURRENT_ENCRYPTED_SERVES as u32) + .await + .unwrap(); + let resp = crate::server::build_router(state) + .oneshot(get_from(&path, "203.0.113.1")) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE); + m.assert_async().await; + } + + /// One client IP holds one serve at a time, and the slot is held for as long + /// as its response body is unread; another IP is still served. + #[sqlx::test] + async fn serve_caps_one_source_while_its_body_is_unread(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let _m = mock_cat(&mut kubo, 200, b"E".to_vec()).await; + let (state, path) = serving_state(pool, kubo.url(), true).await; + let router = crate::server::build_router(state); + let first = router + .clone() + .oneshot(get_from(&path, "203.0.113.1")) + .await + .unwrap(); + assert_eq!(first.status(), StatusCode::OK); + let same = router + .clone() + .oneshot(get_from(&path, "203.0.113.1")) + .await + .unwrap(); + assert_eq!(same.status(), StatusCode::SERVICE_UNAVAILABLE); + let other = router + .clone() + .oneshot(get_from(&path, "203.0.113.2")) + .await + .unwrap(); + assert_eq!(other.status(), StatusCode::OK); + drop(first); + let again = router + .oneshot(get_from(&path, "203.0.113.1")) + .await + .unwrap(); + assert_eq!(again.status(), StatusCode::OK); + } + + /// The global slot outlives the handler: an unread body still counts, and + /// dropping it frees the slot. + #[sqlx::test] + async fn serve_counts_an_unread_body_against_the_global_pool(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let _m = mock_cat(&mut kubo, 200, b"E".to_vec()).await; + let (state, path) = serving_state(pool, kubo.url(), true).await; + let _held = state + .encrypted_serve_semaphore + .clone() + .acquire_many_owned(super::MAX_CONCURRENT_ENCRYPTED_SERVES as u32 - 1) + .await + .unwrap(); + let router = crate::server::build_router(state); + let first = router + .clone() + .oneshot(get_from(&path, "203.0.113.1")) + .await + .unwrap(); + assert_eq!(first.status(), StatusCode::OK); + let blocked = router + .clone() + .oneshot(get_from(&path, "203.0.113.2")) + .await + .unwrap(); + assert_eq!(blocked.status(), StatusCode::SERVICE_UNAVAILABLE); + drop(first); + let freed = router + .oneshot(get_from(&path, "203.0.113.2")) + .await + .unwrap(); + assert_eq!(freed.status(), StatusCode::OK); + } + + /// A serve shed because the global pool is full is retried by clients, so + /// it must hand its brake slot back rather than letting one withheld blob + /// spend the whole allowance without serving bytes. + #[sqlx::test] + async fn a_global_shed_does_not_spend_the_brake(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let _m = mock_cat(&mut kubo, 200, b"E".to_vec()).await; + let (mut state, path) = serving_state(pool, kubo.url(), true).await; + state.encrypted_blob_rate_limiter = + crate::rate_limit::RateLimiter::new_bounded(2, std::time::Duration::from_secs(60), 10); + let held = state + .encrypted_serve_semaphore + .clone() + .acquire_many_owned(super::MAX_CONCURRENT_ENCRYPTED_SERVES as u32) + .await + .unwrap(); + let router = crate::server::build_router(state); + for _ in 0..5 { + let resp = router + .clone() + .oneshot(get_from(&path, "203.0.113.20")) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE); + } + drop(held); + let resp = router + .oneshot(get_from(&path, "203.0.113.20")) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + } + + /// A per-source shed is a retryable refusal too: it must not debit the + /// source's request brake while its first response is still unread. + #[sqlx::test] + async fn a_per_source_shed_does_not_spend_the_brake(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let _m = mock_cat(&mut kubo, 200, b"E".to_vec()).await; + let (mut state, path) = serving_state(pool, kubo.url(), true).await; + state.encrypted_blob_rate_limiter = + crate::rate_limit::RateLimiter::new_bounded(2, std::time::Duration::from_secs(60), 10); + let router = crate::server::build_router(state); + let first = router + .clone() + .oneshot(get_from(&path, "203.0.113.21")) + .await + .unwrap(); + assert_eq!(first.status(), StatusCode::OK); + for _ in 0..5 { + let resp = router + .clone() + .oneshot(get_from(&path, "203.0.113.21")) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE); + } + drop(first); + let resp = router + .oneshot(get_from(&path, "203.0.113.21")) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + } + + /// Denied lookups and upstream failures really cost the caller: refunding + /// them would let existence probing or Kubo pressure escape the brake. + #[sqlx::test] + async fn denials_and_kubo_failures_stay_braked(pool: sqlx::PgPool) { + let kubo = mockito::Server::new_async().await; + let (mut state, path) = serving_state(pool, kubo.url(), true).await; + state.encrypted_blob_rate_limiter = + crate::rate_limit::RateLimiter::new_bounded(2, std::time::Duration::from_secs(60), 10); + let missing_path = path.replace(OID, "missingoid"); + let router = crate::server::build_router(state.clone()); + for (attempt, expected) in [ + StatusCode::NOT_FOUND, + StatusCode::NOT_FOUND, + StatusCode::TOO_MANY_REQUESTS, + ] + .into_iter() + .enumerate() + { + let resp = router + .clone() + .oneshot(get_from(&missing_path, "203.0.113.22")) + .await + .unwrap(); + assert_eq!(resp.status(), expected, "missing oid attempt {attempt}"); + } + + let mut kubo = mockito::Server::new_async().await; + let _m = mock_cat(&mut kubo, 500, b"kubo internal detail".to_vec()).await; + let mut config = (*state.config).clone(); + config.ipfs_api = kubo.url(); + state.config = std::sync::Arc::new(config); + state.encrypted_blob_rate_limiter = + crate::rate_limit::RateLimiter::new_bounded(2, std::time::Duration::from_secs(60), 10); + let router = crate::server::build_router(state); + for (attempt, expected) in [ + StatusCode::INTERNAL_SERVER_ERROR, + StatusCode::INTERNAL_SERVER_ERROR, + StatusCode::TOO_MANY_REQUESTS, + ] + .into_iter() + .enumerate() + { + let resp = router + .clone() + .oneshot(get_from(&path, "203.0.113.22")) + .await + .unwrap(); + assert_eq!(resp.status(), expected, "Kubo failure attempt {attempt}"); + } + } + + /// A frame hyper has already buffered must keep counting its envelope + /// allocation against admission even when the body object itself is gone. + #[tokio::test] + async fn an_emitted_frame_keeps_the_admission_after_the_body_is_dropped() { + use http_body_util::BodyExt; + let pool = std::sync::Arc::new(tokio::sync::Semaphore::new(1)); + let permit = pool.clone().try_acquire_owned().unwrap(); + let permits = super::ServePermits { + _global: permit, + _per_source: None, + }; + let mut body = super::envelope_body( + vec![1u8; 3 * super::SERVE_CHUNK_BYTES], + permits, + std::time::Duration::from_secs(60), + ); + let first = body.frame().await.unwrap().unwrap(); + assert!(first.is_data()); + drop(body); + assert_eq!( + pool.available_permits(), + 0, + "a live frame still retains the envelope allocation" + ); + drop(first); + assert_eq!(pool.available_permits(), 1); + } + + /// Once every frame is read and dropped, the allocation owner is gone and + /// the admission is free again. + #[tokio::test] + async fn a_fully_read_body_frees_its_admission() { + use http_body_util::BodyExt; + let pool = std::sync::Arc::new(tokio::sync::Semaphore::new(1)); + let permit = pool.clone().try_acquire_owned().unwrap(); + let permits = super::ServePermits { + _global: permit, + _per_source: None, + }; + let body = super::envelope_body( + vec![1u8; 3 * super::SERVE_CHUNK_BYTES], + permits, + std::time::Duration::from_secs(60), + ); + let collected = body.collect().await.unwrap(); + drop(collected); + assert_eq!(pool.available_permits(), 1); + } + + /// A body still being read past its send deadline ends in an error and gives + /// its slot back. + #[tokio::test] + async fn a_body_past_its_send_deadline_errors_and_frees_its_slot() { + use http_body_util::BodyExt; + let pool = std::sync::Arc::new(tokio::sync::Semaphore::new(1)); + let permit = pool.clone().try_acquire_owned().unwrap(); + let permits = super::ServePermits { + _global: permit, + _per_source: None, + }; + let mut body = super::envelope_body( + vec![1u8; 3 * super::SERVE_CHUNK_BYTES], + permits, + std::time::Duration::from_millis(50), + ); + let first = body.frame().await.unwrap().unwrap(); + assert!(first.is_data()); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + assert!( + body.frame().await.unwrap().is_err(), + "past the deadline the body must error" + ); + drop(first); + assert_eq!( + pool.available_permits(), + 1, + "the slot must be free once the body errored" + ); + } + + /// A signature header makes the signature middleware collect the request + /// before rejecting it, so the serve brake must debit first: the first bad + /// signature reaches verification, and the second is stopped by the brake. + #[sqlx::test] + async fn serve_brake_runs_before_signature_verification(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let _m = mock_cat(&mut kubo, 200, b"E".to_vec()).await.expect(0); + let (mut state, path) = serving_state(pool, kubo.url(), true).await; + state.encrypted_blob_rate_limiter = + crate::rate_limit::RateLimiter::new_bounded(1, std::time::Duration::from_secs(60), 10); + let router = crate::server::build_router(state); + + let mut first = get_from(&path, "203.0.113.10"); + first + .headers_mut() + .insert("signature-input", axum::http::HeaderValue::from_static("x")); + first + .headers_mut() + .insert("signature", axum::http::HeaderValue::from_static("y")); + let first = router.clone().oneshot(first).await.unwrap(); + assert_eq!(first.status(), StatusCode::BAD_REQUEST); + + let mut second = get_from(&path, "203.0.113.10"); + second + .headers_mut() + .insert("signature-input", axum::http::HeaderValue::from_static("x")); + second + .headers_mut() + .insert("signature", axum::http::HeaderValue::from_static("y")); + let second = router.oneshot(second).await.unwrap(); + assert_eq!(second.status(), StatusCode::TOO_MANY_REQUESTS); + } + + /// A real RFC-9421 GET signature still passes the optional signature layer + /// and reaches the serve handler. + #[sqlx::test] + async fn signed_get_reaches_the_serve_handler(pool: sqlx::PgPool) { + use twigpine_core::http_sig::sign_request; + use twigpine_core::identity::Keypair; + + let mut kubo = mockito::Server::new_async().await; + let _m = mock_cat(&mut kubo, 200, b"ENVELOPE-BYTES".to_vec()).await; + let (state, path) = serving_state(pool, kubo.url(), true).await; + let signed = sign_request(&Keypair::generate(), "GET", &path, b""); + let mut request = get_from(&path, "203.0.113.11"); + request.headers_mut().insert( + "content-digest", + axum::http::HeaderValue::from_str(&signed.content_digest).unwrap(), + ); + request.headers_mut().insert( + "signature-input", + axum::http::HeaderValue::from_str(&signed.signature_input).unwrap(), + ); + request.headers_mut().insert( + "signature", + axum::http::HeaderValue::from_str(&signed.signature).unwrap(), + ); + let resp = crate::server::build_router(state) + .oneshot(request) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + assert_eq!(body_of(resp).await, b"ENVELOPE-BYTES"); + } + + /// The serve route has its own per-IP brake. + #[sqlx::test] + async fn serve_route_brakes_a_repeating_client(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let _m = mock_cat(&mut kubo, 200, b"E".to_vec()).await; + let (mut state, path) = serving_state(pool, kubo.url(), true).await; + state.encrypted_blob_rate_limiter = + crate::rate_limit::RateLimiter::new_bounded(1, std::time::Duration::from_secs(60), 10); + let router = crate::server::build_router(state); + let first = router + .clone() + .oneshot(get_from(&path, "203.0.113.9")) + .await + .unwrap(); + assert_eq!(first.status(), StatusCode::OK); + drop(first); + let second = router + .oneshot(get_from(&path, "203.0.113.9")) + .await + .unwrap(); + assert_eq!(second.status(), StatusCode::TOO_MANY_REQUESTS); + } + + /// The brake stays on its one route: a client it has stopped can still + /// fetch, and `/ipfs/{cid}` traffic does not spend this route's allowance. + #[sqlx::test] + async fn serve_route_brake_is_its_own_bucket(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let _m = mock_cat(&mut kubo, 200, b"E".to_vec()).await; + let (mut state, path) = serving_state(pool, kubo.url(), true).await; + state.encrypted_blob_rate_limiter = + crate::rate_limit::RateLimiter::new_bounded(1, std::time::Duration::from_secs(60), 10); + state.ipfs_rate_limiter = + crate::rate_limit::RateLimiter::new_bounded(1, std::time::Duration::from_secs(60), 10); + let router = crate::server::build_router(state); + let short = OWNER.split(':').next_back().unwrap(); + + // Spend the /ipfs bucket for one IP; the serve route still admits it. + let cid = "/ipfs/bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku"; + let _ = router + .clone() + .oneshot(get_from(cid, "203.0.113.7")) + .await + .unwrap(); + let ipfs_again = router + .clone() + .oneshot(get_from(cid, "203.0.113.7")) + .await + .unwrap(); + assert_eq!( + ipfs_again.status(), + StatusCode::TOO_MANY_REQUESTS, + "the /ipfs bucket is spent" + ); + let served = router + .clone() + .oneshot(get_from(&path, "203.0.113.7")) + .await + .unwrap(); + assert_eq!( + served.status(), + StatusCode::OK, + "/ipfs traffic must not brake the serve route" + ); + drop(served); + + // Now the serve bucket is spent for that IP; clone and fetch are not braked. + let braked = router + .clone() + .oneshot(get_from(&path, "203.0.113.7")) + .await + .unwrap(); + assert_eq!(braked.status(), StatusCode::TOO_MANY_REQUESTS); + let refs = format!("/{short}/enc-serve/info/refs?service=git-upload-pack"); + let info = router + .oneshot(get_from(&refs, "203.0.113.7")) + .await + .unwrap(); + assert_ne!( + info.status(), + StatusCode::TOO_MANY_REQUESTS, + "info/refs must not share the brake" + ); + } + + /// The periodic sweep evicts expired entries from the serve route's limiter. + #[tokio::test] + async fn cleanup_sweeps_the_serve_route_limiter() { + let mut state = crate::test_support::test_state_lazy(); + state.encrypted_blob_rate_limiter = + crate::rate_limit::RateLimiter::new(5, std::time::Duration::from_millis(50)); + assert!(state.encrypted_blob_rate_limiter.check("1.2.3.4").await); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + state.cleanup_rate_limiters().await; + assert_eq!(state.encrypted_blob_rate_limiter.tracked_keys().await, 0); + } + + /// An unreadable repo denies before any Kubo call. + #[sqlx::test] + async fn serve_denies_a_private_repo_before_calling_kubo(pool: sqlx::PgPool) { + let mut kubo = mockito::Server::new_async().await; + let m = mock_cat(&mut kubo, 200, b"E".to_vec()).await.expect(0); + let (state, path) = serving_state(pool, kubo.url(), false).await; + let resp = crate::server::build_router(state) + .oneshot(get_from(&path, "203.0.113.1")) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::NOT_FOUND); + m.assert_async().await; + } + + /// The largest plaintext the node will seal, sealed to the most recipients + /// an envelope may carry, must still fit under the read ceiling, or a + /// legitimately sealed blob would be refused on the way back out. + #[test] + fn a_full_size_envelope_at_the_recipient_cap_fits_the_ceiling() { + use twigpine_core::encrypt::{seal_blob, MAX_RECIPIENTS}; + use twigpine_core::identity::Keypair; + let keys: Vec<_> = (0..MAX_RECIPIENTS) + .map(|_| Keypair::generate().verifying_key()) + .collect(); + let plaintext = vec![7u8; crate::api::ipfs::MAX_SERVED_OBJECT_BYTES as usize]; + let envelope = seal_blob(&plaintext, &keys).unwrap(); + assert!( + envelope.len() <= MAX_SERVED_ENVELOPE_BYTES, + "envelope of {} bytes exceeds the {} byte ceiling", + envelope.len(), + MAX_SERVED_ENVELOPE_BYTES + ); + } #[test] fn replicate_blob_json_omits_recipients() { diff --git a/crates/twigpine-node/src/auth/mod.rs b/crates/twigpine-node/src/auth/mod.rs index b02efbd0d..58df2550b 100644 --- a/crates/twigpine-node/src/auth/mod.rs +++ b/crates/twigpine-node/src/auth/mod.rs @@ -1302,6 +1302,18 @@ mod tests { git_ipfs_walk_per_caller: crate::rate_limit::PerCallerConcurrency::with_default_max_keys(16), task_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)), + encrypted_serve_semaphore: Arc::new(tokio::sync::Semaphore::new( + crate::api::encrypted::MAX_CONCURRENT_ENCRYPTED_SERVES, + )), + encrypted_serve_per_caller: + crate::rate_limit::PerCallerConcurrency::with_default_max_keys( + crate::api::encrypted::ENCRYPTED_SERVES_PER_SOURCE, + ), + encrypted_blob_rate_limiter: crate::rate_limit::RateLimiter::new_bounded( + crate::api::encrypted::ENCRYPTED_BLOB_RATE_PER_MINUTE, + std::time::Duration::from_secs(60), + 200_000, + ), hf_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)), git_bin: "git".to_string(), block_store: None, diff --git a/crates/twigpine-node/src/encrypted_pin.rs b/crates/twigpine-node/src/encrypted_pin.rs index 5749fee5a..bf371d230 100644 --- a/crates/twigpine-node/src/encrypted_pin.rs +++ b/crates/twigpine-node/src/encrypted_pin.rs @@ -233,6 +233,24 @@ pub async fn encrypt_and_pin( } SealPlan::Seal { keys, tag } => (keys, tag), }; + // An envelope the serve route would refuse must not be published, so a + // blob over the served-object ceiling is left withheld with no recovery + // copy. + match object_size_bounded_spawn_blocking(git_bin, repo_path, oid, read_deadline).await { + Ok(size) if size > crate::api::ipfs::MAX_SERVED_OBJECT_BYTES => { + tracing::warn!( + oid = %oid, + size, + "withheld blob exceeds the served-object ceiling; skipping encrypted pin" + ); + continue; + } + Ok(_) => {} + Err(e) => { + tracing::warn!(oid = %oid, err = %e, "object size probe failed; skipping encrypted pin"); + continue; + } + } let data = match read_object_bounded_spawn_blocking(git_bin, repo_path, oid, read_deadline) .await { @@ -300,6 +318,25 @@ pub async fn encrypt_and_pin( sealed } +/// Object size probe for the seal loop, under the same off-thread, reaped, +/// shared-deadline rules as the object read below. +async fn object_size_bounded_spawn_blocking( + git_bin: &str, + repo_path: &Path, + sha256_hex: &str, + deadline: std::time::Instant, +) -> anyhow::Result { + let git_bin = git_bin.to_string(); + let repo_path = repo_path.to_path_buf(); + let sha256_hex = sha256_hex.to_string(); + tokio::task::spawn_blocking(move || { + crate::git::store::object_size_bounded(&git_bin, &repo_path, &sha256_hex, deadline) + .map_err(anyhow::Error::from) + }) + .await + .map_err(|e| anyhow::anyhow!("object size spawn_blocking join failed: {e}"))? +} + /// Bounded, reaped git object read for the seal loop, run off the async thread: /// `read_object_bounded` is synchronous child spawn + pipe drain + watchdog /// join, so blocking the runtime task on it would let a hung git hold a worker @@ -695,6 +732,66 @@ mod tests { ); } + /// A withheld blob too large to be served back is not sealed at all, so no + /// public envelope exists that the serve would refuse; a small blob in the + /// same pass still seals. + #[sqlx::test] + async fn encrypt_and_pin_skips_a_blob_over_the_served_ceiling(pool: sqlx::PgPool) { + let db = crate::db::Db::for_testing(pool); + db.run_migrations().await.expect("migrations"); + let tmp = tempfile::TempDir::new().unwrap(); + let repo_path = tmp.path().join("seal-ceiling.git"); + crate::git::store::init_bare(&repo_path).expect("init bare repo"); + let hash = |content: &[u8]| -> String { + use std::io::Write; + let mut child = std::process::Command::new("git") + .args(["hash-object", "-w", "--stdin"]) + .current_dir(&repo_path) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .expect("spawn git hash-object"); + child + .stdin + .take() + .expect("stdin") + .write_all(content) + .expect("write"); + let out = child.wait_with_output().expect("hash-object output"); + assert!(out.status.success()); + String::from_utf8_lossy(&out.stdout).trim().to_string() + }; + let big = vec![b'x'; crate::api::ipfs::MAX_SERVED_OBJECT_BYTES as usize + 1]; + let big_oid = hash(&big); + let small_oid = hash(b"small secret\n"); + + let reader = did_key(1); + let recipients: HashMap> = [big_oid.clone(), small_oid.clone()] + .into_iter() + .map(|oid| (oid, BTreeSet::from([reader.clone()]))) + .collect(); + let endpoint = delaying_cid_endpoint(vec![Duration::ZERO]).await; + + let sealed = encrypt_and_pin( + &endpoint, + &repo_path, + &db, + &uuid::Uuid::new_v4().to_string(), + &SEED, + "git", + Duration::from_secs(60), + &recipients, + None, + ) + .await; + let sealed_oids: Vec<&str> = sealed.iter().map(|(oid, _)| oid.as_str()).collect(); + assert_eq!( + sealed_oids, + vec![small_oid.as_str()], + "only the servable blob may be sealed" + ); + } + /// A hung git must not hold the seal loop past its read budget (R1-P2): the /// git read runs under `spawn_blocking` against `read_object_bounded`, so /// the watchdog reaps a wedged child at the batch deadline and the loop diff --git a/crates/twigpine-node/src/ipfs_pin.rs b/crates/twigpine-node/src/ipfs_pin.rs index 16614e94e..af9a98fd1 100644 --- a/crates/twigpine-node/src/ipfs_pin.rs +++ b/crates/twigpine-node/src/ipfs_pin.rs @@ -1707,17 +1707,47 @@ pub async fn pin_git_object( Ok(cid) } -/// Fetch raw bytes for a CID from the local Kubo node (`/api/v0/cat`). -pub async fn cat(ipfs_api: &str, cid: &str) -> Result> { +/// Fetch raw bytes for a CID from the local Kubo node (`/api/v0/cat`), +/// refusing a body larger than `max_bytes`. +pub async fn cat(ipfs_api: &str, cid: &str, max_bytes: usize) -> Result> { if ipfs_api.is_empty() { return Err(anyhow::anyhow!("IPFS not configured")); } let url = format!("{}/api/v0/cat?arg={}", ipfs_api.trim_end_matches('/'), cid); - let resp = http_client().post(&url).send().await?; + let mut resp = http_client().post(&url).send().await?; if !resp.status().is_success() { return Err(anyhow::anyhow!("ipfs cat {cid}: {}", resp.status())); } - Ok(resp.bytes().await?.to_vec()) + // The declared length only lets an honest oversize fail early; the running + // count below is the bound, since Kubo may stream with no length at all. + let declared = resp.content_length(); + if declared.is_some_and(|len| len > max_bytes as u64) { + return Err(anyhow::anyhow!( + "ipfs cat {cid}: body exceeds the {max_bytes} byte ceiling" + )); + } + let capacity = declared + .and_then(|len| usize::try_from(len).ok()) + .unwrap_or(0) + .min(max_bytes); + let mut body = Vec::with_capacity(capacity); + while let Some(chunk) = resp.chunk().await? { + if body.len().saturating_add(chunk.len()) > max_bytes { + return Err(anyhow::anyhow!( + "ipfs cat {cid}: body exceeds the {max_bytes} byte ceiling" + )); + } + // Grow geometrically but never past the ceiling, so the buffer the + // caller keeps holds at most `max_bytes` of capacity, not the next + // power of two above it. + let needed = body.len() + chunk.len(); + if needed > body.capacity() { + let target = body.capacity().saturating_mul(2).max(needed).min(max_bytes); + body.reserve_exact(target.saturating_sub(body.len())); + } + body.extend_from_slice(&chunk); + } + Ok(body) } /// The batch's remaining wall-clock, or `None` once too little is left to be worth @@ -2694,7 +2724,7 @@ mod tests { #[tokio::test] async fn cat_against_silent_endpoint_errors_within_its_own_timeout() { let endpoint = crate::test_support::silent_http_endpoint().await; - let inner = tokio::time::timeout(Duration::from_secs(30), cat(&endpoint, "bafkqaaa")) + let inner = tokio::time::timeout(Duration::from_secs(30), cat(&endpoint, "bafkqaaa", 1024)) .await .expect( "cat must return before the outer 30s timeout — an unbounded client hangs here", @@ -2743,6 +2773,134 @@ mod tests { ); } + /// #471: `cat` backs the anonymous encrypted-blob serve and the sync + /// replicate loop, and both buffer what it returns. A body past the served + /// object ceiling must be refused, not read into memory whole. + #[tokio::test] + async fn cat_refuses_a_body_over_the_served_ceiling() { + let ceiling = crate::api::encrypted::MAX_SERVED_ENVELOPE_BYTES; + let oversized = vec![0u8; ceiling + 2 * 1024 * 1024]; + let mut server = mockito::Server::new_async().await; + let _m = server + .mock("POST", mockito::Matcher::Regex(r"^/api/v0/cat".to_string())) + .with_status(200) + .with_body(oversized) + .create_async() + .await; + let result = cat(&server.url(), "bafkreiaaaa", ceiling).await; + assert!( + result.is_err(), + "cat must refuse a body over the served ceiling, got {} bytes", + result.map(|b| b.len()).unwrap_or(0) + ); + } + + /// Kubo may stream `cat` with no Content-Length, so the byte count read so + /// far is the bound that has to hold, not the header. + #[tokio::test] + async fn cat_refuses_a_chunked_body_over_the_ceiling() { + let mut server = mockito::Server::new_async().await; + let _m = server + .mock("POST", mockito::Matcher::Regex(r"^/api/v0/cat".to_string())) + .with_status(200) + .with_chunked_body(|w| { + let chunk = [1u8; 4096]; + for _ in 0..64 { + w.write_all(&chunk)?; + } + Ok(()) + }) + .create_async() + .await; + let result = cat(&server.url(), "bafkreiaaaa", 64 * 1024).await; + assert!( + result.is_err(), + "a chunked body past the ceiling must be refused, got {} bytes", + result.map(|b| b.len()).unwrap_or(0) + ); + } + + /// A declared length over the ceiling is refused before any body is read: + /// this endpoint announces a huge body and then sends nothing, so only the + /// header check can answer before the client's own timeout. + #[tokio::test] + async fn cat_refuses_a_declared_oversize_before_reading_the_body() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + let mut held = Vec::new(); + while let Ok((mut sock, _)) = listener.accept().await { + let mut buf = [0u8; 4096]; + let _ = sock.read(&mut buf).await; + let _ = sock + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 999999999\r\n\r\n") + .await; + held.push(sock); + } + }); + let result = tokio::time::timeout( + Duration::from_secs(2), + cat(&endpoint, "bafkreiaaaa", 64 * 1024), + ) + .await + .expect("an over-ceiling Content-Length must be refused without waiting on the body"); + assert!(result.is_err(), "a declared oversize must be refused"); + } + + /// With no declared length the buffer grows as chunks arrive. Its capacity + /// must stay within the ceiling too, or a body just past a power of two + /// holds nearly twice the bytes the ceiling promises. + #[tokio::test] + async fn cat_keeps_a_chunked_buffer_within_the_ceiling() { + let max_bytes = 1_100_000; + let mut server = mockito::Server::new_async().await; + let _m = server + .mock("POST", mockito::Matcher::Regex(r"^/api/v0/cat".to_string())) + .with_status(200) + .with_chunked_body(|w| { + for _ in 0..105 { + w.write_all(&[3u8; 10_000])?; + } + Ok(()) + }) + .create_async() + .await; + let bytes = cat(&server.url(), "bafkreiaaaa", max_bytes).await.unwrap(); + assert_eq!(bytes.len(), 1_050_000); + assert!( + bytes.capacity() <= max_bytes, + "buffer capacity {} exceeds the {max_bytes} byte ceiling", + bytes.capacity() + ); + } + + /// The ceiling is inclusive: a body of exactly `max_bytes` is returned whole. + #[tokio::test] + async fn cat_returns_a_body_exactly_at_the_ceiling() { + let mut server = mockito::Server::new_async().await; + let _m = server + .mock("POST", mockito::Matcher::Regex(r"^/api/v0/cat".to_string())) + .with_status(200) + .with_body(vec![9u8; 4096]) + .create_async() + .await; + let bytes = cat(&server.url(), "bafkreiaaaa", 4096).await.unwrap(); + assert_eq!(bytes, vec![9u8; 4096]); + } + + #[tokio::test] + async fn cat_reports_a_kubo_error_status() { + let mut server = mockito::Server::new_async().await; + let _m = server + .mock("POST", mockito::Matcher::Regex(r"^/api/v0/cat".to_string())) + .with_status(500) + .with_body("boom") + .create_async() + .await; + assert!(cat(&server.url(), "bafkreiaaaa", 4096).await.is_err()); + } + /// The Hash text goes into the error and `encrypted_pin` logs that error, /// so a backend answering with a huge invalid Hash must not produce an /// unbounded log entry. diff --git a/crates/twigpine-node/src/lib.rs b/crates/twigpine-node/src/lib.rs index 4b1a05ea4..34ec068b2 100644 --- a/crates/twigpine-node/src/lib.rs +++ b/crates/twigpine-node/src/lib.rs @@ -638,6 +638,17 @@ pub async fn run() -> Result<()> { std::time::Duration::from_secs(3600), 200_000, ), + encrypted_serve_semaphore: Arc::new(tokio::sync::Semaphore::new( + crate::api::encrypted::MAX_CONCURRENT_ENCRYPTED_SERVES, + )), + encrypted_serve_per_caller: crate::rate_limit::PerCallerConcurrency::with_default_max_keys( + crate::api::encrypted::ENCRYPTED_SERVES_PER_SOURCE, + ), + encrypted_blob_rate_limiter: crate::rate_limit::RateLimiter::new_bounded( + crate::api::encrypted::ENCRYPTED_BLOB_RATE_PER_MINUTE, + std::time::Duration::from_secs(60), + 200_000, + ), hf_read_rate_limiter: rate_limit::RateLimiter::new_bounded( config.hf_read_rate_limit, std::time::Duration::from_secs(3600), diff --git a/crates/twigpine-node/src/server.rs b/crates/twigpine-node/src/server.rs index 01318b6e9..bb8de3c2f 100644 --- a/crates/twigpine-node/src/server.rs +++ b/crates/twigpine-node/src/server.rs @@ -752,10 +752,6 @@ pub fn build_router(state: AppState) -> Router { "/api/v1/repos/{owner}/{repo}/encrypted-blobs", axum::routing::get(crate::api::encrypted::list_encrypted_blobs), ) - .route( - "/api/v1/repos/{owner}/{repo}/encrypted-blob/{oid}", - axum::routing::get(crate::api::encrypted::get_encrypted_blob), - ) .route( "/api/v1/repos/{owner}/{repo}/encrypted-blobs/replicate", axum::routing::get(crate::api::encrypted::replicate_encrypted_blobs), @@ -770,6 +766,28 @@ pub fn build_router(state: AppState) -> Router { auth::optional_signature, )); + // Encrypted-blob serving is braked on this route alone; see + // `AppState::encrypted_blob_rate_limiter`. The limiter is the outermost + // layer so a flood is rejected before signature verification buffers the + // request, and the extension MUST be attached or `rate_limit_by_ip` is a + // silent no-op. A GET carries no body, so this router uses the standard + // signed-body bound rather than the git pack ceiling. + let encrypted_blob_limiter = rate_limit::IpRateLimiter { + limiter: state.encrypted_blob_rate_limiter.clone(), + trust: state.push_limiter_trust, + }; + let encrypted_blob_serve_routes = Router::new() + .route( + "/api/v1/repos/{owner}/{repo}/encrypted-blob/{oid}", + axum::routing::get(crate::api::encrypted::get_encrypted_blob), + ) + .layer(middleware::from_fn_with_state( + auth::SignatureBodyLimit(SIGNED_BODY_LIMIT), + auth::optional_signature, + )) + .layer(middleware::from_fn(rate_limit::rate_limit_by_ip)) + .layer(axum::Extension(encrypted_blob_limiter)); + // ── Model hosting routes ───────────────────────────────────────────── // Mounted only when the operator enabled the feature (`block_store` is // the flag's live form). Three surfaces with three different auth @@ -889,6 +907,7 @@ pub fn build_router(state: AppState) -> Router { .merge(status_read_routes) .merge(git_write_routes) .merge(git_read_routes) + .merge(encrypted_blob_serve_routes) .merge(issue_write_routes) .merge(read_routes) .merge(peer_read_routes) diff --git a/crates/twigpine-node/src/state.rs b/crates/twigpine-node/src/state.rs index d8c777ca1..e333683a2 100644 --- a/crates/twigpine-node/src/state.rs +++ b/crates/twigpine-node/src/state.rs @@ -386,6 +386,20 @@ pub struct AppState { /// client IP via `push_limiter_trust`; layered on the HF route group /// via `rate_limit_by_ip`. pub hf_read_rate_limiter: RateLimiter, + /// Bounds concurrent encrypted-blob serves node-wide. Each serve buffers an + /// envelope of up to `MAX_SERVED_ENVELOPE_BYTES`, and the permit lives in the + /// response body, so resident envelope memory from this route stays under + /// `MAX_CONCURRENT_ENCRYPTED_SERVES` times that ceiling for as long as any + /// response is still being sent. + pub encrypted_serve_semaphore: Arc, + /// Per-source share of `encrypted_serve_semaphore`, keyed on the resolved + /// client IP, so one source cannot hold every serve slot. A request with no + /// resolvable key is bounded by the global pool only. + pub encrypted_serve_per_caller: crate::rate_limit::PerCallerConcurrency, + /// Per-client-IP rate brake for the encrypted-blob serve, in a bucket of its + /// own: a clone fetches one envelope per withheld blob, so sharing the hourly + /// `/ipfs` bucket would cut a large clone off partway through. + pub encrypted_blob_rate_limiter: RateLimiter, /// The `git` executable the served-git withheld-blob walk spawns. Production is /// `"git"` (resolved via PATH); injectable so a fake `git` can drive the walk's /// process-group teardown in handler tests without mutating the process-global @@ -451,6 +465,7 @@ impl AppState { self.task_read_rate_limiter.cleanup().await; self.federated_rate_limiter.cleanup().await; self.hf_read_rate_limiter.cleanup().await; + self.encrypted_blob_rate_limiter.cleanup().await; } /// Legacy-probe budget wired from the `TWIGPINE_IPFS_MAX_LEGACY_PROBES` operator diff --git a/crates/twigpine-node/src/sync.rs b/crates/twigpine-node/src/sync.rs index 05ab09fcd..9ecf036ec 100644 --- a/crates/twigpine-node/src/sync.rs +++ b/crates/twigpine-node/src/sync.rs @@ -1252,7 +1252,13 @@ async fn replicate_encrypted_blobs( }; for blob in blobs_needing_replication(&parsed.blobs, &have) { - let envelope = match crate::ipfs_pin::cat(ipfs_api, &blob.cid).await { + let envelope = match crate::ipfs_pin::cat( + ipfs_api, + &blob.cid, + crate::api::encrypted::MAX_SERVED_ENVELOPE_BYTES, + ) + .await + { Ok(bytes) => bytes, Err(e) => { warn!(oid = %blob.oid, cid = %blob.cid, err = %e, "failed to fetch encrypted envelope over IPFS; will retry next sync"); @@ -2727,6 +2733,100 @@ mod tests { .replace('\\', "/") } + /// A peer can advertise any CID. The replicate loop reads each envelope + /// through the ceiling, so an over-cap one is dropped before it is re-pinned + /// and the next blob still replicates. + #[sqlx::test] + async fn replicate_skips_an_envelope_over_the_ceiling(pool: PgPool) { + let state = crate::test_support::test_state(pool).await; + let now = chrono::Utc::now(); + let repo_id = uuid::Uuid::new_v4().to_string(); + state + .db + .create_repo(&crate::db::RepoRecord { + id: repo_id.clone(), + name: "mirror".into(), + owner_did: "did:key:zReplicateCeiling".into(), + description: None, + is_public: true, + default_branch: "main".into(), + created_at: now, + updated_at: now, + disk_path: "/tmp/mirror".into(), + forked_from: None, + machine_id: None, + }) + .await + .unwrap(); + + let big_cid = "bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy"; + let small_cid = "bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku"; + // One mock is both the origin peer and the local Kubo. + let mut node = mockito::Server::new_async().await; + let _advert = node + .mock("GET", "/api/v1/repos/o/r/encrypted-blobs/replicate") + .with_status(200) + .with_body( + serde_json::json!({ "blobs": [ + { "oid": "bigoid", "cid": big_cid }, + { "oid": "smalloid", "cid": small_cid }, + ]}) + .to_string(), + ) + .create_async() + .await; + let _big = node + .mock( + "POST", + mockito::Matcher::Regex(format!("^/api/v0/cat\\?arg={big_cid}")), + ) + .with_status(200) + .with_body(vec![ + b'Z'; + crate::api::encrypted::MAX_SERVED_ENVELOPE_BYTES + 1 + ]) + .create_async() + .await; + let _small = node + .mock( + "POST", + mockito::Matcher::Regex(format!("^/api/v0/cat\\?arg={small_cid}")), + ) + .with_status(200) + .with_body(b"small envelope") + .create_async() + .await; + let add = node + .mock("POST", mockito::Matcher::Regex("^/api/v0/add".to_string())) + .with_status(200) + .with_body(serde_json::json!({ "Hash": small_cid }).to_string()) + .expect(1) + .create_async() + .await; + + replicate_encrypted_blobs( + &reqwest::Client::new(), + &node.url(), + "o", + "r", + &state.db, + &repo_id, + &node.url(), + ) + .await; + + add.assert_async().await; + let have: Vec = state + .db + .list_all_encrypted_blobs(&repo_id) + .await + .unwrap() + .into_iter() + .map(|(oid, _)| oid) + .collect(); + assert_eq!(have, vec!["smalloid".to_string()]); + } + #[sqlx::test] async fn process_batch_rejects_slug_escaping_repos_dir(pool: PgPool) { // The verified escape from #272: `PathBuf::join` discards everything diff --git a/crates/twigpine-node/src/test_harness.rs b/crates/twigpine-node/src/test_harness.rs index e90695afe..2a0234c32 100644 --- a/crates/twigpine-node/src/test_harness.rs +++ b/crates/twigpine-node/src/test_harness.rs @@ -246,6 +246,17 @@ fn build_state( git_ipfs_walk_per_caller: crate::rate_limit::PerCallerConcurrency::with_default_max_keys( 16, ), + encrypted_serve_semaphore: Arc::new(tokio::sync::Semaphore::new( + crate::api::encrypted::MAX_CONCURRENT_ENCRYPTED_SERVES, + )), + encrypted_serve_per_caller: crate::rate_limit::PerCallerConcurrency::with_default_max_keys( + crate::api::encrypted::ENCRYPTED_SERVES_PER_SOURCE, + ), + encrypted_blob_rate_limiter: crate::rate_limit::RateLimiter::new_bounded( + crate::api::encrypted::ENCRYPTED_BLOB_RATE_PER_MINUTE, + std::time::Duration::from_secs(60), + 200_000, + ), hf_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)), git_bin: "git".to_string(), block_store, diff --git a/crates/twigpine-node/src/test_support.rs b/crates/twigpine-node/src/test_support.rs index 20bd68494..37ce94e6a 100644 --- a/crates/twigpine-node/src/test_support.rs +++ b/crates/twigpine-node/src/test_support.rs @@ -155,6 +155,17 @@ fn build_state(db: Arc, pool: PgPool) -> AppState { 16, ), task_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)), + encrypted_serve_semaphore: Arc::new(tokio::sync::Semaphore::new( + crate::api::encrypted::MAX_CONCURRENT_ENCRYPTED_SERVES, + )), + encrypted_serve_per_caller: crate::rate_limit::PerCallerConcurrency::with_default_max_keys( + crate::api::encrypted::ENCRYPTED_SERVES_PER_SOURCE, + ), + encrypted_blob_rate_limiter: crate::rate_limit::RateLimiter::new_bounded( + crate::api::encrypted::ENCRYPTED_BLOB_RATE_PER_MINUTE, + std::time::Duration::from_secs(60), + 200_000, + ), hf_read_rate_limiter: RateLimiter::new(1200, Duration::from_secs(3600)), git_bin: "git".to_string(), block_store: None,