feat(athena): check the Glue permissions a DDL statement needs as the caller (#8657)

Athena runs a DDL statement against the Glue Data Catalog with the
caller's identity, so on AWS a caller without the Glue permissions a
statement needs starts the query, and the query fails with
"Insufficient permissions to execute the query." and the Glue denial.
Floci never checked them: under IAM enforcement a caller holding only
athena:* created and dropped Glue databases and tables through Athena.

Neither botocore nor the Service Reference says which Glue actions a
statement needs. Athena's user guide does, in its table "Examples of
database and table-level permissions":

- tools/aws/fetch_athena_glue_ddl_permissions.py vendors that table as
  it stands into tools/aws/sources/athena-glue-ddl-permissions.json:
  each statement's sentence and example policy, and the sentence that
  names the example database and table. --verify compares the file
  with the live page, and athena-glue-ddl-permissions.prompt.md says
  how to rebuild it when the page's layout changes.
- regen_iam_request_resources.py reads it as a source of the IAM
  request table (STATEMENT_SOURCES, for this table alone). Each action
  of a policy statement acts on each of its resources whose type the
  Service Reference gives the action, the type whose format the example
  ARN matches, its variables filled with what the page says the example
  names stand for. The table gains statementActions, the reference's
  types for each action, and statements. --check derives both offline,
  and --verify checks the types and the page. The sync also carries
  the Service Reference's changes since the last one.
- IamEnforcementFilter.statementRefusal checks those requests as the
  caller, the way a forwarded request is checked (aws:ViaAWSService,
  the caller's keys, the resource's policy), and returns AWS's denial.
  authorizeAdditionalResource's caller and decision steps move into
  helpers the two share.
- AthenaService checks CREATE DATABASE, CREATE [EXTERNAL] TABLE, DROP
  TABLE and MSCK REPAIR TABLE in the default catalog before running
  them, naming the database and table lowercase as Glue stores them
  (GlueService.normalizeName), and a denial fails the query with
  AWS's reason. As the guide says, DROP TABLE of a table without
  partitions needs no partition action; a table Glue cannot read for
  another reason fails the query.

AthenaGluePermissionsIntegrationTest runs the guide's policies under
IAM enforcement, and a deny on a lowercase name against a query that
spells it in capitals. RequestResourcesTest and the generator's and
fetch script's tests cover the rest, and athena.md says so.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-16 21:03:21 -04:00
1 parent d606843c49
commit ef07bfd4b3
19 files changed
+1439 -71

No files matched your search

+2 -1
View File
@@ -615,7 +615,8 @@ DOCUMENTED_ROUTES_PATHS := src/main/resources/aws/rest-routes.json tools/aws/reg
tools/aws/test_regen_rest_routes.py tools/aws/regen_partitions.py tools/aws/regen_query_services.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
tools/aws/test_regen_iam_request_resources.py tools/aws/sources/athena-glue-ddl-permissions.json \
tools/aws/fetch_athena_glue_ddl_permissions.py tools/aws/test_fetch_athena_glue_ddl_permissions.py
iam-data-verify: ## CI gate (online): every vendored IAM file must still match AWS; CHANGED="<paths>" checks only the ones they cover
@# Every check runs even when an earlier one fails, so one file's drift cannot hide another's
+8
View File
@@ -173,6 +173,14 @@ Hive DDL runs against the Glue Data Catalog rather than the query engine, as it
Without `IF [NOT] EXISTS`, a table or partition that already exists, or does not, fails the query. Other `ALTER TABLE` statements are not supported.
### Glue permissions under IAM enforcement
Athena runs a DDL statement against the Glue Data Catalog with the caller's identity, so with IAM enforcement on (`floci.services.iam.enforcement-enabled`) a statement of the default catalog also needs the Glue permissions Athena's user guide gives it in [Examples of database and table-level permissions](https://docs.aws.amazon.com/athena/latest/ug/fine-grained-access-to-glue-resources.html). Floci checks each action of the guide's example policy for the statement on each resource of it: the catalog, and the database and table the statement names. For example, `CREATE DATABASE` needs `glue:GetDatabase` and `glue:CreateDatabase`, and `CREATE TABLE` needs `glue:GetDatabase` and `glue:GetDatabases` on the catalog and database, and `glue:GetTables`, `glue:GetTable`, `glue:GetPartitions` and `glue:CreateTable` on the catalog, database and table. The guide's examples are what Floci requires in full, `glue:CreateDatabase` for `MSCK REPAIR TABLE` included, so a policy that grants less is refused even where AWS might allow it. As the guide says, `DROP TABLE` of a table without partitions needs no partition action.
A missing permission does not refuse `StartQueryExecution`. The query starts and fails, as on AWS, with a `StateChangeReason` of `Insufficient permissions to execute the query. ` followed by the denial of the first Glue request refused, for example `User: arn:aws:iam::123456789012:user/analyst is not authorized to perform: glue:GetDatabase on resource: arn:aws:glue:us-east-1:123456789012:catalog because no identity-based policy allows the glue:GetDatabase action `.
The statements checked are `CREATE DATABASE`, `CREATE [EXTERNAL] TABLE`, `DROP TABLE` and `MSCK REPAIR TABLE`, the ones the guide lists that Floci runs. The guide gives no permissions for `ALTER TABLE ... ADD PARTITION`, `ALTER TABLE ... DROP PARTITION`, `SHOW PARTITIONS`, `VACUUM`, `SELECT` or other DML, so those are not checked against Glue, and neither are statements in an [S3 Tables catalog](#s3-tables-catalogs). The table of permissions is vendored from the guide's page by `tools/aws/fetch_athena_glue_ddl_permissions.py` and read into the IAM request table by `tools/aws/regen_iam_request_resources.py`.
## Iceberg tables
Athena manages Iceberg tables through AWS Glue's Iceberg REST catalog, which Floci serves (see [Glue's Iceberg REST endpoint](glue.md#iceberg-rest-endpoint)):
@@ -1644,39 +1644,24 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
throw expiredTokenException(credentialScope);
}
List<List<String>> scpLevels = scpProvider.isResolvable()
? scpProvider.get().effectiveScpLevels(accountId) : null;
boolean accountRootPrincipal = false;
CallerContext caller = iamService.resolveCallerContext(akid, now);
// No unknown-key rejection here, unlike filter(). For a second resource of a request
// filter() has authorized (CopyObject's source, RotateSecret's rotation function, the
// secrets behind SSM GetParameter) the credential is the one filter() evaluated, and
// filter() refuses an unknown key before the handler runs. Two callers reach here with
// a key filter() has not checked: a presigned POST, whose credential is only in the
// form body, and DeleteObjects, where filter() returns before its key checks because
// no action maps the route. For both, S3's own request authentication refuses an
// unknown key when S3 auth enforcement is on; with it off, the request proceeds as an
// unsigned one would.
Caller caller = callerOf(akid, accountId, now);
if (caller == null) {
// No unknown-key rejection here, unlike filter(). For a second resource of a request
// filter() has authorized (CopyObject's source, RotateSecret's rotation function, the
// secrets behind SSM GetParameter) the credential is the one filter() evaluated, and
// filter() refuses an unknown key before the handler runs. Two callers reach here with
// a key filter() has not checked: a presigned POST, whose credential is only in the
// form body, and DeleteObjects, where filter() returns before its key checks because
// no action maps the route. For both, S3's own request authentication refuses an
// unknown key when S3 auth enforcement is on; with it off, the request proceeds as an
// unsigned one would.
if (scpLevels == null || !accountRootKey) {
return;
}
caller = CallerContext.of(List.of(ROOT_ALLOW_ALL));
accountRootPrincipal = true;
}
if (scpLevels != null) {
caller = caller.withScpLevels(scpLevels);
return;
}
Map<String, List<String>> conditionContext = null;
Optional<CallerArns> callerArns = accountRootPrincipal
? Optional.of(accountRootArns(accountId))
: iamService.resolveCallerArns(akid);
if (callerArns.isPresent()) {
caller = caller.withPrincipalArn(callerArns.get().callerArn());
if (caller.arns().isPresent()) {
conditionContext = new HashMap<>();
callerArns.get().putPrincipalKeys(conditionContext);
caller.arns().get().putPrincipalKeys(conditionContext);
}
if (requestConditions != null && !requestConditions.isEmpty()) {
if (conditionContext == null) {
@@ -1685,41 +1670,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
conditionContext.putAll(requestConditions);
}
ResourcePolicyDecision effectiveDecision = resourcePolicyDecision;
String effectiveOwnerAccountId = resourceOwnerAccountId;
List<String> policyDocs = null;
if (effectiveDecision == null) {
// Resource policies belong to the service that owns the resource, which is the action's
// service, not whichever service the caller signed for. filter() picks them by the route's
// serving service for the same reason; a credential scoped to another service, or to a
// signing alias such as s3express, would otherwise see no bucket policy at all.
String resourcePolicyScope = catalog.canonicalCredentialScope(action.split(":", 2)[0]);
List<ResourcePolicyProvider.ResourcePolicy> resourcePolicies = resolveResourcePolicies(
resourcePolicyScope, action, resource);
effectiveOwnerAccountId = resourcePolicies.isEmpty()
? null : resourcePolicies.getFirst().ownerAccountId();
policyDocs = resourcePolicies.stream()
.map(ResourcePolicyProvider.ResourcePolicy::policyDocument)
.filter(doc -> doc != null && !doc.isBlank())
.toList();
}
String region = requestContext.getRegion() == null
? config.defaultRegion() : requestContext.getRegion();
Map<String, List<String>> effectiveContext = IamConditionContextResolver.withGlobalContext(
conditionContext, resource, region, accountId, effectiveOwnerAccountId, action);
if (effectiveDecision == null) {
effectiveDecision = evaluator.evaluateResourcePolicyFor(
policyDocs.isEmpty() ? null : policyDocs,
RequestPrincipal.caller(callerArns.orElse(null)), action, resource, effectiveContext);
}
ResourceAccountRelationship accountRelationship = effectiveOwnerAccountId == null
|| accountId.equals(effectiveOwnerAccountId)
? ResourceAccountRelationship.SAME_ACCOUNT
: ResourceAccountRelationship.CROSS_ACCOUNT;
Decision decision = evaluator.evaluateResolvedResourcePolicy(
caller, effectiveDecision, accountRelationship,
action, resource, effectiveContext);
Decision decision = decideAs(caller, accountId, region, action, resource, conditionContext,
resourcePolicyDecision, resourceOwnerAccountId).decision();
if (decision != Decision.DENY) {
return;
}
@@ -1737,6 +1691,134 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
}
/**
* Why the caller of the current request may not have the operation's service run {@code statement} as it, as AWS
* words the denial of the first request the statement makes that is refused ("User: <caller> is not authorized
* to perform: <action> on resource: <resource> because no identity-based policy allows the <action> action"). The
* requests are the IAM table's ({@link RequestResources#statementRequests}), on the resources {@code names}
* names in the request's partition, Region and account. Each is checked as a forwarded request is, with
* {@code aws:ViaAWSService} true and the keys that say who is calling, the resource's own policy deciding beside
* the caller's where its service holds one. Athena runs a DDL statement against the Glue Data Catalog this way and
* reports a refusal as the query's failure rather than the request's, so the refusal is returned for the service
* to report. Empty when every request is allowed, IAM enforcement is off, or the request carries no key IAM
* checks.
*/
public Optional<String> statementRefusal(String operation, String statement, Map<String, String> names,
boolean partitioned) {
String akid = requestContext.getAccessKeyId();
if (!config.services().iam().enforcementEnabled() || akid == null || "test".equals(akid)) {
return Optional.empty();
}
String accountId = requestContext.getAccountId();
Caller caller = callerOf(akid, accountId, clock.instant());
if (caller == null) {
return Optional.empty();
}
String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion();
for (RequestResources.StatementRequest request : RequestResources.statementRequests(operation, statement,
names, partitioned, requestPartition(), region, accountId)) {
Map<String, List<String>> context = new HashMap<>();
caller.arns().ifPresent(arns -> arns.putPrincipalKeys(context));
context.put("aws:ViaAWSService", List.of("true"));
Decided decided = decideAs(caller, accountId, region, request.action(), request.resource(), context,
null, null);
if (decided.decision() != Decision.DENY) {
continue;
}
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}, which its service makes as the caller",
akid, request.action(), request.resource());
String user = caller.arns().map(CallerArns::callerArn).orElseGet(() ->
AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "user/" + akid).toString());
String reason = AccessDeniedMessages.firstRefusal(evaluator, caller.context(),
iamService.heldPolicies(akid).orElse(null), request.action(), request.resource(),
decided.context());
return Optional.of(AccessDeniedMessages.notAuthorized(user, request.action(), request.resource(), reason));
}
return Optional.empty();
}
/** The context a key acts with, its service control policies applied, and the ARNs that say who is calling. */
private record Caller(CallerContext context, Optional<CallerArns> arns) {
}
/** A decision and the condition context it was made in. */
private record Decided(Decision decision, Map<String, List<String>> context) {
}
/**
* The caller {@code akid} acts as in {@code accountId}: the policies IAM holds for it, or, for the account's own
* root key, which IAM holds none for, an allow of everything its service control policies still limit. Null for
* a key IAM holds nothing for and has nothing else to check it against.
*/
private Caller callerOf(String akid, String accountId, Instant now) {
List<List<String>> scpLevels = scpProvider.isResolvable()
? scpProvider.get().effectiveScpLevels(accountId) : null;
boolean accountRootPrincipal = false;
CallerContext caller = iamService.resolveCallerContext(akid, now);
if (caller == null) {
if (scpLevels == null || !akid.equals(accountId)) {
return null;
}
caller = CallerContext.of(List.of(ROOT_ALLOW_ALL));
accountRootPrincipal = true;
}
if (scpLevels != null) {
caller = caller.withScpLevels(scpLevels);
}
Optional<CallerArns> callerArns = accountRootPrincipal
? Optional.of(accountRootArns(accountId))
: iamService.resolveCallerArns(akid);
if (callerArns.isPresent()) {
caller = caller.withPrincipalArn(callerArns.get().callerArn());
}
return new Caller(caller, callerArns);
}
/**
* The decision on {@code action} on {@code resource} for {@code caller}, and the context it was made in: the
* resource's own policy decides beside the caller's, both having to allow across accounts. Without a
* {@code resourcePolicyDecision} of the caller's own, the policies are resolved here through
* {@link ResourcePolicyProvider}, under the account they belong to.
*/
private Decided decideAs(Caller caller, String accountId, String region, String action, String resource,
Map<String, List<String>> conditionContext, ResourcePolicyDecision resourcePolicyDecision,
String resourceOwnerAccountId) {
ResourcePolicyDecision effectiveDecision = resourcePolicyDecision;
String effectiveOwnerAccountId = resourceOwnerAccountId;
List<String> policyDocs = null;
if (effectiveDecision == null) {
// Resource policies belong to the service that owns the resource, which is the action's
// service, not whichever service the caller signed for. filter() picks them by the route's
// serving service for the same reason; a credential scoped to another service, or to a
// signing alias such as s3express, would otherwise see no bucket policy at all.
String resourcePolicyScope = catalog.canonicalCredentialScope(action.split(":", 2)[0]);
List<ResourcePolicyProvider.ResourcePolicy> resourcePolicies = resolveResourcePolicies(
resourcePolicyScope, action, resource);
effectiveOwnerAccountId = resourcePolicies.isEmpty()
? null : resourcePolicies.getFirst().ownerAccountId();
policyDocs = resourcePolicies.stream()
.map(ResourcePolicyProvider.ResourcePolicy::policyDocument)
.filter(doc -> doc != null && !doc.isBlank())
.toList();
}
Map<String, List<String>> effectiveContext = IamConditionContextResolver.withGlobalContext(
conditionContext, resource, region, accountId, effectiveOwnerAccountId, action);
if (effectiveDecision == null) {
effectiveDecision = evaluator.evaluateResourcePolicyFor(
policyDocs.isEmpty() ? null : policyDocs,
RequestPrincipal.caller(caller.arns().orElse(null)), action, resource, effectiveContext);
}
ResourceAccountRelationship accountRelationship = effectiveOwnerAccountId == null
|| accountId.equals(effectiveOwnerAccountId)
? ResourceAccountRelationship.SAME_ACCOUNT
: ResourceAccountRelationship.CROSS_ACCOUNT;
Decision decision = evaluator.evaluateResolvedResourcePolicy(
caller.context(), effectiveDecision, accountRelationship,
action, resource, effectiveContext);
return new Decided(decision, effectiveContext);
}
/**
* Resolves the account that owns {@code akid} directly from the credential, following the
* same precedence {@link AccountContextFilter} applies to a header or presigned-URL request:
@@ -304,6 +304,22 @@ final class RequestResourceMembers {
record Forwarded(String action, String type, String of, String member, String endpoint, String viaService) {
}
/**
* A request an operation's service makes to another service as the caller to run a statement the operation's
* request carries: {@code action}, on each of {@code resources}, and only for a partitioned table when
* {@code partitioned} (the page vendored for Athena's DDL statements says a table without partitions needs no
* partition action).
*/
record StatementRequest(String action, List<StatementResource> resources, boolean partitioned) {
}
/**
* A resource of a statement's request: of {@code type}, each variable of its format in {@code fill} taking what
* the statement names by that word ({@code database}, {@code table}), the others open.
*/
record StatementResource(String type, Map<String, String> fill) {
}
/**
* The file: each operation's resources, the resource types its action acts on, the resources it creates under a
* parent and the one a create whose action acts on no type, or on other types alone, makes ({@code makes}), as
@@ -311,7 +327,8 @@ final class RequestResourceMembers {
* namespace's ARN formats, and the namespaces it reads, those built by hand, those not read yet, and the others
* with resource types. A located member is a label of the request's path, {@code {Label}}, or a parameter of its
* query, {@code ?name}, by the member's name. Each operation's {@code forwarded} requests are those its service
* makes to another as the caller.
* makes to another as the caller, and its {@code statements} those it makes as the caller to run each statement its
* request may carry.
*/
record Table(Map<String, List<Resource>> operations, Map<String, List<String>> types,
Map<String, List<Created>> creates, Map<String, List<Resource>> makes,
@@ -321,7 +338,7 @@ final class RequestResourceMembers {
Map<String, Map<String, List<String>>> resourceTagKeys,
Map<String, Map<String, Map<String, ResourceKey>>> resourceKeys,
Set<String> namespaces, Set<String> handBuilt, Set<String> notCovered, Set<String> otherNamespaces,
Map<String, List<Forwarded>> forwarded) {
Map<String, List<Forwarded>> forwarded, Map<String, Map<String, List<StatementRequest>>> statements) {
}
private static final class Holder {
@@ -527,7 +544,57 @@ final class RequestResourceMembers {
Map.copyOf(resourceTagKeys), resourceKeys, namespaces,
names(document.path("handBuilt")),
Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()),
names(document.path("otherNamespaces")), Map.copyOf(forwarded));
names(document.path("otherNamespaces")), Map.copyOf(forwarded), statements(document, formats));
}
/**
* Each operation's statements and the requests each makes, refusing an action the file records no types for, a
* resource of a type it does not record for the action or with no format, and a variable its format does not have.
*/
private static Map<String, Map<String, List<StatementRequest>>> statements(
JsonNode document, Map<String, Map<String, ArnFormat>> formats) {
JsonNode actions = document.path("statementActions");
Map<String, Map<String, List<StatementRequest>>> found = new LinkedHashMap<>();
document.path("statements").properties().forEach(operation -> {
Map<String, List<StatementRequest>> byStatement = new LinkedHashMap<>();
operation.getValue().properties().forEach(statement -> {
List<StatementRequest> requests = new ArrayList<>();
for (JsonNode request : statement.getValue()) {
requests.add(statementRequest(operation.getKey() + " " + statement.getKey(), request, actions,
formats));
}
byStatement.put(statement.getKey(), List.copyOf(requests));
});
found.put(operation.getKey(), Map.copyOf(byStatement));
});
return Map.copyOf(found);
}
private static StatementRequest statementRequest(String statement, JsonNode request, JsonNode actions,
Map<String, Map<String, ArnFormat>> formats) {
String action = request.path("action").asText("");
Set<String> types = Set.copyOf(actions.path(action).valueStream().map(JsonNode::asText).toList());
Map<String, ArnFormat> namespaceFormats = formats.getOrDefault(
action.substring(0, Math.max(0, action.indexOf(':'))), Map.of());
List<StatementResource> resources = new ArrayList<>();
for (JsonNode resource : request.path("resources")) {
String type = resource.path("type").asText("");
ArnFormat format = namespaceFormats.get(type);
Map<String, String> fill = new LinkedHashMap<>();
resource.path("fill").properties()
.forEach(variable -> fill.put(variable.getKey(), variable.getValue().asText("")));
if (!types.contains(type) || format == null || fill.entrySet().stream().anyMatch(entry ->
entry.getValue().isEmpty() || !format.format().contains("${" + entry.getKey() + "}"))) {
throw new IllegalStateException(RESOURCE_NAME + " gives " + statement + " " + resource + " for "
+ action + ", no resource of a type the file records for the action");
}
resources.add(new StatementResource(type, Map.copyOf(fill)));
}
if (types.isEmpty() || resources.isEmpty()) {
throw new IllegalStateException(RESOURCE_NAME + " gives " + statement + " " + request
+ ", no recorded action on resources");
}
return new StatementRequest(action, List.copyOf(resources), request.path("partitioned").asBoolean(false));
}
/** Each resource type's member-named condition keys, by namespace, refusing a type or ARN type with no format. */
@@ -208,6 +208,43 @@ public final class RequestResources {
return List.copyOf(found);
}
/** A request a statement's run makes to another service as the caller: {@code action} on {@code resource}. */
public record StatementRequest(String action, String resource) {
}
/**
* The requests the operation's service makes to another service as the caller to run {@code statement}, as the
* table's {@code statements} give them, from the page of AWS's documentation vendored for them: each action on
* each of its resources, in the request's partition, Region and account, a variable taking what {@code names}
* gives the word the table fills it with ({@code database}, {@code table}) and open where it fills it with none. A
* table without partitions makes no partition request. None for a statement the table gives no requests.
*/
public static List<StatementRequest> statementRequests(String operation, String statement,
Map<String, String> names, boolean partitioned,
String partition, String region, String accountId) {
RequestResourceMembers.Table table = RequestResourceMembers.table();
List<StatementRequest> requests = new ArrayList<>();
for (RequestResourceMembers.StatementRequest request : table.statements()
.getOrDefault(operation, Map.of()).getOrDefault(statement, List.of())) {
if (request.partitioned() && !partitioned) {
continue;
}
Map<String, RequestResourceMembers.ArnFormat> formats = table.formats()
.getOrDefault(request.action().substring(0, request.action().indexOf(':')), Map.of());
for (RequestResourceMembers.StatementResource resource : request.resources()) {
Map<String, String> filling = new HashMap<>();
resource.fill().forEach((variable, word) -> {
if (names.get(word) != null) {
filling.put(variable, names.get(word));
}
});
requests.add(new StatementRequest(request.action(),
render(formats.get(resource.type()).format(), filling, partition, region, accountId)));
}
}
return List.copyOf(requests);
}
/** Whether the table holds the operation as one with no resource of its own, which is checked on {@code *}. */
public static boolean actsOnNoResource(String operation) {
return reads(operation) && !hasIndividualTargets(operation)
@@ -5,6 +5,7 @@ import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.CsvParser;
import io.floci.aws.core.common.IamEnforcementFilter;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
@@ -77,6 +78,7 @@ public class AthenaService {
public static final String DEFAULT_CATALOG = "AwsDataCatalog";
private static final String DEFAULT_OUTPUT_BUCKET = "floci-athena-results";
private static final String DEFAULT_WORKGROUP = "primary";
private static final String START_QUERY_EXECUTION = "athena:StartQueryExecution";
private static final String DEFAULT_ENGINE_VERSION = "Athena engine version 3";
/** The engine version a workgroup selects when its request names none: AWS picks the version. */
private static final String AUTO_ENGINE_VERSION = "AUTO";
@@ -119,6 +121,7 @@ public class AthenaService {
private final RegionResolver regionResolver;
private final AthenaHiveDdlExecutor hiveDdlExecutor;
private final AthenaIcebergStatements icebergStatements;
private final IamEnforcementFilter iamEnforcementFilter;
@Inject
public AthenaService(StorageFactory storageFactory,
@@ -129,7 +132,8 @@ public class AthenaService {
Vertx vertx,
GlueViewDdlBuilder ddlBuilder,
RegionResolver regionResolver,
AthenaIcebergStatements icebergStatements) {
AthenaIcebergStatements icebergStatements,
IamEnforcementFilter iamEnforcementFilter) {
this.queryStore = storageFactory.create("athena", "queries.json",
new TypeReference<>() {});
this.workGroupStore = storageFactory.create("athena", "workgroups.json",
@@ -146,6 +150,7 @@ public class AthenaService {
this.ddlBuilder = ddlBuilder;
this.regionResolver = regionResolver;
this.icebergStatements = icebergStatements;
this.iamEnforcementFilter = iamEnforcementFilter;
this.hiveDdlExecutor = new AthenaHiveDdlExecutor(glueService, s3Service, icebergStatements);
}
@@ -199,6 +204,9 @@ public class AthenaService {
if (invalidHiveDdl != null) {
throw invalidHiveDdl;
}
if (s3TablesBucket == null) {
requireGluePermissions(hiveDdl, database);
}
List<String> rows = hiveDdlExecutor.execute(hiveDdl, resolvedContext.getCatalog(), database);
if (outputLocation != null) {
writeSingleColumnResult(id, outputLocation, "partition", rows);
@@ -216,6 +224,10 @@ public class AthenaService {
if (createDatabaseDdl == null) {
throw new AwsException("InvalidRequestException", "Invalid CREATE DATABASE statement", 400);
}
if (s3TablesBucket == null) {
requireGluePermissions("CREATE DATABASE",
Map.of("database", GlueService.normalizeName(createDatabaseDdl.name())), false);
}
if (s3TablesBucket != null) {
// In an S3 Tables catalog a database is a namespace of the table bucket.
icebergStatements.createNamespace(s3TablesBucket, createDatabaseDdl.name(),
@@ -784,6 +796,59 @@ public class AthenaService {
}
}
/**
* Fails the query as Athena does when the caller may not make the Glue requests a statement of the default catalog
* makes. Athena runs a DDL statement against the Glue Data Catalog with the caller's identity, and a denial fails
* the query rather than the request, its reason as AWS reports it: "Insufficient permissions to execute the query.
* User: <caller> is not authorized to perform: glue:GetDatabase on resource: arn:aws:glue:<region>:<account>:catalog
* because no identity-based policy allows the glue:GetDatabase action ". The requests each statement makes are
* the IAM table's, read from the permissions Athena's user guide gives each DDL statement, named as the guide
* names the statement; one it gives none makes none, and only a partitioned table's makes partition requests.
*/
private void requireGluePermissions(AthenaHiveDdl.Statement statement, String contextDatabase) {
String documented = switch (statement) {
case AthenaHiveDdl.CreateTable create -> "CREATE TABLE";
case AthenaHiveDdl.CreateIcebergTable create -> "CREATE TABLE";
case AthenaHiveDdl.DropTable drop -> "DROP TABLE";
case AthenaHiveDdl.RepairTable repair -> "MSCK REPAIR TABLE";
default -> null;
};
if (documented == null) {
return;
}
// Glue names a database and a table in an ARN as it stores them, lowercase, however the query spells them.
String database = GlueService.normalizeName(
statement.ref().database() != null ? statement.ref().database() : contextDatabase);
String table = GlueService.normalizeName(statement.ref().table());
boolean partitioned = statement instanceof AthenaHiveDdl.DropTable && isPartitioned(database, table);
requireGluePermissions(documented, Map.of("database", database, "table", table), partitioned);
}
private void requireGluePermissions(String statement, Map<String, String> names, boolean partitioned) {
Optional<String> refusal = iamEnforcementFilter.statementRefusal(START_QUERY_EXECUTION, statement, names,
partitioned);
if (refusal.isPresent()) {
throw new AwsException("AccessDeniedException",
"Insufficient permissions to execute the query. " + refusal.get() + " ", 400);
}
}
/**
* Whether the catalog holds the table with partition keys. A table it does not hold has none, so dropping it makes
* no partition request; any other failure to read the table fails the query, as the drop itself would.
*/
private boolean isPartitioned(String database, String table) {
try {
Table held = glueService.getTable(database, table);
return held.getPartitionKeys() != null && !held.getPartitionKeys().isEmpty();
} catch (AwsException e) {
if (!"EntityNotFoundException".equals(e.getErrorCode())) {
throw e;
}
return false;
}
}
private void markFailed(String id, QueryExecution execution, Throwable failure) {
synchronized (execution) {
if (isTerminal(execution.getStatus().getState())) {
@@ -1520,7 +1520,8 @@ public class GlueService {
return value;
}
private static String normalizeName(String name) {
/** A database, table or function name as Glue stores it and names it in an ARN: lowercase. */
public static String normalizeName(String name) {
return name.toLowerCase(Locale.ROOT);
}
@@ -12,6 +12,8 @@
"mintedSuffixes": {"secretsmanager": {"Secret": "-??????"}},
"integerVariables": {"lambda": {"layerVersion": ["LayerVersion"]}},
"forwardedActions": {"kms:Decrypt": {"type": "key", "format": "arn:${Partition}:kms:${Region}:${Account}:key/${KeyId}", "viaService": "kms:ViaService"}},
"statementActions": {"glue:BatchCreatePartition": ["catalog", "database", "rootcatalog", "table"], "glue:CreateDatabase": ["catalog", "database", "rootcatalog"], "glue:CreateTable": ["catalog", "database", "rootcatalog", "table"], "glue:DeleteDatabase": ["catalog", "database", "rootcatalog", "table", "userdefinedfunction"], "glue:DeletePartition": ["catalog", "database", "rootcatalog", "table"], "glue:DeleteTable": ["catalog", "database", "rootcatalog", "table"], "glue:GetDatabase": ["catalog", "database", "rootcatalog"], "glue:GetDatabases": ["catalog", "database", "rootcatalog"], "glue:GetPartition": ["catalog", "database", "rootcatalog", "table"], "glue:GetPartitions": ["catalog", "database", "rootcatalog", "table"], "glue:GetTable": ["catalog", "database", "rootcatalog", "table"], "glue:GetTables": ["catalog", "database", "rootcatalog", "table"], "glue:UpdateDatabase": ["catalog", "database", "rootcatalog"]},
"statements": {"athena:StartQueryExecution": {"ALTER DATABASE": [{"action": "glue:GetDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:UpdateDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}], "CREATE DATABASE": [{"action": "glue:GetDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:CreateDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}], "CREATE TABLE": [{"action": "glue:GetDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:GetDatabases", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:GetTables", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}, {"action": "glue:GetTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}, {"action": "glue:GetPartitions", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}, {"action": "glue:CreateTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}], "DROP DATABASE": [{"action": "glue:GetDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:DeleteDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database"}}, {"type": "userdefinedfunction", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:GetTables", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:GetTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:DeleteTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database"}}]}], "DROP TABLE": [{"action": "glue:GetDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:GetTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}, {"action": "glue:DeleteTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}, {"action": "glue:GetPartitions", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}], "partitioned": true}, {"action": "glue:GetPartition", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}], "partitioned": true}, {"action": "glue:DeletePartition", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}], "partitioned": true}], "MSCK REPAIR TABLE": [{"action": "glue:GetDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:CreateDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:GetTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}, {"action": "glue:GetPartitions", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}Line truncated
"operations": {
"access-analyzer:ApplyArchiveRule": {"action": "access-analyzer:ApplyArchiveRule", "types": ["Analyzer"], "resources": [{"types": ["Analyzer"], "arn": "analyzerArn"}]},
"access-analyzer:CancelPolicyGeneration": {"action": "access-analyzer:CancelPolicyGeneration", "types": [], "resources": []},
@@ -856,6 +858,7 @@
"cognito-idp:ForgotPassword": {"action": "cognito-idp:ForgotPassword", "types": [], "resources": []},
"cognito-idp:GetCSVHeader": {"action": "cognito-idp:GetCSVHeader", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
"cognito-idp:GetClientToken": {"action": "cognito-idp:GetClientToken", "types": [], "resources": []},
"cognito-idp:GetDerivedToken": {"action": "cognito-idp:GetDerivedToken", "types": [], "resources": []},
"cognito-idp:GetDevice": {"action": "cognito-idp:GetDevice", "types": [], "resources": []},
"cognito-idp:GetGroup": {"action": "cognito-idp:GetGroup", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
"cognito-idp:GetIdentityProviderByIdentifier": {"action": "cognito-idp:GetIdentityProviderByIdentifier", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
@@ -1042,6 +1045,7 @@
"ec2:AssociateInstanceEventWindow": {"action": "ec2:AssociateInstanceEventWindow", "types": ["instance-event-window"], "resources": [{"type": "instance-event-window", "fill": {"InstanceEventWindowId": "InstanceEventWindowId"}}]},
"ec2:AssociateIpamByoasn": {"action": "ec2:AssociateIpamByoasn", "types": [], "resources": []},
"ec2:AssociateIpamResourceDiscovery": {"action": "ec2:AssociateIpamResourceDiscovery", "types": ["ipam", "ipam-resource-discovery", "ipam-resource-discovery-association"], "resources": [{"type": "ipam", "fill": {"IpamId": "IpamId"}}, {"type": "ipam-resource-discovery", "fill": {"IpamResourceDiscoveryId": "IpamResourceDiscoveryId"}}]},
"ec2:AssociateKmsKeyId": {"action": "ec2:AssociateKmsKeyId", "types": [], "resources": []},
"ec2:AssociateNatGatewayAddress": {"action": "ec2:AssociateNatGatewayAddress", "types": ["elastic-ip", "natgateway"], "resources": [{"type": "elastic-ip", "fill": {"AllocationId": "AllocationIds[]"}}, {"type": "natgateway", "fill": {"NatGatewayId": "NatGatewayId"}}], "ec2Query": {"AllocationIds[]": "AllocationId"}},
"ec2:AssociateNetworkingFlexCostAllocationPolicy": {"action": "ec2:AssociateNetworkingFlexCostAllocationPolicy", "types": [], "resources": []},
"ec2:AssociateRouteServer": {"action": "ec2:AssociateRouteServer", "types": ["route-server", "vpc"], "resources": [{"type": "route-server", "fill": {"RouteServerId": "RouteServerId"}}, {"type": "vpc", "fill": {"VpcId": "VpcId"}}]},
@@ -1169,6 +1173,7 @@
"ec2:CreateTransitGatewayMeteringPolicy": {"action": "ec2:CreateTransitGatewayMeteringPolicy", "types": ["transit-gateway", "transit-gateway-attachment", "transit-gateway-metering-policy"], "resources": [{"type": "transit-gateway", "fill": {"TransitGatewayId": "TransitGatewayId"}}, {"type": "transit-gateway-metering-policy", "fill": {}, "made": true}]},
"ec2:CreateTransitGatewayMeteringPolicyEntry": {"action": "ec2:CreateTransitGatewayMeteringPolicyEntry", "types": ["transit-gateway-attachment", "transit-gateway-metering-policy"], "resources": [{"type": "transit-gateway-attachment", "fill": {"TransitGatewayAttachmentId": "SourceTransitGatewayAttachmentId"}}, {"type": "transit-gateway-metering-policy", "fill": {"TransitGatewayMeteringPolicyId": "TransitGatewayMeteringPolicyId"}}, {"type": "transit-gateway-attachment", "fill": {"TransitGatewayAttachmentId": "DestinationTransitGatewayAttachmentId"}}]},
"ec2:CreateTransitGatewayMulticastDomain": {"action": "ec2:CreateTransitGatewayMulticastDomain", "types": ["transit-gateway", "transit-gateway-multicast-domain"], "resources": [{"type": "transit-gateway", "fill": {"TransitGatewayId": "TransitGatewayId"}}, {"type": "transit-gateway-multicast-domain", "fill": {}, "made": true}]},
"ec2:CreateTransitGatewayNetworkFunctionAttachment": {"action": "ec2:CreateTransitGatewayNetworkFunctionAttachment", "types": [], "resources": []},
"ec2:CreateTransitGatewayPeeringAttachment": {"action": "ec2:CreateTransitGatewayPeeringAttachment", "types": ["transit-gateway", "transit-gateway-attachment"], "resources": [{"type": "transit-gateway", "fill": {"TransitGatewayId": "TransitGatewayId"}}]},
"ec2:CreateTransitGatewayPolicyTable": {"action": "ec2:CreateTransitGatewayPolicyTable", "types": ["transit-gateway", "transit-gateway-policy-table"], "resources": [{"type": "transit-gateway", "fill": {"TransitGatewayId": "TransitGatewayId"}}, {"type": "transit-gateway-policy-table", "fill": {}, "made": true}]},
"ec2:CreateTransitGatewayPolicyTableEntry": {"action": "ec2:CreateTransitGatewayPolicyTableEntry", "types": ["transit-gateway-policy-table", "transit-gateway-route-table"], "resources": [{"type": "transit-gateway-policy-table", "fill": {"TransitGatewayPolicyTableId": "TransitGatewayPolicyTableId"}}, {"type": "transit-gateway-route-table", "fill": {"TransitGatewayRouteTableId": "TargetRouteTableId"}}]},
@@ -1269,6 +1274,7 @@
"ec2:DeleteTransitGatewayMeteringPolicy": {"action": "ec2:DeleteTransitGatewayMeteringPolicy", "types": ["transit-gateway-metering-policy"], "resources": [{"type": "transit-gateway-metering-policy", "fill": {"TransitGatewayMeteringPolicyId": "TransitGatewayMeteringPolicyId"}}]},
"ec2:DeleteTransitGatewayMeteringPolicyEntry": {"action": "ec2:DeleteTransitGatewayMeteringPolicyEntry", "types": ["transit-gateway-metering-policy"], "resources": [{"type": "transit-gateway-metering-policy", "fill": {"TransitGatewayMeteringPolicyId": "TransitGatewayMeteringPolicyId"}}]},
"ec2:DeleteTransitGatewayMulticastDomain": {"action": "ec2:DeleteTransitGatewayMulticastDomain", "types": ["transit-gateway-multicast-domain"], "resources": [{"type": "transit-gateway-multicast-domain", "fill": {"TransitGatewayMulticastDomainId": "TransitGatewayMulticastDomainId"}}]},
"ec2:DeleteTransitGatewayNetworkFunctionAttachment": {"action": "ec2:DeleteTransitGatewayNetworkFunctionAttachment", "types": [], "resources": []},
"ec2:DeleteTransitGatewayPeeringAttachment": {"action": "ec2:DeleteTransitGatewayPeeringAttachment", "types": ["transit-gateway-attachment"], "resources": [{"type": "transit-gateway-attachment", "fill": {"TransitGatewayAttachmentId": "TransitGatewayAttachmentId"}}]},
"ec2:DeleteTransitGatewayPolicyTable": {"action": "ec2:DeleteTransitGatewayPolicyTable", "types": ["transit-gateway-policy-table"], "resources": [{"type": "transit-gateway-policy-table", "fill": {"TransitGatewayPolicyTableId": "TransitGatewayPolicyTableId"}}]},
"ec2:DeleteTransitGatewayPolicyTableEntry": {"action": "ec2:DeleteTransitGatewayPolicyTableEntry", "types": ["transit-gateway-policy-table"], "resources": [{"type": "transit-gateway-policy-table", "fill": {"TransitGatewayPolicyTableId": "TransitGatewayPolicyTableId"}}]},
@@ -1463,6 +1469,7 @@
"ec2:DescribeTransitGatewayConnects": {"action": "ec2:DescribeTransitGatewayConnects", "types": [], "resources": []},
"ec2:DescribeTransitGatewayMeteringPolicies": {"action": "ec2:DescribeTransitGatewayMeteringPolicies", "types": [], "resources": []},
"ec2:DescribeTransitGatewayMulticastDomains": {"action": "ec2:DescribeTransitGatewayMulticastDomains", "types": [], "resources": []},
"ec2:DescribeTransitGatewayNetworkFunctionAttachments": {"action": "ec2:DescribeTransitGatewayNetworkFunctionAttachments", "types": [], "resources": []},
"ec2:DescribeTransitGatewayPeeringAttachments": {"action": "ec2:DescribeTransitGatewayPeeringAttachments", "types": [], "resources": []},
"ec2:DescribeTransitGatewayPolicyTables": {"action": "ec2:DescribeTransitGatewayPolicyTables", "types": [], "resources": []},
"ec2:DescribeTransitGatewayRouteTableAnnouncements": {"action": "ec2:DescribeTransitGatewayRouteTableAnnouncements", "types": [], "resources": []},
@@ -1535,6 +1542,7 @@
"ec2:DisassociateInstanceEventWindow": {"action": "ec2:DisassociateInstanceEventWindow", "types": ["instance-event-window"], "resources": [{"type": "instance-event-window", "fill": {"InstanceEventWindowId": "InstanceEventWindowId"}}]},
"ec2:DisassociateIpamByoasn": {"action": "ec2:DisassociateIpamByoasn", "types": [], "resources": []},
"ec2:DisassociateIpamResourceDiscovery": {"action": "ec2:DisassociateIpamResourceDiscovery", "types": ["ipam-resource-discovery-association"], "resources": [{"type": "ipam-resource-discovery-association", "fill": {"IpamResourceDiscoveryAssociationId": "IpamResourceDiscoveryAssociationId"}}]},
"ec2:DisassociateKmsKeyId": {"action": "ec2:DisassociateKmsKeyId", "types": [], "resources": []},
"ec2:DisassociateNatGatewayAddress": {"action": "ec2:DisassociateNatGatewayAddress", "types": ["elastic-ip", "natgateway", "network-interface"], "resources": [{"type": "natgateway", "fill": {"NatGatewayId": "NatGatewayId"}}]},
"ec2:DisassociateNetworkingFlexCostAllocationPolicy": {"action": "ec2:DisassociateNetworkingFlexCostAllocationPolicy", "types": [], "resources": []},
"ec2:DisassociateRouteServer": {"action": "ec2:DisassociateRouteServer", "types": ["route-server", "vpc"], "resources": [{"type": "route-server", "fill": {"RouteServerId": "RouteServerId"}}, {"type": "vpc", "fill": {"VpcId": "VpcId"}}]},
@@ -1728,6 +1736,7 @@
"ec2:ModifyTransitGateway": {"action": "ec2:ModifyTransitGateway", "types": ["transit-gateway", "transit-gateway-route-table"], "resources": [{"type": "transit-gateway", "fill": {"TransitGatewayId": "TransitGatewayId"}}]},
"ec2:ModifyTransitGatewayAttachmentNatConfiguration": {"action": "ec2:ModifyTransitGatewayAttachmentNatConfiguration", "types": ["transit-gateway-attachment"], "resources": [{"type": "transit-gateway-attachment", "fill": {"TransitGatewayAttachmentId": "TransitGatewayAttachmentId"}}]},
"ec2:ModifyTransitGatewayMeteringPolicy": {"action": "ec2:ModifyTransitGatewayMeteringPolicy", "types": ["transit-gateway-attachment", "transit-gateway-metering-policy"], "resources": [{"type": "transit-gateway-metering-policy", "fill": {"TransitGatewayMeteringPolicyId": "TransitGatewayMeteringPolicyId"}}]},
"ec2:ModifyTransitGatewayNetworkFunctionAttachment": {"action": "ec2:ModifyTransitGatewayNetworkFunctionAttachment", "types": [], "resources": []},
"ec2:ModifyTransitGatewayPolicyTableEntry": {"action": "ec2:ModifyTransitGatewayPolicyTableEntry", "types": ["transit-gateway-policy-table", "transit-gateway-route-table"], "resources": [{"type": "transit-gateway-policy-table", "fill": {"TransitGatewayPolicyTableId": "TransitGatewayPolicyTableId"}}, {"type": "transit-gateway-route-table", "fill": {"TransitGatewayRouteTableId": "TargetRouteTableId"}}]},
"ec2:ModifyTransitGatewayPrefixListReference": {"action": "ec2:ModifyTransitGatewayPrefixListReference", "types": ["prefix-list", "transit-gateway-attachment", "transit-gateway-route-table"], "resources": [{"type": "prefix-list", "fill": {"PrefixListId": "PrefixListId"}}, {"type": "transit-gateway-attachment", "fill": {"TransitGatewayAttachmentId": "TransitGatewayAttachmentId"}}, {"type": "transit-gateway-route-table", "fill": {"TransitGatewayRouteTableId": "TransitGatewayRouteTableId"}}]},
"ec2:ModifyTransitGatewayVpcAttachment": {"action": "ec2:ModifyTransitGatewayVpcAttachment", "types": ["subnet", "transit-gateway-attachment"], "resources": [{"type": "subnet", "fill": {"SubnetId": "AddSubnetIds[]"}}, {"type": "transit-gateway-attachment", "fill": {"TransitGatewayAttachmentId": "TransitGatewayAttachmentId"}}], "ec2Query": {"AddSubnetIds[]": "AddSubnetIds"}},
@@ -4292,6 +4301,7 @@
"s3vectors:TagResource": {"action": "s3vectors:TagResource", "types": ["Index", "VectorBucket"], "resources": [{"types": ["Index", "VectorBucket"], "arn": "resourceArn"}], "located": {"resourceArn": "{resourceArn}"}},
"s3vectors:UntagResource": {"action": "s3vectors:UntagResource", "types": ["Index", "VectorBucket"], "resources": [{"types": ["Index", "VectorBucket"], "arn": "resourceArn"}], "located": {"resourceArn": "{resourceArn}"}},
"s3vectors:UpdateIndexMode": {"action": "s3vectors:UpdateIndexMode", "types": ["Index"], "resources": [{"types": ["Index"], "arn": "indexArn"}, {"type": "Index", "fill": {"BucketName": "vectorBucketName", "IndexName": "indexName"}}]},
"s3vectors:UpdateMetadataConfiguration": {"action": "s3vectors:UpdateMetadataConfiguration", "types": ["Index"], "resources": []},
"scheduler:CreateSchedule": {"action": "scheduler:CreateSchedule", "types": ["schedule"], "resources": [{"types": ["schedule"], "arn": "Target.Arn"}, {"type": "schedule", "fill": {"GroupName": "GroupName", "ScheduleName": "Name"}, "defaults": {"GroupName": "schedule-group"}}], "located": {"Name": "{Name}"}},
"scheduler:CreateScheduleGroup": {"action": "scheduler:CreateScheduleGroup", "types": ["schedule-group"], "resources": [{"type": "schedule-group", "fill": {"GroupName": "Name"}}], "located": {"Name": "{Name}"}},
"scheduler:DeleteSchedule": {"action": "scheduler:DeleteSchedule", "types": ["schedule"], "resources": [{"type": "schedule", "fill": {"GroupName": "GroupName", "ScheduleName": "Name"}, "defaults": {"GroupName": "schedule-group"}}], "located": {"GroupName": "?groupName", "Name": "{Name}"}},
@@ -1228,6 +1228,49 @@ class RequestResourcesTest {
serverless, namespace -> kms));
}
/**
* A DDL statement Athena runs against the Glue Data Catalog makes, as the caller, the Glue requests the table gives
* it from the permissions Athena's user guide gives each statement: each action on the catalog, the database and
* the table the statement names, in the request's partition, Region and account, partition actions only for a
* partitioned table, and none for a statement the guide gives no permissions.
*/
@Test
void aStatementMakesTheRequestsTheVendoredPermissionsGiveItOnWhatItNames() {
String operation = "athena:StartQueryExecution";
String glue = "arn:aws-cn:glue:cn-north-1:111122223333:";
Map<String, String> names = Map.of("database", "sales", "table", "orders");
List<RequestResources.StatementRequest> drop = RequestResources.statementRequests(operation, "DROP TABLE",
names, false, "aws-cn", "cn-north-1", "111122223333");
assertEquals(List.of(
new RequestResources.StatementRequest("glue:GetDatabase", glue + "catalog"),
new RequestResources.StatementRequest("glue:GetDatabase", glue + "database/sales"),
new RequestResources.StatementRequest("glue:GetTable", glue + "catalog"),
new RequestResources.StatementRequest("glue:GetTable", glue + "database/sales"),
new RequestResources.StatementRequest("glue:GetTable", glue + "table/sales/orders"),
new RequestResources.StatementRequest("glue:DeleteTable", glue + "catalog"),
new RequestResources.StatementRequest("glue:DeleteTable", glue + "database/sales"),
new RequestResources.StatementRequest("glue:DeleteTable", glue + "table/sales/orders")), drop);
List<String> partitioned = RequestResources.statementRequests(operation, "DROP TABLE", names, true, "aws-cn",
"cn-north-1", "111122223333").stream().map(RequestResources.StatementRequest::action).distinct().toList();
assertEquals(List.of("glue:GetDatabase", "glue:GetTable", "glue:DeleteTable", "glue:GetPartitions",
"glue:GetPartition", "glue:DeletePartition"), partitioned);
// A wildcard of the guide's policy stays open; the database a statement creates is named by its name.
assertTrue(RequestResources.statementRequests(operation, "SHOW TABLES", names, false, "aws", "us-east-1",
"000000000000").contains(new RequestResources.StatementRequest("glue:GetTables",
"arn:aws:glue:us-east-1:000000000000:table/sales/*")));
assertEquals(List.of("arn:aws:glue:us-east-1:000000000000:catalog",
"arn:aws:glue:us-east-1:000000000000:database/sales"),
RequestResources.statementRequests(operation, "CREATE DATABASE", Map.of("database", "sales"), false,
"aws", "us-east-1", "000000000000").stream()
.filter(request -> request.action().equals("glue:CreateDatabase"))
.map(RequestResources.StatementRequest::resource).toList());
assertEquals(List.of(), RequestResources.statementRequests(operation, "VACUUM", names, false, "aws",
"us-east-1", "000000000000"));
assertEquals(List.of(), RequestResources.statementRequests("athena:GetWorkGroup", "DROP TABLE", names, false,
"aws", "us-east-1", "000000000000"));
}
/**
* An ECS request names its cluster by name or ARN, and the default cluster, which ECS gives, when it names none; a
* service or a task given by its own ARN is that resource, and by its name in the cluster the request names too
@@ -0,0 +1,215 @@
package io.floci.aws.services.athena;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.path.json.JsonPath;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.util.Locale;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Athena runs a DDL statement against the Glue Data Catalog with the caller's identity, so under IAM enforcement the
* statement needs the Glue permissions Athena's user guide gives it. A caller without them still starts the query,
* which fails with AWS's reason, "Insufficient permissions to execute the query." and the denial of the first Glue
* request refused. The policies granted here are the guide's examples for each statement, with this test's names.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class AthenaGluePermissionsIntegrationTest {
private static final String ADMIN = "test";
private static final String GLUE = "arn:aws:glue:us-east-1:000000000000:";
private static final String ATHENA = "{\"Effect\":\"Allow\",\"Action\":\"athena:*\",\"Resource\":\"*\"}";
@TestHTTPResource("/")
static URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void createDatabaseWithoutGluePermissionsFailsTheQueryAndCreatesNothing() {
String database = "perm_db_" + suffix();
User user = user("athena-perm-db");
user.policy(ATHENA);
JsonPath failed = user.run("CREATE DATABASE " + database);
assertEquals("FAILED", failed.getString("QueryExecution.Status.State"));
assertEquals("Insufficient permissions to execute the query. User: arn:aws:iam::000000000000:user/"
+ user.name() + " is not authorized to perform: glue:GetDatabase on resource: " + GLUE
+ "catalog because no identity-based policy allows the glue:GetDatabase action ",
failed.getString("QueryExecution.Status.StateChangeReason"));
glue("GetDatabase", "{\"Name\":\"" + database + "\"}").statusCode(400)
.body("__type", equalTo("EntityNotFoundException"));
user.policy(ATHENA + "," + allow(new String[]{"glue:GetDatabase", "glue:CreateDatabase"},
GLUE + "catalog", GLUE + "database/" + database));
cleanup.register(() -> glue("DeleteDatabase", "{\"Name\":\"" + database + "\"}"));
assertEquals("SUCCEEDED", user.run("CREATE DATABASE " + database).getString("QueryExecution.Status.State"));
glue("GetDatabase", "{\"Name\":\"" + database + "\"}").statusCode(200);
}
@Test
void createTableNeedsEveryActionOfTheGuidesPolicyOnTheCatalogDatabaseAndTable() {
String database = database();
String table = "orders";
String create = "CREATE EXTERNAL TABLE " + database + "." + table
+ " (id string) LOCATION 's3://athena-perm-" + suffix() + "/orders/'";
String databaseStatement = allow(new String[]{"glue:GetDatabase", "glue:GetDatabases"}, GLUE + "catalog",
GLUE + "database/" + database);
String[] tableResources = {GLUE + "catalog", GLUE + "database/" + database,
GLUE + "table/" + database + "/" + table};
User user = user("athena-perm-table");
user.policy(ATHENA + "," + databaseStatement + ","
+ allow(new String[]{"glue:GetTables", "glue:GetTable", "glue:CreateTable"}, tableResources));
JsonPath failed = user.run(create);
assertEquals("FAILED", failed.getString("QueryExecution.Status.State"));
assertEquals("Insufficient permissions to execute the query. User: arn:aws:iam::000000000000:user/"
+ user.name() + " is not authorized to perform: glue:GetPartitions on resource: " + GLUE
+ "catalog because no identity-based policy allows the glue:GetPartitions action ",
failed.getString("QueryExecution.Status.StateChangeReason"));
glue("GetTable", "{\"DatabaseName\":\"" + database + "\",\"Name\":\"" + table + "\"}").statusCode(400);
user.policy(ATHENA + "," + databaseStatement + "," + allow(new String[]{"glue:GetTables", "glue:GetTable",
"glue:GetPartitions", "glue:CreateTable"}, tableResources));
assertEquals("SUCCEEDED", user.run(create).getString("QueryExecution.Status.State"));
glue("GetTable", "{\"DatabaseName\":\"" + database + "\",\"Name\":\"" + table + "\"}").statusCode(200);
}
/**
* The guide's DROP TABLE policy is for a partitioned table, "If your table does not have partitions, do not
* include partition actions", so a table without them drops without those; a deny on the table holds.
*/
@Test
void dropTableOfATableWithoutPartitionsNeedsNoPartitionActionAndADenyOnTheTableHolds() {
String database = database();
String table = "events";
glue("CreateTable", "{\"DatabaseName\":\"" + database + "\",\"TableInput\":{\"Name\":\"" + table + "\"}}")
.statusCode(200);
String tableArn = GLUE + "table/" + database + "/" + table;
String withoutPartitions = allow(new String[]{"glue:GetDatabase", "glue:GetTable", "glue:DeleteTable"},
GLUE + "catalog", GLUE + "database/" + database, tableArn);
User user = user("athena-perm-drop");
user.policy(ATHENA + "," + withoutPartitions + ",{\"Effect\":\"Deny\",\"Action\":\"glue:DeleteTable\","
+ "\"Resource\":\"" + tableArn + "\"}");
JsonPath denied = user.run("DROP TABLE " + database + "." + table);
assertEquals("FAILED", denied.getString("QueryExecution.Status.State"));
assertEquals("Insufficient permissions to execute the query. User: arn:aws:iam::000000000000:user/"
+ user.name() + " is not authorized to perform: glue:DeleteTable on resource: " + tableArn
+ " with an explicit deny in an identity-based policy ",
denied.getString("QueryExecution.Status.StateChangeReason"));
user.policy(ATHENA + "," + withoutPartitions);
assertEquals("SUCCEEDED", user.run("DROP TABLE " + database + "." + table)
.getString("QueryExecution.Status.State"));
glue("GetTable", "{\"DatabaseName\":\"" + database + "\",\"Name\":\"" + table + "\"}").statusCode(400);
}
/**
* Glue names a database and a table in an ARN lowercase, as it stores them, so a deny on that ARN holds however
* the statement or the query's context database spells the name.
*/
@Test
void aDenyOnALowercaseNameHoldsWhateverCaseTheQuerySpellsItIn() {
String database = "perm_db_" + suffix();
User user = user("athena-perm-case");
String allowGlue = "{\"Effect\":\"Allow\",\"Action\":\"glue:*\",\"Resource\":\"*\"}";
user.policy(ATHENA + "," + allowGlue + ",{\"Effect\":\"Deny\",\"Action\":\"glue:CreateDatabase\",\"Resource\":\""
+ GLUE + "database/" + database + "\"}");
JsonPath created = user.run("CREATE DATABASE " + database.toUpperCase(Locale.ROOT));
assertEquals("Insufficient permissions to execute the query. User: arn:aws:iam::000000000000:user/"
+ user.name() + " is not authorized to perform: glue:CreateDatabase on resource: " + GLUE + "database/"
+ database + " with an explicit deny in an identity-based policy ",
created.getString("QueryExecution.Status.StateChangeReason"));
glue("GetDatabase", "{\"Name\":\"" + database + "\"}").statusCode(400);
String existing = database();
user.policy(ATHENA + "," + allowGlue + ",{\"Effect\":\"Deny\",\"Action\":\"glue:CreateTable\",\"Resource\":\""
+ GLUE + "table/" + existing + "/*\"}");
JsonPath table = user.run("CREATE EXTERNAL TABLE Orders (id string) LOCATION 's3://athena-perm-" + suffix()
+ "/orders/'", existing.toUpperCase(Locale.ROOT));
assertEquals("Insufficient permissions to execute the query. User: arn:aws:iam::000000000000:user/"
+ user.name() + " is not authorized to perform: glue:CreateTable on resource: " + GLUE + "table/"
+ existing + "/orders with an explicit deny in an identity-based policy ",
table.getString("QueryExecution.Status.StateChangeReason"));
glue("GetTable", "{\"DatabaseName\":\"" + existing + "\",\"Name\":\"orders\"}").statusCode(400);
}
/** A Glue database the admin creates for one test, deleted afterwards. */
private String database() {
String database = "perm_db_" + suffix();
glue("CreateDatabase", "{\"DatabaseInput\":{\"Name\":\"" + database + "\"}}").statusCode(200);
cleanup.register(() -> glue("DeleteDatabase", "{\"Name\":\"" + database + "\"}"));
return database;
}
private User user(String name) {
String userName = name + "-" + suffix();
return new User(userName, EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ADMIN, "iam"),
userName).accessKeyId());
}
private static String allow(String[] actions, String... resources) {
return "{\"Effect\":\"Allow\",\"Action\":[\"" + String.join("\",\"", actions) + "\"],\"Resource\":[\""
+ String.join("\",\"", resources) + "\"]}";
}
private static ValidatableResponse glue(String operation, String body) {
return given().header("Authorization", auth(ADMIN, "glue")).header("X-Amz-Target", "AWSGlue." + operation)
.contentType("application/x-amz-json-1.1").body(body).when().post("/").then();
}
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
/** An IAM user whose one inline policy each step replaces. */
private record User(String name, String accessKeyId) {
void policy(String statements) {
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ADMIN, "iam"), name, "p",
"{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
}
/** Starts the statement, which the request itself never refuses, and returns its execution once it ends. */
JsonPath run(String query) {
return run(query, null);
}
/** As {@link #run(String)}, with {@code database} as the query's context database when given. */
JsonPath run(String query, String database) {
String context = database == null ? "" : ",\"QueryExecutionContext\":{\"Database\":\"" + database + "\"}";
String id = athena("StartQueryExecution", "{\"QueryString\":\"" + query.replace("\"", "\\\"") + "\""
+ context + "}").statusCode(200).extract().path("QueryExecutionId");
return athena("GetQueryExecution", "{\"QueryExecutionId\":\"" + id + "\"}").statusCode(200).extract()
.jsonPath();
}
private ValidatableResponse athena(String operation, String body) {
return given().header("Authorization", auth(accessKeyId, "athena"))
.header("X-Amz-Target", "AmazonAthena." + operation).contentType("application/x-amz-json-1.1")
.body(body).when().post("/").then();
}
}
}
@@ -2,6 +2,7 @@ package io.floci.aws.services.athena;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.IamEnforcementFilter;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.storage.StorageFactory;
@@ -42,6 +43,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
/**
* Athena's Iceberg statements run end to end through the real floci-duck sidecar: {@code CREATE TABLE} makes a Glue
@@ -101,7 +103,7 @@ class AthenaIcebergSidecarIntegrationTest {
@BeforeEach
void createDatabase() {
athena = new AthenaService(storageFactory, duck, glue, s3, AthenaTestConfigs.realQueries(), vertx, ddlBuilder, regionResolver,
icebergStatements);
icebergStatements, mock(IamEnforcementFilter.class));
long suffix = System.nanoTime();
bucket = "athena-iceberg-" + suffix;
database = "lake_" + suffix;
@@ -1,5 +1,6 @@
package io.floci.aws.services.athena;
import io.floci.aws.core.common.IamEnforcementFilter;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.storage.StorageFactory;
@@ -66,7 +67,8 @@ class AthenaQueryScopeTest {
return null;
}).when(duckClient).execute(anyString(), any(), any(), any());
AthenaService athena = new AthenaService(storageFactory, duckClient, glueService, mock(S3Service.class),
AthenaTestConfigs.realQueries(), vertx, ddlBuilder, regionResolver, mock(AthenaIcebergStatements.class));
AthenaTestConfigs.realQueries(), vertx, ddlBuilder, regionResolver, mock(AthenaIcebergStatements.class),
mock(IamEnforcementFilter.class));
try {
String expected = RequestScopes.callAs(account, REGION, () -> {
glueService.createDatabase(new Database(database));
@@ -1,6 +1,7 @@
package io.floci.aws.services.athena;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.IamEnforcementFilter;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
@@ -68,7 +69,8 @@ class AthenaServiceTest {
when(athena.mock()).thenReturn(false);
service = new AthenaService(storageFactory, duckClient, glueService, s3Service,
config, vertx, ddlBuilder, mock(RegionResolver.class), mock(AthenaIcebergStatements.class));
config, vertx, ddlBuilder, mock(RegionResolver.class), mock(AthenaIcebergStatements.class),
mock(IamEnforcementFilter.class));
}
@AfterEach
@@ -0,0 +1,185 @@
#!/usr/bin/env python3
"""Vendor the Glue permissions Athena's documentation gives each DDL statement into
tools/aws/sources/athena-glue-ddl-permissions.json, a source of regen_iam_request_resources.py.
Athena runs a DDL statement against the AWS Glue Data Catalog with the caller's identity, so the caller needs the
Glue actions the statement calls. Neither botocore nor the Service Reference says which those are: StartQueryExecution
lists no dependent actions. Athena's user guide does, in the table "Examples of database and table-level permissions"
of "Configure access to databases and tables in the AWS Glue Data Catalog":
https://docs.aws.amazon.com/athena/latest/ug/fine-grained-access-to-glue-resources.html
For each statement the table gives the example policy that allows it, written for a database `example_db` and a table
`test` ("In the examples, replace the example_db database and test table with your own database and table names").
This script copies that table as it stands: each statement's sentence and policy, the policy's statements, actions
and example ARNs unchanged, and the sentence naming the example database and table. Nothing in the output is written
by hand. The generator reads the actions and ARNs against the Service Reference.
When the page's layout changes so this script cannot read it, athena-glue-ddl-permissions.prompt.md says how to
rebuild the file from the page by hand and what to check afterwards.
Run from anywhere in the repo:
python3 tools/aws/fetch_athena_glue_ddl_permissions.py # rewrite the vendored file from the page
python3 tools/aws/fetch_athena_glue_ddl_permissions.py --verify # online: the file still says what the page does
"""
from __future__ import annotations
import argparse
import json
import re
import sys
import urllib.request
from datetime import datetime, timezone
from html.parser import HTMLParser
from pathlib import Path
PAGE = "https://docs.aws.amazon.com/athena/latest/ug/fine-grained-access-to-glue-resources.html"
REPO_ROOT = Path(__file__).resolve().parents[2]
OUTPUT = REPO_ROOT / "tools/aws/sources/athena-glue-ddl-permissions.json"
PROMPT = "tools/aws/sources/athena-glue-ddl-permissions.prompt.md"
# The header of the table's first column.
TABLE_HEADER = "DDL statement"
# The sentence naming the example database and table: "replace the example_db database and test table".
EXAMPLES_RE = re.compile(r"replace the (?P<database>\S+) database and (?P<table>\S+) table with your own", re.I)
class StatementTable(HTMLParser):
"""The rows of the table whose first header is `TABLE_HEADER`, each as its first cell's text, the second cell's
text outside its code block and the code block's text, and the page's text outside tables."""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.rows: list[tuple[str, str, str]] = []
self.prose: list[str] = []
self._depth = 0
self._in_table = False
self._header: list[str] | None = None
self._cells: list[list[str]] | None = None
self._code: list[str] | None = None
self._in_pre = False
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag == "table":
self._depth += 1
self._header = []
elif tag == "tr" and self._depth:
self._cells = []
self._code = []
elif tag in ("td", "th") and self._cells is not None:
self._cells.append([])
elif tag == "pre" and self._cells:
self._in_pre = True
def handle_endtag(self, tag: str) -> None:
if tag == "table" and self._depth:
self._depth -= 1
self._in_table = False
elif tag == "pre":
self._in_pre = False
elif tag == "tr" and self._cells is not None:
cells = [" ".join("".join(cell).split()) for cell in self._cells]
if cells and cells[0] == TABLE_HEADER:
self._in_table = True
elif self._in_table and len(cells) == 2:
self.rows.append((cells[0], cells[1], "".join(self._code or [])))
self._cells = None
self._code = None
def handle_data(self, data: str) -> None:
if self._in_pre and self._code is not None:
self._code.append(data)
elif self._cells:
self._cells[-1].append(data)
elif not self._depth:
self.prose.append(data)
def read_page(page: str) -> dict:
"""The statements and examples of the page's table, as the vendored file holds them, its date aside."""
parser = StatementTable()
parser.feed(page)
if not parser.rows:
raise ValueError(f"the page has no table headed {TABLE_HEADER!r}: see {PROMPT}")
prose = " ".join("".join(parser.prose).split())
examples = EXAMPLES_RE.search(prose)
if examples is None:
raise ValueError(f"the page no longer says which database and table its examples name: see {PROMPT}")
statements: dict[str, dict] = {}
for name, text, code in parser.rows:
try:
policy = json.loads("[" + code + "]")
except ValueError as e:
raise ValueError(f"the policy the page gives {name} is not JSON ({e}): see {PROMPT}") from e
if not policy or not all(isinstance(statement, dict) and statement.get("Effect") == "Allow"
and isinstance(statement.get("Action"), list)
and isinstance(statement.get("Resource"), list) for statement in policy):
raise ValueError(f"the policy the page gives {name} is not statements allowing a list of actions on a "
f"list of resources: see {PROMPT}")
if name in statements:
raise ValueError(f"the page gives {name} twice: see {PROMPT}")
statements[name] = {"text": text, "policy": policy}
return {
"examples": {examples.group("database"): "database", examples.group("table"): "table"},
"statements": statements,
}
def build(page: str) -> dict:
return {
"_source": {
"page": PAGE,
"fetcher": "tools/aws/fetch_athena_glue_ddl_permissions.py",
"prompt": PROMPT,
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
"note": "The example policies of the page's table 'Examples of database and table-level permissions', "
"copied as they stand; examples maps the example names to what they stand for, as the page's "
"sentence 'replace the example_db database and test table with your own database and table "
"names' says. regen_iam_request_resources.py reads it.",
},
**read_page(page),
}
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 stale(vendored: dict, page: str) -> bool:
"""Whether the page now gives something other than the vendored file, its date aside."""
return {key: value for key, value in vendored.items() if key != "_source"} != read_page(page)
def main(argv: list[str] | None = None, fetch=fetch_url) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--verify", action="store_true", help="online: the vendored file still says what the page does")
parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
args = parser.parse_args(argv)
try:
page = fetch(PAGE)
except OSError as e:
print(f"error: could not read {PAGE} ({e})", file=sys.stderr)
return 2
try:
if args.verify:
vendored = json.loads(args.output.read_text(encoding="utf-8"))
if stale(vendored, page):
print(f"error: {PAGE} no longer gives what {OUTPUT.relative_to(REPO_ROOT)} holds: run "
f"tools/aws/fetch_athena_glue_ddl_permissions.py and then make iam-request-resources-sync",
file=sys.stderr)
return 1
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches {PAGE}")
return 0
document = build(page)
except (OSError, ValueError) as e:
print(f"error: {e}", file=sys.stderr)
return 1
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8")
print(f"wrote {args.output} ({len(document['statements'])} statements from {PAGE})")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+204 -1
View File
@@ -193,6 +193,16 @@ one the reference lists for the operation, which a rule would read instead: a Re
Redshift Serverless restore asks KMS to decrypt with the snapshot's key. `forwardedActions` records what the
reference gives each such action, the type it acts on, that type's ARN format and the `ViaService` key, which
`--verify` checks against AWS.
An operation whose request carries a statement its service runs against another service as the caller (Athena's
`StartQueryExecution`, whose DDL statements Athena runs against the Glue Data Catalog with the caller's identity) is
also checked, when its service runs the statement, as the requests that statement makes (`statements`). Neither
botocore nor the Service Reference says which those are, so they come from a third source, granted for this one
table and no other: the page of AWS's documentation that gives each statement's permissions, which its own script
vendors as it stands (`STATEMENT_SOURCES`). Each action of a statement's example policy acts on each resource of the
same policy statement whose type the Service Reference gives the action, the type whose format the example ARN
matches, its variables filled from what the page says the example's names stand for (`database`, `table`) and
open where the example has a wildcard. `statementActions` records the types the reference gives each such action,
which `--verify` checks against AWS, as it checks the vendored page against the live one.
A qualified type the reference gives an action, one whose format is another type's and one more `:${...}` (Lambda's
`function alias` and `function version`), which no member fills alone, is named by that type's member and the
request's one member documented as naming the qualified types ("The version number or alias name"): Lambda's
@@ -255,6 +265,7 @@ import sys
from datetime import datetime, timezone
from pathlib import Path
import fetch_athena_glue_ddl_permissions
from regen_iam_authorized_actions import authorized_actions_from, fetch_references
from regen_iam_passed_roles import (
NAMESPACE_RE,
@@ -371,6 +382,21 @@ MEASURED: dict[str, tuple[list[dict], str]] = {
for operation in ("redshift:RestoreFromClusterSnapshot", "redshift-serverless:RestoreFromSnapshot")},
}
# ---------------------------------------------------------------------------------------------------------------------
# STATEMENT_SOURCES: the statements an operation's request carries that its service runs against another service as
# the caller, and the vendored page each one's permissions come from.
#
# This is the file's one source besides botocore and the Service Reference, granted for Athena's DDL statements alone:
# it is not a place for any other table. Its file is written by its own script from AWS's documentation, unchanged
# (tools/aws/fetch_athena_glue_ddl_permissions.py, with a prompt beside the file for rebuilding it when the page's
# layout changes), and the generator only reads it (`statement_requests`): nothing about a statement is stated here.
# ---------------------------------------------------------------------------------------------------------------------
STATEMENT_SOURCES: dict[str, Path] = {
"athena:StartQueryExecution": REPO_ROOT / "tools/aws/sources/athena-glue-ddl-permissions.json",
}
# What a row's sentence says when its policy names partition actions a table without partitions does not need.
UNPARTITIONED_RE = re.compile(r"does not have partitions, do not include partition actions", re.I)
_LATER ="not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint"
_REST = ("REST: its requests name their resources in the path, which RequestResources reads from the route a request "
"matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet")
@@ -2336,6 +2362,97 @@ def forwarded_for(operation: str, types: list[str], models: dict[str, dict], act
return found
def load_statement_sources() -> dict[str, dict]:
"""Each operation's vendored statement source (`STATEMENT_SOURCES`)."""
return {operation: json.loads(path.read_text(encoding="utf-8")) for operation, path in STATEMENT_SOURCES.items()}
def source_actions(sources: dict[str, dict]) -> list[str]:
"""Every action the statement sources' policies name."""
return sorted({action for source in sources.values() for row in source["statements"].values()
for statement in row["policy"] for action in statement["Action"]})
def statement_actions(documents: list[dict], sources: dict[str, dict]) -> dict[str, list[str]]:
"""For each action the statement sources name, the resource types the Service Reference gives it."""
by_name = {document["Name"]: document for document in documents}
found: dict[str, list[str]] = {}
for action in source_actions(sources):
namespace, name = action.split(":", 1)
listed = next((entry for entry in by_name.get(namespace, {}).get("Actions", []) if entry["Name"] == name),
None)
if listed is None:
raise ValueError(f"a statement source names {action}, which the Service Reference does not list")
found[action] = sorted(resource["Name"] for resource in listed.get("Resources") or [])
return found
def example_type(arn: str, formats: dict[str, str], statement: str) -> tuple[str, dict[str, str]]:
"""The one resource type whose ARN format an example ARN matches, and the value it gives each variable of its own."""
matches = []
for kind, arn_format in formats.items():
variables = VARIABLE_RE.findall(arn_format)
pieces = VARIABLE_RE.split(arn_format)[::2]
match = re.fullmatch("([^:/]+)".join(re.escape(piece) for piece in pieces), arn)
if match:
matches.append((kind, {variable: match.group(index + 1) for index, variable in enumerate(variables)
if variable not in KNOWN_VARIABLES}))
if len(matches) != 1:
raise ValueError(f"the policy the page gives {statement} names {arn}, which is "
f"{'no' if not matches else 'more than one'} resource type's ARN format")
return matches[0]
def statement_requests(source: dict, actions: dict[str, list[str]],
formats: dict[str, dict[str, str]]) -> dict[str, list[dict]]:
"""The requests each statement of a vendored source makes: each action of its example policy, on each resource of
the same policy statement of a type the Service Reference gives the action (`actions`), as the type whose format
the example ARN matches, its variables filled from what the page says the example's names stand for and open
where the example has a wildcard. An action whose name says it is a partition action is marked `partitioned` in a
statement whose sentence says a table without partitions does not need those."""
examples = source["examples"]
found: dict[str, list[dict]] = {}
for statement, row in source["statements"].items():
unpartitioned = UNPARTITIONED_RE.search(row["text"]) is not None
requests: dict[str, list[dict]] = {}
for policy_statement in row["policy"]:
for action in policy_statement["Action"]:
namespace = namespace_of(action)
resources = requests.setdefault(action, [])
for arn in policy_statement["Resource"]:
kind, values = example_type(arn, formats.get(namespace, {}), statement)
if kind not in actions[action]:
continue
fill = {}
for variable, value in values.items():
if value == "*":
continue
if value not in examples:
raise ValueError(f"the policy the page gives {statement} names {arn}, whose {value} the "
f"page does not say stands for anything")
fill[variable] = examples[value]
resource = {"type": kind, "fill": dict(sorted(fill.items()))}
if resource not in resources:
resources.append(resource)
entries = []
for action, resources in requests.items():
if not resources:
raise ValueError(f"the policy the page gives {statement} grants {action} on no resource of a type "
f"the Service Reference gives it")
entry = {"action": action, "resources": resources}
if unpartitioned and "Partition" in action.split(":", 1)[1]:
entry["partitioned"] = True
entries.append(entry)
found[statement] = entries
return found
def statements_for(sources: dict[str, dict], actions: dict[str, list[str]],
formats: dict[str, dict[str, str]]) -> dict[str, dict[str, list[dict]]]:
"""Each operation's statements and the requests each makes (`statements`)."""
return {operation: statement_requests(source, actions, formats) for operation, source in sorted(sources.items())}
def read_resources(operation: str, types: list[str], formats: dict[str, str], models: dict[str, dict]) -> list[dict]:
"""The resources the rules read from the request of the clients given."""
name = operation.split(":", 1)[1]
@@ -3080,6 +3197,8 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) ->
suffixes = minted_suffixes(formats, namespaces, data)
check_forwarded(authorized_by(documents))
forwarded = forwarded_actions(documents)
sources = load_statement_sources()
statement_types = statement_actions(documents, sources)
operations = {}
prefixes = {namespace: namespace_id_prefixes(namespace, load_models(data, set(namespaces[namespace])),
load_examples(data, set(namespaces[namespace])))
@@ -3112,6 +3231,8 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) ->
"mintedSuffixes": suffixes,
"integerVariables": integer_variables(operations, namespaces, data),
"forwardedActions": forwarded,
"statementActions": statement_types,
"statements": statements_for(sources, statement_types, formats),
"operations": operations,
}
@@ -3277,7 +3398,8 @@ def render(document: dict) -> str:
"""The document with one operation to a line."""
lines = ["{"]
for key in ("_source", "namespaces", "handBuilt", "notCovered", "otherNamespaces", "arnFormats", "resourceTagKeys",
"resourceKeys", "unqualified", "mintedIds", "mintedSuffixes", "integerVariables", "forwardedActions"):
"resourceKeys", "unqualified", "mintedIds", "mintedSuffixes", "integerVariables", "forwardedActions",
"statementActions", "statements"):
lines.append(f' "{key}": {json.dumps(document[key])},')
lines.append(' "operations": {')
operations = list(document["operations"].items())
@@ -3394,6 +3516,7 @@ def validate(document: dict) -> list[str]:
problems.append("forwardedActions is not each forwarded action's type, its ARN format of one variable and its "
"namespace's ViaService key")
recorded_actions = {}
problems += _statement_problems(document.get("statementActions"), document.get("statements"), operations, formats)
for operation, entry in operations.items():
namespace = namespace_of(operation)
if not OPERATION_RE.match(operation) or namespace not in namespaces:
@@ -3567,6 +3690,47 @@ def _read_as_one(path: object, fill: dict) -> bool:
return bool(FILL_PATH_RE.match(path)) and not path.endswith("[]")
def _statement_problems(actions: object, statements: object, operations: dict,
formats: dict[str, dict[str, str]]) -> list[str]:
"""Whether `statementActions` gives each action resource types and `statements` gives each operation's statements
as requests of those actions on resources of those types, each variable filled from a word or left open."""
actions = {} if actions is None else actions
statements = {} if statements is None else statements
if not isinstance(actions, dict) or not all(
isinstance(action, str) and OPERATION_RE.match(action) and isinstance(types, list) and types == sorted(types)
and all(isinstance(kind, str) for kind in types) for action, types in actions.items()):
return ["statementActions is not each statement action's resource types"]
if not isinstance(statements, dict):
return ["statements is not each operation's statements"]
problems = []
for operation, by_statement in statements.items():
if operation not in operations or not isinstance(by_statement, dict) or not by_statement:
problems.append(f"statements gives {operation!r}, no operation of the file, or no statement of it")
continue
for statement, requests in by_statement.items():
if not isinstance(requests, list) or not requests or not all(
_statement_request_ok(request, actions, formats) for request in requests):
problems.append(f"statements gives {operation} {statement!r} something other than requests of "
f"statementActions on resources of the types they act on")
return problems
def _statement_request_ok(request: object, actions: dict, formats: dict[str, dict[str, str]]) -> bool:
if not isinstance(request, dict) or not {"action", "resources"} <= set(request) <= {"action", "resources",
"partitioned"}:
return False
if request["action"] not in actions or request.get("partitioned", True) is not True:
return False
namespace = namespace_of(request["action"])
return isinstance(request["resources"], list) and bool(request["resources"]) and all(
isinstance(resource, dict) and set(resource) == {"type", "fill"}
and resource["type"] in actions[request["action"]] and resource["type"] in formats.get(namespace, {})
and isinstance(resource["fill"], dict) and all(
variable in set(VARIABLE_RE.findall(formats[namespace][resource["type"]])) - KNOWN_VARIABLES
and isinstance(word, str) and word for variable, word in resource["fill"].items())
for resource in request["resources"])
def _created_problems(operation: str, created: object, types: set[str], formats: dict[str, str]) -> list[str]:
if not isinstance(created, dict) or set(created) != {"type", "parent", "arn"} or not isinstance(created["arn"], str) \
or not PATH_RE.match(created["arn"]):
@@ -3599,6 +3763,19 @@ def derive(document: dict, data: Path) -> list[str]:
if sorted(document["forwardedActions"]) != named:
problems.append(f"the file records {sorted(document['forwardedActions'])} as forwarded actions, MEASURED "
f"names {named}")
sources = load_statement_sources()
if sorted(document["statementActions"]) != source_actions(sources):
problems.append(f"the file records {sorted(document['statementActions'])} as statement actions, the "
f"statement sources name {source_actions(sources)}")
else:
try:
statements = statements_for(sources, document["statementActions"], document["arnFormats"])
except ValueError as e:
problems.append(str(e))
else:
if document["statements"] != statements:
problems.append(f"the file's statements differ from what its sources give: expected "
f"{json.dumps(statements)}")
prefixes = {namespace: namespace_id_prefixes(namespace, load_models(data, set(document["namespaces"][namespace])),
load_examples(data, set(document["namespaces"][namespace])))
for namespace in ID_TARGETS if namespace in document["namespaces"]}
@@ -3633,6 +3810,27 @@ def verify_forwarded(vendored: dict, documents: list[dict]) -> list[str]:
return untrue
def verify_statements(vendored: dict, documents: list[dict]) -> list[str]:
"""What the file records of statement actions and AWS no longer gives, and a vendored page AWS has changed."""
sources = load_statement_sources()
try:
actual = statement_actions(documents, sources)
except ValueError as e:
return [str(e)]
untrue = [f"AWS gives {action} the resource types {actual.get(action)}, not {types}"
for action, types in vendored.get("statementActions", {}).items() if actual.get(action) != types]
for operation, source in sorted(sources.items()):
try:
changed = fetch_athena_glue_ddl_permissions.stale(source, fetch_athena_glue_ddl_permissions.fetch_url(
source["_source"]["page"]))
except (OSError, ValueError) as e:
raise OSError(f"could not read {source['_source']['page']} ({e})") from e
if changed:
untrue.append(f"{source['_source']['page']} no longer gives what {STATEMENT_SOURCES[operation].name} "
f"holds for {operation}: run {source['_source']['fetcher']}")
return untrue
def verify_against(vendored: dict, upstream: dict[str, dict], formats: dict[str, dict[str, str]]) -> tuple[list[str], list[str]]:
"""What the file claims and AWS does not, and the operations AWS has added since."""
untrue: list[str] = []
@@ -3708,6 +3906,11 @@ def main(argv: list[str] | None = None) -> int:
document["namespaces"]):
untrue.append("resourceKeys differ from AWS Service Reference and botocore")
untrue += verify_forwarded(document, documents)
try:
untrue += verify_statements(document, documents)
except OSError as e:
print(f"error: {e}", file=sys.stderr)
return 2
for claim in untrue:
print(f"error: {claim}", file=sys.stderr)
if untrue:
@@ -0,0 +1,175 @@
{
"_source": {
"page": "https://docs.aws.amazon.com/athena/latest/ug/fine-grained-access-to-glue-resources.html",
"fetcher": "tools/aws/fetch_athena_glue_ddl_permissions.py",
"prompt": "tools/aws/sources/athena-glue-ddl-permissions.prompt.md",
"retrieved": "2026-11-16",
"note": "The example policies of the page's table 'Examples of database and table-level permissions', copied as they stand; examples maps the example names to what they stand for, as the page's sentence 'replace the example_db database and test table with your own database and table names' says. regen_iam_request_resources.py reads it."
},
"examples": {
"example_db": "database",
"test": "table"
},
"statements": {
"ALTER DATABASE": {
"text": "Allows you to modify the properties for the example_db database.",
"policy": [
{
"Effect": "Allow",
"Action": [
"glue:GetDatabase",
"glue:UpdateDatabase"
],
"Resource": [
"arn:aws:glue:us-east-1:123456789012:catalog",
"arn:aws:glue:us-east-1:123456789012:database/example_db"
]
}
]
},
"CREATE DATABASE": {
"text": "Allows you to create the database named example_db.",
"policy": [
{
"Effect": "Allow",
"Action": [
"glue:GetDatabase",
"glue:CreateDatabase"
],
"Resource": [
"arn:aws:glue:us-east-1:123456789012:catalog",
"arn:aws:glue:us-east-1:123456789012:database/example_db"
]
}
]
},
"CREATE TABLE": {
"text": "Allows you to create a table named test in the example_db database.",
"policy": [
{
"Sid": "DatabasePermissions",
"Effect": "Allow",
"Action": [
"glue:GetDatabase",
"glue:GetDatabases"
],
"Resource": [
"arn:aws:glue:us-east-1:123456789012:catalog",
"arn:aws:glue:us-east-1:123456789012:database/example_db"
]
},
{
"Sid": "TablePermissions",
"Effect": "Allow",
"Action": [
"glue:GetTables",
"glue:GetTable",
"glue:GetPartitions",
"glue:CreateTable"
],
"Resource": [
"arn:aws:glue:us-east-1:123456789012:catalog",
"arn:aws:glue:us-east-1:123456789012:database/example_db",
"arn:aws:glue:us-east-1:123456789012:table/example_db/test"
]
}
]
},
"DROP DATABASE": {
"text": "Allows you to drop the example_db database, including all tables in it.",
"policy": [
{
"Effect": "Allow",
"Action": [
"glue:GetDatabase",
"glue:DeleteDatabase",
"glue:GetTables",
"glue:GetTable",
"glue:DeleteTable"
],
"Resource": [
"arn:aws:glue:us-east-1:123456789012:catalog",
"arn:aws:glue:us-east-1:123456789012:database/example_db",
"arn:aws:glue:us-east-1:123456789012:table/example_db/*",
"arn:aws:glue:us-east-1:123456789012:userDefinedFunction/example_db/*"
]
}
]
},
"DROP TABLE": {
"text": "Allows you to drop a partitioned table named test in the example_db database. If your table does not have partitions, do not include partition actions.",
"policy": [
{
"Effect": "Allow",
"Action": [
"glue:GetDatabase",
"glue:GetTable",
"glue:DeleteTable",
"glue:GetPartitions",
"glue:GetPartition",
"glue:DeletePartition"
],
"Resource": [
"arn:aws:glue:us-east-1:123456789012:catalog",
"arn:aws:glue:us-east-1:123456789012:database/example_db",
"arn:aws:glue:us-east-1:123456789012:table/example_db/test"
]
}
]
},
"MSCK REPAIR TABLE": {
"text": "Allows you to update catalog metadata after you add Hive compatible partitions to the table named test in the example_db database.",
"policy": [
{
"Effect": "Allow",
"Action": [
"glue:GetDatabase",
"glue:CreateDatabase",
"glue:GetTable",
"glue:GetPartitions",
"glue:GetPartition",
"glue:BatchCreatePartition"
],
"Resource": [
"arn:aws:glue:us-east-1:123456789012:catalog",
"arn:aws:glue:us-east-1:123456789012:database/example_db",
"arn:aws:glue:us-east-1:123456789012:table/example_db/test"
]
}
]
},
"SHOW DATABASES": {
"text": "Allows you to list all databases in the AWS Glue Data Catalog.",
"policy": [
{
"Effect": "Allow",
"Action": [
"glue:GetDatabase",
"glue:GetDatabases"
],
"Resource": [
"arn:aws:glue:us-east-1:123456789012:catalog",
"arn:aws:glue:us-east-1:123456789012:database/*"
]
}
]
},
"SHOW TABLES": {
"text": "Allows you to list all tables in the example_db database.",
"policy": [
{
"Effect": "Allow",
"Action": [
"glue:GetDatabase",
"glue:GetTables"
],
"Resource": [
"arn:aws:glue:us-east-1:123456789012:catalog",
"arn:aws:glue:us-east-1:123456789012:database/example_db",
"arn:aws:glue:us-east-1:123456789012:table/example_db/*"
]
}
]
}
}
}
@@ -0,0 +1,57 @@
# Rebuilding athena-glue-ddl-permissions.json by hand
Use this only when `tools/aws/fetch_athena_glue_ddl_permissions.py` can no longer read the page, because its layout
changed. Fix the script when you can; this is for when you cannot, or to check what the script wrote. Give the
following to whoever (or whatever) rebuilds the file, together with the page.
## The prompt
Read the AWS documentation page
https://docs.aws.amazon.com/athena/latest/ug/fine-grained-access-to-glue-resources.html
("Configure access to databases and tables in the AWS Glue Data Catalog"), and in it the table under "Examples of
database and table-level permissions", whose first column is headed "DDL statement".
Rewrite `tools/aws/sources/athena-glue-ddl-permissions.json` so it holds exactly what that table says, in this shape:
```json
{
"_source": {"page": "<the page's URL>", "fetcher": "tools/aws/fetch_athena_glue_ddl_permissions.py",
"prompt": "tools/aws/sources/athena-glue-ddl-permissions.prompt.md", "retrieved": "<YYYY-MM-DD>",
"note": "<keep the note the file has>"},
"examples": {"<the example database's name>": "database", "<the example table's name>": "table"},
"statements": {
"<the statement as the first column writes it>": {
"text": "<the second column's sentences before the policy, whitespace collapsed to single spaces>",
"policy": [<each statement of the example policy, as JSON objects, in the page's order>]
}
}
}
```
Rules:
1. One entry in `statements` for each row of the table, in the page's order, named as the first column names it
(`CREATE TABLE`, `MSCK REPAIR TABLE`).
2. `policy` is the row's example policy copied as it stands: every statement, with its `Sid` when it has one, its
`Effect`, and its `Action` and `Resource` lists in the page's order. The ARNs keep the page's example Region,
account, database and table (`arn:aws:glue:us-east-1:123456789012:table/example_db/test`) and its wildcards.
3. `examples` comes from the sentence above the table that says which names to replace ("replace the example_db
database and test table with your own database and table names"): each example name, mapped to `database` or
`table` as that sentence says.
4. Add nothing the page does not say. Do not infer an action a statement "probably" needs, do not drop one that looks
unnecessary, do not merge or split statements, and do not add a row for a statement the table has no row for
(`SELECT`, `INSERT INTO`, `ALTER TABLE ADD PARTITION` have none). Keep each row's sentence as written, since the
generator reads conditions from it ("If your table does not have partitions, do not include partition actions").
5. If the page no longer has such a table, or a row's policy is not a list of `Allow` statements with `Action` and
`Resource` lists, stop and report it rather than guessing.
When the file is written, run:
```
python3 tools/aws/fetch_athena_glue_ddl_permissions.py --verify # once the script reads the page again
make iam-request-resources-sync # regenerate the IAM table from it
make iam-request-resources-check iam-request-resources-test
```
`make iam-request-resources-sync` refuses an action the Service Reference does not list for Glue and an ARN that is no
Glue resource type's format, so a mistyped row fails there rather than reaching the IAM table.
@@ -0,0 +1,98 @@
"""Tests for fetch_athena_glue_ddl_permissions.
Run with: pytest tools/aws -q (or: make aws-data-test)
"""
from __future__ import annotations
import json
import pytest
import fetch_athena_glue_ddl_permissions as f
def code_block(*statements: str) -> str:
"""A policy as the page renders it: each statement opened by a span, its example names marked replaceable."""
return ('<pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy">'
'<awsui-icon name="copy"></awsui-icon></div></div><!--DEBUG: cli (json)--><code class="json ">'
+ ",\n".join("<span>{</span>" + statement for statement in statements) + "</code></pre>")
def arn(path: str) -> str:
return ('"arn:aws:glue:<code class="replaceable">us-east-1</code>:<code class="replaceable">123456789012</code>:'
+ path + '"')
CREATE_DATABASE = ('\n "Effect": "Allow",\n "Action": [\n "glue:GetDatabase",\n "glue:CreateDatabase"\n ],\n'
' "Resource": [\n ' + arn("catalog") + ',\n '
+ arn('database/<code class="replaceable">example_db</code>') + '\n ]\n}')
CREATE_TABLE = ('\n "Sid": "TablePermissions",\n "Effect": "Allow",\n "Action": [\n "glue:CreateTable"\n ],\n'
' "Resource": [\n ' + arn("catalog") + ',\n '
+ arn('table/<code class="replaceable">example_db</code>/<code class="replaceable">test</code>')
+ '\n ]\n}')
def page(rows: str, sentence: str = 'In the examples, replace the <code class="code">example_db</code> database and '
'<code class="code">test</code>\n table with your own database and table names.'):
return (f'<html><body><table><tr><th>To perform this task</th><th>See</th></tr></table><p>{sentence}</p>'
'<div class="table-container"><table id="d0e2"><thead><tr><th>DDL statement</th>'
'<th>Example of an IAM access policy granting access to the resource</th></tr></thead>'
f'<tr>{rows}</tr></table></div></body></html>')
def row(name: str, text: str, *statements: str) -> str:
return f'<td tabindex="-1">{name}</td><td tabindex="-1">{text}{code_block(*statements)}</td></tr><tr>'
ROWS = (row("CREATE DATABASE", 'Allows you to create the database named <code class="code">example_db</code>.',
CREATE_DATABASE)
+ row("CREATE TABLE", 'Allows you to create a table named <code class="code">test</code> in the\n'
'<code class="code">example_db</code>\n database.', CREATE_DATABASE, CREATE_TABLE))
DATABASE = {"Effect": "Allow", "Action": ["glue:GetDatabase", "glue:CreateDatabase"],
"Resource": ["arn:aws:glue:us-east-1:123456789012:catalog",
"arn:aws:glue:us-east-1:123456789012:database/example_db"]}
def test_each_statement_keeps_its_sentence_and_its_example_policy_as_the_page_gives_them():
assert f.read_page(page(ROWS)) == {
"examples": {"example_db": "database", "test": "table"},
"statements": {
"CREATE DATABASE": {"text": "Allows you to create the database named example_db.", "policy": [DATABASE]},
"CREATE TABLE": {"text": "Allows you to create a table named test in the example_db database.",
"policy": [DATABASE, {"Sid": "TablePermissions", "Effect": "Allow",
"Action": ["glue:CreateTable"],
"Resource": ["arn:aws:glue:us-east-1:123456789012:catalog",
"arn:aws:glue:us-east-1:123456789012:table/"
"example_db/test"]}]},
},
}
@pytest.mark.parametrize("served, problem", [
# The table is gone or renamed.
(page(ROWS).replace("DDL statement", "Statement"), "no table headed 'DDL statement'"),
# The sentence naming the example database and table is gone.
(page(ROWS, "Replace the names."), "no longer says which database and table"),
# A policy that is no longer JSON, or no longer allows lists of actions on lists of resources.
(page(ROWS.replace('"Effect": "Allow",', '"Effect": "Allow"', 1)), "is not JSON"),
(page(ROWS.replace('"Effect": "Allow"', '"Effect": "Deny"', 1)), "is not statements allowing"),
])
def test_a_page_whose_layout_changed_is_refused_and_points_at_the_prompt(served, problem):
with pytest.raises(ValueError, match=problem) as error:
f.read_page(served)
assert f.PROMPT in str(error.value)
def test_verify_compares_the_vendored_file_with_the_page_its_date_aside(tmp_path, capsys):
output = tmp_path / "source.json"
served = {f.PAGE: page(ROWS)}
assert f.main(["--output", str(output)], fetch=served.get) == 0
vendored = json.loads(output.read_text(encoding="utf-8"))
assert vendored["_source"]["page"] == f.PAGE and len(vendored["statements"]) == 2
vendored["_source"]["retrieved"] = "2020-01-01"
output.write_text(json.dumps(vendored), encoding="utf-8")
assert f.main(["--verify", "--output", str(output)], fetch=served.get) == 0
served[f.PAGE] = page(ROWS.replace("glue:CreateTable", "glue:CreateTables"))
assert f.main(["--verify", "--output", str(output)], fetch=served.get) == 1
assert "no longer gives what" in capsys.readouterr().err
@@ -372,6 +372,7 @@ def isolated(monkeypatch):
monkeypatch.setattr(r, "NOT_COVERED", {"later": "a later batch"})
monkeypatch.setattr(r, "READ_IN_HAND_BUILT", {})
monkeypatch.setattr(r, "MEASURED", {})
monkeypatch.setattr(r, "STATEMENT_SOURCES", {})
return monkeypatch
@@ -2535,3 +2536,117 @@ def test_a_task_identifier_reaches_the_source_arn_its_record_documents():
"<p>The Amazon Resource Name (ARN) of the thing that was exported to storage.</p>"}}}
assert r.read_resources("svc:DescribeExports", ["thing"], FORMATS, {"svc": modeled}) == [
{"types": ["thing"], "through": "ExportTaskIdentifier"}]
GLUE_FORMATS = {
"catalog": "arn:${Partition}:glue:${Region}:${Account}:catalog/${CatalogName}",
"rootcatalog": "arn:${Partition}:glue:${Region}:${Account}:catalog",
"database": "arn:${Partition}:glue:${Region}:${Account}:database/${DatabaseName}",
"table": "arn:${Partition}:glue:${Region}:${Account}:table/${DatabaseName}/${TableName}",
}
EXAMPLE = "arn:aws:glue:us-east-1:123456789012:"
def statement_source(**statements) -> dict:
"""A vendored statement source as the fetch script writes it: the page's example names and each statement's
sentence and example policy."""
return {"_source": {"page": "https://example.com/page", "fetcher": "fetch.py"},
"examples": {"example_db": "database", "test": "table"},
"statements": {name.replace("_", " "): {"text": text, "policy": policy}
for name, (text, policy) in statements.items()}}
def allow(actions: list[str], resources: list[str]) -> dict:
return {"Effect": "Allow", "Action": actions, "Resource": [EXAMPLE + resource for resource in resources]}
GLUE_ACTIONS = {"glue:GetDatabase": ["catalog", "database", "rootcatalog"],
"glue:GetTable": ["catalog", "database", "rootcatalog", "table"],
"glue:DeleteTable": ["catalog", "database", "rootcatalog", "table"],
"glue:GetPartitions": ["catalog", "database", "rootcatalog", "table"]}
def test_a_statement_makes_each_action_of_its_policy_on_each_resource_of_its_statement_the_reference_has_it_act_on():
source = statement_source(
DROP_TABLE=("Allows you to drop a partitioned table named test in the example_db database. If your table does "
"not have partitions, do not include partition actions.",
[allow(["glue:GetDatabase"], ["catalog", "database/example_db"]),
allow(["glue:GetTable", "glue:DeleteTable", "glue:GetPartitions"],
["catalog", "database/example_db", "table/example_db/test"])]),
SHOW_TABLES=("Allows you to list all tables in the example_db database.",
[allow(["glue:GetDatabase", "glue:GetTable"],
["catalog", "database/example_db", "table/example_db/*"])]))
root = {"type": "rootcatalog", "fill": {}}
database = {"type": "database", "fill": {"DatabaseName": "database"}}
table = {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}
assert r.statement_requests(source, GLUE_ACTIONS, {"glue": GLUE_FORMATS}) == {
# Each action on the resources of its own policy statement, the catalog by the bare format it matches.
"DROP TABLE": [{"action": "glue:GetDatabase", "resources": [root, database]},
{"action": "glue:GetTable", "resources": [root, database, table]},
{"action": "glue:DeleteTable", "resources": [root, database, table]},
# The sentence says a table without partitions needs no partition action.
{"action": "glue:GetPartitions", "resources": [root, database, table], "partitioned": True}],
# A wildcard leaves its variable open, and an action is not checked on a type it does not act on.
"SHOW TABLES": [{"action": "glue:GetDatabase", "resources": [root, database]},
{"action": "glue:GetTable", "resources": [
root, database, {"type": "table", "fill": {"DatabaseName": "database"}}]}],
}
@pytest.mark.parametrize("policy, problem", [
# An ARN of no type's format, or of a name the page does not say stands for anything.
([allow(["glue:GetTable"], ["function/f"])], "is no resource type's ARN format"),
([allow(["glue:GetTable"], ["database/default"])], "whose default the page does not say stands for anything"),
# An action granted on no resource of a type the reference gives it.
([allow(["glue:GetDatabase"], ["table/example_db/test"])], "grants glue:GetDatabase on no resource"),
])
def test_a_statement_policy_the_reference_cannot_read_is_refused(policy, problem):
with pytest.raises(ValueError, match=problem):
r.statement_requests(statement_source(DROP_TABLE=("Drops it.", policy)), GLUE_ACTIONS,
{"glue": GLUE_FORMATS})
def test_the_statement_actions_are_the_types_the_reference_gives_each_and_an_unlisted_one_is_refused():
glue = reference("glue", {"GetDatabase": ["catalog", "database", "rootcatalog"]}, GLUE_FORMATS)
source = statement_source(CREATE_DATABASE=("Creates it.", [allow(["glue:GetDatabase"], ["catalog"])]))
assert r.statement_actions([glue], {"svc:A": source}) == {"glue:GetDatabase": ["catalog", "database", "rootcatalog"]}
unlisted = statement_source(CREATE_DATABASE=("Creates it.", [allow(["glue:CreateDatabase"], ["catalog"])]))
with pytest.raises(ValueError, match="names glue:CreateDatabase, which the Service Reference does not list"):
r.statement_actions([glue], {"svc:A": unlisted})
def test_the_statements_are_built_checked_offline_and_verified_against_aws_and_the_page(isolated, tmp_path, monkeypatch):
isolated.setattr(r, "NAMESPACES", ("svc", "glue"))
source = statement_source(CREATE_DATABASE=("Creates the example_db database.",
[allow(["glue:GetDatabase"], ["catalog", "database/example_db"])]))
path = tmp_path / "source.json"
path.write_text(json.dumps(source), encoding="utf-8")
isolated.setattr(r, "STATEMENT_SOURCES", {"svc:GetThing": path})
glue = reference("glue", {"GetDatabase": ["catalog", "database", "rootcatalog"]}, GLUE_FORMATS)
glue["Operations"] = []
documents = [*forwarding_documents(tmp_path), glue]
document = r.build(documents, "test", tmp_path, "botocore test")
assert document["statementActions"] == {"glue:GetDatabase": ["catalog", "database", "rootcatalog"]}
assert document["statements"] == {"svc:GetThing": {"CREATE DATABASE": [{"action": "glue:GetDatabase", "resources": [
{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}]}}
assert r.validate(document) == [] and r.derive(document, tmp_path) == []
assert json.loads(r.render(document)) == document
# A statement edited by hand, or a source changed without a sync, fails the offline check.
edited = json.loads(json.dumps(document))
edited["statements"]["svc:GetThing"]["CREATE DATABASE"][0]["resources"].pop()
assert any("statements differ from what its sources give" in problem for problem in r.derive(edited, tmp_path))
edited["statements"]["svc:GetThing"]["CREATE DATABASE"][0]["action"] = "glue:GetTable"
assert any("something other than requests of statementActions" in problem for problem in r.validate(edited))
# Online, the types AWS gives each action and the page itself are checked.
page = {"https://example.com/page": "the page"}
monkeypatch.setattr(r.fetch_athena_glue_ddl_permissions, "fetch_url", lambda url: page[url])
monkeypatch.setattr(r.fetch_athena_glue_ddl_permissions, "stale", lambda vendored, text: text != "the page")
assert r.verify_statements(document, documents) == []
narrower = reference("glue", {"GetDatabase": ["database"]}, GLUE_FORMATS)
assert r.verify_statements(document, [*documents[:-1], narrower]) == [
"AWS gives glue:GetDatabase the resource types ['database'], not ['catalog', 'database', 'rootcatalog']"]
page["https://example.com/page"] = "a changed page"
assert r.verify_statements(document, documents) == [
"https://example.com/page no longer gives what source.json holds for svc:GetThing: run fetch.py"]