mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
fix(lambda): give resource-tag conditions the tags of the Lambda resource a request names (#8569)
The generated request resources give Lambda's function, function version and alias, event source mapping, web function, revision and endpoint, MicroVM image and network connector types aws:ResourceTag/ keys, but LambdaStoredResourceArns did not answer storedTags, so a condition on their tags saw none. It now answers from the service holding each: LambdaService for a function, whose versions and aliases have its tags as Lambda keeps tags on the function alone, and an event source mapping; LambdaWebService for a web function, whose revisions and endpoints inherit its tags; LambdaMicrovmsService for an image or a connector. Each reads the resource under the ARN in the account and Region it names, a pre-multi-account one of the default account in place, through the new AccountAwareStorageBackend.readInAccount, matched on the whole ARN. Tagging a function or a mapping now puts a new tag map in place of the old one, so the lookup always copies one whole set.
This commit is contained in:
1 parent
08479ffffe
commit
b2a019ef4e
17 files changed
+457
-20
No files matched your search
@@ -3119,8 +3119,10 @@ floci populates:
|
||||
reads from the Service Reference for every namespace it reads, valued from the tags the type's service
|
||||
holds on that resource (`StoredResourceArns.storedTags`); a service that holds none leaves them absent.
|
||||
Secrets Manager answers for its secrets, S3 Tables for its table buckets and tables, EventBridge Scheduler for
|
||||
its schedule groups, and CloudFormation for its stacks, stack sets and change sets. Tag keys differing only in
|
||||
case are one condition key holding every value.
|
||||
its schedule groups, CloudFormation for its stacks, stack sets and change sets, and Lambda for its functions,
|
||||
their versions and aliases (the function's tags), event source mappings, web functions, their revisions and
|
||||
endpoints (the web function's tags), MicroVM images and network connectors. Tag keys differing only in case are
|
||||
one condition key holding every value.
|
||||
- EC2 resource keys such as a network interface's `ec2:Vpc`, `ec2:Subnet`, `ec2:AvailabilityZone` and
|
||||
`ec2:NetworkInterfaceID`: for every action on a resource EC2 holds, the members of the resource the
|
||||
key names, an ARN for a key the Service Reference types as one. `resourceKeys` in
|
||||
|
||||
@@ -28,7 +28,9 @@ import java.util.Optional;
|
||||
* random suffix included, and its tags; EventBridge Scheduler, for its default schedule group and its groups' tags;
|
||||
* CloudFormation, for the stack or the stack set a name names, whose id it minted, and the tags of a stack, a stack set
|
||||
* or a change set; S3 Tables, for the table a request names by its table bucket, namespace and name, and the tags of a
|
||||
* table bucket or a table); looked up lazily by {@code ResourceArnBuilder} and {@code IamConditionContextResolver}
|
||||
* table bucket or a table; Lambda, for the layer version a layer version ARN selects, the image of a MicroVM and the
|
||||
* execution of a callback, and the tags of a function, an event source mapping, a web function, a MicroVM image or a
|
||||
* network connector); looked up lazily by {@code ResourceArnBuilder} and {@code IamConditionContextResolver}
|
||||
* through {@code Instance<StoredResourceArns>} for the namespace a request or an ARN is of, so IAM never depends on
|
||||
* that service directly.</p>
|
||||
*
|
||||
|
||||
@@ -84,6 +84,18 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
|
||||
return store.get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* As {@link #getInAccount}, also finding a pre-multi-account entry of the default account, read in place
|
||||
* ({@link #getLegacyForAccount}), for a lookup that must leave the store as it is, as IAM's reads of a
|
||||
* resource's tags must.
|
||||
*/
|
||||
public static <V> Optional<V> readInAccount(StorageBackend<String, V> store, String accountId, String key) {
|
||||
if (accountId != null && store instanceof AccountAwareStorageBackend<V> aware) {
|
||||
return aware.getForAccount(accountId, key).or(() -> aware.getLegacyForAccount(accountId, key));
|
||||
}
|
||||
return store.get(key);
|
||||
}
|
||||
|
||||
/** Writes {@code value} in {@code accountId}; the counterpart of {@link #getInAccount}. */
|
||||
public static <V> void putInAccount(StorageBackend<String, V> store, String accountId, String key, V value) {
|
||||
if (accountId != null && store instanceof AccountAwareStorageBackend<V> aware) {
|
||||
|
||||
@@ -65,6 +65,11 @@ public class EsmStore {
|
||||
return backend.get(uuid);
|
||||
}
|
||||
|
||||
/** As {@link #getForAccount}, also reading a pre-multi-account mapping of the default account in place. */
|
||||
public Optional<EventSourceMapping> readForAccount(String accountId, String uuid) {
|
||||
return AccountAwareStorageBackend.readInAccount(backend, accountId, uuid);
|
||||
}
|
||||
|
||||
public List<EventSourceMapping> listByFunction(String functionKey) {
|
||||
return backend.scan(k -> {
|
||||
EventSourceMapping esm = backend.get(k).orElse(null);
|
||||
|
||||
@@ -86,6 +86,12 @@ public class LambdaAliasStore {
|
||||
return backend.get(key(region, functionName, aliasName));
|
||||
}
|
||||
|
||||
/** As {@link #getForAccount}, reading a pre-multi-account alias in place instead of moving it. */
|
||||
public Optional<LambdaAlias> readForAccount(
|
||||
String accountId, String region, String functionName, String aliasName) {
|
||||
return AccountAwareStorageBackend.readInAccount(backend, accountId, key(region, functionName, aliasName));
|
||||
}
|
||||
|
||||
public Optional<LambdaAlias> getByUrlId(String urlId) {
|
||||
return Optional.ofNullable(urlIdIndex.get(urlId));
|
||||
}
|
||||
|
||||
@@ -130,6 +130,12 @@ public class LambdaFunctionStore implements Resettable {
|
||||
return backend.get(regionKey(region, functionName, version));
|
||||
}
|
||||
|
||||
/** As {@link #getForAccount}, reading a pre-multi-account record in place instead of moving it. */
|
||||
public Optional<LambdaFunction> readForAccount(
|
||||
String accountId, String region, String functionName, String version) {
|
||||
return AccountAwareStorageBackend.readInAccount(backend, accountId, regionKey(region, functionName, version));
|
||||
}
|
||||
|
||||
private static boolean belongsToAccount(LambdaFunction function, String accountId) {
|
||||
if (function.getAccountId() != null && !function.getAccountId().isBlank()) {
|
||||
return accountId.equals(function.getAccountId());
|
||||
|
||||
@@ -4297,14 +4297,17 @@ public class LambdaService implements ResourceProvider {
|
||||
validateTagKeys(tags);
|
||||
EventSourceMapping esm = taggedEventSourceMapping(functionArn);
|
||||
if (esm != null) {
|
||||
esm.getTags().putAll(tags);
|
||||
synchronized (esm) {
|
||||
esm.setTags(withTags(esm.getTags(), tags));
|
||||
}
|
||||
esmStore.save(esm);
|
||||
return;
|
||||
}
|
||||
TagTarget target = resolveTagTarget(functionArn);
|
||||
LambdaFunction fn = getFunction(target.region, target.name);
|
||||
if (fn.getTags() == null) fn.setTags(new HashMap<>());
|
||||
fn.getTags().putAll(tags);
|
||||
synchronized (fn) {
|
||||
fn.setTags(withTags(fn.getTags(), tags));
|
||||
}
|
||||
functionStore.save(target.region, fn);
|
||||
}
|
||||
|
||||
@@ -4331,18 +4334,78 @@ public class LambdaService implements ResourceProvider {
|
||||
public void untagResource(String functionArn, List<String> tagKeys) {
|
||||
EventSourceMapping esm = taggedEventSourceMapping(functionArn);
|
||||
if (esm != null) {
|
||||
tagKeys.forEach(esm.getTags()::remove);
|
||||
synchronized (esm) {
|
||||
esm.setTags(withoutTags(esm.getTags(), tagKeys));
|
||||
}
|
||||
esmStore.save(esm);
|
||||
return;
|
||||
}
|
||||
TagTarget target = resolveTagTarget(functionArn);
|
||||
LambdaFunction fn = getFunction(target.region, target.name);
|
||||
if (fn.getTags() != null) {
|
||||
tagKeys.forEach(fn.getTags()::remove);
|
||||
synchronized (fn) {
|
||||
fn.setTags(withoutTags(fn.getTags(), tagKeys));
|
||||
}
|
||||
functionStore.save(target.region, fn);
|
||||
}
|
||||
|
||||
/**
|
||||
* A new tag map of {@code current} with {@code added} put in it. A resource's tags are replaced, never changed in
|
||||
* place, so a reader copying them, as {@link #storedTags} does on every request IAM checks, sees one whole set.
|
||||
*/
|
||||
private static Map<String, String> withTags(Map<String, String> current, Map<String, String> added) {
|
||||
Map<String, String> next = current == null ? new HashMap<>() : new HashMap<>(current);
|
||||
next.putAll(added);
|
||||
return next;
|
||||
}
|
||||
|
||||
/** A new tag map of {@code current} without {@code keys}, as {@link #withTags} gives one. */
|
||||
private static Map<String, String> withoutTags(Map<String, String> current, List<String> keys) {
|
||||
Map<String, String> next = current == null ? new HashMap<>() : new HashMap<>(current);
|
||||
keys.forEach(next::remove);
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags of the function, or the event source mapping, stored under {@code arn} in the account and Region it
|
||||
* names, matched on the whole ARN and left as they are; a version or alias ARN has its function's, as Lambda keeps
|
||||
* tags on the function alone. Empty for an ARN naming nothing stored, or any other Lambda resource.
|
||||
*/
|
||||
public Map<String, String> storedTags(String arn) {
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
String uuid = LambdaArnUtils.eventSourceMappingUuid(parsed);
|
||||
if (uuid != null) {
|
||||
return esmStore == null ? Map.of() : esmStore.readForAccount(parsed.accountId(), uuid)
|
||||
.filter(esm -> arn.equals(LambdaArnUtils.eventSourceMappingArn(
|
||||
esm.getRegion(), esm.getAccountId(), esm.getUuid())))
|
||||
.map(esm -> Map.copyOf(esm.getTags()))
|
||||
.orElse(Map.of());
|
||||
}
|
||||
String[] function = parsed.resource().split(":", -1);
|
||||
if (function.length < 2 || function.length > 3 || !"function".equals(function[0])
|
||||
|| parsed.resource().contains("/")) {
|
||||
return Map.of();
|
||||
}
|
||||
String qualifier = function.length == 3 ? function[2] : null;
|
||||
return functionStore.readForAccount(parsed.accountId(), parsed.region(), function[1], "$LATEST")
|
||||
.filter(fn -> arn.equals(qualifier == null ? fn.getFunctionArn()
|
||||
: fn.getFunctionArn() + ":" + qualifier))
|
||||
.filter(fn -> qualifier == null || holdsQualifier(parsed, function[1], qualifier))
|
||||
.map(fn -> fn.getTags() == null ? Map.<String, String>of() : Map.copyOf(fn.getTags()))
|
||||
.orElse(Map.of());
|
||||
}
|
||||
|
||||
/** Whether the function holds the version or the alias {@code qualifier} names; {@code $LATEST} it always has. */
|
||||
private boolean holdsQualifier(AwsArnUtils.Arn function, String name, String qualifier) {
|
||||
if ("$LATEST".equals(qualifier)) {
|
||||
return true;
|
||||
}
|
||||
if (functionStore.readForAccount(function.accountId(), function.region(), name, qualifier).isPresent()) {
|
||||
return true;
|
||||
}
|
||||
return aliasStore != null
|
||||
&& aliasStore.readForAccount(function.accountId(), function.region(), name, qualifier).isPresent();
|
||||
}
|
||||
|
||||
private record TagTarget(String region, String name) {}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,30 +1,39 @@
|
||||
package io.floci.aws.services.lambda;
|
||||
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import io.floci.aws.services.lambda.durable.DurableTokens;
|
||||
import io.floci.aws.services.lambdamicrovms.LambdaMicrovmsService;
|
||||
import io.floci.aws.services.lambdaweb.LambdaWebService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* What IAM asks Lambda of the resources a request names: the stored layer version a layer version ARN selects, the
|
||||
* image the caller's MicroVM runs, which the Service Reference checks an action on a running MicroVM on, and the
|
||||
* durable execution a callback belongs to, which Lambda authorizes a callback request against.
|
||||
* image the caller's MicroVM runs, which the Service Reference checks an action on a running MicroVM on, the
|
||||
* durable execution a callback belongs to, which Lambda authorizes a callback request against, and the tags of a
|
||||
* function, an event source mapping, a web function, a MicroVM image or a network connector.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaStoredResourceArns implements StoredResourceArns {
|
||||
|
||||
private final LambdaLayerService layers;
|
||||
private final LambdaService functions;
|
||||
private final Instance<LambdaMicrovmsService> microvms;
|
||||
private final Instance<LambdaWebService> webFunctions;
|
||||
|
||||
@Inject
|
||||
public LambdaStoredResourceArns(LambdaLayerService layers, Instance<LambdaMicrovmsService> microvms) {
|
||||
public LambdaStoredResourceArns(LambdaLayerService layers, LambdaService functions,
|
||||
Instance<LambdaMicrovmsService> microvms, Instance<LambdaWebService> webFunctions) {
|
||||
this.layers = layers;
|
||||
this.functions = functions;
|
||||
this.microvms = microvms;
|
||||
this.webFunctions = webFunctions;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -59,4 +68,21 @@ public class LambdaStoredResourceArns implements StoredResourceArns {
|
||||
default -> List.of();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags of the resource the ARN names, from the service holding it: a web function's, its revisions' and its
|
||||
* endpoints' from Lambda Web, a MicroVM image's or a network connector's from Lambda MicroVMs, and a function's,
|
||||
* its versions' and aliases', or an event source mapping's from Lambda.
|
||||
*/
|
||||
@Override
|
||||
public Map<String, String> storedTags(String arn) {
|
||||
String resource = AwsArnUtils.resourceIfArnFor(arn, "lambda").orElse("");
|
||||
if (resource.startsWith("web-function/")) {
|
||||
return webFunctions.isResolvable() ? webFunctions.get().storedTags(arn) : Map.of();
|
||||
}
|
||||
if (LambdaMicrovmsService.taggedResource(arn).isPresent()) {
|
||||
return microvms.isResolvable() ? microvms.get().storedTags(arn) : Map.of();
|
||||
}
|
||||
return resource.isEmpty() ? Map.of() : functions.storedTags(arn);
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ public class EventSourceMapping {
|
||||
private Map<String, Object> selfManagedEventSource;
|
||||
private List<String> topics = new ArrayList<>();
|
||||
private List<Map<String, Object>> sourceAccessConfigurations = new ArrayList<>();
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
private volatile Map<String, String> tags = new HashMap<>();
|
||||
|
||||
public EventSourceMapping() {
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ public class LambdaFunction {
|
||||
private String s3Bucket;
|
||||
private String s3Key;
|
||||
private Map<String, String> environment = new HashMap<>();
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
private volatile Map<String, String> tags = new HashMap<>();
|
||||
private List<Map<String, Object>> policies = new ArrayList<>();
|
||||
private long lastModified;
|
||||
private String revisionId;
|
||||
|
||||
@@ -7,7 +7,9 @@ import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.resource.ExplorerResource;
|
||||
import io.floci.aws.core.resource.ResourceProvider;
|
||||
import io.floci.aws.core.resource.SupportedResourceType;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageBackedMap;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.lambda.LambdaArnUtils;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
@@ -77,6 +79,9 @@ public class LambdaMicrovmsService implements ResourceProvider {
|
||||
private Map<String, MicrovmImage> images = new ConcurrentHashMap<>();
|
||||
private Map<String, Microvm> microvms = new ConcurrentHashMap<>();
|
||||
private Map<String, NetworkConnector> connectors = new ConcurrentHashMap<>();
|
||||
/** The backends of {@link #images} and {@link #connectors}, read in another account than the caller's. */
|
||||
private StorageBackend<String, MicrovmImage> imageStorage;
|
||||
private StorageBackend<String, NetworkConnector> connectorStorage;
|
||||
|
||||
@Inject
|
||||
public LambdaMicrovmsService(RegionResolver regionResolver, StorageFactory storageFactory) {
|
||||
@@ -97,12 +102,14 @@ public class LambdaMicrovmsService implements ResourceProvider {
|
||||
if (storageFactory == null) {
|
||||
return; // keeps non-CDI unit tests working
|
||||
}
|
||||
this.images = new StorageBackedMap<>(storageFactory.create("lambda",
|
||||
"lambda-microvm-images.json", new TypeReference<Map<String, MicrovmImage>>() {}));
|
||||
this.imageStorage = storageFactory.create("lambda",
|
||||
"lambda-microvm-images.json", new TypeReference<Map<String, MicrovmImage>>() {});
|
||||
this.images = new StorageBackedMap<>(imageStorage);
|
||||
this.microvms = new StorageBackedMap<>(storageFactory.create("lambda",
|
||||
"lambda-microvms.json", new TypeReference<Map<String, Microvm>>() {}));
|
||||
this.connectors = new StorageBackedMap<>(storageFactory.create("lambda",
|
||||
"lambda-network-connectors.json", new TypeReference<Map<String, NetworkConnector>>() {}));
|
||||
this.connectorStorage = storageFactory.create("lambda",
|
||||
"lambda-network-connectors.json", new TypeReference<Map<String, NetworkConnector>>() {});
|
||||
this.connectors = new StorageBackedMap<>(connectorStorage);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- images
|
||||
@@ -858,6 +865,37 @@ public class LambdaMicrovmsService implements ResourceProvider {
|
||||
return snapshotTags(taggable(region, arn));
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags of the image or the network connector stored under {@code arn} in the account and Region it names,
|
||||
* matched on the whole ARN and left as they are; empty for an ARN naming nothing stored, or any other resource.
|
||||
*/
|
||||
public Map<String, String> storedTags(String arn) {
|
||||
String resource = taggedResource(arn).orElse("");
|
||||
if (resource.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
if (resource.startsWith(IMAGE_RESOURCE)) {
|
||||
String key = key(parsed.region(), resource.substring(IMAGE_RESOURCE.length()));
|
||||
return stored(imageStorage, images, parsed.accountId(), key)
|
||||
.filter(image -> arn.equals(image.imageArn))
|
||||
.map(image -> snapshotTags(image.tags))
|
||||
.orElse(Map.of());
|
||||
}
|
||||
String key = key(parsed.region(), resource.substring(CONNECTOR_RESOURCE.length()));
|
||||
return stored(connectorStorage, connectors, parsed.accountId(), key)
|
||||
.filter(connector -> arn.equals(connector.arn))
|
||||
.map(connector -> snapshotTags(connector.tags))
|
||||
.orElse(Map.of());
|
||||
}
|
||||
|
||||
/** The entry {@code key} names in the account, read in place; from {@code local} where there is no storage. */
|
||||
private static <V> Optional<V> stored(StorageBackend<String, V> storage, Map<String, V> local, String accountId,
|
||||
String key) {
|
||||
return storage == null ? Optional.ofNullable(local.get(key))
|
||||
: AccountAwareStorageBackend.readInAccount(storage, accountId, key);
|
||||
}
|
||||
|
||||
public void tagResource(String region, String arn, Map<String, String> tags) {
|
||||
mutateTags(region, arn, target -> target.putAll(tags));
|
||||
}
|
||||
|
||||
@@ -1339,6 +1339,30 @@ public class LambdaWebService implements Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags of the web function stored under {@code arn} in the account and Region it names, or of the function
|
||||
* whose revision or endpoint it names, which inherit their function's tags; matched on the whole ARN and left as
|
||||
* they are, empty for an ARN naming nothing stored.
|
||||
*/
|
||||
public Map<String, String> storedTags(String arn) {
|
||||
Matcher named = WEB_FUNCTION_ARN.matcher(arn);
|
||||
if (!named.matches()) {
|
||||
return Map.of();
|
||||
}
|
||||
String region = named.group(1);
|
||||
String functionName = named.group(3);
|
||||
String child = named.group(4);
|
||||
String functionArn = child == null ? arn : arn.substring(0, arn.lastIndexOf("/" + child + "/"));
|
||||
synchronized (lockFor(region, functionName)) {
|
||||
return AccountAwareStorageBackend.readInAccount(functions, named.group(2), key(region, functionName))
|
||||
.filter(fn -> functionArn.equals(fn.functionArn))
|
||||
.filter(fn -> child == null || ("revision".equals(child) ? fn.revisions : fn.endpoints)
|
||||
.containsKey(named.group(5)))
|
||||
.map(fn -> Map.copyOf(fn.tags))
|
||||
.orElse(Map.of());
|
||||
}
|
||||
}
|
||||
|
||||
public void tagResource(String region, String resourceArn, JsonNode request) {
|
||||
Map<String, String> tags = LambdaWebJson.stringMap(request, "Tags", true);
|
||||
LambdaWebValidation validation = new LambdaWebValidation();
|
||||
|
||||
@@ -2181,7 +2181,7 @@ class ResourceArnBuilderTest {
|
||||
Instance<LambdaMicrovmsService> instance = mock(Instance.class);
|
||||
when(instance.isResolvable()).thenReturn(true);
|
||||
when(instance.get()).thenReturn(microvms);
|
||||
ResourceArnBuilder backed = reading(new LambdaStoredResourceArns(null, instance));
|
||||
ResourceArnBuilder backed = reading(new LambdaStoredResourceArns(null, null, instance, null));
|
||||
|
||||
assertEquals(List.of(image), lambda(backed, "GET", "/2025-09-09/microvms/microvm-1", "GetMicrovm"));
|
||||
assertEquals(List.of(image), lambda(backed, "POST", "/2025-09-09/microvms/microvm-1/suspend",
|
||||
@@ -2549,7 +2549,7 @@ class ResourceArnBuilderTest {
|
||||
String callbackId = Base64.getEncoder().encodeToString((execution + "|c1|nonce").getBytes(StandardCharsets.UTF_8));
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<LambdaMicrovmsService> none = mock(Instance.class);
|
||||
ResourceArnBuilder backed = reading(new LambdaStoredResourceArns(null, none));
|
||||
ResourceArnBuilder backed = reading(new LambdaStoredResourceArns(null, null, none, null));
|
||||
assertEquals(List.of(execution), lambda(backed, "POST",
|
||||
"/2025-12-01/durable-execution-callbacks/" + callbackId.replace("/", "%2F") + "/succeed",
|
||||
"SendDurableExecutionCallbackSuccess"));
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package io.floci.aws.services.lambda;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.lambda.LambdaClient;
|
||||
import software.amazon.awssdk.services.lambda.model.LambdaException;
|
||||
import software.amazon.awssdk.services.lambda.model.ProvisionedConcurrencyConfigNotFoundException;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class LambdaResourceTagIamIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "741681410031";
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void aResourceTagConditionReadsTheTagsOfTheFunctionItsVersionsAndAnEventSourceMapping() throws Exception {
|
||||
Region region = Region.US_EAST_1;
|
||||
String tagged = "tag-iam-" + UUID.randomUUID();
|
||||
String untagged = "tag-iam-" + UUID.randomUUID();
|
||||
try (LambdaClient owner = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, region, endpoint)) {
|
||||
String taggedArn = LambdaFunctionUrlFixtures.createFunction(owner, tagged, ACCOUNT, region, endpoint, cleanup);
|
||||
LambdaFunctionUrlFixtures.createFunction(owner, untagged, ACCOUNT, region, endpoint, cleanup);
|
||||
owner.tagResource(request -> request.resource(taggedArn).tags(Map.of("team", "data")));
|
||||
String taggedMapping = mapping(owner, tagged, Map.of("team", "data"));
|
||||
String untaggedMapping = mapping(owner, tagged, Map.of("team", "web"));
|
||||
String authorization = auth(ACCOUNT, region.id(), "iam");
|
||||
String user = "tag-reader-" + UUID.randomUUID();
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), authorization, user);
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, user, "team-data",
|
||||
"""
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Action": ["lambda:GetFunction", "lambda:GetProvisionedConcurrencyConfig",
|
||||
"lambda:GetEventSourceMapping"],
|
||||
"Resource": "*",
|
||||
"Condition": {"StringEquals": {"aws:ResourceTag/team": "data"}}
|
||||
}]
|
||||
}
|
||||
""");
|
||||
try (LambdaClient reader = AwsTestClients.create(LambdaClient.builder(),
|
||||
credentials.accessKeyId(), credentials.secretAccessKey(), region, endpoint)) {
|
||||
assertEquals(taggedArn, reader.getFunction(request -> request.functionName(tagged))
|
||||
.configuration().functionArn());
|
||||
denied(() -> reader.getFunction(request -> request.functionName(untagged)));
|
||||
|
||||
assertThrows(ProvisionedConcurrencyConfigNotFoundException.class, () ->
|
||||
reader.getProvisionedConcurrencyConfig(request -> request.functionName(tagged).qualifier("1")));
|
||||
denied(() -> reader.getProvisionedConcurrencyConfig(request ->
|
||||
request.functionName(untagged).qualifier("1")));
|
||||
|
||||
assertEquals(taggedMapping, reader.getEventSourceMapping(request -> request.uuid(taggedMapping))
|
||||
.uuid());
|
||||
denied(() -> reader.getEventSourceMapping(request -> request.uuid(untaggedMapping)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A disabled self-managed Kafka mapping of the function, so nothing polls the endpoint it names. */
|
||||
private String mapping(LambdaClient owner, String function, Map<String, String> tags) {
|
||||
String uuid = owner.createEventSourceMapping(request -> request.functionName(function)
|
||||
.topics("orders").enabled(false).tags(tags)
|
||||
.selfManagedEventSource(source -> source.endpointsWithStrings(
|
||||
Map.of("KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092"))))).uuid();
|
||||
cleanup.register(() -> {
|
||||
try (LambdaClient client = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, Region.US_EAST_1,
|
||||
endpoint)) {
|
||||
client.deleteEventSourceMapping(request -> request.uuid(uuid));
|
||||
}
|
||||
});
|
||||
return uuid;
|
||||
}
|
||||
|
||||
private static void denied(Runnable call) {
|
||||
LambdaException denied = assertThrows(LambdaException.class, call::run);
|
||||
assertEquals(403, denied.statusCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package io.floci.aws.services.lambda;
|
||||
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.lambda.model.EventSourceMapping;
|
||||
import io.floci.aws.services.lambda.model.LambdaFunction;
|
||||
import io.floci.aws.services.lambda.zip.CodeStore;
|
||||
import io.floci.aws.services.lambda.zip.ZipExtractor;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class LambdaStoredTagsTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
private LambdaService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
StorageFactory storageFactory = mock(StorageFactory.class);
|
||||
when(storageFactory.create(anyString(), anyString(), any()))
|
||||
.thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
service = new LambdaService(new LambdaFunctionStore(new InMemoryStorage<String, LambdaFunction>()),
|
||||
new WarmPool(), new CodeStore(Path.of("target/test-data/lambda-code")), new ZipExtractor(), null,
|
||||
new RegionResolver(REGION, "000000000000"), storageFactory);
|
||||
}
|
||||
|
||||
private static Map<String, Object> functionRequest(String name, Map<String, String> tags) {
|
||||
return new HashMap<>(Map.of(
|
||||
"FunctionName", name,
|
||||
"Runtime", "nodejs20.x",
|
||||
"Role", "arn:aws:iam::000000000000:role/test-role",
|
||||
"Handler", "index.handler",
|
||||
"Tags", tags));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFunctionsVersionsAndAliasesHaveItsTags() {
|
||||
LambdaFunction fn = service.createFunction(REGION, functionRequest("tagged-fn", Map.of("team", "data")));
|
||||
LambdaFunction version = service.publishVersion(REGION, "tagged-fn", null);
|
||||
service.createAlias(REGION, "tagged-fn", "live", version.getVersion(), null, null);
|
||||
String arn = fn.getFunctionArn();
|
||||
|
||||
assertEquals(Map.of("team", "data"), service.storedTags(arn));
|
||||
assertEquals(Map.of("team", "data"), service.storedTags(arn + ":$LATEST"));
|
||||
assertEquals(Map.of("team", "data"), service.storedTags(arn + ":" + version.getVersion()));
|
||||
assertEquals(Map.of("team", "data"), service.storedTags(arn + ":live"));
|
||||
assertEquals(Map.of(), service.storedTags(arn + ":7"));
|
||||
assertEquals(Map.of(), service.storedTags(arn + ":staging"));
|
||||
assertEquals(Map.of(), service.storedTags(arn + ":1/durable-execution/run/0a1b2c"));
|
||||
assertEquals(Map.of(), service.storedTags(arn.replace("000000000000", "111111111111")));
|
||||
assertEquals(Map.of(), service.storedTags(arn.replace(REGION, "us-west-2")));
|
||||
assertEquals(Map.of(), service.storedTags(arn + "-missing"));
|
||||
|
||||
service.tagResource(arn, Map.of("stage", "prod"));
|
||||
service.untagResource(arn, List.of("team"));
|
||||
|
||||
assertEquals(Map.of("stage", "prod"), service.storedTags(arn + ":live"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEventSourceMappingHasItsOwnTags() {
|
||||
service.createFunction(REGION, functionRequest("mapped-fn", Map.of("team", "data")));
|
||||
Map<String, Object> request = new HashMap<>(Map.of(
|
||||
"FunctionName", "mapped-fn",
|
||||
"Topics", List.of("orders"),
|
||||
"SelfManagedEventSource", Map.of("Endpoints",
|
||||
Map.of("KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092"))),
|
||||
"Tags", Map.of("pipeline", "orders")));
|
||||
EventSourceMapping esm = service.createEventSourceMapping(REGION, request);
|
||||
String arn = LambdaArnUtils.eventSourceMappingArn(REGION, "000000000000", esm.getUuid());
|
||||
|
||||
assertEquals(Map.of("pipeline", "orders"), service.storedTags(arn));
|
||||
|
||||
service.tagResource(arn, Map.of("owner", "ingest"));
|
||||
|
||||
assertEquals(Map.of("pipeline", "orders", "owner", "ingest"), service.storedTags(arn));
|
||||
assertEquals(Map.of(), service.storedTags(arn.replace(esm.getUuid(), "00000000-0000-0000-0000-000000000000")));
|
||||
assertEquals(Map.of(), service.storedTags(arn.replace("000000000000", "111111111111")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void taggingPutsANewTagMapInPlaceOfTheOneAReaderHolds() {
|
||||
LambdaFunction fn = service.createFunction(REGION, functionRequest("cow-fn", Map.of("team", "data")));
|
||||
Map<String, String> held = service.getFunction(REGION, "cow-fn").getTags();
|
||||
|
||||
service.tagResource(fn.getFunctionArn(), Map.of("stage", "prod"));
|
||||
service.untagResource(fn.getFunctionArn(), List.of("team"));
|
||||
|
||||
assertEquals(Map.of("team", "data"), held);
|
||||
assertEquals(Map.of("stage", "prod"), service.getFunction(REGION, "cow-fn").getTags());
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.services.lambdamicrovms;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.resource.ExplorerResource;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -21,6 +22,8 @@ import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
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.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -91,6 +94,32 @@ class LambdaMicrovmsServiceTest {
|
||||
assertEquals(0, service.getSupportedResourceTypes().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void storedTagsReadTheImageOrTheConnectorTheArnNamesInItsAccount() {
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
|
||||
StorageFactory storageFactory = mock(StorageFactory.class);
|
||||
when(storageFactory.create(anyString(), anyString(), any()))
|
||||
.thenAnswer(inv -> AccountAwareStorageBackend.inMemory(ACCOUNT_ID));
|
||||
LambdaMicrovmsService service = new LambdaMicrovmsService(regionResolver, storageFactory);
|
||||
service.initializeStorage();
|
||||
LambdaMicrovmsService.MicrovmImage image = service.createImage(REGION, ACCOUNT_ID, "tagged-image",
|
||||
"arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1", "arn:aws:iam::000000000000:role/build",
|
||||
"s3://artifacts/app.zip", null);
|
||||
LambdaMicrovmsService.NetworkConnector connector = service.createConnector(REGION, ACCOUNT_ID, "egress",
|
||||
List.of("subnet-00000000000000001"), List.of("sg-00000000000000001"),
|
||||
"arn:aws:iam::000000000000:role/operator", "token", List.of("MicroVm"), "IPv4");
|
||||
service.tagResource(REGION, image.imageArn, Map.of("team", "sandbox"));
|
||||
service.tagResource(REGION, connector.arn, Map.of("team", "net"));
|
||||
|
||||
assertEquals(Map.of("team", "sandbox"), service.storedTags(image.imageArn));
|
||||
assertEquals(Map.of("team", "net"), service.storedTags(connector.arn));
|
||||
assertEquals(Map.of(), service.storedTags(connector.arn + ":1"));
|
||||
assertEquals(Map.of(), service.storedTags(image.imageArn.replace(ACCOUNT_ID, "111111111111")));
|
||||
assertEquals(Map.of(), service.storedTags(image.imageArn.replace(REGION, "us-west-2")));
|
||||
assertEquals(Map.of(), service.storedTags("arn:aws:lambda:us-east-1:000000000000:microvm-image:missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVersionQualifiedConnectorIsNotATagTarget() {
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
|
||||
@@ -254,6 +254,24 @@ class LambdaWebServiceTest {
|
||||
message(() -> service.tagResource(REGION, "not-an-arn", mapper.createObjectNode())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void storedTagsAreTheWebFunctionsForItAndItsRevisionsAndEndpoints() {
|
||||
LambdaWebService service = service();
|
||||
ObjectNode request = createRequest("app");
|
||||
request.putObject("tags").put("team", "data");
|
||||
WebFunction created = service.createFunction(REGION, request);
|
||||
String revision = created.revisions.keySet().iterator().next();
|
||||
|
||||
assertEquals(Map.of("team", "data"), service.storedTags(ARN));
|
||||
assertEquals(Map.of("team", "data"), service.storedTags(ARN + "/revision/" + revision));
|
||||
assertEquals(Map.of("team", "data"), service.storedTags(ARN + "/endpoint/dev"));
|
||||
assertEquals(Map.of(), service.storedTags(ARN + "/endpoint/prod"));
|
||||
assertEquals(Map.of(), service.storedTags(ARN + "/revision/rev-zzzzz"));
|
||||
assertEquals(Map.of(), service.storedTags(ARN.replace(ACCOUNT_ID, "111111111111")));
|
||||
assertEquals(Map.of(), service.storedTags(ARN.replace(REGION, "us-west-2")));
|
||||
assertEquals(Map.of(), service.storedTags(ARN + "-missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void untagValidatesEveryKey() {
|
||||
LambdaWebService service = service();
|
||||
|
||||
Reference in new issue
Block a user