diff --git a/docs/services/athena.md b/docs/services/athena.md index 983676e070..d4790bffa3 100644 --- a/docs/services/athena.md +++ b/docs/services/athena.md @@ -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:::workgroup/`, `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. diff --git a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java index 81addecf47..f3ad383193 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -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 diff --git a/src/main/java/io/floci/aws/services/athena/AthenaNamedQueryService.java b/src/main/java/io/floci/aws/services/athena/AthenaNamedQueryService.java index 1d4d60a013..f0088c6473 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaNamedQueryService.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaNamedQueryService.java @@ -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 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.")); diff --git a/src/main/java/io/floci/aws/services/athena/AthenaService.java b/src/main/java/io/floci/aws/services/athena/AthenaService.java index d3d9120df3..93459e4c46 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaService.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaService.java @@ -112,6 +112,9 @@ public class AthenaService { private final StorageBackend workGroupStore; private final StorageBackend dataCatalogStore; private final StorageBackend> 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 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 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 findQueryExecutionRegion(String id) { + return id == null ? Optional.empty() : queryRegionStore.get(id); + } + public QueryExecution getQueryExecution(String id) { return queryStore.get(id) .orElseThrow(() -> new AwsException("InvalidRequestException", diff --git a/src/main/java/io/floci/aws/services/athena/AthenaStoredResourceArns.java b/src/main/java/io/floci/aws/services/athena/AthenaStoredResourceArns.java index 685106d5e6..d61f4c31d4 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaStoredResourceArns.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaStoredResourceArns.java @@ -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 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 storedTags(String arn) { return athena.storedTags(arn); diff --git a/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java b/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java index ac8649cfbc..f122b2024f 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java @@ -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(); diff --git a/src/test/java/io/floci/aws/services/athena/AthenaStoredResourceArnsTest.java b/src/test/java/io/floci/aws/services/athena/AthenaStoredResourceArnsTest.java new file mode 100644 index 0000000000..cf30f521a5 --- /dev/null +++ b/src/test/java/io/floci/aws/services/athena/AthenaStoredResourceArnsTest.java @@ -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)); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java index 803c2c000c..0a57419e5d 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java @@ -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(); }