Skip to content

Commit e761f86

Browse files
authored
Merge pull request #4528 from guardian/an/treat-501-as-400
add custom error handler to suppress 501 alarms
2 parents 2cb2766 + 71167f3 commit e761f86

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

common-lib/src/main/resources/application.conf

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ play {
1717
assets.defaultCache="public, max-age=60"
1818
}
1919

20+
pekko.http.server.parsing.error-handler = "com.gu.mediaservice.lib.play.UnknownMethodParsingErrorHandler$"
21+
2022
es {
2123
cluster: media-service
2224
port: 9300
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.gu.mediaservice.lib.play
2+
3+
import com.gu.mediaservice.lib.logging.GridLogging
4+
import org.apache.pekko.event.LoggingAdapter
5+
import org.apache.pekko.http.{DefaultParsingErrorHandler, ParsingErrorHandler}
6+
import org.apache.pekko.http.scaladsl.model.{ErrorInfo, HttpResponse, StatusCode, StatusCodes}
7+
import org.apache.pekko.http.scaladsl.settings.ServerSettings
8+
9+
import scala.annotation.unused
10+
11+
/*
12+
Coerces responses from Pekko in response to unknown HTTP methods from 501 to 400.
13+
Technically HTTP spec requires 501s in this case, but this allows external parties
14+
to spam our 5xx alarms with silly requests. We're comfortable treating these as "Bad
15+
requests" instead.
16+
*/
17+
@unused
18+
object UnknownMethodParsingErrorHandler extends ParsingErrorHandler with GridLogging {
19+
override def handle(
20+
status: StatusCode,
21+
error: ErrorInfo,
22+
log: LoggingAdapter,
23+
settings: ServerSettings
24+
): HttpResponse = {
25+
if (status == StatusCodes.NotImplemented && error.summary == "Unsupported HTTP method") {
26+
logger.warn(s"Client attempted to use unknown HTTP method '${error.detail}'. Returning 400 instead of 501.")
27+
HttpResponse(StatusCodes.BadRequest)
28+
} else {
29+
DefaultParsingErrorHandler.handle(status, error, log, settings)
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)