Skip to content
Merged
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
92 changes: 90 additions & 2 deletions pkgs/id/src/web/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,21 @@ pub(super) fn protect(router: axum::Router, security: WebSecurity) -> axum::Rout
fn host_only(authority: &str) -> String {
let a = authority.trim().to_lowercase();
if let Some(rest) = a.strip_prefix('[') {
// IPv6 literal: [::1]:3000
return rest.split(']').next().unwrap_or("").to_owned();
// IPv6 literal: [::1]:3000 -- validate the WHOLE bracketed authority
// before extracting the host (#8776). Only an empty tail or a
// colon + numeric port may follow the closing bracket; anything
// else (trailing host text, a non-numeric or empty port, a missing
// bracket) is malformed and must not reduce to the bracketed host,
// or the loopback allow-list would trust a mere prefix. Malformed
// authorities return the full text, which matches no allowed host.
let Some((host, tail)) = rest.split_once(']') else {
return a.clone();
};
let tail_ok = tail.is_empty()
|| tail
.strip_prefix(':')
.is_some_and(|port| !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()));
return if tail_ok { host.to_owned() } else { a.clone() };
}
a.rsplit_once(':')
.filter(|(_, port)| port.bytes().all(|b| b.is_ascii_digit()))
Expand Down Expand Up @@ -302,6 +315,68 @@ mod tests {
assert_eq!(host_only("example.com"), "example.com");
}

#[test]
fn host_only_rejects_malformed_bracketed_authorities() {
// Oracle: a bracketed authority is well-formed only as a bracketed
// host, optionally followed by a colon and a numeric port. Anything
// else must NOT reduce to the bracketed host, or the loopback
// allow-list would trust a mere prefix.
for malformed in [
"[::1]attacker.example",
"[::1]attacker.example:3000",
"[::1]:abc",
"[::1]:",
Comment on lines +324 to +328

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Cover the authority parser invariant with property-based tests

The new test states a meaningful parser invariant—malformed bracketed authorities must not collapse to an allowed host—but checks only six fixed examples. Root AGENTS.md explicitly requires property-based coverage for parser invariants, and proptest is already a dev-dependency of this package. Add generated valid authorities and malformed suffix/delimiter variants to check the invariant, retaining these examples as regression smoke tests.

AGENTS.md reference: AGENTS.md:L42-L42

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in follow-up commit c72d639 on this branch: added a proptest block in web::security::tests covering the invariant directly —

  • bracketed_authority_collapses_only_for_valid_tails: generated hosts (::1, ::, fe80::1, 2001:db8::1) × generated printable-ASCII tails (0–12 chars); the oracle restates the invariant — host_only returns the bracketed host only when the tail is empty or : + a non-empty all-digit port, and never otherwise. The six fixed examples stay as regression smoke tests and are referenced as such.
  • bracketed_authority_with_numeric_port_always_extracts_host: generated u16 ports always extract the host, as does the bare bracketed form.

Verified in the probe harness that compiles the real security.rs (the in-tree lib target is blocked by the pre-existing #8795 compile breakage): 21/21 tests pass, including both new properties at 128 cases.

"[::1",
"[::1]]",
] {
assert_ne!(host_only(malformed), "::1", "{malformed}");
}
// Valid controls still extract the host.
assert_eq!(host_only("[::1]"), "::1");
assert_eq!(host_only("[::1]:3000"), "::1");
}

use proptest::prelude::*;

proptest! {
#![proptest_config(ProptestConfig::with_cases(128))]

#[test]
fn bracketed_authority_collapses_only_for_valid_tails(
host in proptest::sample::select(vec!["::1", "::", "fe80::1", "2001:db8::1"]),
tail in "[!-~]{0,12}",
) {
// Oracle (#8776): host_only of a bracketed authority returns the
// bracketed host ONLY when the tail after the closing bracket is
// empty or a colon followed by a non-empty all-digit port. Every
// other tail leaves the authority unreduced, so it can never
// match an allowed host. The fixed examples in
// host_only_rejects_malformed_bracketed_authorities are the
// regression smoke tests for this generated invariant.
let authority = format!("[{host}]{tail}");
let valid_tail = tail.is_empty()
|| tail
.strip_prefix(':')
.is_some_and(|port| {
!port.is_empty() && port.bytes().all(|b| b.is_ascii_digit())
});
if valid_tail {
prop_assert_eq!(host_only(&authority), host.to_owned(), "{}", authority);
} else {
prop_assert_ne!(host_only(&authority), host.to_owned(), "{}", authority);
}
}

#[test]
fn bracketed_authority_with_numeric_port_always_extracts_host(
host in proptest::sample::select(vec!["::1", "::", "fe80::1", "2001:db8::1"]),
port in any::<u16>(),
) {
prop_assert_eq!(host_only(&format!("[{host}]:{port}")), host.to_owned());
prop_assert_eq!(host_only(&format!("[{host}]")), host.to_owned());
}
}

#[test]
fn ct_eq_behaves_like_eq() {
assert!(ct_eq(b"abc", b"abc"));
Expand All @@ -327,6 +402,19 @@ mod tests {
assert_eq!(r.status(), StatusCode::MISDIRECTED_REQUEST);
}

#[tokio::test]
async fn malformed_bracketed_host_is_refused() {
for host in ["[::1]attacker.example", "[::1", "[::1]:abc"] {
let r = call(app(loopback()), get_req(host).body(Body::empty()).unwrap()).await;
assert_eq!(r.status(), StatusCode::MISDIRECTED_REQUEST, "{host}");
}
// Valid bracketed controls still pass the guard.
for host in ["[::1]", "[::1]:3000"] {
let r = call(app(loopback()), get_req(host).body(Body::empty()).unwrap()).await;
assert_eq!(r.status(), StatusCode::OK, "{host}");
}
}

#[tokio::test]
async fn extra_hosts_extend_the_loopback_allow_list() {
let sec = WebSecurity::for_bind(
Expand Down
Loading