Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Parse passwords with arbitrary colons #3201

Merged
merged 6 commits into from
Dec 25, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,18 @@
package zio.http.headers

import java.net.URI
import java.util.Base64

import zio.Scope
import zio.test._

import zio.http.Header.Authorization
import zio.http.Header.Authorization.Digest
import zio.http.Header.Authorization.{Basic, Digest}
import zio.http.ZIOHttpSpec

object AuthorizationSpec extends ZIOHttpSpec {
private def encodeCredentials(username: String, password: String): String =
Base64.getEncoder.encodeToString(s"$username:$password".getBytes)

override def spec: Spec[TestEnvironment with Scope, Any] =
suite("Authorization header suite")(
Expand Down Expand Up @@ -104,5 +107,15 @@ object AuthorizationSpec extends ZIOHttpSpec {
val auth = Authorization.parse("Basic not-base64")
assertTrue(auth.isLeft)
},
test("should parse valid Basic Authorization header") {
val encodedHeader = encodeCredentials("user", "pass")
val result = Authorization.parse(s"Basic $encodedHeader")
assertTrue(result.isRight) && assertTrue(result.toOption.get == Basic("user", "pass"))
},
test("should parse header with multiple colons in password") {
val encodedHeader = encodeCredentials("user", "pass:with:colon")
val result = Authorization.parse(s"Basic $encodedHeader")
assertTrue(result.isRight) && assertTrue(result.toOption.get == Basic("user", "pass:with:colon"))
},
)
}
11 changes: 8 additions & 3 deletions zio-http/shared/src/main/scala/zio/http/Header.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1088,9 +1088,14 @@ object Header {

private def parseBasic(value: String): Either[String, Authorization] = {
try {
val partsOfBasic = new String(Base64.getDecoder.decode(value)).split(":")
if (partsOfBasic.length == 2) {
Right(Basic(partsOfBasic(0), Secret(partsOfBasic(1))))
val decoded = new String(Base64.getDecoder.decode(value))
val indexOfColon = decoded.indexOf(":")

if (indexOfColon > 0) {
// Extract username as everything before the first ":", and password as everything after
val username = decoded.substring(0, indexOfColon)
val password = decoded.substring(indexOfColon + 1)
Right(Basic(username, Secret(password)))
} else {
Left("Basic Authorization header value is not in the format username:password")
}
Expand Down
Loading