mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(emr-serverless): give resource-tag conditions the tags of the application, job run or session a request names (#8853)
The generated request resources give EMR Serverless's application, jobRun and session types the aws:ResourceTag/ key, but no service answered the emr-serverless namespace's stored tags, so a condition on their tags saw none. EmrServerlessStoredResourceArns now answers it for the three services that hold them: storedTags reads the application, job run or session by its id, in the request's account, where the tag handlers read, in place, and matches it on its application and on the whole ARN; a deleted application's resources name nothing. The tags fields are now volatile.
This commit is contained in:
1 parent
84e60f73a8
commit
a72aedfbb0
11 files changed
+281
-10
No files matched your search
@@ -3411,8 +3411,9 @@ floci populates:
|
||||
for Apache Flink for its applications, S3 Vectors for its vector buckets and indexes, Timestream for InfluxDB for its
|
||||
DB instances, DB clusters, parameter groups and backups, CloudTrail for its trails, Budgets for its budgets and budget
|
||||
actions, AWS FIS for its experiment templates, experiments and actions, CodePipeline for its pipelines, webhooks and
|
||||
custom action types, DataSync for its agents, locations and tasks, and Global Accelerator for its accelerators,
|
||||
listeners and endpoint groups. Tag keys differing only in case are one condition key holding every value.
|
||||
custom action types, DataSync for its agents, locations and tasks, Global Accelerator for its accelerators, listeners
|
||||
and endpoint groups, and EMR Serverless for its applications, job runs and sessions. 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
|
||||
|
||||
@@ -51,10 +51,10 @@ import java.util.Optional;
|
||||
* tags of a DB instance, a DB cluster, a parameter group or a backup; CloudTrail, for the tags of a trail; Budgets, for
|
||||
* the tags of a budget or a budget action; AWS FIS, for the tags of an experiment template, an experiment or an action;
|
||||
* CodePipeline, for the tags of a pipeline, a webhook or a custom action type; DataSync, for the tags of an agent, a
|
||||
* location or a task; Global Accelerator, for the tags of an accelerator, a listener or an endpoint group); 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>
|
||||
* location or a task; Global Accelerator, for the tags of an accelerator, a listener or an endpoint group; EMR
|
||||
* Serverless, for the tags of an application, a job run or a session); 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>
|
||||
*
|
||||
* <p>Each answer is a lookup of what the service holds, asked for by an entry of the generated table ({@code find},
|
||||
* {@code through}, a default, {@code forwarded}, a type's {@code resourceTagKeys}): never a fact about what an operation acts on, which the table alone
|
||||
|
||||
@@ -48,6 +48,7 @@ import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -480,6 +481,11 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
store.put(record.getJobRun().getJobRunId(), record);
|
||||
}
|
||||
|
||||
/** The job run {@code jobRunId} of {@code account} as stored, read in place, for IAM's lookup of stored tags. */
|
||||
Optional<JobRun> storedRun(String account, String jobRunId) {
|
||||
return AccountAwareStorageBackend.readInAccount(store, account, jobRunId).map(JobRunRecord::getJobRun);
|
||||
}
|
||||
|
||||
/** GetJobRun's {@code attempt}, an integer in the query string. */
|
||||
static Integer parseAttempt(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
|
||||
@@ -82,7 +82,8 @@ public class EmrServerlessService {
|
||||
Set.of("RepositoryNotFoundException", "ImageNotFoundException", "ServerException");
|
||||
// A release label's major and minor versions.
|
||||
private static final Pattern RELEASE_VERSION = Pattern.compile("emr-(\\d{1,6})\\.(\\d{1,6})(?:\\..*)?");
|
||||
private static final Pattern RESOURCE =
|
||||
/** A tagging ARN's resource: an application's id, then {@code jobruns} or {@code sessions} and its id. */
|
||||
static final Pattern RESOURCE =
|
||||
Pattern.compile("/applications/([0-9a-zA-Z]+)(?:/(jobruns|sessions)/([0-9a-zA-Z]+))?");
|
||||
private static final List<String> APPLICATION_STATES =
|
||||
List.of("CREATING", "CREATED", "STARTING", "STARTED", "STOPPING", "STOPPED", "TERMINATED");
|
||||
@@ -569,6 +570,16 @@ public class EmrServerlessService {
|
||||
session ? matcher.group(3) : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The application {@code applicationId} of {@code account} as stored, read in place, a record stored before storage
|
||||
* was account-aware included, unless it was deleted, which leaves it TERMINATED: what IAM's lookup of stored tags
|
||||
* reads, never under this service's lock, a tag call giving the application a new map.
|
||||
*/
|
||||
Optional<Application> storedLive(String account, String applicationId) {
|
||||
return AccountAwareStorageBackend.readInAccount(storage, account, applicationId)
|
||||
.filter(app -> !"TERMINATED".equals(app.getState()));
|
||||
}
|
||||
|
||||
/** Whether the application exists and has not been deleted, which leaves it TERMINATED. */
|
||||
public synchronized boolean isLive(String applicationId) {
|
||||
return live(applicationId).isPresent();
|
||||
|
||||
@@ -368,6 +368,11 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta
|
||||
store.put(record.getSession().getSessionId(), record);
|
||||
}
|
||||
|
||||
/** The session {@code sessionId} of {@code account} as stored, read in place, for IAM's lookup of stored tags. */
|
||||
Optional<Session> storedSession(String account, String sessionId) {
|
||||
return AccountAwareStorageBackend.readInAccount(store, account, sessionId).map(SessionRecord::getSession);
|
||||
}
|
||||
|
||||
private static void validate(StartSessionRequest request) {
|
||||
List<String> violations = new ArrayList<>();
|
||||
if (request.getClientToken() == null) {
|
||||
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package io.floci.aws.services.emrserverless;
|
||||
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import io.floci.aws.services.emrserverless.model.Application;
|
||||
import io.floci.aws.services.emrserverless.model.JobRun;
|
||||
import io.floci.aws.services.emrserverless.model.Session;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
|
||||
/**
|
||||
* What IAM asks EMR Serverless of the resources a request names: the tags of an application, a job run or a session,
|
||||
* which three services hold, so one answer stands for the namespace.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EmrServerlessStoredResourceArns implements StoredResourceArns {
|
||||
|
||||
private static final String NAMESPACE = "emr-serverless";
|
||||
|
||||
private final RegionResolver regionResolver;
|
||||
private final EmrServerlessService applications;
|
||||
private final EmrServerlessJobRunService jobRuns;
|
||||
private final EmrServerlessSessionService sessions;
|
||||
|
||||
@Inject
|
||||
public EmrServerlessStoredResourceArns(RegionResolver regionResolver, EmrServerlessService applications,
|
||||
EmrServerlessJobRunService jobRuns, EmrServerlessSessionService sessions) {
|
||||
this.regionResolver = regionResolver;
|
||||
this.applications = applications;
|
||||
this.jobRuns = jobRuns;
|
||||
this.sessions = sessions;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String namespace() {
|
||||
return NAMESPACE;
|
||||
}
|
||||
|
||||
/** A request names an application, a job run or a session by the id its ARN ends in: nothing to find. */
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags of the application, the job run or the session whose ARN is {@code arn}, in the request's account,
|
||||
* where the tag handlers read: an ARN of another account names none, and neither does one of a deleted
|
||||
* application, nor a job run's or a session's under it. Each is read in place by its id, a record stored before
|
||||
* storage was account-aware included, and matched on its application and on the whole ARN it records. Tag calls
|
||||
* give the resource a new map, so the read is of one whole set.
|
||||
*/
|
||||
@Override
|
||||
public Map<String, String> storedTags(String arn) {
|
||||
if (!AwsArnUtils.isArnFor(arn, NAMESPACE)) {
|
||||
return Map.of();
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
String account = regionResolver.getAccountId();
|
||||
Matcher matcher = EmrServerlessService.RESOURCE.matcher(parsed.resource());
|
||||
if (!parsed.accountId().equals(account) || !matcher.matches()) {
|
||||
return Map.of();
|
||||
}
|
||||
String applicationId = matcher.group(1);
|
||||
Optional<Application> application = applications.storedLive(account, applicationId);
|
||||
if (application.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, String> tags;
|
||||
if (matcher.group(2) == null) {
|
||||
tags = application.filter(app -> arn.equals(app.getArn())).map(Application::getTags).orElse(null);
|
||||
} else if ("sessions".equals(matcher.group(2))) {
|
||||
tags = sessions.storedSession(account, matcher.group(3))
|
||||
.filter(session -> applicationId.equals(session.getApplicationId()) && arn.equals(session.getArn()))
|
||||
.map(Session::getTags).orElse(null);
|
||||
} else {
|
||||
tags = jobRuns.storedRun(account, matcher.group(3))
|
||||
.filter(run -> applicationId.equals(run.getApplicationId()) && arn.equals(run.getArn()))
|
||||
.map(JobRun::getTags).orElse(null);
|
||||
}
|
||||
return tags == null ? Map.of() : new LinkedHashMap<>(tags);
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ public class Application {
|
||||
private Instant createdAt;
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
private Instant updatedAt;
|
||||
private Map<String, String> tags;
|
||||
private volatile Map<String, String> tags;
|
||||
private String architecture;
|
||||
private Map<String, InitialCapacityConfig> initialCapacity;
|
||||
private MaximumCapacity maximumCapacity;
|
||||
|
||||
@@ -27,7 +27,7 @@ public class JobRun {
|
||||
private String releaseLabel;
|
||||
private Map<String, Object> configurationOverrides;
|
||||
private JobDriver jobDriver;
|
||||
private Map<String, String> tags;
|
||||
private volatile Map<String, String> tags;
|
||||
private NetworkConfiguration networkConfiguration;
|
||||
private Integer totalExecutionDurationSeconds;
|
||||
private Long executionTimeoutMinutes;
|
||||
|
||||
@@ -34,7 +34,7 @@ public class Session implements SparkConnectSession {
|
||||
private Map<String, Object> configurationOverrides;
|
||||
private NetworkConfiguration networkConfiguration;
|
||||
private Long idleTimeoutMinutes;
|
||||
private Map<String, String> tags;
|
||||
private volatile Map<String, String> tags;
|
||||
private Long totalExecutionDurationSeconds;
|
||||
|
||||
public String getApplicationId() { return applicationId; }
|
||||
|
||||
+27
@@ -13,6 +13,7 @@ import org.junit.jupiter.api.Test;
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EmrServerlessRequests.tagsPath;
|
||||
import static io.floci.aws.testing.SignedRestRequests.denied;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
@@ -101,6 +102,32 @@ class EmrServerlessIamIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An {@code aws:ResourceTag} condition reads the tags EMR Serverless holds on the application a request names, as
|
||||
* TagResource leaves them, so an allow on one team's tag lets the caller read that team's application and not
|
||||
* another's.
|
||||
*/
|
||||
@Test
|
||||
void aResourceTagConditionReadsTheTagsOfTheApplication() throws Exception {
|
||||
String tagged = createApplication();
|
||||
String other = createApplication();
|
||||
send(admin, "POST", tagsPath(applicationArn(tagged)), "{\"tags\":{\"team\":\"data\"}}").then()
|
||||
.statusCode(200);
|
||||
send(admin, "POST", tagsPath(applicationArn(other)), "{\"tags\":{\"team\":\"web\"}}").then()
|
||||
.statusCode(200);
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "emrs-iam-", "access",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"emr-serverless:GetApplication\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}]}")) {
|
||||
send(user.signer("emr-serverless"), "GET", "/applications/" + tagged, null).then().statusCode(200);
|
||||
denied(send(user.signer("emr-serverless"), "GET", "/applications/" + other, null),
|
||||
"emr-serverless:GetApplication");
|
||||
} finally {
|
||||
send(admin, "DELETE", "/applications/" + tagged, null).then().statusCode(200);
|
||||
send(admin, "DELETE", "/applications/" + other, null).then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
private static String allow(String actions, String resource) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":" + actions
|
||||
+ ",\"Resource\":\"" + resource + "\"}]}";
|
||||
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
package io.floci.aws.services.emrserverless;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
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.services.emrserverless.model.Application;
|
||||
import io.floci.aws.services.emrserverless.model.CreateApplicationRequest;
|
||||
import io.floci.aws.services.emrserverless.model.InteractiveConfiguration;
|
||||
import io.floci.aws.services.emrserverless.model.JobDriver;
|
||||
import io.floci.aws.services.emrserverless.model.StartJobRunRequest;
|
||||
import io.floci.aws.services.emrserverless.model.StartSessionRequest;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.testing.InMemoryStorageFactory;
|
||||
import io.floci.aws.testing.MutableClock;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
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.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** IAM's lookup of the tags EMR Serverless holds on an application, a job run or a session. */
|
||||
class EmrServerlessStoredResourceArnsTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/emr-serverless-tags";
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
private final RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT_ID);
|
||||
private final MutableClock clock = new MutableClock();
|
||||
private EmrServerlessService applications;
|
||||
private EmrServerlessJobRunService jobRuns;
|
||||
private EmrServerlessSessionService sessions;
|
||||
private EmrServerlessStoredResourceArns stored;
|
||||
|
||||
/**
|
||||
* The lookup reads the tags of the application, the job run or the session the ARN names, as the tag calls leave
|
||||
* them, and nothing for another account's, another application's, a deleted application's or an unknown ARN.
|
||||
*/
|
||||
@Test
|
||||
void storedTagsAreTheTagsOfTheResourceTheArnNames() {
|
||||
build(new InMemoryStorageFactory(ACCOUNT_ID));
|
||||
Application app = applications.createApplication(application(Map.of("team", "web", "env", "dev")));
|
||||
String appArn = app.getArn();
|
||||
applications.tagResource(applications.resourceArn(appArn), Map.of("team", "data"));
|
||||
applications.untagResource(applications.resourceArn(appArn), List.of("env"));
|
||||
String runArn = jobRuns.startJobRun(app.getApplicationId(), jobRun(Map.of("team", "ops"))).getArn();
|
||||
StartSessionRequest session = new StartSessionRequest();
|
||||
session.setClientToken(UUID.randomUUID().toString());
|
||||
session.setExecutionRoleArn(ROLE);
|
||||
session.setTags(Map.of("team", "sre"));
|
||||
String sessionArn = sessions.startSession(app.getApplicationId(), session).getArn();
|
||||
Application deleted = applications.createApplication(application(Map.of("team", "data")));
|
||||
applications.deleteApplication(deleted.getApplicationId());
|
||||
|
||||
assertEquals("emr-serverless", stored.namespace());
|
||||
assertEquals(Map.of("team", "data"), stored.storedTags(appArn));
|
||||
assertEquals(Map.of("team", "ops"), stored.storedTags(runArn));
|
||||
assertEquals(Map.of("team", "sre"), stored.storedTags(sessionArn));
|
||||
assertTrue(stored.storedTags(appArn.replace(ACCOUNT_ID, "111122223333")).isEmpty());
|
||||
assertTrue(stored.storedTags(runArn.replace(app.getApplicationId(), deleted.getApplicationId())).isEmpty());
|
||||
assertTrue(stored.storedTags(deleted.getArn()).isEmpty());
|
||||
assertTrue(stored.storedTags(appArn + "/jobruns/00missing00").isEmpty());
|
||||
assertTrue(stored.storedTags("arn:aws:emr-containers:us-east-1:000000000000:/virtualclusters/abc").isEmpty());
|
||||
}
|
||||
|
||||
/** An application stored before storage was account-aware is read in place: the lookup migrates nothing. */
|
||||
@Test
|
||||
void storedTagsReadAPreAccountAwareApplicationInPlace() {
|
||||
InMemoryStorage<String, Application> raw = new InMemoryStorage<>();
|
||||
build(new InMemoryStorageFactory(ACCOUNT_ID).withStore("emr-serverless-applications.json", raw));
|
||||
Application legacy = new Application();
|
||||
legacy.setApplicationId("00legacy00");
|
||||
legacy.setArn("arn:aws:emr-serverless:us-east-1:000000000000:/applications/00legacy00");
|
||||
legacy.setState("CREATED");
|
||||
legacy.setTags(Map.of("team", "data"));
|
||||
raw.put("00legacy00", legacy);
|
||||
|
||||
assertEquals(Map.of("team", "data"), stored.storedTags(legacy.getArn()));
|
||||
assertEquals(Set.of("00legacy00"), raw.keys());
|
||||
}
|
||||
|
||||
private void build(InMemoryStorageFactory storage) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT_ID);
|
||||
applications = new EmrServerlessService(config, storage, regionResolver, clock);
|
||||
IamService iamService = mock(IamService.class);
|
||||
when(iamService.resolveCallerArn(any())).thenReturn(Optional.empty());
|
||||
jobRuns = new EmrServerlessJobRunService(AccountAwareStorageBackend.inMemory(ACCOUNT_ID), applications,
|
||||
iamService, regionResolver, null, objectMapper, 0, clock);
|
||||
sessions = new EmrServerlessSessionService(AccountAwareStorageBackend.inMemory(ACCOUNT_ID), applications,
|
||||
jobRuns, iamService, regionResolver, null, objectMapper, clock, "http://localhost:4566/");
|
||||
stored = new EmrServerlessStoredResourceArns(regionResolver, applications, jobRuns, sessions);
|
||||
}
|
||||
|
||||
private static CreateApplicationRequest application(Map<String, String> tags) {
|
||||
CreateApplicationRequest create = new CreateApplicationRequest();
|
||||
create.setName("tags");
|
||||
create.setReleaseLabel("emr-7.13.0");
|
||||
create.setType("SPARK");
|
||||
create.setClientToken(UUID.randomUUID().toString());
|
||||
InteractiveConfiguration interactive = new InteractiveConfiguration();
|
||||
interactive.setProperty("sessionEnabled", true);
|
||||
create.setInteractiveConfiguration(interactive);
|
||||
create.setTags(tags);
|
||||
return create;
|
||||
}
|
||||
|
||||
private static StartJobRunRequest jobRun(Map<String, String> tags) {
|
||||
JobDriver.SparkSubmit sparkSubmit = new JobDriver.SparkSubmit();
|
||||
sparkSubmit.setEntryPoint("s3://bucket/jobs/app.jar");
|
||||
JobDriver driver = new JobDriver();
|
||||
driver.setSparkSubmit(sparkSubmit);
|
||||
StartJobRunRequest request = new StartJobRunRequest();
|
||||
request.setClientToken(UUID.randomUUID().toString());
|
||||
request.setExecutionRoleArn(ROLE);
|
||||
request.setJobDriver(driver);
|
||||
request.setTags(tags);
|
||||
return request;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user