Something went wrong. Try again.
contributor fork of @ptr.pet hydrant forked from ptr.pet/hydrant
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104#[cfg(test)]use jacquard_api::com_atproto::sync::request_crawl::RequestCrawl;use jacquard_api::com_atproto::sync::request_crawl::{ RequestCrawlError, RequestCrawlRequest, RequestCrawlResponse,};use url::Url;
use super::*;
pub async fn handle( State(hydrant): State<Hydrant>, ExtractXrpc(req): ExtractXrpc<RequestCrawlRequest>,) -> XrpcResult<StatusCode, RequestCrawlError> { let nsid = RequestCrawlResponse::NSID;
let url_str = format!("wss://{}/", req.hostname); let url = Url::parse(&url_str).map_err(|e| bad_request(nsid, e))?;
if hydrant.pds.is_banned(&req.hostname) { return Err(XrpcErrorResponse { status: StatusCode::BAD_REQUEST, error: jacquard_common::xrpc::XrpcError::Xrpc(RequestCrawlError::HostBanned(Some( "host is banned".into(), ))), }); }
// if this host is already running, everything is already ok if hydrant.firehose.is_source_running(&url) { return Ok(StatusCode::OK); }
// enforce daily new pds limit on unknown hosts if !hydrant.firehose.is_source_known(&url) { let (allowed, to_persist) = hydrant.state.pds_daily_limit.try_increment(); if !allowed { return Err(rate_limited( nsid, "POST", "daily limit for new PDS sources reached", )); }
// persist the new count before returning so a crash cannot reset the counter // and allow the budget to be replayed. if let Some((day, count)) = to_persist { hydrant .state .db .run(move |db| crate::db::save_pds_daily_adds(db, day, count)) .await .map_err(|e| internal_error(nsid, e))?; } }
hydrant .firehose .add_source(url, true) .await .map_err(|e| internal_error(nsid, e))?;
Ok(StatusCode::OK)}
#[cfg(test)]mod tests { use super::*; use axum::response::IntoResponse;
#[tokio::test] async fn banned_request_crawl_json_contract() -> miette::Result<()> { let tmp = tempfile::tempdir().map_err(|e| miette::miette!(e))?; let hydrant = Hydrant::new(crate::config::Config { database_path: tmp.path().to_path_buf(), ..Default::default() }) .await?; hydrant.pds.ban("blocked.example").await?;
let error = handle( State(hydrant), ExtractXrpc::<RequestCrawlRequest>(RequestCrawl { hostname: "blocked.example".into(), extra_data: Default::default(), }), ) .await .expect_err("banned host must be rejected"); let response = error.into_response(); assert_eq!(response.status(), StatusCode::BAD_REQUEST); let body = axum::body::to_bytes(response.into_body(), 1024) .await .map_err(|e| miette::miette!(e))?; assert_eq!( serde_json::from_slice::<serde_json::Value>(&body).map_err(|e| miette::miette!(e))?, serde_json::json!({ "error": "HostBanned", "message": "host is banned", }) ); Ok(()) }}