Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
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
22 changes: 17 additions & 5 deletions crates/clipsync-core/src/pairing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,12 +170,18 @@ pub async fn join_room(
))
})?;
if !resp.status().is_success() {
let throttled = resp.status() == reqwest::StatusCode::TOO_MANY_REQUESTS;
let body = resp.text().await.unwrap_or_default();
if body.contains("code_invalid") || body.contains("code_expired") {
return Err(CoreError::Pairing(
"unknown or expired pairing code; on the other device run `clipsync room create` again".into(),
));
}
if throttled || body.contains("too_many_attempts") {
return Err(CoreError::Pairing(
"the relay is limiting pairing attempts; wait a few minutes, then run `clipsync room create` again on the other device and retry with the new code".into(),
));
}
return Err(CoreError::Pairing(format!("join failed: {body}")));
}
let joined: JoinPairingResponse = resp.json().await?;
Expand Down Expand Up @@ -641,10 +647,14 @@ mod tests {
let store =
LocalStore::open_from(crate::AppPaths::from_root(directory.path().into())).unwrap();
let identity = DeviceIdentity::from_bytes("http-failure".into(), [31; 32]);
for body in [
"code_invalid",
"code_expired",
"busy: joiner already connected",
for (status, body) in [
(StatusCode::CONFLICT, "code_invalid"),
(StatusCode::CONFLICT, "code_expired"),
(StatusCode::CONFLICT, "busy: joiner already connected"),
(
StatusCode::TOO_MANY_REQUESTS,
r#"{"code":"too_many_attempts","message":"pairing attempt limit reached"}"#,
),
] {
let server = crate::test_relay::Server::http(
Router::new()
Expand All @@ -654,7 +664,7 @@ mod tests {
)
.route(
"/v1/pairing/join",
post(move || async move { (StatusCode::CONFLICT, body) }),
post(move || async move { (status, body) }),
),
)
.await;
Expand All @@ -669,6 +679,8 @@ mod tests {
.unwrap_err();
if body.starts_with("code_") {
assert!(join.to_string().contains("unknown or expired pairing code"));
} else if status == StatusCode::TOO_MANY_REQUESTS {
assert!(join.to_string().contains("limiting pairing attempts"));
} else {
assert!(join.to_string().contains(body));
}
Expand Down
79 changes: 79 additions & 0 deletions crates/clipsync-relay/src/client_ip.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright the ClipSync contributors.
// SPDX-License-Identifier: MIT
//! Client address resolution for per-client limits.
//!
//! The TCP peer address is authoritative by default. `X-Forwarded-For` is read
//! only when the peer itself is an operator-configured trusted proxy, and then
//! only up to the rightmost hop that is not a trusted proxy: every entry to the
//! left of that hop was written by the client and can be forged.

use std::net::{IpAddr, SocketAddr};

use axum::http::HeaderMap;
use ipnet::IpNet;

const X_FORWARDED_FOR: &str = "x-forwarded-for";

#[derive(Clone, Debug, Default)]
pub(crate) struct TrustedProxies(Vec<IpNet>);

impl TrustedProxies {
pub(crate) fn new(proxies: Vec<IpNet>) -> Self {
Self(proxies.into_iter().map(|net| net.trunc()).collect())
}

fn contains(&self, ip: IpAddr) -> bool {
self.0.iter().any(|net| net.contains(&ip))
}

/// Resolve the client address of a request received from `peer`.
pub(crate) fn client_ip(&self, peer: IpAddr, headers: &HeaderMap) -> IpAddr {
let peer = peer.to_canonical();
if !self.contains(peer) {
return peer;
}
// Each proxy appends the address it received the request from, so walk
// from the right. A malformed hop ends the walk at the nearest trusted
// proxy: nothing to its left can be attributed reliably.
let hops: Vec<Option<&str>> = headers
.get_all(X_FORWARDED_FOR)
.iter()
.flat_map(|value| match value.to_str() {
Ok(list) => list.split(',').map(Some).collect::<Vec<_>>(),
Err(_) => vec![None],
})
.collect();
let mut client = peer;
for hop in hops.into_iter().rev() {
let Some(ip) = hop.and_then(parse_hop) else {
break;
};
client = ip.to_canonical();
if !self.contains(client) {
break;
}
}
client
}
}

fn parse_hop(hop: &str) -> Option<IpAddr> {
let hop = hop.trim();
hop.parse::<IpAddr>()
.ok()
.or_else(|| hop.parse::<SocketAddr>().ok().map(|addr| addr.ip()))
}

/// Parse one `CLIPSYNC_RELAY_TRUSTED_PROXIES` entry: a CIDR range or a single address.
pub(crate) fn parse_trusted_proxy(value: &str) -> Result<IpNet, String> {
let value = value.trim();
value
.parse::<IpNet>()
.or_else(|_| value.parse::<IpAddr>().map(IpNet::from))
.map_err(|_| format!("`{value}` is not an IP address or CIDR range"))
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
#[path = "client_ip_tests.rs"]
mod tests;
99 changes: 99 additions & 0 deletions crates/clipsync-relay/src/client_ip_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// Copyright the ClipSync contributors.
// SPDX-License-Identifier: MIT
use super::*;
use axum::http::HeaderValue;

fn proxies(entries: &[&str]) -> TrustedProxies {
TrustedProxies::new(
entries
.iter()
.map(|entry| parse_trusted_proxy(entry).unwrap())
.collect(),
)
}

fn forwarded(values: &[&[u8]]) -> HeaderMap {
let mut headers = HeaderMap::new();
for value in values {
headers.append(X_FORWARDED_FOR, HeaderValue::from_bytes(value).unwrap());
}
headers
}

fn ip(value: &str) -> IpAddr {
value.parse().unwrap()
}

#[test]
fn forwarded_header_is_ignored_without_trusted_proxy_configuration() {
let headers = forwarded(&[b"203.0.113.9"]);
assert_eq!(
TrustedProxies::default().client_ip(ip("127.0.0.1"), &headers),
ip("127.0.0.1")
);
}

#[test]
fn forwarded_header_is_ignored_from_an_untrusted_peer() {
let trusted = proxies(&["10.0.0.0/8"]);
let headers = forwarded(&[b"203.0.113.9"]);
assert_eq!(
trusted.client_ip(ip("198.51.100.4"), &headers),
ip("198.51.100.4")
);
}

#[test]
fn trusted_proxy_yields_the_rightmost_untrusted_hop_not_client_supplied_entries() {
let trusted = proxies(&["10.0.0.0/8", "127.0.0.1"]);
// The client forged the leftmost entry; the edge proxy (10.0.0.2) appended
// the real client address, and the local proxy appended the edge proxy.
let headers = forwarded(&[b"192.0.2.66, 203.0.113.9", b"10.0.0.2"]);
assert_eq!(
trusted.client_ip(ip("127.0.0.1"), &headers),
ip("203.0.113.9")
);
let single = forwarded(&[b"203.0.113.9:51234"]);
assert_eq!(
trusted.client_ip(ip("127.0.0.1"), &single),
ip("203.0.113.9")
);
let v6 = forwarded(&[b"[2001:db8::7]:443"]);
assert_eq!(
trusted.client_ip(ip("::ffff:127.0.0.1"), &v6),
ip("2001:db8::7")
);
}

#[test]
fn missing_or_malformed_forwarded_hops_fall_back_to_the_nearest_trusted_proxy() {
let trusted = proxies(&["10.0.0.0/8"]);
assert_eq!(
trusted.client_ip(ip("10.0.0.1"), &HeaderMap::new()),
ip("10.0.0.1")
);
let garbage = forwarded(&[b"203.0.113.9, not-an-ip, 10.0.0.3"]);
assert_eq!(trusted.client_ip(ip("10.0.0.1"), &garbage), ip("10.0.0.3"));
let opaque = forwarded(&[b"203.0.113.9", b"\xff"]);
assert_eq!(trusted.client_ip(ip("10.0.0.1"), &opaque), ip("10.0.0.1"));
let all_trusted = forwarded(&[b"10.0.0.9, 10.0.0.3"]);
assert_eq!(
trusted.client_ip(ip("10.0.0.1"), &all_trusted),
ip("10.0.0.9")
);
}

#[test]
fn trusted_proxy_entries_accept_cidrs_and_single_addresses_only() {
let range = parse_trusted_proxy(" 10.1.2.3/8 ").unwrap();
assert_eq!(range, "10.1.2.3/8".parse::<IpNet>().unwrap());
assert_eq!(
parse_trusted_proxy("::1").unwrap(),
"::1/128".parse::<IpNet>().unwrap()
);
assert!(parse_trusted_proxy("proxy.example").is_err());
assert!(parse_trusted_proxy("10.0.0.0/33").is_err());
let trusted = TrustedProxies::new(vec![range]);
assert!(trusted.contains(ip("10.200.0.1")));
assert!(!trusted.contains(ip("11.0.0.1")));
}
Loading
Loading