Skip to content

Commit 589ea9b

Browse files
committed
fix: not responding with 204 on OPTIONS request
1 parent 809c8dd commit 589ea9b

2 files changed

Lines changed: 21 additions & 17 deletions

File tree

src/main/kotlin/net/ccbluex/netty/http/HttpConductor.kt

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,13 @@ internal suspend fun HttpServer.processRequestContext(context: RequestContext) =
4646
return@runCatching httpBadRequest("Incomplete request")
4747
}
4848

49-
val (node, params, remaining) = routeController.processPath(context.path, method) ?:
50-
return@runCatching httpNotFound(context.path, "Route not found")
51-
5249
if (method == HttpMethod.OPTIONS) {
5350
return@runCatching httpNoContent()
5451
}
5552

53+
val (node, params, remaining) = routeController.processPath(context.path, method) ?:
54+
return@runCatching httpNotFound(context.path, "Route not found")
55+
5656
logger.debug("Found destination {}", node)
5757
val requestObject = RequestObject(
5858
uri = context.uri,

src/main/kotlin/net/ccbluex/netty/http/middleware/CorsMiddleware.kt

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -34,26 +34,30 @@ class CorsMiddleware(
3434
override fun invoke(context: RequestContext, response: FullHttpResponse): FullHttpResponse {
3535
val httpHeaders = response.headers()
3636
val requestOrigin = context.headers[HttpHeaderNames.ORIGIN]
37-
38-
if (allowedOrigins.contains("*")) {
39-
httpHeaders[HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN] = "*"
37+
val allowedOrigin = if (allowedOrigins.contains("*")) {
38+
"*"
4039
} else if (requestOrigin != null) {
41-
try {
42-
val uri = URI(requestOrigin)
43-
val host = uri.host
44-
if (allowedOrigins.contains(host) || allowedOrigins.contains(requestOrigin)) {
45-
httpHeaders[HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN] = requestOrigin
46-
} else {
47-
httpHeaders[HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN] = "null"
48-
}
49-
} catch (e: URISyntaxException) {
50-
httpHeaders[HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN] = "null"
40+
val host = try {
41+
URI(requestOrigin).host
42+
} catch (e: Exception) {
5143
logger.error("Invalid Origin header: $requestOrigin", e)
44+
null
45+
}
46+
47+
if (host != null && allowedOrigins.contains(host) || allowedOrigins.contains(requestOrigin)) {
48+
requestOrigin
49+
} else {
50+
null
5251
}
5352
} else {
54-
httpHeaders[HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN] = "null"
53+
null
5554
}
5655

56+
if (allowedOrigin == null) {
57+
logger.debug("CORS origin not allowed: $requestOrigin")
58+
return response
59+
}
60+
httpHeaders[HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN] = allowedOrigin
5761
httpHeaders[HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS] = allowedMethods.joinToString(", ")
5862
httpHeaders[HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS] = allowedHeaders.joinToString(", ")
5963
return response

0 commit comments

Comments
 (0)