Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -163,9 +164,10 @@ public void filter(ContainerRequestContext requestContext) {
ImpersonationContext.clear();
try {
String tokenFromHeader = extractToken(requestContext.getHeaders());
LOG.debug("Token from header:{}", tokenFromHeader);

Map<String, Claim> claims = validateJwtAndGetClaims(tokenFromHeader);
LOG.debug("Authorization header present: {}", !nullOrEmpty(tokenFromHeader));
DecodedJWT decodedJwt = decodeAndVerify(tokenFromHeader);
String tokenKeyId = decodedJwt.getKeyId();
Map<String, Claim> claims = extractClaims(decodedJwt);
String userName =
findUserNameFromClaims(jwtPrincipalClaimsMapping, jwtPrincipalClaims, claims);
String email =
Expand All @@ -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();
Expand All @@ -211,17 +213,40 @@ public void filter(ContainerRequestContext requestContext) {

public void checkValidationsForToken(
Map<String, Claim> 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);
}
Comment on lines 214 to +223

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Public overload re-decodes JWT without signature verification

The backward-compat public checkValidationsForToken(4-arg) calls JWT.decode(tokenFromHeader).getKeyId() — this is a raw, unverified decode. In all current callers (SocketAddressFilter.validatePrefixedTokenRequest and checkForUsernameAndImpersonationValidation), the claims and token already come from the same signature-verified source, so the behavior is correct today. But the method signature makes no guarantee that tokenFromHeader and claims correspond to the same JWT, and a future caller that passes mismatched arguments would silently get a wrong key-ID match result — meaning the bypass either fires when it shouldn't, or doesn't fire when it should, depending on which token carries the OM key ID. A Javadoc note asserting the contract (claims must be extracted from the same already-verified tokenFromHeader) would prevent this footgun.


private void checkValidationsForToken(
Map<String, Claim> 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
Expand All @@ -234,6 +259,12 @@ public void checkValidationsForToken(
validatePersonalAccessToken(claims, tokenFromHeader, userName);
}

private boolean isInternallyIssuedToken(Map<String, Claim> claims, String tokenKeyId) {
JWTTokenGenerator tokenGenerator = JWTTokenGenerator.getInstance();
return SecurityUtil.isOpenMetadataIssuedToken(
claims, tokenKeyId, tokenGenerator.getIssuer(), tokenGenerator.getKid());
}

private Set<String> getUserRolesFromClaims(Map<String, Claim> claims, boolean isBot) {
Set<String> userRoles = new HashSet<>();
// Re-sync user roles from token
Expand All @@ -248,22 +279,23 @@ private Set<String> getUserRolesFromClaims(Map<String, Claim> claims, boolean is

@SneakyThrows
public Map<String, Claim> validateJwtAndGetClaims(String token) {
// Decode JWT Token
return extractClaims(decodeAndVerify(token));
}

@SneakyThrows
private DecodedJWT decodeAndVerify(String token) {
DecodedJWT jwt;
try {
jwt = JWT.decode(token);
} catch (JWTDecodeException e) {
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 {
Expand All @@ -273,9 +305,12 @@ public Map<String, Claim> validateJwtAndGetClaims(String token) {
"Invalid token. Token verification failed. Public key mismatch.", runtimeException);
}

return jwt;
}

private static Map<String, Claim> extractClaims(DecodedJWT jwt) {
Map<String, Claim> claims = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
claims.putAll(jwt.getClaims());

return claims;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() {}

Expand Down Expand Up @@ -390,4 +391,26 @@ public static boolean isBotW(Map<String, ?> 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<String, Claim> 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,30 @@
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 {

private static JwtFilter jwtFilter;
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
Expand Down Expand Up @@ -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<JWTTokenGenerator> 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<JWTTokenGenerator> 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,39 @@ void testValidateDomainEnforcementRejectsInvalidClaimsAndDomains() {
assertTrue(invalidDomainException.getMessage().contains("principal domain example.com"));
}

@Test
void testIsOpenMetadataIssuedTokenRequiresMatchingIssuerAndKeyId() {
Map<String, Claim> 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<String, Claim> 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);
Expand Down
Loading