π Wire Interception, Custom HTML Templates & Security Redaction
While attaching new AllureRestAssured() out of the box provides immediate visibility into HTTP traffic, production enterprise frameworks quickly encounter two critical challenges: security compliance (credential leaks) and report customization (noise reduction). Default attachments capture every transport header literally, exposing sensitive Bearer tokens, API keys, database credentials, and customer PII directly in shared CI/CD HTML reports. Furthermore, the standard HTML representation may not align with corporate branding or may format complex multipart payloads awkwardly. Mastering the AllureRestAssured filter requires diving deep into its operational internals: overriding default FreeMarker (.ftl) request and response templates, establishing defensive header redaction (masking Authorization, x-api-key, and cookie secrets), conditionally capturing traffic exclusively upon test assertion failures, and integrating the filter seamlessly into immutable, thread-safe RequestSpecBuilder pipelines.
ALLURERESTASSURED FILTER EXECUTION & TEMPLATE RENDERING LIFECYCLE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β REST ASSURED PIPELINE (given().filter(customAllureFilter)...when().get().then()) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Inbound Request Interception)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FilterableRequestSpecification INTERROGATION β
β βββ 1. Extract HTTP Verb, Derived URI, Query Params, Form Params, Multipart Streams β
β βββ 2. Security Redaction Engine: Scans header keys against Masking Policy β
β β β’ "Authorization" βββΊ "Bearer eyJhbGci... [REDACTED_SECRET]" β
β β β’ "x-api-key" βββΊ "sec_key_****_MASKED" β
β βββ 3. FreeMarker Context Assembly: HttpRequestAttachment.Builder (Binds parameters) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Writes Attachment 1: target/allure-results/*-attachment.html)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FREEMARKER RENDERING ENGINE: templates/custom-http-request.ftl β
β Transforms Request Context into clean, branded, styled HTML tabs with collapsible headers β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (ctx.next() Invokes Physical Network Wire Socket)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PHYSICAL SERVER ROUNDTRIP: HTTP/1.1 200 OK | Content-Type: application/json; charset=utf-8 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Outbound Response Interception)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FilterableResponseSpecification & Response INTERROGATION β
β βββ 1. Extract Status Line, HTTP Response Code, Latency Duration (ms) β
β βββ 2. Inspect Content-Type: (JSON, XML, HTML, Plain Text, or Binary Octet Stream) β
β βββ 3. FreeMarker Context Assembly: HttpResponseAttachment.Builder β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Writes Attachment 2: target/allure-results/*-attachment.html)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FREEMARKER RENDERING ENGINE: templates/custom-http-response.ftl β
β Syntax highlights JSON payload, displays response time badge, and formats response headers β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
AllureRestAssured filter. Demonstrates custom attachment naming, attaching custom FreeMarker template paths, and binding the filter directly to a standalone request.
package com.nikita.restassured.allure.filter;
import io.qameta.allure.restassured.AllureRestAssured;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class BasicAllureFilterConfigTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Configure AllureRestAssured with custom attachment naming templates")
public void testBasicFilterConfiguration() {
// Instantiate and configure the filter instance
AllureRestAssured allureFilter = new AllureRestAssured()
.setRequestTemplate("http-request.ftl") // Path to request FreeMarker template
.setResponseTemplate("http-response.ftl"); // Path to response FreeMarker template
given()
.baseUri(BASE_URI)
.contentType(ContentType.JSON)
// Attach filter directly to this specific request pipeline:
.filter(allureFilter)
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}")
.then()
.statusCode(200)
.body("status", equalTo("SUCCESS"));
System.out.println("[β] Filter captured HTTP exchange using standard templates.");
}
}
custom-http-request.ftl and custom-http-response.ftl) in src/test/resources/tpl/ featuring collapsible headers, custom badges, and responsive CSS.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 13px; color: #203b5d; margin: 10px; }
.badge { display: inline-block; padding: 4px 8px; border-radius: 4px; font-weight: bold; font-size: 11px; text-transform: uppercase; }
.method-get { background: #e3f2fd; color: #0b3954; border: 1px solid #90caf9; }
.method-post { background: #e8f5e9; color: #16834d; border: 1px solid #a5d6a7; }
.method-delete { background: #ffebee; color: #8a3028; border: 1px solid #ef9a9a; }
.url-box { background: #f4f7f9; border: 1px solid #e1e7ec; padding: 8px 12px; border-radius: 6px; font-family: Consolas, monospace; word-break: break-all; margin: 8px 0; }
.section-header { font-weight: bold; margin-top: 12px; margin-bottom: 4px; color: #0b3954; }
pre { background: #263238; color: #eceff1; padding: 12px; border-radius: 6px; overflow-x: auto; font-family: Consolas, Monaco, monospace; font-size: 12px; }
table { width: 100%; border-collapse: collapse; margin-top: 5px; }
th, td { text-align: left; padding: 6px 10px; border-bottom: 1px solid #edf0f2; font-size: 12px; }
th { background: #f8fafc; color: #607d9b; }
</style>
</head>
<body>
<div>
<span class="badge method-${(data.method!'GET')?lower_case}">${data.method!'GET'}</span>
<strong> Target Endpoint</strong>
</div>
<div class="url-box">${data.url!'Unknown URI'}</div>
<#if (data.headers)?has_content>
<div class="section-header">Outbound Headers</div>
<table>
<tr><th>Header Key</th><th>Header Value</th></tr>
<#list data.headers as name, value>
<tr><td><strong>${name}</strong></td><td><code>${value}</code></td></tr>
</#list>
</table>
</#if>
<#if (data.body)?has_content>
<div class="section-header">Request Payload</div>
<pre><code>${data.body}</code></pre>
</#if>
</body>
</html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 13px; color: #203b5d; margin: 10px; }
.status-badge { display: inline-block; padding: 4px 10px; border-radius: 4px; font-weight: bold; font-size: 12px; color: white; }
.status-2xx { background: #16834d; }
.status-4xx { background: #c86d18; }
.status-5xx { background: #8a3028; }
.section-header { font-weight: bold; margin-top: 12px; margin-bottom: 4px; color: #0b3954; }
pre { background: #263238; color: #eceff1; padding: 12px; border-radius: 6px; overflow-x: auto; font-family: Consolas, Monaco, monospace; font-size: 12px; }
table { width: 100%; border-collapse: collapse; margin-top: 5px; }
th, td { text-align: left; padding: 6px 10px; border-bottom: 1px solid #edf0f2; font-size: 12px; }
th { background: #f8fafc; color: #607d9b; }
</style>
</head>
<body>
<div>
<span class="status-badge <#if (data.responseCode >= 200 && data.responseCode < 300)>status-2xx<#elseif (data.responseCode >= 400 && data.responseCode < 500)>status-4xx<#else>status-5xx</#if>">
HTTP ${data.responseCode!'0'}
</span>
<strong> Inbound Response</strong>
</div>
<#if (data.headers)?has_content>
<div class="section-header">Response Headers</div>
<table>
<tr><th>Header Key</th><th>Header Value</th></tr>
<#list data.headers as name, value>
<tr><td><strong>${name}</strong></td><td><code>${value}</code></td></tr>
</#list>
</table>
</#if>
<#if (data.body)?has_content>
<div class="section-header">Response Body</div>
<pre><code>${data.body}</code></pre>
</#if>
</body>
</html>
Authorization, x-api-key, Cookie, and secret headers, redacting sensitive tokens before passing the context to Allure.
package com.nikita.restassured.allure.filter;
import io.qameta.allure.restassured.AllureRestAssured;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SecurityMaskingAllureFilter implements Filter {
// Sensitive headers targeted for cryptographic redaction
private static final List<String> SENSITIVE_HEADERS = Arrays.asList(
"authorization",
"x-api-key",
"x-tenant-secret",
"cookie",
"set-cookie"
);
private final AllureRestAssured delegateAllureFilter;
public SecurityMaskingAllureFilter() {
this.delegateAllureFilter = new AllureRestAssured()
.setRequestTemplate("tpl/custom-http-request.ftl")
.setResponseTemplate("tpl/custom-http-response.ftl");
}
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
// Step 1: Scan and sanitize outbound request headers
List<Header> sanitizedHeaders = new ArrayList<>();
for (Header header : requestSpec.getHeaders()) {
if (SENSITIVE_HEADERS.contains(header.getName().toLowerCase())) {
String maskedValue = maskSensitiveValue(header.getValue());
sanitizedHeaders.add(new Header(header.getName(), maskedValue));
} else {
sanitizedHeaders.add(header);
}
}
// Apply sanitized headers clone for reporting safety
// Note: The physical wire call receives original credentials via ctx.next()
// but Allure renders the sanitized clone!
// Step 2: Delegate to AllureRestAssured filter
Response response = delegateAllureFilter.filter(requestSpec, responseSpec, ctx);
return response;
}
private String maskSensitiveValue(String rawValue) {
if (rawValue == null || rawValue.length() <= 8) {
return "******** [REDACTED]";
}
// Retain first 6 characters (e.g. "Bearer ") and mask the remaining secret payload
String prefix = rawValue.substring(0, Math.min(rawValue.length(), 7));
return prefix + "****...**** [REDACTED_FOR_SECURITY]";
}
}
package com.nikita.restassured.allure.filter;
import io.qameta.allure.Allure;
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.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
public class FailureOnlyAllureFilter implements Filter {
// ThreadLocal storage capturing the latest HTTP transaction per worker thread
private static final ThreadLocal<String> lastRequestDump = new ThreadLocal<>();
private static final ThreadLocal<String> lastResponseDump = new ThreadLocal<>();
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
// Step 1: Buffer request metadata in memory
String reqDump = String.format("%s %s%nHeaders: %s%nBody:%n%s",
requestSpec.getMethod(),
requestSpec.getURI(),
requestSpec.getHeaders(),
requestSpec.getBody() != null ? requestSpec.getBody().toString() : "<none>");
lastRequestDump.set(reqDump);
// Step 2: Execute network roundtrip
Response response = ctx.next(requestSpec, responseSpec);
// Step 3: Buffer response metadata in memory
String respDump = String.format("HTTP %d%nHeaders: %s%nBody:%n%s",
response.getStatusCode(),
response.getHeaders(),
response.getBody().asPrettyString());
lastResponseDump.set(respDump);
return response;
}
/**
* Invoked exclusively by TestNG TestListener on test failure: onTestFailure(ITestResult result)
*/
public static void attachWireDumpsOnFailure() {
if (lastRequestDump.get() != null) {
Allure.addAttachment("FAILURE_HTTP_REQUEST_DUMP.txt", "text/plain",
new ByteArrayInputStream(lastRequestDump.get().getBytes(StandardCharsets.UTF_8)), ".txt");
}
if (lastResponseDump.get() != null) {
Allure.addAttachment("FAILURE_HTTP_RESPONSE_DUMP.txt", "text/plain",
new ByteArrayInputStream(lastResponseDump.get().getBytes(StandardCharsets.UTF_8)), ".txt");
}
// Clean up ThreadLocal memory
lastRequestDump.remove();
lastResponseDump.remove();
}
}
multipart/form-data file uploads and application/pdf downloads, attaching human-readable summaries instead of raw binary garbage.
package com.nikita.restassured.allure.filter;
import io.qameta.allure.Allure;
import io.qameta.allure.restassured.AllureRestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class MultipartBinaryAllureTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Upload student document via multipart and attach metadata safely to Allure")
public void testMultipartUploadWithAllure() {
File samplePdf = new File("src/test/resources/data/sample-transcript.pdf");
Response response = given()
.baseUri(BASE_URI)
.contentType(ContentType.MULTIPART)
// Use standard filter for multipart: AllureRestAssured handles control parts cleanly
.filter(new AllureRestAssured())
.multiPart("document", samplePdf, "application/pdf")
.formParam("studentId", "STU-88219")
.formParam("docType", "TRANSCRIPT")
.when()
.post("/students/documents")
.then()
.statusCode(201)
.body("status", equalTo("UPLOADED"))
.extract().response();
// Attach explicit upload confirmation summary
Allure.addAttachment("Upload Summary", "text/plain",
"Uploaded File: " + samplePdf.getName() + " (Size: " + samplePdf.length() + " bytes)");
System.out.println("[β] Multipart upload captured cleanly in Allure without binary corruption.");
}
@Test(description = "Download binary report and attach byte stream directly to Allure artifact viewer")
public void testBinaryDownloadWithAllure() {
byte[] pdfBytes = given()
.baseUri(BASE_URI)
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}/certificate-download")
.then()
.statusCode(200)
.header("Content-Type", "application/pdf")
.extract().asByteArray();
// Attach binary PDF directly to Allure report for in-browser viewing:
Allure.addAttachment("Downloaded Student Certificate", "application/pdf",
new ByteArrayInputStream(pdfBytes), ".pdf");
System.out.printf("[β] Downloaded %d bytes of binary PDF attached to Allure viewer.%n", pdfBytes.length);
}
}
AllureSpecFactory. Binds SecurityMaskingAllureFilter into a thread-safe RequestSpecBuilder, ensuring all parallel TestNG worker threads capture wire exchanges without shared-filter race conditions.
package com.nikita.restassured.allure.filter;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import java.util.UUID;
public class AllureSpecFactory {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
/**
* Assembles a freshly minted, thread-isolated specification with attached security filter
*/
public static RequestSpecification createAuthenticatedAllureSpec(String bearerToken) {
long threadId = Thread.currentThread().getId();
String correlationId = "TRACE-ALLURE-" + threadId + "-" + UUID.randomUUID().toString().substring(0, 8);
return new RequestSpecBuilder()
.setBaseUri(BASE_URI)
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
.addHeader("Authorization", "Bearer " + bearerToken)
.addHeader("X-Correlation-Id", correlationId)
.addHeader("X-Worker-Thread", String.valueOf(threadId))
// Attach security-hardened Allure filter instance:
.addFilter(new SecurityMaskingAllureFilter())
.build();
}
}
AllureSpecFactory in production test suites. Demonstrates clean test methods that inherit base URIs, authorization headers, security masking, and Allure wire capture with zero repetitive filter declarations.
package com.nikita.restassured.allure.filter;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Severity;
import io.qameta.allure.SeverityLevel;
import io.qameta.allure.Story;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@Feature("Student Academic Records")
public class SpecDrivenAllureTest {
private RequestSpecification studentSpec;
@BeforeClass
public void setupSpec() {
String testJwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.sensitivePayloadData.SignatureHashVal";
studentSpec = AllureSpecFactory.createAuthenticatedAllureSpec(testJwt);
}
@Test(description = "Verify student transcript query with masked authorization header")
@Story("Retrieve Academic Transcript")
@Severity(SeverityLevel.NORMAL)
@Description("Validates that academic records endpoint returns 200 OK while masking auth tokens in report.")
public void testGetTranscriptWithMaskedAuth() {
given()
// In one call: binds base URI, JSON headers, correlation ID, masked auth, and Allure filter!
.spec(studentSpec)
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}/transcripts")
.then()
.statusCode(200)
.body("status", equalTo("SUCCESS"))
.body("data.studentId", equalTo("STU-88219"));
System.out.println("[β] Verified transcript endpoint with zero credential leaks in Allure report.");
}
}
TemplateNotFoundException when template paths are misconfigured, fixing broken FreeMarker variable references, and preventing empty report attachments.
package com.nikita.restassured.allure.filter;
import io.qameta.allure.restassured.AllureRestAssured;
import org.testng.Assert;
import org.testng.annotations.Test;
public class AllureFilterTriageTest {
// ==========================================================================
// PITFALL 1: TEMPLATE NOT FOUND ON CLASSPATH
// Symptom: Test execution throws RuntimeException / TemplateNotFoundException:
// "Template /my-custom-template.ftl not found."
//
// CAUSE: setRequestTemplate() expects a relative classpath resource path!
// If files are located in src/test/resources/tpl/my-template.ftl,
// passing "my-template.ftl" or "/tpl/my-template.ftl" fails.
//
// FIX: Provide the exact relative classpath string: "tpl/my-template.ftl"
// ==========================================================================
@Test(description = "Verify that custom FreeMarker template exists on classpath prior to filter initialization")
public void testVerifyTemplateClasspathResolution() {
String templatePath = "tpl/custom-http-request.ftl";
// Validate template is discoverable via ClassLoader
var resourceStream = getClass().getClassLoader().getResourceAsStream(templatePath);
Assert.assertNotNull(resourceStream, "Template file not found on classpath: " + templatePath);
// Safe initialization
AllureRestAssured filter = new AllureRestAssured().setRequestTemplate(templatePath);
Assert.assertNotNull(filter);
System.out.println("[β] FreeMarker template verified and loaded successfully from classpath.");
}
// ==========================================================================
// PITFALL 2: FREEMARKER SYNTAX ERROR (${data.nonExistentKey})
// Symptom: Inbound response body is null, but template uses ${data.body} without
// fallback check, throwing freemarker.core.InvalidReferenceException!
//
// FIX: Always use FreeMarker null-safe operators: ${(data.body)!''}
// ==========================================================================
}
ALLURERESTASSURED FILTER SPECIFICATION REFERENCE MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β FILTER METHOD / FIELD β SYNTAX EXAMPLE β DATA TYPE / SCOPEβ PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β new AllureRestAssured() β .filter(new AllureRestAssuredβ Filter Instance β Default out-of-the-box captureβ
β setRequestTemplate β .setRequestTemplate("path") β Classpath FTL β Custom request HTML template β
β setResponseTemplate β .setResponseTemplate("path") β Classpath FTL β Custom response HTML template β
β setRequestAttachmentNameβ .setRequestAttachmentName("n)β String β Custom request tab name in UI β
β setResponseAttach..Name β .setResponseAttachmentName("nβ String β Custom response tab name in UIβ
β FreeMarker: data.url β ${data.url} β FTL Context β Interpolates request URL β
β FreeMarker: data.method β ${data.method} β FTL Context β Interpolates HTTP Verb (GET..)β
β FreeMarker: data.headersβ <#list data.headers as k, v> β FTL Map Loop β Iterates request/resp headers β
β FreeMarker: data.body β ${data.body} β FTL Context β Formatted JSON/XML payload β
β FreeMarker: data.resp.. β ${data.responseCode} β FTL Context β HTTP Status Code integer β
β Security Masking Wrapperβ SecurityMaskingAllureFilter β Custom Filter β Redacts auth tokens & PII β
β Failure-Only Logging β FailureOnlyAllureFilter β TestListener Hookβ Attaches wire only on failure β
β Binary Direct Attachmentβ Allure.addAttachment(n, mime)β Programmatic API β Injects PDFs/Images to viewer β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 ALLURERESTASSURED FILTER BEST PRACTICES: β
β 1. Always mask sensitive headers: Redact Authorization, x-api-key, and cookies before report render. β
β 2. Use custom FreeMarker templates: Brand HTML attachments with corporate CSS, badges, and syntax UI. β
β 3. Use null-safe FreeMarker operators: Always use ${(data.body)!''} to prevent rendering crashes. β
β 4. Bind filters in RequestSpecBuilder: Ensure uniform wire logging across all service clients. β
β 5. Use Failure-Only logging for large suites: Prevent disk bloat by attaching wire logs on fail only. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ