feat(quicksight): add metadata APIs and limited registered-user embedding (#7529)

Closes #7522

Origin comparisons preserved host casing and default ports, CSP named only the immediate parent, and expired sessions remained in storage indefinitely. Normalize both sides of origin checks, allow all configured ancestors, and reap expired sessions across accounts with the shared sweep worker.
This commit is contained in:
jwoa95 authored and GitHub committed 2026-11-06 09:11:30 -04:00
1 parent 5058163409
commit f8670f64fb
40 files changed
+2511 -37

No files matched your search

@@ -884,6 +884,7 @@ public interface EmulatorConfig {
EfsServiceConfig efs();
CodeGuruReviewerServiceConfig codegurureviewer();
CodeArtifactServiceConfig codeartifact();
QuickSightServiceConfig quicksight();
MarketplaceServiceConfig marketplace();
DmsServiceConfig dms();
}
@@ -1029,6 +1030,14 @@ public interface EmulatorConfig {
boolean enabled();
}
interface QuickSightServiceConfig {
@WithDefault("true")
boolean enabled();
/** Public origin used by browser embedding clients. */
Optional<String> embedBaseUrl();
}
interface MarketplaceServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -1862,7 +1862,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
/**
* Builds a 403 Access Denied response in the wire format the calling SDK
* Builds an Access Denied response in the wire format the calling SDK
* expects. AWS SDKs hard-fail when they receive the wrong shape: an XML
* parser blows up on a leading {@code {}, and a JSON parser blows up on
* {@code <}. Pick the shape from request signals:
@@ -1872,7 +1872,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
* <li>{@code application/x-www-form-urlencoded} body → AWS Query
* {@code <ErrorResponse>...</ErrorResponse>} (IAM/STS/EC2/SQS/SNS/...), with the code
* {@link #queryAccessDeniedCode} gives the service that serves the request</li>
* <li>JSON 1.x: JSON with HTTP 400; REST-JSON: JSON with HTTP 403</li>
* <li>JSON 1.x: JSON with HTTP 400; REST-JSON: JSON with its modelled denial status, defaulting to HTTP 403</li>
* <li>CBOR: the request's own encoding with HTTP 403, from {@link #accessDeniedForRequest},
* which has the request to read it from</li>
* </ul>
@@ -1931,7 +1931,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
if (restXml || protocol == WireProtocol.AWS_QUERY || isFormEncoded(requestMediaType)) {
return queryXmlError(queryAccessDeniedCode(credentialScope), message);
}
int status = protocol == WireProtocol.AWS_JSON_1_0 || protocol == WireProtocol.AWS_JSON_1_1 ? 400 : 403;
int status = protocol == WireProtocol.AWS_JSON_1_0 || protocol == WireProtocol.AWS_JSON_1_1
? 400 : IamActionRegistry.accessDeniedStatus(credentialScope, 403);
return jsonAccessDenied(message, status);
}
@@ -31,9 +31,11 @@ final class RequestResourceMembers {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final Pattern VARIABLE = Pattern.compile("\\$\\{(\\w+)}");
private static final Pattern MEMBER = Pattern.compile("[A-Za-z][A-Za-z0-9_]*(\\[])?");
/** A member holding an ARN may also be one level inside a structure or each of a list's structures. */
private static final Pattern ARN_MEMBER = Pattern.compile("[A-Za-z][A-Za-z0-9_]*(\\[])?(\\.[A-Za-z][A-Za-z0-9_]*(\\[])?)?");
private static final Pattern MEMBER = Pattern.compile("[A-Za-z][A-Za-z0-9_]*(\\[]|\\{\\})?");
/** An ARN may be nested in structures, array elements or map values. */
private static final Pattern ARN_MEMBER = Pattern.compile(
"[A-Za-z][A-Za-z0-9_]*(\\[])?(\\.[A-Za-z][A-Za-z0-9_]*(\\[])?)?"
+ "|[A-Za-z][A-Za-z0-9_]*\\{\\}(\\.[A-Za-z][A-Za-z0-9_]*){1,2}");
/**
* A member filling a variable may also be a field of a structure, or of each of a list's structures, one value
* for each.
@@ -56,18 +58,22 @@ final class RequestResourceMembers {
private static final Set<String> THROUGH_KEYS = Set.of("types", "through", "when", "endpoint");
/**
* A top-level request member that holds a string, or a list of them when {@code list}, or, with a
* {@code field}, a structure or a list of them, of which that field is read.
* A request selector that holds a string, an array when {@code list}, or map values when {@code map}.
* With a {@code field}, reads that field from each selected structure.
*/
record Member(String name, boolean list, Member field) {
record Member(String name, boolean list, Member field, boolean map) {
Member(String name, boolean list, Member field) {
this(name, list, field, false);
}
Member(String name, boolean list) {
this(name, list, null);
}
/** As the file writes it: {@code Name}, {@code Name[]}, {@code Name.Field} or {@code Name[].Field}. */
/** The selector path, with {@code []} for array elements and {@code {}} for map values. */
String path() {
return name + (list ? "[]" : "") + (field == null ? "" : "." + field.path());
return name + (map ? "{}" : list ? "[]" : "") + (field == null ? "" : "." + field.path());
}
/** Whether it is a field of each of a list's structures, which gives one value for each of them. */
@@ -419,6 +425,9 @@ final class RequestResourceMembers {
if (!MEMBER.matcher(path).matches()) {
throw new IllegalStateException(RESOURCE_NAME + " reads " + operation + " at " + path + ", which is no member");
}
if (path.endsWith("{}")) {
return new Member(path.substring(0, path.length() - 2), false, null, true);
}
return path.endsWith("[]") ? new Member(path.substring(0, path.length() - 2), true) : new Member(path, false);
}
@@ -445,7 +454,7 @@ final class RequestResourceMembers {
return !member.list() && (member.field() == null || !member.field().list());
}
/** A member holding an ARN: {@code Name}, {@code Name[]}, or a field of it, {@code Name.Field} or {@code Name[].Field}. */
/** A possibly nested ARN selector; {@code []} reads array elements and {@code {}} reads map values. */
private static Member arnMember(String operation, String path) {
if (!ARN_MEMBER.matcher(path).matches()) {
throw new IllegalStateException(RESOURCE_NAME + " reads " + operation + " at " + path + ", which is no member");
@@ -455,7 +464,7 @@ final class RequestResourceMembers {
return member(operation, path);
}
Member outer = member(operation, path.substring(0, dot));
return new Member(outer.name(), outer.list(), member(operation, path.substring(dot + 1)));
return new Member(outer.name(), outer.list(), arnMember(operation, path.substring(dot + 1)), outer.map());
}
/**
@@ -614,6 +614,9 @@ public final class RequestResources {
*/
private static void addFormValues(List<String> values, Map<String, String> form, String prefix,
RequestResourceMembers.Member member) {
if (member.map()) {
return;
}
String key = prefix + member.name();
if (!member.list()) {
if (member.field() == null) {
@@ -640,13 +643,19 @@ public final class RequestResources {
return form.containsKey(element + "." + field.name() + (field.list() ? ".member.1" : ""));
}
/** A body's values of a member, and of its field in its structure or in each of its list's structures. */
/** A body's selector values, traversing structures, array elements and map values. */
private static void addBodyValues(List<String> values, JsonNode node, RequestResourceMembers.Member member) {
JsonNode value = node.get(member.name());
if (value == null) {
return;
}
if (!member.list()) {
if (member.map()) {
if (value.isObject()) {
for (JsonNode element : value) {
addElement(values, element, member.field());
}
}
} else if (!member.list()) {
addElement(values, value, member.field());
} else if (value.isArray()) {
for (JsonNode element : value) {
@@ -68,6 +68,8 @@ import io.github.hectorvent.floci.services.oam.OamController;
import io.github.hectorvent.floci.services.opensearch.ElasticsearchController;
import io.github.hectorvent.floci.services.opensearch.OpenSearchController;
import io.github.hectorvent.floci.services.pipes.PipesController;
import io.github.hectorvent.floci.services.quicksight.QuickSightController;
import io.github.hectorvent.floci.services.quicksight.QuickSightEmbedController;
import io.github.hectorvent.floci.services.ram.RamController;
import io.github.hectorvent.floci.services.rdsdata.RdsDataController;
import io.github.hectorvent.floci.services.resourceexplorer2.ResourceExplorer2Controller;
@@ -816,6 +818,10 @@ public class ResolvedServiceCatalog {
"verifiedpermissions", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("VerifiedPermissions."), Set.of("verifiedpermissions"), Set.of(), Set.of()),
descriptor("quicksight", "quicksight", config.services().quicksight().enabled(), true,
"quicksight", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("quicksight"), Set.of(),
Set.of(QuickSightController.class, QuickSightEmbedController.class)),
descriptor("marketplace", "marketplace", config.services().marketplace().enabled(), true,
"marketplace", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON, ServiceProtocol.JSON, ServiceProtocol.CBOR),
@@ -743,6 +743,11 @@ public class IamActionRegistry {
return null;
}
/** A REST model's explicit denial status, retaining the protocol default when none is modelled. */
public static int accessDeniedStatus(String credentialScope, int fallback) {
return IamRestRoutes.vendored().accessDeniedStatus(credentialScope, fallback);
}
/**
* The value a REST request's path gives each label of the vendored route it matches, decoded, by the label's
* name; empty when it matches none. {@link RequestResources} reads a member the table of request resources
@@ -105,9 +105,11 @@ final class IamRestRoutes {
/** Each credential scope's routes, by method. */
private final Map<String, Map<String, List<Route>>> routes;
private final Map<String, Integer> accessDeniedStatuses;
private IamRestRoutes(Map<String, Map<String, List<Route>>> routes) {
private IamRestRoutes(Map<String, Map<String, List<Route>>> routes, Map<String, Integer> accessDeniedStatuses) {
this.routes = routes;
this.accessDeniedStatuses = accessDeniedStatuses;
}
/** The vendored routes. */
@@ -135,6 +137,11 @@ final class IamRestRoutes {
return best == null ? Optional.empty() : Optional.of(new Match(best.operation(), best.labelValues(requestPath)));
}
/** The modelled denial status, or the existing protocol default when the model declares none. */
int accessDeniedStatus(String scope, int fallback) {
return scope == null ? fallback : accessDeniedStatuses.getOrDefault(scope, fallback);
}
/** Whether the file routes any request of the credential scope. */
boolean routes(String scope) {
return routes.containsKey(scope);
@@ -149,6 +156,7 @@ final class IamRestRoutes {
}
Set<String> skipped = Set.copyOf(handRouted.propertyStream().map(Map.Entry::getKey).toList());
Map<String, Map<String, List<Route>>> routes = new HashMap<>();
Map<String, Integer> denialStatuses = new HashMap<>();
models.properties().forEach(model -> {
String scope = model.getValue().path("credentialScope").asText("");
JsonNode operations = model.getValue().path("operations");
@@ -156,6 +164,18 @@ final class IamRestRoutes {
throw new IllegalStateException(RESOURCE_NAME + " gives model " + model.getKey()
+ " no credential scope or no operations");
}
if (model.getValue().has("accessDeniedStatus")) {
JsonNode status = model.getValue().get("accessDeniedStatus");
if (!status.isIntegralNumber() || !status.canConvertToInt() || status.asInt() < 400 || status.asInt() > 599) {
throw new IllegalStateException(RESOURCE_NAME + " gives model " + model.getKey()
+ " an invalid access-denied HTTP status");
}
Integer previous = denialStatuses.putIfAbsent(scope, status.asInt());
if (previous != null && previous.intValue() != status.asInt()) {
throw new IllegalStateException(RESOURCE_NAME + " gives scope " + scope
+ " conflicting access-denied HTTP statuses");
}
}
if (skipped.contains(scope)) {
return;
}
@@ -177,7 +197,7 @@ final class IamRestRoutes {
byMethod.forEach((method, list) -> methods.put(method, List.copyOf(list)));
copied.put(scope, Map.copyOf(methods));
});
return new IamRestRoutes(Map.copyOf(copied));
return new IamRestRoutes(Map.copyOf(copied), Map.copyOf(denialStatuses));
}
/** A route of the operation from its request URI, its path's segments and the query after its {@code ?}. */
@@ -0,0 +1,182 @@
package io.github.hectorvent.floci.services.quicksight;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("/accounts/{account}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class QuickSightController {
private final QuickSightService service;
private final ObjectReader reader;
private final RegionResolver regions;
@Inject
public QuickSightController(QuickSightService service, ObjectMapper mapper, RegionResolver regions) {
this.service = service;
this.regions = regions;
this.reader = mapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
}
@POST
@Path("/search/dashboards")
public Response searchDashboards(@PathParam("account") String account, String body) {
requireCallerMayActOnAccount(account);
return response(service.searchDashboards(account, parse(body)));
}
@POST
@Path("/dashboards/{id}")
public Response createDashboard(@PathParam("account") String account, @PathParam("id") String id, String body) {
requireCallerMayActOnAccount(account);
return response(service.create(account, "dashboard", id, parse(body)));
}
@GET
@Path("/dashboards/{id}")
public Response describeDashboard(@PathParam("account") String account, @PathParam("id") String id) {
requireCallerMayActOnAccount(account);
return response(service.describe(account, "dashboard", id));
}
@DELETE
@Path("/dashboards/{id}")
public Response deleteDashboard(@PathParam("account") String account, @PathParam("id") String id) {
requireCallerMayActOnAccount(account);
return response(service.delete(account, "dashboard", id));
}
@POST
@Path("/data-sets")
public Response createDataSet(@PathParam("account") String account, String body) {
requireCallerMayActOnAccount(account);
JsonNode request = parse(body);
return response(service.create(account, "dataset", request.path("DataSetId").asText(), request));
}
@GET
@Path("/data-sets/{id}")
public Response describeDataSet(@PathParam("account") String account, @PathParam("id") String id) {
requireCallerMayActOnAccount(account);
return response(service.describe(account, "dataset", id));
}
@DELETE
@Path("/data-sets/{id}")
public Response deleteDataSet(@PathParam("account") String account, @PathParam("id") String id) {
requireCallerMayActOnAccount(account);
return response(service.delete(account, "dataset", id));
}
@POST
@Path("/data-sources")
public Response createDataSource(@PathParam("account") String account, String body) {
requireCallerMayActOnAccount(account);
JsonNode request = parse(body);
return response(service.create(account, "datasource", request.path("DataSourceId").asText(), request));
}
@GET
@Path("/data-sources/{id}")
public Response describeDataSource(@PathParam("account") String account, @PathParam("id") String id) {
requireCallerMayActOnAccount(account);
return response(service.describe(account, "datasource", id));
}
@DELETE
@Path("/data-sources/{id}")
public Response deleteDataSource(@PathParam("account") String account, @PathParam("id") String id) {
requireCallerMayActOnAccount(account);
return response(service.delete(account, "datasource", id));
}
@POST
@Path("/namespaces/{namespace}/users")
public Response registerUser(@PathParam("account") String account, @PathParam("namespace") String namespace, String body) {
requireCallerMayActOnAccount(account);
return response(service.registerUser(account, namespace, parse(body)));
}
@GET
@Path("/namespaces/{namespace}/users/{name}")
public Response describeUser(@PathParam("account") String account, @PathParam("namespace") String namespace,
@PathParam("name") String name) {
requireCallerMayActOnAccount(account);
return response(service.describeUser(account, namespace, name));
}
@PUT
@Path("/data-sets/{id}/ingestions/{ingestion}")
public Response createIngestion(@PathParam("account") String account, @PathParam("id") String id,
@PathParam("ingestion") String ingestion, String body) {
requireCallerMayActOnAccount(account);
return response(service.createIngestion(account, id, ingestion, parse(body)));
}
@GET
@Path("/data-sets/{id}/ingestions")
public Response listIngestions(@PathParam("account") String account, @PathParam("id") String id,
@QueryParam("max-results") String maximum,
@QueryParam("next-token") String token) {
requireCallerMayActOnAccount(account);
Integer limit = Pagination.parseMaxResults(maximum, "InvalidParameterValueException");
return response(service.listIngestions(account, id, limit == null ? 100 : limit, token));
}
@GET
@Path("/data-sets/{id}/ingestions/{ingestion}")
public Response describeIngestion(@PathParam("account") String account, @PathParam("id") String id,
@PathParam("ingestion") String ingestion) {
requireCallerMayActOnAccount(account);
return response(service.describeIngestion(account, id, ingestion));
}
@POST
@Path("/embed-url/registered-user")
public Response generateEmbedUrlForRegisteredUser(@PathParam("account") String account, String body) {
requireCallerMayActOnAccount(account);
return response(service.generateEmbedUrl(account, parse(body)));
}
private void requireCallerMayActOnAccount(String account) {
if (!account.equals(regions.getAccountId())) {
throw new AwsException("AccessDeniedException", "AwsAccountId must match the caller's account.", 401);
}
}
private JsonNode parse(String body) {
try {
JsonNode node = reader.readTree(body == null || body.isBlank() ? "{}" : body);
if (node == null || !node.isObject()) {
throw new AwsException("InvalidParameterValueException", "Request must be a JSON object.", 400);
}
return node;
} catch (AwsException exception) {
throw exception;
} catch (Exception exception) {
throw new AwsException("InvalidParameterValueException", "Request body is not valid JSON.", 400);
}
}
private Response response(ObjectNode body) {
return Response.status(body.path("Status").asInt(200)).header("x-amzn-RequestId", body.path("RequestId").asText()).entity(body).build();
}
}
@@ -0,0 +1,57 @@
package io.github.hectorvent.floci.services.quicksight;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.inject.Inject;
import jakarta.ws.rs.CookieParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
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;
@Path("/embed/{session}")
public class QuickSightEmbedController {
private final QuickSightService service;
@Inject
public QuickSightEmbedController(QuickSightService service) {
this.service = service;
}
@GET
@Path("/dashboards/{id}")
@Produces(MediaType.TEXT_HTML)
public Response dashboard(@PathParam("session") String session, @PathParam("id") String id,
@QueryParam("code") String code, @HeaderParam("Referer") String referer,
@CookieParam("floci-quicksight") String cookie) {
String origin = QuickSightOrigins.fromUrl(referer);
ObjectNode dashboard = service.redeem(session, code, id, origin, cookie);
String name = escape(dashboard.path("Name").asText());
String html = "<!doctype html><html><head><meta charset=\"utf-8\"><title>" + name
+ "</title></head><body><main><h1>" + name + "</h1><p>Local QuickSight metadata preview. BI visualizations are not rendered.</p></main></body></html>";
Response.ResponseBuilder response = Response.ok(html).header("Cache-Control", "no-store")
.header("Set-Cookie", "floci-quicksight=" + dashboard.path("_SessionCookie").asText() + "; Path=/embed/" + session + "; HttpOnly; Secure; SameSite=None");
List<String> ancestors = new ArrayList<>();
for (JsonNode allowedOrigin : dashboard.path("_AllowedOrigins")) {
ancestors.add(allowedOrigin.asText());
}
if (ancestors.isEmpty() && !origin.isEmpty()) {
ancestors.add(origin);
}
if (!ancestors.isEmpty()) {
response.header("Content-Security-Policy", "frame-ancestors " + String.join(" ", ancestors));
}
return response.build();
}
private String escape(String value) {
return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("'", "&#39;");
}
}
@@ -0,0 +1,35 @@
package io.github.hectorvent.floci.services.quicksight;
import java.net.URI;
import java.util.Locale;
final class QuickSightOrigins {
private QuickSightOrigins() {}
static String fromUrl(String value) {
if (value == null) {
return "";
}
try {
return normalize(URI.create(value));
} catch (IllegalArgumentException exception) {
return "";
}
}
static String normalize(URI uri) {
if (uri.getScheme() == null || uri.getHost() == null || uri.getRawUserInfo() != null
|| uri.getPort() > 65535) {
return "";
}
String scheme = uri.getScheme().toLowerCase(Locale.ROOT);
String host = uri.getHost().toLowerCase(Locale.ROOT);
if (!"https".equals(scheme) && !"http".equals(scheme)) {
return "";
}
int port = uri.getPort();
boolean defaultPort = port == -1 || "https".equals(scheme) && port == 443
|| "http".equals(scheme) && port == 80;
return scheme + "://" + host + (defaultPort ? "" : ":" + port);
}
}
@@ -0,0 +1,461 @@
package io.github.hectorvent.floci.services.quicksight;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.StoredResourceArns;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.quicksight.model.QuickSightResource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.net.URI;
import java.time.Clock;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
@ApplicationScoped
public class QuickSightService implements Resettable, StoredResourceArns {
private final ObjectMapper mapper;
private final RegionResolver regions;
private final AccountAwareStorageBackend<QuickSightResource> resources;
private final AccountAwareStorageBackend<QuickSightResource> sessions;
private final String embedBaseUrl;
private final Clock clock;
@Inject
public QuickSightService(StorageFactory factory, ObjectMapper mapper, RegionResolver regions, EmulatorConfig config) {
this(mapper, regions,
factory.create("quicksight", "quicksight-resources.json", new TypeReference<>() {}),
factory.create("quicksight", "quicksight-sessions.json", new TypeReference<>() {}),
config.services().quicksight().embedBaseUrl().orElse(config.baseUrl()), Clock.systemUTC());
}
QuickSightService(ObjectMapper mapper, RegionResolver regions,
AccountAwareStorageBackend<QuickSightResource> resources,
AccountAwareStorageBackend<QuickSightResource> sessions, String embedBaseUrl, Clock clock) {
this.clock = clock;
this.mapper = mapper;
this.regions = regions;
this.resources = resources;
this.sessions = sessions;
this.embedBaseUrl = embedBaseUrl.replaceAll("/$", "");
}
public synchronized ObjectNode create(String account, String kind, String id, JsonNode request) {
ResourceKind resourceKind = ResourceKind.fromPath(kind);
if (id == null || !id.matches("[A-Za-z0-9_-]{1,2048}")) {
throw invalid("Resource identifier is required and must contain letters, numbers, underscores or hyphens.");
}
String key = key(account, kind, id);
if (resources.getForAccount(account, key).isPresent()) {
throw new AwsException("ResourceExistsException", "Resource already exists: " + id, 409);
}
String idField = resourceKind.idField;
String name = required(request, "Name");
ObjectNode resource = mapper.createObjectNode();
resource.put(idField, id).put("Name", name).put("Arn", arn(account, kind, id));
double now = clock.instant().toEpochMilli() / 1000.0;
resource.put("CreatedTime", now).put("LastUpdatedTime", now);
resource.set("Permissions", request.path("Permissions").isArray() ? request.path("Permissions").deepCopy() : mapper.createArrayNode());
switch (resourceKind) {
case DASHBOARD -> {
JsonNode definition = request.path("Definition");
if (!definition.isObject()) {
throw invalid("Definition is required; template-based creation is not supported.");
}
ArrayNode dataSets = mapper.createArrayNode();
for (JsonNode declaration : definition.path("DataSetIdentifierDeclarations")) {
String dataSetArn = required(declaration, "DataSetArn");
String dataSetId = dataSetArn.substring(dataSetArn.lastIndexOf('/') + 1);
if (!arn(account, "dataset", dataSetId).equals(dataSetArn)) {
throw invalid("DataSetArn must reference a data set in this account and region.");
}
get(account, "dataset", dataSetId);
dataSets.add(dataSetArn);
}
ObjectNode version = mapper.createObjectNode().put("VersionNumber", 1).put("Status", "CREATION_SUCCESSFUL").put("CreatedTime", now);
version.set("DataSetArns", dataSets);
resource.set("Version", version);
resource.set("Definition", definition.deepCopy());
resource.put("LastPublishedTime", now).put("PublishedVersionNumber", 1);
}
case DATA_SET -> {
String mode = required(request, "ImportMode");
if (!List.of("SPICE", "DIRECT_QUERY").contains(mode)) {
throw invalid("ImportMode must be SPICE or DIRECT_QUERY.");
}
if (!request.path("PhysicalTableMap").isObject() || request.path("PhysicalTableMap").isEmpty()) {
throw invalid("PhysicalTableMap is required.");
}
resource.put("ImportMode", mode);
resource.set("PhysicalTableMap", request.path("PhysicalTableMap").deepCopy());
resource.set("LogicalTableMap", request.path("LogicalTableMap").deepCopy());
}
case DATA_SOURCE -> {
resource.put("Type", required(request, "Type")).put("Status", "CREATION_SUCCESSFUL");
resource.set("DataSourceParameters", request.path("DataSourceParameters").deepCopy());
}
}
resources.putForAccount(account, key, new QuickSightResource(resource));
ObjectNode response = response(resourceKind.createStatus).put("Arn", resource.path("Arn").asText()).put(idField, id);
if (resourceKind == ResourceKind.DASHBOARD) {
response.put("CreationStatus", "CREATION_SUCCESSFUL").put("VersionArn", resource.path("Arn").asText() + "/version/1");
} else if (resourceKind == ResourceKind.DATA_SOURCE) {
response.put("CreationStatus", "CREATION_SUCCESSFUL");
}
return response;
}
public ObjectNode describe(String account, String kind, String id) {
ResourceKind resourceKind = ResourceKind.fromPath(kind);
ObjectNode resource = get(account, kind, id);
resource.remove("Permissions");
resource.remove("Definition");
return response(200).set(resourceKind.responseField, resource);
}
public synchronized ObjectNode delete(String account, String kind, String id) {
ResourceKind resourceKind = ResourceKind.fromPath(kind);
ObjectNode resource = get(account, kind, id);
resources.deleteForAccount(account, key(account, kind, id));
if (resourceKind == ResourceKind.DATA_SET) {
String prefix = key(account, "ingestion", id + "/");
resources.keysForAccount(account).stream().filter(value -> value.startsWith(prefix))
.forEach(value -> resources.deleteForAccount(account, value));
}
return response(200).put("Arn", resource.path("Arn").asText()).put(resourceKind.idField, id);
}
public synchronized ObjectNode registerUser(String account, String namespace, JsonNode request) {
String name = required(request, "UserName");
if (!List.of("READER", "AUTHOR", "ADMIN").contains(required(request, "UserRole"))) {
throw invalid("Unsupported UserRole.");
}
if (!"QUICKSIGHT".equals(required(request, "IdentityType"))) {
throw invalid("Only QUICKSIGHT identity registration is supported.");
}
String id = namespace + "/" + name;
if (resources.getForAccount(account, key(account, "user", id)).isPresent()) {
throw new AwsException("ResourceExistsException", "User already registered.", 409);
}
ObjectNode user = mapper.createObjectNode().put("Arn", arn(account, "user", id))
.put("UserName", name).put("Email", required(request, "Email"))
.put("Role", request.path("UserRole").asText()).put("IdentityType", "QUICKSIGHT")
.put("Active", true).put("PrincipalId", UUID.randomUUID().toString());
resources.putForAccount(account, key(account, "user", id), new QuickSightResource(user));
return response(201).set("User", user.deepCopy());
}
public ObjectNode describeUser(String account, String namespace, String name) {
return response(200).set("User", get(account, "user", namespace + "/" + name));
}
public ObjectNode searchDashboards(String account, JsonNode request) {
JsonNode filters = request.path("Filters");
if (!filters.isArray() || filters.size() != 1
|| !"QUICKSIGHT_USER".equals(filters.path(0).path("Name").asText())
|| !"StringEquals".equals(filters.path(0).path("Operator").asText())) {
throw invalid("Search requires one QUICKSIGHT_USER StringEquals filter.");
}
String principal = required(filters.path(0), "Value");
requireRegisteredUser(account, principal);
String prefix = key(account, "dashboard", "");
List<ObjectNode> found = resources.scanForAccount(account, value -> value.startsWith(prefix)).stream()
.map(QuickSightResource::document).filter(value -> canRead(value, principal))
.map(value -> {
ObjectNode summary = value.deepCopy();
summary.remove(List.of("Version", "Definition", "Permissions"));
return summary;
}).toList();
Integer maximum = Pagination.parseMaxResults(request, "MaxResults", "InvalidParameterValueException");
return page(found, maximum == null ? 100 : maximum,
Pagination.parseNextToken(request, "NextToken", "InvalidNextTokenException"),
account + ":" + regions.getRegion() + ":dashboards:" + Base64Url.encode(principal),
"DashboardSummaryList", value -> value.path("DashboardId").asText());
}
public synchronized ObjectNode createIngestion(String account, String dataSetId, String id, JsonNode request) {
ObjectNode dataSet = get(account, "dataset", dataSetId);
if (!"SPICE".equals(dataSet.path("ImportMode").asText())) {
throw invalid("Ingestions require a SPICE data set.");
}
String ingestionKey = key(account, "ingestion", dataSetId + "/" + id);
if (resources.getForAccount(account, ingestionKey).isPresent()) {
throw new AwsException("ResourceExistsException", "Ingestion already exists.", 409);
}
String type = request.path("IngestionType").asText("FULL_REFRESH");
if (!List.of("FULL_REFRESH", "INCREMENTAL_REFRESH").contains(type)) {
throw invalid("Unsupported IngestionType.");
}
ObjectNode ingestion = mapper.createObjectNode().put("IngestionId", id)
.put("Arn", arn(account, "dataset", dataSetId) + "/ingestion/" + id)
.put("CreatedTime", clock.instant().toEpochMilli() / 1000.0).put("IngestionStatus", "COMPLETED")
.put("IngestionTimeInSeconds", 0).put("IngestionSizeInBytes", 0)
.put("RequestType", type)
.put("RequestSource", "MANUAL");
ingestion.set("RowInfo", mapper.createObjectNode().put("RowsIngested", 0).put("RowsDropped", 0).put("TotalRowsInDataset", 0));
resources.putForAccount(account, ingestionKey, new QuickSightResource(ingestion));
return response(201).put("Arn", ingestion.path("Arn").asText()).put("IngestionId", id).put("IngestionStatus", "COMPLETED");
}
public ObjectNode listIngestions(String account, String id, int maximum, String token) {
get(account, "dataset", id);
String prefix = key(account, "ingestion", id + "/");
List<ObjectNode> found = resources.scanForAccount(account, value -> value.startsWith(prefix)).stream()
.map(QuickSightResource::document)
.map(ObjectNode::deepCopy).toList();
return page(found, maximum, token, account + ":" + regions.getRegion() + ":ingestions:" + id,
"Ingestions", QuickSightService::ingestionCursor);
}
public ObjectNode describeIngestion(String account, String dataSetId, String id) {
get(account, "dataset", dataSetId);
return response(200).set("Ingestion", get(account, "ingestion", dataSetId + "/" + id));
}
@Override
public String namespace() {
return "quicksight";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
if ("user".equals(type) && names.size() == 3) {
return Optional.of(regions.buildArn("quicksight", region, names.getFirst(),
"user/" + names.get(1) + "/" + names.get(2)));
}
return Optional.empty();
}
public synchronized ObjectNode generateEmbedUrl(String account, JsonNode request) {
String principal = required(request, "UserArn");
requireRegisteredUser(account, principal);
String id = required(request.path("ExperienceConfiguration").path("Dashboard"), "InitialDashboardId");
ObjectNode dashboard = get(account, "dashboard", id);
if (!canRead(dashboard, principal)) {
throw new AwsException("AccessDeniedException", "User does not have permission to view this dashboard.", 401);
}
long lifetime = request.path("SessionLifetimeInMinutes").asLong(600);
if (lifetime < 15 || lifetime > 600) {
throw new AwsException("SessionLifetimeInMinutesInvalidException", "SessionLifetimeInMinutes must be between 15 and 600.", 400);
}
ArrayNode domains = mapper.createArrayNode();
JsonNode requested = request.path("AllowedDomains");
if (!requested.isMissingNode() && (!requested.isArray() || requested.isEmpty() || requested.size() > 3)) {
throw invalid("AllowedDomains must contain between one and three origins.");
}
for (JsonNode domain : requested) {
URI origin;
try {
origin = URI.create(domain.asText());
} catch (IllegalArgumentException exception) {
throw invalid("Invalid allowed domain.");
}
String normalized = QuickSightOrigins.normalize(origin);
if (normalized.isEmpty() || !("https".equalsIgnoreCase(origin.getScheme())
|| "http".equalsIgnoreCase(origin.getScheme()) && "localhost".equalsIgnoreCase(origin.getHost()))
|| origin.getRawQuery() != null || origin.getRawFragment() != null
|| origin.getPath() != null && !origin.getPath().isEmpty() && !origin.getPath().equals("/")) {
throw invalid("AllowedDomains must contain HTTPS origins or HTTP localhost.");
}
domains.add(normalized);
}
String token = account + "-" + UUID.randomUUID();
ObjectNode session = mapper.createObjectNode().put("account", account).put("region", regions.getRegion())
.put("dashboard", id).put("user", principal).put("redeemUntil", clock.instant().getEpochSecond() + 300)
.put("lifetime", lifetime).put("redeemed", false);
session.set("domains", domains);
sessions.putForAccount(account, token, new QuickSightResource(session));
return response(200).put("EmbedUrl", embedBaseUrl + "/embed/" + token + "/dashboards/" + id + "?code=" + token);
}
public synchronized ObjectNode redeem(String token, String code, String id, String origin, String sessionCookie) {
String account = token.length() > 12 ? token.substring(0, 12) : "";
ObjectNode session = sessions.getForAccount(account, token).map(QuickSightResource::document).map(ObjectNode::deepCopy)
.orElseThrow(() -> denied("Invalid embedding session."));
long now = clock.instant().getEpochSecond();
if (!id.equals(session.path("dashboard").asText())) {
throw denied("Dashboard does not match embedding session.");
}
if (!session.path("domains").isEmpty() && !originAllowed(session.path("domains"), origin)) {
throw denied("Embedding origin is not allowed.");
}
ObjectNode dashboard = resources.getForAccount(account, session.path("region").asText() + "/" + account
+ "/dashboard/" + id).map(QuickSightResource::document).map(ObjectNode::deepCopy)
.orElseThrow(() -> missing(id));
if (!canRead(dashboard, session.path("user").asText())) {
throw denied("User does not have permission to view this dashboard.");
}
if (session.path("redeemed").asBoolean()) {
if (!session.path("cookie").asText().equals(sessionCookie) || now >= session.path("expires").asLong()) {
throw denied("Embedding URL has already been redeemed or session expired.");
}
} else {
if (!token.equals(code) || now >= session.path("redeemUntil").asLong()) {
throw denied("Embedding URL has expired.");
}
session.put("redeemed", true).put("cookie", UUID.randomUUID().toString())
.put("expires", now + session.path("lifetime").asInt() * 60L);
sessions.putForAccount(account, token, new QuickSightResource(session));
}
ArrayNode allowedOrigins = mapper.createArrayNode();
for (JsonNode domain : session.path("domains")) {
String normalized = QuickSightOrigins.fromUrl(domain.asText());
if (!normalized.isEmpty()) {
allowedOrigins.add(normalized);
}
}
return dashboard.put("_SessionCookie", session.path("cookie").asText()).set("_AllowedOrigins", allowedOrigins);
}
public synchronized int cleanupExpiredSessions(Instant now) {
long deadline = now.getEpochSecond();
return sessions.deleteAllAccountsMatching(resource -> {
ObjectNode session = resource.document();
String expiryField = session.path("redeemed").asBoolean() ? "expires" : "redeemUntil";
return session.path(expiryField).asLong() <= deadline;
});
}
private void requireRegisteredUser(String account, String principal) {
String userPrefix = arn(account, "user", "");
if (!principal.startsWith(userPrefix)) {
throw new AwsException("AccessDeniedException", "UserArn must belong to this account and region.", 401);
}
get(account, "user", principal.substring(userPrefix.length()));
}
private boolean originAllowed(JsonNode domains, String origin) {
String normalized = QuickSightOrigins.fromUrl(origin);
for (JsonNode domain : domains) {
if (!normalized.isEmpty() && QuickSightOrigins.fromUrl(domain.asText()).equals(normalized)) {
return true;
}
}
return false;
}
private boolean canRead(ObjectNode resource, String principal) {
for (JsonNode permission : resource.path("Permissions")) {
if (principal.equals(permission.path("Principal").asText())) {
for (JsonNode action : permission.path("Actions")) {
if ("quicksight:DescribeDashboard".equals(action.asText())) {
return true;
}
}
}
}
return false;
}
private ObjectNode page(List<ObjectNode> found, int maximum, String token, String scope, String field,
Function<ObjectNode, String> cursorOf) {
if (maximum < 1 || maximum > 100) {
throw invalid("MaxResults must be between 1 and 100.");
}
PaginatedResult<ObjectNode> page = Pagination.paginate(found, cursorOf, maximum, token, scope,
value -> new AwsException("InvalidNextTokenException", "NextToken is invalid for this request.", 400));
ObjectNode result = response(200);
result.set(field, mapper.valueToTree(page.items()));
if (page.nextToken() != null) {
result.put("NextToken", page.nextToken());
}
return result;
}
private static String ingestionCursor(ObjectNode ingestion) {
// Invert epoch milliseconds so the shared ascending cursor lists newest first.
long descendingTime = Long.MAX_VALUE - Math.round(ingestion.path("CreatedTime").asDouble() * 1000);
return "%019d:%s".formatted(descendingTime, ingestion.path("IngestionId").asText());
}
private ObjectNode get(String account, String kind, String id) {
return resources.getForAccount(account, key(account, kind, id)).map(QuickSightResource::document).map(ObjectNode::deepCopy)
.orElseThrow(() -> missing(id));
}
private String key(String account, String kind, String id) {
if (account == null || !account.matches("[0-9]{12}")) {
throw invalid("AwsAccountId must contain 12 digits.");
}
if (id == null || id.contains("..")) {
throw invalid("Invalid resource identifier.");
}
return regions.getRegion() + "/" + account + "/" + kind + "/" + id;
}
private String arn(String account, String kind, String id) {
return regions.buildArn("quicksight", regions.getRegion(), account, kind + "/" + id);
}
private enum ResourceKind {
DASHBOARD("dashboard", "DashboardId", "Dashboard", 202),
DATA_SET("dataset", "DataSetId", "DataSet", 201),
DATA_SOURCE("datasource", "DataSourceId", "DataSource", 202);
private final String path;
private final String idField;
private final String responseField;
private final int createStatus;
ResourceKind(String path, String idField, String responseField, int createStatus) {
this.path = path;
this.idField = idField;
this.responseField = responseField;
this.createStatus = createStatus;
}
private static ResourceKind fromPath(String path) {
for (ResourceKind kind : values()) {
if (kind.path.equals(path)) {
return kind;
}
}
throw invalid("Unsupported resource kind.");
}
}
private ObjectNode response(int status) {
return mapper.createObjectNode().put("Status", status).put("RequestId", UUID.randomUUID().toString());
}
private static String required(JsonNode input, String name) {
JsonNode value = input.path(name);
if (!value.isTextual() || value.asText().isBlank()) {
throw invalid(name + " is required.");
}
return value.asText();
}
private static AwsException invalid(String message) {
return new AwsException("InvalidParameterValueException", message, 400);
}
private static AwsException denied(String message) {
return new AwsException("AccessDeniedException", message, 403);
}
private static AwsException missing(String id) {
return new AwsException("ResourceNotFoundException", "Resource not found: " + id, 404);
}
@Override
public synchronized void clear() {
resources.clear();
sessions.clear();
}
}
@@ -0,0 +1,18 @@
package io.github.hectorvent.floci.services.quicksight;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.SweepScheduler;
import io.github.hectorvent.floci.core.common.SweepWorker;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@ApplicationScoped
public class QuickSightSessionExpirationScheduler extends SweepScheduler {
private static final long SWEEP_INTERVAL_SECONDS = 60;
@Inject
public QuickSightSessionExpirationScheduler(QuickSightService service, EmulatorConfig config) {
super(new SweepWorker("quicksight-session-expiration", config.services().quicksight().enabled(),
SWEEP_INTERVAL_SECONDS, true, service::cleanupExpiredSessions));
}
}
@@ -0,0 +1,7 @@
package io.github.hectorvent.floci.services.quicksight.model;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public record QuickSightResource(ObjectNode document) {}