Light, fluffy, and always free - The AWS Local Emulator alternative
feat(lambdaweb): check the egress network connector as AWS does (#6647)
TATSUNO “Taz” Yasuhiroec13eda2212c
diff --git a/docs/services/lambda-web-functions.md b/docs/services/lambda-web-functions.mdindex a2c03e29ef..c03c199363 100644--- a/docs/services/lambda-web-functions.md+++ b/docs/services/lambda-web-functions.md@@ -39,7 +39,8 @@ The `Lambda Web` service model (apiVersion 2025-03-07, `aws lambda-web` in the A- **Code comes from S3 only.** The object named in `buildConfig.codeConfig.s3Object` must exist in Floci's S3, as on AWS. A request without `versionId` is refused when the latest version is the null version, so the object has to be written after the bucket's versioning is enabled, as on AWS. When IAM enforcement is on, the bucket policy must also let `lambda.amazonaws.com` take `s3:GetObjectVersion` on the object. The policy sees the new revision ARN as `aws:SourceArn`, the function's account as `aws:SourceAccount` and the version Lambda reads as `s3:VersionId`. As on AWS, `s3:GetObject` is not evaluated, although the error names it. Floci does not check the caller's own S3 permissions or the KMS key policy of an encrypted object.- **Each revision keeps its own copy of the code**, read at creation from the version the request names or the current one, under the Lambda `code-path`. As on AWS, a later write or delete in the bucket does not change what the revision runs. AWS moves a revision to `Failed` when it later finds its object version gone, which Floci does not do.- **Revision cleanup:** when a revision turns `Active` and the function has more than 50, the oldest revisions that no endpoint routes to are deleted until 50 are left, `Failed` ones included, as on AWS. A new `Failed` revision deletes nothing. The revision that a `LatestRevision` endpoint leaves is not deleted before the next revision turns `Active`, as on AWS.-- **Execution role:** a role in another account is `403 AccessDeniedException` "Cross-account pass role is not allowed.". A role that does not exist in IAM, or whose trust policy does not let `lambda.amazonaws.com` assume it, is `400 ValidationException` "The execution role <arn> cannot be assumed by lambda.amazonaws.com. Verify its trust policy. If the role was just created, retry in a few seconds.". As on AWS, this check sets no `aws:SourceAccount` or `aws:SourceArn`, so a trust policy that requires either refuses the role. The network connector ARN is checked for shape only.+- **Execution role:** a role in another account is `403 AccessDeniedException` "Cross-account pass role is not allowed.". A role that does not exist in IAM, or whose trust policy does not let `lambda.amazonaws.com` assume it, is `400 ValidationException` "The execution role <arn> cannot be assumed by lambda.amazonaws.com. Verify its trust policy. If the role was just created, retry in a few seconds.". As on AWS, this check sets no `aws:SourceAccount` or `aws:SourceArn`, so a trust policy that requires either refuses the role.+- **Egress network connectors:** `egressNetworkConnectorArn` names a connector version by the connector id, in the function's region, as on AWS. A version that does not exist, a connector name, or another region is `404 ResourceNotFoundException` "The egress network connector <arn> does not exist.". A connector without `WebFunction` in its `AssociatedComputeResourceTypes` is `400 ValidationException`. An unknown region, a partition that is not the region's, or a version such as `0` or `01` is `400 ValidationException` "The egress network connector ARN: '<arn>' is not valid. ...", and a connector in another account is `403 AccessDeniedException`. A version past the 64-bit range is `500 InternalServerException` with the body `{}`, as on AWS. Only a `HomeRegion` endpoint can serve such a revision: `CreateWebFunction` with another endpoint type, and weights of a `PerRegion` or `MultiRegion` endpoint that name such a revision, are `400 ValidationException`. Floci settles a connector at once, so the AWS refusal of a `PENDING` version never happens. Floci does not check `lambda:PassNetworkConnector`, and the connector does not change the network of the function's container.- **Resource policies** are checked the way AWS checks them before storing: the document grammar, a `lambda:` action, a `Resource` that names the function, a valid principal, and no public `Allow`. A wildcard principal needs a positive condition (`StringEquals`, `StringLike`, `ArnLike`, `Bool`) on a trusted key such as `aws:PrincipalAccount` or `aws:PrincipalArn`, with no wildcard in the account it names. An `IamAuth` endpoint evaluates it on requests, as below.- **Function names** are unique across the regions of an account, as on AWS. A name that another region already has is `409 ConflictException` "A function named <name> already exists in the account. Function names must be unique across all regions in an account.".- **ARNs** given as identifiers must name the request's region and the caller's account, as on AWS. A revision or endpoint ARN resolves by its id or name only.diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.javaindex 39acfc301e..034d28ee15 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java@@ -566,6 +566,19 @@ public class LambdaMicrovmsService {return List.copyOf(find(region, ref).versions);}+ /**+ * The version a Web Function revision names by its version-qualified ARN. Only the connector id names it,+ * not its name, and only in {@code region}.+ */+ public synchronized Optional<NetworkConnectorVersion> connectorVersion(String region, String connectorArn,+ long version) {+ Optional<NetworkConnector> connector = in(connectors, region)+ .filter(c -> connectorArn.equals(c.arn))+ .findFirst();+ connector.ifPresent(LambdaMicrovmsService::backfillVersions);+ return connector.flatMap(c -> c.versions.stream().filter(v -> v.version == version).findFirst());+ }+private record ConnectorRef(String unqualified, boolean arn, String idOrName, Long version) {static ConnectorRef parse(String identifier) {@@ -599,11 +612,15 @@ public class LambdaMicrovmsService {: LambdaArnUtils.networkConnectorVersionArn(arn, ref.version()));});}- // One stored before versions has only its latest version.+ backfillVersions(connector);+ return connector;+ }++ /** One stored before versions has only its latest version. */+ private static void backfillVersions(NetworkConnector connector) {if (connector.versions.isEmpty()) {connector.versions.add(snapshot(connector, connector.latestVersion));}- return connector;}private static AwsException connectorNotFound(String arn) {diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.javaindex ca65416dd4..c93edc353b 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.java@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.AwsRegions;import io.github.hectorvent.floci.core.common.Base64Url;import io.github.hectorvent.floci.core.common.IamConditionContextResolver;import io.github.hectorvent.floci.core.common.PaginatedResult;@@ -21,6 +22,7 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;import io.github.hectorvent.floci.services.iam.PublicAccessConditions;+import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint;import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionRevision;@@ -113,8 +115,10 @@ public class LambdaWebService implements Resettable {"arn:(" + AwsArnUtils.PARTITION_REGEX + "):iam::[0-9]{12}:role/[a-zA-Z0-9+=,.@_/-]+");static final Pattern KMS_KEY_ARN = Pattern.compile("arn:(" + AwsArnUtils.PARTITION_REGEX + "):kms:[a-z0-9-]+:[0-9]{12}:key/[a-z0-9-]+");+ /** The model's pattern, which AWS quotes. An unknown partition passes it and fails a later check. */static final Pattern NETWORK_CONNECTOR_ARN = Pattern.compile(- "arn:(" + AwsArnUtils.PARTITION_REGEX + "):lambda:[a-z0-9-]+:[0-9]{12}:network-connector:[a-zA-Z0-9_-]+:[0-9]+");+ "arn:(aws[a-z-]*):lambda:[a-z0-9-]+:[0-9]{12}:network-connector:[a-zA-Z0-9_-]+:[0-9]+");+ private static final Pattern CONNECTOR_VERSION = Pattern.compile("[1-9][0-9]*");static final Pattern S3_BUCKET = Pattern.compile("([a-z0-9][a-z0-9\\.\\-]{1,61}[a-z0-9])");static final Pattern RUNTIME = Pattern.compile("[a-z][a-z0-9]*(\\.[a-z0-9]+)*");static final Pattern ENVIRONMENT_KEY = Pattern.compile("[a-zA-Z]([a-zA-Z0-9_])*");@@ -146,6 +150,7 @@ public class LambdaWebService implements Resettable {private final Instance<RequestContext> requestContext;private final LambdaWebExecutionRole executionRole;private final ServiceCallAuthorizer serviceCalls;+ private final LambdaMicrovmsService microvmsService;/** Keyed {@code region/functionName}. The backend adds the caller's account to every key. */private StorageBackend<String, WebFunction> functions;@@ -159,7 +164,7 @@ public class LambdaWebService implements Resettable {public LambdaWebService(RegionResolver regionResolver, StorageFactory storageFactory, EmulatorConfig config,S3Service s3Service, LambdaWebCode code, ObjectMapper objectMapper,Instance<RequestContext> requestContext, LambdaWebExecutionRole executionRole,- ServiceCallAuthorizer serviceCalls) {+ ServiceCallAuthorizer serviceCalls, LambdaMicrovmsService microvmsService) {this.regionResolver = regionResolver;this.storageFactory = storageFactory;this.config = config;@@ -169,6 +174,7 @@ public class LambdaWebService implements Resettable {this.requestContext = requestContext;this.executionRole = executionRole;this.serviceCalls = serviceCalls;+ this.microvmsService = microvmsService;}@PostConstruct@@ -326,7 +332,13 @@ public class LambdaWebService implements Resettable {validateRevisionRules(region, revisionConfig);String accountId = regionResolver.getAccountId();WebFunctionEndpoint endpoint = draftEndpoint(region, accountId, functionName, endpointConfig, false);+ if (connectorArn(revisionConfig) != null && !"HomeRegion".equals(endpoint.endpointType)) {+ throw new AwsException("ValidationException", "The endpointType " + endpoint.endpointType+ + " cannot be used with a revision that has an egressNetworkConnectorArn specified."+ + " Only the endpointType HomeRegion supports such revisions.", 400);+ }return storeNewFunction(region, functionName, tags, fn -> {+ requireUsableConnector(region, revisionConfig);WebFunctionRevision revision = buildRevision(fn, revisionConfig);keepCode(region, fn, revision);attachEndpoint(region, fn, endpoint, revision);@@ -437,6 +449,7 @@ public class LambdaWebService implements Resettable {validateRevisionRules(region, request);synchronized (lockFor(region, functionName)) {WebFunction fn = function(region, functionName);+ requireUsableConnector(region, request);WebFunctionRevision revision = buildRevision(fn, request);keepCode(region, fn, revision);fn.revisions.put(revision.revisionId, revision);@@ -573,6 +586,13 @@ public class LambdaWebService implements Resettable {if (!AwsArnUtils.parse(role).accountId().equals(regionResolver.getAccountId())) {throw new LambdaWebAccessDeniedException("Cross-account pass role is not allowed.");}+ String connectorArn = connectorArn(request);+ if (connectorArn != null) {+ requireValidConnectorArn(connectorArn);+ if (!AwsArnUtils.parse(connectorArn).accountId().equals(regionResolver.getAccountId())) {+ throw new LambdaWebAccessDeniedException("Cross-account pass lambda-network-connector is not allowed.");+ }+ }Map<String, String> environment = LambdaWebJson.stringMap(service, "environmentVariables", false);if (environment != null) {List<String> reserved = environment.keySet().stream().filter(RESERVED_ENVIRONMENT_KEYS::contains).toList();@@ -589,6 +609,55 @@ public class LambdaWebService implements Resettable {executionRole.requireAssumable(region, role);}+ private static String connectorArn(JsonNode revisionRequest) {+ return LambdaWebJson.text(LambdaWebJson.structure(revisionRequest, "serviceConfig"), "egressNetworkConnectorArn");+ }++ /** AWS checks the region, then the partition, then the version. */+ private static void requireValidConnectorArn(String connectorArn) {+ AwsArnUtils.Arn arn = AwsArnUtils.parse(connectorArn);+ String version = connectorArn.substring(connectorArn.lastIndexOf(':') + 1);+ if (!AwsRegions.isRegionId(arn.region())) {+ throw invalidConnectorArn(connectorArn, "Invalid region.: " + arn.region());+ }+ if (!AwsRegions.partitionFor(arn.region()).equals(arn.partition())) {+ throw invalidConnectorArn(connectorArn, "Invalid arn partition.: " + arn.partition());+ }+ if (!CONNECTOR_VERSION.matcher(version).matches()) {+ throw invalidConnectorArn(connectorArn, "Invalid network connector version format - must be numeric: "+ + version);+ }+ }++ private static AwsException invalidConnectorArn(String connectorArn, String reason) {+ return new AwsException("ValidationException",+ "The egress network connector ARN: '" + connectorArn + "' is not valid. " + reason, 400);+ }++ /** AWS looks the connector up once it knows the function, by its id in the function's region. */+ private void requireUsableConnector(String region, JsonNode revisionRequest) {+ String connectorArn = connectorArn(revisionRequest);+ if (connectorArn == null) {+ return;+ }+ int colon = connectorArn.lastIndexOf(':');+ long version;+ try {+ version = Long.parseLong(connectorArn.substring(colon + 1));+ } catch (NumberFormatException e) {+ // AWS fails internally on a version past the 64-bit range.+ throw new LambdaWebInternalServerException();+ }+ LambdaMicrovmsService.NetworkConnectorVersion named = microvmsService+ .connectorVersion(region, connectorArn.substring(0, colon), version)+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "The egress network connector " + connectorArn + " does not exist.", 404));+ if (!named.associatedComputeResourceTypes.contains("WebFunction")) {+ throw new AwsException("ValidationException", "The egress network connector " + connectorArn+ + " cannot be used because its associatedComputeResourceTypes do not include WebFunction.", 400);+ }+ }+private WebFunctionRevision buildRevision(WebFunction fn, JsonNode request) {WebFunctionRevision revision = new WebFunctionRevision();revision.buildConfig = buildConfigOf(LambdaWebJson.structure(request, "buildConfig"));@@ -871,7 +940,7 @@ public class LambdaWebService implements Resettable {}}if (weights != null) {- newWeights = resolveWeights(fn, requestedWeights(weights));+ newWeights = resolveWeights(fn, endpoint.endpointType, requestedWeights(weights));}WebFunctionEndpoint.ScalingConfig newScaling = scaling != null ? scalingConfigOf(scaling) : null;WebFunctionEndpoint.ThrottleConfig newThrottle = throttle != null ? throttleConfigOf(throttle) : null;@@ -984,7 +1053,7 @@ public class LambdaWebService implements Resettable {if (initialRevision != null) {endpoint.revisionWeights = List.of(weight(initialRevision.revisionId, 100));} else if (!endpoint.revisionWeights.isEmpty()) {- endpoint.revisionWeights = resolveWeights(fn, endpoint.revisionWeights);+ endpoint.revisionWeights = resolveWeights(fn, endpoint.endpointType, endpoint.revisionWeights);} else {endpoint.revisionWeights = latestRevision(fn).map(id -> List.of(weight(id, 100))).orElse(List.of());}@@ -1060,7 +1129,7 @@ public class LambdaWebService implements Resettable {return out;}- private static List<WebFunctionEndpoint.RevisionWeight> resolveWeights(WebFunction fn,+ private static List<WebFunctionEndpoint.RevisionWeight> resolveWeights(WebFunction fn, String endpointType,List<WebFunctionEndpoint.RevisionWeight> weights) {for (WebFunctionEndpoint.RevisionWeight weight : weights) {WebFunctionRevision revision = fn.revisions.get(weight.revisionId);@@ -1073,6 +1142,17 @@ public class LambdaWebService implements Resettable {+ " is in Failed state and cannot be deployed. Only revisions in Active state can be deployed.", 409);}}+ // AWS finds every revision before it refuses one for its connector.+ if (!"HomeRegion".equals(endpointType)) {+ for (WebFunctionEndpoint.RevisionWeight weight : weights) {+ if (fn.revisions.get(weight.revisionId).serviceConfig.egressNetworkConnectorArn != null) {+ throw new AwsException("ValidationException", "The revision " + weight.revisionId+ + " has an egressNetworkConnectorArn configured and cannot be used by a " + endpointType+ + " endpoint. Only HomeRegion endpoints support revisions with an egressNetworkConnectorArn"+ + " configured.", 400);+ }+ }+ }return List.copyOf(weights);}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.javaindex c7c3a5f942..c2790b419b 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.java@@ -787,4 +787,77 @@ class LambdaWebIntegrationTest {given().when().delete(BASE + "/web-functions/" + fn).then().statusCode(204);}++ @Test+ @Order(14)+ void anEgressConnectorIsAWebFunctionVersionOnAHomeRegionEndpoint() {+ String fn = FN + "-connector";+ String connectorArn = given().contentType("application/json")+ .body("""+ {"Name": "web-it-connector", "OperatorRole": "arn:aws:iam::000000000000:role/web-it-operator",+ "ClientToken": "web-it-connector",+ "Configuration": {"VpcEgressConfiguration": {"SubnetIds": ["subnet-0web0000000000001"],+ "SecurityGroupIds": ["sg-0web0000000000001"], "NetworkProtocol": "IPv4",+ "AssociatedComputeResourceTypes": ["WebFunction"]}}}+ """)+ .when().post("/2026-04-04/network-connectors")+ .then().statusCode(202)+ .extract().path("Arn");+ String revision = given().contentType("application/json")+ .body("""+ {"functionName": "%s",+ "revisionConfig": {"buildConfig": %s,+ "serviceConfig": {"executionRoleArn": "%s", "egressNetworkConnectorArn": "%s:1"}},+ "endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion",+ "authType": "ApplicationManaged"}}+ """.formatted(fn, BUILD, ROLE, connectorArn))+ .when().put(BASE + "/web-functions")+ .then().statusCode(202)+ .extract().path("revision.revisionId");+ given().when().get(BASE + "/web-functions/" + fn + "/revisions/" + revision)+ .then().statusCode(200)+ .body("serviceConfig.egressNetworkConnectorArn", equalTo(connectorArn + ":1"));++ String revisions = BASE + "/web-functions/" + fn + "/revisions";+ given().contentType("application/json")+ .body("""+ {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s", "egressNetworkConnectorArn": "%s:2"}}+ """.formatted(BUILD, ROLE, connectorArn))+ .when().post(revisions)+ .then().statusCode(404)+ .header("X-Amzn-Errortype", "ResourceNotFoundException")+ .body("message", equalTo("The egress network connector " + connectorArn + ":2 does not exist."));+ given().contentType("application/json")+ .body("""+ {"buildConfig": %s,+ "serviceConfig": {"executionRoleArn": "%s", "egressNetworkConnectorArn": "%s:9223372036854775808"}}+ """.formatted(BUILD, ROLE, connectorArn))+ .when().post(revisions)+ .then().statusCode(500)+ .header("X-Amzn-Errortype", "InternalServerException")+ .body(equalTo("{}"));+ given().contentType("application/json")+ .body("""+ {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s", "egressNetworkConnectorArn": "%s:1"}}+ """.formatted(BUILD, ROLE, connectorArn.replace("000000000000", "111122223333")))+ .when().post(revisions)+ .then().statusCode(403)+ .header("X-Amzn-Errortype", "AccessDeniedException")+ .body("Message", equalTo("Cross-account pass lambda-network-connector is not allowed."));++ given().contentType("application/json")+ .body("""+ {"endpointName": "pr", "endpointType": "PerRegion", "authType": "ApplicationManaged",+ "regions": ["us-west-2"], "revisionWeights": [{"revisionId": "%s", "weight": 100}]}+ """.formatted(revision))+ .when().put(BASE + "/web-functions/" + fn + "/endpoints")+ .then().statusCode(400)+ .header("X-Amzn-Errortype", "ValidationException")+ .body("message", equalTo("The revision " + revision + " has an egressNetworkConnectorArn configured"+ + " and cannot be used by a PerRegion endpoint. Only HomeRegion endpoints support revisions"+ + " with an egressNetworkConnectorArn configured."));++ given().when().delete(BASE + "/web-functions/" + fn).then().statusCode(204);+ given().when().delete("/2026-04-04/network-connectors/" + connectorArn).then().statusCode(202);+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.javaindex a56852baa8..1c33be5062 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.java@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.core.storage.PersistentStorage;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;+import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint;import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionRevision;@@ -31,6 +32,7 @@ import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.HashMap;+import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;@@ -60,6 +62,7 @@ class LambdaWebServiceTest {private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();private final ServiceCallAuthorizer serviceCalls = mock(ServiceCallAuthorizer.class);+ private final LambdaMicrovmsService microvms = new LambdaMicrovmsService(new RegionResolver(REGION, ACCOUNT_ID), null);@TempDirPath storageDir;@@ -85,7 +88,8 @@ class LambdaWebServiceTest {EmulatorConfig config = mock(EmulatorConfig.class);when(config.effectiveBaseUrl()).thenReturn(baseUrl);LambdaWebService service = new LambdaWebService(new RegionResolver(REGION, ACCOUNT_ID), storage, config,- s3Service, new LambdaWebCode(storageDir.resolve("code")), mapper, null, executionRole, serviceCalls);+ s3Service, new LambdaWebCode(storageDir.resolve("code")), mapper, null, executionRole, serviceCalls,+ microvms);service.initializeStorage();return service;}@@ -105,6 +109,18 @@ class LambdaWebServiceTest {return config;}+ private ObjectNode revisionConfig(String executionRoleArn, String connectorArn) {+ ObjectNode config = revisionConfig(executionRoleArn);+ ((ObjectNode) config.get("serviceConfig")).put("egressNetworkConnectorArn", connectorArn);+ return config;+ }++ private LambdaMicrovmsService.NetworkConnector connector(String name, String computeResourceType) {+ return microvms.createConnector(REGION, ACCOUNT_ID, name, List.of("subnet-00000000000000001"),+ List.of("sg-00000000000000001"), "arn:aws:iam::000000000000:role/operator", "token",+ List.of(computeResourceType), "IPv4");+ }+private ObjectNode endpointConfig(String name) {return mapper.createObjectNode().put("endpointName", name).put("endpointType", "HomeRegion").put("authType", "ApplicationManaged").put("autoDeploymentMode", "LatestRevision");@@ -331,6 +347,141 @@ class LambdaWebServiceTest {assertEquals("cannot be assumed", message(() -> service.createFunction(REGION, multiRegion)));}+ @Test+ void egressConnectorArnIsCheckedInTheOrderAwsChecksIt() {+ String missingRole = "arn:aws:iam::000000000000:role/missing";+ LambdaWebExecutionRole executionRole = mock(LambdaWebExecutionRole.class);+ doThrow(new AwsException("ValidationException", "cannot be assumed", 400))+ .when(executionRole).requireAssumable(REGION, missingRole);+ LambdaWebService service = service(new MemoryStorageFactory(), "http://localhost:4566", null, executionRole);+ String connector = ":000000000000:network-connector:nc-1:";++ String unversioned = "arn:aws:lambda:us-east-1:000000000000:network-connector:nc-1";+ assertEquals("1 validation error detected: Value '" + unversioned + "' at 'serviceConfig.egressNetworkConnectorArn'"+ + " failed to satisfy constraint: Member must satisfy regular expression pattern:"+ + " arn:(aws[a-z-]*):lambda:[a-z0-9-]+:[0-9]{12}:network-connector:[a-zA-Z0-9_-]+:[0-9]+",+ message(() -> service.createRevision(REGION, "missing", revisionConfig(missingRole, unversioned))));+ Map<String, String> invalid = new LinkedHashMap<>();+ invalid.put("arn:aws:lambda:moon-1" + connector + "0", "Invalid region.: moon-1");+ invalid.put("arn:aws:lambda:us-east-1a" + connector + "1", "Invalid region.: us-east-1a");+ invalid.put("arn:aws-cn:lambda:us-east-1" + connector + "0", "Invalid arn partition.: aws-cn");+ invalid.put("arn:aws:lambda:cn-north-1" + connector + "1", "Invalid arn partition.: aws");+ invalid.put("arn:awsx:lambda:us-east-1" + connector + "1", "Invalid arn partition.: awsx");+ invalid.put("arn:aws:lambda:us-east-1" + connector + "0",+ "Invalid network connector version format - must be numeric: 0");+ invalid.put("arn:aws:lambda:us-east-1" + connector + "01",+ "Invalid network connector version format - must be numeric: 01");+ invalid.put("arn:aws:lambda:moon-1:111111111111:network-connector:nc-1:1", "Invalid region.: moon-1");+ invalid.put("arn:aws:lambda:us-east-1:111111111111:network-connector:nc-1:0",+ "Invalid network connector version format - must be numeric: 0");+ invalid.forEach((arn, reason) -> {+ AwsException e = error(() -> service.createRevision(REGION, "missing", revisionConfig(missingRole, arn)));+ assertEquals(400, e.getHttpStatus());+ assertEquals("The egress network connector ARN: '" + arn + "' is not valid. " + reason, e.getMessage());+ });++ String otherAccount = "arn:aws:lambda:us-east-1:111111111111:network-connector:nc-1:1";+ assertEquals("Cross-account pass role is not allowed.", message(() -> service.createRevision(REGION, "missing",+ revisionConfig("arn:aws:iam::111122223333:role/web", "arn:aws:lambda:us-east-1" + connector + "0"))));+ ObjectNode reserved = revisionConfig(missingRole, otherAccount);+ ((ObjectNode) reserved.get("serviceConfig")).putObject("environmentVariables").put("AWS_REGION", "x");+ AwsException denied = error(() -> service.createRevision(REGION, "missing", reserved));+ assertEquals("AccessDeniedException", denied.getErrorCode());+ assertEquals(403, denied.getHttpStatus());+ assertEquals("Cross-account pass lambda-network-connector is not allowed.", denied.getMessage());++ String pastLong = "arn:aws:lambda:us-east-1" + connector + "9223372036854775808";+ assertEquals("cannot be assumed",+ message(() -> service.createRevision(REGION, "missing", revisionConfig(missingRole, pastLong))));+ assertEquals("ResourceNotFoundException",+ error(() -> service.createRevision(REGION, "missing", revisionConfig(ROLE, pastLong))).getErrorCode());+ }++ @Test+ void aRevisionNamesAWebFunctionConnectorVersionByItsId() {+ LambdaWebService service = service();+ service.createFunction(REGION, createRequest("app"));+ LambdaMicrovmsService.NetworkConnector web = connector("web", "WebFunction");+ LambdaMicrovmsService.NetworkConnector vm = connector("vm", "MicroVm");++ WebFunctionRevision first = service.createRevision(REGION, "app", revisionConfig(ROLE, web.arn + ":1"));+ assertEquals(web.arn + ":1", first.serviceConfig.egressNetworkConnectorArn);+ assertEquals("The egress network connector " + web.arn + ":2 does not exist.",+ message(() -> service.createRevision(REGION, "app", revisionConfig(ROLE, web.arn + ":2"))));+ microvms.updateConnector(REGION, web.id, List.of("subnet-00000000000000002"), null, null, null, null);+ service.createRevision(REGION, "app", revisionConfig(ROLE, web.arn + ":2"));+ microvms.deleteConnector(REGION, web.arn + ":1");+ for (String gone : List.of(web.arn + ":1", web.arn.replace(web.id, "web") + ":2",+ web.arn.replace(REGION, "us-west-2") + ":2", web.arn + ":9223372036854775807")) {+ AwsException e = error(() -> service.createRevision(REGION, "app", revisionConfig(ROLE, gone)));+ assertEquals(404, e.getHttpStatus());+ assertEquals("The egress network connector " + gone + " does not exist.", e.getMessage());+ }+ assertEquals("The egress network connector " + vm.arn + ":1 cannot be used because its"+ + " associatedComputeResourceTypes do not include WebFunction.",+ message(() -> service.createRevision(REGION, "app", revisionConfig(ROLE, vm.arn + ":1"))));+ AwsException internal = error(() -> service.createRevision(REGION, "app",+ revisionConfig(ROLE, web.arn + ":9223372036854775808")));+ assertEquals(500, internal.getHttpStatus());+ assertEquals("InternalServerException", internal.getErrorCode());+ }++ @Test+ void onlyHomeRegionEndpointsServeARevisionWithAConnector() {+ LambdaWebService service = service();+ String connectorArn = connector("web", "WebFunction").arn + ":1";+ ObjectNode perRegion = createRequest("app");+ perRegion.set("revisionConfig", revisionConfig(ROLE, connectorArn));+ perRegion.set("endpointConfig", mapper.createObjectNode().put("endpointName", "dev")+ .put("endpointType", "PerRegion").put("authType", "ApplicationManaged"));+ ((ObjectNode) perRegion.get("endpointConfig")).putArray("regions").add("us-west-2");+ String refused = "The endpointType PerRegion cannot be used with a revision that has an"+ + " egressNetworkConnectorArn specified. Only the endpointType HomeRegion supports such revisions.";+ assertEquals(refused, message(() -> service.createFunction(REGION, perRegion)));+ ((ObjectNode) perRegion.get("endpointConfig")).put("endpointType", "MultiRegion");+ assertEquals(refused.replace("PerRegion", "MultiRegion"), message(() -> service.createFunction(REGION, perRegion)));++ service.createFunction(REGION, createRequest("app"));+ ((ObjectNode) perRegion.get("endpointConfig")).put("endpointType", "PerRegion");+ assertEquals(refused, message(() -> service.createFunction(REGION, perRegion)));+ ObjectNode missingConnector = createRequest("app");+ missingConnector.set("revisionConfig", revisionConfig(ROLE, connectorArn.substring(0, connectorArn.length() - 1) + "2"));+ assertEquals("ConflictException", error(() -> service.createFunction(REGION, missingConnector)).getErrorCode());++ String plain = service.getEndpoint(REGION, "app", "dev").revisionWeights.get(0).revisionId;+ String connected = service.createRevision(REGION, "app", revisionConfig(ROLE, connectorArn)).revisionId;+ String notServed = "The revision " + connected + " has an egressNetworkConnectorArn configured and cannot be used"+ + " by a PerRegion endpoint. Only HomeRegion endpoints support revisions with an"+ + " egressNetworkConnectorArn configured.";+ assertEquals(notServed, message(() -> service.createEndpoint(REGION, "app",+ weighted("pr", "PerRegion", plain, connected))));+ assertEquals("The revision rev-zzzzz does not exist.", message(() -> service.createEndpoint(REGION, "app",+ weighted("pr", "PerRegion", connected, "rev-zzzzz"))));+ service.createEndpoint(REGION, "app", weighted("pr", "PerRegion", plain));+ service.createEndpoint(REGION, "app", weighted("mr", "MultiRegion", plain));+ service.createEndpoint(REGION, "app", weighted("home", "HomeRegion", connected));++ ObjectNode update = mapper.createObjectNode();+ update.putArray("revisionWeights").addObject().put("revisionId", connected).put("weight", 100);+ assertEquals(notServed, message(() -> service.updateEndpoint(REGION, "app", "pr", update)));+ assertEquals(notServed.replace("PerRegion", "MultiRegion"),+ message(() -> service.updateEndpoint(REGION, "app", "mr", update)));+ assertEquals(plain, service.getEndpoint(REGION, "app", "pr").revisionWeights.get(0).revisionId);+ }++ private ObjectNode weighted(String name, String endpointType, String... revisionIds) {+ ObjectNode request = mapper.createObjectNode().put("endpointName", name).put("endpointType", endpointType)+ .put("authType", "ApplicationManaged");+ if (!"HomeRegion".equals(endpointType)) {+ request.putArray("regions").add("us-west-2");+ }+ ArrayNode weights = request.putArray("revisionWeights");+ for (String revisionId : revisionIds) {+ weights.addObject().put("revisionId", revisionId).put("weight", 100 / revisionIds.length);+ }+ return request;+ }+@Testvoid aRejectedEndpointUpdateChangesNothing() {LambdaWebService service = service();