fix(apigateway,appsync): sandbox VTL rendering with SecureUberspector and execution limits (#3542)

* fix(apigateway,appsync): sandbox VTL rendering with SecureUberspector and execution limits

VtlTemplateEngine and AppSyncVtlEngine rendered templates with Velocity's
default UberspectImpl introspector, which allows arbitrary reflection
through any context object (e.g. $util.getClass().forName('java.lang.Runtime')),
and had no cap on #foreach iterations, output size, or execution time,
making them vulnerable to both sandbox escapes and denial of service via
runaway loops or #set string doubling.

Add a shared VtlSandbox helper that both engines call to switch to
SecureUberspector and restrict introspection on java.lang.Class,
ClassLoader, Runtime, ProcessBuilder, System, Thread, java.io.File and
related reflection/scripting/process packages, plus three independent
limit layers: a native #foreach loop cap that truncates the loop without
failing the template, a cooperative execution deadline checked from a new
SandboxedForeach directive before each loop iteration, and a BoundedWriter
output-size cap. The latter two throw the new VtlLimitExceededException,
an unchecked RuntimeException that flows through each engine's existing
error handling exactly like any other Velocity evaluation failure, with
no new error shape. Limits are configurable via EmulatorConfig
(vtlMaxLoops, vtlMaxOutputChars, vtlTimeoutMillis; application.yml keys
vtl-max-loops, vtl-max-output-chars, vtl-timeout-millis), mirroring the
project's existing per-service numeric-tunable config pattern, and
documented in api-gateway.md and appsync.md.

The classpath-shadowed velocity.properties resource is kept for any
embedding that resolves it normally, but is not the actual enforcement
point: under this project's test/runtime classloader, Velocity's own
getResourceAsStream lookup for that exact resource path can resolve to
the copy bundled inside the velocity-engine-core jar instead of this
project's shadowed copy, silently leaving the insecure UberspectImpl
active even with a correct properties file on disk. VtlSandbox configures
SecureUberspector and swaps in SandboxedForeach directly via the
VelocityEngine Java API instead, which is unaffected by that ambiguity.

* docs(apigateway): correct foreach registration documentation
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-15 13:03:51 -04:00
1 parent c63c834c0e
commit 144b90e6fa
19 files changed
+741 -8

No files matched your search

@@ -0,0 +1,68 @@
package io.github.hectorvent.floci.services.apigateway;
import org.junit.jupiter.api.Test;
import java.io.StringWriter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Isolated, non-CDI unit tests for {@link BoundedWriter}, exercising writes under, at, and over
* the configured character budget directly, without going through Velocity or Quarkus.
*/
class BoundedWriterTest {
@Test
void write_underLimit_passesThroughToDelegate() throws Exception {
StringWriter delegate = new StringWriter();
BoundedWriter writer = new BoundedWriter(delegate, 10);
writer.write("hello".toCharArray(), 0, 5);
assertEquals("hello", delegate.toString());
}
@Test
void write_exactlyAtLimit_isAllowed() throws Exception {
StringWriter delegate = new StringWriter();
BoundedWriter writer = new BoundedWriter(delegate, 5);
writer.write("hello".toCharArray(), 0, 5);
assertEquals("hello", delegate.toString());
}
@Test
void write_overLimit_throwsAndDoesNotWriteToDelegate() {
StringWriter delegate = new StringWriter();
BoundedWriter writer = new BoundedWriter(delegate, 4);
assertThrows(VtlLimitExceededException.class, () -> writer.write("hello".toCharArray(), 0, 5));
assertEquals("", delegate.toString(), "a write that exceeds the budget must not partially land");
}
@Test
void write_multipleWritesAccumulate_andTripOnceTotalExceedsLimit() throws Exception {
StringWriter delegate = new StringWriter();
BoundedWriter writer = new BoundedWriter(delegate, 6);
writer.write("abc".toCharArray(), 0, 3);
writer.write("def".toCharArray(), 0, 3);
assertEquals("abcdef", delegate.toString());
assertThrows(VtlLimitExceededException.class, () -> writer.write("g".toCharArray(), 0, 1));
}
@Test
void flushAndClose_delegateToUnderlyingWriter() throws Exception {
StringWriter delegate = new StringWriter();
BoundedWriter writer = new BoundedWriter(delegate, 10);
writer.write("ok".toCharArray(), 0, 2);
writer.flush();
writer.close();
assertEquals("ok", delegate.toString());
}
}
@@ -0,0 +1,90 @@
package io.github.hectorvent.floci.services.apigateway;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.junit.jupiter.api.Test;
import java.io.StringWriter;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Isolated, non-CDI test proving that {@link VtlSandbox#installSandboxedForeach(VelocityEngine)}
* actually wires {@link SandboxedForeach}'s per-iteration {@link VtlExecutionGuard#checkDeadline()}
* call into a real {@code #foreach} render.
*
* <p>This is deliberately distinct from the loop-count cap test in {@code VtlTemplateEngineTest}
* (which only proves Velocity's own native {@code directive.foreach.max_loops}) and from
* {@link BoundedWriterTest} (which only proves the output-size cap): the template below never
* writes its growing {@code $s} to the output writer at all, so a failure here can only come from
* the execution-time deadline tripping inside the loop body, which is exactly the "runaway
* {@code #set} string doubling that never reaches the output writer" scenario the deadline check
* exists to catch.
*/
class SandboxedForeachTest {
private VelocityEngine sandboxedEngine() {
VelocityEngine engine = new VelocityEngine();
engine.setProperty(RuntimeConstants.RESOURCE_LOADERS, "string");
engine.setProperty("resource.loader.string.class",
"org.apache.velocity.runtime.resource.loader.StringResourceLoader");
VtlSandbox.restrictIntrospection(engine);
engine.init();
VtlSandbox.installSandboxedForeach(engine);
return engine;
}
@Test
void runawayStringDoublingNeverWrittenToOutput_isStoppedByDeadline_notByOutputCap() {
VelocityEngine engine = sandboxedEngine();
// Doubling a 2-character seed 40 times would reach roughly 2 billion characters, well
// past what any sane loop-count cap (10,000) would prevent, and $s is never written to
// the output writer, so BoundedWriter cannot be what stops this either.
String template = "#set($s = \"xy\")#foreach($i in [1..40])#set($s = \"$s$s\")#end";
StringWriter writer = new StringWriter();
VtlExecutionGuard.begin(Duration.ofMillis(20));
try {
RuntimeException ex = assertThrows(RuntimeException.class,
() -> engine.evaluate(new VelocityContext(), writer, "runaway-doubling", template));
assertTrue(causedByDeadline(ex),
"expected the failure to be caused by VtlLimitExceededException (the deadline check), but was: "
+ ex);
} finally {
VtlExecutionGuard.end();
}
assertEquals("", writer.toString(),
"nothing should have reached the output writer before the deadline tripped inside the loop");
}
@Test
void shortLoopWithinDeadline_completesNormally() {
VelocityEngine engine = sandboxedEngine();
String template = "#foreach($i in [1..5])x#end";
StringWriter writer = new StringWriter();
VtlExecutionGuard.begin(Duration.ofSeconds(30));
try {
engine.evaluate(new VelocityContext(), writer, "short-loop", template);
} finally {
VtlExecutionGuard.end();
}
assertEquals("xxxxx", writer.toString());
}
private static boolean causedByDeadline(Throwable t) {
while (t != null) {
if (t instanceof VtlLimitExceededException) {
return true;
}
t = t.getCause();
}
return false;
}
}
@@ -0,0 +1,67 @@
package io.github.hectorvent.floci.services.apigateway;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Isolated, non-CDI unit tests for {@link VtlExecutionGuard}, run directly against the thread's
* deadline state without going through Velocity or Quarkus, for fast deterministic coverage of
* the execution-time deadline mechanism itself.
*/
class VtlExecutionGuardTest {
@AfterEach
void clearAnyLeftoverDeadline() {
// Guard against a failed assertion mid-test leaking a deadline into later tests on the
// same thread (JUnit5 reuses threads across test methods by default).
VtlExecutionGuard.end();
}
@Test
void checkDeadline_withNoActiveDeadline_doesNothing() {
assertDoesNotThrow(VtlExecutionGuard::checkDeadline);
}
@Test
void checkDeadline_beforeDeadlinePasses_doesNothing() throws InterruptedException {
VtlExecutionGuard.begin(Duration.ofSeconds(30));
assertDoesNotThrow(VtlExecutionGuard::checkDeadline);
}
@Test
void checkDeadline_afterDeadlinePasses_throws() throws InterruptedException {
VtlExecutionGuard.begin(Duration.ofMillis(1));
Thread.sleep(20);
VtlLimitExceededException ex =
assertThrows(VtlLimitExceededException.class, VtlExecutionGuard::checkDeadline);
assertNotNullMessage(ex);
}
@Test
void end_clearsDeadline_soCheckDeadlineNoLongerThrows() throws InterruptedException {
VtlExecutionGuard.begin(Duration.ofMillis(1));
Thread.sleep(20);
VtlExecutionGuard.end();
assertDoesNotThrow(VtlExecutionGuard::checkDeadline);
}
@Test
void begin_replacesAnyPreviousDeadline() throws InterruptedException {
VtlExecutionGuard.begin(Duration.ofMillis(1));
Thread.sleep(20);
// A fresh begin() must reset the deadline, not extend the expired one.
VtlExecutionGuard.begin(Duration.ofSeconds(30));
assertDoesNotThrow(VtlExecutionGuard::checkDeadline);
}
private static void assertNotNullMessage(VtlLimitExceededException ex) {
if (ex.getMessage() == null || ex.getMessage().isBlank()) {
throw new AssertionError("expected a descriptive message on VtlLimitExceededException");
}
}
}
@@ -485,4 +485,77 @@ class VtlTemplateEngineTest {
assertNull(result.statusOverride());
assertTrue(result.headerOverrides().isEmpty());
}
// ────────── Sandbox: reflection escapes must be blocked ──────────
@Test
void security_getClassLoaderIsNotReachable() {
// When SecureUberspector blocks a method call, Velocity (in non-strict mode, the default
// here) renders the literal, unresolved reference text instead of throwing or evaluating
// it. Getting the raw template text back verbatim (rather than an actual ClassLoader
// instance's toString, e.g. "...ClassLoader@<hash>") proves the call was blocked. Note
// this literal text still contains the substring "ClassLoader" (it's the method name), so
// a plain assertFalse(result.contains("ClassLoader")) would wrongly fail here.
String template = "$util.getClass().getClassLoader()";
String result = engine.evaluate(template, ctx("{}")).body();
assertEquals(template, result,
"expected getClassLoader() to be blocked by SecureUberspector and rendered as an "
+ "unresolved literal reference, but got: " + result);
}
@Test
void security_classForNameIsNotReachable() {
String result = engine.evaluate(
"$util.getClass().forName('java.lang.System').getName()", ctx("{}")).body();
assertNotEquals("java.lang.System", result,
"expected Class.forName(...) to be blocked by SecureUberspector, but it resolved: " + result);
}
@Test
void security_runtimeClassIsNotLoadableByName() {
String result = engine.evaluate(
"$util.getClass().forName('java.lang.Runtime').getName()", ctx("{}")).body();
assertNotEquals("java.lang.Runtime", result,
"expected Class.forName('java.lang.Runtime') to be blocked, but it resolved: " + result);
}
@Test
void security_processBuilderClassIsNotLoadableByName() {
String result = engine.evaluate(
"$util.getClass().forName('java.lang.ProcessBuilder').getName()", ctx("{}")).body();
assertNotEquals("java.lang.ProcessBuilder", result,
"expected Class.forName('java.lang.ProcessBuilder') to be blocked, but it resolved: " + result);
}
@Test
void security_getClassStillPermitsGetName() {
// getName() on a Class receiver must remain permitted (SecureUberspector's one exception),
// so ordinary reflection-free VTL idioms relying on it (if any) keep working.
String result = engine.evaluate("$util.getClass().getName()", ctx("{}")).body();
assertTrue(result.contains("UtilVariable"), "expected getName() on Class to still work, got: " + result);
}
// ────────── Sandbox: runaway loop and output limits ──────────
@Test
void security_foreachLoopCountIsBounded() {
// 50,000 requested iterations, each writing a single character. With no cap this renders
// 50,000 characters; the configured default (ApiGatewayServiceConfig.vtlMaxLoops = 10000)
// must cap the loop well before that.
String template = "#foreach($i in [1..50000])x#end";
String result = engine.evaluate(template, ctx("{}")).body();
assertEquals(10000, result.length(),
"expected #foreach to be capped at the configured vtlMaxLoops, but rendered " + result.length()
+ " characters");
}
@Test
void security_outputSizeIsBounded() {
// 21 doublings of a 2-character seed produce roughly 4 million characters, comfortably
// over the default 1,048,576-character output cap, in only 21 loop iterations (well under
// the 10,000-iteration loop cap), so this exercises the output limit specifically.
String template = "#set($s = \"xy\")#foreach($i in [1..21])#set($s = \"$s$s\")#end$s";
assertThrows(RuntimeException.class, () -> engine.evaluate(template, ctx("{}")),
"expected output exceeding the configured vtlMaxOutputChars to throw");
}
}
@@ -765,4 +765,82 @@ class AppSyncVtlEngineTest {
engine.evaluate("#if(true)", defaultCtx()));
}
}
// ────────── Sandbox: reflection escapes, and runaway loop/output limits ──────────
@Nested
class CategoryK_Sandbox {
@Test
void k1_getClassLoaderIsNotReachable() {
// When SecureUberspector blocks a method call, Velocity (non-strict mode, the default
// here) renders the literal, unresolved reference text instead of throwing or
// evaluating it. Getting the raw template text back verbatim (rather than an actual
// ClassLoader instance's toString) proves the call was blocked.
String template = "$util.getClass().getClassLoader()";
var result = engine.evaluate(template, defaultCtx());
assertEquals(template, result.output(),
"expected getClassLoader() to be blocked by SecureUberspector and rendered as "
+ "an unresolved literal reference, but got: " + result.output());
}
@Test
void k2_classForNameIsNotReachable() {
var result = engine.evaluate(
"$util.getClass().forName('java.lang.System').getName()", defaultCtx());
assertNotEquals("java.lang.System", result.output(),
"expected Class.forName(...) to be blocked by SecureUberspector, but it resolved: "
+ result.output());
}
@Test
void k3_runtimeClassIsNotLoadableByName() {
var result = engine.evaluate(
"$util.getClass().forName('java.lang.Runtime').getName()", defaultCtx());
assertNotEquals("java.lang.Runtime", result.output(),
"expected Class.forName('java.lang.Runtime') to be blocked, but it resolved: "
+ result.output());
}
@Test
void k4_processBuilderClassIsNotLoadableByName() {
var result = engine.evaluate(
"$util.getClass().forName('java.lang.ProcessBuilder').getName()", defaultCtx());
assertNotEquals("java.lang.ProcessBuilder", result.output(),
"expected Class.forName('java.lang.ProcessBuilder') to be blocked, but it resolved: "
+ result.output());
}
@Test
void k5_getClassStillPermitsGetName() {
// getName() on a Class receiver must remain permitted (SecureUberspector's one
// exception), so ordinary reflection-free VTL idioms relying on it keep working.
var result = engine.evaluate("$util.getClass().getName()", defaultCtx());
assertTrue(result.output().toString().contains("AppSyncUtil"),
"expected getName() on Class to still work, got: " + result.output());
}
@Test
void k6_foreachLoopCountIsBounded() {
// 50,000 requested iterations, each writing a single character. With no cap this
// renders 50,000 characters; the configured default
// (AppSyncServiceConfig.vtlMaxLoops = 10000) must cap the loop well before that.
String template = "#foreach($i in [1..50000])x#end";
var result = engine.evaluate(template, defaultCtx());
assertEquals(10000, result.output().toString().length(),
"expected #foreach to be capped at the configured vtlMaxLoops, but rendered "
+ result.output().toString().length() + " characters");
}
@Test
void k7_outputSizeIsBounded() {
// 21 doublings of a 2-character seed produce roughly 4 million characters, comfortably
// over the default 1,048,576-character output cap, in only 21 loop iterations (well
// under the 10,000-iteration loop cap), so this exercises the output limit
// specifically.
String template = "#set($s = \"xy\")#foreach($i in [1..21])#set($s = \"$s$s\")#end$s";
assertThrows(RuntimeException.class, () -> engine.evaluate(template, defaultCtx()),
"expected output exceeding the configured vtlMaxOutputChars to throw");
}
}
}