Skip to content

Commit 66368be

Browse files
authored
fix(cookie): normalize host handling with port (#926)
1 parent 979d0bf commit 66368be

1 file changed

Lines changed: 17 additions & 4 deletions

File tree

src/cookie.rs

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,11 @@ impl Jar {
296296
{
297297
let cookie: RawCookie<'static> = cookie.into();
298298
let uri = into_uri!(uri);
299-
let domain = cookie.domain().or_else(|| uri.host()).unwrap_or_default();
299+
let domain = cookie
300+
.domain()
301+
.map(normalize_domain)
302+
.or_else(|| uri.host())
303+
.unwrap_or_default();
300304
let path = cookie.path().unwrap_or_else(|| normalize_path(&uri));
301305

302306
let mut inner = self.0.write();
@@ -443,7 +447,7 @@ const DEFAULT_PATH: &str = "/";
443447
/// - Returns true if the host and domain are identical.
444448
/// - Returns true if the host is a subdomain of the domain (host ends with ".domain").
445449
/// - Returns false otherwise.
446-
pub fn domain_match(host: &str, domain: &str) -> bool {
450+
fn domain_match(host: &str, domain: &str) -> bool {
447451
if domain.is_empty() {
448452
return false;
449453
}
@@ -463,19 +467,28 @@ pub fn domain_match(host: &str, domain: &str) -> bool {
463467
/// - the cookie path ends with '/', or
464468
/// - the next character in the request path after the cookie path is '/'.
465469
/// - Returns false otherwise.
466-
pub fn path_match(req_path: &str, cookie_path: &str) -> bool {
470+
fn path_match(req_path: &str, cookie_path: &str) -> bool {
467471
req_path == cookie_path
468472
|| req_path.starts_with(cookie_path)
469473
&& (cookie_path.ends_with(DEFAULT_PATH)
470474
|| req_path[cookie_path.len()..].starts_with(DEFAULT_PATH))
471475
}
472476

477+
/// Normalizes a domain by stripping any port information.
478+
///
479+
/// According to [RFC 6265 section 5.2.3](https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3),
480+
/// the domain attribute of a cookie must not include a port. If a port is present (non-standard),
481+
/// it will be ignored for domain matching purposes.
482+
fn normalize_domain(domain: &str) -> &str {
483+
domain.split(':').next().unwrap_or(domain)
484+
}
485+
473486
/// Computes the normalized default path for a cookie as specified in
474487
/// [RFC 6265 section 5.1.4](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4).
475488
///
476489
/// This function normalizes the path for a cookie, ensuring it matches
477490
/// browser and server expectations for default cookie scope.
478-
pub fn normalize_path(uri: &Uri) -> &str {
491+
fn normalize_path(uri: &Uri) -> &str {
479492
let path = uri.path();
480493
if !path.starts_with(DEFAULT_PATH) {
481494
return DEFAULT_PATH;

0 commit comments

Comments
 (0)