Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A JAX-RS service accepts gzip-compressed request bodies. A security review flags a decompression bomb risk, and another review mentions BREACH for compressed HTTPS responses containing a CSRF token. Explain both risks and the mitigations.

A decompression bomb is a tiny gzip body that expands to gigabytes, so the service must limit both the compressed size and the decompressed size, check the ratio, and stream rather than buffer, typically with a counting stream in a ReaderInterceptor that rejects the request with 413. BREACH is a different attack: when an HTTPS response is compressed and contains both a secret such as a CSRF token and attacker-reflected input, the attacker can guess the secret byte by byte from changes in response size. We mitigate it by not compressing responses that hold secrets, masking tokens per request, separating secrets from reflected input, or adding length randomisation, and we document and test which endpoints may compress.

Why this question is asked

Compression saves bandwidth because it exploits redundancy, and both of these attacks exploit that same property. In one, the attacker sends us redundancy so extreme that a few kilobytes become gigabytes in our memory. In the other, the attacker uses the way compressed size depends on repeated text to read a secret through encryption. Interviewers ask this scenario because it checks whether we understand the mechanism of each attack well enough to choose mitigations instead of reciting names. In this answer, we will explain how a decompression bomb works, defend against it in JAX-RS, then explain BREACH step by step, go through its mitigations, and finish with documenting and testing the policy.

1How a Decompression Bomb Works

gzip replaces repeated data with short references to earlier data. A long run of identical bytes compresses to almost nothing: 10 GB of zeros fits in about 10 MB of gzip, a ratio of about 1000 to 1, and nested or crafted formats can do even better. If our service accepts Content-Encoding: gzip on request bodies and decompresses them without limits, an attacker sends a 10 MB request, which passes any limit on request size, and our JSON parser starts reading 10 GB. If the code buffers the body, the heap is exhausted; if it streams it, a request thread is busy for minutes. A few such requests at once take the service down.

The important insight is that a limit on the request size seen by the proxy or the container counts compressed bytes. The damage is done by decompressed bytes, which only our application sees.

2Defending With a Bounded ReaderInterceptor

A ReaderInterceptor wraps the entity input stream before the message body reader parses it, which is exactly where we need control. Rather than letting a generic decoder inflate the body, we do the decompression ourselves with limits on both sides and a ratio check.

Java
@Provider
@Priority(Priorities.ENTITY_CODER)
public class SafeGzipReader implements ReaderInterceptor {
static final long MAX_COMPRESSED = 2L * 1024 * 1024; // 2 MB on the wire
static final long MAX_INFLATED = 20L * 1024 * 1024; // 20 MB after decompression
static final long MAX_RATIO = 100; // 100 to 1
@Override
public Object aroundReadFrom(ReaderInterceptorContext ctx) throws IOException {
String enc = ctx.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING);
if (enc != null && enc.equalsIgnoreCase("gzip")) {
var wire = new LimitedInputStream(ctx.getInputStream(), MAX_COMPRESSED, null);
var inflated = new LimitedInputStream(new GZIPInputStream(wire), MAX_INFLATED, wire);
ctx.setInputStream(inflated); // the JSON reader streams from here
ctx.getHeaders().remove(HttpHeaders.CONTENT_ENCODING); // body is now plain
}
return ctx.proceed();
}
}
final class LimitedInputStream extends FilterInputStream {
private final long max; private final LimitedInputStream compressed; long count;
LimitedInputStream(InputStream in, long max, LimitedInputStream compressed) {
super(in); this.max = max; this.compressed = compressed;
}
@Override public int read(byte[] b, int off, int len) throws IOException {
int n = super.read(b, off, len);
if (n > 0) { count += n; check(); }
return n;
}
// read() for single bytes is overridden the same way
private void check() {
boolean ratio = compressed != null && compressed.count > 0
&& count > 1024 * 1024 && count / compressed.count > SafeGzipReader.MAX_RATIO;
if (count > max || ratio) {
throw new WebApplicationException(Response.status(413).build()); // Content Too Large
}
}
}
// 10 MB gzip of zeros -> rejected after about 2 MB on the wire, or at 20 MB inflated, whichever comes first
// normal 40 KB gzip of 300 KB JSON -> accepted (ratio 7.5)

The compressed limit stops large uploads, the inflated limit caps memory and time, and the ratio check catches a bomb after only a megabyte, since real JSON rarely compresses better than 20 to 1. Because we stream, parsing fails as soon as a limit is crossed. If Jersey's EncodingFilter is also registered, its decoder must not inflate bodies before ours; check the interceptor order. Unsupported Content-Encoding values get 415.

3How BREACH Reads a Secret Through Encryption

BREACH targets HTTPS responses. Encryption hides the content but not the length, and compression makes the length depend on the content. Suppose a page contains a CSRF token csrf=7f3a9c... and also echoes a search term from the URL. The attacker, who can make the victim's browser send requests, for example from a malicious page, but cannot read the responses, sends searches for csrf=0, csrf=1, and so on, while watching the size of the encrypted responses on the network.

When the guessed text matches the start of the real token, the compressor finds a longer repeat and the response gets a byte or so shorter. The attacker keeps the guess that produced the shortest response, then guesses the next character. With a few thousand requests, the whole token is recovered. Three conditions must hold: compression, reflected attacker input, and a secret that stays the same across requests.

Step throughOne BREACH round
  1. Attacker makes the victim's browser request ?q=csrf=athe attacker cannot read the response
  2. Server compresses a page with the echoed q and the real token
  3. Attacker measures the encrypted length on the network
  4. Shorter than for other guesses?
    YesKeep the character, guess the next oneNoTry the next character
  5. Repeat until the whole token is knowna few thousand requests

5 steps in order. Play them, or step through them one at a time.

4Mitigating BREACH

Since all three conditions must hold, breaking any one of them works, and each mitigation has a cost. Not compressing responses that contain secrets is the most direct: the token-bearing HTML or JSON is sent uncompressed, at a bandwidth cost. Masking the token per request means sending it XORed with a fresh random value each time (the token plus mask pair changes on every response), so there is no stable string to guess; Spring Security does this for CSRF tokens by default in version 6 and later, and other frameworks offer similar options. Separating secrets from reflected input means the endpoint that echoes user input never also carries a token, for example by delivering the CSRF token through a separate request or a cookie.

Length randomisation, random padding, only raises the number of requests needed, so it is a weak defence on its own, like rate limiting per session. For a pure JSON API authenticated with bearer tokens in headers, BREACH usually does not apply, because there is no secret in the body; the risk lives in pages and APIs that embed tokens.

5Documenting and Testing the Policy

Both risks are easy to reintroduce, so we write down which endpoints may accept compressed request bodies, with their limits, and which responses may be compressed. The proxy and application configuration follow that list, for example by excluding the paths that render forms with CSRF tokens from compression.

Then we test both cases in the pipeline: a small gzip bomb must get 413 quickly and without a heap spike, and responses containing secrets must have no Content-Encoding header, or a masked token that differs between two responses.

6Follow-up questions

Why use 413 for a decompression bomb?

413 Content Too Large says the request body is bigger than the server will process, which is exactly the case: its real, decompressed size is too large. It tells honest clients to send less, and it keeps the response cheap for attackers.

Should we accept compressed request bodies at all?

Only where it pays off, such as large uploads from our own clients over slow networks. For most APIs, request bodies are small and accepting compression only adds risk, so we reject Content-Encoding on requests with 415 unless an endpoint is on the approved list.

7Conclusion

In this answer, we saw that a decompression bomb turns a small gzip body into gigabytes, so we limit the compressed size, the decompressed size and the ratio with a counting stream in a ReaderInterceptor, stream instead of buffering, and reject with 413. BREACH lets an attacker infer a secret from the length of compressed HTTPS responses that also reflect attacker input; we break it by not compressing responses with secrets, masking tokens per request, separating secrets from reflected input, or, more weakly, randomising length. A documented list of endpoints that may compress, with tests for both cases, keeps the protections in place.

What to say in the interviewAbout 100 seconds aloud

Open with

These are two different attacks that both come from how compression works. The decompression bomb is about requests: gzip can compress highly repetitive data by a thousand to one or more, so a 10 MB body can expand to 10 GB, and our size limits at the proxy only see the compressed size.

Then, if they want more

So in JAX-RS I would handle gzip request bodies in a ReaderInterceptor, wrap the raw stream in a counting stream with a limit on compressed bytes, decompress, wrap that in a second counting stream with a limit on decompressed bytes, and also check the ratio, so a bomb is caught after a megabyte or so.

The JSON reader streams from that, and when a limit is crossed I return 413. BREACH is about responses: over HTTPS the attacker cannot read the content but can see the length, and with compression the length depends on content.

If a response reflects attacker input and contains a stable secret like a CSRF token, the attacker can guess the token one character at a time by watching which guess makes the response shorter.

Mitigations are to not compress responses containing secrets, to mask the token with a fresh random value on every response, which Spring Security does by default now, to keep secrets and reflected input apart, and as a weaker layer, length randomisation and rate limits. Then I would document which endpoints may compress and test both cases in the pipeline.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Jakarta EE specifications
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A JAX-RS service accepts gzip-compressed request bodies. A security review flags a...": https://scrivio-interview-library.netlify.app/java/jax-rs/f436f6ef61/