feat(emr): keep persistent application UIs and answer their presigned URLs (#8711)

EMR's application UI operations, CreatePersistentAppUI,
DescribePersistentAppUI, GetPersistentAppUIPresignedURL and
GetOnClusterAppUIPresignedURL, were not served.

Floci now keeps a cluster's persistent application UIs, with the types
its release and applications give it (the Spark History Server from
5.25.0, the Tez UI and YARN timeline server from 5.30.1), refusing a
cluster with more than one primary node and an account past 200, and
reports whether the cluster's security configuration turns on runtime
roles. It serves none of those UIs: a presigned URL, persistent or
on-cluster, opens a signed one-hour page of Floci's about the cluster
and the interface asked for.

The link signing of EMR Serverless's dashboards and these pages is one
helper, core.common.LinkSigner, and their HTML page and table rows come
from core.common.Html.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-17 02:32:58 -04:00
1 parent 7199c8580e
commit 751c97dde6
20 files changed
+959 -88

No files matched your search

@@ -1,5 +1,7 @@
package io.floci.aws.core.common;
import java.util.List;
/** Text put into an HTML page Floci serves, escaped so that it is shown as it is and never read as markup. */
public final class Html {
@@ -14,4 +16,19 @@ public final class Html {
return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
.replace("\"", "&quot;").replace("'", "&#39;");
}
/** A plain page titled {@code title}, the title escaped and repeated as its heading, its body's lines after it. */
public static String page(String title, List<String> body) {
return "<!doctype html>\n"
+ "<html lang=\"en\"><head><meta charset=\"utf-8\"><title>" + escape(title)
+ "</title></head>\n<body>\n<h1>" + escape(title) + "</h1>\n"
+ String.join("\n", body) + "\n</body></html>\n";
}
/** Adds a table row of {@code name} and {@code value}, both escaped; none when there is no value. */
public static void row(List<String> lines, String name, String value) {
if (value != null && !value.isEmpty()) {
lines.add("<tr><th>" + escape(name) + "</th><td>" + escape(value) + "</td></tr>");
}
}
}
@@ -0,0 +1,50 @@
package io.floci.aws.core.common;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.HexFormat;
/**
* Signs the links to pages Floci serves in place of a service's UI, such as an EMR Serverless run's dashboard or an
* EMR cluster's application UI: an HMAC-SHA256 over what a link names, with a key the signer holds. A signer made
* with {@link #withNewKey()} holds a key of its own process, so its links open nothing after a restart.
*/
public final class LinkSigner {
private static final String ALGORITHM = "HmacSHA256";
private static final int KEY_BYTES = 32;
private final byte[] key;
public LinkSigner(byte[] key) {
this.key = key.clone();
}
/** A signer with a new random key, which no other signer shares. */
public static LinkSigner withNewKey() {
byte[] key = new byte[KEY_BYTES];
new SecureRandom().nextBytes(key);
return new LinkSigner(key);
}
/** The signature over {@code fields}, in order, as hexadecimal. */
public String sign(String... fields) {
try {
Mac mac = Mac.getInstance(ALGORITHM);
mac.init(new SecretKeySpec(key, ALGORITHM));
return HexFormat.of().formatHex(mac.doFinal(String.join("\n", fields).getBytes(StandardCharsets.UTF_8)));
} catch (GeneralSecurityException e) {
throw new IllegalStateException("Could not sign a link", e);
}
}
/** Whether {@code signature} is this signer's over {@code fields}, compared in constant time. */
public boolean verifies(String signature, String... fields) {
return signature != null && MessageDigest.isEqual(sign(fields).getBytes(StandardCharsets.US_ASCII),
signature.getBytes(StandardCharsets.US_ASCII));
}
}
@@ -0,0 +1,74 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.Html;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.emr.model.EmrCluster;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* The page a presigned URL of {@code GetPersistentAppUIPresignedURL} or {@code GetOnClusterAppUIPresignedURL} opens
* ({@link EmrAppUiService}). EMR opens the cluster's Spark History Server, Tez UI, YARN timeline server or on-cluster
* UI; Floci serves none of them, so the page shows the cluster as DescribeCluster gives it and which interface was
* asked for. A link that is not one of this process's, or whose hour has passed, opens a refusal instead, and so does
* one whose cluster has gone. Like the rest of Floci the page takes no AWS credentials: the link is all it asks for.
*/
@Path(EmrAppUiService.PATH)
public class EmrAppUiController {
// No source gives AWS's wording for these; they are Floci's.
static final String INVALID = "This application UI link is not valid, or its hour has passed. Call"
+ " GetPersistentAppUIPresignedURL or GetOnClusterAppUIPresignedURL for a new one.";
static final String NO_UI = "Floci serves no Spark History Server, Tez UI, YARN timeline server or on-cluster"
+ " application UI, so this page stands in for the interface EMR opens.";
private final EmrAppUiService appUis;
@Inject
public EmrAppUiController(EmrAppUiService appUis) {
this.appUis = appUis;
}
@GET
@Produces(MediaType.TEXT_HTML)
public Response page(@QueryParam("account") String accountId, @QueryParam("region") String region,
@QueryParam("cluster") String clusterId, @QueryParam("type") String type,
@QueryParam("application") String applicationId, @QueryParam("expires") String expires,
@QueryParam("signature") String signature) {
EmrAppUiService.Link link = appUis.verified(accountId, region, clusterId, type, applicationId, expires,
signature);
if (link == null) {
return page(403, "Application UI", List.of("<p>" + Html.escape(INVALID) + "</p>"));
}
EmrCluster cluster;
try {
cluster = RequestScopes.callAs(link.accountId(), link.region(), () -> appUis.clusterOf(link));
} catch (AwsException e) {
return page(404, "Cluster " + link.clusterId(), List.of("<p>" + Html.escape(e.getMessage()) + "</p>"));
}
List<String> lines = new ArrayList<>();
lines.add("<table>");
Html.row(lines, "Cluster", cluster.getId());
Html.row(lines, "Name", cluster.getName());
Html.row(lines, "State", cluster.getState());
Html.row(lines, "Release label", cluster.getReleaseLabel());
Html.row(lines, "Interface", link.type());
Html.row(lines, "Application", link.applicationId());
lines.add("</table>");
lines.add("<p>" + Html.escape(NO_UI) + "</p>");
return page(200, link.type() + " of cluster " + cluster.getId(), lines);
}
private static Response page(int status, String title, List<String> body) {
return Response.status(status).type(MediaType.TEXT_HTML).entity(Html.page(title, body)).build();
}
}
@@ -0,0 +1,303 @@
package io.floci.aws.services.emr;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.LinkSigner;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrPersistentAppUi;
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* A cluster's application user interfaces: the persistent ones "hosted off-cluster" (Amazon EMR Management Guide, "View
* persistent application user interfaces in Amazon EMR") and the on-cluster ones, both reached through presigned URLs.
* Floci keeps a persistent application UI's record, but serves no Spark History Server, Tez UI, YARN timeline server
* or on-cluster UI: a presigned URL opens a page of Floci's own about the cluster ({@link EmrAppUiController}), signed
* with a key of this process and valid for {@link #VALIDITY}.
*/
@ApplicationScoped
public class EmrAppUiService {
/** Where Floci serves the page a presigned URL opens. */
static final String PATH = "/_aws/emr/app-ui";
// No source gives how long AWS's presigned URLs last; Floci's open its page for an hour, as its other links do.
static final Duration VALIDITY = Duration.ofHours(1);
static final List<String> PROFILER_TYPES = List.of("SHS", "TEZUI", "YTS");
static final List<String> PERSISTENT_TYPES = List.of("SHS", "TEZ", "YTS");
static final List<String> ON_CLUSTER_TYPES = List.of("SparkHistoryServer", "YarnTimelineService", "TezUI",
"ApplicationMaster", "JobHistoryServer", "ResourceManager");
// "For each AWS account, the default limit for active application UIs is 200."
static final int MAX_PERSISTENT_APP_UIS = 200;
// "The logs are available for 30 days after the application ends."
static final Duration LOGS_KEPT = Duration.ofDays(30);
// No source gives AWS's status values; Floci reports this one for every persistent application UI.
static final String ACTIVE = "ACTIVE";
private final AccountAwareStorageBackend<EmrPersistentAppUi> store;
private final EmrService clusters;
private final RegionResolver regionResolver;
private final Clock clock;
private final String baseUrl;
private final LinkSigner signer;
@Inject
public EmrAppUiService(StorageFactory storageFactory, EmrService clusters, RegionResolver regionResolver,
EmulatorConfig config) {
this(storageFactory.create("emr", "emr-persistent-app-uis.json",
new TypeReference<Map<String, EmrPersistentAppUi>>() {}),
clusters, regionResolver, Clock.systemUTC(), config.effectiveBaseUrl(), LinkSigner.withNewKey());
}
EmrAppUiService(AccountAwareStorageBackend<EmrPersistentAppUi> store, EmrService clusters,
RegionResolver regionResolver, Clock clock, String baseUrl, LinkSigner signer) {
this.store = store;
this.clusters = clusters;
this.regionResolver = regionResolver;
this.clock = clock;
String base = baseUrl == null ? "" : baseUrl;
this.baseUrl = base.endsWith("/") ? base.substring(0, base.length() - 1) : base;
this.signer = signer;
}
/** CreatePersistentAppUI's answer: the new UI, and whether its cluster is a runtime role enabled one. */
public record Created(EmrPersistentAppUi appUi, boolean runtimeRoleEnabledCluster) {
}
/**
* Creates a persistent application UI for an EMR cluster of the account in the Region, which its
* {@code TargetResourceArn} names. Floci keeps none for an EMR on EKS virtual cluster. The guide's rules apply:
* the persistent Spark History Server is there "Starting with Amazon EMR version 5.25.0", and the "Tez UI and
* YARN timeline server persistent application interfaces are available starting with Amazon EMR version 5.30.1",
* each for a cluster that installs Spark, Tez or Hadoop; the feature "is currently not available for EMR clusters
* with multiple master nodes"; and an account has at most {@link #MAX_PERSISTENT_APP_UIS}. Each refusal is
* InvalidRequestException in Floci's own wording, as AWS's is not recorded.
*/
public synchronized Created create(String targetResourceArn, String profilerType, Map<String, String> tags) {
List<String> violations = new ArrayList<>();
if (targetResourceArn == null) {
violations.add(SmithyValidationErrors.notNull("targetResourceArn"));
}
EmrService.checkEnum(violations, "profilerType", profilerType, PROFILER_TYPES);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
EmrCluster cluster = clusters.describeCluster(clusterIdOf(targetResourceArn));
if (!EmrService.releaseAtLeast(cluster.getReleaseLabel(), 5, 25, 0)) {
throw EmrService.invalid("Persistent application UIs need a cluster of release emr-5.25.0 or later.");
}
if (EmrSessions.highlyAvailable(cluster)) {
throw EmrService.invalid("Persistent application UIs are not available for a cluster with multiple"
+ " primary nodes.");
}
List<String> types = typesOf(cluster);
if (types.isEmpty()) {
throw EmrService.invalid("Cluster " + cluster.getId() + " installs none of Spark, Tez and Hadoop, whose"
+ " application UIs persist.");
}
if (profilerType != null) {
// The profiler asked for is the one interface the UI has: TEZUI is the Tez UI, as PersistentAppUIType's
// TEZ names it.
String type = "TEZUI".equals(profilerType) ? "TEZ" : profilerType;
if (!types.contains(type)) {
throw EmrService.invalid("Cluster " + cluster.getId() + " has no " + profilerType
+ " interface to persist; it has " + String.join(", ", types) + ".");
}
types = List.of(type);
}
if (activeAppUis() >= MAX_PERSISTENT_APP_UIS) {
throw EmrService.invalid("The account already has " + MAX_PERSISTENT_APP_UIS
+ " persistent application UIs.");
}
Instant now = clock.instant().truncatedTo(ChronoUnit.MILLIS);
EmrPersistentAppUi appUi = new EmrPersistentAppUi();
appUi.setId("p-" + EmrService.randomId(13));
appUi.setClusterId(cluster.getId());
appUi.setTypes(types);
appUi.setStatus(ACTIVE);
appUi.setAuthorId(regionResolver.getAccountId());
appUi.setCreationTime(now);
appUi.setLastModifiedTime(now);
appUi.setTags(tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>());
appUi.setRegion(regionResolver.getRegion());
store.put(appUi.getId(), appUi);
return new Created(copy(appUi), clusters.runtimeRoleEnabled(cluster));
}
/**
* The account's active persistent application UIs: those whose cluster runs, or ended within the 30 days for which
* "The logs are available ... after the application ends"; one whose cluster has gone, or ended earlier, frees its
* place.
*/
private long activeAppUis() {
Instant cutoff = clock.instant().minus(LOGS_KEPT);
return store.scan(key -> true).stream()
.filter(appUi -> {
EmrCluster cluster = RequestScopes.callAs(regionResolver.getAccountId(), appUi.getRegion(),
() -> clusters.findDescribedCluster(appUi.getClusterId()).orElse(null));
return cluster != null && (cluster.getEndDateTime() == null
|| cluster.getEndDateTime().isAfter(cutoff));
})
.count();
}
public synchronized EmrPersistentAppUi describe(String appUiId) {
return copy(require(appUiId));
}
/**
* A presigned URL to one of the persistent UI's types, by default its first, for the application asked for. It is
* ready at once, as Floci's page has nothing to prepare.
*/
public synchronized String persistentUrl(String appUiId, String type, String applicationId) {
List<String> violations = new ArrayList<>();
EmrService.checkEnum(violations, "persistentAppUIType", type, PERSISTENT_TYPES);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
EmrPersistentAppUi appUi = require(appUiId);
if (type != null && !appUi.getTypes().contains(type)) {
throw EmrService.invalid("Persistent application UI " + appUiId + " has no " + type + " interface.");
}
return url(appUi.getClusterId(), type != null ? type : appUi.getTypes().get(0), applicationId);
}
/**
* A presigned URL to one of the cluster's on-cluster UIs, by default its ResourceManager, which there is only while
* the cluster runs or waits; for a dry run the request is checked and no URL is made.
*/
public String onClusterUrl(String clusterId, String type, String applicationId, boolean dryRun) {
List<String> violations = new ArrayList<>();
if (clusterId == null) {
violations.add(SmithyValidationErrors.notNull("clusterId"));
}
EmrService.checkEnum(violations, "onClusterAppUIType", type, ON_CLUSTER_TYPES);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
EmrCluster cluster = clusters.describeCluster(clusterId);
if (!EmrClusterLifecycle.RUNNING.equals(cluster.getState())
&& !EmrClusterLifecycle.WAITING.equals(cluster.getState())) {
throw EmrService.invalid("Cluster " + clusterId + " is " + cluster.getState()
+ ", and its on-cluster application UIs are there only while it is RUNNING or WAITING.");
}
return dryRun ? null : url(clusterId, type != null ? type : "ResourceManager", applicationId);
}
/** What a page link names: an interface of a cluster, for an application or none, and when it expires. */
public record Link(String accountId, String region, String clusterId, String type, String applicationId,
long expires) {
}
/**
* The link a page request's parameters name, or null when one is missing or malformed, the signature is not this
* process's for them, or the link has expired.
*/
public Link verified(String accountId, String region, String clusterId, String type, String applicationId,
String expires, String signature) {
if (accountId == null || region == null || clusterId == null || type == null) {
return null;
}
Link link;
try {
link = new Link(accountId, region, clusterId, type, applicationId, Long.parseLong(expires));
} catch (NumberFormatException e) {
return null;
}
if (!signer.verifies(signature, signedFields(link)) || clock.instant().getEpochSecond() >= link.expires()) {
return null;
}
return link;
}
/** The cluster a page link names, as it now stands, read in its account and Region. */
public EmrCluster clusterOf(Link link) {
return clusters.describeCluster(link.clusterId());
}
private String url(String clusterId, String type, String applicationId) {
Link link = new Link(regionResolver.getAccountId(), regionResolver.getRegion(), clusterId, type,
applicationId, clock.instant().plus(VALIDITY).getEpochSecond());
return baseUrl + PATH + "?account=" + encoded(link.accountId()) + "&region=" + encoded(link.region())
+ "&cluster=" + encoded(clusterId) + "&type=" + encoded(type)
+ (applicationId != null ? "&application=" + encoded(applicationId) : "")
+ "&expires=" + link.expires() + "&signature=" + signer.sign(signedFields(link));
}
// Over what the link names, a link with no application told apart from one for an application named "null".
private static String[] signedFields(Link link) {
return new String[]{link.accountId(), link.region(), link.clusterId(), link.type(),
link.applicationId() != null ? "application" : "none",
link.applicationId() != null ? link.applicationId() : "", String.valueOf(link.expires())};
}
// The persistent UIs a cluster's release and applications give it.
private static List<String> typesOf(EmrCluster cluster) {
String release = cluster.getReleaseLabel();
List<String> types = new ArrayList<>();
if (EmrSparkSteps.names(cluster.getApplications(), EmrService.SNAPSHOT_MAPPER, "Spark")) {
types.add("SHS");
}
if (EmrService.releaseAtLeast(release, 5, 30, 1)
&& !(release != null && EmrServerlessSparkRunner.sparkRuntime(release))) {
if (EmrSparkSteps.names(cluster.getApplications(), EmrService.SNAPSHOT_MAPPER, "Tez")) {
types.add("TEZ");
}
if (EmrSparkSteps.names(cluster.getApplications(), EmrService.SNAPSHOT_MAPPER, "Hadoop")) {
types.add("YTS");
}
}
return types;
}
// The id of the EMR cluster of this account and Region an ARN names; InvalidRequestException for anything else.
private String clusterIdOf(String targetResourceArn) {
String clusterId = null;
if (AwsArnUtils.isArnFor(targetResourceArn, "elasticmapreduce")) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(targetResourceArn);
if (regionResolver.getAccountId().equals(arn.accountId())
&& regionResolver.getRegion().equals(arn.region())) {
clusterId = EmrService.resourceIdOf(arn, EmrService.CLUSTER_RESOURCE);
}
}
if (clusterId == null) {
throw EmrService.invalid("TargetResourceArn " + targetResourceArn + " is not an EMR cluster of the"
+ " account in the Region; Floci keeps persistent application UIs for EMR clusters only.");
}
return clusterId;
}
private EmrPersistentAppUi require(String appUiId) {
if (appUiId == null) {
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("persistentAppUIId"));
}
return store.get(appUiId)
.filter(appUi -> regionResolver.getRegion().equals(appUi.getRegion()))
.orElseThrow(() -> EmrService.invalid("Persistent application UI " + appUiId + " does not exist."));
}
private static EmrPersistentAppUi copy(EmrPersistentAppUi appUi) {
return EmrService.SNAPSHOT_MAPPER.convertValue(appUi, EmrPersistentAppUi.class);
}
private static String encoded(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
}
}
@@ -20,6 +20,7 @@ import io.floci.aws.services.emr.model.EmrErrorDetail;
import io.floci.aws.services.emr.model.EmrInstanceFleet;
import io.floci.aws.services.emr.model.EmrInstanceGroup;
import io.floci.aws.services.emr.model.EmrNotebookExecution;
import io.floci.aws.services.emr.model.EmrPersistentAppUi;
import io.floci.aws.services.emr.model.EmrSession;
import io.floci.aws.services.emr.model.EmrStep;
import io.floci.aws.services.emr.model.EmrStudio;
@@ -55,14 +56,16 @@ public class EmrHandler {
private final EmrService service;
private final EmrStudioService studios;
private final EmrNotebookExecutionService notebookExecutions;
private final EmrAppUiService appUis;
private final ObjectMapper objectMapper;
@Inject
public EmrHandler(EmrService service, EmrStudioService studios, EmrNotebookExecutionService notebookExecutions,
ObjectMapper objectMapper) {
EmrAppUiService appUis, ObjectMapper objectMapper) {
this.service = service;
this.studios = studios;
this.notebookExecutions = notebookExecutions;
this.appUis = appUis;
this.objectMapper = objectMapper;
}
@@ -102,6 +105,10 @@ public class EmrHandler {
case "DescribeNotebookExecution" -> handleDescribeNotebookExecution(request);
case "StopNotebookExecution" -> handleStopNotebookExecution(request);
case "ListNotebookExecutions" -> handleListNotebookExecutions(request);
case "CreatePersistentAppUI" -> handleCreatePersistentAppUi(request);
case "DescribePersistentAppUI" -> handleDescribePersistentAppUi(request);
case "GetPersistentAppUIPresignedURL" -> handleGetPersistentAppUiPresignedUrl(request);
case "GetOnClusterAppUIPresignedURL" -> handleGetOnClusterAppUiPresignedUrl(request);
case "AddInstanceGroups" -> handleAddInstanceGroups(request);
case "ListInstanceGroups" -> handleListInstanceGroups(request);
case "AddInstanceFleet" -> handleAddInstanceFleet(request);
@@ -526,7 +533,10 @@ public class EmrHandler {
}
}
// A TagList member: each Tag's Key and Value strings.
/**
* A TagList member: each Tag's Key and Value strings. A tag without its Key, "the minimum required information for
* a valid tag", is refused, in Floci's own wording.
*/
private static Map<String, String> tagList(JsonNode value, String member) {
Map<String, String> tags = new LinkedHashMap<>();
if (value.isMissingNode() || value.isNull()) {
@@ -540,9 +550,10 @@ public class EmrHandler {
throw malformed(member + " must be a list of tags");
}
String key = string(tag, "Key");
if (key != null) {
tags.put(key, string(tag, "Value"));
if (key == null) {
throw new AwsException("InvalidRequestException", "A tag in " + member + " has no Key.", 400);
}
tags.put(key, string(tag, "Value"));
}
return tags;
}
@@ -848,6 +859,62 @@ public class EmrHandler {
return values;
}
// ──────────────────────────── Application UIs ────────────────────────────
private Response handleCreatePersistentAppUi(JsonNode request) {
JsonNode containers = request.path("EMRContainersConfig");
if (!containers.isMissingNode() && !containers.isNull()) {
requireStructure(containers, "EMRContainersConfig");
string(containers, "JobRunId");
}
string(request, "XReferer");
EmrAppUiService.Created created = appUis.create(string(request, "TargetResourceArn"),
string(request, "ProfilerType"), tagList(request.path("Tags"), "Tags"));
ObjectNode response = objectMapper.createObjectNode();
response.put("PersistentAppUIId", created.appUi().getId());
response.put("RuntimeRoleEnabledCluster", created.runtimeRoleEnabledCluster());
return Response.ok(response).build();
}
private Response handleDescribePersistentAppUi(JsonNode request) {
EmrPersistentAppUi appUi = appUis.describe(string(request, "PersistentAppUIId"));
ObjectNode node = objectMapper.createObjectNode();
node.put("PersistentAppUIId", appUi.getId());
ArrayNode types = node.putArray("PersistentAppUITypeList");
appUi.getTypes().forEach(types::add);
node.put("PersistentAppUIStatus", appUi.getStatus());
node.put("AuthorId", appUi.getAuthorId());
putEpoch(node, "CreationTime", appUi.getCreationTime());
putEpoch(node, "LastModifiedTime", appUi.getLastModifiedTime());
putIfSet(node, "LastStateChangeReason", appUi.getLastStateChangeReason());
node.set("Tags", tagArray(appUi.getTags()));
ObjectNode response = objectMapper.createObjectNode();
response.set("PersistentAppUI", node);
return Response.ok(response).build();
}
private Response handleGetPersistentAppUiPresignedUrl(JsonNode request) {
bool(request, "AuthProxyCall");
string(request, "ExecutionRoleArn");
return presignedUrl(appUis.persistentUrl(string(request, "PersistentAppUIId"),
string(request, "PersistentAppUIType"), string(request, "ApplicationId")));
}
private Response handleGetOnClusterAppUiPresignedUrl(JsonNode request) {
string(request, "ExecutionRoleArn");
Boolean dryRun = bool(request, "DryRun");
return presignedUrl(appUis.onClusterUrl(string(request, "ClusterId"), string(request, "OnClusterAppUIType"),
string(request, "ApplicationId"), Boolean.TRUE.equals(dryRun)));
}
// A presigned URL's answer: ready at once, and the URL, none for a dry run.
private Response presignedUrl(String url) {
ObjectNode response = objectMapper.createObjectNode();
response.put("PresignedURLReady", true);
putIfSet(response, "PresignedURL", url);
return Response.ok(response).build();
}
// ──────────────────────────── Instance groups / fleets ────────────────────────────
private Response handleAddInstanceGroups(JsonNode request) {
@@ -4,7 +4,6 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
@@ -290,19 +289,9 @@ public class EmrNotebookExecutionService {
}
}
/**
* The execution's cluster as it now stands, or null once it is gone, which DescribeCluster answers with
* InvalidRequestException; any other failure is the caller's, not the execution's.
*/
// The execution's cluster as it now stands, or null once it is gone; any other failure is the caller's.
private EmrCluster clusterOf(EmrNotebookExecution execution) {
try {
return clusters.describeCluster(execution.getEngineId());
} catch (AwsException e) {
if ("InvalidRequestException".equals(e.getErrorCode())) {
return null;
}
throw e;
}
return clusters.findDescribedCluster(execution.getEngineId()).orElse(null);
}
private void end(EmrNotebookExecution execution, String status, String reason, Instant at) {
@@ -115,7 +115,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
// The service a step's driver belongs to, which names it and labels it.
private static final String SERVICE = "emr";
// The resource of a cluster's ARN, before its id.
private static final String CLUSTER_RESOURCE = "cluster/";
static final String CLUSTER_RESOURCE = "cluster/";
// The reason of a cluster a failed bootstrap action ended, as Terraform reported a real one's
// (hashicorp/terraform-provider-aws#4378) and the Management Guide's VPC errors page quotes it.
private static final String BOOTSTRAP_ACTION_FAILED =
@@ -503,6 +503,14 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
return call(() -> snapshotOf(requireCluster(id)));
}
/**
* The cluster of that id in the request's Region, as DescribeCluster gives it, or empty when there is none: what a
* notebook execution or an application UI asks of the cluster it names, which may have gone since.
*/
public Optional<EmrCluster> findDescribedCluster(String id) {
return id == null ? Optional.empty() : call(() -> findCluster(id).map(EmrService::snapshotOf));
}
public List<EmrCluster> listClusters(String region, List<String> states,
Instant createdAfter, Instant createdBefore) {
return call(() -> {
@@ -1048,6 +1056,23 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
return sc;
}
/**
* Whether the cluster's security configuration turns on runtime roles, its
* {@code AuthorizationConfiguration.IAMConfiguration.EnableApplicationScopedIAMRole}: false for a cluster with
* none, or whose configuration has since been deleted.
*/
public boolean runtimeRoleEnabled(EmrCluster cluster) {
if (cluster.getSecurityConfiguration() == null) {
return false;
}
return secConfigStore.get(securityConfigurationKey(regionOf(cluster), cluster.getSecurityConfiguration()))
.map(SecurityConfiguration::getSecurityConfiguration)
.map(EmrService::rawJson)
.map(json -> json.path("AuthorizationConfiguration").path("IAMConfiguration")
.path("EnableApplicationScopedIAMRole").asBoolean(false))
.orElse(false);
}
public SecurityConfiguration describeSecurityConfiguration(String name, String region) {
return secConfigStore.get(securityConfigurationKey(region, name)).orElseThrow(() -> new AwsException(
"InvalidRequestException", "Security configuration does not exist: " + name, 400));
@@ -137,7 +137,7 @@ final class EmrSessions {
}
// More than one primary node: a primary instance group of more than one instance, or a primary fleet's capacity.
private static boolean highlyAvailable(EmrCluster cluster) {
static boolean highlyAvailable(EmrCluster cluster) {
for (EmrInstanceGroup group : cluster.getInstanceGroups()) {
if (EmrService.isMasterGroup(group) && group.getRequestedInstanceCount() > 1) {
return true;
@@ -0,0 +1,53 @@
package io.floci.aws.services.emr.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* A persistent application user interface, as DescribePersistentAppUI reports it, with the cluster it was made for and
* the Region it is in.
*/
@RegisterForReflection
public class EmrPersistentAppUi {
private String id;
private String clusterId;
private List<String> types = new ArrayList<>();
private String status;
private String authorId;
private Instant creationTime;
private Instant lastModifiedTime;
private String lastStateChangeReason;
private Map<String, String> tags = new LinkedHashMap<>();
private String region;
public EmrPersistentAppUi() {}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getClusterId() { return clusterId; }
public void setClusterId(String clusterId) { this.clusterId = clusterId; }
public List<String> getTypes() { return types; }
public void setTypes(List<String> types) { this.types = types; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getAuthorId() { return authorId; }
public void setAuthorId(String authorId) { this.authorId = authorId; }
public Instant getCreationTime() { return creationTime; }
public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; }
public Instant getLastModifiedTime() { return lastModifiedTime; }
public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; }
public String getLastStateChangeReason() { return lastStateChangeReason; }
public void setLastStateChangeReason(String lastStateChangeReason) {
this.lastStateChangeReason = lastStateChangeReason;
}
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
}
@@ -86,19 +86,19 @@ public class EmrServerlessDashboardController {
JobRun run = view.run();
List<String> lines = new ArrayList<>();
lines.add("<table>");
row(lines, "Application", run.getApplicationId());
row(lines, "Job run", run.getJobRunId());
row(lines, "Name", run.getName());
row(lines, "Attempt", run.getAttempt() != null ? String.valueOf(run.getAttempt()) : null);
row(lines, "State", run.getState());
row(lines, "State details", run.getStateDetails());
row(lines, "Release label", run.getReleaseLabel());
row(lines, "Created", run.getCreatedAt() != null ? run.getCreatedAt().toString() : null);
row(lines, "Updated", run.getUpdatedAt() != null ? run.getUpdatedAt().toString() : null);
row(lines, "Driver logs in S3", view.logs().s3Folder());
row(lines, "Driver logs in CloudWatch Logs", view.logs().logGroup());
row(lines, "Driver stdout stream", view.logs().stdoutStream());
row(lines, "Driver stderr stream", view.logs().stderrStream());
Html.row(lines, "Application", run.getApplicationId());
Html.row(lines, "Job run", run.getJobRunId());
Html.row(lines, "Name", run.getName());
Html.row(lines, "Attempt", run.getAttempt() != null ? String.valueOf(run.getAttempt()) : null);
Html.row(lines, "State", run.getState());
Html.row(lines, "State details", run.getStateDetails());
Html.row(lines, "Release label", run.getReleaseLabel());
Html.row(lines, "Created", run.getCreatedAt() != null ? run.getCreatedAt().toString() : null);
Html.row(lines, "Updated", run.getUpdatedAt() != null ? run.getUpdatedAt().toString() : null);
Html.row(lines, "Driver logs in S3", view.logs().s3Folder());
Html.row(lines, "Driver logs in CloudWatch Logs", view.logs().logGroup());
Html.row(lines, "Driver stdout stream", view.logs().stdoutStream());
Html.row(lines, "Driver stderr stream", view.logs().stderrStream());
lines.add("</table>");
lines.add("<p>" + Html.escape(NO_UI) + "</p>");
return lines;
@@ -107,16 +107,16 @@ public class EmrServerlessDashboardController {
private static List<String> body(Session session) {
List<String> lines = new ArrayList<>();
lines.add("<table>");
row(lines, "Application", session.getApplicationId());
row(lines, "Session", session.getSessionId());
row(lines, "Name", session.getName());
row(lines, "State", session.getState());
row(lines, "State details", session.getStateDetails());
row(lines, "Release label", session.getReleaseLabel());
row(lines, "Created", text(session.getCreatedAt()));
row(lines, "Started", text(session.getStartedAt()));
row(lines, "Idle since", text(session.getIdleSince()));
row(lines, "Ended", text(session.getEndedAt()));
Html.row(lines, "Application", session.getApplicationId());
Html.row(lines, "Session", session.getSessionId());
Html.row(lines, "Name", session.getName());
Html.row(lines, "State", session.getState());
Html.row(lines, "State details", session.getStateDetails());
Html.row(lines, "Release label", session.getReleaseLabel());
Html.row(lines, "Created", text(session.getCreatedAt()));
Html.row(lines, "Started", text(session.getStartedAt()));
Html.row(lines, "Idle since", text(session.getIdleSince()));
Html.row(lines, "Ended", text(session.getEndedAt()));
lines.add("</table>");
lines.add("<p>" + Html.escape(NO_SESSION_UI) + "</p>");
return lines;
@@ -126,18 +126,7 @@ public class EmrServerlessDashboardController {
return instant != null ? instant.toString() : null;
}
// A row of the table, left out when the run or session has no such value.
private static void row(List<String> lines, String name, String value) {
if (value != null && !value.isEmpty()) {
lines.add("<tr><th>" + Html.escape(name) + "</th><td>" + Html.escape(value) + "</td></tr>");
}
}
private static Response page(int status, String title, List<String> body) {
String html = "<!doctype html>\n"
+ "<html lang=\"en\"><head><meta charset=\"utf-8\"><title>" + Html.escape(title)
+ "</title></head>\n<body>\n<h1>" + Html.escape(title) + "</h1>\n"
+ String.join("\n", body) + "\n</body></html>\n";
return Response.status(status).type(MediaType.TEXT_HTML).entity(html).build();
return Response.status(status).type(MediaType.TEXT_HTML).entity(Html.page(title, body)).build();
}
}
@@ -1,19 +1,14 @@
package io.floci.aws.services.emrserverless;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.LinkSigner;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.util.HexFormat;
/**
* The links {@code GetDashboardForJobRun} gives, "a URL that you can use to access the application UIs for a job run",
@@ -30,22 +25,24 @@ public class EmrServerlessDashboards {
/** Where Floci serves the page a link opens. */
static final String PATH = "/_aws/emr-serverless/dashboard";
static final Duration VALIDITY = Duration.ofHours(1);
private static final String ALGORITHM = "HmacSHA256";
private static final int KEY_BYTES = 32;
private final String baseUrl;
private final Clock clock;
private final byte[] key;
private final LinkSigner signer;
@Inject
public EmrServerlessDashboards(EmulatorConfig config, Clock clock) {
this(config.effectiveBaseUrl(), clock, newKey());
this(config.effectiveBaseUrl(), clock, LinkSigner.withNewKey());
}
EmrServerlessDashboards(String baseUrl, Clock clock, byte[] key) {
this(baseUrl, clock, new LinkSigner(key));
}
private EmrServerlessDashboards(String baseUrl, Clock clock, LinkSigner signer) {
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
this.clock = clock;
this.key = key.clone();
this.signer = signer;
}
/**
@@ -86,8 +83,7 @@ public class EmrServerlessDashboards {
} catch (NumberFormatException e) {
return null;
}
byte[] expected = signature(link).getBytes(StandardCharsets.US_ASCII);
if (!MessageDigest.isEqual(expected, signature.getBytes(StandardCharsets.US_ASCII))
if (!signer.verifies(signature, signedFields(link))
|| clock.instant().getEpochSecond() >= link.expires()) {
return null;
}
@@ -109,23 +105,14 @@ public class EmrServerlessDashboards {
// Over what the link names; a run's link and a session's are told apart, so neither opens as the other.
private String signature(Link link) {
String signed = String.join("\n", link.accountId(), link.region(), link.applicationId(),
link.jobRunId() != null ? "jobRun" : "session",
link.jobRunId() != null ? link.jobRunId() : link.sessionId(),
String.valueOf(link.attempt()), String.valueOf(link.expires()));
try {
Mac mac = Mac.getInstance(ALGORITHM);
mac.init(new SecretKeySpec(key, ALGORITHM));
return HexFormat.of().formatHex(mac.doFinal(signed.getBytes(StandardCharsets.UTF_8)));
} catch (GeneralSecurityException e) {
throw new IllegalStateException("Could not sign an EMR Serverless dashboard link", e);
}
return signer.sign(signedFields(link));
}
private static byte[] newKey() {
byte[] key = new byte[KEY_BYTES];
new SecureRandom().nextBytes(key);
return key;
private static String[] signedFields(Link link) {
return new String[]{link.accountId(), link.region(), link.applicationId(),
link.jobRunId() != null ? "jobRun" : "session",
link.jobRunId() != null ? link.jobRunId() : link.sessionId(),
String.valueOf(link.attempt()), String.valueOf(link.expires())};
}
private static String encoded(String value) {