From 94795dd67b695b0e06377299d31b5559466f2a5e Mon Sep 17 00:00:00 2001 From: Allen Sanborn Date: Wed, 26 Aug 2026 20:03:05 -0500 Subject: [PATCH] fix(lambda): return VpcConfig, SnapStart and LoggingConfig from every read path (#2527) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(lambda): return VpcConfig, SnapStart and LoggingConfig CreateFunction and UpdateFunctionConfiguration accepted all three with a 200 and then omitted them from every read path, so a VPC-attached function read back unattached. Terraform refreshes aws_lambda_function.vpc_config, snap_start and logging_config on every plan, which made the resource permanently non-converging rather than cosmetically incomplete. VpcConfig was already stored but never serialised; SnapStart and LoggingConfig were dropped on the floor entirely. The response shapes are not the request shapes, per the AWS service model: - VpcConfigResponse adds VpcId, which VpcConfig has no member for. Resolved from the first subnet through Ec2Service, and left off when EC2 does not know the subnet — Lambda still accepts unmanaged subnet ids. - SnapStartResponse adds OptimizationStatus, which SnapStart has no member for. On only for a published version with ApplyOn=PublishedVersions. SnapStart and LoggingConfig are always present in a response, as on AWS: unset reads back as ApplyOn=None/OptimizationStatus=Off and LogFormat=Text with the default /aws/lambda/ log group. LogFormat=JSON additionally returns both log levels, defaulting to INFO. RuntimeVersionConfig is returned for managed runtimes. All of it is carried into PublishVersion snapshots. LoggingConfig is replaced wholesale on update rather than merged, matching AWS. Both enums are validated against the model's enum sets before any field is mutated, alongside the existing Layers and EFS pre-checks — updateFunction- Configuration mutates the live store object, so a late throw would leave a rejected update half-applied. * fix(lambda): validate LogGroup and stop storing Text-format log levels pgermosen's review on #2527 flagged two loose ends in LoggingConfig handling. LogGroup accepted any non-blank string instead of AWS's documented 1-512 character, [.\-_/#A-Za-z0-9]+ constraint. Separately, ApplicationLogLevel and SystemLogLevel were stored regardless of LogFormat but only ever surfaced by putLoggingConfig when the format is JSON, so a Text-format function could accept a log level, persist it, and never show it on any read path — the same accepted-then- forgotten shape this PR exists to remove. applyLoggingConfig now only keeps the levels when the resolved format is JSON, so nothing is stored that isn't observable. Also switches the two SnapStart integration tests off nodejs20.x, which AWS's SnapStart guide does not support, onto java21, and adds coverage for the LogGroup constraint, the JSON-only log level validation errors, the VpcConfig detach path, and the parity error wording pgermosen's review called out as unasserted. docs/services/lambda.md is updated to describe the LogGroup constraint and the Text-format no-op behavior. --- docs/services/lambda.md | 38 ++ .../services/lambda/LambdaController.java | 105 ++++ .../floci/services/lambda/LambdaService.java | 146 ++++- .../services/lambda/model/LambdaFunction.java | 28 + .../LambdaArnInvocationAccountTest.java | 3 + ...bdaVpcSnapStartLoggingIntegrationTest.java | 534 ++++++++++++++++++ 6 files changed, 853 insertions(+), 1 deletion(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/lambda/LambdaVpcSnapStartLoggingIntegrationTest.java diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 045612cb8f..754d0e2d8d 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -446,6 +446,44 @@ No extra configuration or `cap_add` is needed because Docker containers have `CAP_NET_BIND_SERVICE` in their default capability set, so Floci (running as a non-root user) can bind UDP/53 without any changes to your Compose file. +### VpcConfig, SnapStart and LoggingConfig + +All three round-trip through `CreateFunction`, `UpdateFunctionConfiguration`, +`GetFunctionConfiguration`, `GetFunction`, `ListFunctions` and `PublishVersion`. + +The response shapes are **not** the request shapes, and Floci follows the AWS model +rather than echoing the request back: + +| Field | Request shape | Response shape | Extra members Floci fills in | +|---|---|---|---| +| `VpcConfig` | `VpcConfig` | `VpcConfigResponse` | `VpcId`, resolved from the first subnet via EC2 | +| `SnapStart` | `SnapStart` | `SnapStartResponse` | `OptimizationStatus` — `On` only for a published version with `ApplyOn=PublishedVersions`, `Off` for `$LATEST` | +| `LoggingConfig` | `LoggingConfig` | `LoggingConfig` | — | + +`SnapStart` and `LoggingConfig` are always present in a response, as on AWS: an +unset function reads back `SnapStart={ApplyOn: None, OptimizationStatus: Off}` and +`LoggingConfig={LogFormat: Text, LogGroup: /aws/lambda/}`. With +`LogFormat=JSON`, `ApplicationLogLevel` and `SystemLogLevel` are also returned, +defaulting to `INFO`. Terraform treats these as `Computed` blocks, so a missing one +is a permanent diff rather than a cosmetic omission. + +`LoggingConfig` is replaced wholesale on update, not merged — an update naming only +`LogFormat` resets `LogGroup` to the default. + +`LogGroup` is validated against AWS's documented constraint: 1-512 characters matching +`[.\-_/#A-Za-z0-9]+`. `ApplicationLogLevel` and `SystemLogLevel` are accepted with any +`LogFormat` but are only ever stored — and therefore only ever returned — when the +resolved format is `JSON`; supplying them with `LogFormat=Text` is not an error, it is +simply a no-op, matching the fact that the response never surfaces them for Text. + +`VpcConfig` is omitted entirely while the function is not attached to a VPC. +Subnets that EC2 does not know about are still accepted and returned; only `VpcId` +is left off in that case. + +`RuntimeVersionConfig.RuntimeVersionArn` is returned for managed (non-image) +runtimes. Its value is derived from the runtime name, so it is stable across +restarts. + ### File system configs `FileSystemConfigs` accepts one EFS access point and mounts it under the diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java index a344eefd2a..b1bc49bf24 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java @@ -28,9 +28,13 @@ import jakarta.ws.rs.core.UriBuilder; import jakarta.ws.rs.core.UriInfo; import org.jboss.logging.Logger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import java.util.HexFormat; import java.util.List; import java.util.Map; @@ -660,8 +664,109 @@ public class LambdaController { fn.getEnvironment().forEach(vars::put); } + putVpcConfig(node, fn); + putSnapStart(node, fn); + putLoggingConfig(node, fn); + putRuntimeVersionConfig(node, fn); + @SuppressWarnings("unchecked") Map result = objectMapper.convertValue(node, Map.class); return result; } + + /** + * VpcConfigResponse, not VpcConfig: the response shape adds VpcId, which the request shape + * has no member for. Emitted only while the function is actually attached to a VPC — AWS + * omits the block entirely once the last subnet and security group are removed. + */ + private void putVpcConfig(ObjectNode node, LambdaFunction fn) { + Map vpcConfig = fn.getVpcConfig(); + List subnetIds = stringList(vpcConfig, "SubnetIds"); + List securityGroupIds = stringList(vpcConfig, "SecurityGroupIds"); + if (subnetIds.isEmpty() && securityGroupIds.isEmpty()) { + return; + } + ObjectNode vpcNode = node.putObject("VpcConfig"); + ArrayNode subnetNode = vpcNode.putArray("SubnetIds"); + subnetIds.forEach(subnetNode::add); + ArrayNode securityGroupNode = vpcNode.putArray("SecurityGroupIds"); + securityGroupIds.forEach(securityGroupNode::add); + if (fn.getVpcId() != null) { + vpcNode.put("VpcId", fn.getVpcId()); + } + vpcNode.put("Ipv6AllowedForDualStack", + Boolean.TRUE.equals(vpcConfig.get("Ipv6AllowedForDualStack"))); + } + + /** + * SnapStartResponse, not SnapStart: the response adds OptimizationStatus, which the request + * shape has no member for. AWS only reports {@code On} for a published version whose snapshot + * has been optimized; {@code $LATEST} is always {@code Off} even with ApplyOn set. + */ + private void putSnapStart(ObjectNode node, LambdaFunction fn) { + String applyOn = fn.getSnapStartApplyOn() != null ? fn.getSnapStartApplyOn() : "None"; + boolean optimized = "PublishedVersions".equals(applyOn) && !"$LATEST".equals(fn.getVersion()); + node.putObject("SnapStart") + .put("ApplyOn", applyOn) + .put("OptimizationStatus", optimized ? "On" : "Off"); + } + + /** + * Always present, as on AWS: an unset LoggingConfig still reads back as Text plus the default + * {@code /aws/lambda/} log group. The two log levels are JSON-format-only. + */ + private void putLoggingConfig(ObjectNode node, LambdaFunction fn) { + String logFormat = fn.getLogFormat() != null ? fn.getLogFormat() : "Text"; + ObjectNode logging = node.putObject("LoggingConfig"); + logging.put("LogFormat", logFormat); + if ("JSON".equals(logFormat)) { + logging.put("ApplicationLogLevel", + fn.getApplicationLogLevel() != null ? fn.getApplicationLogLevel() : "INFO"); + logging.put("SystemLogLevel", + fn.getSystemLogLevel() != null ? fn.getSystemLogLevel() : "INFO"); + } + logging.put("LogGroup", fn.getLogGroup() != null && !fn.getLogGroup().isBlank() + ? fn.getLogGroup() + : "/aws/lambda/" + fn.getFunctionName()); + } + + /** Managed-runtime only: AWS omits it for container images, which pin their own runtime. */ + private void putRuntimeVersionConfig(ObjectNode node, LambdaFunction fn) { + if ("Image".equals(fn.getPackageType()) || fn.getRuntime() == null || fn.getRuntime().isBlank()) { + return; + } + node.putObject("RuntimeVersionConfig") + .put("RuntimeVersionArn", runtimeVersionArn(fn)); + } + + private static String runtimeVersionArn(LambdaFunction fn) { + String region = "us-east-1"; + String[] arnParts = fn.getFunctionArn() != null ? fn.getFunctionArn().split(":") : new String[0]; + if (arnParts.length > 3 && !arnParts[3].isBlank()) { + region = arnParts[3]; + } + return "arn:aws:lambda:" + region + "::runtime:" + runtimeVersionId(fn.getRuntime()); + } + + /** + * AWS identifies a runtime version by a 64-hex digest. Derived from the runtime name so the + * same runtime keeps the same id across restarts — a value that churned would show up as a + * perpetual diff in anything that records it. + */ + private static String runtimeVersionId(String runtime) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256") + .digest(runtime.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 unavailable", e); + } + } + + private static List stringList(Map config, String key) { + if (config == null || !(config.get(key) instanceof List values)) { + return List.of(); + } + return values.stream().filter(java.util.Objects::nonNull).map(Object::toString).toList(); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java index 2a5de66562..5e686e66f2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java @@ -10,6 +10,8 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.core.resource.ExplorerResource; import io.github.hectorvent.floci.core.resource.ResourceProvider; import io.github.hectorvent.floci.core.resource.SupportedResourceType; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.Subnet; import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping; import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfig; import io.github.hectorvent.floci.services.lambda.model.InvocationType; @@ -59,6 +61,7 @@ public class LambdaService implements ResourceProvider { + "(?:(?:-gov)|(?:-iso(?:b)?))?-[a-z]+-\\d:" + "\\d{12}:access-point/fsap-[a-f0-9]{17}$"); private static final Pattern FILE_SYSTEM_LOCAL_MOUNT_PATH = Pattern.compile("^/mnt/[A-Za-z0-9._-]+$"); + private static final Pattern LOG_GROUP_PATTERN = Pattern.compile("[.\\-_/#A-Za-z0-9]+"); private final LambdaFunctionStore functionStore; private final LambdaExecutorService executorService; @@ -77,6 +80,7 @@ public class LambdaService implements ResourceProvider { private final DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller; private final StorageFactory storageFactory; private final LambdaLayerService layerService; + private final Ec2Service ec2Service; private Map versionCounters = new ConcurrentHashMap<>(); private Map eventInvokeConfigs = new ConcurrentHashMap<>(); /** @@ -146,6 +150,7 @@ public class LambdaService implements ResourceProvider { this.dynamodbStreamsPoller = null; this.storageFactory = storageFactory; this.layerService = null; + this.ec2Service = null; } @Inject @@ -165,7 +170,8 @@ public class LambdaService implements ResourceProvider { KinesisEventSourcePoller kinesisPoller, DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller, StorageFactory storageFactory, - LambdaLayerService layerService) { + LambdaLayerService layerService, + Ec2Service ec2Service) { this.functionStore = functionStore; this.executorService = executorService; this.concurrencyLimiter = concurrencyLimiter; @@ -183,6 +189,7 @@ public class LambdaService implements ResourceProvider { this.dynamodbStreamsPoller = dynamodbStreamsPoller; this.storageFactory = storageFactory; this.layerService = layerService; + this.ec2Service = ec2Service; } // Real AWS validates a function's Layers eagerly at CreateFunction/UpdateFunctionConfiguration @@ -384,8 +391,12 @@ public class LambdaService implements ResourceProvider { @SuppressWarnings("unchecked") Map vpc = (Map) request.get("VpcConfig"); fn.setVpcConfig(vpc); + fn.setVpcId(resolveVpcId(region, vpc)); } + applySnapStart(fn, request.get("SnapStart")); + applyLoggingConfig(fn, request.get("LoggingConfig")); + List fileSystemConfigs = parseFileSystemConfigs(request.get("FileSystemConfigs")); validateFileSystemVpcConfig(fileSystemConfigs, fn.getVpcConfig()); @@ -526,6 +537,12 @@ public class LambdaService implements ResourceProvider { if (request.containsKey("Layers")) { validateLayersResolvable(layerList); } + if (request.containsKey("SnapStart")) { + validateSnapStart(request.get("SnapStart")); + } + if (request.containsKey("LoggingConfig")) { + validateLoggingConfig(request.get("LoggingConfig")); + } Map requestedVpcConfig = fn.getVpcConfig(); if (request.get("VpcConfig") instanceof Map) { @@ -619,9 +636,18 @@ public class LambdaService implements ResourceProvider { if (request.containsKey("VpcConfig")) { if (request.get("VpcConfig") instanceof Map) { fn.setVpcConfig(requestedVpcConfig); + fn.setVpcId(resolveVpcId(region, requestedVpcConfig)); } } + if (request.containsKey("SnapStart")) { + applySnapStart(fn, request.get("SnapStart")); + } + + if (request.containsKey("LoggingConfig")) { + applyLoggingConfig(fn, request.get("LoggingConfig")); + } + if (request.containsKey("FileSystemConfigs")) { fn.setFileSystemConfigs(requestedFileSystemConfigs); } @@ -1137,6 +1163,12 @@ public class LambdaService implements ResourceProvider { snapshot.setVpcConfig(fn.getVpcConfig() == null ? null : new java.util.HashMap<>(fn.getVpcConfig())); + snapshot.setVpcId(fn.getVpcId()); + snapshot.setSnapStartApplyOn(fn.getSnapStartApplyOn()); + snapshot.setLogFormat(fn.getLogFormat()); + snapshot.setApplicationLogLevel(fn.getApplicationLogLevel()); + snapshot.setSystemLogLevel(fn.getSystemLogLevel()); + snapshot.setLogGroup(fn.getLogGroup()); snapshot.setFileSystemConfigs(new ArrayList<>(fn.getFileSystemConfigs())); snapshot.setLastModified(System.currentTimeMillis()); snapshot.setRevisionId(UUID.randomUUID().toString()); @@ -1219,6 +1251,118 @@ public class LambdaService implements ResourceProvider { } } + /** + * The VpcConfig request shape carries no VpcId; VpcConfigResponse does. AWS derives it from + * the subnets the function is attached to, so resolve it once at attach time and store it. + * A subnet EC2 has never heard of resolves to null rather than failing the call - Floci's + * Lambda accepts unmanaged subnet ids, and CreateFunction must not start rejecting them. + */ + private String resolveVpcId(String region, Map vpcConfig) { + if (ec2Service == null || !hasValues(vpcConfig, "SubnetIds")) { + return null; + } + for (Object subnetId : (List) vpcConfig.get("SubnetIds")) { + if (subnetId == null) { + continue; + } + try { + List found = ec2Service.describeSubnets(region, List.of(subnetId.toString()), Map.of()); + if (!found.isEmpty() && found.get(0).getVpcId() != null) { + return found.get(0).getVpcId(); + } + } catch (RuntimeException e) { + LOG.debugv(e, "Could not resolve VpcId for subnet {0} in {1}", subnetId, region); + } + } + return null; + } + + private static void validateSnapStart(Object value) { + if (!(value instanceof Map snapStart)) { + return; + } + Object applyOn = snapStart.get("ApplyOn"); + if (applyOn != null && !"None".equals(applyOn) && !"PublishedVersions".equals(applyOn)) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + applyOn + "' at 'snapStart.applyOn' failed to " + + "satisfy constraint: Member must satisfy enum value set: " + + "[PublishedVersions, None]", 400); + } + } + + private static void applySnapStart(LambdaFunction fn, Object value) { + if (!(value instanceof Map snapStart)) { + return; + } + validateSnapStart(value); + Object applyOn = snapStart.get("ApplyOn"); + fn.setSnapStartApplyOn(applyOn instanceof String s && !s.isBlank() ? s : "None"); + } + + private static void validateLoggingConfig(Object value) { + if (!(value instanceof Map logging)) { + return; + } + validateEnum(logging.get("LogFormat"), "loggingConfig.logFormat", List.of("JSON", "Text")); + validateEnum(logging.get("ApplicationLogLevel"), "loggingConfig.applicationLogLevel", + List.of("TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL")); + validateEnum(logging.get("SystemLogLevel"), "loggingConfig.systemLogLevel", + List.of("DEBUG", "INFO", "WARN")); + validateLogGroup(logging.get("LogGroup")); + } + + private static void validateEnum(Object value, String field, List allowed) { + if (value == null || allowed.contains(value)) { + return; + } + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + value + "' at '" + field + "' failed to satisfy " + + "constraint: Member must satisfy enum value set: [" + + String.join(", ", allowed) + "]", 400); + } + + /** + * LogGroup is the one LoggingConfig member with a documented length and character + * constraint rather than an enum: 1-512 characters, {@code [.\-_/#A-Za-z0-9]+}. + */ + private static void validateLogGroup(Object value) { + if (!(value instanceof String group) || group.isBlank()) { + return; + } + if (group.length() > 512 || !LOG_GROUP_PATTERN.matcher(group).matches()) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + group + "' at 'loggingConfig.logGroup' failed to " + + "satisfy constraint: Member must satisfy regular expression pattern: " + + "[.\\-_/#A-Za-z0-9]+ or member must have length less than or equal to 512", 400); + } + } + + /** + * LoggingConfig is replaced wholesale, not merged: AWS resets any member the request omits + * back to its default, so an update that names only LogFormat drops a previously set LogGroup. + * + *

ApplicationLogLevel and SystemLogLevel are JSON-format-only: {@link #putLoggingConfig} + * never surfaces them for a Text-format function. Storing them anyway would leave state + * that is accepted, persisted and then never observable through any read path — the same + * accepted-then-forgotten shape this fix removes elsewhere — so they are only kept when the + * resolved format is JSON. + */ + private static void applyLoggingConfig(LambdaFunction fn, Object value) { + if (!(value instanceof Map logging)) { + return; + } + validateLoggingConfig(value); + String format = logging.get("LogFormat") instanceof String f && !f.isBlank() ? f : "Text"; + boolean json = "JSON".equals(format); + fn.setLogFormat(format); + fn.setApplicationLogLevel(json && logging.get("ApplicationLogLevel") instanceof String level + && !level.isBlank() ? level : null); + fn.setSystemLogLevel(json && logging.get("SystemLogLevel") instanceof String level + && !level.isBlank() ? level : null); + fn.setLogGroup(logging.get("LogGroup") instanceof String group && !group.isBlank() + ? group : null); + } + private static boolean hasValues(Map config, String key) { return config != null && config.get(key) instanceof List values diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java index 2de33e447e..11e0707b16 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java @@ -49,6 +49,16 @@ public class LambdaFunction { private List layers = new ArrayList<>(); private String kmsKeyArn; private Map vpcConfig; + /** + * Resolved at attach time from the first VpcConfig subnet. Response-only: the AWS model's + * VpcConfigResponse carries VpcId, while the VpcConfig request shape does not. + */ + private String vpcId; + private String snapStartApplyOn = "None"; + private String logFormat = "Text"; + private String applicationLogLevel; + private String systemLogLevel; + private String logGroup; private List fileSystemConfigs = new ArrayList<>(); private String codeSha256; @@ -169,6 +179,24 @@ public class LambdaFunction { public Map getVpcConfig() { return vpcConfig; } public void setVpcConfig(Map vpcConfig) { this.vpcConfig = vpcConfig; } + public String getVpcId() { return vpcId; } + public void setVpcId(String vpcId) { this.vpcId = vpcId; } + + public String getSnapStartApplyOn() { return snapStartApplyOn; } + public void setSnapStartApplyOn(String snapStartApplyOn) { this.snapStartApplyOn = snapStartApplyOn; } + + public String getLogFormat() { return logFormat; } + public void setLogFormat(String logFormat) { this.logFormat = logFormat; } + + public String getApplicationLogLevel() { return applicationLogLevel; } + public void setApplicationLogLevel(String applicationLogLevel) { this.applicationLogLevel = applicationLogLevel; } + + public String getSystemLogLevel() { return systemLogLevel; } + public void setSystemLogLevel(String systemLogLevel) { this.systemLogLevel = systemLogLevel; } + + public String getLogGroup() { return logGroup; } + public void setLogGroup(String logGroup) { this.logGroup = logGroup; } + public List getFileSystemConfigs() { return fileSystemConfigs; } public void setFileSystemConfigs(List fileSystemConfigs) { this.fileSystemConfigs = fileSystemConfigs == null ? new ArrayList<>() : new ArrayList<>(fileSystemConfigs); diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java index 0eb0ac3c25..8a5008fc64 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java @@ -66,6 +66,7 @@ class LambdaArnInvocationAccountTest { null, null, null, + null, null); InvokeResult result = service.invokeArn(functionArn, "{}".getBytes(), InvocationType.Event); @@ -125,6 +126,7 @@ class LambdaArnInvocationAccountTest { null, null, null, + null, null); InvokeResult versionResult = service.invokeArn( @@ -262,6 +264,7 @@ class LambdaArnInvocationAccountTest { null, null, null, + null, null); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaVpcSnapStartLoggingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaVpcSnapStartLoggingIntegrationTest.java new file mode 100644 index 0000000000..dd66994ee8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaVpcSnapStartLoggingIntegrationTest.java @@ -0,0 +1,534 @@ +package io.github.hectorvent.floci.services.lambda; + +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.Subnet; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; + +/** + * VpcConfig, SnapStart and LoggingConfig must survive CreateFunction and + * UpdateFunctionConfiguration and read back from GetFunctionConfiguration / GetFunction. + * Terraform refreshes all three on every plan, so a field accepted and then dropped is a + * permanent non-converging diff rather than a cosmetic omission. + * + *

The request and response shapes deliberately differ: VpcConfigResponse adds VpcId and + * SnapStartResponse adds OptimizationStatus, neither of which the caller can send. + */ +@QuarkusTest +class LambdaVpcSnapStartLoggingIntegrationTest { + + private static final String BASE_PATH = "/2015-03-31"; + private static final String REGION = "us-east-1"; + private static final String SECURITY_GROUP_ID = "sg-0123456789abcdef0"; + + @Inject + Ec2Service ec2Service; + + private String subnetId; + private String expectedVpcId; + + @BeforeEach + void resolveSubnet() { + Subnet subnet = ec2Service.describeSubnets(REGION, List.of(), Map.of()).get(0); + subnetId = subnet.getSubnetId(); + expectedVpcId = subnet.getVpcId(); + } + + private void createFunction(String name, String extraJson) { + createFunction(name, "nodejs20.x", extraJson); + } + + /** + * SnapStart is only available on a subset of managed runtimes (Java 11+, Python 3.12+, + * .NET 8+); {@code nodejs20.x} is not among them. Tests that exercise SnapStart use this + * overload with a supported runtime so they don't lock in a create AWS would reject. + */ + private void createFunction(String name, String runtime, String extraJson) { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "%s", + "Runtime": "%s", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler"%s + } + """.formatted(name, runtime, extraJson)) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(201); + } + + private String vpcConfigJson() { + return """ + , + "VpcConfig": { + "SubnetIds": ["%s"], + "SecurityGroupIds": ["%s"] + }""".formatted(subnetId, SECURITY_GROUP_ID); + } + + @Test + void createFunctionReturnsVpcConfigWithResolvedVpcId() { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "vpc-create-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler"%s + } + """.formatted(vpcConfigJson())) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(201) + .body("VpcConfig.SubnetIds", contains(subnetId)) + .body("VpcConfig.SecurityGroupIds", contains(SECURITY_GROUP_ID)) + .body("VpcConfig.VpcId", equalTo(expectedVpcId)) + .body("VpcConfig.Ipv6AllowedForDualStack", equalTo(false)); + } + + @Test + void getFunctionConfigurationReturnsVpcConfig() { + createFunction("vpc-get-config-fn", vpcConfigJson()); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-get-config-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig.SubnetIds", contains(subnetId)) + .body("VpcConfig.SecurityGroupIds", contains(SECURITY_GROUP_ID)) + .body("VpcConfig.VpcId", equalTo(expectedVpcId)); + } + + @Test + void getFunctionReturnsVpcConfig() { + createFunction("vpc-get-fn", vpcConfigJson()); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-get-fn") + .then() + .statusCode(200) + .body("Configuration.VpcConfig.SubnetIds", contains(subnetId)) + .body("Configuration.VpcConfig.SecurityGroupIds", contains(SECURITY_GROUP_ID)) + .body("Configuration.VpcConfig.VpcId", equalTo(expectedVpcId)); + } + + @Test + void updateFunctionConfigurationAttachesVpcAndRoundTrips() { + createFunction("vpc-update-fn", ""); + + given() + .contentType("application/json") + .body(""" + { + "VpcConfig": { + "SubnetIds": ["%s"], + "SecurityGroupIds": ["%s"] + } + } + """.formatted(subnetId, SECURITY_GROUP_ID)) + .when() + .put(BASE_PATH + "/functions/vpc-update-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig.SubnetIds", contains(subnetId)) + .body("VpcConfig.VpcId", equalTo(expectedVpcId)); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-update-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig.SubnetIds", contains(subnetId)) + .body("VpcConfig.SecurityGroupIds", contains(SECURITY_GROUP_ID)) + .body("VpcConfig.VpcId", equalTo(expectedVpcId)); + } + + @Test + void vpcConfigIsAbsentWhenTheFunctionIsNotAttached() { + createFunction("vpc-absent-fn", ""); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-absent-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig", nullValue()); + } + + @Test + void unknownSubnetStillRoundTripsWithoutVpcId() { + createFunction("vpc-unmanaged-subnet-fn", """ + , + "VpcConfig": { + "SubnetIds": ["subnet-ffffffffffffffff0"], + "SecurityGroupIds": ["%s"] + }""".formatted(SECURITY_GROUP_ID)); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-unmanaged-subnet-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig.SubnetIds", contains("subnet-ffffffffffffffff0")) + .body("VpcConfig.VpcId", nullValue()); + } + + @Test + void snapStartAndLoggingConfigDefaultsArePopulatedWhenUnset() { + createFunction("defaults-fn", ""); + + given() + .when() + .get(BASE_PATH + "/functions/defaults-fn/configuration") + .then() + .statusCode(200) + .body("SnapStart.ApplyOn", equalTo("None")) + .body("SnapStart.OptimizationStatus", equalTo("Off")) + .body("LoggingConfig.LogFormat", equalTo("Text")) + .body("LoggingConfig.LogGroup", equalTo("/aws/lambda/defaults-fn")) + .body("LoggingConfig.ApplicationLogLevel", nullValue()) + .body("RuntimeVersionConfig.RuntimeVersionArn", startsWith("arn:aws:lambda:us-east-1::runtime:")); + } + + @Test + void snapStartRoundTripsAndOptimizationStatusIsResponseOnly() { + createFunction("snapstart-fn", "java21", """ + , + "SnapStart": {"ApplyOn": "PublishedVersions"}"""); + + given() + .when() + .get(BASE_PATH + "/functions/snapstart-fn/configuration") + .then() + .statusCode(200) + .body("SnapStart.ApplyOn", equalTo("PublishedVersions")) + .body("SnapStart.OptimizationStatus", equalTo("Off")); + + given() + .contentType("application/json") + .body("{}") + .when() + .post(BASE_PATH + "/functions/snapstart-fn/versions") + .then() + .statusCode(201) + .body("SnapStart.ApplyOn", equalTo("PublishedVersions")) + .body("SnapStart.OptimizationStatus", equalTo("On")); + } + + @Test + void updateFunctionConfigurationRoundTripsSnapStart() { + createFunction("snapstart-update-fn", "java21", ""); + + given() + .contentType("application/json") + .body("{\"SnapStart\": {\"ApplyOn\": \"PublishedVersions\"}}") + .when() + .put(BASE_PATH + "/functions/snapstart-update-fn/configuration") + .then() + .statusCode(200) + .body("SnapStart.ApplyOn", equalTo("PublishedVersions")); + + given() + .when() + .get(BASE_PATH + "/functions/snapstart-update-fn/configuration") + .then() + .statusCode(200) + .body("SnapStart.ApplyOn", equalTo("PublishedVersions")); + } + + @Test + void snapStartRejectsValueOutsideTheEnum() { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "snapstart-invalid-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler", + "SnapStart": {"ApplyOn": "Always"} + } + """) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value 'Always' at 'snapStart.applyOn' " + + "failed to satisfy constraint: Member must satisfy enum value set: " + + "[PublishedVersions, None]")); + } + + @Test + void jsonLoggingConfigRoundTripsWithLogLevels() { + createFunction("logging-json-fn", """ + , + "LoggingConfig": { + "LogFormat": "JSON", + "ApplicationLogLevel": "DEBUG", + "SystemLogLevel": "WARN", + "LogGroup": "/custom/log/group" + }"""); + + given() + .when() + .get(BASE_PATH + "/functions/logging-json-fn/configuration") + .then() + .statusCode(200) + .body("LoggingConfig.LogFormat", equalTo("JSON")) + .body("LoggingConfig.ApplicationLogLevel", equalTo("DEBUG")) + .body("LoggingConfig.SystemLogLevel", equalTo("WARN")) + .body("LoggingConfig.LogGroup", equalTo("/custom/log/group")); + } + + @Test + void jsonLoggingConfigDefaultsBothLogLevelsToInfo() { + createFunction("logging-json-default-fn", """ + , + "LoggingConfig": {"LogFormat": "JSON"}"""); + + given() + .when() + .get(BASE_PATH + "/functions/logging-json-default-fn/configuration") + .then() + .statusCode(200) + .body("LoggingConfig.LogFormat", equalTo("JSON")) + .body("LoggingConfig.ApplicationLogLevel", equalTo("INFO")) + .body("LoggingConfig.SystemLogLevel", equalTo("INFO")) + .body("LoggingConfig.LogGroup", equalTo("/aws/lambda/logging-json-default-fn")); + } + + @Test + void updateFunctionConfigurationReplacesLoggingConfigWholesale() { + createFunction("logging-update-fn", """ + , + "LoggingConfig": { + "LogFormat": "JSON", + "ApplicationLogLevel": "DEBUG", + "LogGroup": "/custom/log/group" + }"""); + + given() + .contentType("application/json") + .body("{\"LoggingConfig\": {\"LogFormat\": \"Text\"}}") + .when() + .put(BASE_PATH + "/functions/logging-update-fn/configuration") + .then() + .statusCode(200) + .body("LoggingConfig.LogFormat", equalTo("Text")) + .body("LoggingConfig.LogGroup", equalTo("/aws/lambda/logging-update-fn")); + + given() + .when() + .get(BASE_PATH + "/functions/logging-update-fn/configuration") + .then() + .statusCode(200) + .body("LoggingConfig.LogFormat", equalTo("Text")) + .body("LoggingConfig.ApplicationLogLevel", nullValue()) + .body("LoggingConfig.LogGroup", equalTo("/aws/lambda/logging-update-fn")); + } + + @Test + void loggingConfigRejectsLogFormatOutsideTheEnum() { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "logging-invalid-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler", + "LoggingConfig": {"LogFormat": "YAML"} + } + """) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value 'YAML' at 'loggingConfig.logFormat' " + + "failed to satisfy constraint: Member must satisfy enum value set: [JSON, Text]")); + } + + @Test + void loggingConfigRejectsApplicationLogLevelOutsideTheEnum() { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "logging-invalid-app-level-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler", + "LoggingConfig": {"LogFormat": "JSON", "ApplicationLogLevel": "VERBOSE"} + } + """) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value 'VERBOSE' at " + + "'loggingConfig.applicationLogLevel' failed to satisfy constraint: Member must satisfy " + + "enum value set: [TRACE, DEBUG, INFO, WARN, ERROR, FATAL]")); + } + + @Test + void loggingConfigRejectsSystemLogLevelOutsideTheEnum() { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "logging-invalid-system-level-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler", + "LoggingConfig": {"LogFormat": "JSON", "SystemLogLevel": "TRACE"} + } + """) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value 'TRACE' at " + + "'loggingConfig.systemLogLevel' failed to satisfy constraint: Member must satisfy " + + "enum value set: [DEBUG, INFO, WARN]")); + } + + @Test + void loggingConfigRejectsLogGroupOutsideTheDocumentedPattern() { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "logging-invalid-group-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler", + "LoggingConfig": {"LogGroup": "my log group"} + } + """) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void loggingConfigRejectsLogGroupLongerThanFiveHundredTwelveCharacters() { + String tooLong = "a".repeat(513); + + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "logging-invalid-long-group-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler", + "LoggingConfig": {"LogGroup": "%s"} + } + """.formatted(tooLong)) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void textFormatLogLevelsAreAcceptedButNeverStoredOrReturned() { + createFunction("logging-text-levels-fn", """ + , + "LoggingConfig": { + "LogFormat": "Text", + "ApplicationLogLevel": "DEBUG", + "SystemLogLevel": "WARN" + }"""); + + given() + .when() + .get(BASE_PATH + "/functions/logging-text-levels-fn/configuration") + .then() + .statusCode(200) + .body("LoggingConfig.LogFormat", equalTo("Text")) + .body("LoggingConfig.ApplicationLogLevel", nullValue()) + .body("LoggingConfig.SystemLogLevel", nullValue()); + } + + @Test + void updateFunctionConfigurationDetachesVpcConfigAndClearsVpcId() { + createFunction("vpc-detach-fn", vpcConfigJson()); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-detach-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig.VpcId", equalTo(expectedVpcId)); + + given() + .contentType("application/json") + .body(""" + { + "VpcConfig": { + "SubnetIds": [], + "SecurityGroupIds": [] + } + } + """) + .when() + .put(BASE_PATH + "/functions/vpc-detach-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig", nullValue()); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-detach-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig", nullValue()); + } + + @Test + void publishedVersionCarriesVpcAndLoggingConfig() { + createFunction("version-carry-fn", vpcConfigJson() + """ + , + "LoggingConfig": {"LogFormat": "JSON", "LogGroup": "/custom/version/group"}"""); + + given() + .contentType("application/json") + .body("{}") + .when() + .post(BASE_PATH + "/functions/version-carry-fn/versions") + .then() + .statusCode(201) + .body("Version", notNullValue()) + .body("VpcConfig.SubnetIds", contains(subnetId)) + .body("VpcConfig.VpcId", equalTo(expectedVpcId)) + .body("LoggingConfig.LogFormat", equalTo("JSON")) + .body("LoggingConfig.LogGroup", equalTo("/custom/version/group")); + } +}