🛡️ A Security Checkpoint Inside the Application: Building an Embedded RASP Spring Boot Starter
A practical walkthrough of spring-boot-rasp-starter—what I built, how requests move through it, and where I draw the security boundary.
I designed the Embedded RASP Spring Boot Starter to add a small, configurable screening layer to a Spring MVC application without asking every team to repeat the same preliminary input checks in every controller.
The idea is deliberately modest: place bounded, heuristic inspection near the HTTP boundary; make the result observable; and let a clear policy decide whether a suspicious request proceeds.
The starter can identify recognizable attack-like input across common request surfaces. It cannot prove that an application is safe, understand every downstream operation, or replace secure coding. I treat it as one layer in a defense-in-depth design—not a substitute for the controls at the actual sink.
I have tried to make those constraints visible in the code and in the project’s README and security policy, rather than hiding them behind the word “protection.”
💡 Why I built it—and what I wanted it to do
I have seen input checking drift into a collection of controller-specific snippets: one endpoint checks for a suspicious token, another forgets, and a third normalizes input differently. Moving every such decision into every controller is repetitive, difficult to audit, and easy to apply inconsistently.
I wanted a reusable screening layer that could run close to the application’s HTTP entry point, with one configuration namespace and a sensible default path through the framework.
In a Spring Boot application, that meant using Boot’s AutoConfiguration.imports mechanism rather than asking every consumer to remember a special enablement annotation or component-scan package.
The auto-configuration is registered in AutoConfiguration.imports. When the servlet stack is present and rasp.enabled is true, it wires the engine, filter, MVC hooks, and optional observability components.
My goal was not to build a network appliance inside a JAR. I approached the problem from two angles at once: as a backend engineer trying to keep request handling predictable, and as a security-minded observer asking where untrusted values enter, how they are transformed, and what trust boundary they may cross next.
That perspective changed the design. I focused on bounded input inspection, preserving the original request for the application, keeping policy separate from detection, and avoiding payload disclosure in ordinary telemetry.
It also forced me to think about what the integration does not see: input created internally, values transformed after the scan, a database or process call, data received over a non-HTTP channel, or an endpoint that bypasses the expected Spring proxy.
My design principle: inspect early enough to be useful, but be explicit that only the eventual application operation can enforce its own security requirements.
⚙️🔍 What it does: one request, end to end
I split the work into a framework-independent engine and a servlet integration. The engine evaluates a ScanContext; the integration extracts request material, applies policy and telemetry, and either continues the filter chain or returns a rejection.
1. RaspFilter: first pass, bounded body handling
The servlet entry point is RaspFilter, registered near the beginning of the filter chain for request dispatches.
For each request it creates or reuses request-local state and assigns an X-RASP-Trace-Id response header. It checks path and IP exemptions before scanning. A whitelisted path or exact configured servlet remote address bypasses the filter’s inspection.
Path exemptions use Ant-style patterns. The code treats ambiguous or non-canonical paths—such as ones containing encoded characters, backslashes, semicolons, repeated slashes, or dot segments—as ineligible for a path exemption, so those paths are scanned instead of bypassed.
When body scanning is eligible, CachedBodyRequest buffers up to the configured rasp.scan.max-body-size budget and supplies a replayable request wrapper downstream.
If the body is oversized, it is passed intact to the application without body scanning. If an I/O error interrupts buffering, the bytes already read are replayed together with the remaining original stream; the integration records an extraction failure and applies the configured failure policy.
I made that behavior a compatibility decision as much as a security one. The application should not receive an accidentally truncated request simply because the inspection layer reached its limit.
2. Extraction: identify supported input surfaces
RequestPayloadExtractor assembles the HTTP context from the surfaces enabled by rasp.scan:
- The request URI/path, when
rasp.scan.uri is enabled.
- Non-exempt header names and values, when
rasp.scan.headers is enabled.
- Query parameters and decoded form fields, when
rasp.scan.query-params is enabled.
- Eligible request bodies, when
rasp.scan.body is enabled.
- Later in MVC handling, resolved URI-template variables and selected multipart metadata.
The Content-Type value remains available as metadata for the XXE detector even if ordinary header scanning is disabled. Header names in the whitelist are matched without case sensitivity.
For JSON, the extractor uses Jackson to decode nested objects and arrays into data values, removes configured exempt field names, and submits those values for inspection. If a body is malformed JSON, it falls back to scanning the raw text; it does not attempt to repair or rewrite the payload.
For application/x-www-form-urlencoded, it scans decoded names and values. XML is treated as text for detection rather than being parsed by the RASP layer. The XXE detector looks for suspicious DTD/entity and external-reference syntax; it does not resolve XML entities.
ScanPayloads flattens supported scalar values, maps, iterables, and arrays while retaining a location label. It does not call arbitrary object methods during core extraction.
The core traversal has depth, node-visit, and value-count limits. The annotated-object scanner has its own configurable depth and value limits. Those bounds reduce accidental unbounded work; they are not a substitute for servlet-container request limits.
3. Bounded normalization, only for detection
InputNormalizer canonicalizes candidate values for the detectors. It applies two passes of supported URL, HTML-entity, and Java Unicode decoding, removes selected control and zero-width characters, and folds case.
It also recognizes a small set of historically accepted overlong path-separator encodings for detection. It does not change the value delivered to the controller or service.
This distinction matters: detection works on a normalized view; application behavior still sees the original input. If the application’s own parser later applies a transformation that the detector does not model, the two views can disagree.
4. Eight detectors, one engine
RaspEngine runs the installed ThreatDetector strategies in priority order. The eight built-in families are:
| Category | What I designed it to recognize | What I still expect the application to do |
|---|
SQLI | Recognizable SQL operators, clauses, stacked statements, and probe patterns | Use prepared statements and allowlist dynamic identifiers |
XSS | Script-like markup, dangerous tags or attributes, and encoded variants | Apply contextual output encoding and suitable browser controls |
SPEL | Suspicious expression syntax and dangerous type or execution access | Do not evaluate untrusted expressions; constrain evaluation contexts |
PATH_TRAVERSAL | Parent segments, encoded separators, and sensitive path patterns | Resolve paths under an allowed root and verify the resolved target |
COMMAND | Command chaining, shell syntax, and suspicious redirection patterns | Avoid shells where possible and validate executable/argument choices |
LDAP | Suspicious filter escaping, wildcard, and bypass structures | Apply correct filter and distinguished-name escaping |
NOSQL | Mongo-style $ operators, including nested JSON key patterns | Validate query schemas; do not merge untrusted objects into queries |
XXE | DTD/entity declarations and external-reference syntax in XML-like input | Disable DTDs and external entities in every XML parser |
The table describes heuristic signals, not a complete grammar for each vulnerability class. A detector match is evidence for a policy decision—not proof that an exploit would succeed.
The built-in rule implementations live under rasp-core/.../detector. Compiled patterns can be shared through PatternCache, whose size and TTL are configurable.
Built-in detection is CPU work on the request thread and does not call a database, filesystem, DNS resolver, or remote service. Reading the servlet body is still synchronous request I/O. A custom detector plugged into this path must also be deterministic, bounded, thread-safe, and free of slow external I/O.
5. ThreatScorer and PolicyEngine: findings become actions
The ThreatScorer uses the highest individual finding score. I chose that over summing duplicate low-confidence matches, which could otherwise inflate a score merely because several related rules matched the same input.
PolicyEngine then combines the score, threshold, mode, and engine-error state into one decision:
| Mode | Practical behavior |
|---|
MONITOR | Record suspicious findings as LOG; allow the request to proceed |
BLOCK | Block a finding at or above rasp.block-threshold; lower scores remain LOG |
STRICT | Apply the same detection policy and additionally track repeat violations by servlet remote address |
The engine represents outcomes as ALLOW, LOG, or BLOCK. A clean scan is ALLOW; a positive score below threshold is LOG; a qualifying score is BLOCK. For ordinary findings, MONITOR records LOG and permits the request. Engine errors follow the configured fail-open policy.
There is an important nuance in the current implementation: PolicyEngine checks engineError && !failOpen before checking MONITOR, so a detector failure can yield BLOCK in MONITOR when fail-open is disabled. The extraction-failure handler, by contrast, explicitly allows in MONITOR. The README and policy comments describe MONITOR as always allowing; I would reconcile this behavior and the documentation before relying on fail-closed MONITOR semantics.
The default mode is BLOCK, the default threshold is 50, and rasp.fail-open defaults to true. I recommend a staged rollout that begins with MONITOR even though the starter’s configuration default is BLOCK.
In STRICT, the integration uses a bounded in-memory Caffeine cache. Its defaults track up to 10,000 entries, count three violations in a 60-second window, and impose a 60-second temporary block. This is per process, and entries can expire or be evicted.
6. Optional service-boundary protection and output encoding
HTTP request screening does not always cover values created or changed inside an application. I added opt-in method-level checks for selected Spring-managed boundaries:
@RaspProtect on a type or method scans all supported method arguments passing through the Spring AOP proxy.
@RaspScan on a method or parameter selects the scan boundary; types can select detector categories and deepScan = true permits bounded reflection into nested DTO fields.
The annotations are in rasp-core and RaspScan; RaspAspect and MethodArgumentScanner provide the Spring integration.
This is explicitly opt-in. Spring AOP cannot intercept self-invocation through this, calls to objects constructed outside Spring, and methods outside its proxy constraints. Deep reflection is not applied to every request object.
For output, SafeOutput.forHtml(value) encodes text intended for HTML content. The optional @RaspEncodeHtml annotation encodes an opted-in String response only when the negotiated media type is text/html.
Neither helper is a universal sanitizer. HTML text encoding is not JavaScript, CSS, URL, or attribute-context encoding, and RASP never silently rewrites request data.
7. Observability without turning payloads into telemetry
The integration publishes ThreatDetectedEvent metadata, including the detection location, and writes structured log fields for category, decision, score, and trace identifier. It does not need to write the submitted payload into logs.
When a Micrometer registry is available and rasp.metrics.enabled is true, the binder registers:
rasp.threats.detected
rasp.threats.blocked
Both use the fixed threat category as their tag. I intentionally avoid request values, URLs, remote addresses, and trace IDs as metric tags to keep cardinality bounded and avoid unnecessary sensitive data exposure.
With Actuator present in the consumer, the raspHealthIndicator reports whether the configured component was constructed and includes mode, enabled detector count, and fail-open setting. UP means ready; it does not mean that all requests are safe or that every attack is detectable.
Optional webhook alerting is disabled by default. If enabled, the listener sends metadata-only threshold alerts asynchronously using a bounded executor. Delivery is best-effort, not a durable audit queue; I would not rely on it for incident evidence or guaranteed notification.
đź§± Why I split the project into modules
I wanted the detector and policy layer to remain usable without making every consumer depend on servlet APIs. At the same time, I wanted Boot users to get a conventional single dependency and a sample they could actually run.
| Module | Responsibility |
|---|
rasp-core | Detection contracts, extraction helpers, normalization, scoring, policy, and reusable engine |
rasp-spring-boot-autoconfigure | Validated rasp.* properties, servlet filter and MVC integration, method scanning, events, metrics, and health |
rasp-spring-boot-starter | Dependency aggregator for the core, auto-configuration, Spring MVC, and AOP integration |
rasp-samples | Safe echo application, sample configuration, and acceptance tests |
This separation gives me a framework-light core, a place for framework lifecycle code, and a simple consumer-facing artifact. The sample depends on the starter rather than manually assembling each internal module, so it exercises the intended installation path.
The parent pom.xml sets Java release 25 and Spring Boot 3.5.16, manages the reactor, and applies the library line-coverage gate. The build enforces JDK 25 and Maven 3.8.6 or newer.
I pinned that stack to match the repository’s current stated baseline. It is not a claim that the baseline remains an appropriate production choice indefinitely: Spring announced Boot 3.5.16 as the final open-source release of the 3.5 line. I call out the lifecycle risk in the project’s documentation rather than treating a passing build as a dependency-support guarantee.
The integration targets the servlet Spring MVC stack. A WebFlux/Netty consumer does not receive this servlet protection. The core engine can be embedded separately, but this project does not include reactive request-body interception.
🛡️⚠️ Security boundaries, trade-offs, and my SECURITY.md reality check
I consider the most important security feature of the repository to be its honest boundary statement. The security policy is intentionally direct about the difference between screening request text and observing a dangerous operation.
Screening is not sink instrumentation
This project does not instrument JDBC calls, process creation, filesystem access, XML parser behavior, expression evaluation, browser execution, or other JVM sinks. It does not track tainted values through application code.
That means a value can be modified after screening, arrive from a non-HTTP source, or reach a sensitive sink through a path the starter never sees. I still expect parameterized queries, contextual encoding, secure XML parser configuration, safe process and filesystem APIs, and ordinary authorization checks at the operation itself.
The eight detector categories recognize patterns, not every encoding, representation, fragmented payload, or application-specific transformation. False positives are possible too. A finite regression corpus—however useful—cannot prove there are none.
Fail-open is a deliberate availability default
rasp.fail-open=true is the default. If extraction or engine work fails, the request can continue. Setting it to false makes processing errors fail closed. There is a code/documentation edge case worth resolving: extraction failures explicitly allow in MONITOR, while detector errors can still become BLOCK because PolicyEngine handles fail-closed errors before its MONITOR branch. The README and policy comments currently say MONITOR always allows.
This is an operational trade-off, not a security ranking. Fail-closed behavior can make inspection failures an availability issue. I would test the chosen policy under malformed and oversized input, detector failures, and normal service load before deployment.
The configured body budget defaults to 1MB and is validated between 1B and 16MB. A body above the budget is replayed but not scanned, regardless of fail-open/fail-closed behavior. The servlet container and ingress still need their own request-size limits.
multipart/form-data and application/octet-stream are excluded from body-byte scanning by default. Some multipart metadata, such as parameter names or original filenames, can be scanned later in MVC processing; that does not inspect file bytes, archives, or embedded documents.
Unknown-length/chunked URL-encoded form requests need special handling. The filter defers body access until Spring MVC has had an opportunity to parse servlet form parameters, preserving normal binding behavior. RASP then inspects decoded fields within its budget.
That scan budget does not limit allocations made by the servlet container’s own form parser or its parameter count. I advise configuring container and ingress limits independently.
Exemptions are bypasses, not harmless conveniences
The defaults exempt /actuator/**, /swagger-ui/**, and /v3/api-docs/** paths. They also exclude the Authorization, Cookie, X-CSRF, X-CSRF-TOKEN, and Content-Length headers from header-value scanning.
These choices avoid inspecting opaque credentials or protocol metadata as ordinary application text. They do not implement authentication, session security, or CSRF protection. The management and documentation routes still need network controls and access policy.
Parameter/field exemptions and exact IP exemptions are also bypasses. I do not exempt password fields by default. If an operator adds an exemption, the eventual sink for that surface still needs to be safe.
IP checks use HttpServletRequest.getRemoteAddr(). The library does not trust X-Forwarded-For or Forwarded to make an exemption or security decision. A container can rewrite the remote address only when configured to trust known proxies; blindly exempting a load balancer address could exempt every caller behind it.
STRICT is not a distributed DDoS shield. It tracks violations locally in one JVM, with bounded state that can expire, be evicted, or disappear on restart. It cannot coordinate across replicas or replace an ingress rate limiter.
Privacy is part of the design
Detection results can contain evidence in process memory. That evidence is sensitive. I keep raw payloads, credentials, authorization and cookie values, and complete exception arguments out of production logs and rejection responses.
The default rasp.response.include-details=false should remain in place unless exposing a threat category is an intentional operational choice. The response returns an error and a generated trace ID; it does not return submitted evidence.
I also avoid request-specific tags in metrics. If an application adds its own ThreatDetectedEvent listener, I expect it to preserve the same privacy discipline and avoid serializing the entire ScanContext or scan result.
The sample exposes health details and metrics for demonstration. I would secure management access before using this pattern in a deployed application.
Lifecycle and release honesty
The project targets Java 25 and Spring Boot 3.5.16. Boot 3.5 supports Java 25, but the repository’s own docs note that 3.5.16 is the last open-source release of that Boot line.
Before an Internet-facing release, I would review the full dependency tree and current advisories, select a supported framework baseline, and establish an owner for patching and vulnerability disclosure. A passing test suite is not a CVE scan, a third-party security audit, or a production certification.
🚀 How I build, run, and use it
Build and start the sample
I use a JDK 25 and Maven 3.8.6 or newer. On a clean workspace, I build the reactor and install its snapshot artifacts locally before launching the sample as an individual module:
123
mvn clean verify
mvn install
mvn -pl rasp-samples spring-boot:run
On Windows, the repository includes a helper that selects a JDK 25 and applies a local socket-temp workaround for Maven child JVMs:
123
.\scripts\maven.ps1 clean verify
.\scripts\maven.ps1 install
.\scripts\maven.ps1 -pl rasp-samples spring-boot:run
The application listens on port 8080 by default; PORT overrides it. I can also start the packaged executable JAR after building:
1
java -jar rasp-samples/target/rasp-samples-1.0.0-SNAPSHOT.jar
The sample endpoints echo input as JSON. They intentionally do not execute commands, evaluate expressions, query a database, contact LDAP, open a file, or parse XML with an application parser.
Add the starter to a consumer
These coordinates are built locally; the repository does not claim a published Maven Central release. After mvn install or publication to an organization’s artifact repository, I add:
12345
<dependency>
<groupId>dev.rasp</groupId>
<artifactId>rasp-spring-boot-starter</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
The Boot auto-configuration registers without an @EnableRasp annotation or extra component scan. The consumer application supplies spring-boot-starter-actuator if it wants Boot’s metrics and health endpoints; the RASP starter does not expose management routes by itself.
Exercise the example
With the sample running, ordinary input passes, while these inert test strings exercise representative detection:
1234
curl --get --data-urlencode 'name=John' http://localhost:8080/api/users
curl --get --data-urlencode "q=' OR 1=1--" http://localhost:8080/api/search
curl -H 'Content-Type: application/json' --data '{"comment":"<script>alert(1)</script>"}' http://localhost:8080/api/comment
curl --get --data-urlencode "expr=T(java.lang.Runtime).getRuntime().exec('id')" http://localhost:8080/api/eval
The demonstrated malicious-looking strings are sent only to the local safe echo sample. They are not executable operations in the sample application.
The default sample mode is BLOCK, so the README expects representative malicious examples to return HTTP 403. To inspect behavior without blocking traffic, I can set RASP_MODE=MONITOR before startup.
With Actuator included in the sample, I can inspect health and counters at:
123
http://localhost:8080/actuator/health
http://localhost:8080/actuator/metrics/rasp.threats.detected
http://localhost:8080/actuator/metrics/rasp.threats.blocked
The health detail is readiness information, not a verdict on traffic safety. I would protect these endpoints in any real application.
For a container-based acceptance run, the repository offers mvn verify -Pdocker-it; that explicit profile requires a working Docker daemon and permission to pull the JRE 25 image. The regular mvn clean verify suite does not require Docker.
I can also run the demo with Docker Compose using docker compose up --build. The sample container is a demonstration environment, not a substitute for an application-specific ingress, authentication policy, or management-endpoint configuration.
Tune with evidence, not guesswork
My rollout recommendation is to begin in MONITOR mode against representative traffic. I would examine false positives, understand which detector and location produced them, and tune only the narrowest relevant surface.
Then I would validate that the policy thresholds and exemptions match the application’s risk and availability needs before moving to BLOCK or STRICT.
I would review at least these settings in context:
| Setting | What I would check |
|---|
rasp.mode and rasp.block-threshold | Start by observing real traffic; understand which scores would block |
rasp.fail-open | Decide what inspection errors mean for availability and test that behavior |
rasp.scan.max-body-size | Budget memory and latency while recognizing that larger bodies are not scanned |
rasp.scan.skip-content-types | Confirm that intentionally excluded body types have their own controls |
rasp.whitelist.* | Treat every exemption as reduced detection coverage and protect its downstream sink |
rasp.scan.max-object-depth and max-object-values | Bound annotated-object traversal without making the annotation ineffective |
rasp.detectors.*.enabled | Understand the detection capability being removed when a detector is disabled |
rasp.rate-limit.* | Remember that STRICT tracking is local to the JVM and supplementary |
rasp.response.include-details | Keep false unless the additional client-visible detail is justified |
I would follow monitoring with application-level tests and end-to-end load tests, including large and adversarial requests. Core-engine timings do not include servlet buffering, container scheduling, network/TLS, application work, or queueing.
The repository includes positive and negative detector corpora, false-positive cases, engine policy tests, auto-configuration tests, MockMvc checks, sample tests, and servlet-container smoke tests. The optional Docker profile adds an executable-container check.
These tests give me useful regression evidence. They do not certify the security of a consumer application or guarantee the advertised performance targets on different hardware.
✨ What this project taught me
Designing this starter reinforced a practical lesson: application security is less about collecting a long list of attack names and more about knowing where data comes from, how it is transformed, and where it eventually matters.
A request filter can catch useful signals early. A policy engine can make decisions consistent. Bounded buffers and traversal budgets can keep work controlled. Metrics and privacy-safe logs can help operators understand what the system is seeing.
But each of those choices has a trade-off: a size cap creates an inspection gap, fail-open protects availability at the cost of scan guarantees, an exemption reduces coverage, and a heuristic can be both wrong and incomplete.
I built spring-boot-rasp-starter to make a useful layer easy to adopt while keeping its limits visible. The engineering work was not just implementing detectors; it was deciding what the integration should inspect, how it should preserve request behavior, and how to avoid claiming more than the code can establish.
I see the starter as a checkpoint—not a security boundary that absolves the application from doing the hard work at its sinks. Used with that understanding, it can add practical visibility and another opportunity to reject recognizable hostile input before it reaches the rest of a Spring MVC request path.
Further reading
Comments 0
Guest comments are reviewed before they appear.
Loading comments…