Post

Write Timing, Masking and Repair Filters in REST Assured

Write filters worth having in a real suite, covering timing every exchange, a log with IBANs and names masked, the built-in RequestLoggingFilter and ResponseLoggingFilter, and repairing a response with ResponseBuilder.

Write Timing, Masking and Repair Filters in REST Assured

The payments suite has three problems that no single test can solve. Nobody knows how long each request takes across the suite. The CI log for a failed payment test shows the customer’s name and IBAN to everyone with access to the build. And a legacy endpoint sends JSON with the content type text/plain, so REST Assured refuses to read its body. Each of these is a filter of a few lines. In this guide, you’ll write a timer, a log filter that masks personal data, and a filter that repairs a response.

Level: Advanced · Time: 25 minutes · Part of: Module 8: Filters and Extensibility, section 2

What You’ll Build

You’ll build a filter called MaskingLogFilter, and a test class called UsefulFiltersTest with four tests: a timer around every exchange, a log with names and IBANs masked, the built-in request logging filter writing to a stream you choose, and a filter that corrects a response’s content type.

The masked log of one payment looks like this, with each IBAN’s middle hidden and each name replaced:

1
2
3
> POST http://localhost:59879/api/v1/payments {"debtorName": "***", "debtorIban": "NL91**********4300",
 "creditorName": "***", "creditorIban": "NL69**********6789", "amount": "42.00"}
< 201 {"debtorName":"***","debtorIban":"NL91**********4300","creditorName":"***","creditorIban":"NL69**********6789","amount":"42.00","paymentId":"pmt-1","status":"RCVD","createdAt":"2026-11-22T07:12:13.574804Z"}

When you’re done, Maven reports four passing tests:

1
2
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Measure every exchange.
  • Log without personal data.
  • Repair a response.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: create UsefulFiltersTest in a new section_02 package next to the class from the previous section, and follow every heading below.
  • Skip ahead: open the finished class (UsefulFiltersTest.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 Write Request and Response Filters in REST Assured.

Out of scope: this guide uses the signing filter without explaining it; Sign Requests With HTTP Message Signatures in REST Assured builds it. It also doesn’t cover parsers, the lighter fix for a wrong content type, which Use Parsers and Failure Listeners in REST Assured teaches.

Understand Useful Filters

The problem. Some needs span the whole suite and don’t belong in any one test. Timing a request inside each test repeats the same lines everywhere. log() writes bodies as they are, and payment bodies are full of names and IBANs, which are personal data under the GDPR; blacklistHeader(..) hides headers, but doesn’t touch bodies. And when an API you can’t change sends a wrong header, every test that reads the body fails for the same reason.

The concept. A filter is worth writing when something must happen for many requests. Three kinds come up again and again:

KindWhat the filter doesExample in this guide
MeasuringRecords something about each exchange, around context.next(..)A timer
LoggingWrites each exchange, with control over what and whereMaskingLogFilter, RequestLoggingFilter
RepairingReturns a corrected copy of the responseA content-type fix with ResponseBuilder

When to use each. Measure and log in a filter whenever many tests need the same record. Repair a response only when the API can’t be fixed, and say so in the code, because the repair hides what the API really sent.

Write suite-wide behaviour once, in a filter, and keep it honest about what it hides.

Meet the API Under Test

The tests use two endpoints of SignedPaymentsApi:

RequestRules
POST /api/v1/payments, JSONNeeds an X-Correlation-Id and a valid signature; answers 201 with the payment
GET /api/v1/legacy/fx-ratesNo rules; answers JSON exchange rates with the content type text/plain

Every test posts the same payment, with two names and two IBANs:

1
2
{"debtorName": "Anna de Vries", "debtorIban": "NL91ABNA0417164300",
 "creditorName": "Jan Jansen", "creditorIban": "NL69INGB0123456789", "amount": "42.00"}

The legacy endpoint answers {"base":"EUR","rates":{"GBP":0.85,"USD":1.09,"SEK":11.42}}. An unsigned payment gets 401 with WWW-Authenticate: Signature error="The request is not signed".

Your tests check these values:

  • How many exchanges the timer recorded, and how long they took.
  • What the log contains, and what it doesn’t.
  • The repaired content type, and the base and rates values it lets you read.

Measure Every Exchange

Set Up the Test Class

Goal: create the test class with the payment, the API and a helper that signs requests.

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
package com.javanibble.module_08.section_02;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.javanibble.module_08.support.CorrelationIdFilter;
import com.javanibble.module_08.support.HttpMessageSignatureFilter;
import com.javanibble.module_08.support.MaskingLogFilter;
import com.javanibble.signing.SignedPaymentsApi;

import io.restassured.builder.ResponseBuilder;
import io.restassured.filter.Filter;
import io.restassured.filter.log.LogDetail;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

class UsefulFiltersTest {

    private static final String PAYMENT = """
        {"debtorName": "Anna de Vries", "debtorIban": "NL91ABNA0417164300",
         "creditorName": "Jan Jansen", "creditorIban": "NL69INGB0123456789", "amount": "42.00"}""";

    private static SignedPaymentsApi api;

    @BeforeAll
    static void startApi() {
        api = SignedPaymentsApi.start();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    private static RequestSpecification signedApi() {
        return given().baseUri(api.baseUri()).port(api.port())
            .filter(new CorrelationIdFilter())
            .filter(new HttpMessageSignatureFilter(SignedPaymentsApi.TPP_KEY_ID, SignedPaymentsApi.TPP_SECRET));
    }
}

What’s happening:

  • signedApi() adds the CorrelationIdFilter from the previous section, and HttpMessageSignatureFilter, which signs each request with the test key.
  • HttpMessageSignatureFilter is already in the module’s support package. If you’re building step by step, copy HttpMessageSignatureFilter.java from the repository; the next section explains how it works.

Checkpoint: the class doesn’t compile yet, because MaskingLogFilter doesn’t exist. You’ll write it after the first test; until then, comment out its import.

Time Every Exchange

Goal: measure how long each exchange takes, without a line of timing code in the test’s request.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
void timeEveryExchange() {
    List<Duration> timings = new ArrayList<>();
    Filter timer = (request, responseSpec, context) -> {
        long start = System.nanoTime();
        Response response = context.next(request, responseSpec);
        timings.add(Duration.ofNanos(System.nanoTime() - start));
        return response;
    };

    signedApi().filter(timer).contentType(ContentType.JSON).body(PAYMENT).when().post("/api/v1/payments")
        .then().statusCode(201);

    assertEquals(1, timings.size());
    assertTrue(timings.getFirst().compareTo(Duration.ofSeconds(5)) < 0);
}

What’s happening:

  • The timer reads the clock, calls context.next(..), and records the difference, so it measures everything after it: the signing filter, which runs last, and the network.
  • The test checks that one exchange was recorded, and that it took less than five seconds.
  • In a real suite, the timings could go to a report that shows the slowest endpoints.

Checkpoint: run UsefulFiltersTest from your IDE. One test runs and passes.

Keep timing limits generous, as Check Every Part of an HTTP Response advised for time(..). A filter that fails on one slow request makes the suite flaky on a busy build agent. Record timings, and watch the trend rather than single values.

Log Without Personal Data

Write the Masking Log Filter

Goal: write a filter that logs each exchange with IBANs and names masked.

Create this class in the support package:

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
package com.javanibble.module_08.support;

import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;

import java.io.PrintStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class MaskingLogFilter implements Filter {

    private static final Pattern IBAN = Pattern.compile("\\b([A-Z]{2}[0-9]{2})([A-Z0-9]{7,26})([A-Z0-9]{4})\\b");
    private static final Pattern NAME_FIELD = Pattern.compile("(\"[A-Za-z]*[Nn]ame\"\\s*:\\s*\")([^\"]*)(\")");

    private final PrintStream out;

    public MaskingLogFilter(PrintStream out) {
        this.out = out;
    }

    @Override
    public Response filter(FilterableRequestSpecification request, FilterableResponseSpecification responseSpec,
                           FilterContext context) {
        Object body = request.getBody();
        out.println("> " + request.getMethod() + " " + request.getURI() + (body == null ? "" : " " + mask(body.toString())));
        Response response = context.next(request, responseSpec);
        out.println("< " + response.statusCode() + " " + mask(response.asString()));
        return response;
    }

    static String mask(String text) {
        Matcher iban = IBAN.matcher(text);
        String masked = iban.replaceAll(m -> m.group(1) + "*".repeat(m.group(2).length()) + m.group(3));
        return NAME_FIELD.matcher(masked).replaceAll("$1***$3");
    }
}

What’s happening:

  • Before context.next(..), the filter writes the method, the URI and the masked request body; after it, the status and the masked response body.
  • IBANs keep their country code, check digits and last four characters, so a reader can still tell accounts apart.
  • The value of any field whose key ends in name or Name becomes ***. Everything else stays readable.
  • The filter writes to the PrintStream it’s given, so a test can capture the log, and a suite can send it to a file.

Checkpoint: put the MaskingLogFilter import back. The project compiles, and the timing test still passes.

Prove the Log Is Masked

Goal: capture the log of a payment, and check that the personal data is gone and the rest is there.

Add this test to UsefulFiltersTest:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
void logWithPersonalDataMasked() {
    ByteArrayOutputStream log = new ByteArrayOutputStream();

    signedApi()
        .filter(new MaskingLogFilter(new PrintStream(log, true, StandardCharsets.UTF_8)))
        .contentType(ContentType.JSON)
        .body(PAYMENT)
    .when()
        .post("/api/v1/payments")
    .then()
        .statusCode(201);

    String logged = log.toString(StandardCharsets.UTF_8);
    assertTrue(logged.contains("NL91**********4300"), logged);
    assertFalse(logged.contains("NL91ABNA0417164300"), logged);
    assertFalse(logged.contains("Anna de Vries"), logged);
    assertTrue(logged.contains("\"amount\""), logged);           // everything else stays readable
}

What’s happening:

  • The log goes to a ByteArrayOutputStream, so the test can read it.
  • The test checks both sides: the masked IBAN is there, the real IBAN and the name aren’t, and the amount is still readable.
  • Each assert.. passes the log as its message, so a failure shows what was written.

Checkpoint: run the class again. Two tests pass.

Regular-expression masking is a safety net, not a guarantee. In a check with the same filter, a name in a free-text field ("remittance": "Rent for Anna de Vries"), an IBAN with spaces (NL91 ABNA 0417 1643 00) and a lowercase IBAN all reached the log unmasked. Keep CI logs short-lived as well.

Use the Built-In Logging Filters

Goal: send REST Assured’s own request log to a stream you choose.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void theBuiltInLoggingFiltersWriteWhereYouWant() {
    // RequestLoggingFilter and ResponseLoggingFilter are what log() uses; as filters they can go in a spec.
    ByteArrayOutputStream log = new ByteArrayOutputStream();

    given().baseUri(api.baseUri()).port(api.port())
        .filter(new RequestLoggingFilter(LogDetail.METHOD, new PrintStream(log, true, StandardCharsets.UTF_8)))
    .when()
        .get("/api/v1/legacy/fx-rates");

    assertTrue(log.toString(StandardCharsets.UTF_8).contains("GET"));
}

What’s happening:

  • RequestLoggingFilter and ResponseLoggingFilter are the filters behind log().
  • As filters, they take a LogDetail and a PrintStream. LogDetail.METHOD writes one line, Request method: GET.
  • They can go in a specification, so every request is logged in the same way to the same place.

Checkpoint: run the class again. Three tests pass.

A logging filter logs the request as it is when the filter runs. The signing filter runs last, so a RequestLoggingFilter with LogDetail.HEADERS added to signedApi() logs Accept, X-Correlation-Id and Content-Type, but not the signature headers that were sent. Mind the order when you need the final request in the log.

Repair a Response

Hand Back a Corrected Copy

Goal: give REST Assured a copy of the legacy response with the right content type.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
void repairAResponseWithResponseBuilder() {
    // The legacy endpoint sends JSON as text/plain, so body paths can't read it. A filter can hand REST Assured
    // a corrected copy of the response. Section 5 shows the lighter fix for this case: a parser.
    Filter fixContentType = (request, responseSpec, context) -> {
        Response response = context.next(request, responseSpec);
        return new ResponseBuilder().clone(response).setContentType(ContentType.JSON).build();
    };

    given().baseUri(api.baseUri()).port(api.port())
        .filter(fixContentType)
    .when()
        .get("/api/v1/legacy/fx-rates")
    .then()
        .contentType(ContentType.JSON)
        .body("base", equalTo("EUR"))
        .body("rates.GBP", equalTo(0.85f));
}

What’s happening:

  • Without the fix, body("base", ..) throws IllegalStateException: Expected response body to be verified as JSON, HTML or XML but content-type 'text/plain' is not supported out of the box.
  • new ResponseBuilder().clone(response) copies the status, headers and body, and setContentType(..) changes the one thing that’s wrong.
  • The filter returns the copy, so every check after it sees application/json and can read the body.

Checkpoint: run the class again. All four tests pass.

A repaired response hides the API’s real content type, so contentType(..) no longer tells the truth. Repair only what you can’t get fixed, and leave a comment saying why. For a wrong content type, a parser is the lighter fix, because it leaves the response alone.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-08 -Dtest=UsefulFiltersTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_08.section_02.UsefulFiltersTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.442 s -- in com.javanibble.module_08.section_02.UsefulFiltersTest
[INFO]
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In repairAResponseWithResponseBuilder, delete the .filter(fixContentType) line and run the command again. You should see a result similar to the following:

1
2
3
[ERROR] Failures:
[ERROR]   UsefulFiltersTest.repairAResponseWithResponseBuilder:123 1 expectation failed.
Expected content-type "JSON" doesn't match actual content-type "text/plain".

Without the filter, the test sees the API’s real content type, and the first check fails before any body path runs. That’s the content type the repair hides from every other check.

Put the .filter(..) line back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
401 with Signature error="The request is not signed"The request was sent without HttpMessageSignatureFilterStart from signedApi()
Names or IBANs appear in the logThey’re in a free-text field, have spaces, or are lowercaseExtend the patterns, or don’t log that body
A logged request lacks headers that were sentThe logging filter ran before the filter that added themGive the logging filter a later order, or log the response side
content-type 'text/plain' is not supported out of the boxThe API sends JSON with the wrong content typeRepair the response in a filter, or register a parser

Try It Yourself

Exercise 1: Record What Was Sent

Add a test called recordWhatWasSent. Write a lambda filter that adds the method and path of each request, such as POST /api/v1/payments, to a list. Post the payment with signedApi() and get the legacy rates, both with the filter, and check that the list holds both entries in order.

Hint

request.getMethod() gives the method, and request.getDerivedPath() gives the path without the base URI and port. Record before context.next(..).

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void recordWhatWasSent() {
    List<String> sent = new ArrayList<>();
    Filter recorder = (request, responseSpec, context) -> {
        sent.add(request.getMethod() + " " + request.getDerivedPath());
        return context.next(request, responseSpec);
    };

    signedApi().filter(recorder).contentType(ContentType.JSON).body(PAYMENT).when().post("/api/v1/payments")
        .then().statusCode(201);
    given().baseUri(api.baseUri()).port(api.port()).filter(recorder).when().get("/api/v1/legacy/fx-rates")
        .then().statusCode(200);

    assertEquals(List.of("POST /api/v1/payments", "GET /api/v1/legacy/fx-rates"), sent);
}

Exercise 2: Log Every Request in a Specification

Add a test called logEveryRequestInASpecification. Build a specification with the base URI and port, a RequestLoggingFilter with LogDetail.URI, and a ResponseLoggingFilter with LogDetail.STATUS, both writing to the same stream. Get the legacy rates with it, and check that the log contains the path and 200.

Hint

Create one PrintStream and pass it to both filters with addFilter(..). You need imports for RequestSpecBuilder and ResponseLoggingFilter.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
void logEveryRequestInASpecification() {
    ByteArrayOutputStream log = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(log, true, StandardCharsets.UTF_8);
    RequestSpecification spec = new RequestSpecBuilder()
        .setBaseUri(api.baseUri()).setPort(api.port())
        .addFilter(new RequestLoggingFilter(LogDetail.URI, out))
        .addFilter(new ResponseLoggingFilter(LogDetail.STATUS, out))
        .build();

    given(spec).when().get("/api/v1/legacy/fx-rates").then().statusCode(200);

    String logged = log.toString(StandardCharsets.UTF_8);
    assertTrue(logged.contains("/api/v1/legacy/fx-rates"), logged);
    assertTrue(logged.contains("200"), logged);
}

Add these imports to the class:

1
2
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.filter.log.ResponseLoggingFilter;

The log holds two lines: Request URI: http://localhost:<port>/api/v1/legacy/fx-rates and HTTP/1.1 200 OK.

Summary

You built MaskingLogFilter, which logs each exchange with names and IBANs hidden, and UsefulFiltersTest, which times an exchange, proves the log is masked, sends the built-in request log to a stream, and repairs a response’s content type. The CI log of a payment no longer shows whose money it was.

  • A timing filter measures around context.next(..), so it covers the later filters and the network.
  • blacklistHeader(..) hides headers only; masking personal data in bodies needs a filter like MaskingLogFilter.
  • Regular-expression masking is a safety net: free-text fields and unusual formats get through.
  • RequestLoggingFilter and ResponseLoggingFilter are the filters behind log(), and take their own LogDetail and PrintStream.
  • ResponseBuilder().clone(..) repairs a response, but hides the original, so prefer a parser where one fits.

Here are the commands you used in this guide:

1
mvn test -pl module-08 -Dtest=UsefulFiltersTest

What’s Next

Next: continue with Sign Requests With HTTP Message Signatures in REST Assured, which builds the HttpMessageSignatureFilter this guide used, and shows why it must run last.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.