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

@@ -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