feat(kinesisanalytics): emit MSF-style JSON CloudWatch logs from Flink (#2656)

* feat(kinesisanalytics): emit MSF-style JSON CloudWatch logs from Flink

The JobManager/TaskManager now start with a log4j-console.properties
that formats every log line as a single JSON object matching real
Managed Service for Apache Flink's CloudWatch Logs schema
(applicationARN, applicationVersionId, locationInformation, logger,
message, messageSchemaVersion, messageType, threadName,
throwableInformation), instead of the stock image's default plain-text
pattern. Applies to Flink's own framework logs and anything a deployed
JAR logs through SLF4J/Log4j2, so a JAR that expects its logs to reach
CloudWatch (or asserts on this schema) sees the same thing here as on
real MSF.

Written into the container before the JVM starts -- log4j2 reads its
config at process boot, so copying the file in after start (the way
application_properties.json already is) would be too late. Required
splitting the JobManager/TaskManager container startup from
createAndStart into create + copyFileIntoContainer + startCreated,
mirroring the create-then-inject-then-start pattern
ContainerLifecycleManager already exposed for exactly this purpose.

* fix(kinesisanalytics): escape log4j2 pattern injection and fail loudly on log4j copy failure

ApplicationName flows unvalidated into the ARN baked into the JSON log
pattern, so a name containing '%' could be interpreted as a log4j2
conversion specifier and a '"' or '\' could break the emitted JSON.
Escape both before embedding, reusing the existing %enc{}{JSON}
wrapper to JSON-encode the value at log time.

Also stop silently swallowing a failed log4j-console.properties copy:
startCluster previously reported success and ran with the stock
(non-JSON) log format if the copy failed. The copy is now required,
so a failure rolls back the cluster the same way a create() failure
already does.

* fix(kinesisanalytics): validate ApplicationName, fix NPE, and block log4j2 Lookup injection

CI failure: startClusterLabelsJobManagerContainerWithResourceIdentity
built a FlinkApplication with no ARN set, and literalForLog4j2Pattern
NPE'd on the null value. Wrap both baked-in values with
String.valueOf() so a null degrades to the literal text "null"
instead of throwing.

Also validate ApplicationName against AWS's real CreateApplication
constraint (Pattern: [a-zA-Z0-9_.-]+, 1-128 chars) instead of only
requiring it non-blank -- this is both a genuine AWS-parity fix and
what keeps '%', '"', '\', or '$' out of the generated log4j2 pattern
in the first place.

Finally, close a gap the previous escaping missed: '$' wasn't
neutralized, so a name containing a log4j2 Lookup ('${env:...}',
'${sys:...}') would have it resolved against the process environment
at config-load time and baked into every emitted log line. Doubling
'$' the way '%' is doubled only defers the lookup to render time
rather than neutralizing it, so literalForLog4j2Pattern now drops '$'
outright.

* fix(kinesisanalytics): reject legacy invalid ApplicationName at StartApplication too

Greptile follow-up: an application persisted before the
ApplicationName validation existed (e.g. one with '$' in its name)
would bypass CreateApplication's new check entirely, and
StartApplication would silently generate a CloudWatch-log
applicationARN with the '$' dropped -- mismatching the real
ApplicationARN.

I verified empirically (a standalone harness against the actual
log4j-core jar) that there's no safe way to preserve '$' here: doubling
it or backslash-escaping it both still let log4j2 resolve the Lookup
and leak the referenced environment variable, so dropping it was the
only safe option. Given that, StartApplication now re-validates the
name and fails loudly for such legacy state instead of quietly
emitting a mismatched ARN -- real AWS could never have had this state
to begin with, so refusing to start it is the more AWS-faithful
outcome anyway.

* fix(kinesisanalytics): fix test compile error from Mockito generic inference

when(storageFactory.create(...)).thenReturn(store) failed to compile:
create()'s type parameter defaults to Object with no target-type
context to unify against the pre-declared, concretely-typed 'store'
variable, so thenReturn(store) rejected it as a type mismatch.
Switch to doReturn(store).when(storageFactory).create(...), matching
the same pattern already used for this exact scenario elsewhere in
this file (readinessPollerPersistsFlinkJobIdAssignedBeforeReachingRunning).
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-08-29 09:15:52 -05:00
1 parent ff61c2b2a5
commit aaae99282f
5 files changed
+277 -9

No files matched your search

@@ -57,6 +57,55 @@ class KinesisAnalyticsV2ServiceTest {
() -> service.createApplication(" ", "FLINK-1_18", ROLE, null, null));
}
@Test
void createApplicationRejectsNamesOutsideAwsCharsetAndLength() {
// AWS ApplicationName Pattern: [a-zA-Z0-9_.-]+, 1-128 chars. Rejecting this at the API
// boundary (matching real AWS) is also what keeps a name containing '%', '"', '\', or '$'
// from ever reaching FlinkContainerManager's generated log4j2 CloudWatch-log-format pattern,
// where those characters would otherwise be a log4j2 conversion-specifier/Lookup or JSON
// injection risk.
for (String badName : List.of("has spaces", "quote\"here", "percent%here", "dollar${x}",
"back\\slash", "a".repeat(129))) {
AwsException ex = assertThrows(AwsException.class,
() -> service.createApplication(badName, "FLINK-1_18", ROLE, null, null));
assertEquals("InvalidArgumentException", ex.getErrorCode());
}
}
@Test
void startApplicationRejectsLegacyStatePersistedBeforeNameValidationExisted() {
// Simulates an application created by a floci build older than
// createApplicationRejectsNamesOutsideAwsCharsetAndLength's check, by writing directly to
// storage (bypassing createApplication). startApplication must still reject it rather than
// silently generating a CloudWatch-log applicationARN that either drops the '$' (mismatching
// the real ApplicationARN) or, if some future change stopped dropping it, resolves it as a
// log4j2 Lookup.
AccountAwareStorageBackend<FlinkApplication> store =
AccountAwareStorageBackend.inMemory("000000000000");
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
Mockito.doReturn(store).when(storageFactory)
.create(Mockito.anyString(), Mockito.anyString(), Mockito.any());
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
var kaConfig = Mockito.mock(EmulatorConfig.KinesisAnalyticsServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.kinesisAnalytics()).thenReturn(kaConfig);
when(kaConfig.mock()).thenReturn(true);
when(config.defaultRegion()).thenReturn("us-east-1");
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
KinesisAnalyticsV2Service legacyState = new KinesisAnalyticsV2Service(
storageFactory, config, regionResolver, Mockito.mock(FlinkContainerManager.class));
FlinkApplication legacyApp = new FlinkApplication("dollar${x}",
"arn:aws:kinesisanalytics:us-east-1:000000000000:application/dollar${x}",
"FLINK-1_18", ROLE, "STREAMING");
store.putForAccount("000000000000", "dollar${x}", legacyApp);
AwsException ex = assertThrows(AwsException.class, () -> legacyState.startApplication("dollar${x}"));
assertEquals("InvalidArgumentException", ex.getErrorCode());
}
@Test
void createApplicationRequiresRuntimeEnvironment() {
assertThrows(AwsException.class,
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.kinesisanalytics.container;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
@@ -28,12 +29,14 @@ import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -97,6 +100,11 @@ class FlinkContainerManagerTest {
ContainerBuilder containerBuilder = new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer);
lifecycleManager = mock(ContainerLifecycleManager.class);
// The log4j-console.properties copy is now required (a failure fails cluster startup, see
// log4jConfigCopyFailureRollsBackTheClusterInsteadOfStartingWithTheStockLogFormat below), so
// every test that gets as far as create() succeeding needs a working docker client for that
// copy to land on by default.
when(lifecycleManager.getDockerClient()).thenReturn(mock(DockerClient.class, RETURNS_DEEP_STUBS));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
ContainerDetector containerDetector = mock(ContainerDetector.class);
RegionResolver regionResolver = mock(RegionResolver.class);
@@ -142,7 +150,9 @@ class FlinkContainerManagerTest {
when(storage.hostPersistentPath()).thenReturn("floci-data");
ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(
when(lifecycleManager.create(any())).thenReturn("jm-container-id");
when(lifecycleManager.getDockerClient()).thenReturn(mock(DockerClient.class, RETURNS_DEEP_STUBS));
when(lifecycleManager.startCreated(any(), any())).thenReturn(
new ContainerLifecycleManager.ContainerInfo("jm-container-id", Map.of(8081,
new ContainerLifecycleManager.EndpointInfo("localhost", 8081))));
@@ -207,10 +217,54 @@ class FlinkContainerManagerTest {
assertEquals(0, root.size());
}
@Test
void msfStyleLog4j2ConfigBakesInTheApplicationArnAndVersion() throws Exception {
FlinkApplication app = new FlinkApplication("demo",
"arn:aws:kinesisanalytics:us-east-1:000000000000:application/demo",
"FLINK-2_3", "arn:aws:iam::000000000000:role/x", "STREAMING");
app.setApplicationVersionId(2L);
String config = new String(manager.msfStyleLog4j2Config(app), java.nio.charset.StandardCharsets.UTF_8);
assertTrue(config.contains(
"\"applicationARN\":\"%enc{arn:aws:kinesisanalytics:us-east-1:000000000000:application/demo}{JSON}\""));
assertTrue(config.contains("\"applicationVersionId\":\"%enc{2}{JSON}\""));
assertTrue(config.contains("\"messageSchemaVersion\":\"1\""));
assertTrue(config.contains("appender.console.layout.type = PatternLayout"));
}
@Test
void msfStyleLog4j2ConfigEscapesLog4jAndPropertiesSyntaxInTheApplicationName() throws Exception {
// KinesisAnalyticsV2Service now rejects an ApplicationName outside AWS's own
// [a-zA-Z0-9_.-] charset, but this stays defensive in case some other caller ever builds a
// FlinkApplication directly: '%' would be a log4j2 conversion-specifier marker, '\' is a
// java.util.Properties escape character (Flink loads this file with Properties-style
// parsing), and '$' could start a log4j2 '${...}' Lookup that leaks an env var/system
// property into every log line -- none of that may reach the pattern unescaped.
FlinkApplication app = new FlinkApplication("100%-\\-${env:PATH}-owned",
"arn:aws:kinesisanalytics:us-east-1:000000000000:application/100%-\\-${env:PATH}-owned",
"FLINK-2_3", "arn:aws:iam::000000000000:role/x", "STREAMING");
app.setApplicationVersionId(1L);
String config = new String(manager.msfStyleLog4j2Config(app), java.nio.charset.StandardCharsets.UTF_8);
assertTrue(config.contains(
"\"applicationARN\":\"%enc{arn:aws:kinesisanalytics:us-east-1:000000000000:application/100%%-\\\\-{env:PATH}-owned}{JSON}\""));
java.util.Properties parsed = new java.util.Properties();
parsed.load(new java.io.ByteArrayInputStream(config.getBytes(java.nio.charset.StandardCharsets.UTF_8)));
String loadedPattern = parsed.getProperty("appender.console.layout.pattern");
assertTrue(loadedPattern.contains(
"\"applicationARN\":\"%enc{arn:aws:kinesisanalytics:us-east-1:000000000000:application/100%%-\\-{env:PATH}-owned}{JSON}\""));
assertFalse(loadedPattern.contains("${env:PATH}"), "the $ must not survive, or log4j2 would treat "
+ "this as a Lookup and resolve it against the environment at config-load time");
}
@Test
void bareClusterInjectsAwsSdkEnvironmentAndContainerReachability() {
FlinkApplication app = application("bare");
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo(
when(lifecycleManager.create(any())).thenReturn("jm-id");
when(lifecycleManager.startCreated(any(), any())).thenReturn(new ContainerInfo(
"jm-id", Map.of(8081, new EndpointInfo("localhost", 49152))));
manager.startCluster(app);
@@ -234,7 +288,8 @@ class FlinkContainerManagerTest {
app.setParallelism(3);
when(s3Service.getObject("code-bucket", "jobs/demo.jar", null))
.thenReturn(new S3Object("code-bucket", "jobs/demo.jar", new byte[]{1}, "application/java-archive"));
when(lifecycleManager.createAndStart(any()))
when(lifecycleManager.create(any())).thenReturn("jm-id").thenReturn("tm-id");
when(lifecycleManager.startCreated(any(), any()))
.thenReturn(new ContainerInfo("jm-id", Map.of(8081, new EndpointInfo("localhost", 49152))))
.thenReturn(new ContainerInfo("tm-id", Map.of()));
@@ -257,7 +312,7 @@ class FlinkContainerManagerTest {
@Test
void jobManagerStartFailureRemovesThePartialCluster() {
FlinkApplication app = application("jm-failure");
when(lifecycleManager.createAndStart(any())).thenThrow(new RuntimeException("jobmanager failed"));
when(lifecycleManager.create(any())).thenThrow(new RuntimeException("jobmanager failed"));
assertThrows(RuntimeException.class, () -> manager.startCluster(app));
@@ -274,9 +329,10 @@ class FlinkContainerManagerTest {
app.setCodeS3Key("jobs/demo.jar");
when(s3Service.getObject("code-bucket", "jobs/demo.jar", null))
.thenReturn(new S3Object("code-bucket", "jobs/demo.jar", new byte[]{1}, "application/java-archive"));
when(lifecycleManager.createAndStart(any()))
.thenReturn(new ContainerInfo("jm-id", Map.of(8081, new EndpointInfo("localhost", 49152))))
when(lifecycleManager.create(any())).thenReturn("jm-id")
.thenThrow(new RuntimeException("taskmanager failed"));
when(lifecycleManager.startCreated(any(), any()))
.thenReturn(new ContainerInfo("jm-id", Map.of(8081, new EndpointInfo("localhost", 49152))));
assertThrows(RuntimeException.class, () -> manager.startCluster(app));
@@ -287,9 +343,28 @@ class FlinkContainerManagerTest {
assertNull(app.getTaskManagerContainerId());
}
@Test
void log4jConfigCopyFailureRollsBackTheClusterInsteadOfStartingWithTheStockLogFormat() {
// Before this test, a failed copy of log4j-console.properties was only logged: startCreated()
// still ran and startCluster() reported success, so the cluster silently kept the stock
// (non-JSON) log format instead of the MSF-style CloudWatch schema this whole feature exists
// to provide. copyFileIntoContainer(..., required=true) now rethrows instead, so this failure
// takes the same create()-failure rollback path already covered above.
FlinkApplication app = application("log4j-copy-failure");
when(lifecycleManager.create(any())).thenReturn("jm-id");
when(lifecycleManager.getDockerClient()).thenThrow(new RuntimeException("docker copy unavailable"));
assertThrows(RuntimeException.class, () -> manager.startCluster(app));
verify(lifecycleManager, times(2)).removeIfExists("floci-kinesisanalytics-log4j-copy-failure");
verify(lifecycleManager, atLeastOnce()).removeIfExists("floci-kinesisanalytics-log4j-copy-failure-tm");
verify(lifecycleManager, Mockito.never()).startCreated(any(), any());
assertNull(app.getContainerId());
}
private List<ContainerSpec> captureCreatedSpecs() {
ArgumentCaptor<ContainerSpec> captor = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager, atLeastOnce()).createAndStart(captor.capture());
verify(lifecycleManager, atLeastOnce()).create(captor.capture());
return captor.getAllValues();
}
}