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

@@ -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);
}