mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(glue): check the Iceberg REST endpoint's routes under IAM enforcement (#8548)
No botocore model describes AWS Glue's Iceberg REST endpoint, so no
vendored route mapped its paths to an action, and the endpoint refused
every IAM principal under enforcement, letting only root credentials
and Floci's own query engine through.
- regen_rest_routes.py reads an endpoint botocore does not model from
the AWS page documenting it (DOCUMENTED): Glue's "REST APIs for Apache
Iceberg specifications" gives each operation's REST path, IAM action,
CloudTrail event and a link to its definition in the Apache Iceberg
REST catalog OpenAPI specification. Each row of the Iceberg REST
Catalog API is the Glue operation its IAM action and CloudTrail event
name, refused when they differ, on the method and path of the
definition it links, under the root and the catalogs/{catalog} prefix
the page's path gives. Rows of one operation are its route and its
alternatives. Where the page's own path differs from the definition
(DeleteNamespace's "namespces", CreateTable's GET), the definition is
taken and the difference recorded. Nothing is typed by hand.
- Reading the page needs the network, so a regeneration carries the
routes over from the vendored file, --fetch-documented reads them
again, and --verify checks them against the page;
documented-routes-verify runs in iam-data-verify.
- rest-routes.json gains the endpoint's ten Glue operations under the
glue scope, and iam-authorized-actions.json lists glue's actions of
no resource type, as it does for every routed scope. The same
regeneration takes the actions AWS has added since: GuardDuty's
ListInvestigationRecords and Route 53's IP guardrail policy actions.
- The controller's refusal of IAM principals goes. Each route is now
checked as its Glue operation, on the account's Data Catalog whichever
catalog the prefix names: the request-resource table reads no Glue
member from an Iceberg request, so a grant or deny scoped to a
federated catalog, a database or a table does not apply here.
Floci's own engine's token is not checked again.
- A request a documented route takes is another API's, so it carries
none of its operation's members: the enforcement filter has every
member reader (request resources, condition keys, tag-on-create,
passed roles) read none from it, so a Glue member a caller adds to an
Iceberg body, such as Tags or DatabaseInput, names no resource and
gives no condition key a value.
GlueIcebergIamIntegrationTest checks a principal allowed GetCatalog and
GetDatabase reading the configuration and the namespaces and refused
creating a namespace or loading a table, by GET or HEAD, a deny on the
catalog holding under an allow on everything, and root credentials and
a minted token answered, and a Glue member added to an Iceberg body
neither satisfying an aws:RequestTag condition nor naming a database.
glue.md and iam.md say so.
This commit is contained in:
1 parent
9392bd54af
commit
0b6077d374
15 files changed
+754
-138
No files matched your search
@@ -603,6 +603,8 @@ S3CONTROL_TAG_CONDITION_KEYS_PATHS := src/main/resources/aws/s3control-tag-condi
|
||||
REQUEST_CONDITION_KEYS_PATHS := src/main/resources/aws/request-condition-keys.json \
|
||||
tools/aws/regen_request_condition_keys.py tools/aws/test_regen_request_condition_keys.py \
|
||||
tools/aws/regen_dynamodb_condition_keys.py tools/aws/regen_iam_tag_on_create.py $(IAM_PASSED_ROLES_GENERATOR)
|
||||
DOCUMENTED_ROUTES_PATHS := src/main/resources/aws/rest-routes.json tools/aws/regen_rest_routes.py \
|
||||
tools/aws/test_regen_rest_routes.py
|
||||
IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json \
|
||||
tools/aws/regen_iam_request_resources.py $(IAM_PASSED_ROLES_GENERATOR) \
|
||||
tools/aws/test_regen_iam_request_resources.py
|
||||
@@ -611,7 +613,7 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A
|
||||
@# Every check runs even when an earlier one fails, so one file's drift cannot hide another's
|
||||
@# state. Sequential steps in CI stop at the first failure, which once left the action
|
||||
@# resource gate unexercised while the namespace list was stale.
|
||||
@namespaces=0; actions=0; authorized=0; passed=0; connectors=0; tagged=0; requested=0; dynamodb=0; conditionkeys=0; s3control=0; requestkeys=0; \
|
||||
@namespaces=0; actions=0; authorized=0; passed=0; connectors=0; tagged=0; requested=0; dynamodb=0; conditionkeys=0; s3control=0; requestkeys=0; routes=0; \
|
||||
covers() { \
|
||||
[ -z "$(strip $(CHANGED))" ] && return 0; \
|
||||
for path in $(CHANGED); do case " $$1 " in *" $$path "*) return 0;; esac; done; \
|
||||
@@ -651,9 +653,12 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A
|
||||
if covers "$(REQUEST_CONDITION_KEYS_PATHS)" "the request condition key table"; then \
|
||||
$(MAKE) --no-print-directory request-condition-keys-verify || requestkeys=$$?; \
|
||||
fi; \
|
||||
if covers "$(DOCUMENTED_ROUTES_PATHS)" "the REST routes AWS documents for endpoints botocore does not model"; then \
|
||||
$(MAKE) --no-print-directory documented-routes-verify || routes=$$?; \
|
||||
fi; \
|
||||
if [ $$namespaces -ne 0 ] || [ $$actions -ne 0 ] || [ $$authorized -ne 0 ] || [ $$passed -ne 0 ] \
|
||||
|| [ $$connectors -ne 0 ] || [ $$tagged -ne 0 ] || [ $$requested -ne 0 ] || [ $$dynamodb -ne 0 ] \
|
||||
|| [ $$conditionkeys -ne 0 ] || [ $$s3control -ne 0 ] || [ $$requestkeys -ne 0 ]; then \
|
||||
|| [ $$conditionkeys -ne 0 ] || [ $$s3control -ne 0 ] || [ $$requestkeys -ne 0 ] || [ $$routes -ne 0 ]; then \
|
||||
echo ""; \
|
||||
echo "error: vendored IAM data does not match upstream:"; \
|
||||
if [ $$namespaces -ne 0 ]; then \
|
||||
@@ -681,6 +686,7 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A
|
||||
if [ $$conditionkeys -ne 0 ]; then echo " the IAM condition key table"; fi; \
|
||||
if [ $$s3control -ne 0 ]; then echo " the S3 Control tag condition key table"; fi; \
|
||||
if [ $$requestkeys -ne 0 ]; then echo " the request condition key table"; fi; \
|
||||
if [ $$routes -ne 0 ]; then echo " the REST routes AWS documents, see its message above"; fi; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
@@ -920,3 +926,9 @@ request-condition-keys-check: ## Check the request condition key members against
|
||||
$(PYTHON) tools/aws/regen_request_condition_keys.py --check
|
||||
request-condition-keys-verify: ## Check the request condition action keys against AWS
|
||||
$(PYTHON) tools/aws/regen_request_condition_keys.py --verify
|
||||
|
||||
.PHONY: documented-routes-sync documented-routes-verify
|
||||
documented-routes-sync: ## Read the REST routes AWS documents for endpoints botocore does not model again (commit the result)
|
||||
$(PYTHON) tools/aws/regen_rest_routes.py --fetch-documented
|
||||
documented-routes-verify: ## CI gate (online): the vendored documented REST routes must still be the ones AWS's pages give
|
||||
$(PYTHON) tools/aws/regen_rest_routes.py --verify
|
||||
@@ -353,7 +353,9 @@ The operations are the twelve AWS lists: `GetConfig`, `ListNamespaces`, `CreateN
|
||||
|
||||
A table bucket federated from Amazon S3 Tables (see [Catalogs and Amazon S3 Tables](#catalogs-and-amazon-s3-tables)) is a catalog of this endpoint too: the warehouse `<account>:s3tablescatalog/<bucket>` configures the prefix `catalogs/<account>:s3tablescatalog:<bucket>` (levels joined by `:`, as AWS's route table writes nested catalogs; `s3tablescatalog:<bucket>` names the caller's own). Its namespaces and tables are the bucket's: S3 Tables decides where a table lives, so a create names no location (a staged create already creates the table, empty, at its warehouse location), namespaces take no properties (Spark's `owner` is let go), no commit moves a table out of its warehouse, each commit moves the table's metadata location with S3 Tables' version token (a stale one answering `CommitFailedException`), a table a staged create holds is listed only once committed, and dropping a table deletes its warehouse, data and all, as S3 Tables' `DeleteTable` does.
|
||||
|
||||
Not yet: IAM policies are not checked on this endpoint, so under IAM enforcement it answers only the account's root credentials and Floci's own query engine, and refuses IAM principals (`ForbiddenException`, 403) rather than let them through unchecked. Other accounts' catalogs are not served. DuckDB signs SigV4 catalog requests only over HTTPS, so DuckDB attaches this endpoint with SigV4 only when Floci serves TLS (`floci.tls.enabled`).
|
||||
Under IAM enforcement, each route is checked as the Glue operation AWS's [Glue Developer Guide](https://docs.aws.amazon.com/glue/latest/dg/iceberg-rest-apis.html) documents it as, its IAM action and CloudTrail event: `GetConfig` as `glue:GetCatalog`, `ListNamespaces` and `LoadNamespaceMetadata` as `glue:GetDatabase`, `CreateNamespace` as `glue:CreateDatabase`, `UpdateNamespaceProperties` as `glue:UpdateDatabase`, `DeleteNamespace` as `glue:DeleteDatabase`, `ListTables` as `glue:GetTables`, `CreateTable` as `glue:CreateTable`, `LoadTable` and `TableExists` as `glue:GetTable`, `UpdateTable` as `glue:UpdateTable`, and `DeleteTable` as `glue:DeleteTable`. Each is checked on the account's Data Catalog, `arn:aws:glue:<region>:<account>:catalog`, whichever catalog the prefix names: nothing AWS publishes says which Glue member an Iceberg path's prefix, namespace or table fills, so a grant or a deny scoped to a federated catalog, a database or a table does not apply on this endpoint. A Glue member a caller adds to an Iceberg request's body, such as `DatabaseInput` or `Tags`, is not read either: it names no resource and gives no condition key a value. Lake Formation permissions are not checked. The token Floci's own query engine attaches with is not checked again, Athena having checked its caller.
|
||||
|
||||
Not yet: Other accounts' catalogs are not served. DuckDB signs SigV4 catalog requests only over HTTPS, so DuckDB attaches this endpoint with SigV4 only when Floci serves TLS (`floci.tls.enabled`).
|
||||
|
||||
## Catalogs and Amazon S3 Tables
|
||||
|
||||
|
||||
@@ -2275,7 +2275,15 @@ OpenSearch Service's `ListDomainNames`, `ListVersions` and VPC endpoint operatio
|
||||
versions, Access Analyzer's `ListAnalyzers` and `ValidatePolicy`, and GuardDuty's operations of no
|
||||
resource type are checked by their routes, and so are OpenSearch Service's domain operations, Access
|
||||
Analyzer's analyzer operations, Security Hub's hub operations and GuardDuty's detector operations, the
|
||||
table of request resources reading the resource they name. Every route Floci serves of AWS Lake
|
||||
table of request resources reading the resource they name. AWS Glue's Iceberg REST endpoint, which no botocore
|
||||
model describes, is routed by the routes AWS's Glue Developer Guide documents for it: each row of its page is the
|
||||
Glue operation its IAM action and CloudTrail event name, on the method and path of the Apache Iceberg REST catalog
|
||||
operation the row links, so `CreateTable` is `glue:CreateTable` on `POST
|
||||
/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}/tables`, the page's own `GET` aside. A regeneration carries
|
||||
these routes over, `tools/aws/regen_rest_routes.py --fetch-documented` reads them again and `--verify` checks them
|
||||
against the page. A request these routes take is Apache Iceberg's and carries none of the Glue operation's members,
|
||||
so nothing reads one from it, not the table of request resources, a condition key or a create's tags: each route is
|
||||
checked on the account's catalog, and a Glue member a caller adds to an Iceberg body names nothing. Every route Floci serves of AWS Lake
|
||||
Formation and Amazon Inspector is one AWS authorizes on no resource type, as is every one of Amazon Macie's but
|
||||
`CreateMember`, so those are checked by their routes alone. `CreateMember`, on `POST /members`, is checked on the
|
||||
account's members, `member/*`, as nothing botocore or the Service Reference says names the member it makes by its
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsCrossAccountService;
|
||||
@@ -80,6 +81,8 @@ public class IamConditionContextResolver {
|
||||
/** Set by {@code ResourceArnBuilder.readJsonBody}, which runs earlier in the same filter pass. */
|
||||
static final String BUFFERED_JSON_BODY = "floci.bufferedJsonBody";
|
||||
private static final String BUFFERED_FORM_BODY = "floci.bufferedFormBody";
|
||||
/** Set on a request that carries none of its operation's members, see {@link #readNoMembers}. */
|
||||
private static final String NO_MEMBERS = "floci.noRequestMembers";
|
||||
/** Prefixes the action whose numbered EC2 targets {@link #heldTargets} looked up for the request. */
|
||||
private static final String HELD_TARGETS = "floci.heldTargets.";
|
||||
private static final String REQUEST_TAG_PREFIX = "aws:RequestTag/";
|
||||
@@ -1195,6 +1198,21 @@ public class IamConditionContextResolver {
|
||||
|
||||
// ── Request body access ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Has every reader of the request's members read none from it: its JSON body reads as one naming nothing, and its
|
||||
* form, its raw body and a Query request's parameters as absent. A request a route AWS documents outside botocore
|
||||
* takes is another API's, so a member its body gives was added by the caller, naming a resource or giving a
|
||||
* condition key a value its handler never acts on.
|
||||
*/
|
||||
static void readNoMembers(ContainerRequestContext ctx) {
|
||||
ctx.setProperty(NO_MEMBERS, Boolean.TRUE);
|
||||
ctx.setProperty(BUFFERED_JSON_BODY, JsonNodeFactory.instance.objectNode());
|
||||
}
|
||||
|
||||
private static boolean carriesNoMembers(ContainerRequestContext ctx) {
|
||||
return Boolean.TRUE.equals(ctx.getProperty(NO_MEMBERS));
|
||||
}
|
||||
|
||||
/**
|
||||
* The decoded form parameters of a Query-protocol request, buffered once per request and
|
||||
* restored for the controller that reads the form next. A repeated key keeps its first
|
||||
@@ -1203,6 +1221,9 @@ public class IamConditionContextResolver {
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
static Map<String, String> formParameters(ContainerRequestContext ctx) {
|
||||
if (carriesNoMembers(ctx)) {
|
||||
return Map.of();
|
||||
}
|
||||
if ("GET".equalsIgnoreCase(ctx.getMethod()) && IamActionRegistry.isQueryRequest(ctx)) {
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
ctx.getUriInfo().getQueryParameters().forEach((key, values) -> {
|
||||
@@ -1242,8 +1263,14 @@ public class IamConditionContextResolver {
|
||||
return parameters;
|
||||
}
|
||||
|
||||
/** Reads the entity fully and puts an equivalent stream back for downstream readers. */
|
||||
/**
|
||||
* Reads the entity fully and puts an equivalent stream back for downstream readers; none for a request that
|
||||
* carries no members, whose entity is left to its handler.
|
||||
*/
|
||||
static byte[] bufferEntity(ContainerRequestContext ctx) {
|
||||
if (carriesNoMembers(ctx)) {
|
||||
return null;
|
||||
}
|
||||
InputStream in = ctx.getEntityStream();
|
||||
if (in == null) {
|
||||
return null;
|
||||
|
||||
@@ -399,6 +399,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
ResolvedAuthorization resolvedAuthorization = resolveAuthorization(auth, claimedScope, ctx);
|
||||
String credentialScope = resolvedAuthorization.credentialScope();
|
||||
String action = resolvedAuthorization.action();
|
||||
if (IamActionRegistry.takenByDocumentedRoute(credentialScope, ctx)) {
|
||||
// Another API's request (Glue's Iceberg REST endpoint takes Apache Iceberg's) carries none of the
|
||||
// operation's members, so none is read from it: not its resources, condition keys, tags or roles.
|
||||
IamConditionContextResolver.readNoMembers(ctx);
|
||||
}
|
||||
if (action == null) {
|
||||
if (!"OPTIONS".equalsIgnoreCase(ctx.getMethod())
|
||||
&& iamService.presignedScope(akid).isPresent()) {
|
||||
|
||||
@@ -2,8 +2,6 @@ package io.floci.aws.services.glue.iceberg;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RequestContext;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
@@ -23,11 +21,10 @@ import jakarta.ws.rs.core.Response;
|
||||
* Apache Iceberg REST catalog specification AWS lists for it, under the {@code /v1/catalogs/{catalog}} prefix.
|
||||
* {@link GlueIcebergRouteFilter} moves requests signed for Glue onto {@link GlueIcebergRouteFilter#INTERNAL_PREFIX}.
|
||||
*
|
||||
* <p>Under IAM enforcement, no rule maps these routes to the Glue actions AWS checks for them yet, and an unmapped REST
|
||||
* route is allowed, so an IAM principal is refused here rather than let through unchecked: only the account's root
|
||||
* credentials, and a bearer token Floci minted for its own query engine, reach the catalog then. The check sits at
|
||||
* this entry point, not in {@link GlueIcebergCatalog}, because Floci's Athena calls the catalog directly for a caller
|
||||
* IAM already checked.
|
||||
* <p>Under IAM enforcement each route is checked as the Glue operation AWS's Glue Developer Guide documents it as, its
|
||||
* IAM action and CloudTrail event, from the routes vendored in {@code aws/rest-routes.json}, before it reaches this
|
||||
* controller. A bearer token Floci minted for its own query engine is not checked again: Floci's Athena hands it to
|
||||
* the engine for a caller IAM already checked.
|
||||
*/
|
||||
@Path(GlueIcebergRouteFilter.INTERNAL_PREFIX + GlueIcebergRouteFilter.ICEBERG_PATH + "/v1")
|
||||
@ApplicationScoped
|
||||
@@ -36,80 +33,76 @@ import jakarta.ws.rs.core.Response;
|
||||
public class GlueIcebergController {
|
||||
|
||||
private final GlueIcebergCatalog catalog;
|
||||
private final EmulatorConfig config;
|
||||
private final RequestContext requestContext;
|
||||
|
||||
@Inject
|
||||
public GlueIcebergController(GlueIcebergCatalog catalog, EmulatorConfig config, RequestContext requestContext) {
|
||||
public GlueIcebergController(GlueIcebergCatalog catalog) {
|
||||
this.catalog = catalog;
|
||||
this.config = config;
|
||||
this.requestContext = requestContext;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/config")
|
||||
public ObjectNode getConfig(@QueryParam("warehouse") String warehouse) {
|
||||
return catalog().config(warehouse);
|
||||
return catalog.config(warehouse);
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/catalogs/{catalog}/namespaces")
|
||||
public ObjectNode listNamespaces(@PathParam("catalog") String catalogId, @QueryParam("parent") String parent) {
|
||||
return catalog().listNamespaces(catalogId, parent);
|
||||
return catalog.listNamespaces(catalogId, parent);
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/catalogs/{catalog}/namespaces")
|
||||
public ObjectNode createNamespace(@PathParam("catalog") String catalogId, JsonNode request) {
|
||||
return catalog().createNamespace(catalogId, request);
|
||||
return catalog.createNamespace(catalogId, request);
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}")
|
||||
public ObjectNode loadNamespaceMetadata(@PathParam("catalog") String catalogId,
|
||||
@PathParam("namespace") String namespace) {
|
||||
return catalog().loadNamespace(catalogId, namespace);
|
||||
return catalog.loadNamespace(catalogId, namespace);
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/properties")
|
||||
public ObjectNode updateNamespaceProperties(@PathParam("catalog") String catalogId,
|
||||
@PathParam("namespace") String namespace, JsonNode request) {
|
||||
return catalog().updateNamespaceProperties(catalogId, namespace, request);
|
||||
return catalog.updateNamespaceProperties(catalogId, namespace, request);
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}")
|
||||
public Response dropNamespace(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace) {
|
||||
catalog().dropNamespace(catalogId, namespace);
|
||||
catalog.dropNamespace(catalogId, namespace);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/tables")
|
||||
public ObjectNode listTables(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace) {
|
||||
return catalog().listTables(catalogId, namespace);
|
||||
return catalog.listTables(catalogId, namespace);
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/tables")
|
||||
public ObjectNode createTable(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace,
|
||||
JsonNode request) {
|
||||
return catalog().createTable(catalogId, namespace, request);
|
||||
return catalog.createTable(catalogId, namespace, request);
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/tables/{table}")
|
||||
public ObjectNode loadTable(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace,
|
||||
@PathParam("table") String table, @QueryParam("snapshots") String snapshots) {
|
||||
return catalog().loadTable(catalogId, namespace, table, snapshots);
|
||||
return catalog.loadTable(catalogId, namespace, table, snapshots);
|
||||
}
|
||||
|
||||
@HEAD
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/tables/{table}")
|
||||
public Response tableExists(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace,
|
||||
@PathParam("table") String table) {
|
||||
catalog().tableExists(catalogId, namespace, table);
|
||||
catalog.tableExists(catalogId, namespace, table);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
@@ -117,28 +110,14 @@ public class GlueIcebergController {
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/tables/{table}")
|
||||
public ObjectNode updateTable(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace,
|
||||
@PathParam("table") String table, JsonNode request) {
|
||||
return catalog().commitTable(catalogId, namespace, table, request);
|
||||
return catalog.commitTable(catalogId, namespace, table, request);
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/tables/{table}")
|
||||
public Response dropTable(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace,
|
||||
@PathParam("table") String table) {
|
||||
catalog().dropTable(catalogId, namespace, table);
|
||||
catalog.dropTable(catalogId, namespace, table);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
/** The catalog, once the caller is one this endpoint can answer under IAM enforcement. */
|
||||
private GlueIcebergCatalog catalog() {
|
||||
if (config.services().iam().enforcementEnabled()) {
|
||||
String accessKeyId = requestContext.getAccessKeyId();
|
||||
if (accessKeyId != null && !"test".equals(accessKeyId)
|
||||
&& !accessKeyId.equals(requestContext.getAccountId())) {
|
||||
throw new IcebergRestException(403, "ForbiddenException",
|
||||
"AWS Glue's Iceberg REST endpoint does not check IAM policies in Floci yet, so under IAM "
|
||||
+ "enforcement it answers only the account's root credentials");
|
||||
}
|
||||
}
|
||||
return catalog;
|
||||
}
|
||||
}
|
||||
@@ -738,9 +738,28 @@ public class IamActionRegistry {
|
||||
if (credentialScope == null || !routes.routes(credentialScope)) {
|
||||
return Map.of();
|
||||
}
|
||||
return matchedRoute(routes, credentialScope, ctx).map(IamRestRoutes.Match::labels).orElse(Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a request of the credential scope is taken by a route of a model AWS documents on a page of its own
|
||||
* rather than in botocore, as Glue's Iceberg REST endpoint is: such a request is another API's, Apache Iceberg's
|
||||
* REST catalog, so it carries none of its operation's members, and one its body gives was added by the caller.
|
||||
*/
|
||||
public static boolean takenByDocumentedRoute(String credentialScope, ContainerRequestContext ctx) {
|
||||
IamRestRoutes routes = IamRestRoutes.vendored();
|
||||
return credentialScope != null && routes.documents(credentialScope)
|
||||
&& matchedRoute(routes, credentialScope, ctx).map(IamRestRoutes.Match::documented).orElse(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* The vendored route of the credential scope a request's method, path and query match, as {@link #resolveRoute}
|
||||
* matches it.
|
||||
*/
|
||||
private static Optional<IamRestRoutes.Match> matchedRoute(IamRestRoutes routes, String credentialScope,
|
||||
ContainerRequestContext ctx) {
|
||||
return routes.match(credentialScope, ctx.getMethod().toUpperCase(), withoutInternalPrefix(ctx, routedPath(ctx)),
|
||||
ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx))
|
||||
.map(IamRestRoutes.Match::labels).orElse(Map.of());
|
||||
ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,6 +12,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -44,6 +45,11 @@ import java.util.regex.Pattern;
|
||||
* the request carries the members the path no longer holds, and the alternative's own method when it is not the
|
||||
* operation's: API Gateway v1 tags with a PUT, and the shared tags controller's bare path tags with a POST.
|
||||
*
|
||||
* <p>A model AWS documents on a page of its own rather than in botocore (its {@code documented} block, Glue's Iceberg
|
||||
* REST endpoint) routes another API's requests: Apache Iceberg's REST catalog, whose bodies carry none of the Glue
|
||||
* operation's members. A request one of its routes takes is {@link Match#documented}, so nothing reads a member from
|
||||
* it.
|
||||
*
|
||||
* <p>The file is generated by {@code tools/aws/regen_rest_routes.py}, which fails when one route names two
|
||||
* operations of a credential scope read here. The scopes it lists as {@code handRouted} are not read: the
|
||||
* registry's rules authorize them alone. A missing or malformed resource is a build defect, so loading fails with
|
||||
@@ -64,16 +70,19 @@ final class IamRestRoutes {
|
||||
private static final int ONE_SEGMENT = 1;
|
||||
private static final int REST_OF_PATH = 0;
|
||||
|
||||
/** A matched operation, decoded path labels, and generated alternative member locations. */
|
||||
record Match(String operation, Map<String, String> labels, Map<String, String> located) {
|
||||
/**
|
||||
* A matched operation, decoded path labels, generated alternative member locations, and whether the route is a
|
||||
* documented model's, whose request carries none of the operation's members.
|
||||
*/
|
||||
record Match(String operation, Map<String, String> labels, Map<String, String> located, boolean documented) {
|
||||
}
|
||||
|
||||
/**
|
||||
* A route: its operation, its path as a pattern capturing each label in turn, the labels' names, each segment's
|
||||
* rank, and the query it names.
|
||||
* rank, the query it names, the members its alternative locates, and whether its model is a documented one.
|
||||
*/
|
||||
private record Route(String operation, Pattern path, Pattern spanning, List<String> labels, int[] ranks,
|
||||
Map<String, String> query, Map<String, String> located) {
|
||||
Map<String, String> query, Map<String, String> located, boolean documented) {
|
||||
|
||||
/** The route's pattern: each label taking one segment, or, spanning, the segments its value spans. */
|
||||
Pattern pattern(boolean spanned) {
|
||||
@@ -122,10 +131,14 @@ 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;
|
||||
/** The credential scopes a documented model routes. */
|
||||
private final Set<String> documentedScopes;
|
||||
|
||||
private IamRestRoutes(Map<String, Map<String, List<Route>>> routes, Map<String, Integer> accessDeniedStatuses) {
|
||||
private IamRestRoutes(Map<String, Map<String, List<Route>>> routes, Map<String, Integer> accessDeniedStatuses,
|
||||
Set<String> documentedScopes) {
|
||||
this.routes = routes;
|
||||
this.accessDeniedStatuses = accessDeniedStatuses;
|
||||
this.documentedScopes = documentedScopes;
|
||||
}
|
||||
|
||||
/** The vendored routes. */
|
||||
@@ -172,7 +185,8 @@ final class IamRestRoutes {
|
||||
}
|
||||
}
|
||||
return best == null ? Optional.empty()
|
||||
: Optional.of(new Match(best.operation(), best.labelValues(requestPath, spanned), best.located()));
|
||||
: Optional.of(new Match(best.operation(), best.labelValues(requestPath, spanned), best.located(),
|
||||
best.documented()));
|
||||
}
|
||||
|
||||
/** The modelled denial status, or the existing protocol default when the model declares none. */
|
||||
@@ -185,6 +199,11 @@ final class IamRestRoutes {
|
||||
return routes.containsKey(scope);
|
||||
}
|
||||
|
||||
/** Whether a documented model routes requests of the credential scope. */
|
||||
boolean documents(String scope) {
|
||||
return documentedScopes.contains(scope);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a route of the credential scope, of any method, takes the path and query: the path is one of its
|
||||
* model's, whatever method a request sends to it.
|
||||
@@ -204,6 +223,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<>();
|
||||
Set<String> documentedScopes = new HashSet<>();
|
||||
models.properties().forEach(model -> {
|
||||
String scope = model.getValue().path("credentialScope").asText("");
|
||||
JsonNode operations = model.getValue().path("operations");
|
||||
@@ -226,6 +246,15 @@ final class IamRestRoutes {
|
||||
if (skipped.contains(scope)) {
|
||||
return;
|
||||
}
|
||||
JsonNode documentation = model.getValue().path("documented");
|
||||
if (!documentation.isMissingNode() && !documentation.isObject()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " gives model " + model.getKey()
|
||||
+ " an invalid documented block");
|
||||
}
|
||||
boolean documented = documentation.isObject();
|
||||
if (documented) {
|
||||
documentedScopes.add(scope);
|
||||
}
|
||||
operations.properties().forEach(operation -> {
|
||||
String method = operation.getValue().path("method").asText("");
|
||||
String requestUri = operation.getValue().path("requestUri").asText("");
|
||||
@@ -235,7 +264,7 @@ final class IamRestRoutes {
|
||||
}
|
||||
routes.computeIfAbsent(scope, ignored -> new HashMap<>())
|
||||
.computeIfAbsent(method, ignored -> new ArrayList<>())
|
||||
.add(route(operation.getKey(), requestUri, Map.of()));
|
||||
.add(route(operation.getKey(), requestUri, Map.of(), documented));
|
||||
JsonNode alternatives = operation.getValue().path("alternatives");
|
||||
if (!alternatives.isMissingNode() && !alternatives.isArray()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " gives " + operation.getKey()
|
||||
@@ -260,7 +289,7 @@ final class IamRestRoutes {
|
||||
located.put(member.getKey(), source);
|
||||
});
|
||||
routes.get(scope).computeIfAbsent(alternativeMethod, ignored -> new ArrayList<>())
|
||||
.add(route(operation.getKey(), uri, Map.copyOf(located)));
|
||||
.add(route(operation.getKey(), uri, Map.copyOf(located), documented));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -270,11 +299,11 @@ 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), Map.copyOf(denialStatuses));
|
||||
return new IamRestRoutes(Map.copyOf(copied), Map.copyOf(denialStatuses), Set.copyOf(documentedScopes));
|
||||
}
|
||||
|
||||
/** A route of the operation from its request URI, its path's segments and the query after its {@code ?}. */
|
||||
private static Route route(String operation, String requestUri, Map<String, String> located) {
|
||||
private static Route route(String operation, String requestUri, Map<String, String> located, boolean documented) {
|
||||
int question = requestUri.indexOf('?');
|
||||
String path = IamActionRegistry.withoutTrailingSlash(question < 0 ? requestUri : requestUri.substring(0, question));
|
||||
List<String> segments = path.equals("/") ? List.of() : List.of(path.substring(1).split("/", -1));
|
||||
@@ -317,6 +346,6 @@ final class IamRestRoutes {
|
||||
}
|
||||
return new Route(operation, Pattern.compile(pattern.isEmpty() ? "/" : pattern.toString()),
|
||||
Pattern.compile(spanning.isEmpty() ? "/" : spanning.toString()), List.copyOf(labels), ranks,
|
||||
Map.copyOf(query), located);
|
||||
Map.copyOf(query), located, documented);
|
||||
}
|
||||
}
|
||||
@@ -561,6 +561,93 @@
|
||||
"ListExperiments",
|
||||
"ListTargetResourceTypes"
|
||||
],
|
||||
"glue": [
|
||||
"AccessDataQualityRuntimeConfiguration",
|
||||
"BatchGetCustomEntityTypes",
|
||||
"BatchGetStageFiles",
|
||||
"CheckSchemaVersionValidity",
|
||||
"CreateClassifier",
|
||||
"CreateCrawler",
|
||||
"CreateCustomEntityType",
|
||||
"CreateDataQualityRuleset",
|
||||
"CreateDevEndpoint",
|
||||
"CreateGlueIdentityCenterConfiguration",
|
||||
"CreateInboundIntegration",
|
||||
"CreateMLTransform",
|
||||
"CreateScript",
|
||||
"CreateSecurityConfiguration",
|
||||
"DeleteClassifier",
|
||||
"DeleteCustomEntityType",
|
||||
"DeleteGlueIdentityCenterConfiguration",
|
||||
"DeleteSecurityConfiguration",
|
||||
"DeregisterDataPreview",
|
||||
"DescribeInboundIntegrations",
|
||||
"GetClassifier",
|
||||
"GetClassifiers",
|
||||
"GetColumnStatisticsTaskRun",
|
||||
"GetColumnStatisticsTaskRuns",
|
||||
"GetColumnStatisticsTaskSettings",
|
||||
"GetCrawlerMetrics",
|
||||
"GetCrawlers",
|
||||
"GetCustomEntityType",
|
||||
"GetDataPreviewStatement",
|
||||
"GetDataflowGraph",
|
||||
"GetDevEndpoints",
|
||||
"GetEnvironment",
|
||||
"GetExecutors",
|
||||
"GetExecutorsThreads",
|
||||
"GetGeneratedCode",
|
||||
"GetGlueIdentityCenterConfiguration",
|
||||
"GetJobBookmark",
|
||||
"GetJobs",
|
||||
"GetLogParsingStatus",
|
||||
"GetMapping",
|
||||
"GetNotebookInstanceStatus",
|
||||
"GetPlan",
|
||||
"GetQueries",
|
||||
"GetQuery",
|
||||
"GetRecipeAction",
|
||||
"GetSecurityConfiguration",
|
||||
"GetSecurityConfigurations",
|
||||
"GetStage",
|
||||
"GetStageAttempt",
|
||||
"GetStageAttemptTaskList",
|
||||
"GetStageAttemptTaskSummary",
|
||||
"GetStageFiles",
|
||||
"GetStages",
|
||||
"GetStorage",
|
||||
"GetStorageUnit",
|
||||
"GetTriggers",
|
||||
"GlueNotebookAuthorize",
|
||||
"GlueNotebookRefreshCredentials",
|
||||
"ListBlueprints",
|
||||
"ListColumnStatisticsTaskRuns",
|
||||
"ListConnectionTypes",
|
||||
"ListCrawlers",
|
||||
"ListCustomEntityTypes",
|
||||
"ListDevEndpoints",
|
||||
"ListJobs",
|
||||
"ListRegistries",
|
||||
"ListSessions",
|
||||
"ListTriggers",
|
||||
"ListUsageProfiles",
|
||||
"ListWorkflows",
|
||||
"ManagedConnector",
|
||||
"RequestLogParsing",
|
||||
"ResetJobBookmark",
|
||||
"RunDataPreviewStatement",
|
||||
"SendFeedback",
|
||||
"SendRecipeAction",
|
||||
"StartCompletion",
|
||||
"StartCrawlerSchedule",
|
||||
"StartNotebook",
|
||||
"StopCrawlerSchedule",
|
||||
"TerminateNotebook",
|
||||
"UpdateClassifier",
|
||||
"UpdateCrawlerSchedule",
|
||||
"UpdateGlueIdentityCenterConfiguration",
|
||||
"UseGlueStudio"
|
||||
],
|
||||
"guardduty": [
|
||||
"AcceptAdministratorInvitation",
|
||||
"AcceptInvitation",
|
||||
@@ -611,6 +698,7 @@
|
||||
"ListFilters",
|
||||
"ListFindings",
|
||||
"ListIPSets",
|
||||
"ListInvestigationRecords",
|
||||
"ListInvestigations",
|
||||
"ListInvitations",
|
||||
"ListMalwareProtectionPlans",
|
||||
@@ -1015,13 +1103,16 @@
|
||||
"CreateCidrCollection",
|
||||
"CreateHealthCheck",
|
||||
"CreateHostedZone",
|
||||
"CreateIpGuardrailPolicy",
|
||||
"CreateReusableDelegationSet",
|
||||
"CreateTrafficPolicy",
|
||||
"DeleteIpGuardrailPolicy",
|
||||
"GetAccountLimit",
|
||||
"GetCheckerIpRanges",
|
||||
"GetGeoLocation",
|
||||
"GetHealthCheckCount",
|
||||
"GetHostedZoneCount",
|
||||
"GetIpGuardrailPolicy",
|
||||
"GetTrafficPolicyInstanceCount",
|
||||
"ListCidrCollections",
|
||||
"ListGeoLocations",
|
||||
@@ -1029,10 +1120,12 @@
|
||||
"ListHostedZones",
|
||||
"ListHostedZonesByName",
|
||||
"ListHostedZonesByVPC",
|
||||
"ListIpGuardrailPolicies",
|
||||
"ListReusableDelegationSets",
|
||||
"ListTrafficPolicies",
|
||||
"ListTrafficPolicyInstances",
|
||||
"TestDNSAnswer"
|
||||
"TestDNSAnswer",
|
||||
"UpdateIpGuardrailPolicy"
|
||||
],
|
||||
"s3tables": [
|
||||
"ListTableBuckets"
|
||||
|
||||
@@ -768,6 +768,23 @@
|
||||
"UpdateTargetAccountConfiguration": {"method": "PATCH", "requestUri": "/experimentTemplates/{id}/targetAccountConfigurations/{accountId}"}
|
||||
}
|
||||
},
|
||||
"glue-iceberg-rest": {
|
||||
"credentialScope": "glue",
|
||||
"apiVersion": "apache-iceberg-1.6.1",
|
||||
"documented": {"page": "https://docs.aws.amazon.com/glue/latest/dg/iceberg-rest-apis.html", "definitions": ["https://raw.githubusercontent.com/apache/iceberg/apache-iceberg-1.6.1/open-api/rest-catalog-open-api.yaml"], "pageDiffers": ["DeleteNamespace: the page gives DELETE/iceberg/v1/catalogs/{catalog}/namespces/{ns}, its definition DELETE /v1/{prefix}/namespaces/{namespace}", "CreateTable: the page gives GET /iceberg/v1/catalogs/{catalog}/namespaces/{ns}/tables, its definition POST /v1/{prefix}/namespaces/{namespace}/tables"], "retrieved": "2026-11-15"},
|
||||
"operations": {
|
||||
"CreateDatabase": {"method": "POST", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces"},
|
||||
"CreateTable": {"method": "POST", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}/tables"},
|
||||
"DeleteDatabase": {"method": "DELETE", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}"},
|
||||
"DeleteTable": {"method": "DELETE", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}/tables/{table}"},
|
||||
"GetCatalog": {"method": "GET", "requestUri": "/iceberg/v1/config"},
|
||||
"GetDatabase": {"method": "GET", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces", "alternatives": [{"requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}", "located": {}}]},
|
||||
"GetTable": {"method": "GET", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}/tables/{table}", "alternatives": [{"method": "HEAD", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}/tables/{table}", "located": {}}]},
|
||||
"GetTables": {"method": "GET", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}/tables"},
|
||||
"UpdateDatabase": {"method": "POST", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}/properties"},
|
||||
"UpdateTable": {"method": "POST", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}/tables/{table}"}
|
||||
}
|
||||
},
|
||||
"guardduty": {
|
||||
"credentialScope": "guardduty",
|
||||
"apiVersion": "2017-11-28",
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
package io.floci.aws.services.glue.iceberg;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestContext;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Answers;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Who the endpoint answers under IAM enforcement. */
|
||||
class GlueIcebergControllerTest {
|
||||
|
||||
private EmulatorConfig config;
|
||||
private RequestContext requestContext;
|
||||
private GlueIcebergController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
config = Mockito.mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS);
|
||||
requestContext = Mockito.mock(RequestContext.class);
|
||||
GlueIcebergCatalog catalog = new GlueIcebergCatalog(Mockito.mock(GlueService.class),
|
||||
Mockito.mock(S3Service.class), new RegionResolver("us-east-1", "000000000000"), new ObjectMapper(),
|
||||
null, null);
|
||||
controller = new GlueIcebergController(catalog, config, requestContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
void underIamEnforcementOnlyRootCredentialsAndFlocisOwnCallersReachTheCatalog() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
when(requestContext.getAccountId()).thenReturn("000000000000");
|
||||
|
||||
when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001");
|
||||
IcebergRestException refused = assertThrows(IcebergRestException.class, () -> controller.getConfig(null));
|
||||
assertEquals(403, refused.code());
|
||||
assertEquals("ForbiddenException", refused.type());
|
||||
|
||||
for (String rootOrInternal : new String[] {"test", "000000000000", null}) {
|
||||
when(requestContext.getAccessKeyId()).thenReturn(rootOrInternal);
|
||||
assertEquals("catalogs/:", controller.getConfig(null).path("overrides").path("prefix").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutEnforcementAnyCallerReachesTheCatalog() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(false);
|
||||
when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001");
|
||||
|
||||
assertEquals("catalogs/:", controller.getConfig(null).path("overrides").path("prefix").asText());
|
||||
}
|
||||
}
|
||||
+77
-16
@@ -7,22 +7,25 @@ import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* Under IAM enforcement, no rule maps the Glue Iceberg REST endpoint's routes to the Glue actions AWS checks for them
|
||||
* yet, so the endpoint refuses an IAM principal, even one allowed every Glue action, rather than let it through
|
||||
* unchecked; the account's root credentials still reach it, and so does a token Floci minted for its query engine,
|
||||
* as the account and Region it was minted for.
|
||||
* Under IAM enforcement, each route of the Glue Iceberg REST endpoint is checked as the Glue operation AWS's Glue
|
||||
* Developer Guide documents it as, on the account's Data Catalog, the one resource the request-resource table reads
|
||||
* for a request that carries no Glue member, as an Iceberg request does not; a token Floci minted for its query engine
|
||||
* is answered as the account and Region it was minted for.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SignedIamEnforcementProfile.class)
|
||||
@@ -35,16 +38,53 @@ class GlueIcebergIamIntegrationTest {
|
||||
GlueIcebergTokens tokens;
|
||||
|
||||
@Test
|
||||
void anIamPrincipalIsRefusedAndRootCredentialsAreAnswered() throws Exception {
|
||||
String allowEverything = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"glue:*\",\"Resource\":\"*\"}]}";
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "glue-iceberg-", "glue", allowEverything)) {
|
||||
get(user.signer("glue"), "/iceberg/v1/config").then().statusCode(403)
|
||||
.body("error.type", equalTo("ForbiddenException"));
|
||||
get(user.signer("glue"), "/iceberg/v1/catalogs/:/namespaces").then().statusCode(403);
|
||||
void eachRouteIsCheckedAsTheGlueOperationAwsDocumentsItAs() throws Exception {
|
||||
String catalog = "arn:aws:glue:us-east-1:000000000000:catalog";
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "glue-iceberg-", "glue",
|
||||
policy(allow("glue:GetCatalog", catalog) + "," + allow("glue:GetDatabase", catalog)))) {
|
||||
AwsRequestSigner signer = user.signer("glue");
|
||||
send(signer, "GET", "/iceberg/v1/config", null).then().statusCode(200)
|
||||
.body("overrides.prefix", equalTo("catalogs/:"));
|
||||
send(signer, "GET", "/iceberg/v1/catalogs/:/namespaces", null).then().statusCode(200);
|
||||
refused(send(signer, "POST", "/iceberg/v1/catalogs/:/namespaces", "{\"namespace\":[\"refused\"]}"),
|
||||
"glue:CreateDatabase");
|
||||
// An operation's alternative route of another method is checked as that operation too.
|
||||
refused(send(signer, "HEAD", "/iceberg/v1/catalogs/:/namespaces/refused/tables/t", null), null);
|
||||
refused(send(signer, "GET", "/iceberg/v1/catalogs/:/namespaces/refused/tables/t", null), "glue:GetTable");
|
||||
}
|
||||
get(AwsRequestSigner.signedAs("test", "test", "glue"), "/iceberg/v1/config").then().statusCode(200)
|
||||
.body("overrides.prefix", equalTo("catalogs/:"));
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "glue-iceberg-", "glue",
|
||||
policy(allow("glue:*", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"glue:GetDatabase\","
|
||||
+ "\"Resource\":\"" + catalog + "\"}"))) {
|
||||
send(user.signer("glue"), "GET", "/iceberg/v1/config", null).then().statusCode(200);
|
||||
refused(send(user.signer("glue"), "GET", "/iceberg/v1/catalogs/:/namespaces", null), "glue:GetDatabase");
|
||||
}
|
||||
send(AwsRequestSigner.signedAs("test", "test", "glue"), "GET", "/iceberg/v1/config", null).then()
|
||||
.statusCode(200).body("overrides.prefix", equalTo("catalogs/:"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A Glue member an Iceberg request's body carries is not read: the request is Apache Iceberg's, so a caller added
|
||||
* it. It gives no condition key a value, as a tag the namespace never gets would, and names no resource, as a
|
||||
* database other than the one the request creates would.
|
||||
*/
|
||||
@Test
|
||||
void aGlueMemberAnIcebergBodyCarriesIsNotRead() throws Exception {
|
||||
String catalog = "arn:aws:glue:us-east-1:000000000000:catalog";
|
||||
String taggedCreate = "{\"Effect\":\"Allow\",\"Action\":[\"glue:CreateDatabase\",\"glue:TagResource\"],"
|
||||
+ "\"Resource\":\"*\",\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"data\"}}}";
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "glue-iceberg-", "glue",
|
||||
policy(allow("glue:GetCatalog", catalog) + "," + taggedCreate))) {
|
||||
refused(send(user.signer("glue"), "POST", "/iceberg/v1/catalogs/:/namespaces",
|
||||
"{\"namespace\":[\"tagged\"],\"Tags\":{\"team\":\"data\"}}"), "glue:CreateDatabase");
|
||||
}
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "glue-iceberg-", "glue",
|
||||
policy(allow("glue:*", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"glue:CreateDatabase\","
|
||||
+ "\"Resource\":\"arn:aws:glue:us-east-1:000000000000:database/decoy\"}"))) {
|
||||
send(user.signer("glue"), "POST", "/iceberg/v1/catalogs/:/namespaces",
|
||||
"{\"namespace\":[\"named\"],\"DatabaseInput\":{\"Name\":\"decoy\"}}").then().statusCode(200);
|
||||
}
|
||||
send(AwsRequestSigner.signedAs("test", "test", "glue"), "DELETE", "/iceberg/v1/catalogs/:/namespaces/named",
|
||||
null).then().statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -67,9 +107,30 @@ class GlueIcebergIamIntegrationTest {
|
||||
.get(endpoint.resolve(path));
|
||||
}
|
||||
|
||||
private Response get(AwsRequestSigner signer, String path) throws Exception {
|
||||
private Response send(AwsRequestSigner signer, String method, String path, String body) throws Exception {
|
||||
URI uri = endpoint.resolve(path);
|
||||
return given().urlEncodingEnabled(false).headers(signer.headersFor("GET", uri, Map.of(), new byte[0]))
|
||||
.request("GET", uri);
|
||||
byte[] bytes = body == null ? new byte[0] : body.getBytes(StandardCharsets.UTF_8);
|
||||
RequestSpecification request = given().urlEncodingEnabled(false)
|
||||
.headers(signer.headersFor(method, uri, Map.of(), bytes));
|
||||
if (body != null) {
|
||||
request = request.contentType("application/json").body(bytes);
|
||||
}
|
||||
return request.request(method, uri);
|
||||
}
|
||||
|
||||
/** A refusal of the action, which a HEAD answers with its status alone. */
|
||||
private static void refused(Response response, String action) {
|
||||
response.then().statusCode(403);
|
||||
if (action != null) {
|
||||
response.then().body(containsString("not authorized to perform: " + action));
|
||||
}
|
||||
}
|
||||
|
||||
private static String policy(String statements) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}";
|
||||
}
|
||||
|
||||
private static String allow(String action, String resource) {
|
||||
return "{\"Effect\":\"Allow\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}";
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,10 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class IamRestRoutesTest {
|
||||
|
||||
@@ -105,6 +107,29 @@ class IamRestRoutesTest {
|
||||
|
||||
private final IamRestRoutes routes = routes(ROUTES);
|
||||
|
||||
/**
|
||||
* A model AWS documents outside botocore routes another API's requests, which carry none of the operation's
|
||||
* members: each of its routes, Glue's Iceberg REST endpoint's among the vendored ones, says so, and a botocore
|
||||
* model's does not.
|
||||
*/
|
||||
@Test
|
||||
void aDocumentedModelsRoutesTakeRequestsCarryingNoMembers() {
|
||||
IamRestRoutes documented = routes(ROUTES.replace("\"svc\": {\"credentialScope\": \"svc\",",
|
||||
"\"svc\": {\"credentialScope\": \"svc\", \"documented\": {\"page\": \"https://docs.example/svc\"},"));
|
||||
assertTrue(documented.documents("svc"));
|
||||
assertTrue(documented.match("svc", "GET", "/things/web", null).orElseThrow().documented());
|
||||
assertFalse(routes.documents("svc"));
|
||||
assertFalse(routes.match("svc", "GET", "/things/web", null).orElseThrow().documented());
|
||||
|
||||
IamRestRoutes vendored = IamRestRoutes.vendored();
|
||||
assertTrue(vendored.match("glue", "POST", "/iceberg/v1/catalogs/:/namespaces/db/tables/t", null)
|
||||
.orElseThrow().documented());
|
||||
assertFalse(vendored.match("lambda", "GET", "/2015-03-31/functions/fn", null).orElseThrow().documented());
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> routes(ROUTES.replace("\"svc\": {\"credentialScope\": \"svc\",",
|
||||
"\"svc\": {\"credentialScope\": \"svc\", \"documented\": \"a page\",")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void routeDataIsBundledWithTheApplicationRatherThanOnlyWithTests() throws Exception {
|
||||
URL application = IamActionRegistry.class.getProtectionDomain().getCodeSource().getLocation();
|
||||
|
||||
@@ -21,9 +21,18 @@ https://github.com/boto/botocore), the latest API version of each, located as
|
||||
`regen_query_services.py` locates them. Which models are read, and which credential scope Floci
|
||||
authorizes each under, is Floci's choice and stays in this file.
|
||||
|
||||
An endpoint no botocore model describes is read from the AWS page that documents it (`DOCUMENTED`):
|
||||
the table the page gives each operation, its REST path, IAM action and CloudTrail event, and the
|
||||
operation's definition in the OpenAPI specification the row links, which gives its method and path.
|
||||
Nothing in it is typed by hand. Reading the page needs the network, so a regeneration carries those
|
||||
routes over from the vendored file, `--fetch-documented` reads them again, and `--verify` checks the
|
||||
vendored ones against the page.
|
||||
|
||||
Run from anywhere in the repo:
|
||||
python3 tools/aws/regen_rest_routes.py # rewrite the vendored file in place
|
||||
python3 tools/aws/regen_rest_routes.py --check # exit 1 when the vendored file is stale
|
||||
python3 tools/aws/regen_rest_routes.py # rewrite the vendored file in place
|
||||
python3 tools/aws/regen_rest_routes.py --check # exit 1 when the vendored file is stale
|
||||
python3 tools/aws/regen_rest_routes.py --fetch-documented # also read the documented endpoints again
|
||||
python3 tools/aws/regen_rest_routes.py --verify # exit 1 when a documented endpoint's page differs
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -31,6 +40,9 @@ import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import urllib.request
|
||||
from datetime import date
|
||||
from html.parser import HTMLParser
|
||||
from pathlib import Path
|
||||
|
||||
from regen_partitions import resolve_botocore_data, strip_source
|
||||
@@ -111,6 +123,25 @@ ARN_SPANNING_ROUTES: dict[str, frozenset[str]] = {
|
||||
"oam": frozenset({"TagResource", "UntagResource", "ListTagsForResource"}),
|
||||
}
|
||||
|
||||
# Endpoints no botocore model describes, each read from the AWS page that documents its operations, one table to an
|
||||
# operation: its name, its type, its REST path, its IAM action, its CloudTrail event and the link to its definition in
|
||||
# an OpenAPI specification. The rows of `type` are read, the operations Floci serves. AWS Glue's Iceberg REST endpoint
|
||||
# serves the Apache Iceberg REST catalog's operations; the page's "AWS Glue extensions API" rows are routes Floci
|
||||
# does not serve. A row is the Glue operation its CloudTrail event names, which has to be its IAM action too.
|
||||
DOCUMENTED: dict[str, dict[str, str]] = {
|
||||
"glue-iceberg-rest": {
|
||||
"credentialScope": "glue",
|
||||
"page": "https://docs.aws.amazon.com/glue/latest/dg/iceberg-rest-apis.html",
|
||||
"type": "Iceberg REST Catalog API",
|
||||
},
|
||||
}
|
||||
|
||||
# A definition link: https://github.com/<owner>/<repo>/blob/<ref>/<path>#L<line>, the line of the operation's method.
|
||||
DEFINITION_LINK = re.compile(r"https://github\.com/([^/\s]+)/([^/\s]+)/blob/([^/\s]+)/(\S+?)\\?#L(\d+)")
|
||||
DEFINITION_METHOD = re.compile(r"^ (get|post|put|delete|head|patch|options):\s*$")
|
||||
DEFINITION_PATH = re.compile(r"^ (/\S*):\s*$")
|
||||
PAGE_ROUTE = re.compile(r"^([A-Z]+)\s*(/\S*)$")
|
||||
|
||||
|
||||
def access_denied_status(model: dict) -> int | None:
|
||||
"""The HTTP status explicitly modelled for a declared AccessDenied or AccessDeniedException error."""
|
||||
@@ -129,8 +160,181 @@ def access_denied_status(model: dict) -> int | None:
|
||||
return next(iter(statuses), None)
|
||||
|
||||
|
||||
def build(models: dict[str, dict], provenance: str) -> dict:
|
||||
"""The vendored document from each loaded model."""
|
||||
class PageTables(HTMLParser):
|
||||
"""The rows of each table of an HTML page, each cell as its text."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.tables: list[list[list[str]]] = []
|
||||
self._row: list[str] | None = None
|
||||
self._cell: list[str] | None = None
|
||||
|
||||
def handle_starttag(self, tag: str, attrs: list) -> None:
|
||||
if tag == "table":
|
||||
self.tables.append([])
|
||||
elif tag == "tr" and self.tables:
|
||||
self._row = []
|
||||
elif tag in ("td", "th") and self._row is not None:
|
||||
self._cell = []
|
||||
|
||||
def handle_endtag(self, tag: str) -> None:
|
||||
if tag in ("td", "th") and self._row is not None and self._cell is not None:
|
||||
self._row.append(" ".join("".join(self._cell).split()))
|
||||
self._cell = None
|
||||
elif tag == "tr" and self._row is not None:
|
||||
self.tables[-1].append(self._row)
|
||||
self._row = None
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
if self._cell is not None:
|
||||
self._cell.append(data)
|
||||
|
||||
|
||||
def documented_rows(page: str) -> list[dict[str, str]]:
|
||||
"""The operation tables of a page, in its order, each as its rows' first cell mapped to their second."""
|
||||
parser = PageTables()
|
||||
parser.feed(page)
|
||||
rows = []
|
||||
for table in parser.tables:
|
||||
fields = {row[0]: row[1] for row in table if len(row) == 2}
|
||||
if "Operation name" in fields:
|
||||
rows.append(fields)
|
||||
return rows
|
||||
|
||||
|
||||
def raw_definition_url(link: str) -> tuple[str, int, str]:
|
||||
"""The raw file a definition link names, the line it anchors, and the ref it pins."""
|
||||
match = DEFINITION_LINK.fullmatch(link.strip())
|
||||
if match is None:
|
||||
raise SystemExit(f"error: {link!r} is not a link to a line of a definition on GitHub")
|
||||
owner, repo, ref, path, line = match.groups()
|
||||
return f"https://raw.githubusercontent.com/{owner}/{repo}/{ref}/{path}", int(line), ref
|
||||
|
||||
|
||||
def defined_route(definition: str, line: int, link: str) -> tuple[str, str]:
|
||||
"""The method and path of the operation whose method key is on the line of an OpenAPI definition."""
|
||||
lines = definition.split("\n")
|
||||
method = DEFINITION_METHOD.match(lines[line - 1]) if 0 < line <= len(lines) else None
|
||||
if method is None:
|
||||
raise SystemExit(f"error: {link} does not anchor an operation's method")
|
||||
for index in range(line - 2, -1, -1):
|
||||
path = DEFINITION_PATH.match(lines[index])
|
||||
if path is not None:
|
||||
return method.group(1).upper(), path.group(1)
|
||||
raise SystemExit(f"error: {link} anchors a method under no path")
|
||||
|
||||
|
||||
def documented_route(page_route: str, defined_path: str) -> tuple[str, str, list[str] | None, bool]:
|
||||
"""The route of a documented operation: its definition's path under the root and the prefix the page's REST path
|
||||
gives it, the definition's `{prefix}` taking the segments the page puts in its place. Returns the page's method,
|
||||
the route, the prefix's segments (None when the definition has none), and whether the page's path past the prefix
|
||||
differs from the definition's in a literal segment or in length."""
|
||||
match = PAGE_ROUTE.match(page_route.strip())
|
||||
if match is None:
|
||||
raise SystemExit(f"error: {page_route!r} is no method and path")
|
||||
page_method, page_path = match.groups()
|
||||
page = page_path.strip("/").split("/")
|
||||
defined = defined_path.strip("/").split("/")
|
||||
if "v1" not in page or not defined or defined[0] != "v1":
|
||||
raise SystemExit(f"error: {page_route!r} and {defined_path!r} do not share a /v1 root")
|
||||
root, page_rest, defined_rest = page[:page.index("v1")], page[page.index("v1") + 1:], defined[1:]
|
||||
prefix = None
|
||||
if defined_rest and defined_rest[0] == "{prefix}":
|
||||
defined_rest = defined_rest[1:]
|
||||
span = len(page_rest) - len(defined_rest)
|
||||
if span < 1:
|
||||
raise SystemExit(f"error: {page_route!r} gives {defined_path!r} no prefix")
|
||||
prefix, page_rest = page_rest[:span], page_rest[span:]
|
||||
differs = len(page_rest) != len(defined_rest) or any(
|
||||
not (re.fullmatch(r"\{[^}]+}", ours) and re.fullmatch(r"\{[^}]+}", theirs)) and ours != theirs
|
||||
for ours, theirs in zip(page_rest, defined_rest))
|
||||
route = "/" + "/".join(root + ["v1"] + (prefix or []) + defined_rest)
|
||||
return page_method, route, prefix, differs
|
||||
|
||||
|
||||
def fetch_url(url: str) -> str:
|
||||
request = urllib.request.Request(url, headers={"User-Agent": "floci-aws-data-generator"})
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
return response.read().decode("utf-8")
|
||||
|
||||
|
||||
def build_documented(spec: dict[str, str], fetch=fetch_url) -> dict:
|
||||
"""The routes of a documented endpoint, read from its page and the definitions its rows link: one per Glue
|
||||
operation, its first row in the page's order the route and the others its alternatives, with their method where
|
||||
it is not the route's. Where the page's REST path differs from the definition its row links, the definition's
|
||||
method and path are taken and the difference recorded."""
|
||||
scope = spec["credentialScope"]
|
||||
rows = [row for row in documented_rows(fetch(spec["page"])) if row.get("Type") == spec["type"]]
|
||||
if not rows:
|
||||
raise SystemExit(f"error: {spec['page']} documents no operation of type {spec['type']!r}")
|
||||
definitions: dict[str, str] = {}
|
||||
refs = set()
|
||||
prefixes = set()
|
||||
differences = []
|
||||
operations: dict[str, dict] = {}
|
||||
for row in rows:
|
||||
name = row["Operation name"]
|
||||
action, event = row.get("IAM action", ""), row.get("CloudTrail event", "")
|
||||
if action != event or not action.startswith(scope + ":"):
|
||||
raise SystemExit(f"error: {name} on {spec['page']}: its IAM action {action!r} is not its CloudTrail "
|
||||
f"event {event!r} in {scope}")
|
||||
raw, line, ref = raw_definition_url(row.get("Open API definition", ""))
|
||||
if raw not in definitions:
|
||||
definitions[raw] = fetch(raw)
|
||||
refs.add(ref)
|
||||
method, defined = defined_route(definitions[raw], line, row["Open API definition"])
|
||||
page_method, route, prefix, differs = documented_route(row.get("REST path", ""), defined)
|
||||
if prefix is not None:
|
||||
prefixes.add("/".join(prefix))
|
||||
if differs or page_method != method:
|
||||
differences.append(f"{name}: the page gives {row['REST path']}, its definition {method} {defined}")
|
||||
operation = action.split(":", 1)[1]
|
||||
if operation not in operations:
|
||||
operations[operation] = {"method": method, "requestUri": route}
|
||||
else:
|
||||
# An alternative says where it locates the members its path no longer holds: none, here.
|
||||
alternative = {"requestUri": route, "located": {}} if method == operations[operation]["method"] \
|
||||
else {"method": method, "requestUri": route, "located": {}}
|
||||
operations[operation].setdefault("alternatives", []).append(alternative)
|
||||
if len(prefixes) > 1 or len(refs) > 1:
|
||||
raise SystemExit(f"error: {spec['page']} gives its routes more than one prefix {sorted(prefixes)} or "
|
||||
f"definition {sorted(refs)}")
|
||||
return {
|
||||
"credentialScope": scope,
|
||||
"apiVersion": next(iter(refs)),
|
||||
"documented": {"page": spec["page"], "definitions": sorted(definitions), "pageDiffers": differences,
|
||||
"retrieved": date.today().isoformat()},
|
||||
"operations": dict(sorted(operations.items())),
|
||||
}
|
||||
|
||||
|
||||
def carried_documented(current: str) -> dict[str, dict]:
|
||||
"""The documented endpoints' routes the vendored file holds, each the endpoint `DOCUMENTED` reads from the same
|
||||
page under the same scope, with the routes a request can match."""
|
||||
models = json.loads(current).get("models", {}) if current.strip() else {}
|
||||
carried = {}
|
||||
for name, spec in DOCUMENTED.items():
|
||||
model = models.get(name)
|
||||
if model is None:
|
||||
raise SystemExit(f"error: the vendored file has no routes of {name}: run with --fetch-documented")
|
||||
if model.get("credentialScope") != spec["credentialScope"] \
|
||||
or model.get("documented", {}).get("page") != spec["page"]:
|
||||
raise SystemExit(f"error: the vendored routes of {name} are not read from {spec['page']} under "
|
||||
f"{spec['credentialScope']}: run with --fetch-documented")
|
||||
operations = model.get("operations")
|
||||
if not operations or not all(isinstance(route, dict) and route.get("method") in METHODS
|
||||
and str(route.get("requestUri", "")).startswith("/")
|
||||
for route in operations.values()):
|
||||
raise SystemExit(f"error: the vendored routes of {name} are malformed: run with --fetch-documented")
|
||||
carried[name] = model
|
||||
return carried
|
||||
|
||||
|
||||
METHODS = ("GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS")
|
||||
|
||||
|
||||
def build(models: dict[str, dict], provenance: str, documented: dict[str, dict] | None = None) -> dict:
|
||||
"""The vendored document from each loaded model, and the routes of each documented endpoint."""
|
||||
routes = {}
|
||||
denial_statuses = {}
|
||||
for name in sorted(models):
|
||||
@@ -163,6 +367,10 @@ def build(models: dict[str, dict], provenance: str) -> dict:
|
||||
raise SystemExit(f"error: REST models of {scope} have conflicting access-denied HTTP statuses")
|
||||
denial_statuses[scope] = status
|
||||
routes[name]["accessDeniedStatus"] = status
|
||||
for name, model in (documented or {}).items():
|
||||
if name in routes:
|
||||
raise SystemExit(f"error: {name} is both a botocore model and a documented endpoint")
|
||||
routes[name] = model
|
||||
routes = dict(sorted(routes.items()))
|
||||
shared = shared_routes(routes)
|
||||
if shared:
|
||||
@@ -228,6 +436,8 @@ def render(doc: dict) -> str:
|
||||
lines.append(f' "apiVersion": {json.dumps(model["apiVersion"])},')
|
||||
if "accessDeniedStatus" in model:
|
||||
lines.append(f' "accessDeniedStatus": {model["accessDeniedStatus"]},')
|
||||
if "documented" in model:
|
||||
lines.append(f' "documented": {json.dumps(model["documented"])},')
|
||||
lines.append(' "operations": {')
|
||||
operations = list(model["operations"].items())
|
||||
for position, (operation, route) in enumerate(operations):
|
||||
@@ -239,18 +449,45 @@ def render(doc: dict) -> str:
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def verify_documented(vendored: dict[str, dict], fetch=fetch_url) -> int:
|
||||
"""Whether each documented endpoint's page and definitions still give the vendored routes, the retrieval date
|
||||
aside."""
|
||||
stale = []
|
||||
for name, spec in DOCUMENTED.items():
|
||||
fresh = build_documented(spec, fetch)
|
||||
ours = json.loads(json.dumps(vendored[name]))
|
||||
ours["documented"].pop("retrieved", None)
|
||||
fresh["documented"].pop("retrieved", None)
|
||||
if ours != fresh:
|
||||
stale.append(name)
|
||||
for name in stale:
|
||||
print(f"error: the routes {DOCUMENTED[name]['page']} documents differ from the vendored {name}: run with "
|
||||
f"--fetch-documented", file=sys.stderr)
|
||||
if not stale:
|
||||
print(f"{len(DOCUMENTED)} documented endpoint(s) match their AWS pages")
|
||||
return 1 if stale else 0
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
|
||||
parser.add_argument("--fetch-documented", action="store_true",
|
||||
help="online: read the documented endpoints' routes again from their AWS pages")
|
||||
parser.add_argument("--verify", action="store_true",
|
||||
help="online: exit 1 when a documented endpoint's AWS page gives other routes than the vendored")
|
||||
parser.add_argument("--botocore-data", type=Path, help="botocore data directory")
|
||||
parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
|
||||
if args.verify:
|
||||
return verify_documented(carried_documented(current))
|
||||
documented = {name: build_documented(spec) for name, spec in DOCUMENTED.items()} if args.fetch_documented \
|
||||
else carried_documented(current)
|
||||
data, provenance = resolve_botocore_data(args.botocore_data)
|
||||
fresh = render(build(load_models(data), provenance))
|
||||
fresh = render(build(load_models(data), provenance, documented))
|
||||
|
||||
if args.check:
|
||||
current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
|
||||
if strip_source(current) != strip_source(fresh):
|
||||
print(f"{args.output} is stale (generated from {provenance}).", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
@@ -54,7 +54,8 @@ def test_a_model_that_is_not_rest_is_refused():
|
||||
r.build({"s3": model("json", "2006-03-01", GetObject=("POST", "/"))}, "botocore test")
|
||||
|
||||
|
||||
def test_check_passes_on_a_fresh_generation_and_fails_on_a_stale_one(tmp_path):
|
||||
def test_check_passes_on_a_fresh_generation_and_fails_on_a_stale_one(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(r, "DOCUMENTED", {})
|
||||
for name in r.MODELS:
|
||||
directory = tmp_path / "data" / name / "2020-01-01"
|
||||
directory.mkdir(parents=True)
|
||||
@@ -191,3 +192,162 @@ def test_an_arn_label_the_controller_lets_span_slashes_is_greedy():
|
||||
doc = r.build({"oam": model("rest-json", "2022-06-10", TagResource=("PUT", "/tags/{ResourceArn}"),
|
||||
GetSink=("POST", "/GetSink"))}, "test")
|
||||
assert doc["models"]["oam"]["operations"]["TagResource"] == {"method": "PUT", "requestUri": "/tags/{ResourceArn+}"}
|
||||
|
||||
|
||||
PAGE = "https://docs.aws.amazon.com/glue/latest/dg/iceberg-rest-apis.html"
|
||||
SPEC = "https://github.com/apache/iceberg/blob/apache-iceberg-1.6.1/open-api/rest-catalog-open-api.yaml"
|
||||
RAW = "https://raw.githubusercontent.com/apache/iceberg/apache-iceberg-1.6.1/open-api/rest-catalog-open-api.yaml"
|
||||
DEFINITION_LINES = [
|
||||
"paths:", # 1
|
||||
" /v1/config:", # 2
|
||||
" get:", # 3
|
||||
" operationId: getConfig", # 4
|
||||
" /v1/{prefix}/namespaces:", # 5
|
||||
" parameters:", # 6
|
||||
" - $ref: '#/components/parameters/prefix'", # 7
|
||||
" get:", # 8
|
||||
" operationId: listNamespaces", # 9
|
||||
" /v1/{prefix}/namespaces/{namespace}:", # 10
|
||||
" get:", # 11
|
||||
" operationId: loadNamespaceMetadata", # 12
|
||||
" delete:", # 13
|
||||
" operationId: dropNamespace", # 14
|
||||
" /v1/{prefix}/namespaces/{namespace}/tables:", # 15
|
||||
" post:", # 16
|
||||
" operationId: createTable", # 17
|
||||
" /v1/{prefix}/namespaces/{namespace}/tables/{table}:", # 18
|
||||
" get:", # 19
|
||||
" operationId: loadTable", # 20
|
||||
" head:", # 21
|
||||
" operationId: tableExists", # 22
|
||||
]
|
||||
|
||||
|
||||
def operation_table(name: str, kind: str, path: str, action: str, event: str, line: int,
|
||||
spec: str = SPEC) -> str:
|
||||
rows = [("Operation name", name), ("Type", kind), ("REST path", path), ("IAM action", action),
|
||||
("Lake Formation permissions", "ALL"), ("CloudTrail event", event),
|
||||
("Open API definition", f'<a href="{spec}#L{line}">{spec}#L{line}</a>')]
|
||||
return "<table><tbody>" + "".join(f"<tr><td>{key}</td><td>{value}</td></tr>" for key, value in rows) \
|
||||
+ "</tbody></table>"
|
||||
|
||||
|
||||
def page(*tables: str) -> str:
|
||||
return "<html><body><table><tr><th>Access pattern</th><th>Prefix</th><th>Example</th></tr></table>" \
|
||||
+ "".join(tables) + "</body></html>"
|
||||
|
||||
|
||||
ICEBERG = "Iceberg REST Catalog API"
|
||||
SERVED = page(
|
||||
operation_table("GetConfig", ICEBERG, "GET /iceberg/v1/config", "glue:GetCatalog", "glue:GetCatalog", 3),
|
||||
operation_table("ListNamespaces", ICEBERG, "GET/iceberg/v1/catalogs/{catalog}/namespaces", "glue:GetDatabase",
|
||||
"glue:GetDatabase", 8),
|
||||
operation_table("LoadNamespaceMetadata", ICEBERG, "GET/iceberg/v1/catalogs/{catalog}/namespaces/{ns}",
|
||||
"glue:GetDatabase", "glue:GetDatabase", 11),
|
||||
operation_table("DeleteNamespace", ICEBERG, "DELETE/iceberg/v1/catalogs/{catalog}/namespces/{ns}",
|
||||
"glue:DeleteDatabase", "glue:DeleteDatabase", 13),
|
||||
operation_table("CreateTable", ICEBERG, "GET /iceberg/v1/catalogs/{catalog}/namespaces/{ns}/tables",
|
||||
"glue:CreateTable", "glue:CreateTable", 16),
|
||||
operation_table("CreateTable", "AWS Glue extensions API",
|
||||
"POST/extensions/v1/catalogs/{catalog}/namespaces/{ns}/tables", "glue:CreateTable",
|
||||
"glue:CreateTable", 107,
|
||||
"https://github.com/awslabs/glue-extensions-for-iceberg/blob/main/glue-extensions-api.yaml"),
|
||||
operation_table("LoadTable", ICEBERG, "GET /iceberg/v1/catalogs/{catalog}/namespaces/{ns}/tables/{table}",
|
||||
"glue:GetTable", "glue:GetTable", 19),
|
||||
operation_table("TableExists", ICEBERG, "HEAD/iceberg/v1/catalogs/{catalog}/namespaces/{ns}/tables/{table}",
|
||||
"glue:GetTable", "glue:GetTable", 21),
|
||||
)
|
||||
GLUE = {"credentialScope": "glue", "page": PAGE, "type": ICEBERG}
|
||||
|
||||
|
||||
def fetcher(pages: dict[str, str]):
|
||||
def fetch(url: str) -> str:
|
||||
return pages[url]
|
||||
return fetch
|
||||
|
||||
|
||||
def test_a_documented_endpoint_takes_each_rows_route_from_the_definition_it_links_under_the_pages_prefix():
|
||||
model = r.build_documented(GLUE, fetcher({PAGE: SERVED, RAW: "\n".join(DEFINITION_LINES)}))
|
||||
|
||||
assert model["credentialScope"] == "glue"
|
||||
assert model["apiVersion"] == "apache-iceberg-1.6.1"
|
||||
assert model["operations"] == {
|
||||
"CreateTable": {"method": "POST", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}/tables"},
|
||||
"DeleteDatabase": {"method": "DELETE", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}"},
|
||||
"GetCatalog": {"method": "GET", "requestUri": "/iceberg/v1/config"},
|
||||
# Rows of one operation are its route, in the page's order, and its alternatives, with their own method.
|
||||
"GetDatabase": {"method": "GET", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces",
|
||||
"alternatives": [{"requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}",
|
||||
"located": {}}]},
|
||||
"GetTable": {"method": "GET", "requestUri": "/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}/tables/{table}",
|
||||
"alternatives": [{"method": "HEAD", "requestUri":
|
||||
"/iceberg/v1/catalogs/{catalog}/namespaces/{namespace}/tables/{table}",
|
||||
"located": {}}]},
|
||||
}
|
||||
# The page's misspelt segment and wrong method give way to the definition the row links, and are recorded.
|
||||
assert model["documented"]["page"] == PAGE
|
||||
assert model["documented"]["definitions"] == [RAW]
|
||||
assert model["documented"]["pageDiffers"] == [
|
||||
"DeleteNamespace: the page gives DELETE/iceberg/v1/catalogs/{catalog}/namespces/{ns}, its definition "
|
||||
"DELETE /v1/{prefix}/namespaces/{namespace}",
|
||||
"CreateTable: the page gives GET /iceberg/v1/catalogs/{catalog}/namespaces/{ns}/tables, its definition "
|
||||
"POST /v1/{prefix}/namespaces/{namespace}/tables",
|
||||
]
|
||||
|
||||
|
||||
def test_a_row_whose_iam_action_is_not_its_cloudtrail_event_is_refused():
|
||||
served = page(operation_table("ListNamespaces", ICEBERG, "GET/iceberg/v1/catalogs/{catalog}/namespaces",
|
||||
"glue:GetDatabases", "glue:GetDatabase", 8))
|
||||
with pytest.raises(SystemExit, match="is not its CloudTrail event"):
|
||||
r.build_documented(GLUE, fetcher({PAGE: served, RAW: "\n".join(DEFINITION_LINES)}))
|
||||
|
||||
|
||||
def test_a_link_that_anchors_no_method_or_a_page_with_no_row_of_the_type_is_refused():
|
||||
served = page(operation_table("ListNamespaces", ICEBERG, "GET/iceberg/v1/catalogs/{catalog}/namespaces",
|
||||
"glue:GetDatabase", "glue:GetDatabase", 9))
|
||||
with pytest.raises(SystemExit, match="does not anchor an operation's method"):
|
||||
r.build_documented(GLUE, fetcher({PAGE: served, RAW: "\n".join(DEFINITION_LINES)}))
|
||||
with pytest.raises(SystemExit, match="documents no operation"):
|
||||
r.build_documented(GLUE, fetcher({PAGE: page(), RAW: ""}))
|
||||
|
||||
|
||||
def test_check_carries_the_documented_routes_over_and_verify_compares_them_with_the_page(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(r, "DOCUMENTED", {"glue-iceberg-rest": GLUE})
|
||||
for name in r.MODELS:
|
||||
directory = tmp_path / "data" / name / "2020-01-01"
|
||||
directory.mkdir(parents=True)
|
||||
with gzip.open(directory / "service-2.json.gz", "wt", encoding="utf-8") as f:
|
||||
json.dump(model("rest-json", "2020-01-01", Ping=("GET", "/ping")), f)
|
||||
output = tmp_path / "rest-routes.json"
|
||||
data = ["--botocore-data", str(tmp_path / "data"), "--output", str(output)]
|
||||
documented = r.build_documented(GLUE, fetcher({PAGE: SERVED, RAW: "\n".join(DEFINITION_LINES)}))
|
||||
|
||||
# A regeneration with no vendored routes of the endpoint cannot read them offline.
|
||||
with pytest.raises(SystemExit, match="--fetch-documented"):
|
||||
r.main(data)
|
||||
output.write_text(r.render(r.build({}, "test", {"glue-iceberg-rest": documented})), encoding="utf-8")
|
||||
assert r.main(data) == 0
|
||||
assert json.loads(output.read_text(encoding="utf-8"))["models"]["glue-iceberg-rest"] == documented
|
||||
assert r.main(data + ["--check"]) == 0
|
||||
|
||||
vendored = r.carried_documented(output.read_text(encoding="utf-8"))
|
||||
assert r.verify_documented(vendored, fetcher({PAGE: SERVED, RAW: "\n".join(DEFINITION_LINES)})) == 0
|
||||
moved = SERVED.replace("glue:GetCatalog", "glue:GetCatalogs")
|
||||
assert r.verify_documented(vendored, fetcher({PAGE: moved, RAW: "\n".join(DEFINITION_LINES)})) == 1
|
||||
fewer = SERVED.replace(
|
||||
operation_table("TableExists", ICEBERG, "HEAD/iceberg/v1/catalogs/{catalog}/namespaces/{ns}/tables/{table}",
|
||||
"glue:GetTable", "glue:GetTable", 21), "")
|
||||
assert r.verify_documented(vendored, fetcher({PAGE: fewer, RAW: "\n".join(DEFINITION_LINES)})) == 1
|
||||
|
||||
|
||||
def test_vendored_documented_routes_read_from_another_page_or_malformed_are_refused(monkeypatch):
|
||||
monkeypatch.setattr(r, "DOCUMENTED", {"glue-iceberg-rest": GLUE})
|
||||
documented = r.build_documented(GLUE, fetcher({PAGE: SERVED, RAW: "\n".join(DEFINITION_LINES)}))
|
||||
elsewhere = json.loads(json.dumps(documented))
|
||||
elsewhere["documented"]["page"] = "https://example.com/other.html"
|
||||
with pytest.raises(SystemExit, match="are not read from"):
|
||||
r.carried_documented(r.render(r.build({}, "test", {"glue-iceberg-rest": elsewhere})))
|
||||
malformed = json.loads(json.dumps(documented))
|
||||
malformed["operations"]["GetCatalog"] = {"method": "FETCH", "requestUri": "/iceberg/v1/config"}
|
||||
with pytest.raises(SystemExit, match="malformed"):
|
||||
r.carried_documented(r.render(r.build({}, "test", {"glue-iceberg-rest": malformed})))
|
||||
Reference in new issue
Block a user