World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#10959] feat(idp-basic): Add Basic authentication for built-in IdP (#11226)
MaSai3c60292e3116
diff --git a/.github/workflows/backend-integration-test-action.yml b/.github/workflows/backend-integration-test-action.ymlindex 0c507fc25c..641b66e6f1 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 :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 \$EXCLUDE_CONTRIB_TESTSdiff --git a/.github/workflows/idp-basic-test.yml b/.github/workflows/idp-basic-test.ymlindex 9e3d7e05bf..cc584e7747 100644--- a/.github/workflows/idp-basic-test.yml+++ b/.github/workflows/idp-basic-test.yml@@ -46,7 +46,7 @@ jobs:needs: changesif: needs.changes.outputs.source_changes == 'true' && needs.changes.outputs.module_exists == 'true'runs-on: ubuntu-22.04- timeout-minutes: 60+ timeout-minutes: 30steps:- uses: actions/checkout@v4@@ -56,21 +56,52 @@ jobs:distribution: "temurin"cache: "gradle"+ - 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 spacerun: |dev/ci/util_free_space.sh- name: Run idp-basic tests+ id: idpBasicTestenv:dockerTest: true+ GRAVITINO_INITIAL_ADMIN_PASSWORD: Passw0rd-For-Admin1run: |- ./gradlew :plugins:idp-basic:test -PskipITs -PskipDockerTests=false -PskipWeb=true+ set -euo pipefail++ # Unit and in-process tests (no Docker, no REST IT).+ ./gradlew :plugins:idp-basic:test -PskipITs -PskipDockerTests=true++ # REST IT: embedded and deploy, each against h2 / MySQL / PostgreSQL.+ for test_mode in embedded deploy; do+ for backend in h2 mysql postgresql; do+ ./gradlew :plugins:idp-basic:test \+ -PtestMode="${test_mode}" \+ -PjdbcBackend="${backend}" \+ -PskipDockerTests=false \+ --tests "org.apache.gravitino.idp.integration.test.**"+ done+ done- name: Upload idp-basic test reportsuses: actions/upload-artifact@v7- if: failure()+ if: ${{ (failure() && steps.idpBasicTest.outcome == 'failure') || contains(github.event.pull_request.labels.*.name, 'upload log') }}with:name: idp-basic-test-reportspath: |plugins/idp-basic/build/reportsplugins/idp-basic/build/test-results+ distribution/package-all/logs/gravitino-server.out+ distribution/package-all/logs/gravitino-server.log+ distribution/package/logs/gravitino-server.out+ distribution/package/logs/gravitino-server.logdiff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/BasicTokenProvider.java b/clients/client-java/src/main/java/org/apache/gravitino/client/BasicTokenProvider.javanew file mode 100644index 0000000000..aa1a598de7--- /dev/null+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/BasicTokenProvider.java@@ -0,0 +1,57 @@+/*+ * 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.client;++import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.util.Base64;+import org.apache.gravitino.auth.AuthConstants;++/** Provides HTTP Basic credentials for Gravitino built-in IdP authentication. */+final class BasicTokenProvider implements AuthDataProvider {++ private final byte[] token;++ BasicTokenProvider(String username, String password) {+ this.token = buildToken(username, password);+ }++ private static byte[] buildToken(String username, String password) {+ String userInformation = username + ":" + password;+ return (AuthConstants.AUTHORIZATION_BASIC_HEADER+ + new String(+ Base64.getEncoder().encode(userInformation.getBytes(StandardCharsets.UTF_8)),+ StandardCharsets.UTF_8))+ .getBytes(StandardCharsets.UTF_8);+ }++ @Override+ public boolean hasTokenData() {+ return true;+ }++ @Override+ public byte[] getTokenData() {+ return token;+ }++ @Override+ public void close() throws IOException {}+}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClientBase.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClientBase.javaindex 60e6902091..996c149591 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClientBase.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClientBase.java@@ -276,6 +276,20 @@ public abstract class GravitinoClientBase implements Closeable {return this;}+ /**+ * Sets HTTP Basic authentication for Gravitino.+ *+ * @param username The username for Basic authentication.+ * @param password The password for Basic authentication.+ * @return This Builder instance for method chaining.+ */+ public Builder<T> withBasicAuth(String username, String password) {+ Preconditions.checkArgument(StringUtils.isNotBlank(username), "username can't be blank");+ Preconditions.checkArgument(StringUtils.isNotBlank(password), "password can't be blank");+ this.authDataProvider = new BasicTokenProvider(username, password);+ return this;+ }+/*** Optional, set a flag to verify the client is supported to connector the server*diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestBasicTokenProvider.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestBasicTokenProvider.javanew file mode 100644index 0000000000..4e9a614f48--- /dev/null+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestBasicTokenProvider.java@@ -0,0 +1,47 @@+/*+ * 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.client;++import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.util.Base64;+import org.apache.gravitino.auth.AuthConstants;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestBasicTokenProvider {++ @Test+ public void testAuthentication() throws IOException {+ try (AuthDataProvider provider = new BasicTokenProvider("admin", "YourSecurePassword12")) {+ Assertions.assertTrue(provider.hasTokenData());+ String token = new String(provider.getTokenData(), StandardCharsets.UTF_8);+ Assertions.assertTrue(token.startsWith(AuthConstants.AUTHORIZATION_BASIC_HEADER));+ String tokenString =+ new String(+ Base64.getDecoder()+ .decode(+ token+ .substring(AuthConstants.AUTHORIZATION_BASIC_HEADER.length())+ .getBytes(StandardCharsets.UTF_8)),+ StandardCharsets.UTF_8);+ Assertions.assertEquals("admin:YourSecurePassword12", tokenString);+ }+ }+}diff --git a/clients/client-python/gravitino/auth/basic_auth_provider.py b/clients/client-python/gravitino/auth/basic_auth_provider.pynew file mode 100644index 0000000000..e3bd67fa9e--- /dev/null+++ b/clients/client-python/gravitino/auth/basic_auth_provider.py@@ -0,0 +1,56 @@+# 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 base64++from gravitino.auth.auth_constants import AuthConstants+from gravitino.auth.auth_data_provider import AuthDataProvider+from gravitino.exceptions.base import IllegalArgumentException+++class BasicAuthProvider(AuthDataProvider):+ """Provides HTTP Basic credentials for Gravitino built-in IdP authentication."""++ _token: bytes++ def __init__(self, username: str, password: str):+ if username is None or not username.strip():+ raise IllegalArgumentException("username can't be blank")+ if password is None or not password.strip():+ raise IllegalArgumentException("password can't be blank")++ self._token = self._build_basic_auth_token(username, password)++ def has_token_data(self) -> bool:+ return True++ def get_token_data(self) -> bytes:+ return self._token++ def close(self):+ pass++ @staticmethod+ def _build_basic_auth_token(username: str, password: str) -> bytes:+ credentials = f"{username}:{password}"+ encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode(+ "utf-8"+ )+ authorization_header = (+ AuthConstants.AUTHORIZATION_BASIC_HEADER + encoded_credentials+ )+ return authorization_header.encode("utf-8")diff --git a/clients/client-python/gravitino/filesystem/gvfs_config.py b/clients/client-python/gravitino/filesystem/gvfs_config.pyindex 969d8a9052..f6c46f7741 100644--- a/clients/client-python/gravitino/filesystem/gvfs_config.py+++ b/clients/client-python/gravitino/filesystem/gvfs_config.py@@ -25,6 +25,9 @@ class GVFSConfig:AUTH_TYPE = "auth_type"SIMPLE_AUTH_TYPE = "simple"+ BASIC_AUTH_TYPE = "basic"+ BASIC_USERNAME = "basic_username"+ BASIC_PASSWORD = "basic_password"OAUTH2_AUTH_TYPE = "oauth2"OAUTH2_SERVER_URI = "oauth2_server_uri"diff --git a/clients/client-python/gravitino/filesystem/gvfs_utils.py b/clients/client-python/gravitino/filesystem/gvfs_utils.pyindex ac71af815a..9c3ef17257 100644--- a/clients/client-python/gravitino/filesystem/gvfs_utils.py+++ b/clients/client-python/gravitino/filesystem/gvfs_utils.py@@ -18,6 +18,7 @@ import refrom typing import Dictfrom gravitino.client.gravitino_client import GravitinoClient+from gravitino.auth.basic_auth_provider import BasicAuthProviderfrom gravitino.auth.default_oauth2_token_provider import DefaultOAuth2TokenProviderfrom gravitino.auth.oauth2_token_provider import OAuth2TokenProviderfrom gravitino.auth.simple_auth_provider import SimpleAuthProvider@@ -73,6 +74,21 @@ def create_client(client_config=client_config,)+ if auth_type == GVFSConfig.BASIC_AUTH_TYPE:+ basic_username = options.get(GVFSConfig.BASIC_USERNAME)+ _check_auth_config(auth_type, GVFSConfig.BASIC_USERNAME, basic_username)++ basic_password = options.get(GVFSConfig.BASIC_PASSWORD)+ _check_auth_config(auth_type, GVFSConfig.BASIC_PASSWORD, basic_password)++ return GravitinoClient(+ uri=server_uri,+ metalake_name=metalake_name,+ auth_data_provider=BasicAuthProvider(basic_username, basic_password),+ request_headers=request_headers,+ client_config=client_config,+ )+if auth_type == GVFSConfig.OAUTH2_AUTH_TYPE:oauth2_server_uri = options.get(GVFSConfig.OAUTH2_SERVER_URI)_check_auth_config(auth_type, GVFSConfig.OAUTH2_SERVER_URI, oauth2_server_uri)diff --git a/clients/client-python/tests/unittests/auth/test_basic_auth_provider.py b/clients/client-python/tests/unittests/auth/test_basic_auth_provider.pynew file mode 100644index 0000000000..dc26a7d5e8--- /dev/null+++ b/clients/client-python/tests/unittests/auth/test_basic_auth_provider.py@@ -0,0 +1,47 @@+# 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 base64+import unittest++from gravitino.auth.auth_constants import AuthConstants+from gravitino.auth.auth_data_provider import AuthDataProvider+from gravitino.auth.basic_auth_provider import BasicAuthProvider+from gravitino.exceptions.base import IllegalArgumentException+++class TestBasicAuthProvider(unittest.TestCase):+ def test_auth_provider(self):+ provider: AuthDataProvider = BasicAuthProvider(+ "admin", "YourSecureGravitinoPassword"+ )+ self.assertTrue(provider.has_token_data())+ token = provider.get_token_data().decode("utf-8")+ self.assertTrue(token.startswith(AuthConstants.AUTHORIZATION_BASIC_HEADER))+ token_string = base64.b64decode(+ token[len(AuthConstants.AUTHORIZATION_BASIC_HEADER) :]+ ).decode("utf-8")+ self.assertEqual("admin:YourSecureGravitinoPassword", token_string)+ provider.close()++ def test_blank_username(self):+ with self.assertRaises(IllegalArgumentException):+ BasicAuthProvider(" ", "password")++ def test_blank_password(self):+ with self.assertRaises(IllegalArgumentException):+ BasicAuthProvider("admin", " ")diff --git a/clients/client-python/tests/unittests/test_gvfs_with_local.py b/clients/client-python/tests/unittests/test_gvfs_with_local.pyindex 46a7215d76..88c6003fb9 100644--- a/clients/client-python/tests/unittests/test_gvfs_with_local.py+++ b/clients/client-python/tests/unittests/test_gvfs_with_local.py@@ -197,6 +197,25 @@ class TestLocalFilesystem(unittest.TestCase):if current_user is not None:os.environ["user.name"] = current_user+ def test_basic_auth(self, *mock_methods):+ options = {+ GVFSConfig.AUTH_TYPE: GVFSConfig.BASIC_AUTH_TYPE,+ GVFSConfig.BASIC_USERNAME: "admin",+ GVFSConfig.BASIC_PASSWORD: "YourSecureGravitinoPassword",+ }+ fs = gvfs.GravitinoVirtualFileSystem(+ server_uri=self._server_uri,+ metalake_name=self._metalake_name,+ options=options,+ skip_instance_cache=True,+ )+ client = fs._operations._get_gravitino_client()+ token = client._rest_client.auth_data_provider.get_token_data()+ token_string = base64.b64decode(+ token.decode("utf-8")[len(AuthConstants.AUTHORIZATION_BASIC_HEADER) :]+ ).decode("utf-8")+ self.assertEqual("admin:YourSecureGravitinoPassword", token_string)+def test_oauth2_auth(self, *mock_methods):fs_options = {GVFSConfig.AUTH_TYPE: GVFSConfig.OAUTH2_AUTH_TYPE,diff --git a/docs/how-to-use-gvfs.md b/docs/how-to-use-gvfs.mdindex 7f252a8f42..1710a31f76 100644--- a/docs/how-to-use-gvfs.md+++ b/docs/how-to-use-gvfs.md@@ -416,7 +416,9 @@ to recompile the native libraries like `libhdfs` and others, and completely repl| `metalake_name` | The metalake name which the fileset belongs to. | (none) | Yes | 0.6.0-incubating || `cache_size` | The cache capacity of the Gravitino Virtual File System. | `20` | No | 0.6.0-incubating || `cache_expired_time` | The value of time that the cache expires after accessing in the Gravitino Virtual File System. The value is in `seconds`. | `3600` | No | 0.6.0-incubating |-| `auth_type` | The auth type to initialize the Gravitino client to use with the Gravitino Virtual File System. Currently supports `simple` and `oauth2` auth types. | `simple` | No | 0.6.0-incubating |+| `auth_type` | The auth type to initialize the Gravitino client to use with the Gravitino Virtual File System. Currently supports `simple`, `basic`, and `oauth2` auth types. | `simple` | No | 0.6.0-incubating |+| `basic_username` | The username for the Gravitino client when using `basic` auth type with the built-in IDP. | (none) | Yes if you use `basic` auth type | 1.3.0 |+| `basic_password` | The password for the Gravitino client when using `basic` auth type with the built-in IDP. | (none) | Yes if you use `basic` auth type | 1.3.0 || `oauth2_server_uri` | The auth server URI for the Gravitino client when using `oauth2` auth type. | (none) | Yes if you use `oauth2` auth type | 0.7.0-incubating || `oauth2_credential` | The auth credential for the Gravitino client when using `oauth2` auth type. | (none) | Yes if you use `oauth2` auth type | 0.7.0-incubating || `oauth2_path` | The auth server path for the Gravitino client when using `oauth2` auth type. Please remove the first slash `/` from the path, for example `oauth/token`. | (none) | Yes if you use `oauth2` auth type | 0.7.0-incubating |@@ -695,7 +697,7 @@ print(documents)### Authentication-Currently, Gravitino Virtual File System in Python supports two kinds of authentication types to access Gravitino server: `simple` and `oauth2`.+Currently, Gravitino Virtual File System in Python supports three kinds of authentication types to access Gravitino server: `simple`, `basic`, and `oauth2`.The type of `simple` is the default authentication type in Gravitino Virtual File System in Python.@@ -715,6 +717,26 @@ fs = gvfs.GravitinoVirtualFileSystem(server_uri="http://localhost:8090", metalakprint(fs.ls("gvfs://fileset/fileset_catalog/tmp/test_fileset"))```+##### Using `basic` authentication++First, make sure that your Gravitino server is also configured to use the `basic` authentication mode.+See [How to authenticate](security/how-to-authenticate.md#basic-mode) for server-side setup.++Then, you can configure the authentication like this:++```python+from gravitino import gvfs+from gravitino.filesystem.gvfs_config import GVFSConfig++options = {+ GVFSConfig.AUTH_TYPE: GVFSConfig.BASIC_AUTH_TYPE,+ GVFSConfig.BASIC_USERNAME: "admin",+ GVFSConfig.BASIC_PASSWORD: "YourSecureGravitinoPassword",+}+fs = gvfs.GravitinoVirtualFileSystem(server_uri="http://localhost:8090", metalake_name="test_metalake", options=options)+print(fs.ls("gvfs://fileset/fileset_catalog/tmp/test_fileset"))+```+##### Using `OAuth` authenticationFirst, make sure that your Gravitino server is also configured to use the `oauth2` authentication mode,diff --git a/docs/index.md b/docs/index.mdindex bd48ce4924..f30fd380ab 100644--- a/docs/index.md+++ b/docs/index.md@@ -210,7 +210,7 @@ Gravitino provides several ways to configure and manage the Gravitino server. SeGravitino provides security configurations for Gravitino, including HTTPS, authentication and access control configurations.* [HTTPS](./security/how-to-use-https.md): provides HTTPS configurations.-* [Authentication](./security/how-to-authenticate.md): provides authentication configurations including simple, OAuth, Kerberos.+* [Authentication](./security/how-to-authenticate.md): provides authentication configurations including simple, basic, OAuth, and Kerberos.* [Access Control](./security/access-control.md): provides access control configurations.* [CORS](./security/how-to-use-cors.md): provides CORS configurations.diff --git a/docs/security/how-to-authenticate.md b/docs/security/how-to-authenticate.mdindex 54dab3bac9..004a98c661 100644--- a/docs/security/how-to-authenticate.md+++ b/docs/security/how-to-authenticate.md@@ -7,7 +7,7 @@ license: "This software is licensed under the Apache License version 2."## Authentication-Apache Gravitino supports three kinds of authentication mechanisms: simple, OAuth and Kerberos.+Apache Gravitino supports four kinds of authentication mechanisms: simple, Basic, OAuth and Kerberos.If you don't enable authentication for your client and server explicitly, the user `anonymous` will be used to access the server.### Simple mode@@ -43,6 +43,49 @@ curl -v -X GET \http://localhost:8090/api/version```+### Basic mode++In Basic mode, Gravitino verifies HTTP Basic credentials against built-in IDP user metadata stored+in the relational entity store.++To enable Basic mode:++- Set `gravitino.server.rest.extensionPackages` to `org.apache.gravitino.idp.web.rest.feature`.+- Set `gravitino.authorization.serviceAdmins` to the service admin usernames that should exist in+ the built-in IDP.+- On the first startup, if any configured service admin does not yet have a password, set the+ `GRAVITINO_INITIAL_ADMIN_PASSWORD` environment variable to the initial password (12 to 64+ characters) before starting Gravitino. The same password is applied to every configured service+ admin that does not yet exist in the built-in IDP.++For the client side, enable Basic mode with the following code:++```java+GravitinoClient client = GravitinoClient.builder(uri)+ .withMetalake("metalake")+ .withBasicAuth("admin", "YourSecureGravitinoPassword")+ .build();+```++```python+from gravitino.auth.basic_auth_provider import BasicAuthProvider+from gravitino.client.gravitino_client import GravitinoClient++client = GravitinoClient(+ uri="http://localhost:8090",+ metalake_name="metalake",+ auth_data_provider=BasicAuthProvider("admin", "YourSecureGravitinoPassword"),+)+```++```shell+curl -v -X GET \+ -H "Accept: application/vnd.gravitino.v1+json" \+ -H "Content-Type: application/json" \+ -H "Authorization: Basic $(echo -n 'admin:YourSecureGravitinoPassword' | base64)" \+ http://localhost:8090/api/version+```+### OAuth modeGravitino supports external OAuth 2.0 servers with two token validation methods:@@ -315,6 +358,45 @@ The signature algorithms that Gravitino supports follows:| PS384 | RSASSA-PSS using SHA-384 and MGF1 with SHA-384 || PS512 | RSASSA-PSS using SHA-512 and MGF1 with SHA-512 |+### Example: Basic authentication++This example shows how to enable built-in Basic authentication.++**Prerequisites:**++- Gravitino distribution package (includes the idp-basic plugin on the server classpath)++**Configuration:**++Append the following to `conf/gravitino.conf`:++```text+gravitino.server.rest.extensionPackages = org.apache.gravitino.idp.web.rest.feature+gravitino.authorization.serviceAdmins = admin+```++On the first startup, if the `admin` service admin does not yet have a password in the store,+set initial passwords before starting the server:++```bash+export GRAVITINO_INITIAL_ADMIN_PASSWORD='YourSecureGravitinoPassword'+./bin/start-gravitino.sh+```++**Usage:**++```shell+curl -v -X GET \+ -H "Accept: application/vnd.gravitino.v1+json" \+ -H "Content-Type: application/json" \+ -H "Authorization: Basic $(echo -n 'admin:YourSecureGravitinoPassword' | base64)" \+ http://localhost:8090/api/version+```++If the service admin already has a password, you do not need to set+`GRAVITINO_INITIAL_ADMIN_PASSWORD` on restart. Gravitino does not change existing passwords+when the server starts again.+### Example: Azure AD as OIDC Provider with JWKS ValidationThis example shows how to configure Gravitino with Azure AD using JWKS-based token validation.diff --git a/plugins/idp-basic/build.gradle.kts b/plugins/idp-basic/build.gradle.ktsindex f7ac06bb91..1a91a0ec33 100644--- a/plugins/idp-basic/build.gradle.kts+++ b/plugins/idp-basic/build.gradle.kts@@ -26,6 +26,8 @@ plugins {dependencies {annotationProcessor(libs.lombok)+ implementation(project(":api"))+ implementation(project(":server-common"))implementation(project(":common"))implementation(project(":core"))@@ -42,6 +44,7 @@ dependencies {compileOnly(libs.lombok)compileOnly(libs.slf4j.api)+ testImplementation(project(":clients:client-java"))testImplementation(project(":server"))testImplementation(project(":server-common"))testImplementation(project(":integration-test-common", "testArtifacts"))@@ -89,6 +92,10 @@ tasks {test {environment("GRAVITINO_HOME", rootDir.path)- environment("GRAVITINO_TEST", "true")++ val skipITs = project.hasProperty("skipITs")+ if (skipITs) {+ exclude("**/integration/test/**")+ }}}diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/IdpUserGroupManager.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/IdpUserGroupManager.javaindex 1468fc811b..b0c2a5c68e 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/IdpUserGroupManager.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/IdpUserGroupManager.java@@ -21,13 +21,19 @@ package org.apache.gravitino.idp;import com.google.common.base.Preconditions;import java.io.Closeable;import java.io.IOException;+import java.util.ArrayList;import java.util.Collections;import java.util.List;import javax.annotation.Nullable;+import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.Config;+import org.apache.gravitino.Configs;+import org.apache.gravitino.auth.AuthConstants;+import org.apache.gravitino.exceptions.NotFoundException;+import org.apache.gravitino.exceptions.UnauthorizedException;+import org.apache.gravitino.idp.basic.IdpCredentialValidator;import org.apache.gravitino.idp.basic.password.PasswordHasher;import org.apache.gravitino.idp.basic.password.PasswordHasherFactory;-import org.apache.gravitino.idp.exception.NotFoundException;import org.apache.gravitino.idp.model.IdpGroup;import org.apache.gravitino.idp.model.IdpUser;import org.apache.gravitino.idp.storage.po.IdpGroupPO;@@ -48,23 +54,67 @@ public class IdpUserGroupManager implements Closeable {private static final IdpUserMetaService USER_SERVICE = IdpUserMetaService.getInstance();private static final IdpGroupMetaService GROUP_SERVICE = IdpGroupMetaService.getInstance();+ private static volatile IdpUserGroupManager instance;+private final IdpRelationalStorage relationalStorage;+ private final IdpGarbageCollector garbageCollector;private final IdGenerator idGenerator;private final PasswordHasher passwordHasher;- private final IdpGarbageCollector garbageCollector;/**- * Creates a built-in IdP user and group manager.+ * Returns the shared built-in IdP user and group manager for the server process.** @param config The server configuration.* @param idGenerator The id generator.+ * @return The singleton manager instance.*/- public IdpUserGroupManager(Config config, IdGenerator idGenerator) {+ public static IdpUserGroupManager getInstance(Config config, IdGenerator idGenerator) {+ if (instance == null) {+ synchronized (IdpUserGroupManager.class) {+ if (instance == null) {+ instance = new IdpUserGroupManager(config, idGenerator);+ }+ }+ }+ return instance;+ }++ private IdpUserGroupManager(Config config, IdGenerator idGenerator) {this.relationalStorage = new IdpRelationalStorage(config);this.idGenerator = idGenerator;this.passwordHasher = PasswordHasherFactory.create();this.garbageCollector = new IdpGarbageCollector(config);- garbageCollector.start();+ this.garbageCollector.start();+ }++ public void initializeConfiguredServiceAdmins(Config config, String initialAdminPassword)+ throws IOException {+ List<String> serviceAdmins = config.get(Configs.SERVICE_ADMINS);+ if (serviceAdmins == null || serviceAdmins.isEmpty()) {+ return;+ }++ List<String> missingServiceAdmins = new ArrayList<>();+ for (String serviceAdmin : serviceAdmins) {+ IdpCredentialValidator.validateUsername(serviceAdmin);+ if (!checkUserExistence(serviceAdmin)) {+ missingServiceAdmins.add(serviceAdmin);+ }+ }+ if (missingServiceAdmins.isEmpty()) {+ return;+ }++ Preconditions.checkArgument(+ !StringUtils.isBlank(initialAdminPassword),+ "Missing initial password for configured service admin %s; declare"+ + " GRAVITINO_INITIAL_ADMIN_PASSWORD",+ missingServiceAdmins.get(0));+ IdpCredentialValidator.validatePassword(initialAdminPassword);+ String passwordHash = passwordHasher.hash(initialAdminPassword);+ for (String serviceAdmin : missingServiceAdmins) {+ USER_SERVICE.insertIdpUser(newUserPO(serviceAdmin, passwordHash));+ }}/**@@ -75,7 +125,8 @@ public class IdpUserGroupManager implements Closeable {* @return The created built-in IdP user.*/public IdpUser addUser(String username, String password) throws IOException {- USER_SERVICE.insertIdpUser(newUserPO(username, passwordHasher.hash(password)));+ String passwordHash = passwordHasher.hash(password);+ USER_SERVICE.insertIdpUser(newUserPO(username, passwordHash));return new IdpUser(username, Collections.emptyList());}@@ -96,8 +147,21 @@ public class IdpUserGroupManager implements Closeable {* @return The built-in IdP user.*/public IdpUser getUser(String username) {- IdpUserPO userPO = USER_SERVICE.getIdpUserByUsername(username);- return new IdpUser(userPO.getUsername(), USER_SERVICE.listGroupNamesByUsername(username));+ return USER_SERVICE.getIdpUser(username);+ }++ public IdpUser authenticate(String username, String password) {+ try {+ IdpUser user = USER_SERVICE.getIdpUser(username);+ if (user.passwordHash() == null || !passwordHasher.verify(password, user.passwordHash())) {+ throw new UnauthorizedException(+ "Invalid username or password", AuthConstants.AUTHORIZATION_BASIC_HEADER.trim());+ }+ return user;+ } catch (NotFoundException e) {+ throw new UnauthorizedException(+ "Invalid username or password", AuthConstants.AUTHORIZATION_BASIC_HEADER.trim());+ }}/**@@ -141,8 +205,7 @@ public class IdpUserGroupManager implements Closeable {* @return The built-in IdP group.*/public IdpGroup getGroup(String groupName) {- IdpGroupPO groupPO = GROUP_SERVICE.getIdpGroupByName(groupName);- return new IdpGroup(groupPO.getGroupName(), GROUP_SERVICE.listUsernamesByGroupName(groupName));+ return GROUP_SERVICE.getIdpGroup(groupName);}/**@@ -182,6 +245,15 @@ public class IdpUserGroupManager implements Closeable {.build();}+ private boolean checkUserExistence(String username) {+ try {+ USER_SERVICE.getIdpUserByUsername(username);+ return true;+ } catch (NotFoundException e) {+ return false;+ }+ }+private IdpGroupPO newGroupPO(String groupName) {return IdpGroupPO.builder().withGroupId(idGenerator.nextId())diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/auth/BasicAuthenticator.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/auth/BasicAuthenticator.javanew file mode 100644index 0000000000..3192f2fb67--- /dev/null+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/auth/BasicAuthenticator.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.idp.auth;++import com.google.common.base.Preconditions;+import java.nio.charset.StandardCharsets;+import java.security.Principal;+import java.util.Base64;+import java.util.List;+import java.util.Optional;+import java.util.stream.Collectors;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.Config;+import org.apache.gravitino.GravitinoEnv;+import org.apache.gravitino.UserGroup;+import org.apache.gravitino.UserPrincipal;+import org.apache.gravitino.auth.AuthConstants;+import org.apache.gravitino.exceptions.UnauthorizedException;+import org.apache.gravitino.idp.IdpUserGroupManager;+import org.apache.gravitino.idp.model.IdpUser;+import org.apache.gravitino.server.authentication.Authenticator;++/** Authenticates HTTP Basic credentials against built-in IdP user metadata. */+public class BasicAuthenticator implements Authenticator {++ private static final String BASIC_CHALLENGE = AuthConstants.AUTHORIZATION_BASIC_HEADER.trim();++ private IdpUserGroupManager userGroupManager;++ public BasicAuthenticator() {}++ @Override+ public boolean isDataFromToken() {+ return true;+ }++ @Override+ public Principal authenticateToken(byte[] tokenData) {+ Preconditions.checkState(+ userGroupManager != null, "Basic authenticator has not been initialized");+ String authData = requireBasicAuthHeader(tokenData);+ BasicCredentials credentials = parseBasicCredentials(authData);+ return authenticate(credentials, authData);+ }++ @Override+ public void initialize(Config config) {+ GravitinoEnv env = GravitinoEnv.getInstance();+ this.userGroupManager = IdpUserGroupManager.getInstance(config, env.idGenerator());+ }++ @Override+ public boolean supportsToken(byte[] tokenData) {+ return tokenData != null+ && new String(tokenData, StandardCharsets.UTF_8)+ .startsWith(AuthConstants.AUTHORIZATION_BASIC_HEADER);+ }++ private String requireBasicAuthHeader(byte[] tokenData) {+ String authData = tokenData == null ? "" : new String(tokenData, StandardCharsets.UTF_8);+ if (StringUtils.isBlank(authData)) {+ throw new UnauthorizedException("Empty token authorization header", BASIC_CHALLENGE);+ }+ if (!authData.startsWith(AuthConstants.AUTHORIZATION_BASIC_HEADER)) {+ throw new UnauthorizedException("Invalid token authorization header", BASIC_CHALLENGE);+ }+ return authData;+ }++ private BasicCredentials parseBasicCredentials(String authData) {+ String credential = authData.substring(AuthConstants.AUTHORIZATION_BASIC_HEADER.length());+ if (StringUtils.isBlank(credential)) {+ throw new UnauthorizedException(+ "Malformed Basic authorization header: missing credentials", BASIC_CHALLENGE);+ }+ credential = credential.trim();++ final byte[] decodedBytes;+ try {+ decodedBytes = Base64.getDecoder().decode(credential);+ } catch (IllegalArgumentException e) {+ throw new UnauthorizedException(+ "Malformed Basic authorization header: invalid base64", BASIC_CHALLENGE);+ }++ String decodedCredential = new String(decodedBytes, StandardCharsets.UTF_8);+ String[] parts = decodedCredential.split(":", 2);+ if (parts.length != 2) {+ throw new UnauthorizedException(+ "Malformed Basic authorization header: credentials must be in username:password format",+ BASIC_CHALLENGE);+ }++ String username = parts[0];+ if (StringUtils.isBlank(username)) {+ throw new UnauthorizedException(+ "Malformed Basic authorization header: username must not be blank", BASIC_CHALLENGE);+ }++ String password = parts[1];+ if (StringUtils.isBlank(password)) {+ throw new UnauthorizedException("Invalid username or password", BASIC_CHALLENGE);+ }+ return new BasicCredentials(username, password);+ }++ private UserPrincipal authenticate(BasicCredentials credentials, String authData) {+ IdpUser user = userGroupManager.authenticate(credentials.username(), credentials.password());++ List<UserGroup> groups =+ user.groupNames().stream()+ .map(groupName -> new UserGroup(Optional.empty(), groupName))+ .collect(Collectors.toList());+ return new UserPrincipal(user.name(), groups, authData);+ }++ private static final class BasicCredentials {+ private final String username;+ private final String password;++ private BasicCredentials(String username, String password) {+ this.username = username;+ this.password = password;+ }++ private String username() {+ return username;+ }++ private String password() {+ return password;+ }+ }+}diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/exception/AlreadyExistsException.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/exception/AlreadyExistsException.javadeleted file mode 100644index 24f0ae6dde..0000000000--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/exception/AlreadyExistsException.java+++ /dev/null@@ -1,49 +0,0 @@-/*- * 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.idp.exception;--import com.google.errorprone.annotations.FormatMethod;-import com.google.errorprone.annotations.FormatString;--/** Exception thrown when a built-in IdP entity already exists. */-public class AlreadyExistsException extends RuntimeException {-- /**- * Constructs a new exception with the specified detail message.- *- * @param message The detail message.- * @param args The arguments to the message.- */- @FormatMethod- public AlreadyExistsException(@FormatString String message, Object... args) {- super(String.format(message, args));- }-- /**- * Constructs a new exception with the specified detail message and cause.- *- * @param cause The cause.- * @param message The detail message.- * @param args The arguments to the message.- */- @FormatMethod- public AlreadyExistsException(Throwable cause, @FormatString String message, Object... args) {- super(String.format(message, args), cause);- }-}diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/exception/NotFoundException.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/exception/NotFoundException.javadeleted file mode 100644index 33e5852a78..0000000000--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/exception/NotFoundException.java+++ /dev/null@@ -1,49 +0,0 @@-/*- * 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.idp.exception;--import com.google.errorprone.annotations.FormatMethod;-import com.google.errorprone.annotations.FormatString;--/** This exception is thrown when a built-in IdP resource is not found. */-public class NotFoundException extends RuntimeException {-- /**- * Constructs a new NotFoundException with the given message.- *- * @param message the detail message- * @param args the arguments to the message- */- @FormatMethod- public NotFoundException(@FormatString String message, Object... args) {- super(String.format(message, args));- }-- /**- * Constructs a new NotFoundException with the given message and cause.- *- * @param cause the cause of the exception- * @param message the detail message- * @param args the arguments to the message- */- @FormatMethod- public NotFoundException(Throwable cause, @FormatString String message, Object... args) {- super(String.format(message, args), cause);- }-}diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/model/IdpUser.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/model/IdpUser.javaindex cf5037c56f..7fc84c2ea0 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/model/IdpUser.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/model/IdpUser.java@@ -18,24 +18,43 @@*/package org.apache.gravitino.idp.model;+import com.google.common.base.Preconditions;import java.util.List;import java.util.Objects;+import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.idp.dto.IdpUserDTO;/** Built-in IdP user. */public class IdpUser {private final String name;+ private final String passwordHash;private final List<String> groupNames;/**- * Creates a built-in IdP user.+ * Creates a built-in IdP user without a password hash.** @param name The username.* @param groupNames The group names the user belongs to.*/public IdpUser(String name, List<String> groupNames) {this.name = name;+ this.passwordHash = null;+ this.groupNames = groupNames;+ }++ /**+ * Creates a built-in IdP user with a password hash loaded from storage.+ *+ * @param name The username.+ * @param passwordHash The password hash.+ * @param groupNames The group names the user belongs to.+ */+ public IdpUser(String name, String passwordHash, List<String> groupNames) {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(passwordHash), "passwordHash must not be blank");+ this.name = name;+ this.passwordHash = passwordHash;this.groupNames = groupNames;}@@ -44,6 +63,15 @@ public class IdpUser {return name;}+ /**+ * Returns the password hash when loaded from storage.+ *+ * @return The password hash, or null if not available.+ */+ public String passwordHash() {+ return passwordHash;+ }+/** Returns the group names the user belongs to. */public List<String> groupNames() {return groupNames;@@ -67,12 +95,14 @@ public class IdpUser {return false;}IdpUser that = (IdpUser) other;- return Objects.equals(name, that.name) && Objects.equals(groupNames, that.groupNames);+ return Objects.equals(name, that.name)+ && Objects.equals(passwordHash, that.passwordHash)+ && Objects.equals(groupNames, that.groupNames);}@Overridepublic int hashCode() {- return Objects.hash(name, groupNames);+ return Objects.hash(name, passwordHash, groupNames);}@Overridediff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpGroupMetaMapper.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpGroupMetaMapper.javaindex cc4a01e9f3..d33693c202 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpGroupMetaMapper.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpGroupMetaMapper.java@@ -20,6 +20,7 @@package org.apache.gravitino.idp.storage.mapper;import org.apache.gravitino.idp.storage.po.IdpGroupPO;+import org.apache.gravitino.idp.storage.po.IdpGroupWithUsersPO;import org.apache.ibatis.annotations.DeleteProvider;import org.apache.ibatis.annotations.InsertProvider;import org.apache.ibatis.annotations.Param;@@ -40,6 +41,9 @@ public interface IdpGroupMetaMapper {@SelectProvider(type = IdpGroupMetaSQLProviderFactory.class, method = "selectIdpGroup")IdpGroupPO selectIdpGroup(@Param("groupName") String groupName);+ @SelectProvider(type = IdpGroupMetaSQLProviderFactory.class, method = "selectIdpGroupWithUsers")+ IdpGroupWithUsersPO selectIdpGroupWithUsers(@Param("groupName") String groupName);+@InsertProvider(type = IdpGroupMetaSQLProviderFactory.class, method = "insertIdpGroup")void insertIdpGroup(@Param("groupMeta") IdpGroupPO groupPO);diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpGroupMetaSQLProviderFactory.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpGroupMetaSQLProviderFactory.javaindex ee52b33c36..bd8475236c 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpGroupMetaSQLProviderFactory.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpGroupMetaSQLProviderFactory.java@@ -49,6 +49,10 @@ public class IdpGroupMetaSQLProviderFactory {return currentProvider().selectIdpGroup(groupName);}+ public static String selectIdpGroupWithUsers(@Param("groupName") String groupName) {+ return currentProvider().selectIdpGroupWithUsers(groupName);+ }+public static String insertIdpGroup(@Param("groupMeta") IdpGroupPO groupPO) {return currentProvider().insertIdpGroup(groupPO);}diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpUserMetaMapper.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpUserMetaMapper.javaindex aa61b70d21..79552780d4 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpUserMetaMapper.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpUserMetaMapper.java@@ -21,6 +21,7 @@ package org.apache.gravitino.idp.storage.mapper;import java.util.List;import org.apache.gravitino.idp.storage.po.IdpUserPO;+import org.apache.gravitino.idp.storage.po.IdpUserWithGroupsPO;import org.apache.ibatis.annotations.DeleteProvider;import org.apache.ibatis.annotations.InsertProvider;import org.apache.ibatis.annotations.Param;@@ -41,6 +42,9 @@ public interface IdpUserMetaMapper {@SelectProvider(type = IdpUserMetaSQLProviderFactory.class, method = "selectIdpUser")IdpUserPO selectIdpUser(@Param("username") String username);+ @SelectProvider(type = IdpUserMetaSQLProviderFactory.class, method = "selectIdpUserWithGroups")+ IdpUserWithGroupsPO selectIdpUserWithGroups(@Param("username") String username);+@SelectProvider(type = IdpUserMetaSQLProviderFactory.class, method = "selectIdpUsersByUsernames")List<IdpUserPO> selectIdpUsersByUsernames(@Param("usernames") List<String> usernames);diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpUserMetaSQLProviderFactory.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpUserMetaSQLProviderFactory.javaindex 99cf0c3b4a..01de6df97e 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpUserMetaSQLProviderFactory.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/IdpUserMetaSQLProviderFactory.java@@ -49,6 +49,10 @@ public class IdpUserMetaSQLProviderFactory {return currentProvider().selectIdpUser(username);}+ public static String selectIdpUserWithGroups(@Param("username") String username) {+ return currentProvider().selectIdpUserWithGroups(username);+ }+public static String selectIdpUsersByUsernames(@Param("usernames") List<String> usernames) {return currentProvider().selectIdpUsersByUsernames(usernames);}diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/base/IdpGroupMetaBaseSQLProvider.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/base/IdpGroupMetaBaseSQLProvider.javaindex 878aa44f1c..46cf1e54ed 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/base/IdpGroupMetaBaseSQLProvider.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/base/IdpGroupMetaBaseSQLProvider.java@@ -20,6 +20,8 @@package org.apache.gravitino.idp.storage.mapper.provider.base;import org.apache.gravitino.idp.storage.mapper.IdpGroupMetaMapper;+import org.apache.gravitino.idp.storage.mapper.IdpUserGroupRelMapper;+import org.apache.gravitino.idp.storage.mapper.IdpUserMetaMapper;import org.apache.gravitino.idp.storage.po.IdpGroupPO;import org.apache.ibatis.annotations.Param;@@ -34,6 +36,21 @@ public class IdpGroupMetaBaseSQLProvider {+ " WHERE group_name = #{groupName} AND deleted_at = 0";}+ public String selectIdpGroupWithUsers(@Param("groupName") String groupName) {+ return "SELECT g.group_name as name,"+ + " COALESCE(JSON_ARRAYAGG(u.user_name), JSON_ARRAY()) as usernames"+ + " FROM "+ + IdpGroupMetaMapper.IDP_GROUP_TABLE_NAME+ + " g LEFT JOIN "+ + IdpUserGroupRelMapper.IDP_USER_GROUP_REL_TABLE_NAME+ + " r ON r.group_id = g.group_id AND r.deleted_at = 0"+ + " LEFT JOIN "+ + IdpUserMetaMapper.IDP_USER_TABLE_NAME+ + " u ON u.user_id = r.user_id AND u.deleted_at = 0"+ + " WHERE g.group_name = #{groupName} AND g.deleted_at = 0"+ + " GROUP BY g.group_id, g.group_name";+ }+public String insertIdpGroup(@Param("groupMeta") IdpGroupPO groupPO) {return "INSERT INTO "+ IdpGroupMetaMapper.IDP_GROUP_TABLE_NAMEdiff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/base/IdpUserMetaBaseSQLProvider.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/base/IdpUserMetaBaseSQLProvider.javaindex f194d66663..255baa518b 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/base/IdpUserMetaBaseSQLProvider.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/base/IdpUserMetaBaseSQLProvider.java@@ -20,6 +20,8 @@package org.apache.gravitino.idp.storage.mapper.provider.base;import java.util.List;+import org.apache.gravitino.idp.storage.mapper.IdpGroupMetaMapper;+import org.apache.gravitino.idp.storage.mapper.IdpUserGroupRelMapper;import org.apache.gravitino.idp.storage.mapper.IdpUserMetaMapper;import org.apache.gravitino.idp.storage.po.IdpUserPO;import org.apache.ibatis.annotations.Param;@@ -34,6 +36,21 @@ public class IdpUserMetaBaseSQLProvider {+ " WHERE user_name = #{username} AND deleted_at = 0";}+ public String selectIdpUserWithGroups(@Param("username") String username) {+ return "SELECT u.user_name as name, u.password_hash as passwordHash,"+ + " COALESCE(JSON_ARRAYAGG(g.group_name), JSON_ARRAY()) as groupNames"+ + " FROM "+ + IdpUserMetaMapper.IDP_USER_TABLE_NAME+ + " u LEFT JOIN "+ + IdpUserGroupRelMapper.IDP_USER_GROUP_REL_TABLE_NAME+ + " r ON r.user_id = u.user_id AND r.deleted_at = 0"+ + " LEFT JOIN "+ + IdpGroupMetaMapper.IDP_GROUP_TABLE_NAME+ + " g ON g.group_id = r.group_id AND g.deleted_at = 0"+ + " WHERE u.user_name = #{username} AND u.deleted_at = 0"+ + " GROUP BY u.user_id, u.user_name, u.password_hash";+ }+public String selectIdpUsersByUsernames(@Param("usernames") List<String> usernames) {return "<script>"+ "SELECT user_id as userId, user_name as username, password_hash as passwordHash,"diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/h2/IdpGroupMetaH2Provider.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/h2/IdpGroupMetaH2Provider.javaindex b87e0bee38..e15542f518 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/h2/IdpGroupMetaH2Provider.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/h2/IdpGroupMetaH2Provider.java@@ -19,11 +19,33 @@package org.apache.gravitino.idp.storage.mapper.provider.h2;+import org.apache.gravitino.idp.storage.mapper.IdpGroupMetaMapper;+import org.apache.gravitino.idp.storage.mapper.IdpUserGroupRelMapper;+import org.apache.gravitino.idp.storage.mapper.IdpUserMetaMapper;import org.apache.gravitino.idp.storage.mapper.provider.base.IdpGroupMetaBaseSQLProvider;+import org.apache.ibatis.annotations.Param;/** SQL provider for IdP group metadata statements on H2 backends. */public class IdpGroupMetaH2Provider extends IdpGroupMetaBaseSQLProvider {+ @Override+ public String selectIdpGroupWithUsers(@Param("groupName") String groupName) {+ return "SELECT g.group_name as name,"+ + " '['"+ + " || COALESCE(GROUP_CONCAT('\"' || u.user_name || '\"'), '')"+ + " || ']' as usernames"+ + " FROM "+ + IdpGroupMetaMapper.IDP_GROUP_TABLE_NAME+ + " g LEFT JOIN "+ + IdpUserGroupRelMapper.IDP_USER_GROUP_REL_TABLE_NAME+ + " r ON r.group_id = g.group_id AND r.deleted_at = 0"+ + " LEFT JOIN "+ + IdpUserMetaMapper.IDP_USER_TABLE_NAME+ + " u ON u.user_id = r.user_id AND u.deleted_at = 0"+ + " WHERE g.group_name = #{groupName} AND g.deleted_at = 0"+ + " GROUP BY g.group_id, g.group_name";+ }+@Overrideprotected String currentTimeMillisExpression() {return "DATEDIFF('MILLISECOND', TIMESTAMP '1970-01-01 00:00:00', CURRENT_TIMESTAMP())";diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/h2/IdpUserMetaH2Provider.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/h2/IdpUserMetaH2Provider.javaindex 8731a3354d..36b00a074a 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/h2/IdpUserMetaH2Provider.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/h2/IdpUserMetaH2Provider.java@@ -19,11 +19,33 @@package org.apache.gravitino.idp.storage.mapper.provider.h2;+import org.apache.gravitino.idp.storage.mapper.IdpGroupMetaMapper;+import org.apache.gravitino.idp.storage.mapper.IdpUserGroupRelMapper;+import org.apache.gravitino.idp.storage.mapper.IdpUserMetaMapper;import org.apache.gravitino.idp.storage.mapper.provider.base.IdpUserMetaBaseSQLProvider;+import org.apache.ibatis.annotations.Param;/** SQL provider for IdP user metadata statements on H2 backends. */public class IdpUserMetaH2Provider extends IdpUserMetaBaseSQLProvider {+ @Override+ public String selectIdpUserWithGroups(@Param("username") String username) {+ return "SELECT u.user_name as name, u.password_hash as passwordHash,"+ + " '['"+ + " || COALESCE(GROUP_CONCAT('\"' || g.group_name || '\"'), '')"+ + " || ']' as groupNames"+ + " FROM "+ + IdpUserMetaMapper.IDP_USER_TABLE_NAME+ + " u LEFT JOIN "+ + IdpUserGroupRelMapper.IDP_USER_GROUP_REL_TABLE_NAME+ + " r ON r.user_id = u.user_id AND r.deleted_at = 0"+ + " LEFT JOIN "+ + IdpGroupMetaMapper.IDP_GROUP_TABLE_NAME+ + " g ON g.group_id = r.group_id AND g.deleted_at = 0"+ + " WHERE u.user_name = #{username} AND u.deleted_at = 0"+ + " GROUP BY u.user_id, u.user_name, u.password_hash";+ }+@Overrideprotected String currentTimeMillisExpression() {return "DATEDIFF('MILLISECOND', TIMESTAMP '1970-01-01 00:00:00', CURRENT_TIMESTAMP())";diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/postgresql/IdpGroupMetaPostgreSQLProvider.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/postgresql/IdpGroupMetaPostgreSQLProvider.javaindex 3bed7f059d..28e0869367 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/postgresql/IdpGroupMetaPostgreSQLProvider.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/postgresql/IdpGroupMetaPostgreSQLProvider.java@@ -20,11 +20,29 @@package org.apache.gravitino.idp.storage.mapper.provider.postgresql;import org.apache.gravitino.idp.storage.mapper.IdpGroupMetaMapper;+import org.apache.gravitino.idp.storage.mapper.IdpUserGroupRelMapper;+import org.apache.gravitino.idp.storage.mapper.IdpUserMetaMapper;import org.apache.gravitino.idp.storage.mapper.provider.base.IdpGroupMetaBaseSQLProvider;import org.apache.ibatis.annotations.Param;public class IdpGroupMetaPostgreSQLProvider extends IdpGroupMetaBaseSQLProvider {+ @Override+ public String selectIdpGroupWithUsers(@Param("groupName") String groupName) {+ return "SELECT g.group_name as name,"+ + " COALESCE(JSON_AGG(u.user_name), '[]'::json) as usernames"+ + " FROM "+ + IdpGroupMetaMapper.IDP_GROUP_TABLE_NAME+ + " g LEFT JOIN "+ + IdpUserGroupRelMapper.IDP_USER_GROUP_REL_TABLE_NAME+ + " r ON r.group_id = g.group_id AND r.deleted_at = 0"+ + " LEFT JOIN "+ + IdpUserMetaMapper.IDP_USER_TABLE_NAME+ + " u ON u.user_id = r.user_id AND u.deleted_at = 0"+ + " WHERE g.group_name = #{groupName} AND g.deleted_at = 0"+ + " GROUP BY g.group_id, g.group_name";+ }+@Overridepublic String deleteIdpGroupMetasByLegacyTimeline(@Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/postgresql/IdpUserMetaPostgreSQLProvider.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/postgresql/IdpUserMetaPostgreSQLProvider.javaindex 9993b2e041..b9cebbfb56 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/postgresql/IdpUserMetaPostgreSQLProvider.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/mapper/provider/postgresql/IdpUserMetaPostgreSQLProvider.java@@ -19,12 +19,30 @@package org.apache.gravitino.idp.storage.mapper.provider.postgresql;+import org.apache.gravitino.idp.storage.mapper.IdpGroupMetaMapper;+import org.apache.gravitino.idp.storage.mapper.IdpUserGroupRelMapper;import org.apache.gravitino.idp.storage.mapper.IdpUserMetaMapper;import org.apache.gravitino.idp.storage.mapper.provider.base.IdpUserMetaBaseSQLProvider;import org.apache.ibatis.annotations.Param;public class IdpUserMetaPostgreSQLProvider extends IdpUserMetaBaseSQLProvider {+ @Override+ public String selectIdpUserWithGroups(@Param("username") String username) {+ return "SELECT u.user_name as name, u.password_hash as passwordHash,"+ + " COALESCE(JSON_AGG(g.group_name), '[]'::json) as groupNames"+ + " FROM "+ + IdpUserMetaMapper.IDP_USER_TABLE_NAME+ + " u LEFT JOIN "+ + IdpUserGroupRelMapper.IDP_USER_GROUP_REL_TABLE_NAME+ + " r ON r.user_id = u.user_id AND r.deleted_at = 0"+ + " LEFT JOIN "+ + IdpGroupMetaMapper.IDP_GROUP_TABLE_NAME+ + " g ON g.group_id = r.group_id AND g.deleted_at = 0"+ + " WHERE u.user_name = #{username} AND u.deleted_at = 0"+ + " GROUP BY u.user_id, u.user_name, u.password_hash";+ }+@Overridepublic String deleteIdpUserMetasByLegacyTimeline(@Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {diff --git a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/web/rest/feature/TestIdpRESTFeature.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/po/IdpGroupWithUsersPO.javasimilarity index 56%rename from plugins/idp-basic/src/test/java/org/apache/gravitino/idp/web/rest/feature/TestIdpRESTFeature.javarename to plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/po/IdpGroupWithUsersPO.javaindex b9ca933e72..d971ae1773 100644--- a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/web/rest/feature/TestIdpRESTFeature.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/po/IdpGroupWithUsersPO.java@@ -16,22 +16,27 @@* specific language governing permissions and limitations* under the License.*/-package org.apache.gravitino.idp.web.rest.feature;+package org.apache.gravitino.idp.storage.po;-import static org.junit.jupiter.api.Assertions.assertFalse;-import static org.junit.jupiter.api.Assertions.assertTrue;+import lombok.AccessLevel;+import lombok.AllArgsConstructor;+import lombok.Builder;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.NoArgsConstructor;+import lombok.ToString;-import java.util.List;-import org.junit.jupiter.api.Test;--class TestIdpRESTFeature {-- @Test- void testBasicAuthenticatorEnabled() {- assertFalse(IdpRESTFeature.basicAuthenticatorEnabled(null));- assertFalse(IdpRESTFeature.basicAuthenticatorEnabled(List.of("simple")));- assertTrue(- IdpRESTFeature.basicAuthenticatorEnabled(- List.of("simple", IdpRESTFeature.BASIC_AUTHENTICATOR)));- }+/**+ * Read-only PO for built-in IdP group rows joined with aggregated usernames. This PO is not written+ * to the database.+ */+@Getter+@EqualsAndHashCode+@ToString+@NoArgsConstructor(access = AccessLevel.PRIVATE)+@AllArgsConstructor(access = AccessLevel.PRIVATE)+@Builder(setterPrefix = "with")+public class IdpGroupWithUsersPO {+ private String name;+ private String usernames;}diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/po/IdpUserWithGroupsPO.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/po/IdpUserWithGroupsPO.javanew file mode 100644index 0000000000..4938d780a7--- /dev/null+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/po/IdpUserWithGroupsPO.java@@ -0,0 +1,43 @@+/*+ * 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.idp.storage.po;++import lombok.AccessLevel;+import lombok.AllArgsConstructor;+import lombok.Builder;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.NoArgsConstructor;+import lombok.ToString;++/**+ * Read-only PO for built-in IdP user rows joined with aggregated group names. This PO is not+ * written to the database.+ */+@Getter+@EqualsAndHashCode+@ToString+@NoArgsConstructor(access = AccessLevel.PRIVATE)+@AllArgsConstructor(access = AccessLevel.PRIVATE)+@Builder(setterPrefix = "with")+public class IdpUserWithGroupsPO {+ private String name;+ private String passwordHash;+ private String groupNames;+}diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/relational/converters/IdpSQLExceptionConverter.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/relational/converters/IdpSQLExceptionConverter.javaindex 89721f0eab..06c76a7c9f 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/relational/converters/IdpSQLExceptionConverter.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/relational/converters/IdpSQLExceptionConverter.java@@ -20,7 +20,7 @@ package org.apache.gravitino.idp.storage.relational.converters;import java.io.IOException;import java.sql.SQLException;-import org.apache.gravitino.idp.exception.AlreadyExistsException;+import org.apache.gravitino.exceptions.AlreadyExistsException;/** Converts JDBC SQL exceptions to built-in IdP exceptions. */public final class IdpSQLExceptionConverter {diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/relational/utils/IdpPOConverters.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/relational/utils/IdpPOConverters.javanew file mode 100644index 0000000000..41dbe3bfcc--- /dev/null+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/relational/utils/IdpPOConverters.java@@ -0,0 +1,74 @@+/*+ * 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.idp.storage.relational.utils;++import com.google.common.base.Preconditions;+import java.util.Collections;+import java.util.List;+import java.util.stream.Collectors;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.idp.model.IdpGroup;+import org.apache.gravitino.idp.model.IdpUser;+import org.apache.gravitino.idp.storage.po.IdpGroupWithUsersPO;+import org.apache.gravitino.idp.storage.po.IdpUserWithGroupsPO;+import org.apache.gravitino.json.JsonUtils;++/** Converts built-in IdP persistence objects to domain models. */+public final class IdpPOConverters {+ private IdpPOConverters() {}++ /**+ * Converts a joined user row to a built-in IdP user.+ *+ * @param userPO The joined user row.+ * @return The built-in IdP user.+ */+ public static IdpUser fromIdpUserWithGroupsPO(IdpUserWithGroupsPO userPO) {+ Preconditions.checkNotNull(userPO, "userPO must not be null");+ List<String> groupNames = parseJsonStringList(userPO.getGroupNames());+ if (StringUtils.isBlank(userPO.getPasswordHash())) {+ return new IdpUser(userPO.getName(), groupNames);+ }+ return new IdpUser(userPO.getName(), userPO.getPasswordHash(), groupNames);+ }++ /**+ * Converts a joined group row to a built-in IdP group.+ *+ * @param groupPO The joined group row.+ * @return The built-in IdP group.+ */+ public static IdpGroup fromIdpGroupWithUsersPO(IdpGroupWithUsersPO groupPO) {+ Preconditions.checkNotNull(groupPO, "groupPO must not be null");+ return new IdpGroup(groupPO.getName(), parseJsonStringList(groupPO.getUsernames()));+ }++ @SuppressWarnings("unchecked")+ private static List<String> parseJsonStringList(String json) {+ if (StringUtils.isBlank(json)) {+ return Collections.emptyList();+ }+ try {+ List<String> values = JsonUtils.anyFieldMapper().readValue(json, List.class);+ return values.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());+ } catch (Exception e) {+ throw new RuntimeException("Failed to parse built-in IdP JSON string list", e);+ }+ }+}diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/service/IdpGroupMetaService.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/service/IdpGroupMetaService.javaindex 93394b8475..c4bfdd3601 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/service/IdpGroupMetaService.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/service/IdpGroupMetaService.java@@ -27,12 +27,15 @@ import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Set;-import org.apache.gravitino.idp.exception.NotFoundException;+import org.apache.gravitino.exceptions.NotFoundException;+import org.apache.gravitino.idp.model.IdpGroup;import org.apache.gravitino.idp.storage.mapper.IdpGroupMetaMapper;import org.apache.gravitino.idp.storage.mapper.IdpUserGroupRelMapper;import org.apache.gravitino.idp.storage.po.IdpGroupPO;+import org.apache.gravitino.idp.storage.po.IdpGroupWithUsersPO;import org.apache.gravitino.idp.storage.po.IdpUserGroupRelPO;import org.apache.gravitino.idp.storage.relational.utils.IdpExceptionUtils;+import org.apache.gravitino.idp.storage.relational.utils.IdpPOConverters;import org.apache.gravitino.metrics.Monitored;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.utils.SessionUtils;@@ -63,6 +66,17 @@ public class IdpGroupMetaService {return groupPO;}+ @Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME, baseMetricName = "getIdpGroup")+ public IdpGroup getIdpGroup(String groupName) {+ IdpGroupWithUsersPO groupWithUsers =+ SessionUtils.getWithoutCommit(+ IdpGroupMetaMapper.class, mapper -> mapper.selectIdpGroupWithUsers(groupName));+ if (groupWithUsers == null) {+ throw new NotFoundException("IdP group not found: %s", groupName);+ }+ return IdpPOConverters.fromIdpGroupWithUsersPO(groupWithUsers);+ }+@Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,baseMetricName = "listUsernamesByGroupName")diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/service/IdpUserMetaService.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/service/IdpUserMetaService.javaindex c3d3205bd2..78a42e1b15 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/service/IdpUserMetaService.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/storage/service/IdpUserMetaService.java@@ -24,11 +24,14 @@ import java.io.IOException;import java.util.HashMap;import java.util.List;import java.util.Map;-import org.apache.gravitino.idp.exception.NotFoundException;+import org.apache.gravitino.exceptions.NotFoundException;+import org.apache.gravitino.idp.model.IdpUser;import org.apache.gravitino.idp.storage.mapper.IdpUserGroupRelMapper;import org.apache.gravitino.idp.storage.mapper.IdpUserMetaMapper;import org.apache.gravitino.idp.storage.po.IdpUserPO;+import org.apache.gravitino.idp.storage.po.IdpUserWithGroupsPO;import org.apache.gravitino.idp.storage.relational.utils.IdpExceptionUtils;+import org.apache.gravitino.idp.storage.relational.utils.IdpPOConverters;import org.apache.gravitino.metrics.Monitored;import org.apache.gravitino.storage.relational.utils.SessionUtils;@@ -58,6 +61,17 @@ public class IdpUserMetaService {return userPO;}+ @Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME, baseMetricName = "getIdpUser")+ public IdpUser getIdpUser(String username) {+ IdpUserWithGroupsPO userWithGroups =+ SessionUtils.getWithoutCommit(+ IdpUserMetaMapper.class, mapper -> mapper.selectIdpUserWithGroups(username));+ if (userWithGroups == null) {+ throw new NotFoundException("IdP user not found: %s", username);+ }+ return IdpPOConverters.fromIdpUserWithGroupsPO(userWithGroups);+ }+@Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,baseMetricName = "listGroupNamesByUsername")diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/web/IdpRESTUtils.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/web/IdpRESTUtils.javaindex ea9c44e8f8..047f490be8 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/web/IdpRESTUtils.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/web/IdpRESTUtils.java@@ -26,8 +26,8 @@ import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.UserPrincipal;import org.apache.gravitino.auth.AuthConstants;import org.apache.gravitino.dto.responses.ErrorResponse;-import org.apache.gravitino.idp.exception.AlreadyExistsException;-import org.apache.gravitino.idp.exception.NotFoundException;+import org.apache.gravitino.exceptions.AlreadyExistsException;+import org.apache.gravitino.exceptions.NotFoundException;import org.apache.gravitino.utils.PrincipalUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/web/rest/IdpBasicBinder.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/web/rest/IdpBasicBinder.javaindex f9722c76f7..ef34e210ce 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/web/rest/IdpBasicBinder.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/web/rest/IdpBasicBinder.java@@ -28,7 +28,7 @@ public class IdpBasicBinder extends AbstractBinder {@Overrideprotected void configure() {GravitinoEnv gravitinoEnv = GravitinoEnv.getInstance();- bind(new IdpUserGroupManager(gravitinoEnv.config(), gravitinoEnv.idGenerator()))+ bind(IdpUserGroupManager.getInstance(gravitinoEnv.config(), gravitinoEnv.idGenerator())).to(IdpUserGroupManager.class);}}diff --git a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/web/rest/feature/IdpRESTFeature.java b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/web/rest/feature/IdpRESTFeature.javaindex 129a771527..939c4d8406 100644--- a/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/web/rest/feature/IdpRESTFeature.java+++ b/plugins/idp-basic/src/main/java/org/apache/gravitino/idp/web/rest/feature/IdpRESTFeature.java@@ -18,37 +18,55 @@*/package org.apache.gravitino.idp.web.rest.feature;+import java.io.IOException;import java.util.List;import javax.ws.rs.core.Feature;import javax.ws.rs.core.FeatureContext;import javax.ws.rs.ext.Provider;+import org.apache.gravitino.Config;import org.apache.gravitino.Configs;import org.apache.gravitino.GravitinoEnv;+import org.apache.gravitino.idp.IdpUserGroupManager;+import org.apache.gravitino.idp.auth.BasicAuthenticator;import org.apache.gravitino.idp.web.rest.IdpAuthorizationFilter;import org.apache.gravitino.idp.web.rest.IdpBasicBinder;import org.apache.gravitino.idp.web.rest.IdpGroupOperations;import org.apache.gravitino.idp.web.rest.IdpUserOperations;+import org.apache.gravitino.server.authentication.Authenticator;+import org.apache.gravitino.server.authentication.ServerAuthenticator;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;/**- * Conditionally registers built-in IdP REST resources when {@code basic} is configured in {@link- * Configs#AUTHENTICATORS}.+ * Registers built-in IdP REST resources for the idp-basic plugin.** <p>Configure {@link Configs#REST_API_EXTENSION_PACKAGES} to {@code- * org.apache.gravitino.idp.web.rest.feature} so Jersey only auto-discovers this feature. IdP REST- * resource classes remain in {@code org.apache.gravitino.idp.web.rest} and are registered here only- * when the {@code basic} authenticator is enabled.+ * org.apache.gravitino.idp.web.rest.feature} so Jersey auto-discovers this feature. IdP REST+ * resource classes remain in {@code org.apache.gravitino.idp.web.rest} and are registered here.+ * Also initializes configured service admins in the built-in IdP when they do not yet exist.*/@Providerpublic class IdpRESTFeature implements Feature {- /** Authenticator name that enables built-in IdP management APIs. */- public static final String BASIC_AUTHENTICATOR = "basic";+ private static final Logger LOG = LoggerFactory.getLogger(IdpRESTFeature.class);++ public static final String IDP_REST_EXTENSION_PACKAGE = IdpRESTFeature.class.getPackageName();++ /** Environment variable for the initial password of configured service admins. */+ public static final String INITIAL_ADMIN_PASSWORD_ENV = "GRAVITINO_INITIAL_ADMIN_PASSWORD";@Overridepublic boolean configure(FeatureContext context) {- if (!basicAuthenticatorEnabled(- GravitinoEnv.getInstance().config().get(Configs.AUTHENTICATORS))) {- return true;+ GravitinoEnv env = GravitinoEnv.getInstance();+ Config config = env.config();+ registerBasicAuthenticator(config);++ try {+ IdpUserGroupManager manager = IdpUserGroupManager.getInstance(config, env.idGenerator());+ manager.initializeConfiguredServiceAdmins(config, System.getenv(INITIAL_ADMIN_PASSWORD_ENV));+ LOG.info("Initialized built-in IdP service admins");+ } catch (IOException e) {+ throw new IllegalStateException("Failed to initialize built-in IdP service admins", e);}context.register(IdpBasicBinder.class);@@ -58,13 +76,18 @@ public class IdpRESTFeature implements Feature {return true;}- /**- * Returns whether built-in IdP management REST APIs should be registered.- *- * @param authenticators configured authenticator names- * @return {@code true} when {@code basic} is included in {@code authenticators}- */- public static boolean basicAuthenticatorEnabled(List<String> authenticators) {- return authenticators != null && authenticators.contains(BASIC_AUTHENTICATOR);+ private static void registerBasicAuthenticator(Config config) {+ List<Authenticator> authenticators = ServerAuthenticator.getInstance().authenticators();+ if (authenticators == null) {+ return;+ }+ for (Authenticator authenticator : authenticators) {+ if (authenticator instanceof BasicAuthenticator) {+ return;+ }+ }+ BasicAuthenticator basicAuthenticator = new BasicAuthenticator();+ basicAuthenticator.initialize(config);+ authenticators.add(0, basicAuthenticator);}}diff --git a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/IdpUserGroupManagerTestHelper.java b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/IdpUserGroupManagerTestHelper.javanew file mode 100644index 0000000000..7567e3ceae--- /dev/null+++ b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/IdpUserGroupManagerTestHelper.java@@ -0,0 +1,44 @@+/*+ * 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.idp;++import java.lang.reflect.Constructor;+import org.apache.gravitino.Config;+import org.apache.gravitino.storage.IdGenerator;++/** Test-only helpers for {@link IdpUserGroupManager}. */+public final class IdpUserGroupManagerTestHelper {++ private IdpUserGroupManagerTestHelper() {}++ /**+ * Creates an isolated manager instance without using the process-wide singleton.+ *+ * @param config The server configuration.+ * @param idGenerator The id generator.+ * @return A new manager instance.+ */+ public static IdpUserGroupManager newManager(Config config, IdGenerator idGenerator)+ throws ReflectiveOperationException {+ Constructor<IdpUserGroupManager> constructor =+ IdpUserGroupManager.class.getDeclaredConstructor(Config.class, IdGenerator.class);+ constructor.setAccessible(true);+ return constructor.newInstance(config, idGenerator);+ }+}diff --git a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/TestIdpUserGroupManager.java b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/TestIdpUserGroupManager.javaindex 9bc0d26a57..b18972c597 100644--- a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/TestIdpUserGroupManager.java+++ b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/TestIdpUserGroupManager.java@@ -18,6 +18,7 @@*/package org.apache.gravitino.idp;+import static org.apache.gravitino.Configs.AUTHENTICATORS;import static org.apache.gravitino.Configs.CACHE_ENABLED;import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;@@ -26,8 +27,10 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_Mimport static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;import static org.apache.gravitino.Configs.ENTITY_STORE;import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;+import static org.apache.gravitino.Configs.SERVICE_ADMINS;import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;+import com.google.common.collect.ImmutableMap;import com.google.common.collect.Lists;import java.io.IOException;import java.nio.file.Files;@@ -35,9 +38,10 @@ import java.nio.file.Path;import java.util.Comparator;import java.util.stream.Stream;import org.apache.gravitino.Config;+import org.apache.gravitino.exceptions.AlreadyExistsException;+import org.apache.gravitino.exceptions.NotFoundException;+import org.apache.gravitino.idp.auth.BasicAuthenticator;import org.apache.gravitino.idp.basic.IdpCredentialValidator;-import org.apache.gravitino.idp.exception.AlreadyExistsException;-import org.apache.gravitino.idp.exception.NotFoundException;import org.apache.gravitino.idp.model.IdpGroup;import org.apache.gravitino.idp.model.IdpUser;import org.apache.gravitino.storage.RandomIdGenerator;@@ -45,10 +49,15 @@ import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;/** Integration tests for {@link IdpUserGroupManager} backed by an embedded H2 store. */public class TestIdpUserGroupManager {+ private static final String BASIC_AUTHENTICATOR_CLASS =+ BasicAuthenticator.class.getCanonicalName();+private static final String VALID_PASSWORD = "Passw0rd-1234";private static final String ANOTHER_VALID_PASSWORD = "AnotherPass1!";private static final String NEW_VALID_PASSWORD = "New-Password1!";@@ -60,25 +69,14 @@ public class TestIdpUserGroupManager {}private static IdpUserGroupManager manager;+ private static Config config;private static Path h2Path;@BeforeAllpublic static void setUp() throws Exception {h2Path = Files.createTempDirectory("gravitino_idp_manager_h2_");-- Config config = new Config(false) {};- config.set(ENTITY_STORE, RELATIONAL_ENTITY_STORE);- config.set(ENTITY_RELATIONAL_STORE, "h2");- config.set(- ENTITY_RELATIONAL_JDBC_BACKEND_URL,- String.format("jdbc:h2:file:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL", h2Path));- config.set(ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER, "org.h2.Driver");- config.set(ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS, 100);- config.set(ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_MILLISECONDS, 1000L);- config.set(STORE_DELETE_AFTER_TIME, 20 * 60 * 1000L);- config.set(CACHE_ENABLED, false);-- manager = new IdpUserGroupManager(config, RandomIdGenerator.INSTANCE);+ config = createH2Config(h2Path);+ manager = IdpUserGroupManagerTestHelper.newManager(config, RandomIdGenerator.INSTANCE);}@AfterAll@@ -208,6 +206,103 @@ public class TestIdpUserGroupManager {Assertions.assertTrue(manager.removeGroup("testForceRemoveGroup", true));}+ @Test+ public void testInitializeConfiguredServiceAdminsCreatesMissingServiceAdmin() throws IOException {+ loadServiceAdminConfig(BASIC_AUTHENTICATOR_CLASS, "initAdminCreate1,initAdminCreate2");+ manager.addUser("initAdminCreate2", VALID_PASSWORD);++ manager.initializeConfiguredServiceAdmins(config, VALID_PASSWORD);++ Assertions.assertEquals("initAdminCreate1", manager.getUser("initAdminCreate1").name());+ Assertions.assertEquals("initAdminCreate2", manager.getUser("initAdminCreate2").name());+ }++ @Test+ public void testInitializeConfiguredServiceAdminsSkipsWhenNoServiceAdminsConfigured()+ throws IOException {+ loadServiceAdminConfig(BASIC_AUTHENTICATOR_CLASS, "");+ manager.initializeConfiguredServiceAdmins(config, VALID_PASSWORD);+ Assertions.assertThrows(NotFoundException.class, () -> manager.getUser("initAdminSkipList1"));+ }++ @Test+ public void testInitializeConfiguredServiceAdminsSkipsWhenAllServiceAdminsAlreadyExist()+ throws IOException {+ loadServiceAdminConfig(BASIC_AUTHENTICATOR_CLASS, "initAdminExist1,initAdminExist2");+ manager.addUser("initAdminExist1", VALID_PASSWORD);+ manager.addUser("initAdminExist2", VALID_PASSWORD);++ manager.initializeConfiguredServiceAdmins(config, "");++ Assertions.assertEquals("initAdminExist1", manager.getUser("initAdminExist1").name());+ Assertions.assertEquals("initAdminExist2", manager.getUser("initAdminExist2").name());+ }++ @Test+ public void testInitializeConfiguredServiceAdminsFailsWhenRequiredPasswordMissing() {+ loadServiceAdminConfig(BASIC_AUTHENTICATOR_CLASS, "initAdminNoPwd1");++ IllegalArgumentException exception =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> manager.initializeConfiguredServiceAdmins(config, ""));++ Assertions.assertEquals(+ "Missing initial password for configured service admin initAdminNoPwd1; declare"+ + " GRAVITINO_INITIAL_ADMIN_PASSWORD",+ exception.getMessage());+ }++ @ParameterizedTest+ @ValueSource(strings = {"short"})+ public void testInitializeConfiguredServiceAdminsFailsOnInvalidPasswordPayload(String payload) {+ loadServiceAdminConfig(BASIC_AUTHENTICATOR_CLASS, "initAdminBadPwd1");++ IllegalArgumentException exception =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> manager.initializeConfiguredServiceAdmins(config, payload));++ Assertions.assertEquals(+ "Password must be at least 12 characters long and at most 64 characters long",+ exception.getMessage());+ }++ @Test+ public void testInitializeConfiguredServiceAdminsUsesSamePasswordForAllMissingServiceAdmins()+ throws IOException {+ loadServiceAdminConfig(BASIC_AUTHENTICATOR_CLASS, "initAdminSame1,initAdminSame2");++ manager.initializeConfiguredServiceAdmins(config, VALID_PASSWORD);++ Assertions.assertEquals(+ "initAdminSame1", manager.authenticate("initAdminSame1", VALID_PASSWORD).name());+ Assertions.assertEquals(+ "initAdminSame2", manager.authenticate("initAdminSame2", VALID_PASSWORD).name());+ }++ private static Config createH2Config(Path h2Path) {+ Config backendConfig = new Config(false) {};+ backendConfig.set(ENTITY_STORE, RELATIONAL_ENTITY_STORE);+ backendConfig.set(ENTITY_RELATIONAL_STORE, "h2");+ backendConfig.set(+ ENTITY_RELATIONAL_JDBC_BACKEND_URL,+ String.format("jdbc:h2:file:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL", h2Path));+ backendConfig.set(ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER, "org.h2.Driver");+ backendConfig.set(ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS, 100);+ backendConfig.set(ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_MILLISECONDS, 1000L);+ backendConfig.set(STORE_DELETE_AFTER_TIME, 20 * 60 * 1000L);+ backendConfig.set(CACHE_ENABLED, false);+ return backendConfig;+ }++ private static void loadServiceAdminConfig(String authenticators, String serviceAdmins) {+ config.loadFromMap(+ ImmutableMap.of(+ AUTHENTICATORS.getKey(), authenticators, SERVICE_ADMINS.getKey(), serviceAdmins),+ t -> true);+ }+private static void deletePath(Path path) {try {Files.deleteIfExists(path);diff --git a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/auth/TestBasicAuthenticationIntegration.java b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/auth/TestBasicAuthenticationIntegration.javanew file mode 100644index 0000000000..c72535d757--- /dev/null+++ b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/auth/TestBasicAuthenticationIntegration.java@@ -0,0 +1,142 @@+/*+ * 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.idp.auth;++import static org.apache.gravitino.Configs.CACHE_ENABLED;+import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;+import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;+import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL;+import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_MILLISECONDS;+import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;+import static org.apache.gravitino.Configs.ENTITY_STORE;+import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;+import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;++import java.io.IOException;+import java.lang.reflect.Field;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.Base64;+import java.util.Comparator;+import java.util.stream.Stream;+import org.apache.gravitino.Config;+import org.apache.gravitino.UserPrincipal;+import org.apache.gravitino.auth.AuthConstants;+import org.apache.gravitino.exceptions.UnauthorizedException;+import org.apache.gravitino.idp.IdpUserGroupManager;+import org.apache.gravitino.idp.IdpUserGroupManagerTestHelper;+import org.apache.gravitino.storage.RandomIdGenerator;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++/** Integration tests for {@link BasicAuthenticator} backed by an embedded H2 store. */+class TestBasicAuthenticationIntegration {++ private static final String USER = "alice";+ private static final String PASSWORD = "Passw0rd-For-Alice";++ private static Config config;+ private static Path h2Path;+ private static IdpUserGroupManager userGroupManager;+ private static BasicAuthenticator authenticator;++ @BeforeAll+ static void setUp() throws Exception {+ h2Path = Files.createTempDirectory("gravitino_basic_auth_it_");+ config = new Config(false) {};+ config.set(ENTITY_STORE, RELATIONAL_ENTITY_STORE);+ config.set(ENTITY_RELATIONAL_STORE, "h2");+ config.set(+ ENTITY_RELATIONAL_JDBC_BACKEND_URL,+ String.format("jdbc:h2:file:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL", h2Path));+ config.set(ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER, "org.h2.Driver");+ config.set(ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS, 100);+ config.set(ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_MILLISECONDS, 1000L);+ config.set(STORE_DELETE_AFTER_TIME, 20 * 60 * 1000L);+ config.set(CACHE_ENABLED, false);++ userGroupManager = IdpUserGroupManagerTestHelper.newManager(config, RandomIdGenerator.INSTANCE);+ userGroupManager.addUser(USER, PASSWORD);++ authenticator = new BasicAuthenticator();+ Field userGroupManagerField = BasicAuthenticator.class.getDeclaredField("userGroupManager");+ userGroupManagerField.setAccessible(true);+ userGroupManagerField.set(authenticator, userGroupManager);+ }++ @AfterAll+ static void tearDown() throws IOException {+ authenticator = null;+ if (userGroupManager != null) {+ userGroupManager.close();+ userGroupManager = null;+ }+ if (h2Path != null && Files.exists(h2Path)) {+ try (Stream<Path> paths = Files.walk(h2Path)) {+ paths+ .sorted(Comparator.reverseOrder())+ .forEach(TestBasicAuthenticationIntegration::deletePath);+ }+ }+ }++ @Test+ void testAuthenticateToken() {+ UserPrincipal principal =+ (UserPrincipal)+ authenticator.authenticateToken(basicAuthBytes(basicAuthHeader(USER, PASSWORD)));++ assertEquals(USER, principal.getName());+ }++ @Test+ void testInvalidPassword() {+ UnauthorizedException exception =+ assertThrows(+ UnauthorizedException.class,+ () ->+ authenticator.authenticateToken(+ basicAuthBytes(basicAuthHeader(USER, "wrong-password"))));++ assertEquals("Invalid username or password", exception.getMessage());+ }++ private static String basicAuthHeader(String username, String password) {+ return AuthConstants.AUTHORIZATION_BASIC_HEADER+ + Base64.getEncoder()+ .encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));+ }++ private static byte[] basicAuthBytes(String authHeader) {+ return authHeader.getBytes(StandardCharsets.UTF_8);+ }++ private static void deletePath(Path path) {+ try {+ Files.deleteIfExists(path);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+}diff --git a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/auth/TestBasicAuthenticator.java b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/auth/TestBasicAuthenticator.javanew file mode 100644index 0000000000..661ea88bda--- /dev/null+++ b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/auth/TestBasicAuthenticator.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.idp.auth;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import java.lang.reflect.Field;+import java.nio.charset.StandardCharsets;+import java.util.Arrays;+import java.util.Base64;+import org.apache.gravitino.UserPrincipal;+import org.apache.gravitino.auth.AuthConstants;+import org.apache.gravitino.exceptions.UnauthorizedException;+import org.apache.gravitino.idp.IdpUserGroupManager;+import org.apache.gravitino.idp.model.IdpUser;+import org.junit.jupiter.api.Test;++class TestBasicAuthenticator {++ @Test+ void testNotInitialized() {+ IllegalStateException exception =+ assertThrows(+ IllegalStateException.class, () -> new BasicAuthenticator().authenticateToken(null));++ assertEquals("Basic authenticator has not been initialized", exception.getMessage());+ }++ @Test+ void testSupportsBasic() throws Exception {+ BasicAuthenticator authenticator = authenticator();++ assertTrue(authenticator.supportsToken(basicAuthBytes(basicAuthHeader("alice", "secret"))));+ assertFalse(authenticator.supportsToken("Bearer token".getBytes(StandardCharsets.UTF_8)));+ assertFalse(authenticator.supportsToken(null));+ }++ @Test+ void testEmptyHeader() throws Exception {+ BasicAuthenticator authenticator = authenticator();+ UnauthorizedException exception =+ assertThrows(UnauthorizedException.class, () -> authenticator.authenticateToken(null));++ assertEquals("Empty token authorization header", exception.getMessage());+ assertEquals("Basic", exception.getChallenges().get(0));+ }++ @Test+ void testMissingCredentials() throws Exception {+ BasicAuthenticator authenticator = authenticator();+ UnauthorizedException exception =+ assertThrows(+ UnauthorizedException.class,+ () ->+ authenticator.authenticateToken(+ AuthConstants.AUTHORIZATION_BASIC_HEADER.getBytes(StandardCharsets.UTF_8)));++ assertEquals(+ "Malformed Basic authorization header: missing credentials", exception.getMessage());+ assertEquals("Basic", exception.getChallenges().get(0));+ }++ @Test+ void testValidCredentials() throws Exception {+ IdpUserGroupManager userGroupManager = mock(IdpUserGroupManager.class);+ when(userGroupManager.authenticate("alice", "Passw0rd-For-Alice"))+ .thenReturn(new IdpUser("alice", Arrays.asList("group-a", "group-b")));+ BasicAuthenticator authenticator = authenticator(userGroupManager);+ String authHeader = basicAuthHeader("alice", "Passw0rd-For-Alice");++ UserPrincipal principal =+ (UserPrincipal) authenticator.authenticateToken(basicAuthBytes(authHeader));++ assertEquals("alice", principal.getName());+ assertEquals(authHeader, principal.getAccessToken().orElse(null));+ assertEquals(2, principal.getGroups().size());+ assertEquals("group-a", principal.getGroups().get(0).getGroupname());+ assertEquals("group-b", principal.getGroups().get(1).getGroupname());+ }++ @Test+ void testUserNotFound() throws Exception {+ IdpUserGroupManager userGroupManager = mock(IdpUserGroupManager.class);+ when(userGroupManager.authenticate("alice", "Passw0rd-For-Alice"))+ .thenThrow(+ new UnauthorizedException(+ "Invalid username or password", AuthConstants.AUTHORIZATION_BASIC_HEADER.trim()));+ BasicAuthenticator authenticator = authenticator(userGroupManager);++ UnauthorizedException exception =+ assertThrows(+ UnauthorizedException.class,+ () ->+ authenticator.authenticateToken(+ basicAuthBytes(basicAuthHeader("alice", "Passw0rd-For-Alice"))));++ assertUnauthorized(exception);+ }++ @Test+ void testInvalidBase64() throws Exception {+ BasicAuthenticator authenticator = authenticator();++ UnauthorizedException exception =+ assertThrows(+ UnauthorizedException.class,+ () -> authenticator.authenticateToken(basicAuthBytesWithCredential("not-valid!!!")));++ assertEquals("Malformed Basic authorization header: invalid base64", exception.getMessage());+ assertEquals("Basic", exception.getChallenges().get(0));+ }++ @Test+ void testMissingSeparator() throws Exception {+ BasicAuthenticator authenticator = authenticator();+ String credential =+ Base64.getEncoder().encodeToString("aliceonly".getBytes(StandardCharsets.UTF_8));++ UnauthorizedException exception =+ assertThrows(+ UnauthorizedException.class,+ () -> authenticator.authenticateToken(basicAuthBytesWithCredential(credential)));++ assertEquals(+ "Malformed Basic authorization header: credentials must be in username:password format",+ exception.getMessage());+ assertEquals("Basic", exception.getChallenges().get(0));+ }++ @Test+ void testEmptyUsername() throws Exception {+ BasicAuthenticator authenticator = authenticator();+ String credential =+ Base64.getEncoder().encodeToString(":password".getBytes(StandardCharsets.UTF_8));++ UnauthorizedException exception =+ assertThrows(+ UnauthorizedException.class,+ () -> authenticator.authenticateToken(basicAuthBytesWithCredential(credential)));++ assertEquals(+ "Malformed Basic authorization header: username must not be blank", exception.getMessage());+ assertEquals("Basic", exception.getChallenges().get(0));+ }++ @Test+ void testTrimmedCredential() throws Exception {+ IdpUserGroupManager userGroupManager = mock(IdpUserGroupManager.class);+ when(userGroupManager.authenticate("alice", "Passw0rd-For-Alice"))+ .thenReturn(new IdpUser("alice", Arrays.asList()));+ BasicAuthenticator authenticator = authenticator(userGroupManager);+ String credential =+ " "+ + Base64.getEncoder()+ .encodeToString("alice:Passw0rd-For-Alice".getBytes(StandardCharsets.UTF_8))+ + " ";++ UserPrincipal principal =+ (UserPrincipal) authenticator.authenticateToken(basicAuthBytesWithCredential(credential));++ assertEquals("alice", principal.getName());+ }++ @Test+ void testBlankPassword() throws Exception {+ IdpUserGroupManager userGroupManager = mock(IdpUserGroupManager.class);+ BasicAuthenticator authenticator = authenticator(userGroupManager);++ UnauthorizedException exception =+ assertThrows(+ UnauthorizedException.class,+ () -> authenticator.authenticateToken(basicAuthBytes(basicAuthHeader("alice", " "))));++ assertUnauthorized(exception);+ }++ @Test+ void testWrongPassword() throws Exception {+ IdpUserGroupManager userGroupManager = mock(IdpUserGroupManager.class);+ when(userGroupManager.authenticate("alice", "Passw0rd-For-Alice"))+ .thenThrow(+ new UnauthorizedException(+ "Invalid username or password", AuthConstants.AUTHORIZATION_BASIC_HEADER.trim()));+ BasicAuthenticator authenticator = authenticator(userGroupManager);++ UnauthorizedException exception =+ assertThrows(+ UnauthorizedException.class,+ () ->+ authenticator.authenticateToken(+ basicAuthBytes(basicAuthHeader("alice", "Passw0rd-For-Alice"))));++ assertUnauthorized(exception);+ }++ private static void assertUnauthorized(UnauthorizedException exception) {+ assertEquals("Invalid username or password", exception.getMessage());+ assertEquals("Basic", exception.getChallenges().get(0));+ }++ private static String basicAuthHeader(String username, String password) {+ return AuthConstants.AUTHORIZATION_BASIC_HEADER+ + Base64.getEncoder()+ .encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));+ }++ private static byte[] basicAuthBytes(String authHeader) {+ return authHeader.getBytes(StandardCharsets.UTF_8);+ }++ private static byte[] basicAuthBytesWithCredential(String credential) {+ return (AuthConstants.AUTHORIZATION_BASIC_HEADER + credential).getBytes(StandardCharsets.UTF_8);+ }++ private BasicAuthenticator authenticator() throws Exception {+ return authenticator(mock(IdpUserGroupManager.class));+ }++ private static BasicAuthenticator authenticator(IdpUserGroupManager userGroupManager)+ throws Exception {+ BasicAuthenticator authenticator = new BasicAuthenticator();+ Field field = BasicAuthenticator.class.getDeclaredField("userGroupManager");+ field.setAccessible(true);+ field.set(authenticator, userGroupManager);+ return authenticator;+ }+}diff --git a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/integration/test/IdpRESTApiIT.java b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/integration/test/IdpRESTApiIT.javanew file mode 100644index 0000000000..899c143e98--- /dev/null+++ b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/integration/test/IdpRESTApiIT.java@@ -0,0 +1,366 @@+/*+ * 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.idp.integration.test;++import static org.apache.gravitino.integration.test.util.BaseIT.setEnv;++import com.google.common.collect.Maps;+import java.io.IOException;+import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.Paths;+import java.util.Base64;+import java.util.List;+import java.util.Map;+import java.util.Set;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.Configs;+import org.apache.gravitino.auth.AuthConstants;+import org.apache.gravitino.dto.responses.ErrorConstants;+import org.apache.gravitino.idp.dto.requests.AddGroupRequest;+import org.apache.gravitino.idp.dto.requests.AddUserRequest;+import org.apache.gravitino.idp.dto.requests.ChangePasswordRequest;+import org.apache.gravitino.idp.dto.requests.GroupMembershipChangeRequest;+import org.apache.gravitino.idp.dto.responses.IdpGroupResponse;+import org.apache.gravitino.idp.dto.responses.IdpUserResponse;+import org.apache.gravitino.idp.web.rest.feature.IdpRESTFeature;+import org.apache.gravitino.integration.test.util.BaseIT;+import org.apache.gravitino.integration.test.util.ITUtils;+import org.apache.gravitino.json.JsonUtils;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++/**+ * End-to-end tests for built-in IdP REST APIs.+ *+ * <p>Run with {@code -PjdbcBackend=h2}, {@code mysql}, or {@code postgresql} to exercise the same+ * API surface against each relational backend.+ */+public class IdpRESTApiIT extends BaseIT {++ private static final String ACCEPT = "application/vnd.gravitino.v1+json";+ private static final String ADMIN = "admin";+ private static final String ADMIN_PASSWORD = "Passw0rd-For-Admin1";+ private static final String USER1 = "user1";+ private static final String USER2 = "user2";+ private static final String GROUP1 = "group1";+ private static final String USER_PASSWORD = "Passw0rd-For-User1";+ private static final String UPDATED_PASSWORD = "Passw0rd-For-User2";+ private static final String MISSING_USER = "missing-user";+ private static final String MISSING_GROUP = "missing-group";++ private static final HttpClient HTTP = HttpClient.newHttpClient();++ private static String apiBase;++ @BeforeAll+ public void startIntegrationTest() throws Exception {+ setEnv(IdpRESTFeature.INITIAL_ADMIN_PASSWORD_ENV, ADMIN_PASSWORD);+ ensureDeployInitialAdminPasswordInDistributionEnv();+ Map<String, String> configs = Maps.newHashMap();+ configs.put(Configs.ENABLE_AUTHORIZATION.getKey(), String.valueOf(false));+ configs.put(Configs.CACHE_ENABLED.getKey(), String.valueOf(false));+ configs.put(Configs.STORE_DELETE_AFTER_TIME.getKey(), String.valueOf(20 * 60 * 1000L));+ configs.put(Configs.SERVICE_ADMINS.getKey(), ADMIN);+ configs.put(+ Configs.REST_API_EXTENSION_PACKAGES.getKey(), IdpRESTFeature.IDP_REST_EXTENSION_PACKAGE);+ registerCustomConfigs(configs);+ super.startIntegrationTest();+ apiBase = serverUri + "/api";+ }++ private static void ensureDeployInitialAdminPasswordInDistributionEnv() throws IOException {+ if (!ITUtils.DEPLOY_TEST_MODE.equals(System.getProperty(ITUtils.TEST_MODE))) {+ return;+ }+ String gravitinoHome = System.getenv("GRAVITINO_HOME");+ if (StringUtils.isBlank(gravitinoHome)) {+ return;+ }+ Path envFile = Paths.get(gravitinoHome, "conf", "gravitino-env.sh");+ String exportLine =+ "export GRAVITINO_INITIAL_ADMIN_PASSWORD='" + ADMIN_PASSWORD.replace("'", "'\\''") + "'";+ String existing =+ Files.exists(envFile) ? Files.readString(envFile, StandardCharsets.UTF_8) : "";+ if (existing.contains("GRAVITINO_INITIAL_ADMIN_PASSWORD")) {+ return;+ }+ String separator = existing.endsWith(System.lineSeparator()) ? "" : System.lineSeparator();+ Files.writeString(+ envFile,+ existing + separator + exportLine + System.lineSeparator(),+ StandardCharsets.UTF_8);+ }++ @Test+ void testIdpAuthorization() throws Exception {+ Assertions.assertEquals(200, get("/version", ADMIN, ADMIN_PASSWORD).statusCode());+ // No Authorization: simple authenticator allows anonymous access; IdP filter rejects.+ assertError(403, get("/idp/users/" + USER1, null, null), ErrorConstants.FORBIDDEN_CODE);++ postUser(USER2, USER_PASSWORD);+ assertError(+ 403, get("/idp/users/" + USER2, USER2, USER_PASSWORD), ErrorConstants.FORBIDDEN_CODE);+ Assertions.assertTrue(deleteUser(USER2));+ }++ @Test+ void testManageUsers() throws Exception {+ postUser(USER1, USER_PASSWORD);+ IdpUserResponse user = getUser(USER1);+ Assertions.assertEquals(USER1, user.getUser().name());+ Assertions.assertTrue(user.getUser().groups().isEmpty());++ assertError(+ 400,+ post("/idp/users", new AddUserRequest("", USER_PASSWORD)),+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE);+ assertError(+ 400,+ post("/idp/users", new AddUserRequest(USER1, " ")),+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE);+ assertError(+ 409,+ post("/idp/users", new AddUserRequest(USER1, USER_PASSWORD)),+ ErrorConstants.ALREADY_EXISTS_CODE);++ changePassword(USER1, UPDATED_PASSWORD);+ Assertions.assertEquals(USER1, getUser(USER1).getUser().name());++ assertError(+ 404,+ get("/idp/users/" + MISSING_USER, ADMIN, ADMIN_PASSWORD),+ ErrorConstants.NOT_FOUND_CODE);+ assertError(+ 404,+ put("/idp/users/" + MISSING_USER, new ChangePasswordRequest(UPDATED_PASSWORD)),+ ErrorConstants.NOT_FOUND_CODE);+ assertError(+ 400,+ put("/idp/users/" + USER1, new ChangePasswordRequest(" ")),+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE);++ Assertions.assertTrue(deleteUser(USER1));+ assertError(+ 404, get("/idp/users/" + USER1, ADMIN, ADMIN_PASSWORD), ErrorConstants.NOT_FOUND_CODE);+ Assertions.assertFalse(deleteUser(USER1));+ }++ @Test+ void testManageGroups() throws Exception {+ postUser(USER1, USER_PASSWORD);+ postUser(USER2, USER_PASSWORD);++ IdpGroupResponse group = postGroup(GROUP1);+ Assertions.assertEquals(GROUP1, group.getGroup().name());+ Assertions.assertTrue(group.getGroup().users().isEmpty());++ assertError(+ 409, post("/idp/groups", new AddGroupRequest(GROUP1)), ErrorConstants.ALREADY_EXISTS_CODE);+ assertError(+ 404,+ get("/idp/groups/" + MISSING_GROUP, ADMIN, ADMIN_PASSWORD),+ ErrorConstants.NOT_FOUND_CODE);++ group =+ putMembership(GROUP1, new GroupMembershipChangeRequest(new String[] {USER1, USER2}, null));+ Assertions.assertEquals(Set.of(USER1, USER2), Set.copyOf(group.getGroup().users()));++ assertError(405, deleteGroupResponse(GROUP1, false), ErrorConstants.UNSUPPORTED_OPERATION_CODE);++ group =+ putMembership(GROUP1, new GroupMembershipChangeRequest(null, new String[] {USER1, USER2}));+ Assertions.assertTrue(group.getGroup().users().isEmpty());++ Assertions.assertTrue(deleteGroup(GROUP1, false));+ Assertions.assertFalse(deleteGroup(GROUP1, false));++ deleteUser(USER1);+ deleteUser(USER2);+ }++ @Test+ void testGroupMembership() throws Exception {+ postUser(USER1, USER_PASSWORD);+ postGroup(GROUP1);++ assertError(+ 400,+ put("/idp/groups/" + GROUP1 + "/users", new GroupMembershipChangeRequest(null, null)),+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE);+ assertError(+ 400,+ put(+ "/idp/groups/" + GROUP1 + "/users",+ new GroupMembershipChangeRequest(new String[] {}, new String[] {})),+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE);+ assertError(+ 404,+ put(+ "/idp/groups/" + GROUP1 + "/users",+ new GroupMembershipChangeRequest(new String[] {MISSING_USER}, null)),+ ErrorConstants.NOT_FOUND_CODE);+ assertError(+ 404,+ put(+ "/idp/groups/" + MISSING_GROUP + "/users",+ new GroupMembershipChangeRequest(new String[] {USER1}, null)),+ ErrorConstants.NOT_FOUND_CODE);++ IdpGroupResponse group =+ putMembership(GROUP1, new GroupMembershipChangeRequest(new String[] {USER1}, null));+ Assertions.assertEquals(List.of(USER1), group.getGroup().users());++ Assertions.assertTrue(deleteGroup(GROUP1, true));+ deleteUser(USER1);+ }++ private static HttpResponse<String> get(String path, String username, String password)+ throws Exception {+ HttpRequest.Builder builder =+ HttpRequest.newBuilder().uri(URI.create(apiBase + path)).header("Accept", ACCEPT).GET();+ if (StringUtils.isNotBlank(username)) {+ builder.header("Authorization", basicAuth(username, password));+ }+ return HTTP.send(builder.build(), HttpResponse.BodyHandlers.ofString());+ }++ private static void postUser(String username, String password) throws Exception {+ HttpResponse<String> response = post("/idp/users", new AddUserRequest(username, password));+ Assertions.assertEquals(200, response.statusCode(), response.body());+ JsonUtils.objectMapper().readValue(response.body(), IdpUserResponse.class).validate();+ }++ private static IdpUserResponse getUser(String username) throws Exception {+ HttpResponse<String> response = get("/idp/users/" + username, ADMIN, ADMIN_PASSWORD);+ Assertions.assertEquals(200, response.statusCode(), response.body());+ IdpUserResponse userResponse =+ JsonUtils.objectMapper().readValue(response.body(), IdpUserResponse.class);+ userResponse.validate();+ return userResponse;+ }++ private static void changePassword(String username, String password) throws Exception {+ HttpResponse<String> response =+ put("/idp/users/" + username, new ChangePasswordRequest(password));+ Assertions.assertEquals(200, response.statusCode(), response.body());+ }++ private static boolean deleteUser(String username) throws Exception {+ HttpResponse<String> response = deleteUserResponse(username);+ Assertions.assertEquals(200, response.statusCode(), response.body());+ return JsonUtils.objectMapper().readTree(response.body()).get("removed").asBoolean();+ }++ private static HttpResponse<String> deleteUserResponse(String username) throws Exception {+ return HTTP.send(+ authorized(ADMIN, ADMIN_PASSWORD)+ .uri(URI.create(apiBase + "/idp/users/" + username))+ .DELETE()+ .build(),+ HttpResponse.BodyHandlers.ofString());+ }++ private static IdpGroupResponse postGroup(String groupName) throws Exception {+ HttpResponse<String> response = post("/idp/groups", new AddGroupRequest(groupName));+ Assertions.assertEquals(200, response.statusCode(), response.body());+ IdpGroupResponse groupResponse =+ JsonUtils.objectMapper().readValue(response.body(), IdpGroupResponse.class);+ groupResponse.validate();+ return groupResponse;+ }++ private static IdpGroupResponse putMembership(+ String groupName, GroupMembershipChangeRequest request) throws Exception {+ HttpResponse<String> response = put("/idp/groups/" + groupName + "/users", request);+ Assertions.assertEquals(200, response.statusCode(), response.body());+ IdpGroupResponse groupResponse =+ JsonUtils.objectMapper().readValue(response.body(), IdpGroupResponse.class);+ groupResponse.validate();+ return groupResponse;+ }++ private static boolean deleteGroup(String groupName, boolean force) throws Exception {+ HttpResponse<String> response = deleteGroupResponse(groupName, force);+ Assertions.assertEquals(200, response.statusCode(), response.body());+ return JsonUtils.objectMapper().readTree(response.body()).get("removed").asBoolean();+ }++ private static HttpResponse<String> deleteGroupResponse(String groupName, boolean force)+ throws Exception {+ return HTTP.send(+ authorized(ADMIN, ADMIN_PASSWORD)+ .uri(URI.create(apiBase + "/idp/groups/" + groupName + "?force=" + force))+ .DELETE()+ .build(),+ HttpResponse.BodyHandlers.ofString());+ }++ private static HttpResponse<String> post(String path, Object body) throws Exception {+ return HTTP.send(+ authorized(ADMIN, ADMIN_PASSWORD)+ .uri(URI.create(apiBase + path))+ .header("Content-Type", ACCEPT)+ .POST(jsonBody(body))+ .build(),+ HttpResponse.BodyHandlers.ofString());+ }++ private static HttpResponse<String> put(String path, Object body) throws Exception {+ return HTTP.send(+ authorized(ADMIN, ADMIN_PASSWORD)+ .uri(URI.create(apiBase + path))+ .header("Content-Type", ACCEPT)+ .PUT(jsonBody(body))+ .build(),+ HttpResponse.BodyHandlers.ofString());+ }++ private static HttpRequest.BodyPublisher jsonBody(Object body) throws Exception {+ return HttpRequest.BodyPublishers.ofString(JsonUtils.objectMapper().writeValueAsString(body));+ }++ private static HttpRequest.Builder authorized(String username, String password) {+ return HttpRequest.newBuilder()+ .header("Accept", ACCEPT)+ .header("Authorization", basicAuth(username, password));+ }++ private static String basicAuth(String username, String password) {+ return AuthConstants.AUTHORIZATION_BASIC_HEADER+ + Base64.getEncoder()+ .encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));+ }++ private static void assertError(int expectedStatus, HttpResponse<String> response, int errorCode)+ throws Exception {+ Assertions.assertEquals(expectedStatus, response.statusCode(), response.body());+ Assertions.assertEquals(errorCode, errorCode(response));+ }++ private static int errorCode(HttpResponse<String> response) throws Exception {+ return JsonUtils.objectMapper().readTree(response.body()).get("code").asInt();+ }+}diff --git a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/mapper/TestIdpGroupMetaStorage.java b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/mapper/TestIdpGroupMetaStorage.javaindex 40433a46f9..ffc00944ba 100644--- a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/mapper/TestIdpGroupMetaStorage.java+++ b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/mapper/TestIdpGroupMetaStorage.java@@ -21,9 +21,13 @@ package org.apache.gravitino.idp.storage.mapper;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertTrue;import java.io.IOException;+import java.util.List;import org.apache.gravitino.idp.storage.po.IdpGroupPO;+import org.apache.gravitino.idp.storage.po.IdpUserGroupRelPO;+import org.apache.gravitino.idp.storage.po.IdpUserPO;import org.junit.jupiter.api.Tag;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.MethodSource;@@ -55,6 +59,65 @@ class TestIdpGroupMetaStorage extends AbstractIdpMetaStorageTest {assertNull(idpGroupMetaMapper.selectIdpGroup("unknown"));}+ @ParameterizedTest+ @MethodSource("storageProvider")+ void testSelectIdpGroupWithUsers(String type) throws IOException {+ init(type);+ idpGroupMetaMapper.insertIdpGroup(+ IdpGroupPO.builder()+ .withGroupId(1L)+ .withGroupName("dev")+ .withCurrentVersion(1L)+ .withLastVersion(0L)+ .withDeletedAt(0L)+ .build());+ IdpUserMetaMapper idpUserMetaMapper = sharedSession.getMapper(IdpUserMetaMapper.class);+ IdpUserGroupRelMapper idpUserGroupRelMapper =+ sharedSession.getMapper(IdpUserGroupRelMapper.class);+ idpUserMetaMapper.insertIdpUser(+ IdpUserPO.builder()+ .withUserId(1L)+ .withUsername("alice")+ .withPasswordHash("hash-a")+ .withCurrentVersion(1L)+ .withLastVersion(0L)+ .withDeletedAt(0L)+ .build());+ idpUserMetaMapper.insertIdpUser(+ IdpUserPO.builder()+ .withUserId(2L)+ .withUsername("bob")+ .withPasswordHash("hash-b")+ .withCurrentVersion(1L)+ .withLastVersion(0L)+ .withDeletedAt(0L)+ .build());+ idpUserGroupRelMapper.batchInsertRelations(+ List.of(+ IdpUserGroupRelPO.builder()+ .withId(100L)+ .withUserId(1L)+ .withGroupId(1L)+ .withCurrentVersion(1L)+ .withLastVersion(0L)+ .withDeletedAt(0L)+ .build(),+ IdpUserGroupRelPO.builder()+ .withId(101L)+ .withUserId(2L)+ .withGroupId(1L)+ .withCurrentVersion(1L)+ .withLastVersion(0L)+ .withDeletedAt(0L)+ .build()));++ var groupWithUsers = idpGroupMetaMapper.selectIdpGroupWithUsers("dev");+ assertEquals("dev", groupWithUsers.getName());+ assertTrue(groupWithUsers.getUsernames().contains("alice"));+ assertTrue(groupWithUsers.getUsernames().contains("bob"));+ assertNull(idpGroupMetaMapper.selectIdpGroupWithUsers("unknown"));+ }+@ParameterizedTest@MethodSource("storageProvider")void testSelectIdpGroupIgnoresDeletedGroups(String type) throws IOException {diff --git a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/mapper/TestIdpUserMetaStorage.java b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/mapper/TestIdpUserMetaStorage.javaindex a99430d8d9..c8a5b9701c 100644--- a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/mapper/TestIdpUserMetaStorage.java+++ b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/mapper/TestIdpUserMetaStorage.java@@ -21,9 +21,12 @@ package org.apache.gravitino.idp.storage.mapper;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertTrue;import java.io.IOException;import java.util.List;+import org.apache.gravitino.idp.storage.po.IdpGroupPO;+import org.apache.gravitino.idp.storage.po.IdpUserGroupRelPO;import org.apache.gravitino.idp.storage.po.IdpUserPO;import org.junit.jupiter.api.Tag;import org.junit.jupiter.params.ParameterizedTest;@@ -57,6 +60,65 @@ class TestIdpUserMetaStorage extends AbstractIdpMetaStorageTest {assertNull(idpUserMetaMapper.selectIdpUser("unknown"));}+ @ParameterizedTest+ @MethodSource("storageProvider")+ void testSelectIdpUserWithGroups(String type) throws IOException {+ init(type);+ idpUserMetaMapper.insertIdpUser(+ IdpUserPO.builder()+ .withUserId(1L)+ .withUsername("alice")+ .withPasswordHash("hash-a")+ .withCurrentVersion(1L)+ .withLastVersion(0L)+ .withDeletedAt(0L)+ .build());+ IdpGroupMetaMapper idpGroupMetaMapper = sharedSession.getMapper(IdpGroupMetaMapper.class);+ IdpUserGroupRelMapper idpUserGroupRelMapper =+ sharedSession.getMapper(IdpUserGroupRelMapper.class);+ idpGroupMetaMapper.insertIdpGroup(+ IdpGroupPO.builder()+ .withGroupId(1L)+ .withGroupName("dev")+ .withCurrentVersion(1L)+ .withLastVersion(0L)+ .withDeletedAt(0L)+ .build());+ idpGroupMetaMapper.insertIdpGroup(+ IdpGroupPO.builder()+ .withGroupId(2L)+ .withGroupName("ops")+ .withCurrentVersion(1L)+ .withLastVersion(0L)+ .withDeletedAt(0L)+ .build());+ idpUserGroupRelMapper.batchInsertRelations(+ List.of(+ IdpUserGroupRelPO.builder()+ .withId(100L)+ .withUserId(1L)+ .withGroupId(1L)+ .withCurrentVersion(1L)+ .withLastVersion(0L)+ .withDeletedAt(0L)+ .build(),+ IdpUserGroupRelPO.builder()+ .withId(101L)+ .withUserId(1L)+ .withGroupId(2L)+ .withCurrentVersion(1L)+ .withLastVersion(0L)+ .withDeletedAt(0L)+ .build()));++ var userWithGroups = idpUserMetaMapper.selectIdpUserWithGroups("alice");+ assertEquals("alice", userWithGroups.getName());+ assertEquals("hash-a", userWithGroups.getPasswordHash());+ assertTrue(userWithGroups.getGroupNames().contains("dev"));+ assertTrue(userWithGroups.getGroupNames().contains("ops"));+ assertNull(idpUserMetaMapper.selectIdpUserWithGroups("unknown"));+ }+@ParameterizedTest@MethodSource("storageProvider")void testSelectIdpUsersByUsernames(String type) throws IOException {diff --git a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/service/TestIdpGroupMetaService.java b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/service/TestIdpGroupMetaService.javaindex 42d5f1fc84..b0b22e7f21 100644--- a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/service/TestIdpGroupMetaService.java+++ b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/service/TestIdpGroupMetaService.java@@ -26,8 +26,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;import java.io.IOException;import java.util.List;-import org.apache.gravitino.idp.exception.AlreadyExistsException;-import org.apache.gravitino.idp.exception.NotFoundException;+import java.util.Set;+import org.apache.gravitino.exceptions.AlreadyExistsException;+import org.apache.gravitino.exceptions.NotFoundException;import org.apache.gravitino.idp.storage.po.IdpGroupPO;import org.junit.jupiter.api.Tag;import org.junit.jupiter.params.ParameterizedTest;@@ -47,6 +48,34 @@ class TestIdpGroupMetaService extends AbstractIdpMetaServiceTest {assertEquals("group1", groupMetaService.getIdpGroupByName("group1").getGroupName());}+ @ParameterizedTest+ @MethodSource("storageProvider")+ void testGetIdpGroup(String type) throws IOException {+ init(type);+ insertUsers(2);+ IdpGroupMetaService groupMetaService = IdpGroupMetaService.getInstance();+ runServiceCall(+ () ->+ groupMetaService.insertIdpGroup(+ IdpGroupPO.builder()+ .withGroupId(1L)+ .withGroupName("engineering")+ .withCurrentVersion(1L)+ .withLastVersion(0L)+ .withDeletedAt(0L)+ .build()));+ runServiceCall(+ () ->+ groupMetaService.changeGroupMembership(+ "engineering", List.of("user1", "user2"), List.of()));++ assertThrows(NotFoundException.class, () -> groupMetaService.getIdpGroup("missing"));+ assertEquals("engineering", groupMetaService.getIdpGroup("engineering").name());+ assertEquals(+ Set.of("user1", "user2"),+ Set.copyOf(groupMetaService.getIdpGroup("engineering").usernames()));+ }+@ParameterizedTest@MethodSource("storageProvider")void testInsertIdpGroup(String type) throws IOException {diff --git a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/service/TestIdpUserMetaService.java b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/service/TestIdpUserMetaService.javaindex d1c7422f5b..e732bb0f92 100644--- a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/service/TestIdpUserMetaService.java+++ b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/storage/service/TestIdpUserMetaService.java@@ -26,8 +26,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;import java.io.IOException;import java.util.List;-import org.apache.gravitino.idp.exception.AlreadyExistsException;-import org.apache.gravitino.idp.exception.NotFoundException;+import org.apache.gravitino.exceptions.AlreadyExistsException;+import org.apache.gravitino.exceptions.NotFoundException;import org.apache.gravitino.idp.storage.po.IdpUserPO;import org.junit.jupiter.api.Tag;import org.junit.jupiter.params.ParameterizedTest;@@ -45,6 +45,8 @@ class TestIdpUserMetaService extends AbstractIdpMetaServiceTest {assertThrows(NotFoundException.class, () -> userMetaService.getIdpUserByUsername("missing"));assertEquals("user1", userMetaService.getIdpUserByUsername("user1").getUsername());+ assertEquals("user1", userMetaService.getIdpUser("user1").name());+ assertThrows(NotFoundException.class, () -> userMetaService.getIdpUser("missing"));}@ParameterizedTestdiff --git a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/web/rest/TestIdpOperations.java b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/web/rest/TestIdpOperations.javaindex 79427a63e1..f8ae328fe1 100644--- a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/web/rest/TestIdpOperations.java+++ b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/web/rest/TestIdpOperations.java@@ -37,6 +37,8 @@ import javax.ws.rs.core.Response;import org.apache.gravitino.dto.responses.ErrorConstants;import org.apache.gravitino.dto.responses.ErrorResponse;import org.apache.gravitino.dto.responses.RemoveResponse;+import org.apache.gravitino.exceptions.AlreadyExistsException;+import org.apache.gravitino.exceptions.NotFoundException;import org.apache.gravitino.idp.IdpUserGroupManager;import org.apache.gravitino.idp.dto.requests.AddGroupRequest;import org.apache.gravitino.idp.dto.requests.AddUserRequest;@@ -44,8 +46,6 @@ import org.apache.gravitino.idp.dto.requests.ChangePasswordRequest;import org.apache.gravitino.idp.dto.requests.GroupMembershipChangeRequest;import org.apache.gravitino.idp.dto.responses.IdpGroupResponse;import org.apache.gravitino.idp.dto.responses.IdpUserResponse;-import org.apache.gravitino.idp.exception.AlreadyExistsException;-import org.apache.gravitino.idp.exception.NotFoundException;import org.apache.gravitino.idp.model.IdpGroup;import org.apache.gravitino.idp.model.IdpUser;import org.apache.gravitino.rest.RESTUtils;diff --git a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/web/rest/TestIdpRestExtension.java b/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/web/rest/TestIdpRestExtension.javadeleted file mode 100644index b13c97ca07..0000000000--- a/plugins/idp-basic/src/test/java/org/apache/gravitino/idp/web/rest/TestIdpRestExtension.java+++ /dev/null@@ -1,180 +0,0 @@-/*- * 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.idp.web.rest;--import static org.apache.gravitino.Configs.CACHE_ENABLED;-import static org.apache.gravitino.Configs.ENABLE_AUTHORIZATION;-import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;-import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;-import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL;-import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_MILLISECONDS;-import static org.apache.gravitino.Configs.ENTITY_STORE;-import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;-import static org.apache.gravitino.Configs.REST_API_EXTENSION_PACKAGES;-import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;-import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertFalse;--import com.fasterxml.jackson.databind.JsonNode;-import com.google.common.collect.ImmutableMap;-import java.io.IOException;-import java.net.URI;-import java.net.http.HttpClient;-import java.net.http.HttpRequest;-import java.net.http.HttpResponse;-import java.nio.file.Files;-import java.nio.file.Path;-import org.apache.commons.io.FileUtils;-import org.apache.gravitino.Configs;-import org.apache.gravitino.GravitinoEnv;-import org.apache.gravitino.auxiliary.AuxiliaryServiceManager;-import org.apache.gravitino.dto.responses.ErrorConstants;-import org.apache.gravitino.json.JsonUtils;-import org.apache.gravitino.rest.RESTUtils;-import org.apache.gravitino.server.GravitinoServer;-import org.apache.gravitino.server.ServerConfig;-import org.apache.gravitino.server.web.JettyServerConfig;-import org.junit.jupiter.api.AfterAll;-import org.junit.jupiter.api.BeforeAll;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.TestInstance;-import org.junit.jupiter.api.TestInstance.Lifecycle;-import org.mockito.Mockito;--/** Verifies IdP REST resources load via {@link Configs#REST_API_EXTENSION_PACKAGES}. */-@TestInstance(Lifecycle.PER_CLASS)-public class TestIdpRestExtension {-- private static final String ACCEPT = "application/vnd.gravitino.v1+json";- private static final String IDP_REST_EXTENSION_PACKAGE =- "org.apache.gravitino.idp.web.rest.feature";- private static final HttpClient HTTP = HttpClient.newHttpClient();-- private int httpPort;- private Path h2Path;-- @BeforeAll- void init() throws IOException {- httpPort = RESTUtils.findAvailablePort(5000, 6000);- h2Path = Files.createTempDirectory("gravitino_idp_rest_extension_it_");- }-- @AfterAll- void cleanup() throws IOException {- if (h2Path != null) {- FileUtils.deleteDirectory(h2Path.toFile());- }- }-- @Test- public void testWithoutExtension() throws Exception {- try (ServerHarness harness = startServer(newConfig(false))) {- HttpResponse<String> response = getUser(harness.port(), "missing-user");- assertEquals(404, response.statusCode());- assertFalse(isNotFoundError(response.body()));- }- }-- @Test- public void testWithExtensionWithoutBasicAuthenticator() throws Exception {- try (ServerHarness harness = startServer(newConfig(true))) {- HttpResponse<String> response = getUser(harness.port(), "missing-user");- assertEquals(404, response.statusCode());- assertFalse(- isNotFoundError(response.body()),- "IdP REST routes should not be registered when basic authenticator is disabled");- }- }-- private ServerConfig newConfig(boolean enableExtension) {- ImmutableMap.Builder<String, String> builder =- ImmutableMap.<String, String>builder()- .put(- GravitinoServer.WEBSERVER_CONF_PREFIX- + JettyServerConfig.WEBSERVER_HTTP_PORT.getKey(),- String.valueOf(httpPort))- .put(ENTITY_STORE.getKey(), RELATIONAL_ENTITY_STORE)- .put(- ENTITY_RELATIONAL_JDBC_BACKEND_URL.getKey(),- String.format("jdbc:h2:file:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL", h2Path))- .put(ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER.getKey(), "org.h2.Driver")- .put(ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS.getKey(), "100")- .put(ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_MILLISECONDS.getKey(), "1000")- .put(STORE_DELETE_AFTER_TIME.getKey(), String.valueOf(20 * 60 * 1000L))- .put(CACHE_ENABLED.getKey(), "false")- .put(ENABLE_AUTHORIZATION.getKey(), "false");- if (enableExtension) {- builder.put(REST_API_EXTENSION_PACKAGES.getKey(), IDP_REST_EXTENSION_PACKAGE);- }-- ServerConfig serverConfig = new ServerConfig();- serverConfig.loadFromMap(builder.build(), key -> true);- ServerConfig spyServerConfig = Mockito.spy(serverConfig);- Mockito.when(- spyServerConfig.getConfigsWithPrefix(- AuxiliaryServiceManager.GRAVITINO_AUX_SERVICE_PREFIX))- .thenReturn(ImmutableMap.of(AuxiliaryServiceManager.AUX_SERVICE_NAMES, ""));- return spyServerConfig;- }-- private ServerHarness startServer(ServerConfig serverConfig) throws Exception {- GravitinoServer gravitinoServer = new GravitinoServer(serverConfig, GravitinoEnv.getInstance());- gravitinoServer.initialize();- gravitinoServer.start();- return new ServerHarness(gravitinoServer, httpPort);- }-- private HttpResponse<String> getUser(int port, String user) throws Exception {- return send(- HttpRequest.newBuilder()- .uri(URI.create(String.format("http://localhost:%d/api/idp/users/%s", port, user)))- .header("Accept", ACCEPT)- .GET()- .build());- }-- private HttpResponse<String> send(HttpRequest request) throws Exception {- return HTTP.send(request, HttpResponse.BodyHandlers.ofString());- }-- private boolean isNotFoundError(String body) throws IOException {- JsonNode root = JsonUtils.objectMapper().readTree(body);- return root.has("code") && root.get("code").asInt() == ErrorConstants.NOT_FOUND_CODE;- }-- private static final class ServerHarness implements AutoCloseable {-- private final GravitinoServer gravitinoServer;- private final int port;-- private ServerHarness(GravitinoServer gravitinoServer, int port) {- this.gravitinoServer = gravitinoServer;- this.port = port;- }-- private int port() {- return port;- }-- @Override- public void close() throws IOException {- gravitinoServer.stop();- }- }-}