Keep Secrets Out of REST Assured Logs
Mask Authorization and Cookie headers in every log with LogConfig.blacklistHeader(..), check that masking also applies when logging on failure, and test what was logged by sending the log to memory.
A failing account test prints its request with log().ifValidationFails(), as it should. Someone copies the CI log into a ticket, and the ticket now holds Authorization=Bearer test-token, readable by anyone with access to the tracker, for as long as the ticket lives. In this guide, you’ll mask secret headers in every REST Assured log, prove that masking also works when a test fails, and keep a passing suite’s log empty.
Level: Intermediate · Time: 15 minutes · Part of: Module 5: Reusable Specifications and Configuration, section 4
What You’ll Build
You’ll build a test class called SecretsInLogsTest with three tests. Each one sends a request with a bearer token, captures REST Assured’s log in memory, and checks what would have been printed: the token masked, masked again on failure, and nothing at all when the test passes.
The first test logs the request headers, with the token masked:
1
2
3
Headers: Authorization=[ BLACKLISTED ]
x-fapi-interaction-id=ddeee496-e80d-410f-8042-5d969b98a86b
Accept=*/*
When you’re done, Maven reports three passing tests:
1
2
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Mask headers in the log.
- Mask headers when logging on failure.
- Log nothing when a test passes.
What You Need
- About 15 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can log requests and responses, including only on failure, as taught in Log REST Assured Requests and Responses, and apply a
RestAssuredConfig, from Configure Timeouts, Redirects and Charsets in REST Assured.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
SecretsInLogsTestin a newsection_04package next to the classes from the previous sections, and follow every heading below. - Skip ahead: open the finished class (
SecretsInLogsTest.java) and read along. You can run it at any time with the command in Run the Tests.
Get the code: if you haven’t cloned the examples repository yet, follow the steps in Build Reusable Request Specifications in REST Assured.
Out of scope: this guide doesn’t cover masking secrets in query strings, bodies or cookies; that needs a custom filter, taught in Module 8.
Understand Header Blacklisting
The problem. log() prints everything: the URL, the body and every header, including Authorization: Bearer .... CI logs are kept for months, copied into tickets and read by many people. A token in a log is a leaked credential, and a suite that logs one every time a test fails is leaking credentials on a schedule.
The concept. LogConfig controls how REST Assured logs. Two of its settings matter here:
blacklistHeader(name, more..)prints the value of the named headers as[ BLACKLISTED ], in every request and response log. Names are case-insensitive, like header names.defaultStream(printStream)sends the log to a stream of your choice instead of standard out.
Blacklisting changes only the log. The real header is still sent, so the request works as before.
When to use it. Blacklist every header that carries a secret: Authorization almost always, plus API key headers such as X-API-Key. Put the LogConfig where every request gets it: in a shared request specification with setConfig(..), in a JUnit extension that builds specifications, or in RestAssured.config if your suite already sets global defaults. Combine it with ifValidationFails(), so a passing suite logs nothing at all.
Mask secrets in every log, and log only when a test fails.
Meet the API Under Test
The tests send requests to the Open Banking API from Build Reusable Request Specifications in REST Assured:
| Method | Path | Needs |
|---|---|---|
GET | /accounts | Authorization: Bearer test-token and an x-fapi-interaction-id |
A successful request returns the three accounts, starting with the one whose Nickname is "Main account".
Your tests check the log, not the API:
- The
Authorizationheader appears in the log, as[ BLACKLISTED ]. - The token,
test-token, appears nowhere in the log. - Other headers, such as
x-fapi-interaction-id, are still logged in full.
Mask Headers in the Log
Set Up the Test Class
Goal: create the test class with a fresh in-memory log for every test, and a config that masks Authorization and Cookie.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.javanibble.module_05.section_04;
import static io.restassured.RestAssured.given;
import static io.restassured.config.LogConfig.logConfig;
import static io.restassured.config.RestAssuredConfig.config;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.javanibble.openbanking.OpenBankingApi;
import io.restassured.config.RestAssuredConfig;
import io.restassured.filter.log.LogDetail;
import io.restassured.specification.RequestSpecification;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class SecretsInLogsTest {
private static final String TOKEN = "test-token";
private static OpenBankingApi api;
private ByteArrayOutputStream log;
private RestAssuredConfig loggingToMemory;
@BeforeAll
static void startApi() {
api = OpenBankingApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
@BeforeEach
void captureTheLog() {
log = new ByteArrayOutputStream();
loggingToMemory = config().logConfig(logConfig()
.defaultStream(new PrintStream(log, true, StandardCharsets.UTF_8))
.blacklistHeader("Authorization", "Cookie"));
}
private RequestSpecification openBanking() {
return given()
.config(loggingToMemory)
.baseUri(api.baseUri()).port(api.port()).basePath(OpenBankingApi.BASE_PATH)
.header("Authorization", "Bearer " + TOKEN)
.header("x-fapi-interaction-id", UUID.randomUUID().toString());
}
private String logged() {
return log.toString(StandardCharsets.UTF_8);
}
}
What’s happening:
@BeforeEachcreates a newByteArrayOutputStreamfor every test, so each test sees only its own log.defaultStream(..)sends the log there instead of standard out, andblacklistHeader(..)masksAuthorizationandCookie.openBanking()builds a request with the config, the token and an interaction id.logged()returns what would have been printed.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Capturing the log in memory is only for these tests: it lets them assert on what would have been printed. In your own suite, set
blacklistHeader(..)and leave the stream alone.
Check That the Token Is Masked
Goal: log the request headers, and prove that the token never reaches the log.
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void blacklistedHeadersAreMasked() {
openBanking()
.log().headers()
.when()
.get("/accounts")
.then()
.statusCode(200);
assertTrue(logged().contains("Authorization=[ BLACKLISTED ]"), logged());
assertFalse(logged().contains(TOKEN), logged());
assertTrue(logged().contains("x-fapi-interaction-id="), logged());
}
What’s happening:
- The first assertion proves the header is still in the log, so a reader knows it was sent.
- The second proves the token is nowhere in the log. This is the real security check.
- The third proves other headers are logged as usual, so the log stays useful.
- The
200status proves the real header still reached the server.
Checkpoint: run SecretsInLogsTest from your IDE. One test runs and passes.
Blacklisting masks headers only, and cookies aren’t headers in the request log. A cookie added with
cookie("session", "secret-session")is printed in full underCookies:bylog().all(), even with"Cookie"blacklisted. Log only the parts you need, such asLogDetail.HEADERS, or mask cookies with a filter.
Mask Headers When Logging on Failure
Fail a Check on Purpose
Goal: prove that masking also applies with ifValidationFails(), the most common logging set-up.
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void maskingAlsoAppliesWhenLoggingOnFailure() {
assertThrows(AssertionError.class, () ->
openBanking()
.log().ifValidationFails(LogDetail.HEADERS)
.when()
.get("/accounts")
.then()
.body("Data.Account[0].Nickname", equalTo("not the nickname")));
assertTrue(logged().contains("[ BLACKLISTED ]"), logged());
assertFalse(logged().contains(TOKEN), logged());
}
What’s happening:
- The nickname check fails on purpose, so
ifValidationFails(LogDetail.HEADERS)logs the request headers. assertThrows(..)catches the failure, so the test can check the log afterwards.- The token is still masked. This matters most, because a failure’s log is the one people read and share.
Checkpoint: run the class again. Two tests pass.
Blacklisting doesn’t reach the URL or the body. A token in a query parameter, such as
?access_token=.., is printed in the request URI, as inRequest URI: http://localhost:57631/test-support/landing?access_token=secret-in-url, and a password in a body is printed with the body. Keep secrets in headers, or mask the rest with a filter.
Log Nothing When a Test Passes
Log Only on Failure, on Both Sides
Goal: prove that a passing request with ifValidationFails() logs nothing at all.
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void nothingIsLoggedWhenTheTestPasses() {
openBanking()
.log().ifValidationFails()
.when()
.get("/accounts")
.then()
.log().ifValidationFails()
.statusCode(200);
assertTrue(logged().isEmpty(), logged());
}
What’s happening:
ifValidationFails()on the request and the response holds both logs back until a check fails.- Every check passes, so the log stays empty. Fewer logs means less to leak, even with masking.
Checkpoint: run the class again. All three tests pass.
Masking also works on responses, so blacklist response headers that carry secrets too, such as
Set-Cookieon a sign-in response. And avoidlog().all()in committed tests: it logs every request, even when the test passes.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-05 -Dtest=SecretsInLogsTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_05.section_04.SecretsInLogsTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.413 s -- in com.javanibble.module_05.section_04.SecretsInLogsTest
[INFO]
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In captureTheLog, change .blacklistHeader("Authorization", "Cookie") to .blacklistHeader("Cookie") and run the command again. You should see a result similar to the following:
1
2
3
4
5
[ERROR] Failures:
[ERROR] SecretsInLogsTest.blacklistedHeadersAreMasked:81 Headers: Authorization=Bearer test-token
x-fapi-interaction-id=a02a7e26-75b1-4e42-9efb-e7f6013fd2d0
Accept=*/*
==> expected: <true> but was: <false>
The failure message is the log itself, because every assertion passes logged() as its message, and it shows Authorization=Bearer test-token in full. That’s the leak these tests exist to catch: a refactoring that drops one header from the blacklist turns a test red instead of quietly printing tokens. maskingAlsoAppliesWhenLoggingOnFailure fails the same way.
Put "Authorization" back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| A token appears in a log | The header isn’t blacklisted, or the request doesn’t use the config | Add it to blacklistHeader(..), and share the config through a specification |
A cookie value appears under Cookies: | blacklistHeader("Cookie") doesn’t mask the request log’s cookie section | Log only LogDetail.HEADERS, or mask cookies with a filter |
A secret appears in the Request URI line | It was sent as a query parameter | Send it in a header, or mask it with a filter |
| The log is empty though you expected output | ifValidationFails() logs only when a check fails | Use log().headers() while you’re investigating |
Try It Yourself
Exercise 1: Blacklist in Lower Case
Header names are case-insensitive. Add a test called blacklistNamesIgnoreCase that builds its own config with blacklistHeader("authorization"), all lower case, logs the request headers of GET /accounts, and checks that the token isn’t in the log.
Hint
Build the config like captureTheLog does, with the same log stream, and pass it to the request with config(..) instead of using openBanking().
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
void blacklistNamesIgnoreCase() {
RestAssuredConfig lowerCase = config().logConfig(logConfig()
.defaultStream(new PrintStream(log, true, StandardCharsets.UTF_8))
.blacklistHeader("authorization"));
given()
.config(lowerCase)
.baseUri(api.baseUri()).port(api.port()).basePath(OpenBankingApi.BASE_PATH)
.header("Authorization", "Bearer " + TOKEN)
.header("x-fapi-interaction-id", UUID.randomUUID().toString())
.log().headers()
.when()
.get("/accounts")
.then()
.statusCode(200);
assertFalse(logged().contains(TOKEN), logged());
}
Exercise 2: Mask an API Key Through a Specification
Add a test called aSpecificationMasksEverySecret. Build a request specification with setConfig(..) whose log config writes to log and blacklists Authorization, Cookie and X-API-Key, and that adds the token and an X-API-Key: key-42 header. With it, send GET /accounts with log().all() on the request and the response. Check that neither the token nor the key is in the log, that the key’s header is logged as [ BLACKLISTED ], and that the response’s status line is in the log.
Hint
Use RequestSpecBuilder, as in Build Reusable Request Specifications in REST Assured. The interaction id still goes on the request, because it must be new every time.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Test
void aSpecificationMasksEverySecret() {
RequestSpecification spec = new RequestSpecBuilder()
.setBaseUri(api.baseUri()).setPort(api.port()).setBasePath(OpenBankingApi.BASE_PATH)
.setConfig(config().logConfig(logConfig()
.defaultStream(new PrintStream(log, true, StandardCharsets.UTF_8))
.blacklistHeader("Authorization", "Cookie", "X-API-Key")))
.addHeader("Authorization", "Bearer " + TOKEN)
.addHeader("X-API-Key", "key-42")
.build();
given(spec)
.header("x-fapi-interaction-id", UUID.randomUUID().toString())
.log().all()
.when()
.get("/accounts")
.then()
.log().all()
.statusCode(200);
assertFalse(logged().contains(TOKEN), logged());
assertFalse(logged().contains("key-42"), logged());
assertTrue(logged().contains("X-API-Key=[ BLACKLISTED ]"), logged());
assertTrue(logged().contains("HTTP/1.1 200 OK"), logged());
}
Add import io.restassured.builder.RequestSpecBuilder; to the class.
Summary
You built SecretsInLogsTest, which captures REST Assured’s log in memory and proves that the token is masked, masked again when a test fails, and not logged at all when a test passes. A ticket full of copied CI logs no longer holds a bearer token.
LogConfig.blacklistHeader(..)prints the named headers as[ BLACKLISTED ]in every request and response log; names are case-insensitive, and the real headers are still sent.- Masking also applies with
ifValidationFails(), when logs are most often read and shared. ifValidationFails()on both sides keeps a passing suite’s log empty, so there’s less to leak.- Blacklisting covers headers only: cookies under
Cookies:, query strings and bodies need a filter, or shouldn’t be logged. - Put the
LogConfigin a shared specification so every request gets it, and test the masking by capturing the log withdefaultStream(..).
Here are the commands you used in this guide:
1
mvn test -pl module-05 -Dtest=SecretsInLogsTest
What’s Next
Next: continue with Inject REST Assured Specifications With a JUnit Extension, which starts the API once per class and injects ready-made specifications into every test: a natural home for a log config like this one.
The code:
- The finished test class:
SecretsInLogsTest.java - The code and run commands for this module: Module 5 README
Go deeper:
- REST Assured Usage wiki, for
LogConfigand blacklisted headers. - OWASP Logging Cheat Sheet, for the data that must never be logged.
Related guides:
- Log REST Assured Requests and Responses, for every logging option, including
ifValidationFails(). - Module 8: Filters and Extensibility, for masking secrets outside headers with a filter.
