Skip to content

Commit c8e2ed8

Browse files
authored
Merge pull request #187 from fgstewart/proxy-header-fix
Parse host:port in host header for proxied connections
2 parents e37b68c + 64e00de commit c8e2ed8

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

src/main/kotlin/no/nav/security/mock/oauth2/http/OAuth2HttpRequest.kt

+7-2
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import no.nav.security.mock.oauth2.http.RequestType.WELL_KNOWN
3333
import no.nav.security.mock.oauth2.missingParameter
3434
import okhttp3.Headers
3535
import okhttp3.HttpUrl
36+
import java.net.URI
3637

3738
data class OAuth2HttpRequest(
3839
val headers: Headers,
@@ -109,11 +110,15 @@ data class OAuth2HttpRequest(
109110
val proto = this.headers["x-forwarded-proto"]
110111
val port = this.headers["x-forwarded-port"]
111112
return if (hostheader != null && proto != null) {
113+
val hostUri = URI(null, hostheader, null, null, null).parseServerAuthority()
114+
val hostFromHostHeader = hostUri.host
115+
val portFromHostHeader = hostUri.port
116+
112117
HttpUrl.Builder()
113118
.scheme(proto)
114-
.host(hostheader)
119+
.host(hostFromHostHeader)
115120
.apply {
116-
port?.toInt()?.let { port(it) }
121+
port?.toInt()?.let { port(it) } ?: port(portFromHostHeader)
117122
}
118123
.encodedPath(originalUrl.encodedPath)
119124
.query(originalUrl.query).build()

src/test/kotlin/no/nav/security/mock/oauth2/http/OAuth2HttpRequestTest.kt

+28
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,34 @@ internal class OAuth2HttpRequestTest {
2828
originalUrl = "http://localhost:8080/mypath?query=1".toHttpUrl()
2929
)
3030
req2.proxyAwareUrl().toString() shouldBe "https://fakedings.nais.io:444/mypath?query=1"
31+
32+
// host header has host:port and x-forwarded-port is set
33+
val req3 = OAuth2HttpRequest(
34+
headers = Headers.headersOf(
35+
"host",
36+
"fakedings.nais.io:666",
37+
"x-forwarded-proto",
38+
"https",
39+
"x-forwarded-port",
40+
"444"
41+
),
42+
method = "GET",
43+
originalUrl = "http://localhost:8080/mypath?query=1".toHttpUrl()
44+
)
45+
req3.proxyAwareUrl().toString() shouldBe "https://fakedings.nais.io:444/mypath?query=1"
46+
47+
// host header has host:port and no x-forwarded-port
48+
val req4 = OAuth2HttpRequest(
49+
headers = Headers.headersOf(
50+
"host",
51+
"fakedings.nais.io:666",
52+
"x-forwarded-proto",
53+
"https"
54+
),
55+
method = "GET",
56+
originalUrl = "http://localhost:8080/mypath?query=1".toHttpUrl()
57+
)
58+
req4.proxyAwareUrl().toString() shouldBe "https://fakedings.nais.io:666/mypath?query=1"
3159
}
3260

3361
@Test

0 commit comments

Comments
 (0)