Fix cookies when domain is null (#1538)

This commit is contained in:
Mitchell Syer
2025-07-21 15:13:04 -04:00
committed by GitHub
parent 3ff29aa38a
commit 798b9d0c98
@@ -113,7 +113,7 @@ class PersistentCookieStore(
cookie: HttpCookie, cookie: HttpCookie,
) { ) {
lock.withLock { lock.withLock {
val cookie = cookie.toCookie() val cookie = cookie.toCookie(uri?.host) ?: return@withLock
val cookiesForDomain = cookieMap[cookie.domain].orEmpty().toMutableList() val cookiesForDomain = cookieMap[cookie.domain].orEmpty().toMutableList()
// Find a cookie with the same name. Replace it if found, otherwise add a new one. // Find a cookie with the same name. Replace it if found, otherwise add a new one.
val pos = cookiesForDomain.indexOfFirst { it.name == cookie.name } val pos = cookiesForDomain.indexOfFirst { it.name == cookie.name }
@@ -153,7 +153,7 @@ class PersistentCookieStore(
cookie: HttpCookie, cookie: HttpCookie,
): Boolean = ): Boolean =
lock.withLock { lock.withLock {
val cookie = cookie.toCookie() val cookie = cookie.toCookie(uri?.host) ?: return@withLock false
val cookies = cookieMap[cookie.domain].orEmpty() val cookies = cookieMap[cookie.domain].orEmpty()
val index = val index =
cookies.indexOfFirst { cookies.indexOfFirst {
@@ -196,12 +196,12 @@ class PersistentCookieStore(
private fun Cookie.hasExpired() = System.currentTimeMillis() >= expiresAt private fun Cookie.hasExpired() = System.currentTimeMillis() >= expiresAt
private fun HttpCookie.toCookie() = private fun HttpCookie.toCookie(urlDomain: String?): Cookie? {
Cookie return Cookie
.Builder() .Builder()
.name(name) .name(name)
.value(value) .value(value)
.domain(domain.removePrefix(".")) .domain((domain ?: urlDomain ?: return null).removePrefix("."))
.path(path ?: "/") .path(path ?: "/")
.also { .also {
if (maxAge != -1L) { if (maxAge != -1L) {
@@ -215,10 +215,11 @@ class PersistentCookieStore(
if (isHttpOnly) { if (isHttpOnly) {
it.httpOnly() it.httpOnly()
} }
if (!domain.startsWith('.')) { if (domain != null && !domain.startsWith('.')) {
it.hostOnlyDomain(domain.removePrefix(".")) it.hostOnlyDomain(domain.removePrefix("."))
} }
}.build() }.build()
}
private fun Cookie.toHttpCookie(): HttpCookie { private fun Cookie.toHttpCookie(): HttpCookie {
val it = this val it = this