Skip to content

Commit

Permalink
Redact sensitive headers
Browse files Browse the repository at this point in the history
  • Loading branch information
Stexxe committed Dec 24, 2024
1 parent 4ef4897 commit acf10cf
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,11 @@ public val Logging: ClientPlugin<LoggingConfig> = createClientPlugin("Logging",
}

for ((name, values) in headers.entries()) {
logger.log("$name: ${values.joinToString(separator = ", ")}")
if (sanitizedHeaders.find { sh -> sh.predicate(name) } == null) {
logger.log("$name: ${values.joinToString(separator = ", ")}")
} else {
logger.log("$name: ██")
}
}

if (!isBody() || request.method == HttpMethod.Get) {
Expand Down Expand Up @@ -203,7 +207,7 @@ public val Logging: ClientPlugin<LoggingConfig> = createClientPlugin("Logging",
suspend fun logResponseStdFormat(response: HttpResponse): HttpResponse {
if (isNone()) return response

var contentLength = response.headers[HttpHeaders.ContentLength]?.toLongOrNull()
val contentLength = response.headers[HttpHeaders.ContentLength]?.toLongOrNull()
val request = response.request
val duration = response.responseTime.timestamp - response.requestTime.timestamp

Expand All @@ -226,7 +230,11 @@ public val Logging: ClientPlugin<LoggingConfig> = createClientPlugin("Logging",
}

for ((name, values) in response.headers.entries()) {
logger.log("$name: ${values.joinToString(separator = ", ")}")
if (sanitizedHeaders.find { sh -> sh.predicate(name) } == null) {
logger.log("$name: ${values.joinToString(separator = ", ")}")
} else {
logger.log("$name: ██")
}
}

if (!isBody()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,46 @@ class NewFormatTest {
.assertNoMoreLogs()
}

@Test
fun headersAreRedacted() = runTest {
HttpClient(MockEngine) {
install(Logging) {
level = LogLevel.HEADERS
logger = log
standardFormat = true
sanitizeHeader { it == "SeNsItIvE" }
}

engine {
addHandler {
respondWithLength("", headers = Headers.build {
append("SeNsItIvE", "value")
append("Not-Sensitive", "value")
})
}
}
}.use { client ->
client.get("/") {
header("SeNsItIvE", "value")
header("Not-Sensitive", "value")
}
log.assertLogEqual("--> GET /")
.assertLogEqual("SeNsItIvE: ██")
.assertLogEqual("Not-Sensitive: value")
.assertLogEqual("Accept-Charset: UTF-8")
.assertLogEqual("Accept: */*")
.assertLogEqual("--> END GET")
.assertLogMatch(Regex("""<-- 200 OK / \(\d+ms\)"""))
.assertLogEqual("SeNsItIvE: ██")
.assertLogEqual("Not-Sensitive: value")
.assertLogEqual("Content-Length: 0")
.assertLogEqual("Content-Type: text/plain")
.assertLogEqual("<-- END HTTP")
.assertNoMoreLogs()

}
}

private fun MockRequestHandleScope.respondWithLength(): HttpResponseData {
return respond("", headers = Headers.build {
append("Content-Length", "0")
Expand Down

0 comments on commit acf10cf

Please sign in to comment.