mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
fix(lambda): resolve ARN and function URL invocations in owning account (#2414)
* fix(lambda): resolve ARN and function URL invocations in owning account * test(lambda): adapt account routing fixtures to layer service * fix(lambda): migrate legacy ARN invocation targets
This commit is contained in:
1 parent
06d58aad36
commit
c22652dd15
13 files changed
+698
-15
No files matched your search
+64
@@ -0,0 +1,64 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.lambda.LambdaClient;
|
||||
import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest;
|
||||
import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest;
|
||||
import software.amazon.awssdk.services.lambda.model.FunctionCode;
|
||||
import software.amazon.awssdk.services.lambda.model.InvocationType;
|
||||
import software.amazon.awssdk.services.lambda.model.InvokeRequest;
|
||||
import software.amazon.awssdk.services.lambda.model.Runtime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class LambdaAccountRoutingTest {
|
||||
|
||||
private static final String CALLER_ACCOUNT = "234567890123";
|
||||
private static final String TARGET_ACCOUNT = "345678901234";
|
||||
private static final Region REGION = Region.US_EAST_1;
|
||||
|
||||
@Test
|
||||
void invokeFullArnUsesTargetAccountWithDifferentCallerCredentials() {
|
||||
String functionName = TestFixtures.uniqueName("sdk-arn-account-routing");
|
||||
try (LambdaClient caller = client(CALLER_ACCOUNT);
|
||||
LambdaClient target = client(TARGET_ACCOUNT)) {
|
||||
target.createFunction(CreateFunctionRequest.builder()
|
||||
.functionName(functionName)
|
||||
.runtime(Runtime.NODEJS20_X)
|
||||
.role("arn:aws:iam::" + TARGET_ACCOUNT + ":role/lambda-role")
|
||||
.handler("index.handler")
|
||||
.code(FunctionCode.builder()
|
||||
.zipFile(SdkBytes.fromByteArray(LambdaUtils.minimalZip()))
|
||||
.build())
|
||||
.build());
|
||||
|
||||
try {
|
||||
String functionArn = "arn:aws:lambda:" + REGION.id() + ":" + TARGET_ACCOUNT
|
||||
+ ":function:" + functionName;
|
||||
assertThat(caller.invoke(InvokeRequest.builder()
|
||||
.functionName(functionArn)
|
||||
.invocationType(InvocationType.DRY_RUN)
|
||||
.payload(SdkBytes.fromUtf8String("{}"))
|
||||
.build())
|
||||
.statusCode()).isEqualTo(204);
|
||||
} finally {
|
||||
target.deleteFunction(DeleteFunctionRequest.builder()
|
||||
.functionName(functionName)
|
||||
.build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private LambdaClient client(String accountId) {
|
||||
return LambdaClient.builder()
|
||||
.endpointOverride(TestFixtures.endpoint())
|
||||
.region(REGION)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(
|
||||
AwsBasicCredentials.create(accountId, "test")))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+1
-3
@@ -89,9 +89,7 @@ public class EventBridgeInvoker {
|
||||
|
||||
try {
|
||||
if (arn.contains(":lambda:") || arn.contains(":function:")) {
|
||||
String fnName = arn.substring(arn.lastIndexOf(':') + 1);
|
||||
String fnRegion = extractRegionFromArn(arn, region);
|
||||
lambdaService.invoke(fnRegion, fnName, payload.getBytes(), InvocationType.Event);
|
||||
lambdaService.invokeArn(arn, payload.getBytes(), InvocationType.Event);
|
||||
LOG.debugv("EventBridge delivered to Lambda: {0}", arn);
|
||||
} else if (arn.contains(":sqs:")) {
|
||||
String queueUrl = AwsArnUtils.arnToQueueUrl(arn, baseUrl);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
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.lambda.model.LambdaAlias;
|
||||
@@ -31,7 +33,10 @@ public class LambdaAliasStore {
|
||||
}
|
||||
|
||||
private void loadIndex() {
|
||||
backend.scan(k -> true).forEach(this::indexAlias);
|
||||
List<LambdaAlias> all = backend instanceof AccountAwareStorageBackend<LambdaAlias> aware
|
||||
? aware.scanAllAccounts()
|
||||
: backend.scan(k -> true);
|
||||
all.forEach(this::indexAlias);
|
||||
}
|
||||
|
||||
private void indexAlias(LambdaAlias alias) {
|
||||
@@ -70,6 +75,17 @@ public class LambdaAliasStore {
|
||||
return backend.get(key(region, functionName, aliasName));
|
||||
}
|
||||
|
||||
public Optional<LambdaAlias> getForAccount(
|
||||
String accountId, String region, String functionName, String aliasName) {
|
||||
if (backend instanceof AccountAwareStorageBackend<LambdaAlias> aware) {
|
||||
return aware.getForAccountMigratingLegacy(
|
||||
accountId,
|
||||
key(region, functionName, aliasName),
|
||||
alias -> accountId.equals(AwsArnUtils.accountOrDefault(alias.getAliasArn(), "")));
|
||||
}
|
||||
return backend.get(key(region, functionName, aliasName));
|
||||
}
|
||||
|
||||
public Optional<LambdaAlias> getByUrlId(String urlId) {
|
||||
return Optional.ofNullable(urlIdIndex.get(urlId));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
@@ -90,10 +91,25 @@ public class LambdaFunctionStore implements Resettable {
|
||||
}
|
||||
|
||||
public Optional<LambdaFunction> getForAccount(String accountId, String region, String functionName) {
|
||||
return getForAccount(accountId, region, functionName, "$LATEST");
|
||||
}
|
||||
|
||||
public Optional<LambdaFunction> getForAccount(
|
||||
String accountId, String region, String functionName, String version) {
|
||||
if (backend instanceof AccountAwareStorageBackend<LambdaFunction> aware) {
|
||||
return aware.getForAccount(accountId, regionKey(region, functionName, "$LATEST"));
|
||||
return aware.getForAccountMigratingLegacy(
|
||||
accountId,
|
||||
regionKey(region, functionName, version),
|
||||
function -> belongsToAccount(function, accountId));
|
||||
}
|
||||
return backend.get(regionKey(region, functionName, "$LATEST"));
|
||||
return backend.get(regionKey(region, functionName, version));
|
||||
}
|
||||
|
||||
private static boolean belongsToAccount(LambdaFunction function, String accountId) {
|
||||
if (function.getAccountId() != null && !function.getAccountId().isBlank()) {
|
||||
return accountId.equals(function.getAccountId());
|
||||
}
|
||||
return accountId.equals(AwsArnUtils.accountOrDefault(function.getFunctionArn(), ""));
|
||||
}
|
||||
|
||||
public Optional<LambdaFunction> getByUrlId(String urlId) {
|
||||
|
||||
@@ -669,7 +669,24 @@ public class LambdaService {
|
||||
enforceRegion(region, ref);
|
||||
String name = ref.name();
|
||||
String qualifier = ref.qualifier();
|
||||
LambdaFunction fn = resolveInvokeTarget(region, name, qualifier);
|
||||
LambdaFunction fn;
|
||||
if (functionName.startsWith("arn:")) {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(functionName);
|
||||
fn = resolveInvokeTargetForAccount(arn.accountId(), region, name, qualifier);
|
||||
} else {
|
||||
fn = resolveInvokeTarget(region, name, qualifier);
|
||||
}
|
||||
InvokeResult result = executorService.invoke(fn, payload, type);
|
||||
result.setExecutedVersion(fn.getVersion());
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Invokes a Lambda target ARN using the account encoded in that ARN. */
|
||||
public InvokeResult invokeArn(String functionArn, byte[] payload, InvocationType type) {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(functionArn);
|
||||
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(functionArn);
|
||||
LambdaFunction fn = resolveInvokeTargetForAccount(
|
||||
arn.accountId(), arn.region(), ref.name(), ref.qualifier());
|
||||
InvokeResult result = executorService.invoke(fn, payload, type);
|
||||
result.setExecutedVersion(fn.getVersion());
|
||||
return result;
|
||||
@@ -697,6 +714,37 @@ public class LambdaService {
|
||||
"Function version not found: " + name + ":" + version, 404));
|
||||
}
|
||||
|
||||
private LambdaFunction resolveInvokeTargetForAccount(
|
||||
String accountId, String region, String name, String qualifier) {
|
||||
if (qualifier == null || qualifier.equals("$LATEST")) {
|
||||
return functionStore.getForAccount(accountId, region, name)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Function not found: " + name, 404));
|
||||
}
|
||||
if (qualifier.chars().allMatch(Character::isDigit)) {
|
||||
return functionStore.getForAccount(accountId, region, name, qualifier)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Function version not found: " + name + ":" + qualifier, 404));
|
||||
}
|
||||
LambdaAlias alias = aliasStore != null
|
||||
? aliasStore.getForAccount(accountId, region, name, qualifier)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Alias not found: " + qualifier, 404))
|
||||
: null;
|
||||
if (alias == null) {
|
||||
throw new AwsException("ResourceNotFoundException", "Alias not found: " + qualifier, 404);
|
||||
}
|
||||
String version = pickAliasVersion(alias);
|
||||
if (version == null || version.equals("$LATEST")) {
|
||||
return functionStore.getForAccount(accountId, region, name)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Function not found: " + name, 404));
|
||||
}
|
||||
return functionStore.getForAccount(accountId, region, name, version)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Function version not found: " + name + ":" + version, 404));
|
||||
}
|
||||
|
||||
private String pickAliasVersion(LambdaAlias alias) {
|
||||
java.util.Map<String, Double> weights = alias.getRoutingConfig();
|
||||
if (weights == null || weights.isEmpty()) {
|
||||
@@ -1240,7 +1288,12 @@ public class LambdaService {
|
||||
urlConfig.setInvokeMode((String) request.get("InvokeMode"));
|
||||
}
|
||||
|
||||
String urlId = UUID.nameUUIDFromBytes((region + functionName + (qualifier != null ? qualifier : "")).getBytes()).toString().replace("-", "").substring(0, 32);
|
||||
String accountId = regionResolver.getAccountId();
|
||||
String urlId = UUID.nameUUIDFromBytes(
|
||||
(accountId + region + functionName + (qualifier != null ? qualifier : "")).getBytes())
|
||||
.toString()
|
||||
.replace("-", "")
|
||||
.substring(0, 32);
|
||||
String baseHost = config.effectiveBaseUrl().replaceFirst("https?://", "");
|
||||
String url = String.format("http://%s.lambda-url.%s.%s/", urlId, region, baseHost);
|
||||
urlConfig.setFunctionUrl(url);
|
||||
|
||||
+19
-4
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.lambda;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
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.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaAlias;
|
||||
@@ -49,13 +50,15 @@ public class LambdaUrlInvocationController {
|
||||
private final LambdaService lambdaService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RequestContext requestContext;
|
||||
|
||||
@Inject
|
||||
public LambdaUrlInvocationController(LambdaService lambdaService, RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper) {
|
||||
ObjectMapper objectMapper, RequestContext requestContext) {
|
||||
this.lambdaService = lambdaService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
this.requestContext = requestContext;
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -96,25 +99,37 @@ public class LambdaUrlInvocationController {
|
||||
private Response invoke(String method, String urlId, String proxy, HttpHeaders headers, UriInfo uriInfo, byte[] body) {
|
||||
Object target = lambdaService.getTargetByUrlId(urlId);
|
||||
String functionName;
|
||||
String functionArn;
|
||||
String region;
|
||||
String accountId;
|
||||
|
||||
if (target instanceof LambdaAlias alias) {
|
||||
functionName = alias.getFunctionName();
|
||||
region = AwsArnUtils.parse(alias.getAliasArn()).region();
|
||||
functionArn = alias.getAliasArn();
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(functionArn);
|
||||
region = arn.region();
|
||||
accountId = arn.accountId();
|
||||
} else if (target instanceof LambdaFunction fn) {
|
||||
functionName = fn.getFunctionName();
|
||||
region = AwsArnUtils.parse(fn.getFunctionArn()).region();
|
||||
functionArn = fn.getFunctionArn();
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(functionArn);
|
||||
region = arn.region();
|
||||
accountId = fn.getAccountId() != null ? fn.getAccountId() : arn.accountId();
|
||||
} else {
|
||||
return Response.status(404).entity(jsonMessage("Function URL not found")).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
requestContext.setAccountId(accountId);
|
||||
requestContext.setRegion(region);
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String event = buildEvent(method, urlId, proxy, headers, uriInfo, body, requestId, region);
|
||||
|
||||
LOG.infov("Lambda URL invocation: {0} {1} -> {2} (region: {3})", method, urlId, functionName, region);
|
||||
|
||||
try {
|
||||
InvokeResult result = lambdaService.invoke(region, functionName, event.getBytes(), InvocationType.RequestResponse);
|
||||
InvokeResult result = lambdaService.invokeArn(
|
||||
functionArn, event.getBytes(), InvocationType.RequestResponse);
|
||||
return buildResponse(result);
|
||||
} catch (AwsException e) {
|
||||
return Response.status(e.getHttpStatus()).entity(e.getMessage()).build();
|
||||
|
||||
@@ -87,8 +87,7 @@ public class ScheduleInvoker {
|
||||
sqsService.sendMessage(queueUrl, payload, 0, messageGroupId, null, targetRegion);
|
||||
LOG.debugv("Scheduler delivered to SQS: {0}", arn);
|
||||
} else if (arn.contains(":lambda:") || arn.contains(":function:")) {
|
||||
String fnName = arn.substring(arn.lastIndexOf(':') + 1);
|
||||
lambdaService.invoke(targetRegion, fnName, payload.getBytes(), InvocationType.Event);
|
||||
lambdaService.invokeArn(arn, payload.getBytes(), InvocationType.Event);
|
||||
LOG.debugv("Scheduler delivered to Lambda: {0}", arn);
|
||||
} else if (arn.contains(":sns:")) {
|
||||
snsService.publish(arn, null, payload, "Scheduler", targetRegion);
|
||||
|
||||
+16
-1
@@ -22,12 +22,14 @@ import java.util.Map;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.AdditionalMatchers.aryEq;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class EventBridgeInvokerTest {
|
||||
|
||||
private EventBridgeInvoker invoker;
|
||||
private LambdaService lambdaService;
|
||||
private SqsService sqsService;
|
||||
private BatchService batchService;
|
||||
private FirehoseService firehoseService;
|
||||
@@ -36,7 +38,7 @@ class EventBridgeInvokerTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
LambdaService lambdaService = mock(LambdaService.class);
|
||||
lambdaService = mock(LambdaService.class);
|
||||
sqsService = mock(SqsService.class);
|
||||
SnsService snsService = mock(SnsService.class);
|
||||
batchService = mock(BatchService.class);
|
||||
@@ -59,6 +61,19 @@ class EventBridgeInvokerTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_lambdaTargetPreservesArnAccount() {
|
||||
String arn = "arn:aws:lambda:ap-south-1:100000000012:function:cross-account-function";
|
||||
Target target = new Target("id1", arn, "{\"detail\":{\"job\":\"workflow-recovery\"}}", null);
|
||||
|
||||
invoker.invokeTarget(target, "{\"ignored\":true}", "ap-south-1");
|
||||
|
||||
verify(lambdaService).invokeArn(
|
||||
eq(arn),
|
||||
aryEq("{\"detail\":{\"job\":\"workflow-recovery\"}}".getBytes()),
|
||||
eq(io.github.hectorvent.floci.services.lambda.model.InvocationType.Event));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_sqsTarget_usesSuppliedRegion() {
|
||||
Target target = new Target("id1", "arn:aws:sqs:eu-west-1:000000000000:my-queue", null, null);
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
@QuarkusTest
|
||||
class LambdaArnInvocationAccountIntegrationTest {
|
||||
|
||||
private static final String CALLER_ACCOUNT = "234567890123";
|
||||
private static final String TARGET_ACCOUNT = "345678901234";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String FUNCTION_NAME = "arn-invocation-account-routing";
|
||||
|
||||
@Test
|
||||
void fullArnInvocationUsesArnAccountInsteadOfCallerAccount() {
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.header("Authorization", authorization(TARGET_ACCOUNT))
|
||||
.body("""
|
||||
{
|
||||
"FunctionName":"%s",
|
||||
"Runtime":"nodejs20.x",
|
||||
"Role":"arn:aws:iam::%s:role/lambda-role",
|
||||
"Handler":"index.handler"
|
||||
}
|
||||
""".formatted(FUNCTION_NAME, TARGET_ACCOUNT))
|
||||
.when().post("/2015-03-31/functions")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
|
||||
String functionArn = "arn:aws:lambda:" + REGION + ":" + TARGET_ACCOUNT
|
||||
+ ":function:" + FUNCTION_NAME;
|
||||
|
||||
given()
|
||||
.header("Authorization", authorization(CALLER_ACCOUNT))
|
||||
.header("X-Amz-Invocation-Type", "DryRun")
|
||||
.contentType("application/json")
|
||||
.body("{}")
|
||||
.when().post("/2015-03-31/functions/{functionArn}/invocations", functionArn)
|
||||
.then()
|
||||
.statusCode(204)
|
||||
.header("X-Amz-Executed-Version", equalTo("$LATEST"));
|
||||
}
|
||||
|
||||
private String authorization(String accountId) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accountId
|
||||
+ "/20260812/" + REGION + "/lambda/aws4_request";
|
||||
}
|
||||
}
|
||||
+267
@@ -0,0 +1,267 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
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.InMemoryStorage;
|
||||
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.LambdaAlias;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.github.hectorvent.floci.services.lambda.zip.CodeStore;
|
||||
import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.AdditionalMatchers.aryEq;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class LambdaArnInvocationAccountTest {
|
||||
|
||||
@Test
|
||||
void invokeArnResolvesFunctionFromArnAccountOutsideRequestContext() {
|
||||
String defaultAccount = "000000000000";
|
||||
String targetAccount = "100000000012";
|
||||
String region = "ap-south-1";
|
||||
String functionName = "cross-account-function";
|
||||
String functionArn = "arn:aws:lambda:" + region + ":" + targetAccount
|
||||
+ ":function:" + functionName;
|
||||
|
||||
AccountAwareStorageBackend<LambdaFunction> backend = new AccountAwareStorageBackend<>(
|
||||
new InMemoryStorage<>(), null, defaultAccount);
|
||||
LambdaFunctionStore store = new LambdaFunctionStore(backend);
|
||||
LambdaFunction function = new LambdaFunction();
|
||||
function.setAccountId(targetAccount);
|
||||
function.setFunctionName(functionName);
|
||||
function.setFunctionArn(functionArn);
|
||||
function.setVersion("$LATEST");
|
||||
backend.putForAccount(targetAccount,
|
||||
"lambda::" + region + "::" + functionName + "::$LATEST", function);
|
||||
|
||||
LambdaExecutorService executor = mock(LambdaExecutorService.class);
|
||||
InvokeResult executorResult = new InvokeResult();
|
||||
when(executor.invoke(eq(function), aryEq("{}".getBytes()), eq(InvocationType.Event)))
|
||||
.thenReturn(executorResult);
|
||||
LambdaService service = new LambdaService(
|
||||
store,
|
||||
executor,
|
||||
new LambdaConcurrencyLimiter(),
|
||||
new WarmPool(),
|
||||
new CodeStore(Path.of("target/test-data/lambda-code")),
|
||||
new ZipExtractor(),
|
||||
null,
|
||||
new RegionResolver(region, defaultAccount),
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
InvokeResult result = service.invokeArn(functionArn, "{}".getBytes(), InvocationType.Event);
|
||||
|
||||
assertEquals("$LATEST", result.getExecutedVersion());
|
||||
verify(executor).invoke(eq(function), aryEq("{}".getBytes()), eq(InvocationType.Event));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeArnResolvesVersionAndAliasFromArnAccount() {
|
||||
String defaultAccount = "000000000000";
|
||||
String targetAccount = "100000000012";
|
||||
String region = "ap-south-1";
|
||||
String functionName = "versioned-account-function";
|
||||
String functionArn = "arn:aws:lambda:" + region + ":" + targetAccount
|
||||
+ ":function:" + functionName;
|
||||
|
||||
AccountAwareStorageBackend<LambdaFunction> functionBackend = new AccountAwareStorageBackend<>(
|
||||
new InMemoryStorage<>(), null, defaultAccount);
|
||||
LambdaFunctionStore functionStore = new LambdaFunctionStore(functionBackend);
|
||||
LambdaFunction version = new LambdaFunction();
|
||||
version.setAccountId(targetAccount);
|
||||
version.setFunctionName(functionName);
|
||||
version.setFunctionArn(functionArn + ":7");
|
||||
version.setVersion("7");
|
||||
functionBackend.putForAccount(targetAccount,
|
||||
"lambda::" + region + "::" + functionName + "::7", version);
|
||||
|
||||
AccountAwareStorageBackend<LambdaAlias> aliasBackend = new AccountAwareStorageBackend<>(
|
||||
new InMemoryStorage<>(), null, defaultAccount);
|
||||
LambdaAliasStore aliasStore = new LambdaAliasStore(aliasBackend);
|
||||
LambdaAlias alias = new LambdaAlias();
|
||||
alias.setName("live");
|
||||
alias.setFunctionName(functionName);
|
||||
alias.setFunctionVersion("7");
|
||||
alias.setAliasArn(functionArn + ":live");
|
||||
aliasBackend.putForAccount(targetAccount,
|
||||
"alias::" + region + "::" + functionName + "::live", alias);
|
||||
|
||||
LambdaExecutorService executor = mock(LambdaExecutorService.class);
|
||||
when(executor.invoke(eq(version), aryEq("{}".getBytes()), eq(InvocationType.Event)))
|
||||
.thenAnswer(ignored -> new InvokeResult());
|
||||
LambdaService service = new LambdaService(
|
||||
functionStore,
|
||||
executor,
|
||||
new LambdaConcurrencyLimiter(),
|
||||
new WarmPool(),
|
||||
new CodeStore(Path.of("target/test-data/lambda-code")),
|
||||
new ZipExtractor(),
|
||||
null,
|
||||
new RegionResolver(region, defaultAccount),
|
||||
null,
|
||||
aliasStore,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
InvokeResult versionResult = service.invokeArn(
|
||||
functionArn + ":7", "{}".getBytes(), InvocationType.Event);
|
||||
InvokeResult aliasResult = service.invokeArn(
|
||||
functionArn + ":live", "{}".getBytes(), InvocationType.Event);
|
||||
|
||||
assertEquals("7", versionResult.getExecutedVersion());
|
||||
assertEquals("7", aliasResult.getExecutedVersion());
|
||||
verify(executor, org.mockito.Mockito.times(2))
|
||||
.invoke(eq(version), aryEq("{}".getBytes()), eq(InvocationType.Event));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeArnMigratesOwnedLegacyFunctionVersionAndAlias() {
|
||||
String defaultAccount = "000000000000";
|
||||
String targetAccount = "100000000012";
|
||||
String region = "ap-south-1";
|
||||
String functionName = "legacy-account-function";
|
||||
String functionArn = "arn:aws:lambda:" + region + ":" + targetAccount
|
||||
+ ":function:" + functionName;
|
||||
String latestKey = "lambda::" + region + "::" + functionName + "::$LATEST";
|
||||
String versionKey = "lambda::" + region + "::" + functionName + "::7";
|
||||
String aliasKey = "alias::" + region + "::" + functionName + "::live";
|
||||
|
||||
InMemoryStorage<String, LambdaFunction> rawFunctions = new InMemoryStorage<>();
|
||||
LambdaFunction latest = function(functionName, functionArn, "$LATEST");
|
||||
LambdaFunction version = function(functionName, functionArn + ":7", "7");
|
||||
rawFunctions.put(latestKey, latest);
|
||||
rawFunctions.put(versionKey, version);
|
||||
LambdaFunctionStore functionStore = new LambdaFunctionStore(
|
||||
new AccountAwareStorageBackend<>(rawFunctions, null, defaultAccount));
|
||||
|
||||
InMemoryStorage<String, LambdaAlias> rawAliases = new InMemoryStorage<>();
|
||||
LambdaAlias alias = new LambdaAlias();
|
||||
alias.setName("live");
|
||||
alias.setFunctionName(functionName);
|
||||
alias.setFunctionVersion("7");
|
||||
alias.setAliasArn(functionArn + ":live");
|
||||
rawAliases.put(aliasKey, alias);
|
||||
LambdaAliasStore aliasStore = new LambdaAliasStore(
|
||||
new AccountAwareStorageBackend<>(rawAliases, null, defaultAccount));
|
||||
|
||||
LambdaExecutorService executor = mock(LambdaExecutorService.class);
|
||||
when(executor.invoke(eq(latest), aryEq("{}".getBytes()), eq(InvocationType.Event)))
|
||||
.thenAnswer(ignored -> new InvokeResult());
|
||||
when(executor.invoke(eq(version), aryEq("{}".getBytes()), eq(InvocationType.Event)))
|
||||
.thenAnswer(ignored -> new InvokeResult());
|
||||
LambdaService service = service(functionStore, aliasStore, executor, region, defaultAccount);
|
||||
|
||||
service.invokeArn(functionArn, "{}".getBytes(), InvocationType.Event);
|
||||
service.invokeArn(functionArn + ":7", "{}".getBytes(), InvocationType.Event);
|
||||
service.invokeArn(functionArn + ":live", "{}".getBytes(), InvocationType.Event);
|
||||
|
||||
assertTrue(rawFunctions.get(latestKey).isEmpty());
|
||||
assertTrue(rawFunctions.get(versionKey).isEmpty());
|
||||
assertEquals(latest, rawFunctions.get(targetAccount + "/" + latestKey).orElseThrow());
|
||||
assertEquals(version, rawFunctions.get(targetAccount + "/" + versionKey).orElseThrow());
|
||||
assertTrue(rawAliases.get(aliasKey).isEmpty());
|
||||
assertEquals(alias, rawAliases.get(targetAccount + "/" + aliasKey).orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeArnDoesNotMigrateForeignLegacyFunctionOrAlias() {
|
||||
String defaultAccount = "000000000000";
|
||||
String targetAccount = "100000000012";
|
||||
String foreignAccount = "200000000034";
|
||||
String region = "ap-south-1";
|
||||
String functionName = "legacy-account-function";
|
||||
String targetArn = "arn:aws:lambda:" + region + ":" + targetAccount
|
||||
+ ":function:" + functionName;
|
||||
String functionKey = "lambda::" + region + "::" + functionName + "::$LATEST";
|
||||
|
||||
InMemoryStorage<String, LambdaFunction> rawFunctions = new InMemoryStorage<>();
|
||||
LambdaFunction foreignFunction = function(
|
||||
functionName,
|
||||
"arn:aws:lambda:" + region + ":" + foreignAccount + ":function:" + functionName,
|
||||
"$LATEST");
|
||||
rawFunctions.put(functionKey, foreignFunction);
|
||||
LambdaFunctionStore functionStore = new LambdaFunctionStore(
|
||||
new AccountAwareStorageBackend<>(rawFunctions, null, defaultAccount));
|
||||
|
||||
String aliasKey = "alias::" + region + "::" + functionName + "::live";
|
||||
InMemoryStorage<String, LambdaAlias> rawAliases = new InMemoryStorage<>();
|
||||
LambdaAlias foreignAlias = new LambdaAlias();
|
||||
foreignAlias.setName("live");
|
||||
foreignAlias.setFunctionName(functionName);
|
||||
foreignAlias.setFunctionVersion("7");
|
||||
foreignAlias.setAliasArn(
|
||||
"arn:aws:lambda:" + region + ":" + foreignAccount + ":function:" + functionName + ":live");
|
||||
rawAliases.put(aliasKey, foreignAlias);
|
||||
LambdaAliasStore aliasStore = new LambdaAliasStore(
|
||||
new AccountAwareStorageBackend<>(rawAliases, null, defaultAccount));
|
||||
LambdaService service = service(
|
||||
functionStore, aliasStore, mock(LambdaExecutorService.class), region, defaultAccount);
|
||||
|
||||
assertThrows(AwsException.class,
|
||||
() -> service.invokeArn(targetArn, "{}".getBytes(), InvocationType.Event));
|
||||
assertThrows(AwsException.class,
|
||||
() -> service.invokeArn(targetArn + ":live", "{}".getBytes(), InvocationType.Event));
|
||||
assertEquals(foreignFunction, rawFunctions.get(functionKey).orElseThrow());
|
||||
assertTrue(rawFunctions.get(targetAccount + "/" + functionKey).isEmpty());
|
||||
assertEquals(foreignAlias, rawAliases.get(aliasKey).orElseThrow());
|
||||
assertTrue(rawAliases.get(targetAccount + "/" + aliasKey).isEmpty());
|
||||
}
|
||||
|
||||
private static LambdaFunction function(String functionName, String functionArn, String version) {
|
||||
LambdaFunction function = new LambdaFunction();
|
||||
function.setFunctionName(functionName);
|
||||
function.setFunctionArn(functionArn);
|
||||
function.setVersion(version);
|
||||
return function;
|
||||
}
|
||||
|
||||
private static LambdaService service(
|
||||
LambdaFunctionStore functionStore,
|
||||
LambdaAliasStore aliasStore,
|
||||
LambdaExecutorService executor,
|
||||
String region,
|
||||
String defaultAccount) {
|
||||
return new LambdaService(
|
||||
functionStore,
|
||||
executor,
|
||||
new LambdaConcurrencyLimiter(),
|
||||
new WarmPool(),
|
||||
new CodeStore(Path.of("target/test-data/lambda-code")),
|
||||
new ZipExtractor(),
|
||||
null,
|
||||
new RegionResolver(region, defaultAccount),
|
||||
null,
|
||||
aliasStore,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
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.assertNotEquals;
|
||||
|
||||
@QuarkusTest
|
||||
class LambdaFunctionUrlAccountRoutingTest {
|
||||
|
||||
private static final String ACCOUNT_A = "345678901234";
|
||||
private static final String ACCOUNT_B = "456789012345";
|
||||
private static final String FUNCTION_NAME = "function-url-multi-account";
|
||||
|
||||
@Test
|
||||
void functionUrlIdsAndInvocationsAreAccountScoped() throws Exception {
|
||||
String urlA = createFunctionUrl(ACCOUNT_A);
|
||||
String urlB = createFunctionUrl(ACCOUNT_B);
|
||||
|
||||
assertNotEquals(urlA, urlB);
|
||||
|
||||
given()
|
||||
.when().get("/lambda-url/" + urlId(urlA) + "/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("accountId", equalTo(ACCOUNT_A));
|
||||
|
||||
given()
|
||||
.when().get("/lambda-url/" + urlId(urlB) + "/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("accountId", equalTo(ACCOUNT_B));
|
||||
}
|
||||
|
||||
private String createFunctionUrl(String accountId) throws Exception {
|
||||
String authorization = authorization(accountId, "lambda");
|
||||
String zip = Base64.getEncoder().encodeToString(lambdaZip());
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.header("Authorization", authorization)
|
||||
.body("""
|
||||
{
|
||||
"FunctionName":"%s",
|
||||
"Runtime":"nodejs20.x",
|
||||
"Role":"arn:aws:iam::%s:role/lambda-role",
|
||||
"Handler":"index.handler",
|
||||
"Code":{"ZipFile":"%s"}
|
||||
}
|
||||
""".formatted(FUNCTION_NAME, accountId, zip))
|
||||
.when().post("/2015-03-31/functions")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
|
||||
return given()
|
||||
.contentType("application/json")
|
||||
.header("Authorization", authorization)
|
||||
.body("""
|
||||
{"AuthType":"NONE"}
|
||||
""")
|
||||
.when().post("/2021-10-31/functions/" + FUNCTION_NAME + "/url")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract().path("FunctionUrl");
|
||||
}
|
||||
|
||||
private byte[] lambdaZip() throws Exception {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
|
||||
zip.putNextEntry(new ZipEntry("index.js"));
|
||||
zip.write("""
|
||||
exports.handler = async (event) => ({
|
||||
statusCode: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ accountId: event.requestContext.accountId })
|
||||
});
|
||||
""".getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
}
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
|
||||
private String urlId(String functionUrl) {
|
||||
int scheme = functionUrl.indexOf("://");
|
||||
int firstDot = functionUrl.indexOf('.', scheme + 3);
|
||||
return functionUrl.substring(scheme + 3, firstDot);
|
||||
}
|
||||
|
||||
private String authorization(String accountId, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accountId
|
||||
+ "/20260803/us-east-1/" + service + "/aws4_request";
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
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.LambdaAlias;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
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.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class LambdaUrlInvocationControllerTest {
|
||||
|
||||
@Test
|
||||
void aliasUrlInvokesOwningAccountAliasArn() {
|
||||
String accountId = "100000000012";
|
||||
String region = "ap-south-1";
|
||||
String aliasArn = "arn:aws:lambda:" + region + ":" + accountId
|
||||
+ ":function:account-function:live";
|
||||
LambdaAlias alias = new LambdaAlias();
|
||||
alias.setFunctionName("account-function");
|
||||
alias.setName("live");
|
||||
alias.setAliasArn(aliasArn);
|
||||
|
||||
LambdaService lambdaService = mock(LambdaService.class);
|
||||
when(lambdaService.getTargetByUrlId("url-id")).thenReturn(alias);
|
||||
InvokeResult invokeResult = new InvokeResult();
|
||||
invokeResult.setStatusCode(200);
|
||||
invokeResult.setPayload("{\"statusCode\":200,\"body\":\"ok\"}"
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
when(lambdaService.invokeArn(eq(aliasArn), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(invokeResult);
|
||||
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn(accountId);
|
||||
RequestContext requestContext = new RequestContext();
|
||||
LambdaUrlInvocationController controller = new LambdaUrlInvocationController(
|
||||
lambdaService, regionResolver, new ObjectMapper(), requestContext);
|
||||
|
||||
HttpHeaders headers = mock(HttpHeaders.class);
|
||||
when(headers.getRequestHeaders()).thenReturn(new MultivaluedHashMap<>());
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost/lambda-url/url-id/"));
|
||||
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
|
||||
Response response = controller.handleGet("url-id", "", headers, uriInfo);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(accountId, requestContext.getAccountId());
|
||||
assertEquals(region, requestContext.getRegion());
|
||||
ArgumentCaptor<byte[]> event = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService).invokeArn(eq(aliasArn), event.capture(), eq(InvocationType.RequestResponse));
|
||||
assertTrue(new String(event.getValue(), StandardCharsets.UTF_8)
|
||||
.contains("\"accountId\":\"" + accountId + "\""));
|
||||
}
|
||||
}
|
||||
@@ -169,6 +169,22 @@ class ScheduleInvokerTest {
|
||||
eq("group-7"), isNull(), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lambdaTargetPreservesArnAccount() {
|
||||
String arn = "arn:aws:lambda:ap-south-1:100000000012:function:cross-account-function";
|
||||
Target target = new Target();
|
||||
target.setArn(arn);
|
||||
target.setInput("{\"detail\":{\"job\":\"workflow-recovery\"}}");
|
||||
|
||||
invoker.invoke(target, "ap-south-1");
|
||||
|
||||
verify(lambdaService).invokeArn(
|
||||
eq(arn),
|
||||
org.mockito.AdditionalMatchers.aryEq(
|
||||
"{\"detail\":{\"job\":\"workflow-recovery\"}}".getBytes()),
|
||||
eq(io.github.hectorvent.floci.services.lambda.model.InvocationType.Event));
|
||||
}
|
||||
|
||||
@Test
|
||||
void directSnsTopicArnStillDelivers() {
|
||||
Target target = new Target();
|
||||
|
||||
Reference in new issue
Block a user