fix(apigateway): preserve API ownership across integration invocations (#6001)

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-19 19:58:19 -04:00
1 parent 456ae15684
commit 4b3681eb90
28 files changed
+1063 -172

No files matched your search

+18
View File
@@ -220,9 +220,27 @@ local suffix such as `localhost.floci.io`; see [TLS](../configuration/tls.md).
Templates can create domains and mappings with `AWS::ApiGateway::DomainName` and
`AWS::ApiGateway::BasePathMapping`; see [CloudFormation](cloudformation.md).
Custom-domain invocation resolves the domain's owner independently of the caller, then
uses only that owner's mappings in the domain's region. If the same hostname is stored
under multiple accounts or regions, invocation returns `409 ConflictException` instead
of choosing one. Domain and mapping management remain scoped to the requesting account.
Once a mapping resolves, invocation keeps its API type, account and region even if an
API with the same ID exists elsewhere. Without a mapping, a signed request can select the
caller's own API in its signing region; requests without a matching scope reject ambiguous IDs.
This routing lookup does not add IAM identity or resource-policy evaluation.
### IAM Authorization (`AWS_IAM`) {#iam-authorization}
A method (v1) or route (v2) whose `authorizationType` is `AWS_IAM` requires a SigV4-signed caller.
REST invocation URLs identify the API owner independently of the caller's account.
An unsigned request can therefore reach a public method, or receive the method's
authentication error, when the API belongs to a nondefault account. Signed callers
from another account use the same resource lookup and still undergo signature
verification. Management requests remain scoped to the requesting account.
When an API ID is ambiguous, signed callers retain access to their own account's API in
the signing region; requests without a matching caller scope are rejected.
This lookup does not add IAM identity or resource-policy evaluation.
Before the integration runs, the signature is verified against the request as it arrived (method,
path, query string, the headers named in `SignedHeaders`, and the SHA-256 of the body). A request
that reaches the API through a [custom domain](#custom-domain-names) or an `execute-api` virtual
@@ -1,8 +1,8 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.RequestHost;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
@@ -62,7 +62,7 @@ public class ApiGatewayCustomDomainFilter implements ContainerRequestFilter {
String hostname = stripPort(host);
// Try matching by regionalDomainName first, then by bare domain name
CustomDomain domain = null;
ApiGatewayService.CustomDomainRoute domain = null;
if (hostname.endsWith(REGIONAL_SUFFIX)) {
domain = apiGatewayService.findDomainByRegionalHostname(hostname);
}
@@ -80,9 +80,9 @@ public class ApiGatewayCustomDomainFilter implements ContainerRequestFilter {
}
// Resolve the base path mapping for this domain + path
BasePathMapping mapping = apiGatewayService.resolveBasePathMapping(domain.getDomainName(), path);
BasePathMapping mapping = apiGatewayService.resolveBasePathMapping(domain, path);
if (mapping == null) {
LOG.debugv("No base path mapping found for domain {0} path {1}", domain.getDomainName(), path);
LOG.debugv("No base path mapping found for domain {0} path {1}", domain.domainName(), path);
return;
}
@@ -112,16 +112,13 @@ public class ApiGatewayCustomDomainFilter implements ContainerRequestFilter {
.build();
LOG.debugv("Custom domain routing: {0}{1} -> {2}", host, path, newUri.getPath());
// AWS_IAM dispatch rebuilds the caller's canonical request, which covers the path they
// signed: the custom-domain path, not the /execute-api/... form this rewrite produces.
// Older persisted mappings have no type. Prefer REST if that API exists; otherwise
// retain v2 routing when a v2 API owns the id.
if ("REST".equals(mapping.getApiType())
|| (mapping.getApiType() == null
&& (apiGatewayService.hasRestApi(restApiId)
|| apiGatewayV2Service.findApiOwner(restApiId).isEmpty()))) {
routeContext.routeToRestApi();
}
String mappedRegion = domain.region();
boolean restApi = "REST".equals(mapping.getApiType())
|| (mapping.getApiType() == null && RequestScopes.callAs(
domain.accountId(), domain.region(),
() -> apiGatewayService.hasRestApi(mappedRegion, restApiId)
|| !apiGatewayV2Service.hasApi(mappedRegion, restApiId)));
routeContext.routeToMappedApi(domain, restApi);
routeContext.recordSignedRequestPath(path);
requestContext.setProperty(ROUTED_PROPERTY, Boolean.TRUE);
requestContext.setRequestUri(newUri);
@@ -21,6 +21,8 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsEndpoints;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsPartition;
import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.CookieHeaders;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
@@ -344,9 +346,17 @@ public class ApiGatewayExecuteController {
Response dispatch(String httpMethod, String apiId, String stageName,
String proxy, HttpHeaders headers, UriInfo uriInfo, byte[] body) {
String region = regionResolver.resolveRegion(headers);
ApiGatewayService.CustomDomainRoute mappedDomain = routeContext.mappedDomain();
if (mappedDomain != null) {
region = mappedDomain.region();
requestContext.setAccountId(mappedDomain.accountId());
requestContext.setRegion(region);
requestContext.setPartition(AwsPartitions.forRegion(region).map(AwsPartition::id).orElse(null));
}
String httpApiRegion = routeContext.httpApiRegion();
if (httpApiRegion != null) {
Optional<ApiGatewayV2Service.ApiOwner> owner = apiGatewayV2Service.findApiOwner(apiId);
Optional<ApiGatewayV2Service.ApiOwner> owner = mappedDomain == null
? apiGatewayV2Service.findApiOwner(apiId) : Optional.empty();
if (owner.isPresent()) {
applyApiOwnerContext(owner.get());
httpApiRegion = owner.get().region();
@@ -360,13 +370,29 @@ public class ApiGatewayExecuteController {
// fell back to defaultRegion in both cases, so the resolved region is a guess.
boolean regionUnresolved = regionResolver.resolveRegionFromAuthOrNull(
headers == null ? null : headers.getHeaderString("Authorization")) == null;
if (regionUnresolved) {
Optional<ApiGatewayService.ApiOwner> restOwner = mappedDomain == null
? apiGatewayService.findRestApiOwner(apiId,
regionUnresolved ? null : requestContext.getAccountId(), region) : Optional.empty();
if (restOwner.isPresent()) {
requestContext.setAccountId(restOwner.get().accountId());
if (regionUnresolved) {
region = restOwner.get().region();
requestContext.setRegion(region);
requestContext.setPartition(AwsPartitions.forRegion(region).map(AwsPartition::id).orElse(null));
}
}
if (regionUnresolved && mappedDomain == null) {
region = apiGatewayService.resolveRestApiRegion(region, apiId);
}
try {
apiGatewayService.getRestApi(region, apiId);
} catch (AwsException restApiError) {
if (mappedDomain != null) {
return Response.status(restApiError.getHttpStatus())
.entity(jsonMessage(restApiError.getMessage()))
.type(MediaType.APPLICATION_JSON).build();
}
Optional<ApiGatewayV2Service.ApiOwner> owner = apiGatewayV2Service.findApiOwner(apiId);
if (owner.isPresent()) {
applyApiOwnerContext(owner.get());
@@ -546,7 +572,7 @@ public class ApiGatewayExecuteController {
authorizerResult.principalId(), authorizerResult.context(), resolvedApiKey, iamIdentity);
try {
InvokeResult result = lambdaService.invoke(region, functionName, eventJson.getBytes(),
InvokeResult result = lambdaService.invokeTarget(region, functionName, eventJson.getBytes(),
InvocationType.RequestResponse);
Response response = buildProxyResponse(result, false);
if (response.getStatus() == 502 && isGatewayGeneratedProxyFailure(result)) {
@@ -1039,7 +1065,7 @@ public class ApiGatewayExecuteController {
RestLambdaAuthorizer.Result verified = restLambdaAuthorizer.get(key);
if (verified == null) {
try (RestLambdaAuthorizer.Invocation pending = restLambdaAuthorizer.beginInvocation(key)) {
InvokeResult invocation = lambdaService.invoke(region, function,
InvokeResult invocation = lambdaService.invokeTarget(region, function,
event.getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse);
if (invocation.getFunctionError() != null) {
return lambdaAuthorizerFailure(scope, invocation);
@@ -1362,10 +1388,10 @@ public class ApiGatewayExecuteController {
/**
* Extracts function name from integration URI like
* {@code arn:aws:apigateway:...:lambda:path/2015-03-31/functions/{fnArn}/invocations}.
* Delegates to {@link LambdaArnUtils#extractFunctionNameFromUri(String)}.
* Delegates to {@link LambdaArnUtils#extractFunctionReferenceFromUri(String)}.
*/
private String functionNameFromUri(String uri) {
return LambdaArnUtils.extractFunctionNameFromUri(uri);
return LambdaArnUtils.extractFunctionReferenceFromUri(uri);
}
// Package-private rather than private so a focused unit test can assert the event's wire shape
@@ -1853,7 +1879,7 @@ public class ApiGatewayExecuteController {
"Cannot resolve Lambda function name from URI: " + integration.getUri(), 400);
}
byte[] payload = transformedBody != null ? transformedBody.getBytes(StandardCharsets.UTF_8) : new byte[0];
InvokeResult invokeResult = lambdaService.invoke(region, functionName, payload, InvocationType.RequestResponse);
InvokeResult invokeResult = lambdaService.invokeTarget(region, functionName, payload, InvocationType.RequestResponse);
String lambdaResponseBody = invokeResult.getPayload() != null
? new String(invokeResult.getPayload(), StandardCharsets.UTF_8) : "{}";
int lambdaStatus = invokeResult.getStatusCode() > 0 ? invokeResult.getStatusCode() : 200;
@@ -2822,7 +2848,7 @@ public class ApiGatewayExecuteController {
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → Lambda {4}", httpMethod, apiId, stageName, path, functionName);
try {
InvokeResult result = lambdaService.invoke(region, functionName,
InvokeResult result = lambdaService.invokeTarget(region, functionName,
eventJson.getBytes(), InvocationType.RequestResponse);
return buildProxyResponse(result, true, !payloadV1);
} catch (AwsException e) {
@@ -3276,7 +3302,7 @@ public class ApiGatewayExecuteController {
// Invoke the authorizer Lambda
InvokeResult invokeResult;
try {
invokeResult = lambdaService.invoke(region, functionName,
invokeResult = lambdaService.invokeTarget(region, functionName,
eventJson.getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse);
} catch (Exception e) {
LOG.warnv("Lambda REQUEST authorizer invocation failed for API {0}: {1}", apiId, e.getMessage());
@@ -73,6 +73,20 @@ public class ApiGatewayExecuteRouteContext {
private String httpApiRegion;
private boolean restApiRoute;
private String signedRequestPath;
private ApiGatewayService.CustomDomainRoute mappedDomain;
void routeToMappedApi(ApiGatewayService.CustomDomainRoute domain, boolean restApi) {
mappedDomain = domain;
if (restApi) {
routeToRestApi();
} else {
routeToHttpApi(domain.region());
}
}
ApiGatewayService.CustomDomainRoute mappedDomain() {
return mappedDomain;
}
void routeToHttpApi(String region) {
this.httpApiRegion = region;
@@ -19,6 +19,7 @@ import io.github.hectorvent.floci.core.common.ReservedTags;
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.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.apigateway.model.Account;
@@ -106,7 +107,7 @@ public class ApiGatewayService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(ApiGatewayService.class);
private final StorageBackend<String, RestApi> apiStore;
private final AccountAwareStorageBackend<RestApi> apiStore;
private final StorageBackend<String, ApiGatewayResource> resourceStore;
private final StorageBackend<String, Deployment> deploymentStore;
private final StorageBackend<String, Map<String, String>> deploymentModelStore;
@@ -120,8 +121,8 @@ public class ApiGatewayService implements ResourceProvider {
private final StorageBackend<String, Model> modelStore;
private final StorageBackend<String, VpcLink> vpcLinkStore;
private final StorageBackend<String, Account> accountStore;
private final StorageBackend<String, CustomDomain> domainStore;
private final StorageBackend<String, BasePathMapping> basePathMappingStore;
private final AccountAwareStorageBackend<CustomDomain> domainStore;
private final AccountAwareStorageBackend<BasePathMapping> basePathMappingStore;
/**
* Guards every change to a custom domain or a base path mapping. The stores hand out live
* objects, so a patch or a tag write is a read-modify-write; two of them on one domain at the
@@ -394,6 +395,38 @@ public class ApiGatewayService implements ResourceProvider {
return apiStore.keys().stream().anyMatch(key -> key.endsWith("::" + apiId));
}
public boolean hasRestApi(String region, String apiId) {
return apiStore.get(apiKey(region, apiId)).isPresent();
}
public record ApiOwner(String accountId, String region) {}
/** Resolve resource ownership for data-plane URLs without changing management isolation. */
public Optional<ApiOwner> findRestApiOwner(String apiId) {
return findRestApiOwner(apiId, null, null);
}
public Optional<ApiOwner> findRestApiOwner(String apiId, String callerAccount, String callerRegion) {
List<AccountAwareStorageBackend.AccountEntry<RestApi>> matches =
apiStore.scanAllAccountEntries(key -> key.endsWith("::" + apiId));
if (matches.size() > 1 && callerAccount != null
&& matches.stream().anyMatch(entry -> callerAccount.equals(entry.accountId())
&& (callerRegion + "::" + apiId).equals(entry.key()))) {
return Optional.of(new ApiOwner(callerAccount, callerRegion));
}
if (matches.size() > 1) {
throw new AwsException("ConflictException",
"REST API id '" + apiId + "' is ambiguous across accounts", 409);
}
return matches.stream().findFirst().map(entry -> {
int delimiter = entry.key().indexOf("::");
if (delimiter <= 0) {
throw new IllegalStateException("Invalid REST API storage key: " + entry.key());
}
return new ApiOwner(entry.accountId(), entry.key().substring(0, delimiter));
});
}
public String resolveRestApiRegion(String preferredRegion, String apiId) {
if (apiStore.get(apiKey(preferredRegion, apiId)).isPresent()) {
@@ -2960,13 +2993,15 @@ public class ApiGatewayService implements ResourceProvider {
// ──────────────────────────── Custom Domain Resolution ────────────────────────────
public record CustomDomainRoute(String accountId, String region, String domainName) {}
/**
* Resolves a custom domain by its regionalDomainName (e.g., "my-domain.regional.local").
* Derives the domain name from the regionalDomainName and performs a key-based lookup.
*
* @return the CustomDomain if found, or null if no domain matches
* @return the domain's routing scope if found, or null if no domain matches
*/
public CustomDomain findDomainByRegionalHostname(String regionalDomainName) {
public CustomDomainRoute findDomainByRegionalHostname(String regionalDomainName) {
if (!regionalDomainName.endsWith(".regional.local")) {
return null;
}
@@ -2976,27 +3011,41 @@ public class ApiGatewayService implements ResourceProvider {
}
/**
* Resolves a custom domain by its actual domain name (e.g., "api.example.com").
* Domain names are globally unique across regions.
* Resolves data-plane ownership before the caller's account context is initialized.
* Management reads keep their account-scoped lookup.
*
* @return the CustomDomain if found, or null if no domain matches
* @return the domain's routing scope if found, or null if no domain matches
*/
public CustomDomain findDomainByName(String domainName) {
List<CustomDomain> results = domainStore.scan(k -> k.endsWith("::" + domainName));
return results.isEmpty() ? null : results.get(0);
public CustomDomainRoute findDomainByName(String domainName) {
List<AccountAwareStorageBackend.AccountEntry<CustomDomain>> matches =
domainStore.scanAllAccountEntries(key -> key.endsWith("::" + domainName));
if (matches.size() > 1) {
throw new AwsException("ConflictException",
"Custom domain '" + domainName + "' is ambiguous across accounts or regions", 409);
}
if (matches.isEmpty()) {
return null;
}
AccountAwareStorageBackend.AccountEntry<CustomDomain> entry = matches.getFirst();
int delimiter = entry.key().indexOf("::");
if (delimiter <= 0) {
throw new IllegalStateException("Invalid custom domain storage key: " + entry.key());
}
return new CustomDomainRoute(entry.accountId(), entry.key().substring(0, delimiter), domainName);
}
/**
* Resolves the base path mapping for a given domain and request path.
* Uses longest-prefix matching on the base path.
*
* @param domainName the custom domain name
* @param domain the exact custom domain owner and region
* @param requestPath the incoming request path (e.g., "/v1/items/123")
* @return the matching BasePathMapping, or null if none matches
*/
public BasePathMapping resolveBasePathMapping(String domainName, String requestPath) {
// Get all mappings across all regions for this domain
List<BasePathMapping> allMappings = basePathMappingStore.scan(k -> k.contains("::" + domainName + "::"));
public BasePathMapping resolveBasePathMapping(CustomDomainRoute domain, String requestPath) {
String mappingPrefix = domainKey(domain.region(), domain.domainName()) + "::";
List<BasePathMapping> allMappings =
basePathMappingStore.scanForAccount(domain.accountId(), key -> key.startsWith(mappingPrefix));
if (allMappings.isEmpty()) {
return null;
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.auth.CredentialScope;
import io.github.hectorvent.floci.core.common.auth.SessionTokenCheck;
import io.github.hectorvent.floci.core.common.auth.SigV4Canonicalization;
@@ -232,16 +233,16 @@ public class ExecuteApiSigV4Authorizer {
if (LEGACY_ACCESS_KEY_ID.equals(accessKeyId)) {
return LEGACY_SECRET_KEY;
}
String secretKey = iamService.findSecretKey(accessKeyId).orElse(null);
if (secretKey == null) {
return null;
}
if (iamService.resolveAccountId(accessKeyId).isEmpty()) {
String callerAccount = iamService.resolveAccountId(accessKeyId).orElse(null);
if (callerAccount == null) {
LOG.debugv("execute-api request uses an expired or inactive credential: accessKey={0}",
SigV4RequestValidator.sanitizeForLog(accessKeyId));
return null;
}
return secretKey;
// Dispatch reads integrations in the API owner's account. Credentials remain owned by
// the caller, who may belong to another account; only this lookup adopts that account.
return RequestScopes.callAs(callerAccount,
() -> iamService.findSecretKey(accessKeyId).orElse(null));
}
/**
@@ -268,14 +269,16 @@ public class ExecuteApiSigV4Authorizer {
private CallerIdentity resolveIdentity(String accessKeyId) {
String accountId = iamService.resolveAccountId(accessKeyId)
.orElseGet(regionResolver::getAccountId);
String userArn = iamService.resolveCallerArn(accessKeyId)
.orElseGet(() -> regionResolver.buildGlobalArn("iam", accountId, "root"));
String userId = iamService.findAccessKey(accessKeyId)
.map(AccessKey::getUserName)
.flatMap(iamService::findUser)
.map(IamUser::getUserId)
.orElse(accessKeyId);
return new CallerIdentity(accessKeyId, accountId, userArn, userId);
return RequestScopes.callAs(accountId, () -> {
String userArn = iamService.resolveCallerArn(accessKeyId)
.orElseGet(() -> regionResolver.buildGlobalArn("iam", accountId, "root"));
String userId = iamService.findAccessKey(accessKeyId)
.map(AccessKey::getUserName)
.flatMap(iamService::findUser)
.map(IamUser::getUserId)
.orElse(accessKeyId);
return new CallerIdentity(accessKeyId, accountId, userArn, userId);
});
}
/** The signing time of a header signature: {@code X-Amz-Date}, or {@code Date} when it is absent. */
@@ -160,6 +160,10 @@ public class ApiGatewayV2Service {
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid API id specified", 404));
}
public boolean hasApi(String region, String apiId) {
return apiStore.get(apiKey(region, apiId)).isPresent();
}
/** Persists an Api the caller already holds — used to attach OpenAPI import diagnostics. */
public void putApi(String region, Api api) {
apiStore.put(apiKey(region, api.getApiId()), api);
@@ -134,7 +134,7 @@ public class WebSocketAuthorizerService {
// Invoke the authorizer Lambda
InvokeResult invokeResult;
try {
invokeResult = lambdaService.invoke(region, functionName,
invokeResult = lambdaService.invokeTarget(region, functionName,
authorizerEventJson.getBytes(), InvocationType.RequestResponse);
} catch (Exception e) {
LOG.warnv("Lambda authorizer invocation failed for API {0}: {1}", apiId, e.getMessage());
@@ -217,9 +217,9 @@ public class WebSocketAuthorizerService {
/**
* Extract the Lambda function name from an authorizer URI.
* Delegates to {@link LambdaArnUtils#extractFunctionNameFromUri(String)}.
* Delegates to {@link LambdaArnUtils#extractFunctionReferenceFromUri(String)}.
*/
private String extractFunctionNameFromUri(String uri) {
return LambdaArnUtils.extractFunctionNameFromUri(uri);
return LambdaArnUtils.extractFunctionReferenceFromUri(uri);
}
}
@@ -160,7 +160,7 @@ public class WebSocketIntegrationInvoker {
LOG.debugv("Invoking Lambda function {0} for AWS_PROXY integration", functionName);
InvokeResult result = lambdaService.invoke(region, functionName,
InvokeResult result = lambdaService.invokeTarget(region, functionName,
eventJson.getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse);
int statusCode = 200;
@@ -230,7 +230,7 @@ public class WebSocketIntegrationInvoker {
LOG.debugv("Invoking Lambda function {0} for AWS integration", functionName);
InvokeResult result = lambdaService.invoke(region, functionName,
InvokeResult result = lambdaService.invokeTarget(region, functionName,
transformedPayload.getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse);
int statusCode = 200;
@@ -544,13 +544,13 @@ public class WebSocketIntegrationInvoker {
/**
* Extract Lambda function name from an integration URI.
* Delegates to {@link LambdaArnUtils#extractFunctionNameFromUri(String)}.
* Delegates to {@link LambdaArnUtils#extractFunctionReferenceFromUri(String)}.
*
* @param uri the integration URI (Lambda ARN or function name)
* @return the extracted function name, or null if not parseable
*/
String extractFunctionName(String uri) {
return LambdaArnUtils.extractFunctionNameFromUri(uri);
return LambdaArnUtils.extractFunctionReferenceFromUri(uri);
}
/**
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import java.util.Arrays;
import java.util.regex.Pattern;
/**
@@ -236,54 +237,20 @@ public final class LambdaArnUtils {
+ "constraint: " + constraint);
}
/**
* Extracts the Lambda function reference from an API Gateway integration URI.
* Handles formats like:
* <ul>
* <li>{@code arn:aws:lambda:us-east-1:000000000000:function:myFn/invocations}</li>
* <li>{@code arn:aws:lambda:us-east-1:000000000000:function:myFn}</li>
* <li>{@code arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD/invocations} (alias/version)</li>
* <li>{@code myFn} (bare function name)</li>
* </ul>
*
* <p>Any trailing {@code :qualifier} (alias or version) is preserved in the returned
* value (e.g. {@code myFn:PROD}) so downstream {@code invoke} calls, which resolve the
* reference via {@link #resolve(String)}, target the configured alias/version rather
* than reducing to the bare function name and invoking {@code $LATEST}.
*
* @param uri the integration URI (may be null)
* @return the extracted function reference (name, optionally with {@code :qualifier}),
* or null if the URI is null or unparseable
*/
public static String extractFunctionNameFromUri(String uri) {
/** Unwraps an API Gateway invocation URI without discarding the target ARN's owner, region or qualifier. */
public static String extractFunctionReferenceFromUri(String uri) {
if (uri == null) {
return null;
}
try {
// Parse as a full ARN — resource is "function:myFn" or "function:myFn/invocations"
String resource = AwsArnUtils.parse(uri).resource();
String[] parts = resource.split("/");
// API Gateway v1 style: resource is "path/2015-03-31/functions/{lambdaArn}/invocations"
// In this case recurse on the embedded Lambda ARN
if (parts.length >= 4 && "path".equals(parts[0]) && "functions".equals(parts[2])) {
// parts[3] onwards is the embedded Lambda ARN
String embeddedArn = String.join("/", java.util.Arrays.copyOfRange(parts, 3, parts.length));
return extractFunctionNameFromUri(embeddedArn);
return extractFunctionReferenceFromUri(String.join("/", Arrays.copyOfRange(parts, 3, parts.length)));
}
// Standard Lambda ARN: parts[0] is "function:myFn" or "function:myFn:qualifier".
// Strip only the leading "function:" resource-type prefix, preserving any
// trailing :qualifier (alias/version) so the invoke target is not lost.
String functionPart = parts[0];
String functionPrefix = "function:";
if (functionPart.startsWith(functionPrefix)) {
return functionPart.substring(functionPrefix.length());
}
// Fallback for malformed/non-standard resources: every real Lambda ARN resource
// starts with "function:" and is handled above, so this only fires on unexpected input.
int colon = functionPart.lastIndexOf(':');
return colon >= 0 ? functionPart.substring(colon + 1) : functionPart;
return uri.split("/", 2)[0];
} catch (IllegalArgumentException e) {
// Not a valid ARN — treat the entire URI as the function name
// Bare and partial function references are validated by the Lambda service.
return uri;
}
}
@@ -1332,6 +1332,12 @@ public class LambdaService implements ResourceProvider {
return new InvokeResult(200, "Unhandled", DurableWire.functionErrorPayload(error), null, requestId);
}
/** Service integrations use the target's region; direct Invoke requests must match their endpoint region. */
public InvokeResult invokeTarget(String defaultRegion, String functionReference, byte[] payload, InvocationType type) {
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(functionReference);
return invoke(ref.region() == null ? defaultRegion : ref.region(), functionReference, payload, type);
}
/**
* Invokes a Lambda target ARN using the account encoded in that ARN.
*
@@ -28,6 +28,7 @@ class ApiGatewayAwsStatusSelectionIntegrationTest {
private static final String ACCOUNT_ID = "000000000000";
private static final String LAMBDA_FUNCTION = "aws-status-selection";
private static final String LAMBDA_ARN = "arn:aws:lambda:us-east-1:" + ACCOUNT_ID + ":function:" + LAMBDA_FUNCTION;
private static final String MESSAGE = "{\"hello\":\"status-selection\"}";
@InjectMock
@@ -111,7 +112,7 @@ class ApiGatewayAwsStatusSelectionIntegrationTest {
@Test
void lambdaSuccessDoesNotMatchHttpStatusPattern() {
when(lambdaService.invoke(eq("us-east-1"), eq(LAMBDA_FUNCTION), any(byte[].class),
when(lambdaService.invokeTarget(eq("us-east-1"), eq(LAMBDA_ARN), any(byte[].class),
eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult(200, null, "{}".getBytes(StandardCharsets.UTF_8), null, "success"));
String apiId = lambdaApi(201, "2\\d{2}");
@@ -119,14 +120,14 @@ class ApiGatewayAwsStatusSelectionIntegrationTest {
given().contentType(ContentType.JSON).body(MESSAGE)
.post("/execute-api/" + apiId + "/test/send")
.then().statusCode(200).body("result", equalTo("default"));
verify(lambdaService).invoke(eq("us-east-1"), eq(LAMBDA_FUNCTION),
verify(lambdaService).invokeTarget(eq("us-east-1"), eq(LAMBDA_ARN),
eq(MESSAGE.getBytes(StandardCharsets.UTF_8)), eq(InvocationType.RequestResponse));
}
@Test
void lambdaFunctionErrorStillMatchesErrorTextPattern() {
byte[] errorPayload = "{\"errorMessage\":\"boom\"}".getBytes(StandardCharsets.UTF_8);
when(lambdaService.invoke(eq("us-east-1"), eq(LAMBDA_FUNCTION), any(byte[].class),
when(lambdaService.invokeTarget(eq("us-east-1"), eq(LAMBDA_ARN), any(byte[].class),
eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult(200, "Unhandled", errorPayload, null, "function-error"));
String apiId = lambdaApi(502, ".*boom.*");
@@ -134,7 +135,7 @@ class ApiGatewayAwsStatusSelectionIntegrationTest {
given().contentType(ContentType.JSON).body(MESSAGE)
.post("/execute-api/" + apiId + "/test/send")
.then().statusCode(502).body("result", equalTo("matched"));
verify(lambdaService).invoke(eq("us-east-1"), eq(LAMBDA_FUNCTION),
verify(lambdaService).invokeTarget(eq("us-east-1"), eq(LAMBDA_ARN),
eq(MESSAGE.getBytes(StandardCharsets.UTF_8)), eq(InvocationType.RequestResponse));
}
@@ -1,11 +1,12 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.lang.reflect.Proxy;
import java.net.URI;
@@ -14,6 +15,7 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -38,9 +40,28 @@ class ApiGatewayCustomDomainFilterTest {
assertEquals("/execute-api/" + API_ID + "/prod/iam", request.routedUri().getRawPath());
assertEquals("tenant=alpha", request.routedUri().getRawQuery());
assertEquals("/v1/iam", routeContext.signedRequestPath());
assertEquals(new ApiGatewayService.CustomDomainRoute("111122223333", "us-east-1", DOMAIN),
routeContext.mappedDomain());
assertTrue(routeContext.isRestApiRoute());
assertEquals(Boolean.TRUE, request.property(ApiGatewayCustomDomainFilter.ROUTED_PROPERTY));
}
@ParameterizedTest
@ValueSource(strings = {"HTTP", "WEBSOCKET"})
void mappedV2ApisKeepTheirOwnerRegionAndType(String type) {
ApiGatewayService service = serviceWithMapping("(none)", "prod", type);
RecordingRequest request = new RecordingRequest(DOMAIN, URI.create("http://" + DOMAIN + "/orders"));
ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext();
new ApiGatewayCustomDomainFilter(service, mock(ApiGatewayV2Service.class), routeContext)
.filter(request.context());
assertEquals("us-east-1", routeContext.httpApiRegion());
assertEquals(new ApiGatewayService.CustomDomainRoute("111122223333", "us-east-1", DOMAIN),
routeContext.mappedDomain());
assertEquals("/orders", routeContext.signedRequestPath());
}
@Test
void recordsBareDomainPathAsTheSignedPath() {
ApiGatewayService service = serviceWithMapping("(none)", "prod");
@@ -74,8 +95,8 @@ class ApiGatewayCustomDomainFilterTest {
@Test
void leavesSignedPathUnsetWhenNoMappingMatches() {
ApiGatewayService service = mock(ApiGatewayService.class);
CustomDomain domain = new CustomDomain();
domain.setDomainName(DOMAIN);
ApiGatewayService.CustomDomainRoute domain =
new ApiGatewayService.CustomDomainRoute("111122223333", "us-east-1", DOMAIN);
when(service.findDomainByName(DOMAIN)).thenReturn(domain);
RecordingRequest request = new RecordingRequest(
DOMAIN, URI.create("http://" + DOMAIN + "/unmapped"));
@@ -90,14 +111,18 @@ class ApiGatewayCustomDomainFilterTest {
}
private static ApiGatewayService serviceWithMapping(String basePath, String stage) {
return serviceWithMapping(basePath, stage, "REST");
}
private static ApiGatewayService serviceWithMapping(String basePath, String stage, String type) {
ApiGatewayService service = mock(ApiGatewayService.class);
CustomDomain domain = new CustomDomain();
domain.setDomainName(DOMAIN);
ApiGatewayService.CustomDomainRoute domain =
new ApiGatewayService.CustomDomainRoute("111122223333", "us-east-1", DOMAIN);
BasePathMapping mapping = new BasePathMapping(basePath, API_ID, stage);
mapping.setApiType("REST");
mapping.setApiType(type);
when(service.findDomainByRegionalHostname(DOMAIN + ".regional.local")).thenReturn(domain);
when(service.findDomainByName(DOMAIN)).thenReturn(domain);
when(service.resolveBasePathMapping(anyString(), anyString())).thenReturn(mapping);
when(service.resolveBasePathMapping(eq(domain), anyString())).thenReturn(mapping);
when(service.stripBasePath(anyString(), eq(mapping)))
.thenAnswer(invocation -> {
String path = invocation.getArgument(0);
@@ -0,0 +1,255 @@
package io.github.hectorvent.floci.services.apigateway;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* A custom-domain route must resolve its resource owner before request account initialization.
* The distinct caller signs the original host/path. This tests routing and authentication only,
* not cross-account IAM policy evaluation.
*/
@QuarkusTest
class ApiGatewayCustomDomainOwnerRoutingTest {
private static final String OWNER = "111122223333";
private static final String CALLER = "444455556666";
private static final String REGION = "us-east-1";
private static final String STAGE = "prod";
private static final String PATH = "/status";
private static final String BODY = "{\"value\":\"original\"}";
@Inject
IamService iamService;
@Inject
ApiGatewayService apiGatewayService;
private String apiId;
private String domain;
private String user;
private AccessKey callerKey;
private boolean domainCreated;
@BeforeEach
void createOwnedApiAndDistinctCaller() {
String suffix = UUID.randomUUID().toString();
user = "domain-route-" + suffix;
domain = "route-" + suffix + ".example.test";
callerKey = RequestScopes.callAs(CALLER, REGION, () -> {
iamService.createUser(user, "/");
return iamService.createAccessKey(user);
});
assertEquals(CALLER, iamService.resolveAccountId(callerKey.getAccessKeyId()).orElseThrow());
apiId = management(OWNER).body("{\"name\":\"owned-domain-route\"}")
.post("/restapis").then().statusCode(201).extract().path("id");
String rootId = management(OWNER).get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item[0].id");
String resourceId = management(OWNER).body("{\"pathPart\":\"status\"}")
.post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201).extract().path("id");
String method = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST";
management(OWNER).body("{\"authorizationType\":\"AWS_IAM\"}")
.put(method).then().statusCode(201);
management(OWNER).body("{\"responseParameters\":{}}")
.put(method + "/responses/200").then().statusCode(201);
management(OWNER).body("""
{"type":"MOCK","requestTemplates":{"application/json":"{\\"statusCode\\":200}"}}
""").put(method + "/integration").then().statusCode(201);
management(OWNER).body("""
{"selectionPattern":"","responseTemplates":{
"application/json":"{\\"reached\\":\\"account-owned-api\\"}"}}
""").put(method + "/integration/responses/200").then().statusCode(201);
String deployment = management(OWNER).body("{\"description\":\"owner-route\"}")
.post("/restapis/" + apiId + "/deployments")
.then().statusCode(201).extract().path("id");
management(OWNER).body(Map.of("stageName", STAGE, "deploymentId", deployment))
.post("/restapis/" + apiId + "/stages").then().statusCode(201);
management(OWNER).body(Map.of(
"domainName", domain, "endpointConfiguration", Map.of("types", List.of("REGIONAL"))))
.post("/domainnames").then().statusCode(201);
domainCreated = true;
management(OWNER).body(Map.of("restApiId", apiId, "stage", STAGE))
.post("/domainnames/" + domain + "/basepathmappings").then().statusCode(201);
management(OWNER).get("/domainnames/" + domain + "/basepathmappings")
.then().statusCode(200).body("item[0].basePath", equalTo("(none)"))
.body("item[0].restApiId", equalTo(apiId)).body("item[0].stage", equalTo(STAGE));
management(CALLER).get("/restapis/" + apiId).then().statusCode(404);
management(CALLER).get("/domainnames/" + domain).then().statusCode(404);
}
@Test
void nonDefaultOwnerRoutesBeforeAccountContextAndKeepsTheOriginalSignature() throws Exception {
String virtualHost = apiId + ".execute-api." + REGION + ".amazonaws.com";
String virtualPath = "/" + STAGE + PATH;
// This control proves the API, caller credential and signature work before testing domain lookup.
given().contentType(ContentType.JSON).header("Host", virtualHost)
.headers(sign(virtualPath, virtualHost)).body(BODY).post(virtualPath)
.then().statusCode(200).body("reached", equalTo("account-owned-api"));
Map<String, String> originalSignature = sign(PATH, domain);
given().contentType(ContentType.JSON).header("Host", domain)
.headers(originalSignature).body(BODY).post(PATH)
.then().statusCode(200).body("reached", equalTo("account-owned-api"));
given().contentType(ContentType.JSON).header("Host", domain)
.headers(originalSignature).body("{\"value\":\"tampered\"}").post(PATH)
.then().statusCode(403).header("x-amzn-ErrorType", "InvalidSignatureException");
given().contentType(ContentType.JSON).header("Host", domain)
.headers(sign("/different", domain)).body(BODY).post(PATH)
.then().statusCode(403).header("x-amzn-ErrorType", "InvalidSignatureException");
given().contentType(ContentType.JSON).header("Host", domain)
.headers(sign(PATH, "other.example.test")).body(BODY).post(PATH)
.then().statusCode(403).header("x-amzn-ErrorType", "InvalidSignatureException");
given().contentType(ContentType.JSON).header("Host", domain)
.headers(sign("/execute-api/" + apiId + "/" + STAGE + PATH, domain)).body(BODY).post(PATH)
.then().statusCode(403).header("x-amzn-ErrorType", "InvalidSignatureException");
management(CALLER).get("/restapis/" + apiId).then().statusCode(404);
}
@ParameterizedTest
@CsvSource({
"444455556666,us-east-1,false", "111122223333,us-west-2,false",
"444455556666,us-east-1,true", "111122223333,us-west-2,true"
})
void mappedRestApiDoesNotBecomeAmbiguousWhenItsIdExistsElsewhere(
String otherAccount, String otherRegion, boolean legacyMapping)
throws Exception {
if (legacyMapping) {
RequestScopes.runAs(OWNER, REGION, () ->
apiGatewayService.getBasePathMapping(REGION, domain, "(none)").setApiType(null));
}
RequestScopes.runAs(otherAccount, otherRegion, () -> apiGatewayService.createRestApi(
otherRegion, Map.of("name", "foreign-collision", "tags", Map.of("floci:override-id", apiId))));
try {
given().contentType(ContentType.JSON).header("Host", domain)
.headers(sign(PATH, domain)).body(BODY).post(PATH)
.then().statusCode(200).body("reached", equalTo("account-owned-api"));
given().post("/execute-api/" + apiId + "/" + STAGE + PATH).then().statusCode(409);
} finally {
RequestScopes.runAs(otherAccount, otherRegion,
() -> apiGatewayService.deleteRestApi(otherRegion, apiId));
}
}
@ParameterizedTest
@CsvSource({"us-east-1", "us-west-2"})
void mappedHttpApiCannotBeClaimedByAForeignRestApiWithTheSameId(String httpRegion) throws Exception {
HttpServer target = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
target.createContext("/", exchange -> {
byte[] response = "{\"reached\":\"mapped-http-api\"}".getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, response.length);
try (OutputStream output = exchange.getResponseBody()) {
output.write(response);
}
});
target.start();
String httpDomain = "http-" + domain;
String httpApi = null;
boolean httpDomainCreated = false;
boolean collisionCreated = false;
try {
httpApi = management(OWNER, httpRegion).body(Map.of("name", "mapped-http", "protocolType", "HTTP"))
.post("/v2/apis").then().statusCode(201).extract().path("apiId");
String integration = management(OWNER, httpRegion).body(Map.of(
"integrationType", "HTTP_PROXY", "integrationMethod", "ANY",
"integrationUri", "http://127.0.0.1:" + target.getAddress().getPort()))
.post("/v2/apis/" + httpApi + "/integrations").then().statusCode(201)
.extract().path("integrationId");
management(OWNER, httpRegion).body(
Map.of("routeKey", "GET /status", "target", "integrations/" + integration))
.post("/v2/apis/" + httpApi + "/routes").then().statusCode(201);
management(OWNER, httpRegion).body(Map.of("stageName", STAGE, "autoDeploy", true))
.post("/v2/apis/" + httpApi + "/stages").then().statusCode(201);
management(OWNER, httpRegion).body(Map.of("domainName", httpDomain,
"domainNameConfigurations", List.of(Map.of("endpointType", "REGIONAL"))))
.post("/v2/domainnames").then().statusCode(201);
httpDomainCreated = true;
management(OWNER, httpRegion).body(Map.of("apiId", httpApi, "stage", STAGE))
.post("/v2/domainnames/" + httpDomain + "/apimappings").then().statusCode(201);
management(CALLER).body(Map.of("name", "foreign-rest",
"tags", Map.of("floci:override-id", httpApi)))
.post("/restapis").then().statusCode(201);
collisionCreated = true;
given().header("Host", httpDomain).get(PATH)
.then().statusCode(200).body("reached", equalTo("mapped-http-api"));
management(CALLER, httpRegion).get("/v2/apis/" + httpApi).then().statusCode(404);
} finally {
target.stop(0);
if (collisionCreated) {
management(CALLER).delete("/restapis/" + httpApi).then().statusCode(202);
}
if (httpDomainCreated) {
management(OWNER, httpRegion).delete("/v2/domainnames/" + httpDomain).then().statusCode(204);
}
if (httpApi != null) {
management(OWNER, httpRegion).delete("/v2/apis/" + httpApi).then().statusCode(204);
}
}
}
private Map<String, String> sign(String path, String host) throws Exception {
return ExecuteApiRequestSigner.signedHeaders(
"POST", path, Map.of(), host, BODY.getBytes(StandardCharsets.UTF_8),
callerKey.getAccessKeyId(), callerKey.getSecretAccessKey(), REGION, Instant.now());
}
private static RequestSpecification management(String account) {
return management(account, REGION);
}
private static RequestSpecification management(String account, String region) {
// Management account selection follows the existing public API tests; data-plane calls use real HMACs.
return given().contentType(ContentType.JSON).header("Authorization",
"AWS4-HMAC-SHA256 Credential=" + account + "/20261008/" + region + "/apigateway/aws4_request");
}
@AfterEach
void removeOnlyThisTestGraph() {
List<Executable> cleanup = new ArrayList<>();
if (domainCreated) {
cleanup.add(() -> management(OWNER).delete("/domainnames/" + domain).then().statusCode(202));
}
if (apiId != null) {
cleanup.add(() -> management(OWNER).delete("/restapis/" + apiId).then().statusCode(202));
}
if (callerKey != null) {
cleanup.add(() -> RequestScopes.runAs(CALLER, REGION,
() -> iamService.deleteAccessKey(user, callerKey.getAccessKeyId())));
}
if (user != null) {
cleanup.add(() -> RequestScopes.runAs(CALLER, REGION, () -> iamService.deleteUser(user)));
}
assertAll("owned test resource cleanup", cleanup);
}
}
@@ -0,0 +1,128 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ApiGatewayCustomDomainOwnerServiceTest {
private static final String DEFAULT_ACCOUNT = "000000000000";
private static final String OWNER = "111122223333";
private static final String OTHER_ACCOUNT = "444455556666";
private static final String REGION = "us-east-1";
private static final String OTHER_REGION = "us-west-2";
private static final String DOMAIN = "owned.example.test";
private final Map<String, AccountAwareStorageBackend<?>> stores = new HashMap<>();
private ApiGatewayService service;
@BeforeEach
void setUp() {
StorageFactory storageFactory = mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(invocation ->
stores.computeIfAbsent(invocation.getArgument(1, String.class),
ignored -> AccountAwareStorageBackend.inMemory(DEFAULT_ACCOUNT)));
service = new ApiGatewayService(storageFactory,
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), mock(TlsCertificateManager.class),
new RegionResolver(REGION, DEFAULT_ACCOUNT));
}
@Test
void resolvesNonDefaultOwnerWithoutGrantingManagementVisibility() {
putDomain(OWNER, REGION);
ApiGatewayService.CustomDomainRoute route = service.findDomainByName(DOMAIN);
assertEquals(new ApiGatewayService.CustomDomainRoute(OWNER, REGION, DOMAIN), route);
assertEquals(route, service.findDomainByRegionalHostname(DOMAIN + ".regional.local"));
AwsException hidden = assertThrows(AwsException.class, () -> service.getDomainName(REGION, DOMAIN));
assertEquals("NotFoundException", hidden.getErrorCode());
}
@Test
void usesOnlyTheOwnersExactRegionAndDomainThenKeepsLongestPrefixMatching() {
putDomain(OWNER, REGION);
ApiGatewayService.CustomDomainRoute route = service.findDomainByName(DOMAIN);
BasePathMapping foreign = new BasePathMapping("orders/special", "foreign-api", "foreign");
mappings().putForAccount(OTHER_ACCOUNT, REGION + "::" + DOMAIN + "::orders/special", foreign);
mappings().putForAccount(OWNER, OTHER_REGION + "::" + DOMAIN + "::orders/special", foreign);
mappings().putForAccount(OWNER, REGION + "::prefix." + DOMAIN + "::orders/special", foreign);
assertNull(service.resolveBasePathMapping(route, "/orders/special/42"));
BasePathMapping root = new BasePathMapping("(none)", "owned-api", "root");
BasePathMapping orders = new BasePathMapping("orders", "owned-api", "orders");
mappings().putForAccount(OWNER, REGION + "::" + DOMAIN + "::(none)", root);
mappings().putForAccount(OWNER, REGION + "::" + DOMAIN + "::orders", orders);
assertSame(orders, service.resolveBasePathMapping(route, "/orders/special/42"));
assertSame(orders, service.resolveBasePathMapping(route, "/orders"));
assertSame(root, service.resolveBasePathMapping(route, "/orders-other"));
assertSame(root, service.resolveBasePathMapping(route, "/"));
}
@Test
void refusesAmbiguousDomainAcrossAccounts() {
putDomain(OWNER, REGION);
putDomain(OTHER_ACCOUNT, REGION);
AwsException ambiguous = assertThrows(AwsException.class, () -> service.findDomainByName(DOMAIN));
assertEquals("ConflictException", ambiguous.getErrorCode());
assertEquals(409, ambiguous.getHttpStatus());
}
@Test
void refusesAmbiguousDomainAcrossRegions() {
putDomain(OWNER, REGION);
putDomain(OWNER, OTHER_REGION);
AwsException ambiguous = assertThrows(AwsException.class,
() -> service.findDomainByRegionalHostname(DOMAIN + ".regional.local"));
assertEquals("ConflictException", ambiguous.getErrorCode());
assertEquals(409, ambiguous.getHttpStatus());
}
@Test
void leavesUnknownHostsUnclaimed() {
putDomain(OWNER, REGION);
assertNull(service.findDomainByName("other.example.test"));
assertNull(service.findDomainByRegionalHostname("other.example.test.regional.local"));
assertNull(service.findDomainByRegionalHostname(DOMAIN));
}
@SuppressWarnings("unchecked")
private void putDomain(String account, String region) {
AccountAwareStorageBackend<CustomDomain> domains =
(AccountAwareStorageBackend<CustomDomain>) stores.get("apigateway-domains.json");
CustomDomain domain = new CustomDomain();
domain.setDomainName(DOMAIN);
domains.putForAccount(account, region + "::" + DOMAIN, domain);
}
@SuppressWarnings("unchecked")
private AccountAwareStorageBackend<BasePathMapping> mappings() {
return (AccountAwareStorageBackend<BasePathMapping>) stores.get("apigateway-mappings.json");
}
}
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.apigatewayv2.model.Api;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
@@ -452,6 +453,8 @@ class ApiGatewayExecuteControllerTest {
@Test
void signedV2RequestDoesNotConsultRegionFallback() {
RegionResolver regionResolver = mock(RegionResolver.class);
RequestContext requestContext = new RequestContext();
requestContext.setAccountId("000000000000");
ApiGatewayV2Service apiGatewayV2Service = mock(ApiGatewayV2Service.class);
ApiGatewayService apiGatewayService = mock(ApiGatewayService.class);
HttpHeaders headers = mock(HttpHeaders.class);
@@ -471,13 +474,14 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, null, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null);
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, requestContext, null, null, null);
controller.dispatch("GET", "abc123", "prod", "hello", headers, null, null);
// A correctly-signed (or otherwise resolved) request must not pay for the v1 region
// scan — resolveRestApiRegion is only for the "region is a guess" case.
verify(apiGatewayService, never()).resolveRestApiRegion(anyString(), anyString());
verify(apiGatewayService).findRestApiOwner("abc123", "000000000000", "us-east-1");
verify(apiGatewayV2Service, atLeastOnce()).getApi("us-east-1", "abc123");
}
@@ -244,7 +244,7 @@ class ApiGatewayHttpContextMappingIntegrationTest {
assertNotEquals(previousRequestId, requestId);
previousRequestId = requestId;
}
verify(lambdaService).invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
verify(lambdaService).invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
}
@ParameterizedTest
@@ -450,7 +450,7 @@ class ApiGatewayHttpContextMappingIntegrationTest {
.get("/execute-api/" + apiId + "/test/orders/42")
.then().statusCode(200).extract().asByteArray());
ArgumentCaptor<byte[]> invocation = ArgumentCaptor.forClass(byte[].class);
verify(lambdaService).invoke(eq("us-east-1"), eq(FUNCTION), invocation.capture(), eq(InvocationType.RequestResponse));
verify(lambdaService).invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + FUNCTION), invocation.capture(), eq(InvocationType.RequestResponse));
JsonNode authorizerContext = MAPPER.readTree(invocation.getValue()).path("requestContext");
for (String field : List.of("requestId", "extendedRequestId", "requestTimeEpoch")) {
assertEquals(authorizerContext.path(field).asText(), response.path("headers").path("x-" + field.toLowerCase(Locale.ROOT)).path(0).asText());
@@ -540,7 +540,7 @@ class ApiGatewayHttpContextMappingIntegrationTest {
given().contentType(ContentType.JSON)
.body(Map.of("authorizationType", "CUSTOM", "authorizerId", authorizerId))
.put(methodPath + "GET").then().statusCode(201);
when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenAnswer(invocation -> {
JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2));
String effect = "REQUEST".equals(type) || "Bearer allowed".equals(event.path("authorizationToken").asText()) ? "Allow" : "Deny";
@@ -111,7 +111,7 @@ class ApiGatewayMockAuthorizerIntegrationTest {
given().get("/execute-api/" + apiId + "/test/claims")
.then().statusCode(201).body("hasAuthorizer", equalTo(false));
verify(lambdaService, never()).invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class),
verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + FUNCTION), any(byte[].class),
eq(InvocationType.RequestResponse));
}
@@ -131,7 +131,7 @@ class ApiGatewayMockAuthorizerIntegrationTest {
"Action", "execute-api:Invoke", "Effect", effect, "Resource", "*"))),
"context", Map.of("principalId", "custom-principal", "role", "admin",
"numberKey", 1, "booleanKey", true)));
when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class),
when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + FUNCTION), any(byte[].class),
eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult(200, null, payload, null, "authorizer-request"));
}
@@ -325,7 +325,7 @@ class ApiGatewayPutRestApiMergeAuthorizationTest {
() -> assertEquals("COGNITO_USER_POOLS", authorizer.path("type").asText()),
() -> assertEquals(AUTHORIZER_URI, authorizer.path("authorizerUri").asText()));
when(lambdaService.invoke(eq("us-east-1"), eq(AUTHORIZER_FUNCTION), any(byte[].class),
when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + AUTHORIZER_FUNCTION), any(byte[].class),
eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult(200, null, ALLOW_POLICY, null, "authorizer-request"));
deploy(apiId, "mismatched-type");
@@ -878,7 +878,7 @@ class ApiGatewayPutRestApiMergeAuthorizationTest {
}
private void denyAuthorizerRequests(String function) {
when(lambdaService.invoke(eq("us-east-1"), eq(function), any(byte[].class),
when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + function), any(byte[].class),
eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult(200, null, DENY_POLICY, null, "authorizer-request"));
}
@@ -888,7 +888,7 @@ class ApiGatewayPutRestApiMergeAuthorizationTest {
}
private void verifyDenyInvocations(String function, int count) {
verify(lambdaService, times(count)).invoke(eq("us-east-1"), eq(function),
verify(lambdaService, times(count)).invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + function),
any(byte[].class), eq(InvocationType.RequestResponse));
}
}
@@ -6,6 +6,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.apigatewayv2.model.Api;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.testing.ConfiguredHostnameProfile;
import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner;
import io.quarkus.test.junit.QuarkusTest;
@@ -13,9 +15,13 @@ import io.quarkus.test.junit.TestProfile;
import io.restassured.http.ContentType;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@@ -29,6 +35,183 @@ class ApiGatewayRestExecuteApiHostIntegrationTest {
@Inject
ApiGatewayV2Service v2Service;
@Inject
ApiGatewayService restService;
@Inject
IamService iamService;
@ParameterizedTest
@CsvSource({"eu-west-1,amazonaws.com", "us-gov-west-1,amazonaws.com", "cn-north-1,amazonaws.com.cn"})
void publicRestUrlResolvesItsOwnerWithoutExposingManagementReads(String region, String suffix) {
String owner = "111122223333";
String authorization = managementAccount(owner, region);
String apiId = createOwnedApi(authorization);
try {
given().header("Authorization", authorization).contentType(ContentType.JSON)
.body("{\"stageName\":\"test\"}").post("/restapis/" + apiId + "/deployments")
.then().statusCode(201);
given().header("Host", apiId + ".execute-api." + region + "." + suffix)
.get("/test/ping").then().statusCode(200).body("route", equalTo("ping"));
given().header("Authorization", managementAccount("000000000000", region))
.get("/restapis/" + apiId).then().statusCode(404);
given().header("Authorization", authorization).get("/restapis/" + apiId)
.then().statusCode(200).body("id", equalTo(apiId));
} finally {
RequestScopes.runAs(owner, () -> restService.deleteRestApi(region, apiId));
}
}
@Test
void signedRestCallerCanDifferFromApiOwnerAndMissingOrTamperedSignaturesStillFail() throws Exception {
String owner = "222233334444";
String caller = "444455556666";
String authorization = managementAccount(owner);
String apiId = createOwnedApi(authorization);
String userName = "rest-caller-" + UUID.randomUUID();
AccessKey key = RequestScopes.callAs(caller, () -> {
iamService.createUser(userName, "/");
return iamService.createAccessKey(userName);
});
try {
String methodPath = "/restapis/" + apiId + "/resources/"
+ resourceId(apiId, "/ping", authorization) + "/methods/GET";
given().header("Authorization", authorization).contentType(ContentType.JSON)
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/authorizationType\","
+ "\"value\":\"AWS_IAM\"}]}").patch(methodPath).then().statusCode(200);
given().header("Authorization", authorization).contentType(ContentType.JSON)
.body("{\"stageName\":\"test\"}").post("/restapis/" + apiId + "/deployments")
.then().statusCode(201);
String host = apiId + ".execute-api.eu-west-1.amazonaws.com";
String path = "/test/ping";
given().header("Host", host).get(path).then().statusCode(403);
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders(
"GET", path, Map.of(), host, null, key.getAccessKeyId(),
key.getSecretAccessKey(), "eu-west-1", Instant.now());
given().header("Host", host).headers(signed).get(path)
.then().statusCode(200).body("route", equalTo("ping"))
.body("callerAccount", equalTo(caller))
.body("callerArn", equalTo("arn:aws:iam::" + caller + ":user/" + userName));
Map<String, String> tampered = new LinkedHashMap<>(signed);
String header = signed.get("Authorization");
tampered.put("Authorization", header.substring(0, header.length() - 1)
+ (header.endsWith("0") ? "1" : "0"));
given().header("Host", host).headers(tampered).get(path).then().statusCode(403);
given().header("Authorization", managementAccount(caller)).get("/restapis/" + apiId)
.then().statusCode(404);
} finally {
RequestScopes.runAs(caller, () -> {
iamService.deleteAccessKey(userName, key.getAccessKeyId());
iamService.deleteUser(userName);
});
RequestScopes.runAs(owner, () -> restService.deleteRestApi("eu-west-1", apiId));
}
}
@Test
void ambiguousRestIdsAcrossOwnersRefuseDataPlaneLookup() {
String apiId = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
for (String owner : new String[]{"555566667777", "666677778888"}) {
RequestScopes.runAs(owner, () -> restService.createRestApi("eu-west-1",
Map.of("name", "ambiguous-rest", "tags", Map.of("floci:override-id", apiId))));
}
try {
given().header("Host", apiId + ".execute-api.eu-west-1.amazonaws.com")
.get("/test/ping").then().statusCode(409);
} finally {
for (String owner : new String[]{"555566667777", "666677778888"}) {
RequestScopes.runAs(owner, () -> restService.deleteRestApi("eu-west-1", apiId));
}
}
}
@Test
void signedCallersRetainTheirOwnApiWhenIdsAreDuplicatedAcrossAccounts() throws Exception {
String region = "eu-west-1";
String apiId = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
String user = "duplicate-id-" + UUID.randomUUID();
String[] owners = {"555566667777", "666677778888"};
String unrelated = "777788889999";
Map<String, AccessKey> keys = new LinkedHashMap<>();
try {
for (String account : new String[] {owners[0], owners[1], unrelated}) {
keys.put(account, RequestScopes.callAs(account, () -> {
iamService.createUser(user, "/");
return iamService.createAccessKey(user);
}));
}
for (String owner : owners) {
ObjectNode document = JSON.createObjectNode();
document.put("openapi", "3.0.1");
document.putObject("info").put("title", "duplicate-owner").put("version", "1");
ObjectNode paths = document.putObject("paths");
addMockMethod(paths, "/ping", owner);
document.putObject("components").putObject("securitySchemes").putObject("iam")
.put("type", "apiKey").put("name", "Authorization").put("in", "header")
.put("x-amazon-apigateway-authtype", "awsSigv4");
((ObjectNode) document.at("/paths/~1ping/get")).putArray("security")
.addObject().putArray("iam");
RequestScopes.runAs(owner, region, () -> {
restService.createRestApi(region,
Map.of("name", "duplicate-owner", "tags", Map.of("floci:override-id", apiId)));
restService.putRestApi(region, apiId, "overwrite", document.toString());
restService.createDeployment(region, apiId, Map.of("stageName", "test"));
});
}
String host = apiId + ".execute-api." + region + ".amazonaws.com";
String path = "/test/ping";
for (String owner : owners) {
AccessKey key = keys.get(owner);
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders(
"GET", path, Map.of(), host, null,
key.getAccessKeyId(), key.getSecretAccessKey(), region, Instant.now());
given().header("Host", host).headers(signed).get(path)
.then().statusCode(200).body("route", equalTo(owner))
.body("callerAccount", equalTo(owner));
Map<String, String> tampered = new LinkedHashMap<>(signed);
String authorization = signed.get("Authorization");
tampered.put("Authorization", authorization.substring(0, authorization.length() - 1)
+ (authorization.endsWith("0") ? "1" : "0"));
given().header("Host", host).headers(tampered).get(path).then().statusCode(403);
}
AccessKey otherKey = keys.get(unrelated);
Map<String, String> otherSigned = ExecuteApiRequestSigner.signedHeaders(
"GET", path, Map.of(), host, null,
otherKey.getAccessKeyId(), otherKey.getSecretAccessKey(), region, Instant.now());
given().header("Host", host).headers(otherSigned).get(path).then().statusCode(409);
given().header("Host", host).get(path).then().statusCode(409);
} finally {
for (String owner : owners) {
RequestScopes.runAs(owner, region, () -> {
if (restService.hasRestApi(region, apiId)) {
restService.deleteRestApi(region, apiId);
}
});
}
for (Map.Entry<String, AccessKey> entry : keys.entrySet()) {
RequestScopes.runAs(entry.getKey(), () -> {
iamService.deleteAccessKey(user, entry.getValue().getAccessKeyId());
iamService.deleteUser(user);
});
}
}
}
private static String managementAccount(String account) {
return managementAccount(account, "eu-west-1");
}
private static String managementAccount(String account, String region) {
return "AWS4-HMAC-SHA256 Credential=" + account
+ "/20261008/" + region + "/apigateway/aws4_request, SignedHeaders=host, Signature=abc";
}
private static String createOwnedApi(String authorization) {
return given().header("Authorization", authorization).contentType(ContentType.JSON)
.queryParam("mode", "import").body(spec()).post("/restapis")
.then().statusCode(201).extract().path("id");
}
@Test
void routesRestApiVirtualHostToDeployedMethods() {
String apiId = given()
@@ -270,7 +453,12 @@ class ApiGatewayRestExecuteApiHostIntegrationTest {
}
private static String resourceId(String apiId, String path) throws Exception {
return resourceId(apiId, path, null);
}
private static String resourceId(String apiId, String path, String authorization) throws Exception {
String resources = given()
.headers(authorization == null ? Map.of() : Map.of("Authorization", authorization))
.when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200)
.extract().asString();
@@ -301,6 +489,8 @@ class ApiGatewayRestExecuteApiHostIntegrationTest {
integration.putObject("requestTemplates").put("application/json", "{\"statusCode\":200}");
integration.putObject("responses").putObject("default")
.put("statusCode", "200")
.putObject("responseTemplates").put("application/json", "{\"route\":\"" + route + "\"}");
.putObject("responseTemplates").put("application/json", "{\"route\":\"" + route
+ "\",\"callerAccount\":\"$context.identity.accountId\","
+ "\"callerArn\":\"$context.identity.userArn\"}");
}
}
@@ -167,7 +167,8 @@ class ApiGatewayV2ApiMappingServiceTest {
StoredMapping created = service.createApiMapping(REGION, DOMAIN, "orders/v1/items", apiId, "prod");
assertEquals("REST", created.mapping().getApiType());
assertEquals(apiId, service.resolveBasePathMapping(DOMAIN, "/orders/v1/items/123").getRestApiId());
assertEquals(apiId, service.resolveBasePathMapping(
service.findDomainByName(DOMAIN), "/orders/v1/items/123").getRestApiId());
}
@Test
@@ -67,7 +67,7 @@ class HttpApiAuthorizerPolicyTest {
when(headers.getRequestHeaders()).thenReturn(new MultivaluedHashMap<>());
when(uri.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
when(uri.getRequestUri()).thenReturn(URI.create("http://localhost/execute-api/api/test/items"));
when(lambda.invoke(eq("us-east-1"), eq("backend"), any(byte[].class), eq(InvocationType.RequestResponse)))
when(lambda.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + "backend"), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenAnswer(invocation -> {
JsonNode event = mapper.readTree((byte[]) invocation.getArgument(2));
assertEquals(7, event.at("/requestContext/authorizer/lambda/tenant/id").asInt());
@@ -89,7 +89,7 @@ class HttpApiAuthorizerPolicyTest {
}
private void assertPolicy(String version, String statements, int expectedStatus) {
when(lambda.invoke(eq("us-east-1"), eq("authorizer"), any(byte[].class), eq(InvocationType.RequestResponse)))
when(lambda.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + "authorizer"), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenAnswer(invocation -> {
JsonNode event = mapper.readTree((byte[]) invocation.getArgument(2));
String arn = event.path("1.0".equals(version) ? "methodArn" : "routeArn").asText();
@@ -103,7 +103,7 @@ class HttpApiAuthorizerPolicyTest {
assertEquals(expectedStatus, response.getStatus(), "payload version " + version);
}
verify(lambda, times(expectedStatus == 200 ? 1 : 0))
.invoke(eq("us-east-1"), eq("backend"), any(byte[].class), eq(InvocationType.RequestResponse));
.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + "backend"), any(byte[].class), eq(InvocationType.RequestResponse));
}
@ParameterizedTest
@@ -149,13 +149,13 @@ class HttpApiAuthorizerPolicyTest {
@ParameterizedTest
@ValueSource(booleans = {true, false})
void simpleResponsesUseIsAuthorized(boolean authorized) {
when(lambda.invoke(eq("us-east-1"), eq("authorizer"), any(byte[].class), eq(InvocationType.RequestResponse)))
when(lambda.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + "authorizer"), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenReturn(result("{\"isAuthorized\":" + authorized + ",\"context\":{\"tenant\":{\"id\":7}}}"));
try (Response response = controller("2.0", true).handleGet(headers, uri, "api", "test", "items")) {
assertEquals(authorized ? 200 : 403, response.getStatus());
}
verify(lambda, times(authorized ? 1 : 0))
.invoke(eq("us-east-1"), eq("backend"), any(byte[].class), eq(InvocationType.RequestResponse));
.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + "backend"), any(byte[].class), eq(InvocationType.RequestResponse));
}
private ApiGatewayExecuteController controller(String version, boolean simpleResponses) {
@@ -161,7 +161,7 @@ class RestLambdaAuthorizerIntegrationTest {
given().contentType(ContentType.JSON).body(Map.of("type", "AWS_PROXY", "httpMethod", "POST",
"uri", AUTHORIZER_URI.replace(FUNCTION, "context-proxy")))
.put(methodPath(resourceId) + "/integration").then().statusCode(201);
when(lambdaService.invoke(eq("us-east-1"), eq("context-proxy"), any(byte[].class), eq(InvocationType.RequestResponse)))
when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + "context-proxy"), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenAnswer(invocation -> {
ObjectMapper mapper = new ObjectMapper();
String context = mapper.readTree((byte[]) invocation.getArgument(2))
@@ -230,7 +230,7 @@ class RestLambdaAuthorizerIntegrationTest {
CountDownLatch started = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicInteger invocations = new AtomicInteger();
when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenAnswer(invocation -> {
boolean first = invocations.incrementAndGet() == 1;
if (first) {
@@ -308,7 +308,7 @@ class RestLambdaAuthorizerIntegrationTest {
void lambdaErrorsDistinguishUnauthorizedFromFailure(String message) throws Exception {
configure("TOKEN", 300, "method.request.header.Authorization");
byte[] payload = new ObjectMapper().writeValueAsBytes(Map.of("errorMessage", message));
when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult(200, "Unhandled", payload, null, "lambda-error"));
for (int i = 0; i < 2; i++) {
given().header("Authorization", "token").get(execute("allowed"))
@@ -355,15 +355,15 @@ class RestLambdaAuthorizerIntegrationTest {
private void respond(Map<String, Object> output) throws Exception {
byte[] payload = new ObjectMapper().writeValueAsBytes(output);
when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult(200, null, payload, null, "lambda-request"));
}
private void verifyInvocation(int count) {
if (count == 0) {
verify(lambdaService, never()).invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
verify(lambdaService, never()).invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
} else {
verify(lambdaService, times(count)).invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
verify(lambdaService, times(count)).invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
}
}
@@ -55,12 +55,12 @@ class LambdaAuthorizerPolicyIntegrationTest {
void httpRequestsEnforceAuthorizerPolicies(String scenario, String statements, int expectedStatus) {
configureApi("HTTP");
stubAuthorizer(statements);
when(lambdaService.invoke(eq("us-east-1"), eq(BACKEND_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + BACKEND_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenReturn(result("{\"statusCode\":200,\"body\":\"allowed\"}"));
given().header("X-Forwarded-For", "198.51.100.42")
.get("/execute-api/" + apiId + "/test/items").then().statusCode(expectedStatus);
verify(lambdaService, times(expectedStatus == 200 ? 1 : 0))
.invoke(eq("us-east-1"), eq(BACKEND_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + BACKEND_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse));
}
@ParameterizedTest(name = "WebSocket: {0}")
@@ -122,7 +122,7 @@ class LambdaAuthorizerPolicyIntegrationTest {
}
private void stubAuthorizer(String statements) {
when(lambdaService.invoke(eq("us-east-1"), eq(AUTHORIZER_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + AUTHORIZER_FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenAnswer(invocation -> {
JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2));
String arn = event.has("routeArn") ? event.path("routeArn").asText() : event.path("methodArn").asText();
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.apigatewayv2;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
@@ -11,7 +12,6 @@ import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.notNullValue;
@@ -187,14 +187,8 @@ class WebSocketStageVariablesTest {
ws.sendText("{\"action\":\"test\",\"data\":\"missing-var-test\"}", true).join();
// The substitution replaces ${stageVariables.missingVar} with empty string,
// resulting in an empty function name. The invoker returns IntegrationResult(500, null, ...)
// Since body is null, no response is sent back to the client.
// We verify this by expecting a timeout — proving the substitution happened
// (empty string was used) and the Lambda was NOT successfully invoked.
assertThrows(TimeoutException.class, () -> {
capture.getResponse(3, TimeUnit.SECONDS);
}, "Should not receive a successful response when stage variable is undefined (function name becomes empty)");
String response = capture.getResponse(3, TimeUnit.SECONDS);
assertEquals("Internal server error", JsonPath.from(response).getString("message"));
ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();
Thread.sleep(500);
@@ -81,7 +81,7 @@ class WebSocketAuthorizerPolicyTest {
WebSocketProxyEventBuilder builder = new WebSocketProxyEventBuilder();
builder.objectMapper = mapper;
builder.regionResolver = new RegionResolver("us-east-1", "000000000000");
when(lambda.invoke(eq("us-east-1"), eq("authorizer"), any(byte[].class), eq(InvocationType.RequestResponse)))
when(lambda.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:" + "authorizer"), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenAnswer(invocation -> {
JsonNode event = mapper.readTree((byte[]) invocation.getArgument(2));
String arn = event.path("methodArn").asText();
@@ -0,0 +1,205 @@
package io.github.hectorvent.floci.services.lambda;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.stubbing.Answer;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.when;
/** Real account, function and alias resolution; only execution of the selected function is mocked. */
@QuarkusTest
class ApiGatewayLambdaOwnerIntegrationTest {
private static final String API_OWNER = "111122223333";
private static final String TARGET_OWNER = "777788889999";
private static final String CALLER = "444455556666";
private static final String REGION = "us-east-1";
private static final byte[] BODY = "{\"value\":\"original\"}".getBytes(StandardCharsets.UTF_8);
@Inject
IamService iamService;
@Inject
ObjectMapper mapper;
@InjectMock
LambdaExecutorService executor;
private final List<Executable> cleanup = new ArrayList<>();
private String function;
private String apiId;
private String method;
private String domain;
private AccessKey callerKey;
@BeforeEach
void setUp() throws Exception {
String suffix = UUID.randomUUID().toString();
function = "owned-lambda-" + suffix;
domain = suffix + ".example.test";
callerKey = RequestScopes.callAs(CALLER, REGION, () -> {
iamService.createUser(function, "/");
return iamService.createAccessKey(function);
});
cleanup.add(() -> RequestScopes.runAs(CALLER, REGION,
() -> iamService.deleteAccessKey(function, callerKey.getAccessKeyId())));
cleanup.add(() -> RequestScopes.runAs(CALLER, REGION, () -> iamService.deleteUser(function)));
Answer<InvokeResult> execution = invocation -> {
LambdaFunction selected = invocation.getArgument(0);
String body = mapper.writeValueAsString(Map.of(
"account", selected.getAccountId(), "version", selected.getVersion(),
"arn", selected.getFunctionArn()));
return new InvokeResult(200, null,
mapper.writeValueAsBytes(Map.of("statusCode", 200, "body", body)), null, "selected-function");
};
when(executor.invoke(any(LambdaFunction.class), any(byte[].class), eq(InvocationType.RequestResponse),
anyInt(), nullable(String.class), nullable(String.class))).thenAnswer(execution);
when(executor.invoke(any(LambdaFunction.class), any(byte[].class), eq(InvocationType.RequestResponse),
anyInt(), nullable(String.class))).thenAnswer(execution);
createFunction(API_OWNER, REGION);
apiId = management(API_OWNER, REGION, "apigateway").body(Map.of("name", function))
.post("/restapis").then().statusCode(201).extract().path("id");
cleanup.add(() -> management(API_OWNER, REGION, "apigateway")
.delete("/restapis/" + apiId).then().statusCode(202));
String rootId = management(API_OWNER, REGION, "apigateway").get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item[0].id");
method = "/restapis/" + apiId + "/resources/" + rootId + "/methods/POST";
management(API_OWNER, REGION, "apigateway").body(Map.of("authorizationType", "AWS_IAM"))
.put(method).then().statusCode(201);
}
@ParameterizedTest
@CsvSource({"AWS_PROXY,live,us-east-1", "AWS_PROXY,1,us-east-1",
"AWS,live,us-east-1", "AWS,1,us-east-1",
"AWS_PROXY,live,eu-west-1", "AWS,live,eu-west-1"})
void theIntegrationSelectsItsAccountRegionAndPublishedVersion(String type, String qualifier,
String targetRegion) throws Exception {
createFunction(TARGET_OWNER, targetRegion);
integrate(type, arn(TARGET_OWNER, targetRegion) + ":" + qualifier);
String bodyPath = type.equals("AWS") ? "body" : "";
String response = invoke(200);
String body = bodyPath.isEmpty() ? response : mapper.readTree(response).path(bodyPath).asText();
assertAll(
() -> assertEquals(TARGET_OWNER,
mapper.readTree(body).path("account").asText()),
() -> assertEquals("1",
mapper.readTree(body).path("version").asText()),
() -> assertTrue(
mapper.readTree(body).path("arn").asText().contains(":" + targetRegion + ":" + TARGET_OWNER + ":")));
}
@Test
void missingTargetDoesNotFallBackToSameNamedFunctionInApiAccount() throws Exception {
integrate("AWS_PROXY", arn(TARGET_OWNER, REGION) + ":live");
invoke(404);
}
@Test
void unqualifiedLocalNameKeepsTheApiOwner() throws Exception {
integrate("AWS_PROXY", function + ":live");
given().contentType(ContentType.JSON).header("Host", domain).headers(sign()).body(BODY).post("/")
.then().statusCode(200).body("account", equalTo(API_OWNER)).body("version", equalTo("1"));
}
private void createFunction(String account, String region) throws Exception {
ByteArrayOutputStream archive = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(archive)) {
zip.putNextEntry(new ZipEntry("handler.py"));
zip.write("def handler(event, context):\n return event\n".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
String path = "/2015-03-31/functions/" + function;
management(account, region, "lambda").body(Map.of(
"FunctionName", function, "Runtime", "python3.12", "Handler", "handler.handler",
"Role", "arn:aws:iam::" + account + ":role/test",
"Code", Map.of("ZipFile", Base64.getEncoder().encodeToString(archive.toByteArray()))))
.post("/2015-03-31/functions").then().statusCode(201);
cleanup.add(() -> management(account, region, "lambda").delete(path).then().statusCode(204));
management(account, region, "lambda").body("{}").post(path + "/versions")
.then().statusCode(201).body("Version", equalTo("1"));
management(account, region, "lambda").body(Map.of("Name", "live", "FunctionVersion", "1"))
.post(path + "/aliases").then().statusCode(201);
}
private void integrate(String type, String target) {
String uri = target.startsWith("arn:")
? "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + target + "/invocations"
: target;
management(API_OWNER, REGION, "apigateway")
.body(Map.of("type", type, "httpMethod", "POST", "uri", uri))
.put(method + "/integration").then().statusCode(201);
if (type.equals("AWS")) {
management(API_OWNER, REGION, "apigateway").body("{}")
.put(method + "/responses/200").then().statusCode(201);
management(API_OWNER, REGION, "apigateway").body(Map.of("selectionPattern", ""))
.put(method + "/integration/responses/200").then().statusCode(201);
}
management(API_OWNER, REGION, "apigateway").body(Map.of("stageName", "prod"))
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
management(API_OWNER, REGION, "apigateway").body(Map.of(
"domainName", domain, "endpointConfiguration", Map.of("types", List.of("REGIONAL"))))
.post("/domainnames").then().statusCode(201);
cleanup.add(() -> management(API_OWNER, REGION, "apigateway")
.delete("/domainnames/" + domain).then().statusCode(202));
management(API_OWNER, REGION, "apigateway").body(Map.of("restApiId", apiId, "stage", "prod"))
.post("/domainnames/" + domain + "/basepathmappings").then().statusCode(201);
}
private String invoke(int expectedStatus) throws Exception {
return given().contentType(ContentType.JSON).header("Host", domain).headers(sign()).body(BODY).post("/")
.then().statusCode(expectedStatus).extract().asString();
}
private Map<String, String> sign() throws Exception {
return ExecuteApiRequestSigner.signedHeaders("POST", "/", Map.of(), domain, BODY,
callerKey.getAccessKeyId(), callerKey.getSecretAccessKey(), REGION, Instant.now());
}
private String arn(String account, String region) {
return "arn:aws:lambda:" + region + ":" + account + ":function:" + function;
}
private static RequestSpecification management(String account, String region, String service) {
return given().contentType(ContentType.JSON).header("Authorization",
"AWS4-HMAC-SHA256 Credential=" + account + "/20261012/" + region + "/" + service + "/aws4_request");
}
@AfterEach
void removeOwnedResources() {
assertAll("remove only this test graph", cleanup);
}
}
@@ -176,76 +176,80 @@ class LambdaArnUtilsTest {
return (s == null || s.isEmpty()) ? null : s;
}
// ──────────────────────────── extractFunctionNameFromUri tests ────────────────────────────
// ──────────────────────────── extractFunctionReferenceFromUri tests ────────────────────────────
@ParameterizedTest
@CsvSource({
// input URI, expected function name
"arn:aws:lambda:us-east-1:000000000000:function:myFn/invocations, myFn",
"arn:aws:lambda:us-east-1:000000000000:function:myFn, myFn",
"arn:aws:lambda:eu-west-1:123456789012:function:my-handler/invocations, my-handler",
"arn:aws:lambda:us-east-1:000000000000:function:my_fn-2/invocations, my_fn-2",
"arn:aws:lambda:us-east-1:000000000000:function:myFn/invocations, arn:aws:lambda:us-east-1:000000000000:function:myFn",
"arn:aws:lambda:us-east-1:000000000000:function:myFn, arn:aws:lambda:us-east-1:000000000000:function:myFn",
"arn:aws:lambda:eu-west-1:123456789012:function:my-handler/invocations, arn:aws:lambda:eu-west-1:123456789012:function:my-handler",
"arn:aws:lambda:us-east-1:000000000000:function:my_fn-2/invocations, arn:aws:lambda:us-east-1:000000000000:function:my_fn-2",
"myFn, myFn",
"my-handler, my-handler",
})
void extractFunctionNameFromUri_validInputs(String uri, String expectedName) {
assertEquals(expectedName, LambdaArnUtils.extractFunctionNameFromUri(uri));
void extractFunctionReferenceFromUri_validInputs(String uri, String expectedName) {
assertEquals(expectedName, LambdaArnUtils.extractFunctionReferenceFromUri(uri));
}
@Test
void extractFunctionNameFromUri_nullReturnsNull() {
assertNull(LambdaArnUtils.extractFunctionNameFromUri(null));
void extractFunctionReferenceFromUri_nullReturnsNull() {
assertNull(LambdaArnUtils.extractFunctionReferenceFromUri(null));
}
@Test
void extractFunctionNameFromUri_noFunctionPrefixReturnsFull() {
void extractFunctionReferenceFromUri_noFunctionPrefixReturnsFull() {
// When no "function:" prefix, the entire URI is treated as the function name
assertEquals("just-a-name", LambdaArnUtils.extractFunctionNameFromUri("just-a-name"));
assertEquals("just-a-name", LambdaArnUtils.extractFunctionReferenceFromUri("just-a-name"));
}
@Test
void extractFunctionNameFromUri_stripsInvocationsSuffix() {
void extractFunctionReferenceFromUri_stripsInvocationsSuffix() {
String uri = "arn:aws:lambda:us-east-1:000000000000:function:handler/invocations";
assertEquals("handler", LambdaArnUtils.extractFunctionNameFromUri(uri));
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:handler",
LambdaArnUtils.extractFunctionReferenceFromUri(uri));
}
@Test
void extractFunctionNameFromUri_handlesStageVariableSubstitutedUri() {
void extractFunctionReferenceFromUri_handlesStageVariableSubstitutedUri() {
// After stage variable substitution, the URI looks like a normal ARN
String uri = "arn:aws:lambda:us-east-1:000000000000:function:ws-stage-var-fn/invocations";
assertEquals("ws-stage-var-fn", LambdaArnUtils.extractFunctionNameFromUri(uri));
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:ws-stage-var-fn",
LambdaArnUtils.extractFunctionReferenceFromUri(uri));
}
@Test
void extractFunctionNameFromUri_handlesApiGatewayStyleUri() {
void extractFunctionReferenceFromUri_handlesApiGatewayStyleUri() {
// API Gateway v1 uses a longer URI format
String uri = "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:myFn/invocations";
assertEquals("myFn", LambdaArnUtils.extractFunctionNameFromUri(uri));
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:myFn",
LambdaArnUtils.extractFunctionReferenceFromUri(uri));
}
@ParameterizedTest
@CsvSource({
// Qualified targets (alias / numbered version) must preserve the :qualifier
// so downstream invoke resolves the configured target instead of $LATEST.
"arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD/invocations, myFn:PROD",
"arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD, myFn:PROD",
"arn:aws:lambda:us-east-1:000000000000:function:myFn:1/invocations, myFn:1",
"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD/invocations, myFn:PROD",
"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:myFn:42/invocations, myFn:42",
"arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD/invocations, arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD",
"arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD, arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD",
"arn:aws:lambda:us-east-1:000000000000:function:myFn:1/invocations, arn:aws:lambda:us-east-1:000000000000:function:myFn:1",
"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD/invocations, arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD",
"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:myFn:42/invocations, arn:aws:lambda:us-east-1:000000000000:function:myFn:42",
})
void extractFunctionNameFromUri_preservesQualifier(String uri, String expected) {
assertEquals(expected, LambdaArnUtils.extractFunctionNameFromUri(uri));
void extractFunctionReferenceFromUri_preservesQualifier(String uri, String expected) {
assertEquals(expected, LambdaArnUtils.extractFunctionReferenceFromUri(uri));
}
@Test
void extractFunctionNameFromUri_qualifiedRef_resolvesToNameAndQualifier() {
// The extracted "myFn:PROD" must resolve into a distinct name + qualifier,
// which is what invoke() relies on to target the alias/version.
String extracted = LambdaArnUtils.extractFunctionNameFromUri(
void extractFunctionReferenceFromUri_qualifiedRef_resolvesToNameAndQualifier() {
// The complete target identity survives extraction and Lambda validation.
String extracted = LambdaArnUtils.extractFunctionReferenceFromUri(
"arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD/invocations");
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(extracted);
assertEquals("myFn", ref.name());
assertEquals("PROD", ref.qualifier());
assertEquals("000000000000", ref.account());
assertEquals("us-east-1", ref.region());
}
@ParameterizedTest