World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#7926] feat(auth): Add OAuth support for JWKS URLs (#7883)
Bharath Krishnaf644acf4cf65
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 4d6fa790ae..85c1a07427 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -71,6 +71,7 @@ scala-java-compat = "1.0.2"sqlite-jdbc = "3.42.0.0"testcontainers = "1.20.6"jwt = "0.11.1"+nimbus-jose-jwt = "9.37.3"jline = "3.21.0"okhttp3 = "4.11.0"opencsv = "2.3"@@ -238,6 +239,7 @@ trino-jdbc = { group = "io.trino", name = "trino-jdbc", version.ref = "trino" }jwt-api = { group = "io.jsonwebtoken", name = "jjwt-api", version.ref = "jwt"}jwt-impl = { group = "io.jsonwebtoken", name = "jjwt-impl", version.ref = "jwt"}jwt-gson = { group = "io.jsonwebtoken", name = "jjwt-gson", version.ref = "jwt"}+nimbus-jose-jwt = { group = "com.nimbusds", name = "nimbus-jose-jwt", version.ref = "nimbus-jose-jwt"}metrics-core = { group = "io.dropwizard.metrics", name = "metrics-core", version.ref = "metrics" }metrics-jersey2 = { group = "io.dropwizard.metrics", name = "metrics-jersey2", version.ref = "metrics" }metrics-jvm = { group = "io.dropwizard.metrics", name = "metrics-jvm", version.ref = "metrics" }diff --git a/server-common/build.gradle.kts b/server-common/build.gradle.ktsindex 943ff3758e..d209acb9e1 100644--- a/server-common/build.gradle.kts+++ b/server-common/build.gradle.kts@@ -48,6 +48,7 @@ dependencies {}implementation(libs.ognl)implementation(libs.prometheus.servlet)+ implementation(libs.nimbus.jose.jwt)testImplementation(libs.commons.io)testImplementation(libs.junit.jupiter.api)diff --git a/server-common/src/main/java/org/apache/gravitino/server/authentication/JwksTokenValidator.java b/server-common/src/main/java/org/apache/gravitino/server/authentication/JwksTokenValidator.javanew file mode 100644index 0000000000..9c91c54871--- /dev/null+++ b/server-common/src/main/java/org/apache/gravitino/server/authentication/JwksTokenValidator.java@@ -0,0 +1,172 @@+/*+ * 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 com.nimbusds.jose.JWSAlgorithm;+import com.nimbusds.jose.jwk.source.JWKSource;+import com.nimbusds.jose.jwk.source.JWKSourceBuilder;+import com.nimbusds.jose.proc.JWSKeySelector;+import com.nimbusds.jose.proc.JWSVerificationKeySelector;+import com.nimbusds.jose.proc.SecurityContext;+import com.nimbusds.jwt.JWTClaimsSet;+import com.nimbusds.jwt.SignedJWT;+import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier;+import com.nimbusds.jwt.proc.DefaultJWTProcessor;+import java.net.URL;+import java.security.Principal;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.Config;+import org.apache.gravitino.UserPrincipal;+import org.apache.gravitino.exceptions.UnauthorizedException;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Generic JWKS-based OAuth token validator that uses Nimbus JOSE + JWT library to validate JWT+ * tokens from any OAuth provider that exposes a JWKS endpoint.+ *+ * <p>This validator supports OAuth providers that publish their public keys via JWKS (JSON Web Key+ * Set) endpoints+ */+public class JwksTokenValidator implements OAuthTokenValidator {+ private static final Logger LOG = LoggerFactory.getLogger(JwksTokenValidator.class);++ private String jwksUri;+ private String expectedIssuer;+ private String principalField;+ private long allowSkewSeconds;++ @Override+ public void initialize(Config config) {+ this.jwksUri = config.get(OAuthConfig.JWKS_URI);+ this.expectedIssuer = config.get(OAuthConfig.AUTHORITY);+ this.principalField = config.get(OAuthConfig.PRINCIPAL_FIELD);+ this.allowSkewSeconds = config.get(OAuthConfig.ALLOW_SKEW_SECONDS);++ LOG.info("Initializing JWKS token validator");++ if (StringUtils.isBlank(jwksUri)) {+ throw new IllegalArgumentException(+ "JWKS URI must be configured when using JWKS-based OAuth providers");+ }++ // Validate JWKS URI format+ try {+ new URL(jwksUri);+ } catch (Exception e) {+ LOG.error("Invalid JWKS URI format: {}", jwksUri);+ throw new IllegalArgumentException("Invalid JWKS URI format: " + jwksUri, e);+ }+ }++ @Override+ public Principal validateToken(String token, String serviceAudience) {+ if (token == null || token.trim().isEmpty()) {+ LOG.error("Token is null or empty");+ throw new UnauthorizedException("Token cannot be null or empty");+ }++ if (serviceAudience == null || serviceAudience.trim().isEmpty()) {+ LOG.error("Service audience is null or empty");+ throw new UnauthorizedException("Service audience cannot be null or empty");+ }++ try {+ SignedJWT signedJWT = SignedJWT.parse(token);++ // Set up JWKS source and processor+ JWKSource<SecurityContext> jwkSource = createJwkSource();+ JWSAlgorithm algorithm = JWSAlgorithm.parse(signedJWT.getHeader().getAlgorithm().getName());+ JWSKeySelector<SecurityContext> keySelector =+ new JWSVerificationKeySelector<>(algorithm, jwkSource);++ DefaultJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();+ jwtProcessor.setJWSKeySelector(keySelector);++ // Configure claims verification+ JWTClaimsSet.Builder expectedClaimsBuilder = new JWTClaimsSet.Builder();++ // Set expected issuer if configured+ if (StringUtils.isNotBlank(expectedIssuer)) {+ expectedClaimsBuilder.issuer(expectedIssuer);+ }++ // Set expected audience if provided+ if (StringUtils.isNotBlank(serviceAudience)) {+ expectedClaimsBuilder.audience(serviceAudience);+ }++ DefaultJWTClaimsVerifier<SecurityContext> claimsVerifier =+ new DefaultJWTClaimsVerifier<SecurityContext>(expectedClaimsBuilder.build(), null);++ // Set clock skew tolerance+ claimsVerifier.setMaxClockSkew((int) allowSkewSeconds);+ jwtProcessor.setJWTClaimsSetVerifier(claimsVerifier);++ // Process and validate the token+ JWTClaimsSet validatedClaims = jwtProcessor.process(signedJWT, null);++ String principal = extractPrincipal(validatedClaims);+ if (principal == null) {+ LOG.error("No valid principal found in token");+ throw new UnauthorizedException("No valid principal found in token");+ }++ return new UserPrincipal(principal);++ } catch (Exception e) {+ LOG.error("JWKS JWT validation error: {}", e.getMessage());+ throw new UnauthorizedException(e, "JWKS JWT validation error");+ }+ }++ /** Creates a JWK source from the configured JWKS URI. */+ private JWKSource<SecurityContext> createJwkSource() throws Exception {+ try {+ return JWKSourceBuilder.create(new URL(jwksUri)).build();+ } catch (Exception e) {+ LOG.error("Failed to create JWKS source from URI: {}", jwksUri, e);+ throw new Exception("Failed to create JWKS source: " + e.getMessage(), e);+ }+ }++ /** Extracts the principal from the validated JWT claims using configured field or fallbacks. */+ private String extractPrincipal(JWTClaimsSet validatedClaims) {+ // Try the configured principal field first+ if (StringUtils.isNotBlank(principalField)) {+ String principal = (String) validatedClaims.getClaim(principalField);+ if (principal != null) {+ return principal;+ }+ }++ // Fallback to common user identity fields+ // TODO: Consider making this configurable+ String[] fallbackFields = {"unique_name", "upn", "email", "preferred_username", "sub"};+ for (String field : fallbackFields) {+ String principal = (String) validatedClaims.getClaim(field);+ if (principal != null) {+ return principal;+ }+ }++ return null;+ }+}diff --git a/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuth2TokenAuthenticator.java b/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuth2TokenAuthenticator.javaindex c3433cf585..7f2821e411 100644--- a/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuth2TokenAuthenticator.java+++ b/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuth2TokenAuthenticator.java@@ -19,53 +19,57 @@package org.apache.gravitino.server.authentication;import com.google.common.base.Preconditions;-import io.jsonwebtoken.Claims;-import io.jsonwebtoken.ExpiredJwtException;-import io.jsonwebtoken.Jwt;-import io.jsonwebtoken.JwtParser;-import io.jsonwebtoken.Jwts;-import io.jsonwebtoken.MalformedJwtException;-import io.jsonwebtoken.SignatureAlgorithm;-import io.jsonwebtoken.UnsupportedJwtException;-import io.jsonwebtoken.security.Keys;-import io.jsonwebtoken.security.SignatureException;import java.nio.charset.StandardCharsets;-import java.security.Key;-import java.security.KeyFactory;import java.security.Principal;-import java.security.spec.X509EncodedKeySpec;-import java.util.Base64;-import java.util.List;import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.Config;-import org.apache.gravitino.UserPrincipal;import org.apache.gravitino.auth.AuthConstants;-import org.apache.gravitino.auth.SignatureAlgorithmFamilyType;import org.apache.gravitino.exceptions.UnauthorizedException;/**- * OAuth2TokenAuthenticator provides the OAuth 2.0 authentication mechanism.- * OAuth2TokenAuthenticator only supports to validate the format of JWT's Bearer Token.+ * OAuth2TokenAuthenticator provides the OAuth 2.0 authentication support. OAuth2TokenAuthenticator+ * supports pluggable token validators for different validation mechanisms.*/class OAuth2TokenAuthenticator implements Authenticator {+ private static final org.slf4j.Logger LOG =+ org.slf4j.LoggerFactory.getLogger(OAuth2TokenAuthenticator.class);- private long allowSkewSeconds;- private Key defaultSigningKey;private String serviceAudience;+ private OAuthTokenValidator tokenValidator;@Overridepublic boolean isDataFromToken() {return true;}+ @Override+ public void initialize(Config config) throws RuntimeException {+ this.serviceAudience = config.get(OAuthConfig.SERVICE_AUDIENCE);+ Preconditions.checkArgument(+ StringUtils.isNotBlank(serviceAudience),+ "Service audience cannot be blank for OAuth authentication");++ Preconditions.checkArgument(+ StringUtils.isNotBlank(config.get(OAuthConfig.DEFAULT_TOKEN_PATH)),+ "The path for token of the default OAuth server can't be blank");+ Preconditions.checkArgument(+ StringUtils.isNotBlank(config.get(OAuthConfig.DEFAULT_SERVER_URI)),+ "The uri of the default OAuth server can't be blank");++ // Create the appropriate token validator based on configuration+ this.tokenValidator = OAuthTokenValidatorFactory.createValidator(config);+ }+@Overridepublic Principal authenticateToken(byte[] tokenData) {if (tokenData == null) {+ LOG.warn("Empty token authorization header");throw new UnauthorizedException("Empty token authorization header");}String authData = new String(tokenData, StandardCharsets.UTF_8);if (StringUtils.isBlank(authData)|| !authData.startsWith(AuthConstants.AUTHORIZATION_BEARER_HEADER)) {+ LOG.warn("Invalid token authorization header format");throw new UnauthorizedException("Invalid token authorization header");}String token = authData.substring(AuthConstants.AUTHORIZATION_BEARER_HEADER.length());@@ -75,80 +79,20 @@ class OAuth2TokenAuthenticator implements Authenticator {// TODO: If we support multiple OAuth 2.0 servers, we should use multiple// signing keys.try {- JwtParser parser =- Jwts.parserBuilder()- .setAllowedClockSkewSeconds(allowSkewSeconds)- .setSigningKey(defaultSigningKey)- .build();- Jwt<?, Claims> jwt = parser.parseClaimsJws(token);- Object audienceObject = jwt.getBody().get(Claims.AUDIENCE);- if (audienceObject == null) {- throw new UnauthorizedException("Found null Audience in token");- }- if (audienceObject instanceof String) {- if (!serviceAudience.equals(audienceObject)) {- throw new UnauthorizedException(- "Audience in the token [%s] doesn't contain %s", audienceObject, serviceAudience);- }- } else if (audienceObject instanceof List) {- List<Object> audiences = (List<Object>) audienceObject;- if (audiences.stream()- .noneMatch(audienceInToken -> audienceInToken.equals(serviceAudience))) {- throw new UnauthorizedException(- "Audiences in the token %s don't contain %s", audienceObject, serviceAudience);- }- } else {- throw new UnauthorizedException(- "Audiences in token is not in expected format: %s", audienceObject);- }- return new UserPrincipal(jwt.getBody().getSubject());- } catch (ExpiredJwtException- | UnsupportedJwtException- | MalformedJwtException- | SignatureException- | IllegalArgumentException e) {+ return tokenValidator.validateToken(token, serviceAudience);+ } catch (UnauthorizedException e) {+ // Re-throw validation errors (audience, subject, etc.) without wrapping+ throw e;+ } catch (Exception e) {+ LOG.error("JWT parse error: {}", e.getMessage(), e);throw new UnauthorizedException(e, "JWT parse error");}}- @Override- public void initialize(Config config) throws RuntimeException {- this.serviceAudience = config.get(OAuthConfig.SERVICE_AUDIENCE);- this.allowSkewSeconds = config.get(OAuthConfig.ALLOW_SKEW_SECONDS);- String configuredSignKey = config.get(OAuthConfig.DEFAULT_SIGN_KEY);- Preconditions.checkArgument(- StringUtils.isNotBlank(config.get(OAuthConfig.DEFAULT_TOKEN_PATH)),- "The path for token of the default OAuth server can't be blank");- Preconditions.checkArgument(- StringUtils.isNotBlank(config.get(OAuthConfig.DEFAULT_SERVER_URI)),- "The uri of the default OAuth server can't be blank");- String algType = config.get(OAuthConfig.SIGNATURE_ALGORITHM_TYPE);- this.defaultSigningKey = decodeSignKey(Base64.getDecoder().decode(configuredSignKey), algType);- }-@Overridepublic boolean supportsToken(byte[] tokenData) {return tokenData != null&& new String(tokenData, StandardCharsets.UTF_8).startsWith(AuthConstants.AUTHORIZATION_BEARER_HEADER);}-- private static Key decodeSignKey(byte[] key, String algType) {- try {- SignatureAlgorithmFamilyType algFamilyType =- SignatureAlgorithmFamilyType.valueOf(SignatureAlgorithm.valueOf(algType).getFamilyName());-- if (SignatureAlgorithmFamilyType.HMAC == algFamilyType) {- return Keys.hmacShaKeyFor(key);- } else if (SignatureAlgorithmFamilyType.RSA == algFamilyType- || SignatureAlgorithmFamilyType.ECDSA == algFamilyType) {- X509EncodedKeySpec spec = new X509EncodedKeySpec(key);- KeyFactory kf = KeyFactory.getInstance(algFamilyType.name());- return kf.generatePublic(spec);- }- } catch (Exception e) {- throw new IllegalArgumentException("Failed to decode key", e);- }- throw new IllegalArgumentException("Unsupported signature algorithm type: " + algType);- }}diff --git a/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuthConfig.java b/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuthConfig.javaindex e9731f7080..796a31112c 100644--- a/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuthConfig.java+++ b/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuthConfig.java@@ -83,7 +83,7 @@ public interface OAuthConfig {.create();ConfigEntry<String> CLIENT_ID =- new ConfigBuilder(OAUTH_CONFIG_PREFIX + "client-id")+ new ConfigBuilder(OAUTH_CONFIG_PREFIX + "clientId").doc("OAuth client ID used for Web UI authentication").version(ConfigConstants.VERSION_1_0_0).stringConf()@@ -104,9 +104,23 @@ public interface OAuthConfig {.create();ConfigEntry<String> JWKS_URI =- new ConfigBuilder(OAUTH_CONFIG_PREFIX + "jwks-uri")+ new ConfigBuilder(OAUTH_CONFIG_PREFIX + "jwksUri").doc("JWKS URI for token validation").version(ConfigConstants.VERSION_1_0_0).stringConf().create();++ ConfigEntry<String> PRINCIPAL_FIELD =+ new ConfigBuilder(OAUTH_CONFIG_PREFIX + "principalField")+ .doc("JWT claim field to use as principal identity (e.g., 'sub', 'client_id', 'appid')")+ .version(ConfigConstants.VERSION_1_0_0)+ .stringConf()+ .createWithDefault("sub");++ ConfigEntry<String> TOKEN_VALIDATOR_CLASS =+ new ConfigBuilder(OAUTH_CONFIG_PREFIX + "tokenValidatorClass")+ .doc("Fully qualified class name of the OAuth token validator implementation")+ .version(ConfigConstants.VERSION_1_0_0)+ .stringConf()+ .createWithDefault("org.apache.gravitino.server.authentication.StaticSignKeyValidator");}diff --git a/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuthTokenValidator.java b/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuthTokenValidator.javanew file mode 100644index 0000000000..3037ed19ac--- /dev/null+++ b/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuthTokenValidator.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.server.authentication;++import java.security.Principal;+import org.apache.gravitino.Config;++/**+ * Interface for OAuth token validators that can be plugged into the OAuth2TokenAuthenticator.+ * Implementations should handle provider-specific token validation logic.+ */+public interface OAuthTokenValidator {++ /**+ * Initialize the validator with the provided configuration.+ *+ * @param config The configuration object containing OAuth settings+ */+ void initialize(Config config);++ /**+ * Validate the given JWT token and return a Principal if valid.+ *+ * @param token The JWT token to validate+ * @param serviceAudience The expected audience for the token+ * @return A Principal representing the authenticated user+ * @throws org.apache.gravitino.exceptions.UnauthorizedException if token validation fails+ */+ Principal validateToken(String token, String serviceAudience);+}diff --git a/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuthTokenValidatorFactory.java b/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuthTokenValidatorFactory.javanew file mode 100644index 0000000000..f05aac2629--- /dev/null+++ b/server-common/src/main/java/org/apache/gravitino/server/authentication/OAuthTokenValidatorFactory.java@@ -0,0 +1,62 @@+/*+ * 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 org.apache.gravitino.Config;++/**+ * Factory for creating OAuth token validators based on configuration.+ *+ * <p>Creates validators using the {@code tokenValidatorClass} configuration.+ */+public class OAuthTokenValidatorFactory {+ /**+ * Create and initialize a token validator based on configuration.+ *+ * @param config The configuration object+ * @return An initialized OAuthTokenValidator+ * @throws IllegalArgumentException if configuration is invalid+ */+ public static OAuthTokenValidator createValidator(Config config) {+ if (config == null) {+ throw new IllegalArgumentException("Configuration cannot be null");+ }++ String validatorClass = config.get(OAuthConfig.TOKEN_VALIDATOR_CLASS);+ OAuthTokenValidator validator = createValidatorFromClass(validatorClass);++ validator.initialize(config);+ return validator;+ }++ private static OAuthTokenValidator createValidatorFromClass(String className) {+ try {+ Class<?> clazz = Class.forName(className);+ if (!OAuthTokenValidator.class.isAssignableFrom(clazz)) {+ throw new IllegalArgumentException(+ "Class " + className + " does not implement OAuthTokenValidator");+ }+ return (OAuthTokenValidator) clazz.getDeclaredConstructor().newInstance();+ } catch (Exception e) {+ throw new IllegalArgumentException(+ "Failed to create validator instance from class: " + className, e);+ }+ }+}diff --git a/server-common/src/main/java/org/apache/gravitino/server/authentication/StaticSignKeyValidator.java b/server-common/src/main/java/org/apache/gravitino/server/authentication/StaticSignKeyValidator.javanew file mode 100644index 0000000000..c9d477ffda--- /dev/null+++ b/server-common/src/main/java/org/apache/gravitino/server/authentication/StaticSignKeyValidator.java@@ -0,0 +1,128 @@+/*+ * 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 com.google.common.base.Preconditions;+import io.jsonwebtoken.Claims;+import io.jsonwebtoken.ExpiredJwtException;+import io.jsonwebtoken.Jwt;+import io.jsonwebtoken.JwtParser;+import io.jsonwebtoken.Jwts;+import io.jsonwebtoken.MalformedJwtException;+import io.jsonwebtoken.SignatureAlgorithm;+import io.jsonwebtoken.UnsupportedJwtException;+import io.jsonwebtoken.security.Keys;+import io.jsonwebtoken.security.SignatureException;+import java.security.Key;+import java.security.KeyFactory;+import java.security.Principal;+import java.security.spec.X509EncodedKeySpec;+import java.util.Base64;+import java.util.List;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.Config;+import org.apache.gravitino.UserPrincipal;+import org.apache.gravitino.auth.SignatureAlgorithmFamilyType;+import org.apache.gravitino.exceptions.UnauthorizedException;++/**+ * Static OAuth token validator that uses a pre-configured signing key for JWT validation.+ *+ * <p>This validator is designed for JWT validation scenarios where a single signing key is shared+ * between the token issuer and Gravitino. It uses the configured {@code defaultSignKey} and {@code+ * signAlgorithmType} for validation.+ */+public class StaticSignKeyValidator implements OAuthTokenValidator {+ private long allowSkewSeconds;+ private Key defaultSigningKey;++ @Override+ public void initialize(Config config) {+ this.allowSkewSeconds = config.get(OAuthConfig.ALLOW_SKEW_SECONDS);+ String configuredSignKey = config.get(OAuthConfig.DEFAULT_SIGN_KEY);+ Preconditions.checkArgument(+ StringUtils.isNotBlank(config.get(OAuthConfig.DEFAULT_TOKEN_PATH)),+ "The path for token of the default OAuth server can't be blank");+ Preconditions.checkArgument(+ StringUtils.isNotBlank(config.get(OAuthConfig.DEFAULT_SERVER_URI)),+ "The uri of the default OAuth server can't be blank");+ String algType = config.get(OAuthConfig.SIGNATURE_ALGORITHM_TYPE);+ this.defaultSigningKey = decodeSignKey(Base64.getDecoder().decode(configuredSignKey), algType);+ }++ @Override+ public Principal validateToken(String token, String serviceAudience) {+ try {+ JwtParser parser =+ Jwts.parserBuilder()+ .setAllowedClockSkewSeconds(allowSkewSeconds)+ .setSigningKey(defaultSigningKey)+ .build();+ Jwt<?, Claims> jwt = parser.parseClaimsJws(token);+ Object audienceObject = jwt.getBody().get(Claims.AUDIENCE);+ if (audienceObject == null) {+ throw new UnauthorizedException("Found null Audience in token");+ }+ if (audienceObject instanceof String) {+ if (!serviceAudience.equals(audienceObject)) {+ throw new UnauthorizedException(+ "Audience in the token [%s] doesn't contain %s", audienceObject, serviceAudience);+ }+ } else if (audienceObject instanceof List) {+ @SuppressWarnings("unchecked")+ List<Object> audiences = (List<Object>) audienceObject;+ if (audiences.stream()+ .noneMatch(audienceInToken -> audienceInToken.equals(serviceAudience))) {+ throw new UnauthorizedException(+ "Audiences in the token %s don't contain %s", audienceObject, serviceAudience);+ }+ } else {+ throw new UnauthorizedException(+ "Audiences in token is not in expected format: %s", audienceObject);+ }+ return new UserPrincipal(jwt.getBody().getSubject());+ } catch (ExpiredJwtException+ | UnsupportedJwtException+ | MalformedJwtException+ | SignatureException+ | IllegalArgumentException e) {+ throw new UnauthorizedException(e, "JWT parse error");+ }+ }++ private static Key decodeSignKey(byte[] key, String algType) {+ try {+ SignatureAlgorithmFamilyType algFamilyType =+ SignatureAlgorithmFamilyType.valueOf(SignatureAlgorithm.valueOf(algType).getFamilyName());++ if (SignatureAlgorithmFamilyType.HMAC == algFamilyType) {+ return Keys.hmacShaKeyFor(key);+ } else if (SignatureAlgorithmFamilyType.RSA == algFamilyType+ || SignatureAlgorithmFamilyType.ECDSA == algFamilyType) {+ X509EncodedKeySpec spec = new X509EncodedKeySpec(key);+ KeyFactory kf = KeyFactory.getInstance(algFamilyType.name());+ return kf.generatePublic(spec);+ }+ } catch (Exception e) {+ throw new IllegalArgumentException("Failed to decode key", e);+ }+ throw new IllegalArgumentException("Unsupported signature algorithm type: " + algType);+ }+}diff --git a/server-common/src/test/java/org/apache/gravitino/server/authentication/TestJwksTokenValidator.java b/server-common/src/test/java/org/apache/gravitino/server/authentication/TestJwksTokenValidator.javanew file mode 100644index 0000000000..20c3e587d3--- /dev/null+++ b/server-common/src/test/java/org/apache/gravitino/server/authentication/TestJwksTokenValidator.java@@ -0,0 +1,337 @@+/*+ * 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.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.mockStatic;+import static org.mockito.Mockito.when;++import com.nimbusds.jose.JWSAlgorithm;+import com.nimbusds.jose.JWSHeader;+import com.nimbusds.jose.JWSSigner;+import com.nimbusds.jose.crypto.RSASSASigner;+import com.nimbusds.jose.jwk.RSAKey;+import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;+import com.nimbusds.jose.jwk.source.JWKSource;+import com.nimbusds.jose.jwk.source.JWKSourceBuilder;+import com.nimbusds.jose.proc.SecurityContext;+import com.nimbusds.jwt.JWTClaimsSet;+import com.nimbusds.jwt.SignedJWT;+import java.net.URL;+import java.security.Principal;+import java.time.Instant;+import java.util.Arrays;+import java.util.Date;+import java.util.HashMap;+import java.util.Map;+import org.apache.gravitino.Config;+import org.apache.gravitino.UserPrincipal;+import org.apache.gravitino.exceptions.UnauthorizedException;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.mockito.MockedStatic;++public class TestJwksTokenValidator {++ private JwksTokenValidator validator;+ private String serviceAudience = "test-service";+ private String validJwksUri = "https://login.microsoftonline.com/common/discovery/v2.0/keys";++ @BeforeEach+ public void setUp() {+ validator = new JwksTokenValidator();+ }++ private Config createConfig(Map<String, String> properties) {+ Config config = new Config(false) {};+ config.loadFromMap(properties, k -> true);+ return config;+ }++ @Test+ public void testInitializeSuccess() {+ Map<String, String> properties = new HashMap<>();+ properties.put("gravitino.authenticator.oauth.jwksUri", validJwksUri);+ properties.put("gravitino.authenticator.oauth.authority", "https://login.microsoftonline.com");+ properties.put("gravitino.authenticator.oauth.principalField", "sub");+ properties.put("gravitino.authenticator.oauth.allowSkewSecs", "60");++ validator.initialize(createConfig(properties));+ // Should not throw exception+ }++ @Test+ public void testInitializeWithoutJwksUri() {+ Map<String, String> config = new HashMap<>();+ config.put("gravitino.authenticator.oauth.authority", "https://login.microsoftonline.com");++ assertThrows(IllegalArgumentException.class, () -> validator.initialize(createConfig(config)));+ }++ @Test+ public void testInitializeWithInvalidJwksUri() {+ Map<String, String> config = new HashMap<>();+ config.put("gravitino.authenticator.oauth.jwksUri", "invalid-url");++ assertThrows(IllegalArgumentException.class, () -> validator.initialize(createConfig(config)));+ }++ @Test+ public void testValidateNullToken() {+ Map<String, String> config = new HashMap<>();+ config.put("gravitino.authenticator.oauth.jwksUri", validJwksUri);+ validator.initialize(createConfig(config));++ assertThrows(UnauthorizedException.class, () -> validator.validateToken(null, serviceAudience));+ }++ @Test+ public void testValidateEmptyToken() {+ Map<String, String> config = new HashMap<>();+ config.put("gravitino.authenticator.oauth.jwksUri", validJwksUri);+ validator.initialize(createConfig(config));++ assertThrows(UnauthorizedException.class, () -> validator.validateToken("", serviceAudience));+ }++ @Test+ public void testCustomPrincipalField() throws Exception {+ // Generate a test RSA key pair+ RSAKey rsaKey =+ new RSAKeyGenerator(2048).keyID("test-key-id").algorithm(JWSAlgorithm.RS256).generate();++ // Create a signed JWT token with custom principal field+ JWTClaimsSet claimsSet =+ new JWTClaimsSet.Builder()+ .subject("default-subject")+ .claim("client_id", "custom-client-123") // This should be used as principal+ .claim("email", "[email protected]")+ .audience("test-service")+ .issuer("https://test-issuer.com")+ .expirationTime(Date.from(Instant.now().plusSeconds(3600)))+ .issueTime(Date.from(Instant.now()))+ .build();++ SignedJWT signedJWT =+ new SignedJWT(+ new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("test-key-id").build(), claimsSet);++ JWSSigner signer = new RSASSASigner(rsaKey);+ signedJWT.sign(signer);++ String tokenString = signedJWT.serialize();++ // Mock the JWKSourceBuilder to return our test key+ try (MockedStatic<JWKSourceBuilder> mockedBuilder = mockStatic(JWKSourceBuilder.class)) {+ @SuppressWarnings("unchecked")+ JWKSource<SecurityContext> mockJwkSource = mock(JWKSource.class);+ @SuppressWarnings("unchecked")+ JWKSourceBuilder<SecurityContext> mockBuilder = mock(JWKSourceBuilder.class);++ mockedBuilder.when(() -> JWKSourceBuilder.create(any(URL.class))).thenReturn(mockBuilder);+ when(mockBuilder.build()).thenReturn(mockJwkSource);++ // Configure the mock to return our test key+ when(mockJwkSource.get(any(), any())).thenReturn(Arrays.asList(rsaKey));++ // Initialize validator with custom principal field+ Map<String, String> config = new HashMap<>();+ config.put(+ "gravitino.authenticator.oauth.jwksUri", "https://test-jwks.com/.well-known/jwks.json");+ config.put("gravitino.authenticator.oauth.authority", "https://test-issuer.com");+ config.put(+ "gravitino.authenticator.oauth.principalField",+ "client_id"); // Use client_id instead of default 'sub'+ config.put("gravitino.authenticator.oauth.allowSkewSecs", "120");++ validator.initialize(createConfig(config));+ Principal result = validator.validateToken(tokenString, "test-service");++ assertNotNull(result);+ assertEquals("custom-client-123", result.getName()); // Should be client_id value, not subject+ assertEquals(UserPrincipal.class, result.getClass());+ }+ }++ @Test+ public void testPrincipalFieldFallback() throws Exception {+ // Generate a test RSA key pair+ RSAKey rsaKey =+ new RSAKeyGenerator(2048).keyID("test-key-id").algorithm(JWSAlgorithm.RS256).generate();++ // Create a signed JWT token without the configured principal field, but with fallback fields+ JWTClaimsSet claimsSet =+ new JWTClaimsSet.Builder()+ .subject("fallback-subject")+ .claim("email", "[email protected]") // This should be used as fallback+ .audience("test-service")+ .issuer("https://test-issuer.com")+ .expirationTime(Date.from(Instant.now().plusSeconds(3600)))+ .issueTime(Date.from(Instant.now()))+ .build();++ SignedJWT signedJWT =+ new SignedJWT(+ new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("test-key-id").build(), claimsSet);++ JWSSigner signer = new RSASSASigner(rsaKey);+ signedJWT.sign(signer);++ String tokenString = signedJWT.serialize();++ // Mock the JWKSourceBuilder to return our test key+ try (MockedStatic<JWKSourceBuilder> mockedBuilder = mockStatic(JWKSourceBuilder.class)) {+ @SuppressWarnings("unchecked")+ JWKSource<SecurityContext> mockJwkSource = mock(JWKSource.class);+ @SuppressWarnings("unchecked")+ JWKSourceBuilder<SecurityContext> mockBuilder = mock(JWKSourceBuilder.class);++ mockedBuilder.when(() -> JWKSourceBuilder.create(any(URL.class))).thenReturn(mockBuilder);+ when(mockBuilder.build()).thenReturn(mockJwkSource);++ // Configure the mock to return our test key+ when(mockJwkSource.get(any(), any())).thenReturn(Arrays.asList(rsaKey));++ // Initialize validator with principal field that doesn't exist in token+ Map<String, String> config = new HashMap<>();+ config.put(+ "gravitino.authenticator.oauth.jwksUri", "https://test-jwks.com/.well-known/jwks.json");+ config.put("gravitino.authenticator.oauth.authority", "https://test-issuer.com");+ config.put(+ "gravitino.authenticator.oauth.principalField",+ "non_existent_field"); // This field doesn't exist+ config.put("gravitino.authenticator.oauth.allowSkewSecs", "120");++ validator.initialize(createConfig(config));++ // Test token validation - should fall back to 'email' field (which is in fallback list)+ Principal result = validator.validateToken(tokenString, "test-service");++ assertNotNull(result);+ assertEquals("[email protected]", result.getName()); // Should use email as fallback+ assertEquals(UserPrincipal.class, result.getClass());+ }+ }++ @Test+ public void testValidateTokenWithMockJwks() throws Exception {+ // Generate a test RSA key pair+ RSAKey rsaKey =+ new RSAKeyGenerator(2048).keyID("test-key-id").algorithm(JWSAlgorithm.RS256).generate();++ // Create a signed JWT token+ JWTClaimsSet claimsSet =+ new JWTClaimsSet.Builder()+ .subject("test-user")+ .audience("test-service")+ .issuer("https://test-issuer.com")+ .expirationTime(Date.from(Instant.now().plusSeconds(3600)))+ .issueTime(Date.from(Instant.now()))+ .build();++ SignedJWT signedJWT =+ new SignedJWT(+ new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("test-key-id").build(), claimsSet);++ JWSSigner signer = new RSASSASigner(rsaKey);+ signedJWT.sign(signer);++ String tokenString = signedJWT.serialize();++ // Mock the JWKSourceBuilder to return our test key+ try (MockedStatic<JWKSourceBuilder> mockedBuilder = mockStatic(JWKSourceBuilder.class)) {+ @SuppressWarnings("unchecked")+ JWKSource<SecurityContext> mockJwkSource = mock(JWKSource.class);+ @SuppressWarnings("unchecked")+ JWKSourceBuilder<SecurityContext> mockBuilder = mock(JWKSourceBuilder.class);++ mockedBuilder.when(() -> JWKSourceBuilder.create(any(URL.class))).thenReturn(mockBuilder);+ when(mockBuilder.build()).thenReturn(mockJwkSource);++ // Configure the mock to return our test key+ when(mockJwkSource.get(any(), any())).thenReturn(Arrays.asList(rsaKey));++ // Initialize validator+ Map<String, String> config = new HashMap<>();+ config.put(+ "gravitino.authenticator.oauth.jwksUri", "https://test-jwks.com/.well-known/jwks.json");+ config.put("gravitino.authenticator.oauth.authority", "https://test-issuer.com");+ config.put("gravitino.authenticator.oauth.principalField", "sub");+ config.put("gravitino.authenticator.oauth.allowSkewSecs", "60");++ validator.initialize(createConfig(config));++ // Test token validation+ Principal result = validator.validateToken(tokenString, "test-service");++ assertNotNull(result);+ assertEquals("test-user", result.getName());+ }+ }++ @Test+ public void testValidateTokenWithInvalidToken() {+ Map<String, String> config = new HashMap<>();+ config.put("gravitino.authenticator.oauth.jwksUri", validJwksUri);+ validator.initialize(createConfig(config));++ // Test with malformed JWT+ assertThrows(+ UnauthorizedException.class,+ () -> validator.validateToken("invalid.jwt.token", "test-service"));+ }++ @Test+ public void testValidateTokenWithNullAudience() {+ Map<String, String> config = new HashMap<>();+ config.put("gravitino.authenticator.oauth.jwksUri", validJwksUri);+ validator.initialize(createConfig(config));++ assertThrows(+ UnauthorizedException.class, () -> validator.validateToken("some.jwt.token", null));+ }++ @Test+ public void testPostInitializationState() {+ Map<String, String> properties = new HashMap<>();+ properties.put("gravitino.authenticator.oauth.jwksUri", validJwksUri);+ properties.put("gravitino.authenticator.oauth.authority", "https://login.microsoftonline.com");+ properties.put("gravitino.authenticator.oauth.principalField", "custom_field");+ properties.put("gravitino.authenticator.oauth.allowSkewSecs", "300");++ validator.initialize(createConfig(properties));++ // After initialization, the validator should be ready to validate tokens+ // We can test this by trying to validate a token and checking the error type+ UnauthorizedException exception =+ assertThrows(+ UnauthorizedException.class,+ () -> validator.validateToken("invalid.token", "test-service"));++ // The exception should indicate JWT parsing/validation error, not initialization error+ assertNotNull(exception.getMessage());+ // The message should not contain "not initialized" or similar+ assertEquals(true, exception.getMessage().toLowerCase().contains("jwt"));+ }+}diff --git a/server-common/src/test/java/org/apache/gravitino/server/authentication/TestOAuth2TokenAuthenticator.java b/server-common/src/test/java/org/apache/gravitino/server/authentication/TestOAuth2TokenAuthenticator.javaindex 0f7e718a4f..080ceb439b 100644--- a/server-common/src/test/java/org/apache/gravitino/server/authentication/TestOAuth2TokenAuthenticator.java+++ b/server-common/src/test/java/org/apache/gravitino/server/authentication/TestOAuth2TokenAuthenticator.java@@ -18,6 +18,11 @@*/package org.apache.gravitino.server.authentication;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import com.google.common.collect.Lists;import com.google.common.collect.Maps;import io.jsonwebtoken.Claims;@@ -26,14 +31,15 @@ import io.jsonwebtoken.SignatureAlgorithm;import io.jsonwebtoken.impl.DefaultClaims;import io.jsonwebtoken.security.Keys;import java.nio.charset.StandardCharsets;+import java.security.Key;import java.security.KeyPair;+import java.security.Principal;import java.util.Base64;import java.util.Date;import java.util.Map;import org.apache.gravitino.Config;import org.apache.gravitino.auth.AuthConstants;import org.apache.gravitino.exceptions.UnauthorizedException;-import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;@SuppressWarnings("JavaUtilDate")@@ -48,31 +54,31 @@ public class TestOAuth2TokenAuthenticator {Base64.getEncoder().encode(keyPair.getPublic().getEncoded()), StandardCharsets.UTF_8);Config config = new Config(false) {};config.set(OAuthConfig.SERVICE_AUDIENCE, "service1");- Assertions.assertThrows(- IllegalArgumentException.class, () -> auth2TokenAuthenticator.initialize(config));+ assertThrows(IllegalArgumentException.class, () -> auth2TokenAuthenticator.initialize(config));config.set(OAuthConfig.DEFAULT_SIGN_KEY, publicKey);+ config.set(OAuthConfig.SIGNATURE_ALGORITHM_TYPE, "RS256");config.set(OAuthConfig.ALLOW_SKEW_SECONDS, 6L);config.set(OAuthConfig.DEFAULT_TOKEN_PATH, "test");config.set(OAuthConfig.DEFAULT_SERVER_URI, "test");auth2TokenAuthenticator.initialize(config);- Assertions.assertTrue(auth2TokenAuthenticator.isDataFromToken());+ assertTrue(auth2TokenAuthenticator.isDataFromToken());Exception e =- Assertions.assertThrows(+ assertThrows(UnauthorizedException.class, () -> auth2TokenAuthenticator.authenticateToken(null));- Assertions.assertEquals("Empty token authorization header", e.getMessage());+ assertEquals("Empty token authorization header", e.getMessage());byte[] bytes = "Xx".getBytes(StandardCharsets.UTF_8);e =- Assertions.assertThrows(+ assertThrows(UnauthorizedException.class, () -> auth2TokenAuthenticator.authenticateToken(bytes));- Assertions.assertEquals("Invalid token authorization header", e.getMessage());+ assertEquals("Invalid token authorization header", e.getMessage());byte[] bytes2 = AuthConstants.AUTHORIZATION_BEARER_HEADER.getBytes(StandardCharsets.UTF_8);e =- Assertions.assertThrows(+ assertThrows(UnauthorizedException.class,() -> {auth2TokenAuthenticator.authenticateToken(bytes2);});- Assertions.assertEquals("Blank token found", e.getMessage());+ assertEquals("Blank token found", e.getMessage());String token1 =Jwts.builder().setSubject("gravitino")@@ -82,12 +88,12 @@ public class TestOAuth2TokenAuthenticator {String header1 = AuthConstants.AUTHORIZATION_BEARER_HEADER + token1;byte[] bytes3 = header1.getBytes(StandardCharsets.UTF_8);e =- Assertions.assertThrows(+ assertThrows(UnauthorizedException.class,() -> {auth2TokenAuthenticator.authenticateToken(bytes3);});- Assertions.assertEquals("Found null Audience in token", e.getMessage());+ assertEquals("Found null Audience in token", e.getMessage());String token2 =Jwts.builder()@@ -99,10 +105,9 @@ public class TestOAuth2TokenAuthenticator {String header2 = AuthConstants.AUTHORIZATION_BEARER_HEADER + token2;byte[] bytes4 = header2.getBytes(StandardCharsets.UTF_8);e =- Assertions.assertThrows(+ assertThrows(UnauthorizedException.class, () -> auth2TokenAuthenticator.authenticateToken(bytes4));- Assertions.assertEquals(- "Audience in the token [xxxx] doesn't contain service1", e.getMessage());+ assertEquals("Audience in the token [xxxx] doesn't contain service1", e.getMessage());Claims audienceClaims = new DefaultClaims();audienceClaims.put(Claims.AUDIENCE, Lists.newArrayList("x1", "x2", "x3"));@@ -116,10 +121,9 @@ public class TestOAuth2TokenAuthenticator {String header3 = AuthConstants.AUTHORIZATION_BEARER_HEADER + token3;byte[] bytes5 = header3.getBytes(StandardCharsets.UTF_8);e =- Assertions.assertThrows(+ assertThrows(UnauthorizedException.class, () -> auth2TokenAuthenticator.authenticateToken(bytes5));- Assertions.assertEquals(- "Audiences in the token [x1, x2, x3] don't contain service1", e.getMessage());+ assertEquals("Audiences in the token [x1, x2, x3] don't contain service1", e.getMessage());audienceClaims = new DefaultClaims();Map<String, String> map = Maps.newHashMap();@@ -136,10 +140,9 @@ public class TestOAuth2TokenAuthenticator {String header4 = AuthConstants.AUTHORIZATION_BEARER_HEADER + token4;byte[] bytes6 = header4.getBytes(StandardCharsets.UTF_8);e =- Assertions.assertThrows(+ assertThrows(UnauthorizedException.class, () -> auth2TokenAuthenticator.authenticateToken(bytes6));- Assertions.assertEquals(- "Audiences in token is not in expected format: {k1=v1, k2=v2}", e.getMessage());+ assertEquals("Audiences in token is not in expected format: {k1=v1, k2=v2}", e.getMessage());String token5 =Jwts.builder()@@ -148,7 +151,7 @@ public class TestOAuth2TokenAuthenticator {.setAudience("service1").signWith(keyPair.getPrivate(), SignatureAlgorithm.RS256).compact();- Assertions.assertEquals(+ assertEquals("gravitino",auth2TokenAuthenticator.authenticateToken(@@ -156,4 +159,112 @@ public class TestOAuth2TokenAuthenticator {.getBytes(StandardCharsets.UTF_8)).getName());}++ @Test+ public void testInitializeWithBlankServiceAudience() {+ OAuth2TokenAuthenticator authenticator = new OAuth2TokenAuthenticator();+ Config config = new Config(false) {};+ config.set(OAuthConfig.SERVICE_AUDIENCE, "");+ Key tempKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);+ config.set(+ OAuthConfig.DEFAULT_SIGN_KEY, Base64.getEncoder().encodeToString(tempKey.getEncoded()));+ config.set(OAuthConfig.DEFAULT_TOKEN_PATH, "/token");+ config.set(OAuthConfig.DEFAULT_SERVER_URI, "http://localhost:8080");++ assertThrows(IllegalArgumentException.class, () -> authenticator.initialize(config));+ }++ @Test+ public void testInitializeWithJwksConfiguration() {+ OAuth2TokenAuthenticator authenticator = new OAuth2TokenAuthenticator();++ Config config = new Config(false) {};+ config.set(OAuthConfig.SERVICE_AUDIENCE, "test-service");+ config.set(+ OAuthConfig.JWKS_URI, "https://login.microsoftonline.com/common/discovery/v2.0/keys");+ config.set(OAuthConfig.AUTHORITY, "https://login.microsoftonline.com");+ config.set(OAuthConfig.DEFAULT_TOKEN_PATH, "/token");+ config.set(OAuthConfig.DEFAULT_SERVER_URI, "http://localhost:8080");+ config.set(+ OAuthConfig.TOKEN_VALIDATOR_CLASS,+ "org.apache.gravitino.server.authentication.JwksTokenValidator");++ // Should initialize with JWKS validator+ authenticator.initialize(config);+ assertTrue(authenticator.isDataFromToken());+ }++ @Test+ public void testSupportsToken() {+ OAuth2TokenAuthenticator authenticator = new OAuth2TokenAuthenticator();++ // Test valid Bearer token+ String bearerToken = AuthConstants.AUTHORIZATION_BEARER_HEADER + "some-token";+ byte[] tokenData = bearerToken.getBytes(StandardCharsets.UTF_8);+ assertTrue(authenticator.supportsToken(tokenData));++ // Test invalid token format+ String basicToken = "Basic some-token";+ byte[] basicTokenData = basicToken.getBytes(StandardCharsets.UTF_8);+ assertTrue(!authenticator.supportsToken(basicTokenData));++ // Test null token+ assertTrue(!authenticator.supportsToken(null));++ // Test empty token data+ assertTrue(!authenticator.supportsToken(new byte[0]));+ }++ @Test+ public void testAuthenticateWithMultipleAudiencesIncludingCorrect() {+ OAuth2TokenAuthenticator authenticator = new OAuth2TokenAuthenticator();+ KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);+ String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());++ Config config = new Config(false) {};+ config.set(OAuthConfig.SERVICE_AUDIENCE, "service1");+ config.set(OAuthConfig.DEFAULT_SIGN_KEY, publicKey);+ config.set(OAuthConfig.SIGNATURE_ALGORITHM_TYPE, "RS256");+ config.set(OAuthConfig.DEFAULT_TOKEN_PATH, "/token");+ config.set(OAuthConfig.DEFAULT_SERVER_URI, "http://localhost:8080");++ authenticator.initialize(config);++ Claims claims = new DefaultClaims();+ claims.put(Claims.AUDIENCE, Lists.newArrayList("other1", "service1", "other2"));+ String token =+ Jwts.builder()+ .setClaims(claims)+ .setSubject("test-user") // Set subject AFTER claims to avoid overwriting+ .setExpiration(new Date(System.currentTimeMillis() + 100000))+ .signWith(keyPair.getPrivate(), SignatureAlgorithm.RS256)+ .compact();++ String bearerToken = AuthConstants.AUTHORIZATION_BEARER_HEADER + token;+ byte[] tokenData = bearerToken.getBytes(StandardCharsets.UTF_8);++ Principal principal = authenticator.authenticateToken(tokenData);+ assertNotNull(principal);+ assertEquals("test-user", principal.getName());+ }++ @Test+ public void testAuthenticateWithEmptyTokenAfterBearer() {+ OAuth2TokenAuthenticator authenticator = new OAuth2TokenAuthenticator();+ Config config = new Config(false) {};+ config.set(OAuthConfig.SERVICE_AUDIENCE, "service1");+ Key tempKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);+ config.set(+ OAuthConfig.DEFAULT_SIGN_KEY, Base64.getEncoder().encodeToString(tempKey.getEncoded()));+ config.set(OAuthConfig.SIGNATURE_ALGORITHM_TYPE, "HS256");+ config.set(OAuthConfig.DEFAULT_TOKEN_PATH, "/token");+ config.set(OAuthConfig.DEFAULT_SERVER_URI, "http://localhost:8080");++ authenticator.initialize(config);++ String bearerToken = AuthConstants.AUTHORIZATION_BEARER_HEADER + " ";+ byte[] tokenData = bearerToken.getBytes(StandardCharsets.UTF_8);++ assertThrows(UnauthorizedException.class, () -> authenticator.authenticateToken(tokenData));+ }}diff --git a/server-common/src/test/java/org/apache/gravitino/server/authentication/TestOAuthTokenValidatorFactory.java b/server-common/src/test/java/org/apache/gravitino/server/authentication/TestOAuthTokenValidatorFactory.javanew file mode 100644index 0000000000..f9fca1ca7d--- /dev/null+++ b/server-common/src/test/java/org/apache/gravitino/server/authentication/TestOAuthTokenValidatorFactory.java@@ -0,0 +1,160 @@+/*+* Licensed to the Apache Software Foundation (ASF) under one+* or mor props.put(+ "gravitino.authenticator.oauth.tokenValidatorClass",+ "org.apache.gravitino.server.authentication.DefaultSignKeyValidator");++ Config config = createConfig(props);+ OAuthTokenValidator validator = OAuthTokenValidatorFactory.createValidator(config);+ assertNotNull(validator);+ assertTrue(validator instanceof DefaultSignKeyValidator);butor 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.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++import io.jsonwebtoken.SignatureAlgorithm;+import io.jsonwebtoken.security.Keys;+import java.security.Key;+import java.util.Base64;+import java.util.HashMap;+import java.util.Map;+import org.apache.gravitino.Config;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++public class TestOAuthTokenValidatorFactory {++ private String validSignKey;++ @BeforeEach+ public void setUp() {+ // Generate a secure key that meets JJWT requirements (256+ bits for HS256)+ Key hmacKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);+ validSignKey = Base64.getEncoder().encodeToString(hmacKey.getEncoded());+ }++ private Config createConfig(Map<String, String> properties) {+ Config config = new Config(false) {};+ config.loadFromMap(properties, k -> true);+ return config;+ }++ @Test+ public void testCreateDefaultValidator() {+ Map<String, String> props = new HashMap<>();+ props.put("gravitino.authenticator.oauth.serviceAudience", "test-audience");+ props.put("gravitino.authenticator.oauth.defaultSignKey", validSignKey);+ props.put("gravitino.authenticator.oauth.signAlgorithmType", "HS256");+ props.put("gravitino.authenticator.oauth.tokenPath", "/token");+ props.put("gravitino.authenticator.oauth.serverUri", "http://localhost:8080");++ Config config = createConfig(props);+ OAuthTokenValidator validator = OAuthTokenValidatorFactory.createValidator(config);+ assertNotNull(validator);+ assertTrue(validator instanceof StaticSignKeyValidator);+ }++ @Test+ public void testCreateJwksValidator() {+ Map<String, String> props = new HashMap<>();+ props.put("gravitino.authenticator.oauth.serviceAudience", "test-audience");+ props.put(+ "gravitino.authenticator.oauth.jwksUri",+ "https://login.microsoftonline.com/common/discovery/v2.0/keys");+ props.put(+ "gravitino.authenticator.oauth.tokenValidatorClass",+ "org.apache.gravitino.server.authentication.JwksTokenValidator");++ Config config = createConfig(props);+ OAuthTokenValidator validator = OAuthTokenValidatorFactory.createValidator(config);+ assertNotNull(validator);+ assertTrue(validator instanceof JwksTokenValidator);+ }++ @Test+ public void testCreateValidatorWithNullConfig() {+ assertThrows(+ IllegalArgumentException.class, () -> OAuthTokenValidatorFactory.createValidator(null));+ }++ @Test+ public void testJwksTakesPrecedenceOverDefaultKey() {+ Map<String, String> props = new HashMap<>();+ props.put("gravitino.authenticator.oauth.serviceAudience", "test-audience");+ props.put("gravitino.authenticator.oauth.defaultSignKey", validSignKey);+ props.put(+ "gravitino.authenticator.oauth.jwksUri",+ "https://login.microsoftonline.com/common/discovery/v2.0/keys");+ props.put(+ "gravitino.authenticator.oauth.tokenValidatorClass",+ "org.apache.gravitino.server.authentication.JwksTokenValidator");++ Config config = createConfig(props);+ // Should use JWKS validator since it's explicitly configured+ OAuthTokenValidator validator = OAuthTokenValidatorFactory.createValidator(config);+ assertNotNull(validator);+ assertTrue(validator instanceof JwksTokenValidator);+ }++ @Test+ public void testExplicitValidatorClassTakesPrecedence() {+ Map<String, String> props = new HashMap<>();+ props.put("gravitino.authenticator.oauth.serviceAudience", "test-audience");+ props.put("gravitino.authenticator.oauth.defaultSignKey", validSignKey);+ props.put("gravitino.authenticator.oauth.signAlgorithmType", "HS256");+ props.put("gravitino.authenticator.oauth.tokenPath", "/token");+ props.put("gravitino.authenticator.oauth.serverUri", "http://localhost:8080");+ props.put(+ "gravitino.authenticator.oauth.jwksUri",+ "https://login.microsoftonline.com/common/discovery/v2.0/keys");+ props.put(+ "gravitino.authenticator.oauth.tokenValidatorClass",+ "org.apache.gravitino.server.authentication.StaticSignKeyValidator");++ Config config = createConfig(props);+ // Should use explicit class even though JWKS URI is configured+ OAuthTokenValidator validator = OAuthTokenValidatorFactory.createValidator(config);+ assertNotNull(validator);+ assertTrue(validator instanceof StaticSignKeyValidator);+ }++ @Test+ public void testInvalidValidatorClass() {+ Map<String, String> props = new HashMap<>();+ props.put("gravitino.authenticator.oauth.serviceAudience", "test-audience");+ props.put("gravitino.authenticator.oauth.tokenValidatorClass", "com.invalid.NonExistentClass");++ Config config = createConfig(props);+ assertThrows(+ IllegalArgumentException.class, () -> OAuthTokenValidatorFactory.createValidator(config));+ }++ @Test+ public void testValidatorClassNotImplementingInterface() {+ Map<String, String> props = new HashMap<>();+ props.put("gravitino.authenticator.oauth.serviceAudience", "test-audience");+ props.put("gravitino.authenticator.oauth.tokenValidatorClass", "java.lang.String");++ Config config = createConfig(props);+ assertThrows(+ IllegalArgumentException.class, () -> OAuthTokenValidatorFactory.createValidator(config));+ }+}diff --git a/server-common/src/test/java/org/apache/gravitino/server/authentication/TestStaticSignKeyValidator.java b/server-common/src/test/java/org/apache/gravitino/server/authentication/TestStaticSignKeyValidator.javanew file mode 100644index 0000000000..827265612d--- /dev/null+++ b/server-common/src/test/java/org/apache/gravitino/server/authentication/TestStaticSignKeyValidator.java@@ -0,0 +1,231 @@+/*+ * 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.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;++import io.jsonwebtoken.Jwts;+import io.jsonwebtoken.SignatureAlgorithm;+import io.jsonwebtoken.security.Keys;+import java.security.Key;+import java.security.Principal;+import java.time.Instant;+import java.util.Arrays;+import java.util.Base64;+import java.util.Date;+import java.util.HashMap;+import java.util.Map;+import org.apache.gravitino.Config;+import org.apache.gravitino.exceptions.UnauthorizedException;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++public class TestStaticSignKeyValidator {++ private StaticSignKeyValidator validator;+ private Key hmacKey;+ private String serviceAudience = "test-service";++ @BeforeEach+ public void setUp() {+ validator = new StaticSignKeyValidator();+ hmacKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);+ }++ private Config createConfig(Map<String, String> properties) {+ Config config = new Config(false) {};+ config.loadFromMap(properties, k -> true);+ return config;+ }++ private Map<String, String> createBaseConfig() {+ Map<String, String> config = new HashMap<>();+ config.put(+ "gravitino.authenticator.oauth.defaultSignKey",+ Base64.getEncoder().encodeToString(hmacKey.getEncoded()));+ config.put("gravitino.authenticator.oauth.signAlgorithmType", "HS256");+ config.put("gravitino.authenticator.oauth.allowSkewSecs", "60");+ // Add required configuration parameters+ config.put("gravitino.authenticator.oauth.serverUri", "http://localhost:8080");+ config.put("gravitino.authenticator.oauth.tokenPath", "/oauth/token");+ return config;+ }++ @Test+ public void testInitializeSuccess() {+ Map<String, String> config = createBaseConfig();++ validator.initialize(createConfig(config));+ // Should not throw exception+ }++ @Test+ public void testInitializeWithMissingSignKey() {+ Map<String, String> config = new HashMap<>();+ config.put("gravitino.authenticator.oauth.signAlgorithmType", "HS256");+ config.put("gravitino.authenticator.oauth.serverUri", "http://localhost:8080");+ config.put("gravitino.authenticator.oauth.tokenPath", "/oauth/token");++ assertThrows(IllegalArgumentException.class, () -> validator.initialize(createConfig(config)));+ }++ @Test+ public void testValidateValidToken() {+ Map<String, String> config = createBaseConfig();+ validator.initialize(createConfig(config));++ // Create valid token+ String token =+ Jwts.builder()+ .setSubject("test-user")+ .setAudience(serviceAudience)+ .setIssuedAt(Date.from(Instant.now()))+ .setExpiration(Date.from(Instant.now().plusSeconds(3600)))+ .signWith(hmacKey, SignatureAlgorithm.HS256)+ .compact();++ Principal principal = validator.validateToken(token, serviceAudience);+ assertNotNull(principal);+ assertEquals("test-user", principal.getName());+ }++ @Test+ public void testValidateTokenWithMultipleAudiences() {+ Map<String, String> config = createBaseConfig();+ validator.initialize(createConfig(config));++ // Create token with multiple audiences+ String token =+ Jwts.builder()+ .setSubject("test-user")+ .claim("aud", Arrays.asList("other-service", serviceAudience, "another-service"))+ .setIssuedAt(Date.from(Instant.now()))+ .setExpiration(Date.from(Instant.now().plusSeconds(3600)))+ .signWith(hmacKey, SignatureAlgorithm.HS256)+ .compact();++ Principal principal = validator.validateToken(token, serviceAudience);+ assertNotNull(principal);+ assertEquals("test-user", principal.getName());+ }++ @Test+ public void testValidateTokenWithWrongAudience() {+ // Setup validator+ Map<String, String> config = createBaseConfig();+ validator.initialize(createConfig(config));++ // Create token with wrong audience+ String token =+ Jwts.builder()+ .setSubject("test-user")+ .setAudience("wrong-audience")+ .setIssuedAt(Date.from(Instant.now()))+ .setExpiration(Date.from(Instant.now().plusSeconds(3600)))+ .signWith(hmacKey, SignatureAlgorithm.HS256)+ .compact();++ assertThrows(+ UnauthorizedException.class, () -> validator.validateToken(token, serviceAudience));+ }++ @Test+ public void testValidateTokenWithNoAudience() {+ // Setup validator+ Map<String, String> config = createBaseConfig();+ validator.initialize(createConfig(config));++ // Create token without audience+ String token =+ Jwts.builder()+ .setSubject("test-user")+ .setIssuedAt(Date.from(Instant.now()))+ .setExpiration(Date.from(Instant.now().plusSeconds(3600)))+ .signWith(hmacKey, SignatureAlgorithm.HS256)+ .compact();++ assertThrows(+ UnauthorizedException.class, () -> validator.validateToken(token, serviceAudience));+ }++ @Test+ public void testValidateExpiredToken() {+ // Setup validator+ Map<String, String> config = createBaseConfig();+ validator.initialize(createConfig(config));++ // Create expired token+ String token =+ Jwts.builder()+ .setSubject("test-user")+ .setAudience(serviceAudience)+ .setIssuedAt(Date.from(Instant.now().minusSeconds(7200)))+ .setExpiration(Date.from(Instant.now().minusSeconds(3600)))+ .signWith(hmacKey, SignatureAlgorithm.HS256)+ .compact();++ assertThrows(+ UnauthorizedException.class, () -> validator.validateToken(token, serviceAudience));+ }++ @Test+ public void testValidateNullToken() {+ // Setup validator+ Map<String, String> config = createBaseConfig();+ validator.initialize(createConfig(config));++ assertThrows(UnauthorizedException.class, () -> validator.validateToken(null, serviceAudience));+ }++ @Test+ public void testValidateMalformedToken() {+ // Setup validator+ Map<String, String> config = createBaseConfig();+ validator.initialize(createConfig(config));++ // JsonSyntaxException is thrown for malformed tokens due to Gson parsing+ assertThrows(+ com.google.gson.JsonSyntaxException.class,+ () -> validator.validateToken("invalid.jwt.token", serviceAudience));+ }++ @Test+ public void testValidateTokenWithWrongSignature() {+ // Setup validator+ Map<String, String> config = createBaseConfig();+ validator.initialize(createConfig(config));++ // Create token with different key+ Key differentKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);+ String token =+ Jwts.builder()+ .setSubject("test-user")+ .setAudience(serviceAudience)+ .setIssuedAt(Date.from(Instant.now()))+ .setExpiration(Date.from(Instant.now().plusSeconds(3600)))+ .signWith(differentKey, SignatureAlgorithm.HS256)+ .compact();++ assertThrows(+ UnauthorizedException.class, () -> validator.validateToken(token, serviceAudience));+ }+}