Copilot commented on code in PR #11214: URL: https://github.com/apache/gravitino/pull/11214#discussion_r3297405041
########## plugins/idp-basic/src/main/java/org/apache/gravitino/idp/auth/BasicAuthenticator.java: ########## @@ -0,0 +1,180 @@ +/* + * 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.UserGroup; +import org.apache.gravitino.UserPrincipal; +import org.apache.gravitino.auth.AuthConstants; +import org.apache.gravitino.exceptions.BadRequestException; +import org.apache.gravitino.exceptions.UnauthorizedException; +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.storage.po.IdpUserPO; +import org.apache.gravitino.idp.storage.service.IdpUserMetaService; +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 IdpUserMetaService userMetaService; + private PasswordHasher passwordHasher; + + /** Creates a {@link BasicAuthenticator} for reflective loading. */ + public BasicAuthenticator() {} + + BasicAuthenticator(IdpUserMetaService userMetaService, PasswordHasher passwordHasher) { + this.userMetaService = userMetaService; + this.passwordHasher = passwordHasher; + } + + @Override + public boolean isDataFromToken() { + return true; + } + + @Override + public Principal authenticateToken(byte[] tokenData) { + Preconditions.checkState( + userMetaService != null && passwordHasher != 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) { + this.userMetaService = IdpUserMetaService.getInstance(); + this.passwordHasher = PasswordHasherFactory.create(); + } + + @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) { + if (tokenData == null) { + throw unauthorized("Empty token authorization header"); + } + + String authData = new String(tokenData, StandardCharsets.UTF_8); + if (authData.trim().isEmpty()) { + throw unauthorized("Empty token authorization header"); + } + if (!authData.startsWith(AuthConstants.AUTHORIZATION_BASIC_HEADER)) { + throw unauthorized("Invalid token authorization header"); + } Review Comment: The HTTP auth scheme name is case-insensitive (e.g., `basic`, `BASIC` should be treated the same as `Basic`). The current `startsWith(...)` checks are case-sensitive, which can incorrectly reject valid requests. Consider implementing a case-insensitive scheme check (without lowercasing the entire header if you want to preserve the credential bytes), and add a unit test that verifies `supportsToken` / `authenticateToken` accept a different-cased `Basic` scheme. ########## plugins/idp-basic/src/main/java/org/apache/gravitino/idp/auth/BasicAuthenticator.java: ########## @@ -0,0 +1,180 @@ +/* + * 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.UserGroup; +import org.apache.gravitino.UserPrincipal; +import org.apache.gravitino.auth.AuthConstants; +import org.apache.gravitino.exceptions.BadRequestException; +import org.apache.gravitino.exceptions.UnauthorizedException; +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.storage.po.IdpUserPO; +import org.apache.gravitino.idp.storage.service.IdpUserMetaService; +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 IdpUserMetaService userMetaService; + private PasswordHasher passwordHasher; + + /** Creates a {@link BasicAuthenticator} for reflective loading. */ + public BasicAuthenticator() {} + + BasicAuthenticator(IdpUserMetaService userMetaService, PasswordHasher passwordHasher) { + this.userMetaService = userMetaService; + this.passwordHasher = passwordHasher; + } + + @Override + public boolean isDataFromToken() { + return true; + } + + @Override + public Principal authenticateToken(byte[] tokenData) { + Preconditions.checkState( + userMetaService != null && passwordHasher != 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) { + this.userMetaService = IdpUserMetaService.getInstance(); + this.passwordHasher = PasswordHasherFactory.create(); + } + + @Override + public boolean supportsToken(byte[] tokenData) { + return tokenData != null + && new String(tokenData, StandardCharsets.UTF_8) + .startsWith(AuthConstants.AUTHORIZATION_BASIC_HEADER); + } Review Comment: The HTTP auth scheme name is case-insensitive (e.g., `basic`, `BASIC` should be treated the same as `Basic`). The current `startsWith(...)` checks are case-sensitive, which can incorrectly reject valid requests. Consider implementing a case-insensitive scheme check (without lowercasing the entire header if you want to preserve the credential bytes), and add a unit test that verifies `supportsToken` / `authenticateToken` accept a different-cased `Basic` scheme. ########## plugins/idp-basic/src/main/java/org/apache/gravitino/idp/auth/BasicAuthenticator.java: ########## @@ -0,0 +1,180 @@ +/* + * 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.UserGroup; +import org.apache.gravitino.UserPrincipal; +import org.apache.gravitino.auth.AuthConstants; +import org.apache.gravitino.exceptions.BadRequestException; +import org.apache.gravitino.exceptions.UnauthorizedException; +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.storage.po.IdpUserPO; +import org.apache.gravitino.idp.storage.service.IdpUserMetaService; +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 IdpUserMetaService userMetaService; + private PasswordHasher passwordHasher; + + /** Creates a {@link BasicAuthenticator} for reflective loading. */ + public BasicAuthenticator() {} + + BasicAuthenticator(IdpUserMetaService userMetaService, PasswordHasher passwordHasher) { + this.userMetaService = userMetaService; + this.passwordHasher = passwordHasher; + } + + @Override + public boolean isDataFromToken() { + return true; + } + + @Override + public Principal authenticateToken(byte[] tokenData) { + Preconditions.checkState( + userMetaService != null && passwordHasher != 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) { + this.userMetaService = IdpUserMetaService.getInstance(); + this.passwordHasher = PasswordHasherFactory.create(); + } + + @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) { + if (tokenData == null) { + throw unauthorized("Empty token authorization header"); + } + + String authData = new String(tokenData, StandardCharsets.UTF_8); + if (authData.trim().isEmpty()) { + throw unauthorized("Empty token authorization header"); + } + if (!authData.startsWith(AuthConstants.AUTHORIZATION_BASIC_HEADER)) { + throw unauthorized("Invalid token authorization header"); + } + return authData; + } + + private BasicCredentials parseBasicCredentials(String authData) { + String credential = authData.substring(AuthConstants.AUTHORIZATION_BASIC_HEADER.length()); + credential = credential.trim(); + if (credential.isEmpty()) { + throw new BadRequestException("Malformed Basic authorization header: missing credentials"); + } + + try { + String decodedCredential = + new String(Base64.getDecoder().decode(credential), StandardCharsets.UTF_8); + int separatorIndex = decodedCredential.indexOf(':'); + if (separatorIndex < 0) { + throw new BadRequestException( + "Malformed Basic authorization header: credentials must be in username:password format"); + } + + String userName = decodedCredential.substring(0, separatorIndex); + if (userName.isEmpty()) { + throw new BadRequestException( + "Malformed Basic authorization header: username must not be empty"); + } + + String password = decodedCredential.substring(separatorIndex + 1); + if (StringUtils.isBlank(password)) { + throw invalidCredentials(); + } + return new BasicCredentials(userName, password); + } catch (IllegalArgumentException e) { + throw new BadRequestException(e, "Malformed Basic authorization header: invalid base64"); + } + } + + private UserPrincipal authenticate(BasicCredentials credentials, String authData) { + IdpUserPO userPO = loadUser(credentials.userName()); + if (!passwordHasher.verify(credentials.password(), userPO.getPasswordHash())) { + throw invalidCredentials(); + } + + List<UserGroup> groups = + userMetaService.listGroupNamesByUsername(credentials.userName()).stream() + .map(groupName -> new UserGroup(Optional.empty(), groupName)) + .collect(Collectors.toList()); + return new UserPrincipal(credentials.userName(), groups, authData); Review Comment: Returning a `UserPrincipal` that stores the raw `Authorization: Basic ...` header as the access token leaks user passwords (Base64-decoded) to any downstream logging/serialization/auditing that includes `accessToken`. Basic auth credentials should not be retained after authentication. Consider omitting the access token for BASIC (e.g., pass `null`/empty token depending on the available `UserPrincipal` constructors) or storing only a non-sensitive marker (like the scheme name) instead, and update the tests that currently assert the header is preserved. ########## server-common/src/main/java/org/apache/gravitino/server/authentication/AuthenticatorFactory.java: ########## @@ -40,7 +40,9 @@ public class AuthenticatorFactory { AuthenticatorType.OAUTH.name().toLowerCase(), OAuth2TokenAuthenticator.class.getCanonicalName(), AuthenticatorType.KERBEROS.name().toLowerCase(), - KerberosAuthenticator.class.getCanonicalName()); + KerberosAuthenticator.class.getCanonicalName(), + AuthenticatorType.BASIC.name().toLowerCase(), + "org.apache.gravitino.idp.auth.BasicAuthenticator"); Review Comment: The BASIC authenticator is registered using a hard-coded FQCN string, unlike the other entries that use `Class.getCanonicalName()`. This is brittle during refactors (package/class rename won’t be caught by the compiler). If a direct dependency isn’t possible here, consider centralizing the class name in a shared constant (or in `AuthenticatorType` metadata) to avoid string duplication/typos and make updates safer. ########## plugins/idp-basic/build.gradle.kts: ########## @@ -26,6 +26,8 @@ plugins { dependencies { annotationProcessor(libs.lombok) + compileOnly(project(":api")) + compileOnly(project(":server-common")) Review Comment: Declaring `:api` and `:server-common` as `compileOnly` means consumers that depend on the `idp-basic` artifact alone will not get these at runtime, which can lead to `ClassNotFoundException`/`NoClassDefFoundError` when loading `BasicAuthenticator` (it references types like `Authenticator`, `Config`, `UserPrincipal`, etc.). If the plugin is meant to be usable as a standalone dependency, consider switching these to `implementation`/`api`, or adding corresponding `runtimeOnly` constraints and documenting that these are required runtime dependencies. ########## server-common/src/test/java/org/apache/gravitino/server/authentication/TestBasicAuthentication.java: ########## @@ -0,0 +1,207 @@ +/* + * 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.server.authentication; + +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.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.common.collect.Lists; +import java.lang.reflect.Constructor; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.Vector; +import javax.servlet.FilterChain; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.gravitino.UserPrincipal; +import org.apache.gravitino.auth.AuthConstants; +import org.apache.gravitino.exceptions.BadRequestException; +import org.apache.gravitino.exceptions.UnauthorizedException; +import org.apache.gravitino.idp.auth.BasicAuthenticator; +import org.apache.gravitino.idp.basic.password.PasswordHasher; +import org.apache.gravitino.idp.exception.NotFoundException; +import org.apache.gravitino.idp.storage.po.IdpUserPO; +import org.apache.gravitino.idp.storage.service.IdpUserMetaService; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +public class TestBasicAuthentication { + + private static final String USER = "alice"; + private static final String PASSWORD = "Passw0rd-For-Alice"; + private static final String PASSWORD_HASH = "hash-1"; + + @Test + public void testSupportsBasic() throws Exception { + BasicAuthenticator authenticator = authenticator(); + + assertTrue(authenticator.supportsToken(basicAuthBytes(USER, PASSWORD))); + assertFalse(authenticator.supportsToken("Bearer token".getBytes(StandardCharsets.UTF_8))); + assertFalse(authenticator.supportsToken(null)); + } + + @Test + public void testValidCredentials() throws Exception { + BasicAuthenticator authenticator = + aliceAuthenticator(true, Arrays.asList("group-a", "group-b")); + String authHeader = basicAuthHeader(USER, PASSWORD); + + UserPrincipal principal = + (UserPrincipal) authenticator.authenticateToken(basicAuthBytes(authHeader)); + + assertEquals(USER, principal.getName()); + assertEquals(authHeader, principal.getAccessToken().orElse(null)); Review Comment: This test asserts that the `UserPrincipal` retains the full Basic Authorization header as an access token, which includes password-equivalent material. If you address the credential-retention issue in `BasicAuthenticator`, this assertion should be updated to expect an empty/redacted token to prevent accidental propagation of secrets. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
