feat(iam): check Athena query executions and named queries on their workgroup (#9442)

The generated request-resources table reads the workgroup of an Athena
query execution or named query through its id (`through`), which no
service answered, so GetQueryExecution, GetQueryResults,
GetQueryRuntimeStatistics, StopQueryExecution, GetNamedQuery,
UpdateNamedQuery and DeleteNamedQuery were checked on `*`.
AthenaStoredResourceArns now answers it with the workgroup the stored query
execution or named query runs in, `primary` for one naming none, looked up
read-only; an id Athena holds none of names nothing.

Athena kept query executions by their id alone, so a request sent to one
Region could name another Region's execution. Each execution's Region is
now recorded beside it (query-regions.json), and an execution is checked
on its workgroup in the Region it was started in, whichever Region the
request is sent to: a grant on another Region's workgroup of the same
name does not reach it, and a deny on its own workgroup is not passed by
through another Region.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-25 09:49:34 -04:00
1 parent bf13478d03
commit 93cab8398d
8 files changed
+224 -6

No files matched your search

+11
View File
@@ -182,6 +182,17 @@ 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.
### Query executions and named queries under IAM enforcement
With IAM enforcement on, a request naming a query execution by its `QueryExecutionId` (`GetQueryExecution`,
`GetQueryResults`, `GetQueryRuntimeStatistics`, `StopQueryExecution`) or a named query by its `NamedQueryId`
(`GetNamedQuery`, `UpdateNamedQuery`, `DeleteNamedQuery`) is checked on the workgroup it runs in,
`arn:aws:athena:<region>:<account>:workgroup/<name>`, `primary` for one naming none, as the Service Authorization
Reference gives these actions the workgroup. A query execution is checked on its workgroup in the Region it was
started in, whichever Region the request is sent to, so a grant on another Region's workgroup of the same name does
not reach it and a deny on its own workgroup holds. An id Athena holds none of names no workgroup, and the request is
checked as one naming none.
### 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.
@@ -42,9 +42,10 @@ import java.util.Optional;
* execution of a callback, and the tags of a function, an event source mapping, a web function, a MicroVM image or a
* network connector; Glue, for the tags of a resource it tags; Step Functions, for the tags of a state machine, its
* versions and executions, and an activity; CodeBuild, for the project a build belongs to and the tags of a project or
* a report group; Athena, for the workgroup and the data catalog a request naming none uses and the tags of a
* workgroup or a data catalog; Redshift Serverless, for the tags of a namespace, a workgroup or a snapshot; DynamoDB,
* for the tags of a table and its indexes; ECR, for the tags of a repository; Redshift, for the key a snapshot records
* a report group; Athena, for the workgroup and the data catalog a request naming none uses, the workgroup a query
* execution or a named query runs in, and the tags of a workgroup or a data catalog; Redshift Serverless, for the
* tags of a namespace, a workgroup or a snapshot; DynamoDB, for the tags of a table and its indexes; ECR, for the
* tags of a repository; Redshift, for the key a snapshot records
* and the tags of a cluster, a snapshot, a parameter group, a subnet group, a snapshot copy grant, a snapshot
* schedule, an event subscription or an integration; SSM, for the parameter a legacy ARN names, the document of
* another account an association runs and the tags of a parameter, a document or an association; CloudFront, for the
@@ -15,6 +15,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
@ApplicationScoped
@@ -56,6 +57,11 @@ public class AthenaNamedQueryService {
return id;
}
/** The Region's stored named query of the id; empty for one Athena holds none of. */
public Optional<NamedQuery> findNamedQuery(String region, String id) {
return id == null ? Optional.empty() : queries.get(key(region, id));
}
public NamedQuery getNamedQuery(String region, String id) {
return queries.get(key(region, id))
.orElseThrow(() -> invalid("Named query " + id + " does not exist."));
@@ -112,6 +112,9 @@ public class AthenaService {
private final StorageBackend<String, WorkGroup> workGroupStore;
private final StorageBackend<String, DataCatalog> dataCatalogStore;
private final StorageBackend<String, List<String>> resultColumnTypeStore;
// The Region each query execution was started in, by its id: the execution's own record is the API's shape, which
// carries none, and IAM checks a request naming the execution on its workgroup in that Region alone.
private final StorageBackend<String, String> queryRegionStore;
private final FlociDuckClient duckClient;
private final GlueService glueService;
private final S3Service s3Service;
@@ -142,6 +145,8 @@ public class AthenaService {
new TypeReference<>() {});
this.resultColumnTypeStore = storageFactory.create("athena", "query-result-column-types.json",
new TypeReference<>() {});
this.queryRegionStore = storageFactory.create("athena", "query-regions.json",
new TypeReference<>() {});
this.duckClient = duckClient;
this.glueService = glueService;
this.s3Service = s3Service;
@@ -222,6 +227,11 @@ public class AthenaService {
execution.setStatementType("DDL");
}
execution.getStatus().setState(QueryExecutionState.RUNNING);
// Recorded before the execution, so no lookup finds the execution without its Region.
String startedIn = regionResolver.getRegion();
if (startedIn != null) {
queryRegionStore.put(id, startedIn);
}
queryStore.put(id, execution);
if (hiveDdlStatement) {
@@ -361,6 +371,16 @@ public class AthenaService {
}
}
/** The stored query execution of the id; empty for one Athena holds none of. */
public Optional<QueryExecution> findQueryExecution(String id) {
return id == null ? Optional.empty() : queryStore.get(id);
}
/** The Region the query execution of the id was started in; empty for one whose Region Athena did not record. */
public Optional<String> findQueryExecutionRegion(String id) {
return id == null ? Optional.empty() : queryRegionStore.get(id);
}
public QueryExecution getQueryExecution(String id) {
return queryStore.get(id)
.orElseThrow(() -> new AwsException("InvalidRequestException",
@@ -11,18 +11,22 @@ import java.util.Optional;
/**
* What IAM asks Athena of the resources a request names: the workgroup and the data catalog its handlers use for a
* request naming none, {@code primary} and {@code AwsDataCatalog}, and the tags of a workgroup or a data catalog.
* request naming none, {@code primary} and {@code AwsDataCatalog}, the workgroup a query execution or a named query of
* an id belongs to, and the tags of a workgroup or a data catalog.
*/
@ApplicationScoped
public class AthenaStoredResourceArns implements StoredResourceArns {
private final RegionResolver regionResolver;
private final AthenaService athena;
private final AthenaNamedQueryService namedQueries;
@Inject
public AthenaStoredResourceArns(RegionResolver regionResolver, AthenaService athena) {
public AthenaStoredResourceArns(RegionResolver regionResolver, AthenaService athena,
AthenaNamedQueryService namedQueries) {
this.regionResolver = regionResolver;
this.athena = athena;
this.namedQueries = namedQueries;
}
@Override
@@ -45,6 +49,33 @@ public class AthenaStoredResourceArns implements StoredResourceArns {
};
}
/**
* The workgroup the caller's query execution ({@code QueryExecutionId}) or named query ({@code NamedQueryId}) of the
* id runs in, {@code primary} for one naming none, as Athena checks a request naming it: an execution's in the
* Region it was started in, whichever Region the request is sent to, so neither a grant on another Region's
* workgroup of the same name nor a request sent to another Region passes a check its own workgroup refuses; a named
* query's in the Region of the request, which holds it. None for an id Athena holds none of, or an execution whose
* Region it did not record, so a request naming one is checked as naming no workgroup.
*/
@Override
public List<String> through(String member, String value, String region) {
return switch (member) {
case "QueryExecutionId" -> athena.findQueryExecution(value)
.flatMap(execution -> athena.findQueryExecutionRegion(value)
.map(startedIn -> workGroupArn(startedIn, execution.getWorkGroup())))
.stream().toList();
case "NamedQueryId" -> namedQueries.findNamedQuery(region, value)
.map(query -> workGroupArn(region, query.workGroup()))
.stream().toList();
default -> List.of();
};
}
private String workGroupArn(String region, String group) {
return regionResolver.buildArn("athena", region,
"workgroup/" + (group == null || group.isBlank() ? "primary" : group));
}
@Override
public Map<String, String> storedTags(String arn) {
return athena.storedTags(arn);
@@ -57,6 +57,7 @@ class AthenaServiceTest {
private AthenaIcebergStatements icebergStatements;
private S3Service s3Service;
private AthenaService service;
private RegionResolver regionResolver;
@BeforeEach
void setUp() {
@@ -80,8 +81,9 @@ class AthenaServiceTest {
when(services.athena()).thenReturn(athena);
when(athena.mock()).thenReturn(false);
regionResolver = mock(RegionResolver.class);
service = new AthenaService(storageFactory, duckClient, glueService, s3Service,
config, vertx, ddlBuilder, mock(RegionResolver.class), icebergStatements,
config, vertx, ddlBuilder, regionResolver, icebergStatements,
mock(IamEnforcementFilter.class));
}
@@ -90,6 +92,25 @@ class AthenaServiceTest {
vertx.close();
}
@Test
void aQueryExecutionRecordsTheRegionItWasStartedIn() {
when(regionResolver.getRegion()).thenReturn("eu-west-1");
String id = service.startQueryExecution("SELECT 1", "primary", null, null);
assertTrue(service.findQueryExecution(id).isPresent());
assertEquals("eu-west-1", service.findQueryExecutionRegion(id).orElseThrow());
assertTrue(service.findQueryExecutionRegion("missing").isEmpty());
}
@Test
void aQueryExecutionStartedWithNoRegionRecordsNone() {
when(regionResolver.getRegion()).thenReturn(null);
String id = service.startQueryExecution("SELECT 1", "primary", null, null);
assertTrue(service.findQueryExecution(id).isPresent());
assertTrue(service.findQueryExecutionRegion(id).isEmpty());
}
@Test
void storedTagsReadTheWorkgroupOrTheDataCatalogTheArnNamesInItsAccountAndRegion() {
CreateWorkGroupRequest request = new CreateWorkGroupRequest();
@@ -0,0 +1,77 @@
package io.floci.aws.services.athena;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.athena.model.NamedQuery;
import io.floci.aws.services.athena.model.QueryExecution;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* What Athena gives the request-resources table through a query execution or a named query: the workgroup it runs in,
* which Athena checks a request naming it on.
*/
class AthenaStoredResourceArnsTest {
private static final String REGION = "eu-west-1";
private static final String WORKGROUPS = "arn:aws:athena:" + REGION + ":000000000000:workgroup/";
private final AthenaService athena = mock(AthenaService.class);
private final AthenaNamedQueryService namedQueries = mock(AthenaNamedQueryService.class);
private final AthenaStoredResourceArns stored = new AthenaStoredResourceArns(
new RegionResolver("us-east-1", "000000000000"), athena, namedQueries);
@Test
void aQueryExecutionOrANamedQueryReachesTheWorkgroupItRunsIn() {
QueryExecution execution = new QueryExecution();
execution.setWorkGroup("etl");
when(athena.findQueryExecution("q-1")).thenReturn(Optional.of(execution));
when(athena.findQueryExecutionRegion("q-1")).thenReturn(Optional.of(REGION));
when(namedQueries.findNamedQuery(REGION, "n-1"))
.thenReturn(Optional.of(new NamedQuery("n-1", "daily", "db", "select 1", null, "reports")));
assertEquals(List.of(WORKGROUPS + "etl"), stored.through("QueryExecutionId", "q-1", REGION));
assertEquals(List.of(WORKGROUPS + "reports"), stored.through("NamedQueryId", "n-1", REGION));
}
@Test
void aQueryExecutionIsCheckedOnItsWorkgroupInTheRegionItWasStartedIn() {
// A request sent to another Region is checked on the execution's own workgroup, so neither a grant on that
// Region's workgroup of the same name passes nor a deny on the execution's own is passed by.
QueryExecution execution = new QueryExecution();
execution.setWorkGroup("etl");
when(athena.findQueryExecution("q-3")).thenReturn(Optional.of(execution));
when(athena.findQueryExecutionRegion("q-3")).thenReturn(Optional.of("us-east-1"));
assertEquals(List.of("arn:aws:athena:us-east-1:000000000000:workgroup/etl"),
stored.through("QueryExecutionId", "q-3", REGION));
}
@Test
void aQueryExecutionNamingNoWorkgroupRunsInPrimary() {
when(athena.findQueryExecution("q-2")).thenReturn(Optional.of(new QueryExecution()));
when(athena.findQueryExecutionRegion("q-2")).thenReturn(Optional.of(REGION));
assertEquals(List.of(WORKGROUPS + "primary"), stored.through("QueryExecutionId", "q-2", REGION));
}
@Test
void anIdAthenaHoldsNoneOfReachesNothing() {
when(athena.findQueryExecution("missing")).thenReturn(Optional.empty());
when(namedQueries.findNamedQuery(REGION, "missing")).thenReturn(Optional.empty());
assertEquals(List.of(), stored.through("QueryExecutionId", "missing", REGION));
assertEquals(List.of(), stored.through("NamedQueryId", "missing", REGION));
assertEquals(List.of(), stored.through("NotebookId", "nb-1", REGION));
}
@Test
void aQueryExecutionWhoseRegionWasNotRecordedReachesNothing() {
when(athena.findQueryExecution("q-old")).thenReturn(Optional.of(new QueryExecution()));
when(athena.findQueryExecutionRegion("q-old")).thenReturn(Optional.empty());
assertEquals(List.of(), stored.through("QueryExecutionId", "q-old", REGION));
}
}
@@ -3764,6 +3764,57 @@ class IamRequestResourceEnforcementIntegrationTest {
"{\"ServerId\":\"s-0123456789abcdef1\"}"), "transfer:DescribeServer");
}
/**
* An Athena query execution is checked on its workgroup in the Region it was started in, whichever Region the
* request is sent to: a grant on another Region's workgroup of the same name does not reach it, a deny on its own
* workgroup is not passed by through another Region, and a grant on its own workgroup lets the caller read it.
*/
@Test
void anAthenaQueryExecutionIsCheckedOnItsWorkgroupInTheRegionItRunsIn() {
String id = adminJson("athena", "AmazonAthena.StartQueryExecution")
.body("{\"QueryString\":\"DROP TABLE IF EXISTS no_such_table\",\"WorkGroup\":\"primary\"}")
.post("/").then().statusCode(200).extract().path("QueryExecutionId");
String other = "eu-west-1";
String primary = ":" + ACCOUNT + ":workgroup/primary";
String body = "{\"QueryExecutionId\":\"" + id + "\"}";
User user = user("res-athena-execution");
user.policy(allowOn("athena:GetQueryExecution", "arn:aws:athena:" + other + primary));
refusedJson(getQueryExecutionIn(user, other, body), "athena:GetQueryExecution");
user.policy(allowOn("athena:GetQueryExecution", "*") + ",{\"Effect\":\"Deny\",\"Action\":"
+ "\"athena:GetQueryExecution\",\"Resource\":\"arn:aws:athena:" + REGION + primary + "\"}");
refusedJson(getQueryExecutionIn(user, other, body), "athena:GetQueryExecution");
user.policy(allowOn("athena:GetQueryExecution", "arn:aws:athena:" + REGION + primary));
send(user, "athena", "AmazonAthena.GetQueryExecution", "1.1", body).statusCode(200);
}
private static ValidatableResponse getQueryExecutionIn(User user, String region, String body) {
return given().header("Authorization", auth(user.accessKeyId(), region, "athena"))
.header("X-Amz-Target", "AmazonAthena.GetQueryExecution").contentType("application/x-amz-json-1.1")
.body(body).post("/").then();
}
/**
* An Athena named query is checked on the workgroup it runs in, which its request names only by the query's id, so a
* grant on that workgroup lets the caller read it and a grant on another does not.
*/
@Test
void anAthenaNamedQueryIsCheckedOnTheWorkgroupItRunsIn() {
String id = adminJson("athena", "AmazonAthena.CreateNamedQuery")
.body("{\"Name\":\"res-" + suffix() + "\",\"Database\":\"db\",\"QueryString\":\"select 1\","
+ "\"WorkGroup\":\"primary\"}")
.post("/").then().statusCode(200).extract().path("NamedQueryId");
cleanup.register(() -> adminJson("athena", "AmazonAthena.DeleteNamedQuery")
.body("{\"NamedQueryId\":\"" + id + "\"}").post("/"));
String workgroups = "arn:aws:athena:" + REGION + ":" + ACCOUNT + ":workgroup/";
User user = user("res-athena");
user.policy(allowOn("athena:GetNamedQuery", workgroups + "primary"));
send(user, "athena", "AmazonAthena.GetNamedQuery", "1.1", "{\"NamedQueryId\":\"" + id + "\"}")
.statusCode(200);
user.policy(allowOn("athena:GetNamedQuery", workgroups + "reports"));
refusedJson(send(user, "athena", "AmazonAthena.GetNamedQuery", "1.1", "{\"NamedQueryId\":\"" + id + "\"}"),
"athena:GetNamedQuery");
}
private static ValidatableResponse glue(String operation, String body) {
return adminJson("glue", "AWSGlue." + operation).body(body).post("/").then();
}