diff --git a/crates/twigpine-node/src/api/peers.rs b/crates/twigpine-node/src/api/peers.rs index 0e0497118..f7cc156d5 100644 --- a/crates/twigpine-node/src/api/peers.rs +++ b/crates/twigpine-node/src/api/peers.rs @@ -604,7 +604,8 @@ pub async fn notify_sync( /// GET /api/v1/peers/{did}/ping /// -/// Check if a specific peer in our list is currently reachable. +/// Report the readiness the gossip loop last recorded for the peer. The route +/// sends no request to the peer and writes nothing. pub async fn ping_peer( State(state): State, Path(did): Path, @@ -615,19 +616,10 @@ pub async fn ping_peer( .find(|p| p.did == did) .ok_or_else(|| AppError::RepoNotFound(format!("peer {did} not found")))?; - // Use DB-aware readiness rather than process liveness: `/health` stays 200 - // during a mid-life database outage, while `/ready` reports 503. A 404-only - // fallback keeps pre-readiness peers compatible. The shared helper also - // preserves the no-redirect SSRF guard on peer-controlled URLs. - let ok = crate::ping_peer_readiness(&state.http_client, &peer.http_url).await; - - // This anonymous diagnostic endpoint is intentionally read-only. The - // periodic gossip loop owns the persisted federation-reachability gate and - // requires consecutive failures before marking a peer unreachable. Ok(Json(serde_json::json!({ "did": did, "http_url": peer.http_url, - "reachable": ok, + "reachable": peer.last_ping_ok, }))) } @@ -1036,13 +1028,28 @@ mod tests { did } + async fn seed_ping_peer_row(pool: &PgPool, did: &str, http_url: &str, last_ping_ok: bool) { + let now = chrono::Utc::now().to_rfc3339(); + sqlx::query( + "INSERT INTO peers (did, http_url, last_seen, last_ping_ok, announced_at) + VALUES ($1, $2, $3, $4, $3)", + ) + .bind(did) + .bind(http_url) + .bind(now) + .bind(last_ping_ok) + .execute(pool) + .await + .unwrap(); + } + #[sqlx::test] - async fn manual_ping_uses_readiness_without_mutating_federation_gate(pool: PgPool) { + async fn ping_peer_reports_stored_ready_without_probe_or_write(pool: PgPool) { let mut server = mockito::Server::new_async().await; let ready = server .mock("GET", "/ready") .with_status(503) - .expect(1) + .expect(0) .create_async() .await; let health = server @@ -1056,17 +1063,7 @@ mod tests { state.http_client = Arc::new(crate::build_http_client().expect("production HTTP client should build")); let did = Keypair::generate().did().to_string(); - let now = chrono::Utc::now().to_rfc3339(); - sqlx::query( - "INSERT INTO peers (did, http_url, last_seen, last_ping_ok, announced_at) - VALUES ($1, $2, $3, TRUE, $3)", - ) - .bind(&did) - .bind(server.url()) - .bind(now) - .execute(&pool) - .await - .unwrap(); + seed_ping_peer_row(&pool, &did, &server.url(), true).await; let response = Router::new() .route("/api/v1/peers/{did}/ping", get(super::ping_peer)) @@ -1086,7 +1083,15 @@ mod tests { .await .unwrap(); let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); - assert_eq!(json["reachable"], false); + assert_eq!(json["reachable"], true); + let mut keys = json + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect::>(); + keys.sort_unstable(); + assert_eq!(keys, vec!["did", "http_url", "reachable"]); ready.assert_async().await; health.assert_async().await; @@ -1100,7 +1105,114 @@ mod tests { .unwrap(); assert!( peer.last_ping_ok, - "an anonymous manual sample must not rewrite the federation gate" + "the ping route must not rewrite the federation gate" + ); + } + + #[sqlx::test] + async fn ping_peer_makes_no_outbound_request(pool: PgPool) { + let mut server = mockito::Server::new_async().await; + let ready = server + .mock("GET", "/ready") + .with_status(200) + .expect(0) + .create_async() + .await; + let health = server + .mock("GET", "/health") + .with_status(200) + .expect(0) + .create_async() + .await; + + let mut state = test_state(pool.clone()).await; + state.http_client = + Arc::new(crate::build_http_client().expect("production HTTP client should build")); + let did = Keypair::generate().did().to_string(); + seed_ping_peer_row(&pool, &did, &server.url(), false).await; + + let response = Router::new() + .route("/api/v1/peers/{did}/ping", get(super::ping_peer)) + .with_state(state.clone()) + .oneshot( + Request::builder() + .method(Method::GET) + .uri(format!("/api/v1/peers/{did}/ping")) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(json["reachable"], false); + ready.assert_async().await; + health.assert_async().await; + } + + #[sqlx::test] + async fn ping_peer_private_url_makes_no_outbound_request(pool: PgPool) { + let mut state = test_state(pool.clone()).await; + state.http_client = + Arc::new(crate::build_http_client().expect("production HTTP client should build")); + let did = Keypair::generate().did().to_string(); + seed_ping_peer_row(&pool, &did, "http://10.0.0.1:9", true).await; + + let router = Router::new() + .route("/api/v1/peers/{did}/ping", get(super::ping_peer)) + .with_state(state); + let response = tokio::time::timeout( + Duration::from_secs(2), + router.oneshot( + Request::builder() + .method(Method::GET) + .uri(format!("/api/v1/peers/{did}/ping")) + .body(Body::empty()) + .unwrap(), + ), + ) + .await + .expect("the ping route must not wait on the peer URL") + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(json["reachable"], true); + } + + #[sqlx::test] + async fn ping_peer_unknown_did_is_not_found_without_probe(pool: PgPool) { + let state = test_state(pool).await; + let did = Keypair::generate().did().to_string(); + + let response = Router::new() + .route("/api/v1/peers/{did}/ping", get(super::ping_peer)) + .with_state(state) + .oneshot( + Request::builder() + .method(Method::GET) + .uri(format!("/api/v1/peers/{did}/ping")) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::NOT_FOUND); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!( + json["message"], + format!("repository 'peer {did} not found' not found") ); } diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 87e225155..9687c432d 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -21530,7 +21530,7 @@ mod peer_authority_tests { /// | `prune_non_public_peers` (db/mod.rs) | a delete keyed on a computed bad-DID array; cannot repoint; boot-only caller in main.rs | /// | `seed_local_peer` (sync.rs) | excluded by test-module location: a deliberate `upsert_peer` bypass for `file://` fixtures, which the public-URL gate rejects | /// | `a_legacy_row_can_still_refresh_its_liveness` (db/mod.rs) | test-only. Seeds a PRE-GATE row by raw SQL on purpose: `upsert_peer` cannot create one, since the gate it is testing refuses exactly that DID. The fixture models what a deployed table already holds | -/// | `manual_ping_uses_readiness_without_mutating_federation_gate` (api/peers.rs) | test-only fixture seed, same shape and same reason: the row under test must pre-exist so the assertion is about what the ping does NOT rewrite | +/// | `seed_ping_peer_row` (api/peers.rs) | test-only fixture seed, same shape and same reason: the row under test must pre-exist so the ping tests assert what the route does not probe or rewrite | /// | `gossip_ping_round_never_dials_a_refused_ip_literal` (lib.rs) | test-only fixture seed for a legacy row holding an IP literal `upsert_peer` would refuse; the round must count it unready without dialing it | /// | `gossip_ping_round_requires_two_failures_before_persisting_unreachable` (lib.rs) | test-only fixture seed for the gossip hysteresis round; the row must pre-exist so the assertion is about when `mark_peer_ping` fires | /// | `seed_peer` (p2p/mod.rs) | test-only fixture seed. Raw SQL so the gossip ingest tests can drive the known-peer gate directly, including the did:web case `upsert_peer` would refuse | @@ -21630,10 +21630,7 @@ mod peers_table_writer_guard { "federated_route_reports_truncated_when_peer_table_overflows", 1, ), - ( - "manual_ping_uses_readiness_without_mutating_federation_gate", - 1, - ), + ("seed_ping_peer_row", 1), ("gossip_ping_round_never_dials_a_refused_ip_literal", 1), ( "gossip_ping_round_requires_two_failures_before_persisting_unreachable", diff --git a/docs/RUN-A-NODE.md b/docs/RUN-A-NODE.md index b6acd8d91..d6c4e30fd 100644 --- a/docs/RUN-A-NODE.md +++ b/docs/RUN-A-NODE.md @@ -106,7 +106,7 @@ TWIGPINE_TRUSTED_PROXY_CIDRS=10.0.0.8/32 Use the narrowest range you control, preferably the proxy's exact address. Do not guess broad platform ranges. Fly sets `Fly-Client-IP`, but Fly does not publish stable proxy source ranges, so a stock Fly deployment cannot provide verified per-client keying unless the operator can measure and accept a trustworthy range. Full client-IP keys also remain cheaply rotatable for a caller controlling a routed IPv6 `/64`; this boundary stops forwarded-header spoofing, not address-space rotation. -Outbound requests to URLs other people choose (peer announce and ping, bootstrap, webhook delivery, and the sync worker's git fetch of a peer) resolve each hostname and connect only when every resolved address passes the node's outbound address policy. The policy refuses loopback, private and unique-local, link-local (which covers the `169.254.169.254` cloud metadata address), carrier-grade NAT, multicast, and the documentation, benchmarking and other non-global special-purpose ranges the node lists. It is narrower than every IANA special-purpose range: an address in the well-known NAT64 prefix `64:ff9b::/96` is allowed when the IPv4 address it embeds is public. Every refused lookup is logged at `warn`. An IP-literal URL never reaches a resolver. The URL check at registration and at webhook delivery refuses loopback, private, link-local and carrier-grade NAT literals, and the sync worker and the periodic gossip ping also apply the full policy to a literal before sending anything. The manual `GET /api/v1/peers/{did}/ping` diagnostic does not apply that literal check. The node ignores `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY` for that traffic. Endpoints you configure yourself (`TWIGPINE_IPFS_API`, Pinata and Irys) are unaffected and keep working on a private or loopback hostname, on the push path and in the reconciliation sweep alike. +Outbound requests to URLs other people choose (peer announce and ping, bootstrap, webhook delivery, and the sync worker's git fetch of a peer) resolve each hostname and connect only when every resolved address passes the node's outbound address policy. The policy refuses loopback, private and unique-local, link-local (which covers the `169.254.169.254` cloud metadata address), carrier-grade NAT, multicast, and the documentation, benchmarking and other non-global special-purpose ranges the node lists. It is narrower than every IANA special-purpose range: an address in the well-known NAT64 prefix `64:ff9b::/96` is allowed when the IPv4 address it embeds is public. Every refused lookup is logged at `warn`. An IP-literal URL never reaches a resolver. The URL check at registration and at webhook delivery refuses loopback, private, link-local and carrier-grade NAT literals, and the sync worker and the periodic gossip ping also apply the full policy to a literal before sending anything. The manual `GET /api/v1/peers/{did}/ping` diagnostic makes no outbound request and returns the readiness the periodic gossip ping last recorded. The node ignores `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY` for that traffic. Endpoints you configure yourself (`TWIGPINE_IPFS_API`, Pinata and Irys) are unaffected and keep working on a private or loopback hostname, on the push path and in the reconciliation sweep alike. The sync worker writes the same hardening into each peer mirror's own git config, so a later lazy fetch of a promisor mirror (for example a read of an object the peer withheld) stays pinned to the last checked addresses with proxy, redirect, credential and bundle channels off. If the peer legitimately moves to new addresses, that lazy fetch fails until the next sync refresh writes a fresh pin.