World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#11501] test(iceberg-rest): Add Trino IT for Iceberg REST authorization in auxMode (#11502)
roryqi88d399682d93
diff --git a/.github/workflows/backend-integration-test-action.yml b/.github/workflows/backend-integration-test-action.ymlindex 641b66e6f1..08b82f9331 100644--- a/.github/workflows/backend-integration-test-action.yml+++ b/.github/workflows/backend-integration-test-action.yml@@ -88,6 +88,7 @@ jobs:-x :spark-connector:spark-3.3:test -x :spark-connector:spark-3.4:test -x :spark-connector:spark-3.5:test \-x :spark-connector:spark-runtime-3.3:test -x :spark-connector:spark-runtime-3.4:test -x :spark-connector:spark-runtime-3.5:test \-x :trino-connector:integration-test:test -x :trino-connector:trino-connector:test \+ -x :iceberg:iceberg-rest-trino-it:test \-x :plugins:idp-basic:test \-x :authorizations:authorization-chain:test -x :authorizations:authorization-ranger:test \-x :clients:cli:test -x :maintenance:jobs:test -x :maintenance:optimizer:test \diff --git a/.github/workflows/cron-integration-test.yml b/.github/workflows/cron-integration-test.ymlindex 8bf1bc484d..5fbcb5830c 100644--- a/.github/workflows/cron-integration-test.yml+++ b/.github/workflows/cron-integration-test.yml@@ -81,7 +81,10 @@ jobs:- name: Integration Testid: integrationTestrun: |- ./gradlew test -PskipTests -PtestMode=${{ matrix.test-mode }} -PskipDockerTests=false -PskipWeb=true+ # iceberg-rest-trino-it runs in its own dedicated workflow (Java 24 / Trino, deploy+ # only); exclude it here so it is not run redundantly.+ ./gradlew test -PskipTests -PtestMode=${{ matrix.test-mode }} -PskipDockerTests=false -PskipWeb=true \+ -x :iceberg:iceberg-rest-trino-it:test- name: Upload integrate tests reportsuses: actions/upload-artifact@v7diff --git a/.github/workflows/iceberg-rest-trino-integration-test.yml b/.github/workflows/iceberg-rest-trino-integration-test.ymlnew file mode 100644index 0000000000..fee150d7cc--- /dev/null+++ b/.github/workflows/iceberg-rest-trino-integration-test.yml@@ -0,0 +1,98 @@+name: Iceberg REST Trino Integration Test++# Verifies Gravitino authorization is enforced when an Iceberg REST Catalog served+# in auxiliary mode is accessed through Trino's native iceberg REST connector.+# The module uses a Java 24 toolchain (Trino 478) and runs in deploy mode against+# the built distribution, so it needs its own job rather than the catch-all backend IT.+on:+ push:+ branches: [ "main", "branch-*" ]+ pull_request:+ branches: [ "main", "branch-*" ]++concurrency:+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}+ cancel-in-progress: true++jobs:+ changes:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36+ id: filter+ with:+ filters: |+ source_changes:+ - .github/**+ - api/**+ - catalogs/catalog-common/**+ - clients/client-java/**+ - common/**+ - core/**+ - server-common/**+ - iceberg/**+ - integration-test-common/**+ - gradle/**+ - build.gradle.kts+ - gradle.properties+ - gradlew+ - settings.gradle.kts+ outputs:+ source_changes: ${{ steps.filter.outputs.source_changes }}++ IcebergRestTrinoIT:+ needs: changes+ if: needs.changes.outputs.source_changes == 'true'+ runs-on: ubuntu-latest+ timeout-minutes: 90+ strategy:+ matrix:+ architecture: [linux/amd64]+ java-version: [ 17 ]+ env:+ PLATFORM: ${{ matrix.architecture }}+ steps:+ - uses: actions/checkout@v4++ # Installs the primary JDK plus JDK 24 and registers JDK 24 with the Gradle+ # toolchain, which the trino-iceberg-rest module requires.+ - uses: ./.github/actions/setup-java-toolchains+ with:+ java-version: ${{ matrix.java-version }}++ - name: Set up QEMU+ uses: docker/setup-qemu-action@ce360397dd3f832beb865e1373c09c0e9f86d70a # v4.0.0++ - name: Check required command+ run: |+ dev/ci/check_commands.sh++ - name: Package Gravitino+ run: |+ ./gradlew compileDistribution -PskipWeb=true -x test++ - name: Free up disk space+ run: |+ dev/ci/util_free_space.sh++ - name: Install dependencies+ run: |+ wget https://nz2.archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2_amd64.deb+ sudo dpkg -i libssl1.1_1.1.1f-1ubuntu2_amd64.deb++ - name: Iceberg REST Trino Integration Test+ id: integrationTest+ run: |+ ./gradlew :iceberg:iceberg-rest-trino-it:test -PtestMode=deploy -PskipDockerTests=false -PskipWeb=true++ - name: Upload integrate tests reports+ uses: actions/upload-artifact@v7+ if: ${{ (failure() && steps.integrationTest.outcome == 'failure') || contains(github.event.pull_request.labels.*.name, 'upload log') }}+ with:+ name: iceberg-rest-trino-it-reports-${{ matrix.java-version }}+ path: |+ build/reports+ iceberg/iceberg-rest-trino-it/build/reports+ distribution/package/logs/*.out+ distribution/package/logs/*.logdiff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex bd9a1d15ff..4a896fa95d 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -77,10 +77,15 @@ spark35 = "3.5.3"kyuubi4spark = "1.11.0"kyuubi4authz = "1.10.2"trino = '435'+# Trino version the iceberg-rest-trino-it module's in-process query runner is tested against.+trino-iceberg-it = "478"scala-collection-compat = "2.7.0"scala-java-compat = "1.0.2"sqlite-jdbc = "3.42.0.0"testcontainers = "1.21.4"+# docker-java version aligned with testcontainers 1.21.4; forced in iceberg-rest-trino-it to+# override the newer versions Trino's test stack would otherwise pull in.+docker-java = "3.4.2"jwt = "0.11.1"nimbus-jose-jwt = "10.9"jline = "3.21.0"diff --git a/iceberg/iceberg-rest-trino-it/build.gradle.kts b/iceberg/iceberg-rest-trino-it/build.gradle.ktsnew file mode 100644index 0000000000..670e7bbf2b--- /dev/null+++ b/iceberg/iceberg-rest-trino-it/build.gradle.kts@@ -0,0 +1,110 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+import net.ltgt.gradle.errorprone.errorprone++plugins {+ id("java")+}++// Versions are centrally managed in gradle/libs.versions.toml.+val testcontainersVersion: String = libs.versions.testcontainers.get()+val dockerJavaVersion: String = libs.versions.docker.java.get()++// This test-only module boots an in-process Trino query runner, so it only needs to run against a+// single Trino version. Unlike the trino-connector modules (which must support a range of+// versions), there is no need for the multi-version range machinery here.+val trinoVersion: String = libs.versions.trino.iceberg.it.get()++configurations.configureEach {+ resolutionStrategy.force(+ "org.testcontainers:testcontainers:$testcontainersVersion",+ "com.github.docker-java:docker-java-api:$dockerJavaVersion",+ "com.github.docker-java:docker-java-transport:$dockerJavaVersion",+ "com.github.docker-java:docker-java-transport-zerodep:$dockerJavaVersion"+ )+ exclude(group = "io.jsonwebtoken", module = "jjwt-gson")+ exclude(group = "org.apache.logging.log4j", module = "log4j-to-slf4j")+}++java {+ toolchain.languageVersion.set(JavaLanguageVersion.of(24))+}++dependencies {+ testImplementation(project(":api"))+ testImplementation(project(":catalogs:catalog-common"))+ testImplementation(project(":common"))+ testImplementation(project(":clients:client-java"))+ testImplementation(project(":core"))+ testImplementation(project(":server-common"))++ testImplementation("io.trino:trino-iceberg:$trinoVersion")+ testImplementation("io.trino:trino-hdfs:$trinoVersion")+ testImplementation("io.trino:trino-testing:$trinoVersion")+ testImplementation("io.trino:trino-main:$trinoVersion")++ testImplementation(project(":integration-test-common", "testArtifacts"))++ // Runtime dependencies of the inherited BaseIT/ITUtils harness. The testArtifacts dependency+ // above only carries their compiled classes, not their transitive runtime deps, so these must be+ // declared here (BaseIT uses Awaitility and commons-lang3; omitting them fails the ITs at runtime+ // with NoClassDefFoundError).+ testRuntimeOnly(libs.awaitility)+ testRuntimeOnly(libs.commons.lang3)+ testImplementation(libs.postgresql.driver)+ testImplementation(libs.testcontainers)+ testImplementation(libs.testcontainers.postgresql)++ // jjwt is resolved to 0.13.x on this module's test classpath (Trino forces it up). Only pull+ // api + impl; the JSON serializer (jjwt-jackson:0.13.x) is already provided transitively by+ // Trino, so it does not need to be declared here. Do NOT pull jjwt-gson:0.11.x (the bundle's+ // default) — its stale 0.11.x serializer service is incompatible with the 0.13.x runtime and+ // makes signWith().compact() fail.+ testImplementation(libs.jwt.api)+ testRuntimeOnly(libs.jwt.impl)+ testImplementation(libs.guava)+ testImplementation(libs.slf4j.api)+ // Trino 478's test stack forces JUnit to 6.0.0; pin the BOM to match so the platform launcher,+ // engine and commons jars stay on the same version (a mismatch makes Gradle's TagFilter crash+ // with NoSuchMethodError on CollectionUtils.toUnmodifiableList).+ testImplementation(platform("org.junit:junit-bom:6.0.0"))+ testImplementation("org.junit.jupiter:junit-jupiter")+ testRuntimeOnly("org.junit.platform:junit-platform-launcher")+}++tasks.withType<JavaCompile>().configureEach {+ // Error Prone (2.10.0) is incompatible with the JDK 24 toolchain required by this Trino range.+ options.errorprone.isEnabled.set(false)+}++tasks.withType<Test>().configureEach {+ // JaCoCo 0.8.9 cannot instrument classes compiled for the JDK 24 toolchain used here.+ extensions+ .findByType(org.gradle.testing.jacoco.plugins.JacocoTaskExtension::class.java)+ ?.isEnabled = false+}++tasks.test {+ // This module contains only integration tests that require the built distribution (deploy+ // mode). Exclude them when integration tests are skipped, consistent with the other modules.+ val skipITs = project.hasProperty("skipITs")+ if (skipITs) {+ exclude("**/integration/test/**")+ }+}diff --git a/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/MockOAuthTokenServer.java b/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/MockOAuthTokenServer.javanew file mode 100644index 0000000000..fd3b4b88d7--- /dev/null+++ b/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/MockOAuthTokenServer.java@@ -0,0 +1,151 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.iceberg.integration.test.trino;++import com.sun.net.httpserver.HttpExchange;+import com.sun.net.httpserver.HttpServer;+import io.jsonwebtoken.Jwts;+import java.io.IOException;+import java.io.OutputStream;+import java.net.InetSocketAddress;+import java.nio.charset.StandardCharsets;+import java.security.KeyPair;+import java.util.Date;++/**+ * A minimal OAuth2 token endpoint for tests. Answers any client-credentials POST with a freshly+ * signed RS256 JWT whose subject and audience are fixed at construction. Bound to 127.0.0.1 so a+ * deploy-mode Gravitino server subprocess on the same host can reach it.+ *+ * <p>This module's test classpath resolves jjwt to 0.13.x (forced up by Trino's transitive+ * dependencies), so the non-deprecated 0.13.x signing API is used here.+ */+public final class MockOAuthTokenServer implements AutoCloseable {++ private static final String TOKEN_PATH = "/oauth2/token";++ private final HttpServer httpServer;+ private final KeyPair keyPair;+ private final String audience;+ private final String subject;+ private volatile String lastIssuedToken;++ /**+ * Creates a token server bound to an ephemeral port on 127.0.0.1.+ *+ * @param keyPair the RS256 key pair used to sign issued tokens+ * @param audience the audience claim placed on every issued token+ * @param subject the subject claim placed on every issued token+ * @throws IOException if the underlying HTTP server cannot be created+ */+ public MockOAuthTokenServer(KeyPair keyPair, String audience, String subject) throws IOException {+ this.keyPair = keyPair;+ this.audience = audience;+ this.subject = subject;+ this.httpServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);+ this.httpServer.createContext(TOKEN_PATH, this::handle);+ }++ /**+ * Generates an RS256 key pair suitable for signing/validating the test tokens.+ *+ * @return a freshly generated RSA key pair+ */+ public static KeyPair newRsaKeyPair() {+ return Jwts.SIG.RS256.keyPair().build();+ }++ /** Starts the embedded HTTP server. */+ public void start() {+ httpServer.start();+ }++ /**+ * Returns the ephemeral port the server is listening on.+ *+ * @return the bound TCP port+ */+ public int port() {+ return httpServer.getAddress().getPort();+ }++ /**+ * Returns the base server URI, e.g. {@code http://127.0.0.1:34567} — pass as {@code+ * GRAVITINO_OAUTH2_SERVER_URI}.+ *+ * @return the base server URI+ */+ public String serverUri() {+ return "http://127.0.0.1:" + port();+ }++ /**+ * Returns the token path, e.g. {@code /oauth2/token} — pass as {@code+ * GRAVITINO_OAUTH2_TOKEN_PATH}.+ *+ * @return the token path+ */+ public String tokenPath() {+ return TOKEN_PATH;+ }++ /**+ * Returns the fully qualified token endpoint URL.+ *+ * @return the token endpoint URL+ */+ public String tokenEndpoint() {+ return serverUri() + TOKEN_PATH;+ }++ /**+ * Returns the most recently issued token, or {@code null} if none has been issued yet.+ *+ * @return the last issued token+ */+ public String lastIssuedToken() {+ return lastIssuedToken;+ }++ private void handle(HttpExchange exchange) throws IOException {+ String token =+ Jwts.builder()+ .subject(subject)+ .audience()+ .add(audience)+ .and()+ .expiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000))+ .signWith(keyPair.getPrivate(), Jwts.SIG.RS256)+ .compact();+ this.lastIssuedToken = token;+ String body =+ "{\"access_token\":\"" + token + "\",\"token_type\":\"Bearer\",\"expires_in\":3600}";+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);+ exchange.getResponseHeaders().add("Content-Type", "application/json");+ exchange.sendResponseHeaders(200, bytes.length);+ try (OutputStream os = exchange.getResponseBody()) {+ os.write(bytes);+ }+ }++ @Override+ public void close() {+ httpServer.stop(0);+ }+}diff --git a/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TestMockOAuthTokenServer.java b/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TestMockOAuthTokenServer.javanew file mode 100644index 0000000000..694869a9ff--- /dev/null+++ b/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TestMockOAuthTokenServer.java@@ -0,0 +1,69 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.iceberg.integration.test.trino;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++import io.jsonwebtoken.Claims;+import io.jsonwebtoken.Jwts;+import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;+import java.security.KeyPair;+import org.junit.jupiter.api.Test;++public class TestMockOAuthTokenServer {++ @Test+ public void testServesSignedTokenForSubject() throws Exception {+ KeyPair keyPair = MockOAuthTokenServer.newRsaKeyPair();+ try (MockOAuthTokenServer server =+ new MockOAuthTokenServer(keyPair, "test-audience", "service-user")) {+ server.start();++ HttpResponse<String> resp =+ HttpClient.newHttpClient()+ .send(+ HttpRequest.newBuilder(URI.create(server.tokenEndpoint()))+ .header("Content-Type", "application/x-www-form-urlencoded")+ .POST(HttpRequest.BodyPublishers.ofString("grant_type=client_credentials"))+ .build(),+ HttpResponse.BodyHandlers.ofString());++ assertEquals(200, resp.statusCode());+ String accessToken = server.lastIssuedToken();+ assertTrue(resp.body().contains(accessToken));++ // jjwt is resolved to 0.13.x on this module's test classpath (forced up by Trino's+ // transitive dependencies). In 0.13.x, Jwts.parserBuilder() was renamed to Jwts.parser(),+ // setSigningKey(PublicKey) became verifyWith(PublicKey), and parseClaimsJws(...).getBody()+ // became parseSignedClaims(...).getPayload(). getAudience() now returns a Set<String>.+ Claims claims =+ Jwts.parser()+ .verifyWith(keyPair.getPublic())+ .build()+ .parseSignedClaims(accessToken)+ .getPayload();+ assertEquals("service-user", claims.getSubject());+ assertTrue(claims.getAudience().contains("test-audience"));+ }+ }+}diff --git a/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TrinoIcebergRESTAuthorizationIT.java b/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TrinoIcebergRESTAuthorizationIT.javanew file mode 100644index 0000000000..044a265482--- /dev/null+++ b/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TrinoIcebergRESTAuthorizationIT.java@@ -0,0 +1,114 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.iceberg.integration.test.trino;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++import com.google.common.collect.ImmutableList;+import java.util.HashMap;+import org.apache.gravitino.authorization.Privileges;+import org.apache.gravitino.authorization.SecurableObject;+import org.apache.gravitino.authorization.SecurableObjects;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Tag;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++@Tag("gravitino-docker-test")+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+public class TrinoIcebergRESTAuthorizationIT extends TrinoIcebergRESTAuthorizationITBase {++ private static final String ROLE = "trino_role";++ // Substring of the message Gravitino's IRC authorization filter returns in the Iceberg REST 403+ // response (see BaseMetadataAuthorizationMethodInterceptor). Trino surfaces it verbatim for write+ // operations (e.g. CREATE TABLE).+ private static final String NOT_AUTHORIZED_MESSAGE = "is not authorized to perform operation";++ // On the read path Trino masks the REST 403 body and only reports that it could not load the+ // table/view, so a denied SELECT shows up as this instead of the message above.+ private static final String LOAD_FAILED_MESSAGE = "Failed to load";++ @BeforeAll+ public void setupTrino() throws Exception {+ catalogAsSuper.asSchemas().createSchema("db1", "", new HashMap<>());+ startTrino();+ sql(SUPER_CATALOG, "CREATE TABLE db1.shared (id integer)");+ sql(SUPER_CATALOG, "INSERT INTO db1.shared VALUES (1)");+ }++ @Test+ @Order(1)+ public void testNormalUserDeniedWithoutPrivileges() {+ RuntimeException e =+ assertThrows(RuntimeException.class, () -> sql(NORMAL_CATALOG, "SELECT * FROM db1.shared"));+ assertAuthorizationDenied(e);+ }++ @Test+ @Order(2)+ public void testNormalUserAllowedAfterGrant() {+ SecurableObject catalogObject =+ SecurableObjects.ofCatalog(+ CATALOG_NAME,+ ImmutableList.of(+ Privileges.UseCatalog.allow(),+ Privileges.UseSchema.allow(),+ Privileges.SelectTable.allow()));+ metalakeAsSuper.createRole(ROLE, new HashMap<>(), ImmutableList.of(catalogObject));+ metalakeAsSuper.grantRolesToUser(ImmutableList.of(ROLE), NORMAL_USER);++ assertEquals(1L, sql(NORMAL_CATALOG, "SELECT count(*) FROM db1.shared").getOnlyValue());+ }++ @Test+ @Order(3)+ public void testNormalUserDeniedCreateTable() {+ RuntimeException e =+ assertThrows(+ RuntimeException.class,+ () -> sql(NORMAL_CATALOG, "CREATE TABLE db1.normal_made (id integer)"));+ assertAuthorizationDenied(e);+ }++ /**+ * Asserts that the query failed because access was denied (an Iceberg REST 403) rather than for+ * some unrelated reason, by inspecting the whole exception cause chain. The companion {@link+ * #testNormalUserAllowedAfterGrant()} confirms the same query succeeds once the privilege is+ * granted, which together establishes that authorization is what blocked it.+ *+ * @param e the exception thrown by the denied Trino query+ */+ private static void assertAuthorizationDenied(RuntimeException e) {+ StringBuilder messages = new StringBuilder();+ for (Throwable cause = e; cause != null; cause = cause.getCause()) {+ if (cause.getMessage() != null) {+ messages.append(cause.getMessage()).append('\n');+ }+ }+ String chain = messages.toString();+ assertTrue(+ chain.contains(NOT_AUTHORIZED_MESSAGE) || chain.contains(LOAD_FAILED_MESSAGE),+ "Expected an authorization failure but got: " + chain);+ }+}diff --git a/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TrinoIcebergRESTAuthorizationITBase.java b/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TrinoIcebergRESTAuthorizationITBase.javanew file mode 100644index 0000000000..56e9b0d6b6--- /dev/null+++ b/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TrinoIcebergRESTAuthorizationITBase.java@@ -0,0 +1,249 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.iceberg.integration.test.trino;++import static io.trino.testing.TestingSession.testSessionBuilder;++import com.google.common.collect.ImmutableMap;+import io.jsonwebtoken.Jwts;+import io.trino.plugin.iceberg.IcebergPlugin;+import io.trino.testing.DistributedQueryRunner;+import io.trino.testing.MaterializedResult;+import io.trino.testing.QueryRunner;+import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.security.KeyPair;+import java.util.Base64;+import java.util.Date;+import java.util.HashMap;+import java.util.Map;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.Configs;+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;+import org.apache.gravitino.client.GravitinoMetalake;+import org.apache.gravitino.integration.test.util.BaseIT;+import org.apache.gravitino.integration.test.util.ITUtils;+import org.apache.gravitino.integration.test.util.OAuthMockDataProvider;+import org.apache.gravitino.integration.test.util.TestDatabaseName;+import org.apache.gravitino.server.authentication.OAuthConfig;+import org.apache.gravitino.server.authorization.jcasbin.JcasbinAuthorizer;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.Assumptions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.TestInstance;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Boots a deploy-mode Gravitino server with the Iceberg REST auxiliary service, OAuth+ * authentication, and authorization enabled.+ */+@TestInstance(TestInstance.Lifecycle.PER_CLASS)+public abstract class TrinoIcebergRESTAuthorizationITBase extends BaseIT {++ private static final Logger LOG =+ LoggerFactory.getLogger(TrinoIcebergRESTAuthorizationITBase.class);+ private static final String GRAVITINO_ICEBERG_REST_PREFIX = "gravitino.iceberg-rest.";++ protected static final String METALAKE_NAME = "test_metalake";+ protected static final String CATALOG_NAME = "iceberg";+ protected static final String SERVICE_AUDIENCE = "gravitino-irc";+ protected static final String SUPER_USER = "super";+ protected static final String NORMAL_USER = "normal";+ protected static final String SUPER_CATALOG = "iceberg_super";+ protected static final String NORMAL_CATALOG = "iceberg_normal";++ protected final KeyPair keyPair = MockOAuthTokenServer.newRsaKeyPair();+ protected MockOAuthTokenServer tokenServer;+ protected String warehouseDir;+ protected GravitinoMetalake metalakeAsSuper;+ protected Catalog catalogAsSuper;+ protected QueryRunner queryRunner;++ /**+ * Mints a signed bearer token for a test user.+ *+ * @param user token subject+ * @return an RS256-signed JWT+ */+ @SuppressWarnings("JavaUtilDate")+ protected String mintToken(String user) {+ return Jwts.builder()+ .subject(user)+ .audience()+ .add(SERVICE_AUDIENCE)+ .and()+ .expiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000))+ .signWith(keyPair.getPrivate(), Jwts.SIG.RS256)+ .compact();+ }++ @BeforeAll+ @Override+ public void startIntegrationTest() throws Exception {+ // This IT boots the Gravitino server with the Iceberg REST auxiliary service and drives it+ // through Trino's native REST connector, which only works against the packaged distribution in+ // deploy mode. The Java 24 / Trino module does not carry the server on its classpath, so the+ // embedded path would fail with NoClassDefFoundError; skip it when not running in deploy mode.+ Assumptions.assumeFalse(+ ITUtils.isEmbedded(), "Trino Iceberg REST authorization IT only runs in deploy mode");+ containerSuite.startPostgreSQLContainer(TestDatabaseName.PG_ICEBERG_AUTHZ_IT);+ tokenServer = new MockOAuthTokenServer(keyPair, SERVICE_AUDIENCE, SUPER_USER);+ tokenServer.start();+ warehouseDir = Files.createTempDirectory("trino-irc-warehouse").toString();++ String publicKey =+ new String(+ Base64.getEncoder().encode(keyPair.getPublic().getEncoded()), StandardCharsets.UTF_8);++ customConfigs.putAll(+ ImmutableMap.of(+ Configs.AUTHENTICATORS.getKey(),+ "oauth",+ OAuthConfig.SERVICE_AUDIENCE.getKey(),+ SERVICE_AUDIENCE,+ OAuthConfig.DEFAULT_SIGN_KEY.getKey(),+ publicKey,+ OAuthConfig.ALLOW_SKEW_SECONDS.getKey(),+ "30",+ OAuthConfig.DEFAULT_SERVER_URI.getKey(),+ tokenServer.serverUri(),+ OAuthConfig.DEFAULT_TOKEN_PATH.getKey(),+ tokenServer.tokenPath()));+ customConfigs.putAll(+ ImmutableMap.of(+ "gravitino.authorization.serviceAdmins",+ SUPER_USER,+ Configs.ENABLE_AUTHORIZATION.getKey(),+ "true",+ Configs.AUTHORIZATION_IMPL.getKey(),+ JcasbinAuthorizer.class.getCanonicalName(),+ Configs.CACHE_ENABLED.getKey(),+ "false"));++ ignoreIcebergAuxRestService = false;+ Map<String, String> ircConfigs = new HashMap<>();+ ircConfigs.put(+ GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.ICEBERG_REST_CATALOG_CONFIG_PROVIDER,+ IcebergConstants.DYNAMIC_ICEBERG_CATALOG_CONFIG_PROVIDER_NAME);+ ircConfigs.put(+ GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_METALAKE, METALAKE_NAME);+ ircConfigs.put(+ GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.ICEBERG_REST_DEFAULT_DYNAMIC_CATALOG_NAME,+ CATALOG_NAME);+ ircConfigs.put(GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_AUTH_TYPE, "oauth");+ ircConfigs.put(+ GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_OAUTH2_SERVER_URI,+ tokenServer.serverUri());+ ircConfigs.put(+ GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_OAUTH2_TOKEN_PATH,+ tokenServer.tokenPath());+ ircConfigs.put(+ GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_OAUTH2_CREDENTIAL,+ "test-client:test-secret");+ ircConfigs.put(GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_OAUTH2_SCOPE, "test");+ customConfigs.putAll(ircConfigs);++ OAuthMockDataProvider.getInstance()+ .setTokenData(mintToken(SUPER_USER).getBytes(StandardCharsets.UTF_8));++ super.startIntegrationTest();+ initMetalakeAndCatalog();+ }++ private void initMetalakeAndCatalog() {+ metalakeAsSuper = client.createMetalake(METALAKE_NAME, "", new HashMap<>());+ metalakeAsSuper.addUser(NORMAL_USER);+ Map<String, String> properties =+ ImmutableMap.<String, String>builder()+ .put(IcebergConstants.CATALOG_BACKEND, "jdbc")+ .put(+ IcebergConstants.URI,+ containerSuite+ .getPostgreSQLContainer()+ .getJdbcUrl(TestDatabaseName.PG_ICEBERG_AUTHZ_IT))+ .put(IcebergConstants.GRAVITINO_JDBC_DRIVER, "org.postgresql.Driver")+ .put(+ IcebergConstants.GRAVITINO_JDBC_USER,+ containerSuite.getPostgreSQLContainer().getUsername())+ .put(+ IcebergConstants.GRAVITINO_JDBC_PASSWORD,+ containerSuite.getPostgreSQLContainer().getPassword())+ .put(IcebergConstants.ICEBERG_JDBC_INITIALIZE, "true")+ .put("gravitino.bypass.jdbc.schema-version", "v1")+ .put(IcebergConstants.WAREHOUSE, "file://" + warehouseDir)+ .build();+ catalogAsSuper =+ metalakeAsSuper.createCatalog(+ CATALOG_NAME, Catalog.Type.RELATIONAL, "lakehouse-iceberg", "comment", properties);+ LOG.info("Created metalake {} and catalog {}", METALAKE_NAME, CATALOG_NAME);+ }++ /** Starts Trino with one native Iceberg REST catalog for each test identity. */+ protected void startTrino() throws Exception {+ queryRunner = DistributedQueryRunner.builder(testSessionBuilder().build()).build();+ queryRunner.installPlugin(new IcebergPlugin());+ queryRunner.createCatalog(+ SUPER_CATALOG, "iceberg", icebergCatalogConfig(mintToken(SUPER_USER)));+ queryRunner.createCatalog(+ NORMAL_CATALOG, "iceberg", icebergCatalogConfig(mintToken(NORMAL_USER)));+ }++ /** Executes SQL through the selected Trino Iceberg REST catalog. */+ protected MaterializedResult sql(String catalog, String query) {+ return queryRunner.execute(testSessionBuilder().setCatalog(catalog).build(), query);+ }++ private Map<String, String> icebergCatalogConfig(String bearerToken) {+ Map<String, String> config = new HashMap<>();+ config.put("iceberg.catalog.type", "rest");+ config.put("iceberg.rest-catalog.uri", getIcebergRestServiceUri());+ config.put("iceberg.rest-catalog.security", "OAUTH2");+ config.put("iceberg.rest-catalog.oauth2.token", bearerToken);+ config.put("fs.hadoop.enabled", "true");+ return config;+ }++ @AfterAll+ @Override+ public void stopIntegrationTest() throws IOException, InterruptedException {+ try {+ if (queryRunner != null) {+ queryRunner.close();+ }+ try {+ if (client != null) {+ client.dropMetalake(METALAKE_NAME, true);+ }+ } catch (Exception e) {+ LOG.warn("Failed to drop test metalake", e);+ }+ } finally {+ if (tokenServer != null) {+ tokenServer.close();+ }+ // Do not close the shared ContainerSuite here: it is a process-wide singleton whose+ // PostgreSQL container may be reused by other tests in the same JVM. Test classes that share+ // its PostgreSQL-backed Iceberg catalog isolate themselves with distinct schema namespaces+ // rather than resetting the container; the suite cleans up its containers on JVM shutdown.+ super.stopIntegrationTest();+ }+ }+}diff --git a/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TrinoIcebergRESTSmokeIT.java b/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TrinoIcebergRESTSmokeIT.javanew file mode 100644index 0000000000..52d1227414--- /dev/null+++ b/iceberg/iceberg-rest-trino-it/src/test/java/org/apache/gravitino/iceberg/integration/test/trino/TrinoIcebergRESTSmokeIT.java@@ -0,0 +1,49 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.iceberg.integration.test.trino;++import static org.junit.jupiter.api.Assertions.assertEquals;++import java.util.HashMap;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Tag;+import org.junit.jupiter.api.Test;++@Tag("gravitino-docker-test")+public class TrinoIcebergRESTSmokeIT extends TrinoIcebergRESTAuthorizationITBase {++ // Use a schema name distinct from the other IT classes: they share one PostgreSQL-backed Iceberg+ // catalog (the shared ContainerSuite is intentionally not reset between classes), so a common+ // namespace would collide across classes.+ private static final String SCHEMA = "smoke_db";++ @BeforeAll+ public void setupTrino() throws Exception {+ catalogAsSuper.asSchemas().createSchema(SCHEMA, "", new HashMap<>());+ startTrino();+ }++ @Test+ public void testCreateInsertSelectAsSuperUser() {+ sql(SUPER_CATALOG, "CREATE TABLE " + SCHEMA + ".t1 (id integer, name varchar)");+ sql(SUPER_CATALOG, "INSERT INTO " + SCHEMA + ".t1 VALUES (1, 'a'), (2, 'b')");+ assertEquals(2L, sql(SUPER_CATALOG, "SELECT count(*) FROM " + SCHEMA + ".t1").getOnlyValue());+ sql(SUPER_CATALOG, "DROP TABLE " + SCHEMA + ".t1");+ }+}diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 5f21cc7790..e49a0e4d11 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -66,6 +66,7 @@ if (gradle.startParameter.projectProperties["enableFuse"]?.toBoolean() == true)}include("iceberg:iceberg-common")include("iceberg:iceberg-rest-server")+include("iceberg:iceberg-rest-trino-it")include("lance:lance-common")include("lance:lance-rest-server")include("authorizations:authorization-ranger", "authorizations:authorization-common", "authorizations:authorization-chain")