//! Authenticated discovery + fetch for encrypted withheld blobs (Option B1). use axum::extract::{Extension, Path, State}; use axum::Json; 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, /// so access control here is repo readability and decryption is gated by the /// envelope crypto (only a real recipient can open an envelope). /// /// Quarantined repos are opaque 404 via [`crate::api::authorize_repo_read`] — /// same as issues/changelogs — so a public-but-quarantined mirror cannot leak /// its encrypted blob index. pub async fn list_encrypted_blobs( State(state): State, auth: Option>, Path((owner, repo)): Path<(String, String)>, ) -> Result> { 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?; let rows = state.db.list_all_encrypted_blobs(&record.id).await?; let blobs: Vec<_> = rows .into_iter() .map(|(oid, cid)| serde_json::json!({ "oid": oid, "cid": cid })) .collect(); Ok(Json(serde_json::json!({ "blobs": blobs }))) } /// GET /api/v1/repos/{owner}/{repo}/encrypted-blob/{oid} /// Returns raw envelope bytes to callers who can read the repo; the envelope /// 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 { 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?; let cid = state .db .encrypted_blob_cid(&record.id, &oid) .await? .ok_or_else(|| AppError::RepoNotFound(format!("{owner}/{repo}/{oid}")))?; // 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::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 /// Returns [{oid, cid}] for every encrypted blob in the repo, for peer-mirror /// replication (Option B2). Gated by repo readability, like discovery, so a /// non-readable repo does not expose its blob index; for the intended case (a /// public repo with withheld subtrees) the public root keeps this open to peers. /// Recipient identities are deliberately withheld: the v2 envelopes no longer /// carry recipient public keys, so peers must not learn the reader set either. A /// mirror detects a re-seal by the CID changing (the OID is stable across /// re-seals). Ciphertext metadata only, never plaintext. pub async fn replicate_encrypted_blobs( State(state): State, auth: Option>, Path((owner, repo)): Path<(String, String)>, ) -> Result> { 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?; let rows = state.db.list_all_encrypted_blobs(&record.id).await?; let blobs: Vec<_> = rows .into_iter() .map(|(oid, cid)| replicate_blob_json(oid, cid)) .collect(); Ok(Json(serde_json::json!({ "blobs": blobs }))) } /// Serialize one blob for the replication wire. Recipient identities are /// intentionally absent so a mirror never learns the reader set. fn replicate_blob_json(oid: String, cid: String) -> serde_json::Value { serde_json::json!({ "oid": oid, "cid": cid }) } #[cfg(test)] mod tests { 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() { let v = replicate_blob_json("oid1".into(), "cidA".into()); assert_eq!(v["oid"], "oid1"); assert_eq!(v["cid"], "cidA"); assert!( v.get("recipients").is_none(), "replication wire must not carry recipient identities" ); } }