Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fix(security): reject non-public peer URLs + prune poisoned peers
The unauthenticated POST /api/v1/peers/announce only validated the
http(s) scheme, so anyone could register loopback/private 'peers'
(localhost:5432, localhost:22, internal admin URLs). On every push the
node fans out signed sync-notify POSTs to all peers — turning this into
an SSRF probe and burying the real peers under junk so node-origin repos
stopped replicating. Observed on node.gitlawb.com: 126/194 peer rows were
injected junk (fake DIDs z6MkScan…/z6MkAdmin…, localhost targets).

- is_public_http_url(): reject non-http(s), loopback, unspecified, private
  (RFC1918 + ULA), link-local, and localhost/.local/.internal hosts.
  Applied at announce time.
- db.prune_non_public_peers(): boot-time sweep removing already-injected
  rows, run from main() alongside prune_self_peers — self-heals poisoned
  tables on deploy.
- tests for the validator (accept public, reject loopback/private/internal,
  incl. IPv6 [::1]).

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>
  • Loading branch information
kevincodex1 and openclaudeai committed Jun 22, 2026
commit 5c4c8e7c2c815544271aa372576a0c654590a47c
92 changes: 89 additions & 3 deletions crates/gitlawb-node/src/api/peers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,54 @@ pub struct PeerResponse {
pub reachable: bool,
}

/// Whether a peer `http_url` is a public http(s) endpoint safe to register.
/// Rejects non-http(s) schemes, loopback/unspecified/private/link-local IPs,
/// and `localhost` / `.local` / `.internal` hostnames. Used at announce time
/// and by the boot-time prune of already-poisoned rows.
pub fn is_public_http_url(raw: &str) -> bool {
let url = match reqwest::Url::parse(raw) {
Ok(u) => u,
Err(_) => return false,
};
if !matches!(url.scheme(), "http" | "https") {
return false;
}
let host = match url.host_str() {
Some(h) => h.to_ascii_lowercase(),
None => return false,
};
if host.is_empty()
|| host == "localhost"
|| host.ends_with(".local")
|| host.ends_with(".internal")
{
return false;
}
// host_str() keeps brackets on IPv6 literals (e.g. "[::1]"); strip them
// before parsing as an IP.
let ip_candidate = host.trim_start_matches('[').trim_end_matches(']');
if let Ok(ip) = ip_candidate.parse::<std::net::IpAddr>() {
if ip.is_loopback() || ip.is_unspecified() {
return false;
}
match ip {
std::net::IpAddr::V4(v4) => {
if v4.is_private() || v4.is_link_local() {
return false;
}
}
std::net::IpAddr::V6(v6) => {
let s = v6.segments();
// fc00::/7 (unique-local) or fe80::/10 (link-local)
if (s[0] & 0xfe00) == 0xfc00 || (s[0] & 0xffc0) == 0xfe80 {
return false;
}
}
}
Comment thread
beardthelion marked this conversation as resolved.
Resolved
}
true
}

/// GET /api/v1/peers
pub async fn list_peers(State(state): State<AppState>) -> Result<Json<serde_json::Value>> {
let peers = state.db.list_peers().await?;
Expand Down Expand Up @@ -83,10 +131,14 @@ pub async fn announce(
);
}

// Validate the URL is HTTP/HTTPS
if !req.http_url.starts_with("http://") && !req.http_url.starts_with("https://") {
// Validate the URL is a public http(s) endpoint. The announce route is
// reachable unauthenticated (until all peers sign), so without this an
// attacker can register loopback/private "peers" (localhost:5432, etc.)
// and turn our outbound sync-notify fan-out into an SSRF probe — and bury
// the real peers under junk so node-origin repos stop replicating.
if !is_public_http_url(&req.http_url) {
return Err(AppError::BadRequest(
"http_url must start with http:// or https://".into(),
"http_url must be a public http(s) URL (no loopback, private, or .internal/.local hosts)".into(),
));
}

Expand Down Expand Up @@ -324,3 +376,37 @@ pub async fn ping_peer(
"reachable": ok,
})))
}

#[cfg(test)]
mod tests {
use super::is_public_http_url;

#[test]
fn accepts_public_https_and_http() {
assert!(is_public_http_url("https://node.gitlawb.com"));
assert!(is_public_http_url("https://manila.gitlawb.com/"));
assert!(is_public_http_url("http://203.0.113.10:7545"));
}

#[test]
fn rejects_loopback_private_and_internal() {
for bad in [
"http://localhost:7545",
"http://127.0.0.1:5432/",
"http://localhost:22/",
"http://0.0.0.0:7545",
"http://10.0.0.5:7545",
"http://192.168.1.10/",
"http://172.16.0.1:7545",
"http://169.254.1.1/",
"http://[::1]:7545",
"http://gitlawb-node.internal:7545",
"http://my-node.local/",
"ftp://node.gitlawb.com",
"not-a-url",
"",
] {
assert!(!is_public_http_url(bad), "{bad:?} must be rejected");
}
}
}
20 changes: 20 additions & 0 deletions crates/gitlawb-node/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1601,6 +1601,26 @@ impl Db {
.await?;
Ok(result.rows_affected())
}

/// Remove peer rows whose `http_url` is not a public http(s) endpoint
/// (loopback/private/internal hosts injected via the open announce route).
/// Runs at boot to clean tables poisoned before announce-time validation
/// existed. Filtering is done in Rust to share one definition of "public"
/// with the announce handler.
pub async fn prune_non_public_peers(&self) -> Result<u64> {
let peers = self.list_peers().await?;
let mut removed = 0u64;
for p in peers {
if !crate::api::peers::is_public_http_url(&p.http_url) {
sqlx::query("DELETE FROM peers WHERE did = $1")
.bind(&p.did)
.execute(&self.pool)
.await?;
removed += 1;
}
}
Ok(removed)
}
}

// ── Pinned CIDs ───────────────────────────────────────────────────────────────
Expand Down
32 changes: 15 additions & 17 deletions crates/gitlawb-node/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ mod pinata;
mod rate_limit;
mod server;
mod state;
mod storage;
mod sync;
mod visibility;
mod webhooks;
Expand Down Expand Up @@ -97,6 +98,15 @@ async fn main() -> Result<()> {
}
}

// Prune peer rows with non-public hosts (loopback/private/internal) that
// were injected via the unauthenticated announce route — they poison the
// sync-notify fan-out (SSRF + crowding out real peers).
match db.prune_non_public_peers().await {
Ok(0) => {}
Ok(n) => info!(removed = n, "pruned non-public (poisoned) peer rows"),
Err(e) => warn!(err = %e, "prune_non_public_peers failed (non-fatal)"),
}

// Ensure repos directory exists
std::fs::create_dir_all(&config.repos_dir).context("failed to create repos directory")?;

Expand Down Expand Up @@ -152,25 +162,13 @@ async fn main() -> Result<()> {
info!(" fly machine: {mid}");
}

// Initialize Tigris S3 client if bucket is configured
let tigris = if !config.tigris_bucket.is_empty() {
match git::tigris::TigrisClient::new(&config.tigris_bucket).await {
Ok(client) => {
info!(bucket = %config.tigris_bucket, "tigris storage enabled");
Some(client)
}
Err(e) => {
tracing::warn!(err = %e, "failed to initialize Tigris client — using local-only storage");
None
}
}
} else {
info!("tigris storage disabled (no bucket configured)");
None
};
// Initialize the storage-agnostic blob backend (S3-compatible / filesystem /
// IPFS), then wrap it in the repo-archive layer. `None` = local-only mode.
let blob_store = storage::build(&config).await;
let archive = blob_store.map(storage::archive::RepoArchive::new);

let repo_store =
git::repo_store::RepoStore::new(config.repos_dir.clone(), tigris, db.pool().clone());
git::repo_store::RepoStore::new(config.repos_dir.clone(), archive, db.pool().clone());

let rate_limiter = rate_limit::RateLimiter::new(10, std::time::Duration::from_secs(3600));

Expand Down
Loading