π Intercepting, Transforming, and Observing the Wire Protocol
In enterprise Java automation frameworks, treating HTTP calls as opaque black boxes causes severe diagnostic bottlenecks when test assertions fail inside headless CI/CD execution pipelines. Simply scattering verbose .log().all() statements across thousands of automated tests floods terminal buffers with gigabytes of unreadable plain text while leaking sensitive API keys, database passwords, and Bearer tokens into persistent server logs. The RestAssured Filter Interface provides a powerful interceptor mechanism modeled after the classic Chain of Responsibility pattern. By implementing custom filters, quality engineers can intercept active requests before wire transmission, dynamically inject correlation headers and HMAC signatures, sanitize and mask credentials, capture timing metrics, stream network logs only upon test assertion failures, and export structured attachments to Allure Reports and test management systems.
Filter interface.
RESTASSURED FILTER EXECUTION LIFECYCLE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β GIVEN: FilterChain Execution Starts β
β 1. RequestSpecification assembled: headers, params, body, auth β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Traverses filters in order of registration)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FILTER 1: SENSITIVE DATA MASKING & SANITIZATION β
β * Inspects headers: Masks 'Authorization: Bearer ****' and 'X-API-KEY: ****' β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β FILTER 2: DYNAMIC HEADER INJECTOR / CORRELATION FILTER β
β * Injects X-Correlation-ID: UUID and X-Timestamp before socket transmission β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β FILTER 3: TELEMETRY & LATENCY BENCHMARKING FILTER β
β * Records System.currentTimeMillis() immediately before calling ctx.next(req, res) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ ctx.next(requestSpec, responseSpec)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β HTTP WIRE TRANSMISSION (Apache HttpClient Socket Transport) β
β Request sent to remote server -> Server processes -> Response stream received β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Response unwinds backward through filters)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FILTER 3: Captures elapsed time: (End - Start) -> Asserts latency SLA threshold β
β FILTER 2: Passes unmodified response upward β
β FILTER 1: Conditionally logs request & response ONLY IF status code != expected β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β THEN: Assertion & Extraction Phase (.statusCode(200), .extract().as(POJO.class)) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
RequestLoggingFilter and ResponseLoggingFilter with specific log details (headers, cookies, params, body).
package com.nikitainfotech.api.filters;
import io.restassured.filter.log.LogDetail;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.filter.log.ResponseLoggingFilter;
import org.testng.annotations.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class BuiltInLoggingFiltersDemo {
private static final String BASE_URL = "https://jsonplaceholder.typicode.com";
@Test
public void testSelectiveLoggingFilters() {
// 1. Capture logs into an in-memory byte stream instead of polluting system stdout
ByteArrayOutputStream logStream = new ByteArrayOutputStream();
PrintStream customPrintStream = new PrintStream(logStream);
given()
.baseUri(BASE_URL)
// Log only URI and Headers on Request:
.filter(new RequestLoggingFilter(LogDetail.URI, customPrintStream))
.filter(new RequestLoggingFilter(LogDetail.HEADERS, customPrintStream))
// Log only Response Body and Status Line:
.filter(new ResponseLoggingFilter(LogDetail.STATUS, customPrintStream))
.filter(new ResponseLoggingFilter(LogDetail.BODY, customPrintStream))
.header("X-Client-App", "NikitaInfotechAutomation")
.when()
.get("/posts/1")
.then()
.statusCode(200)
.body("id", equalTo(1));
// Output captured stream to inspection buffer
String capturedLogs = logStream.toString();
System.out.println("Captured Log Output:\n" + capturedLogs);
}
}
logValidationErrors() or enableLoggingOfRequestAndResponseIfValidationFails() logs traffic ONLY when an assertion fails.
package com.nikitainfotech.api.filters;
import io.restassured.RestAssured;
import io.restassured.config.LogConfig;
import io.restassured.config.RestAssuredConfig;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class LogOnFailureConfiguration {
@BeforeClass
public void setupGlobalLoggingConfiguration() {
// Globally configure RestAssured to log ONLY on test assertion failures across all tests
RestAssured.config = RestAssuredConfig.config().logConfig(
LogConfig.logConfig()
.enableLoggingOfRequestAndResponseIfValidationFails()
.blacklistHeader("Authorization") // Automatically sanitize credentials
.blacklistHeader("X-API-KEY")
);
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
}
@Test
public void testPassingScenarioProducesZeroLogs() {
// This test passes: Console stays 100% clean, saving runner memory
given()
.header("Authorization", "Bearer sensitive-secret-token")
.when()
.get("/posts/1")
.then()
.statusCode(200);
}
@Test
public void testFailingScenarioDumpsDiagnosticTraffic() {
// This test intentionally fails: RestAssured automatically dumps full request/response!
given()
.header("Authorization", "Bearer sensitive-secret-token")
.when()
.get("/posts/1")
.then()
.statusCode(201); // Mismatch: Expected 201 Created, actual is 200 OK
}
}
Filter interface to intercept outgoing requests and dynamically inject enterprise distributed tracing headers (X-Correlation-ID, X-Request-Timestamp) without modifying test code.
package com.nikitainfotech.api.filters;
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.util.UUID;
public class CorrelationIdFilter implements Filter {
private static final String CORRELATION_HEADER = "X-Correlation-ID";
private static final String TIMESTAMP_HEADER = "X-Request-Timestamp";
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
// 1. Check if correlation ID already supplied; if absent, generate fresh UUID
if (!requestSpec.getHeaders().hasHeaderWithName(CORRELATION_HEADER)) {
String generatedCorrelationId = "REQ-" + UUID.randomUUID().toString();
requestSpec.header(CORRELATION_HEADER, generatedCorrelationId);
}
// 2. Inject current epoch timestamp header
requestSpec.header(TIMESTAMP_HEADER, String.valueOf(System.currentTimeMillis()));
// 3. Delegate to next filter in chain and execute HTTP wire call
Response response = ctx.next(requestSpec, responseSpec);
// 4. Verify server echoed the correlation ID back in response headers
String echoedId = response.getHeader(CORRELATION_HEADER);
if (echoedId != null) {
System.out.println("[+] Distributed Trace Confirmed: " + echoedId);
}
return response;
}
}
package com.nikitainfotech.api.filters;
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.util.regex.Pattern;
public class SecuritySanitizerFilter implements Filter {
private static final Pattern SENSITIVE_JSON_PATTERN = Pattern.compile(
"\"(password|client_secret|cvv|accessToken|pin)\"\\s*:\\s*\"([^\"]+)\"",
Pattern.CASE_INSENSITIVE
);
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
// Log sanitized representation of outgoing request
String targetUri = requestSpec.getURI();
String method = requestSpec.getMethod();
System.out.println("--------------------------------------------------");
System.out.println("[SECURE AUDIT] " + method + " " + targetUri);
// Mask Authorization Header if present
if (requestSpec.getHeaders().hasHeaderWithName("Authorization")) {
String authVal = requestSpec.getHeaders().getValue("Authorization");
String maskedAuth = authVal.length() > 12 ? authVal.substring(0, 7) + "********" : "********";
System.out.println(" βββ Header Authorization: " + maskedAuth);
}
// Mask Sensitive JSON Body Attributes in audit log
Object bodyObj = requestSpec.getBody();
if (bodyObj instanceof String) {
String sanitizedBody = SENSITIVE_JSON_PATTERN.matcher((String) bodyObj)
.replaceAll("\"$1\": \"[REDACTED-SECRET]\"");
System.out.println(" βββ Body Payload: " + sanitizedBody);
}
System.out.println("--------------------------------------------------");
// Proceed with unmodified request over the wire (server gets real credentials!)
return ctx.next(requestSpec, responseSpec);
}
}
package com.nikitainfotech.api.filters;
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;
public class PerformanceBenchmarkFilter implements Filter {
private final long maxAllowedSlaMs;
public PerformanceBenchmarkFilter(long maxAllowedSlaMs) {
this.maxAllowedSlaMs = maxAllowedSlaMs;
}
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
long startTime = System.currentTimeMillis();
// Dispatch request to server
Response response = ctx.next(requestSpec, responseSpec);
long elapsedTime = System.currentTimeMillis() - startTime;
String endpoint = requestSpec.getMethod() + " " + requestSpec.getURI();
System.out.println(String.format("[TIMER] %s -> %d ms (Status: %d)",
endpoint, elapsedTime, response.getStatusCode()));
// Enforce hard SLA assertion boundary
if (elapsedTime > maxAllowedSlaMs) {
System.err.println(String.format("β οΈ [SLA VIOLATION] %s exceeded budget! Target: %d ms, Actual: %d ms",
endpoint, maxAllowedSlaMs, elapsedTime));
}
return response;
}
}
AllureRestAssured filter. Automatically captures request headers, bodies, response status, and payloads as interactive attachments.
<!-- 1. MAVEN POM DEPENDENCY -->
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-rest-assured</artifactId>
<version>2.25.0</version>
<scope>test</scope>
</dependency>
// 2. JAVA TEST INTEGRATION
package com.nikitainfotech.api.tests;
import io.qameta.allure.restassured.AllureRestAssured;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class AllureReportingFilterTest {
@Test(description = "Verify student registration with full Allure network attachments")
public void testStudentRegistrationAllure() {
given()
.baseUri("https://jsonplaceholder.typicode.com")
// Attach AllureRestAssured filter: writes request and response files into allure-results
.filter(new AllureRestAssured()
.setRequestTemplate("http-request.ftl")
.setResponseTemplate("http-response.ftl"))
.contentType("application/json")
.body("{\"title\": \"API Masterclass\", \"userId\": 101}")
.when()
.post("/posts")
.then()
.statusCode(201)
.body("userId", equalTo(101));
}
}
401 Unauthorized responses, refreshes the expired token via an out-of-band call, updates the request header, and replays the original call automatically.
package com.nikitainfotech.api.filters;
import io.restassured.RestAssured;
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;
public class AutoTokenRefreshFilter implements Filter {
private static String currentBearerToken = "INITIAL_EXPIRED_MOCK_TOKEN";
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
// 1. Attach current token to outgoing request
requestSpec.header("Authorization", "Bearer " + currentBearerToken);
// 2. Dispatch request
Response response = ctx.next(requestSpec, responseSpec);
// 3. Detect 401 Unauthorized caused by token expiration
if (response.getStatusCode() == 401) {
System.out.println("[!] Detected 401 Unauthorized. Refreshing token via Auth Provider...");
// 4. Execute out-of-band token refresh request
currentBearerToken = acquireFreshOAuthToken();
System.out.println("[+] Token refreshed successfully. Replaying original request...");
// 5. Update request header with fresh token
requestSpec.replaceHeader("Authorization", "Bearer " + currentBearerToken);
// 6. Replay the request through the filter chain
response = ctx.next(requestSpec, responseSpec);
}
return response;
}
private synchronized String acquireFreshOAuthToken() {
// Real implementation calls: RestAssured.given().post("/oauth/token").extract().path("access_token")
return "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.FRESH_VALID_TOKEN_" + System.currentTimeMillis();
}
}
RequestSpecBuilder, mounting them to RestAssured.requestSpecification so all tests inherit logging and security rules.
package com.nikitainfotech.api.specs;
import com.nikitainfotech.api.filters.CorrelationIdFilter;
import com.nikitainfotech.api.filters.PerformanceBenchmarkFilter;
import com.nikitainfotech.api.filters.SecuritySanitizerFilter;
import io.qameta.allure.restassured.AllureRestAssured;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.BeforeSuite;
public class GlobalSpecSetup {
@BeforeSuite(alwaysRun = true)
public void configureGlobalFrameworkSpecifications() {
// Build unified RequestSpecification containing all enterprise filters
RequestSpecification globalSpec = new RequestSpecBuilder()
.setBaseUri("https://api.nikita-infotech.com")
.setBasePath("/v1")
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
// Register Filters in exact execution order:
.addFilter(new SecuritySanitizerFilter()) // 1. Sanitize & mask credentials
.addFilter(new CorrelationIdFilter()) // 2. Inject distributed tracing UUIDs
.addFilter(new PerformanceBenchmarkFilter(800)) // 3. Assert 800ms SLA budget
.addFilter(new AllureRestAssured()) // 4. Attach traffic to Allure reports
.build();
// Assign as default for all RestAssured calls across the entire test suite
RestAssured.requestSpecification = globalSpec;
System.out.println("[+] Global RestAssured RequestSpecification & Filters Initialized.");
}
}
RESTASSURED FILTERS CAPABILITIES & ARCHITECTURAL MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FILTER / METHOD β APPLIED SCOPE β PRIMARY PURPOSE & BEHAVIOR β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β RequestLoggingFilter β Request Pipeline β Logs URI, headers, parameters, and request body β
β ResponseLoggingFilter β Response Pipeline β Logs status line, headers, cookies, and payload β
β logValidationErrors() β LogConfig β Suppresses logs; prints ONLY on assertion failure β
β blacklistHeader("Auth") β LogConfig β Masks sensitive credentials with [BLACK-LISTED] β
β AllureRestAssured β Reporting Pipeline β Attaches request/response tabs to Allure HTML β
β Custom Filter (ctx.next)β Pre & Post Execution Chain β Modifies headers, measures SLA, handles re-auth β
β RequestSpecBuilder β Suite / Class Configuration β Registers filters globally across all test cases β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β TOP 5 RESTASSURED LOGGING & FILTER BEST PRACTICES: β
β 1. Never use .log().all() in CI: Floods build logs; use enableLoggingOfRequestAndResponseIfValidationFails() β
β 2. Mask authorization credentials: Use blacklistHeader() to keep secrets out of persistent logs. β
β 3. Inject correlation IDs via filters: Avoid manually adding X-Correlation-ID to every request. β
β 4. Track response SLAs: Measure System.currentTimeMillis() in a custom filter to catch regressions. β
β 5. Register filters centrally: Use RequestSpecBuilder in @BeforeSuite to maintain clean test classes. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ