From 946e756b0e68b00dae19c1c9c45e514137379bba Mon Sep 17 00:00:00 2001 From: Vishnu Jain <121681876+Vishnuujain@users.noreply.github.com> Date: Fri, 26 Jun 2026 20:55:20 +0530 Subject: [PATCH] fix: bypass domain enforcement for OM-internally-issued tokens (#29433) * fix: bypass domain enforcement for OM-internally-issued tokens * review: fix comment accuracy and short-circuit bypass when enforcement disabled * refactor: eliminate redundant JWT decode in JwtFilter hot path --- .../service/security/JwtFilter.java | 69 +++++++++--- .../service/security/SecurityUtil.java | 23 ++++ .../security/jwt/JWTTokenGenerator.java | 4 +- .../service/security/JwtFilterTest.java | 105 +++++++++++++++++- .../service/security/SecurityUtilTest.java | 33 ++++++ 5 files changed, 213 insertions(+), 21 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/JwtFilter.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/JwtFilter.java index d62c3ca7bfd0..83e950a9944c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/JwtFilter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/JwtFilter.java @@ -65,6 +65,7 @@ import org.openmetadata.service.security.auth.BotTokenCache; import org.openmetadata.service.security.auth.CatalogSecurityContext; import org.openmetadata.service.security.auth.UserTokenCache; +import org.openmetadata.service.security.jwt.JWTTokenGenerator; import org.openmetadata.service.security.saml.JwtTokenCacheManager; @Slf4j @@ -163,9 +164,10 @@ public void filter(ContainerRequestContext requestContext) { ImpersonationContext.clear(); try { String tokenFromHeader = extractToken(requestContext.getHeaders()); - LOG.debug("Token from header:{}", tokenFromHeader); - - Map claims = validateJwtAndGetClaims(tokenFromHeader); + LOG.debug("Authorization header present: {}", !nullOrEmpty(tokenFromHeader)); + DecodedJWT decodedJwt = decodeAndVerify(tokenFromHeader); + String tokenKeyId = decodedJwt.getKeyId(); + Map claims = extractClaims(decodedJwt); String userName = findUserNameFromClaims(jwtPrincipalClaimsMapping, jwtPrincipalClaims, claims); String email = @@ -184,7 +186,7 @@ public void filter(ContainerRequestContext requestContext) { userName = impersonateUser; } - checkValidationsForToken(claims, tokenFromHeader, userName, impersonatedBy); + checkValidationsForToken(claims, tokenFromHeader, tokenKeyId, userName, impersonatedBy); CatalogPrincipal catalogPrincipal = new CatalogPrincipal(userName, email); String scheme = requestContext.getUriInfo().getRequestUri().getScheme(); @@ -211,17 +213,40 @@ public void filter(ContainerRequestContext requestContext) { public void checkValidationsForToken( Map claims, String tokenFromHeader, String userName, String impersonatedBy) { + String tokenKeyId = null; + try { + tokenKeyId = JWT.decode(tokenFromHeader).getKeyId(); + } catch (JWTDecodeException e) { + LOG.debug("Unable to read key id from token during OpenMetadata issuer check", e); + } + checkValidationsForToken(claims, tokenFromHeader, tokenKeyId, userName, impersonatedBy); + } + + private void checkValidationsForToken( + Map claims, + String tokenFromHeader, + String tokenKeyId, + String userName, + String impersonatedBy) { // the case where OMD generated the Token for the Client in case OM generated Token validateTokenIsNotUsedAfterLogout(tokenFromHeader); - // Validate Domain - validateDomainEnforcement( - jwtPrincipalClaimsMapping, - jwtPrincipalClaims, - claims, - principalDomain, - allowedDomains, - enforcePrincipalDomain); + // OM-issued tokens (PATs, session tokens, user tokens) set preferred_username to the bare + // username without an @domain suffix, which causes getFirstMatchJwtClaim-based domain + // extraction to return an empty domain and fail enforcement. Since OM owns the user identity + // these tokens are trusted and domain enforcement is skipped — consistent with how bot tokens + // are already handled (validateDomainEnforcement returns early for isBot=true tokens). + // The isInternallyIssuedToken check is guarded by enforcePrincipalDomain to avoid the + // singleton lookup on deployments where enforcement is disabled. + if (enforcePrincipalDomain && !isInternallyIssuedToken(claims, tokenKeyId)) { + validateDomainEnforcement( + jwtPrincipalClaimsMapping, + jwtPrincipalClaims, + claims, + principalDomain, + allowedDomains, + enforcePrincipalDomain); + } // Validate Bot token matches what was created in OM // Skip validation for impersonation tokens - they are generated dynamically and not stored in @@ -234,6 +259,12 @@ public void checkValidationsForToken( validatePersonalAccessToken(claims, tokenFromHeader, userName); } + private boolean isInternallyIssuedToken(Map claims, String tokenKeyId) { + JWTTokenGenerator tokenGenerator = JWTTokenGenerator.getInstance(); + return SecurityUtil.isOpenMetadataIssuedToken( + claims, tokenKeyId, tokenGenerator.getIssuer(), tokenGenerator.getKid()); + } + private Set getUserRolesFromClaims(Map claims, boolean isBot) { Set userRoles = new HashSet<>(); // Re-sync user roles from token @@ -248,7 +279,11 @@ private Set getUserRolesFromClaims(Map claims, boolean is @SneakyThrows public Map validateJwtAndGetClaims(String token) { - // Decode JWT Token + return extractClaims(decodeAndVerify(token)); + } + + @SneakyThrows + private DecodedJWT decodeAndVerify(String token) { DecodedJWT jwt; try { jwt = JWT.decode(token); @@ -256,14 +291,11 @@ public Map validateJwtAndGetClaims(String token) { throw AuthenticationException.getInvalidTokenException("Invalid token."); } - // Check if expired - // If expiresAt is set to null, treat it as never expiring token if (jwt.getExpiresAt() != null && jwt.getExpiresAt().before(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime())) { throw AuthenticationException.getExpiredTokenException(); } - // Validate JWT with public key Jwk jwk = jwkProvider.get(jwt.getKeyId()); Algorithm algorithm = createAlgorithmFromJwk(tokenValidationAlgorithm, jwk); try { @@ -273,9 +305,12 @@ public Map validateJwtAndGetClaims(String token) { "Invalid token. Token verification failed. Public key mismatch.", runtimeException); } + return jwt; + } + + private static Map extractClaims(DecodedJWT jwt) { Map claims = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); claims.putAll(jwt.getClaims()); - return claims; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/SecurityUtil.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/SecurityUtil.java index fb4bfb5fbcbd..d48f3cc37d0e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/SecurityUtil.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/SecurityUtil.java @@ -46,6 +46,7 @@ @Slf4j public final class SecurityUtil { public static final String DEFAULT_PRINCIPAL_DOMAIN = "openmetadata.org"; + public static final String ISSUER_CLAIM = "iss"; private SecurityUtil() {} @@ -390,4 +391,26 @@ public static boolean isBotW(Map claims) { Claim isBotClaim = (Claim) claims.get("isBot"); return isBotClaim != null && Boolean.TRUE.equals(isBotClaim.asBoolean()); } + + /** + * Returns true only when the token was provably minted by OpenMetadata itself. A token qualifies + * when its key id matches OpenMetadata's own signing key id and its issuer matches OpenMetadata's + * configured issuer. The key id is the trust anchor: the signature has already been verified + * against the public key served for that key id, so a matching key id proves OpenMetadata's + * private key produced the signature - an external identity provider cannot forge it. The issuer + * check is defense in depth against a key id collision in a multi-source JWK provider. + */ + public static boolean isOpenMetadataIssuedToken( + Map claims, + String tokenKeyId, + String openMetadataIssuer, + String openMetadataKeyId) { + boolean issuedByOpenMetadata = false; + if (!nullOrEmpty(openMetadataIssuer) && !nullOrEmpty(openMetadataKeyId)) { + boolean keyIdMatches = openMetadataKeyId.equals(tokenKeyId); + boolean issuerMatches = openMetadataIssuer.equals(getClaimOrObject(claims.get(ISSUER_CLAIM))); + issuedByOpenMetadata = keyIdMatches && issuerMatches; + } + return issuedByOpenMetadata; + } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/jwt/JWTTokenGenerator.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/jwt/JWTTokenGenerator.java index 10e622b8d6df..6542ceea02a7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/jwt/JWTTokenGenerator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/jwt/JWTTokenGenerator.java @@ -61,8 +61,8 @@ public class JWTTokenGenerator { private static final JWTTokenGenerator INSTANCE = new JWTTokenGenerator(); private RSAPrivateKey privateKey; @Getter private RSAPublicKey publicKey; - private String issuer; - private String kid; + @Getter private String issuer; + @Getter private String kid; private AuthenticationConfiguration.TokenValidationAlgorithm tokenValidationAlgorithm; private JWTTokenGenerator() { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/JwtFilterTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/JwtFilterTest.java index 25412609252c..f60f69892706 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/security/JwtFilterTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/JwtFilterTest.java @@ -46,7 +46,9 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; import org.openmetadata.schema.auth.ServiceTokenType; +import org.openmetadata.service.security.jwt.JWTTokenGenerator; class JwtFilterTest { @@ -54,16 +56,20 @@ class JwtFilterTest { private static JwkProvider jwkProvider; private static Algorithm algorithm; + private static RSAPublicKey publicKey; private static UriInfo mockRequestURIInfo; + private static final String OM_ISSUER = "open-metadata.org"; + private static final String OM_KEY_ID = "om-signing-key"; + @BeforeAll static void before() throws Exception { // Create a RSA256 algorithm wth random public/private key pair KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); - algorithm = - Algorithm.RSA256((RSAPublicKey) keyPair.getPublic(), (RSAPrivateKey) keyPair.getPrivate()); + publicKey = (RSAPublicKey) keyPair.getPublic(); + algorithm = Algorithm.RSA256(publicKey, (RSAPrivateKey) keyPair.getPrivate()); // Mock a JwkProvider that has a single JWK containing the public key from the algorithm above // This is used to verify the JWT @@ -253,6 +259,101 @@ void testPersonalAccessTokenClaimIsValidated() { assertTrue(exception.getMessage().toLowerCase(Locale.ROOT).contains("personal access token")); } + @Test + void openMetadataIssuedTokenBypassesDomainEnforcement() throws Exception { + JwtFilter enforcingFilter = newEnforcingFilterForKeyId(OM_KEY_ID); + String jwt = + JWT.create() + .withKeyId(OM_KEY_ID) + .withIssuer(OM_ISSUER) + .withExpiresAt(Date.from(Instant.now().plus(1, ChronoUnit.DAYS))) + .withClaim("sub", "asmith") + .withClaim("email", "asmith@intermedia.com") + .withClaim(TOKEN_TYPE, ServiceTokenType.OM_USER.value()) + .sign(algorithm); + ContainerRequestContext context = createRequestContextWithJwt(jwt); + + try (MockedStatic generator = + org.mockito.Mockito.mockStatic( + JWTTokenGenerator.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { + JWTTokenGenerator instance = mock(JWTTokenGenerator.class); + when(instance.getIssuer()).thenReturn(OM_ISSUER); + when(instance.getKid()).thenReturn(OM_KEY_ID); + generator.when(JWTTokenGenerator::getInstance).thenReturn(instance); + + enforcingFilter.filter(context); + } + + verify(context, times(1)) + .setSecurityContext(org.mockito.ArgumentMatchers.any(SecurityContext.class)); + } + + @Test + void externalTokenStillEnforcedWhenServerHasNoSigningIdentity() throws Exception { + JwtFilter enforcingFilter = newEnforcingFilterForKeyId(OM_KEY_ID); + String jwt = + JWT.create() + .withKeyId(OM_KEY_ID) + .withIssuer(OM_ISSUER) + .withExpiresAt(Date.from(Instant.now().plus(1, ChronoUnit.DAYS))) + .withClaim("email", "asmith@intermedia.com") + .sign(algorithm); + ContainerRequestContext context = createRequestContextWithJwt(jwt); + + try (MockedStatic generator = + org.mockito.Mockito.mockStatic( + JWTTokenGenerator.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { + JWTTokenGenerator instance = mock(JWTTokenGenerator.class); + when(instance.getIssuer()).thenReturn(null); + when(instance.getKid()).thenReturn(null); + generator.when(JWTTokenGenerator::getInstance).thenReturn(instance); + + Exception exception = + assertThrows(AuthenticationException.class, () -> enforcingFilter.filter(context)); + assertTrue( + exception + .getMessage() + .toLowerCase(Locale.ROOT) + .contains("email does not match the principal domain")); + } + } + + @Test + void spoofedOpenMetadataKeyIdWithoutMatchingSignatureIsRejected() throws Exception { + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(2048); + KeyPair attackerKeyPair = keyPairGenerator.generateKeyPair(); + Algorithm attackerAlgorithm = + Algorithm.RSA256( + (RSAPublicKey) attackerKeyPair.getPublic(), + (RSAPrivateKey) attackerKeyPair.getPrivate()); + + String jwt = + JWT.create() + .withKeyId(OM_KEY_ID) + .withIssuer(OM_ISSUER) + .withExpiresAt(Date.from(Instant.now().plus(1, ChronoUnit.DAYS))) + .withClaim("sub", "asmith") + .withClaim("email", "asmith@intermedia.com") + .withClaim(TOKEN_TYPE, ServiceTokenType.OM_USER.value()) + .sign(attackerAlgorithm); + JwtFilter enforcingFilter = newEnforcingFilterForKeyId(OM_KEY_ID); + ContainerRequestContext context = createRequestContextWithJwt(jwt); + + Exception exception = + assertThrows(AuthenticationException.class, () -> enforcingFilter.filter(context)); + assertTrue( + exception.getMessage().toLowerCase(Locale.ROOT).contains("token verification failed")); + } + + private static JwtFilter newEnforcingFilterForKeyId(String keyId) throws Exception { + Jwk jwk = mock(Jwk.class); + when(jwk.getPublicKey()).thenReturn(publicKey); + JwkProvider keyIdAwareProvider = mock(JwkProvider.class); + when(keyIdAwareProvider.get(keyId)).thenReturn(jwk); + return new JwtFilter(keyIdAwareProvider, List.of("sub", "email"), OM_ISSUER, true); + } + /** * Creates the ContainerRequestsContext that is passed to the filter. This object can be quite complex, but the * JwtFilter cares only about the Authorization header and request URI. diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/SecurityUtilTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/SecurityUtilTest.java index 877adff73dbc..ee903002d138 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/security/SecurityUtilTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/SecurityUtilTest.java @@ -441,6 +441,39 @@ void testValidateDomainEnforcementRejectsInvalidClaimsAndDomains() { assertTrue(invalidDomainException.getMessage().contains("principal domain example.com")); } + @Test + void testIsOpenMetadataIssuedTokenRequiresMatchingIssuerAndKeyId() { + Map claims = Map.of(SecurityUtil.ISSUER_CLAIM, stringClaim("open-metadata.org")); + + assertTrue( + SecurityUtil.isOpenMetadataIssuedToken(claims, "om-key", "open-metadata.org", "om-key")); + + assertFalse( + SecurityUtil.isOpenMetadataIssuedToken( + claims, "attacker-key", "open-metadata.org", "om-key")); + + assertFalse( + SecurityUtil.isOpenMetadataIssuedToken( + Map.of(SecurityUtil.ISSUER_CLAIM, stringClaim("evil.com")), + "om-key", + "open-metadata.org", + "om-key")); + + assertFalse( + SecurityUtil.isOpenMetadataIssuedToken(Map.of(), "om-key", "open-metadata.org", "om-key")); + } + + @Test + void testIsOpenMetadataIssuedTokenFalseWhenServerHasNoSigningIdentity() { + Map spoofed = + Map.of(SecurityUtil.ISSUER_CLAIM, stringClaim("open-metadata.org")); + + assertFalse(SecurityUtil.isOpenMetadataIssuedToken(spoofed, "om-key", null, "om-key")); + assertFalse( + SecurityUtil.isOpenMetadataIssuedToken(spoofed, "om-key", "open-metadata.org", null)); + assertFalse(SecurityUtil.isOpenMetadataIssuedToken(spoofed, "om-key", "", "")); + } + @Test void testWriteJsonResponseSetsBodyHeadersAndStatus() throws IOException { HttpServletResponse response = mock(HttpServletResponse.class);