Skip to content

Fixes #29142: mint IdP-shaped principal claims in JWTTokenGenerator - #33725

Merged
mohityadav766 merged 4 commits into
mainfrom
fix/29142-jwt-preferred-username-domain
Sep 22, 2026
Merged

mohityadav766 merged 4 commits into
mainfrom
fix/29142-jwt-preferred-username-domain

Conversation

@mohityadav766

@mohityadav766 mohityadav766 commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

Describe your changes:

Fixes #29142

OpenMetadata-issued tokens (PATs, bot tokens, session/OM_USER tokens) carried preferred_username as the bare username, while identity providers put the login / UPN email there (Okta login, Azure UPN). Every token is then resolved through the deployment's jwtPrincipalClaims / jwtPrincipalClaimsMapping, so our own tokens resolved differently from the IdP's token for the same user:

  • domain enforcement: getFirstMatchJwtClaim-based extraction found no @ → empty domain → rejected (the ticket's scenario; fix: bypass domain enforcement for OM-internally-issued tokens #29433 papered over this with an OM-issued-token bypass);
  • email: an order starting at preferred_username — the UI's default for Azure is ['preferred_username', 'email', 'upn', 'sub'] — synthesized name@principalDomain, contradicting the user's real email and making /users/loggedInUser fail with "Account already exists" when principalDomain ≠ the user's email domain;
  • provider-specific mappings (email:upn, email:mail, …): the claim is absent from our tokens altogether → AuthenticationException, every PAT rejected.

JWTTokenGenerator now mints identity claims shaped the way the configured resolution reads them, so a token we issue resolves to exactly the (name, email) the IdP's token yields for that user:

claim before after
sub, username bare name bare name (unchanged — stable subject) — unless the claim order reads one of them first, see below
email email email (omitted when the user has none, instead of JSON null)
preferred_username bare name email (bare name only when there is no email)
mapped username:<claim> not minted bare name
mapped email:<claim> not minted email (wins if both map onto one claim — as in the IdP's token)
first claim of jwtPrincipalClaims (upn, unique_name, … — and sub/username when they come first) not minted / bare email

JWTTokenGenerator.init() now takes the whole AuthenticationConfiguration (was: just the TokenValidationAlgorithm) so the generator sees the principal-claim config — and stays in sync on runtime SSO reload, since reinitializeAuthSystem already re-calls init. All four production callers and four test callers are updated. Downstream callers of init() need the same one-line change.

JwtFilter: comment-only. The #29433 enforcement bypass for OM-issued tokens is kept — unlimited-expiry bot tokens minted before this change still carry a bare preferred_username; it can be dropped once those are rotated.

Type of change:

  • Bug fix

High-level design:

Approach. Fix at the source: make our minted claims consistent with what the IdP emits, driven by the same jwtPrincipalClaims / jwtPrincipalClaimsMapping the filter resolves with. identityClaims() builds the fixed set (sub, username, email, preferred_username); putConfiguredPrincipalClaims() adds whatever the configuration reads that we would not otherwise emit. Identity claims are applied to the builder first, so the fixed claims (roles, isBot, tokenType, iss, …) always win on a name collision.

Alternatives rejected.

  • Special-casing OM-issued tokens in SecurityUtil/JwtFilter resolution (read our own claims when kid+issuer prove the token is ours). Works, but it is a second identity-resolution path and a hack around the real mismatch; also has to be replicated in SocketAddressFilter.
  • Only setting preferred_username = email. Fixes the order-based cases in one line but not mappings onto provider-specific claims.

Backward compatibility / rollout. Forward-only: existing tokens keep their old shape and keep working under the default order as today (the enforcement bypass covers them). Under the default order sub/username are unchanged, so nothing keyed on the subject moves. An order that reads sub or username first gets the email there too (review follow-up): a deployment resolving principals from sub first has an IdP whose sub is the email-shaped login, so mirroring it is the consistent choice — and nothing in openmetadata-service/openmetadata-mcp reads sub/username from our tokens directly (InternalActionTokenSigner mints and reads its own tokens).

Downstream. maven-collate-ci builds Collate main against this PR's sha, and Collate's SupportAwareAuthenticatorTest still called init(TokenValidationAlgorithm, JWTTokenConfiguration). The old signature is kept as a @Deprecated(forRemoval = true) shim that delegates with an AuthenticationConfiguration holding only the algorithm (and warns that no principal-claim configuration was supplied), so this check is green and Collate main keeps compiling when this merges. Paired Collate PR moving that test to the new signature: open-metadata/openmetadata-collate#6771 (draft; merge after this). The shim can be removed once it lands.

Tests:

Use cases covered

  • PAT / session token for a user whose username ≠ email local part (mohit / [email protected]) resolves to the right user under the default claim order.
  • Azure-style order [preferred_username, email, upn, sub] (the UI default): our token resolves to the real email and passes principal-domain enforcement on the real domain.
  • Claim mapping onto provider-specific claims (username:upn, email:mail): our token carries them and resolves.
  • Order starting with a claim we did not previously emit (unique_name): minted, so first-match lands on an email.
  • username and email mapped onto the same claim: the email wins.
  • Order starting with sub ([sub, email]): sub carries the email, username stays bare, resolution and enforcement pass.
  • User without an email: bare name stands in, token still resolves.

Unit tests

  • I added unit tests for the new/changed logic.
  • Files updated: JWTTokenGeneratorTest (8 new tests, incl. one for the deprecated shim — each mints a real token and resolves it through the real SecurityUtil.findUserNameFromClaims / findEmailFromClaims / validateDomainEnforcement with the same configuration; no mocks), InternalActionTokenSignerTest, SocketAddressFilterTest, SocketAddressFilterSpoofRevalidationBypassTest (new init() signature).
  • Red before green (fix reverted): mintedIdentityClaimsMirrorProviderShape → expected: <[email protected]> but was: <mohit>; …UnderPreferredUsernameOrder → expected: <[email protected]> but was: <[email protected]>; mintedTokenCarriesMappedProviderClaims → AuthenticationException: 'username' claim is not present; …FirstConfiguredClaimWhenNotMapped fails on the synthesized email.
  • Coverage (mvn -P static-code-analysis test jacoco:report, security suite — 257 tests, 0 failures): changed methods identityClaims 9/9 lines, putConfiguredPrincipalClaims 10/10, init 24/26 (the two misses are the pre-existing key-loading catch). JWTTokenGenerator.java overall 68.3 % line — the remainder is pre-existing untested code (generateImpersonationToken — no callers —, getJWKSResponse, getTokenExpiryFromJWT, RS-384/512 and EC branches, expiry cases), left out of scope.

Backend integration tests

  • Not applicable (no API changes). Existing ITs authenticate with generated PATs / bot tokens under the default claim order and exercise the new claim shape end-to-end.

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

Manual testing performed

No local stack was run for this PR; verification is the round-trip unit tests above (real signing, real resolution code). To reproduce the ticket by hand:

  1. Configure jwtPrincipalClaims: [preferred_username, email, sub], principalDomain: open-metadata.org, enforcePrincipalDomain: true; create user mohit with email [email protected].
  2. Log in, create a PAT, decode it: preferred_username should be [email protected] (was mohit).
  3. GET /api/v1/users/loggedInUser with the PAT → 200 and the user's real email (was 400 "Account already exists", or 401 with enforcement before fix: bypass domain enforcement for OM-internally-issued tokens #29433).

UI screen recording / screenshots:

Not applicable.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR title is Fixes <issue-number>: <short explanation>
  • My PR is linked to a GitHub issue via Fixes #<issue-number> above.
  • I have commented on my code, particularly in hard-to-understand areas.
  • For JSON Schema changes: not applicable — no schema changes.
  • For UI changes: not applicable — no UI changes.
  • I have added tests (unit / integration / Playwright as applicable) and listed them above.

Bug fix

🤖 Generated with Claude Code

RetriggerConfidence Score: 5/5

The PR appears safe to merge; no outstanding correctness, security, or repository-rule issue was identified.

Summary

This PR aligns identity claims in OpenMetadata-issued JWTs with the deployment’s configured principal-claim resolution.

  • Passes the complete authentication configuration into JWTTokenGenerator, including during runtime reloads.
  • Emits email-shaped first-priority and provider-specific mapped claims while retaining bare stable identity claims where applicable.
  • Preserves the former initialization signature as a deprecated downstream compatibility overload.
  • Adds round-trip tests for custom claim orders, mappings, missing email addresses, shared mapped claims, and compatibility behavior.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
    A[AuthenticationConfiguration] --> B[JWTTokenGenerator.init]
    B --> C[Principal claim order and mapping]
    D[User name and email] --> E[identityClaims]
    C --> E
    E --> F[Signed OpenMetadata JWT]
    F --> G[SecurityUtil claim resolution]
    G --> H[Resolved user name and email]
    G --> I[Principal-domain validation]
Loading

Reviews (4) · Last reviewed commit: "Keep a deprecated algorithm-only init ov..."

OM-issued tokens (PATs, bot and session tokens) carried preferred_username
as the bare username, while identity providers put the login/UPN email
there. Run through the deployment's jwtPrincipalClaims /
jwtPrincipalClaimsMapping, our own tokens resolved to an empty domain under
principal-domain enforcement and to a synthesized name@principalDomain
email that contradicted the user's real one; a mapping onto a
provider-specific claim (upn, mail, ...) rejected them outright.

JWTTokenGenerator now mints identity claims shaped the way the configured
resolution reads them: preferred_username carries the email, the mapped
username/email claims are minted, and the first configured order claim is
minted when we would not otherwise emit it. init() takes the whole
AuthenticationConfiguration so the claim configuration follows runtime
security-config reloads.

Co-Authored-By: Claude Opus 5 <[email protected]>
@github-actions

github-actions Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

The linked issue has a description and all required Shipping project fields set. Thanks!

@github-actions github-actions Bot added backend safe to test Add this label to run secure Github workflows on PRs labels Sep 21, 2026
@github-actions

github-actions Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

✅ Playwright Results — workflow succeeded

Validated commit 0eab853fe69bb7509c05df90fe535919761ac29e in Playwright run 35653146490, attempt 3.

✅ 4538 passed · ❌ 0 failed · 🟡 7 flaky · ⏭️ 1 skipped · 🧰 0 lifecycle flaky

Performance

Blocking targets: ✅ met · Optimization targets: 🟡 in progress

Shard-job maxima below are not the full workflow wall time; the linked run includes build, fixture, planning, and reporting.

🕒 Full workflow signal wall (to summary) 6h 48m 2s

⏱️ Max setup 4m 34s · max shard execution 22m 37s · max shard-job elapsed before upload 26m 36s · reporting 20s

🌐 224.86 requests/attempt · 2.23 app boots/UI scenario · 37.95% common-shard skew

Optimization targets still in progress:

  • Common shard skew was 37.95% (convergence target: at most 15%).
  • Browser traffic was 224.86 requests per attempt (convergence target: fewer than 200).
  • Application boot ratio was 2.23 per UI scenario (10771 boots / 4835 scenarios; convergence target: at most 1).
Shard Passed Failed Flaky Skipped Lifecycle failed Lifecycle flaky
✅ Shard advanced-search-01 130 0 0 0 0 0
✅ Shard chromium-01 159 0 0 0 0 0
✅ Shard chromium-02 141 0 0 0 0 0
✅ Shard chromium-03 167 0 0 0 0 0
🟡 Shard chromium-04 178 0 1 0 0 0
🟡 Shard chromium-05 154 0 1 0 0 0
✅ Shard chromium-06 167 0 0 0 0 0
✅ Shard chromium-07 163 0 0 0 0 0
🟡 Shard chromium-08 190 0 1 0 0 0
✅ Shard chromium-09 188 0 0 0 0 0
✅ Shard chromium-10 196 0 0 0 0 0
✅ Shard chromium-11 183 0 0 0 0 0
🟡 Shard chromium-12 156 0 3 0 0 0
✅ Shard chromium-13 168 0 0 0 0 0
✅ Shard chromium-14 187 0 0 0 0 0
✅ Shard chromium-15 179 0 0 0 0 0
✅ Shard chromium-16 161 0 0 0 0 0
✅ Shard chromium-17 159 0 0 0 0 0
✅ Shard chromium-18 180 0 0 0 0 0
🟡 Shard chromium-19 156 0 1 0 0 0
✅ Shard chromium-20 159 0 0 0 0 0
✅ Shard chromium-21 178 0 0 0 0 0
✅ Shard chromium-22 197 0 0 0 0 0
✅ Shard chromium-23 197 0 0 1 0 0
✅ Shard data-asset-rules-01 65 0 0 0 0 0
✅ Shard domain-isolation-01 16 0 0 0 0 0
✅ Shard global-state-01 34 0 0 0 0 0
✅ Shard import-export-01 51 0 0 0 0 0
✅ Shard import-export-02 99 0 0 0 0 0
✅ Shard ingestion-01 40 0 0 0 0 0
✅ Shard ingestion-02 59 0 0 0 0 0
✅ Shard reindex-01 40 0 0 0 0 0
✅ Shard search-01 12 0 0 0 0 0
✅ Shard search-rbac-01 29 0 0 0 0 0
🟡 7 flaky test(s) (passed on retry)
  • Flow/CustomizeWidgets.spec.ts › KPI Widget (shard chromium-04, 1 retry)
  • Pages/ServiceEntity.spec.ts › Tier Add, Update and Remove (shard chromium-05, 1 retry)
  • Flow/NotificationAlerts.spec.ts › Single Filter Alert (shard chromium-08, 1 retry)
  • Features/UserProfileOnlineStatus.spec.ts › Should show online status badge on user profile for active users (shard chromium-12, 1 retry)
  • Features/UserProfileOnlineStatus.spec.ts › Should not show online status for inactive users (shard chromium-12, 1 retry)
  • Features/AccessControlSettings.spec.ts › should show all 4 landing cards and navigate to each panel (shard chromium-12, 1 retry)
  • Pages/ExplorePageRightPanel_KnowledgeCenter.spec.ts › Should remove user owner for knowledgeCenter (shard chromium-19, 1 retry)

📦 Download artifacts

How to debug locally
# Download playwright-test-results-<shard> artifact and unzip
npx playwright show-trace path/to/trace.zip    # view trace

mohityadav766 and others added 2 commits September 21, 2026 23:39
… or username

Review follow-up on #33725: with putIfAbsent, an order such as [sub, email]
left sub as the bare name, so the first-match resolver synthesized
name@principalDomain and domain enforcement saw an empty domain - the
original bug for that configuration. A deployment that resolves principals
from sub first has an identity provider whose sub is the email-shaped
login, so our token mirrors that too.

Co-Authored-By: Claude Opus 5 <[email protected]>
openmetadata-collate's SupportAwareAuthenticatorTest still initialises the
generator with init(TokenValidationAlgorithm, JWTTokenConfiguration). The
maven-collate-ci check builds Collate main against this PR, so without the
old signature it is red here and Collate main stops compiling the moment
this merges. The overload delegates to the new init with a configuration
that holds only the algorithm and warns that no principal-claim
configuration was supplied. Remove once the paired Collate test migration
is merged.

Co-Authored-By: Claude Opus 5 <[email protected]>
@gitar-bot

gitar-bot Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Code Review ✅ Approved

🔴 High risk · JWT claim generation changes authentication identity resolution across issued tokens

Fixes JWT principal claims minting to mirror the configured identity-provider shape, ensuring OpenMetadata-issued tokens (PATs, bot tokens, session tokens) resolve consistently with IdP tokens for the same user. JWTTokenGenerator now reads the full AuthenticationConfiguration to emit email-shaped preferred_username and first-priority claims per the deployment's jwtPrincipalClaims order and mappings, resolving issues with domain enforcement, email synthesis, and provider-specific claim mappings. All production and test callers updated; comprehensive round-trip tests confirm the fix works across default, Azure-style, mapped, and edge-case configurations.

Review coverage

📋 Rules No rules evaluated

🧪 Functional validation Not enabled · Set up

🤖 Auto-approval Not enabled · Set up

Options

Display: compact → Counting what did not apply, without listing it.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

@github-actions

Copy link
Copy Markdown
Contributor

✅ SSO Login Nightly — PASSED

View workflow run · Commit d783b1a

Provider                        Status        Pass   Fail  Flaky   Skip    Duration
------------------------------  -----------  -----  -----  -----  -----  ----------
basic                           pass             4      0      0      0      0m 23s
ldap                            pass             4      0      0      0      0m 19s
keycloak-oidc-confidential      pass             6      0      0      0      0m 47s
keycloak-oidc-public            pass             6      0      0      0      0m 37s
msal-mock                       pass             4      0      0      0      0m 21s
auth0-mock                      pass             3      0      0      0      0m 22s
okta                            skipped          -      -      -      -           -
keycloak-azure-saml             pass             1      0      0      0      0m 23s
keycloak-azure-saml-crosssite   skipped          -      -      -      -           -

Totals: 28 passed · 0 failed · 0 flaky · 0 skipped · duration 3m 15s

manerow
manerow approved these changes Sep 22, 2026 •
@github-actions

Copy link
Copy Markdown
Contributor

🤖 Backport to 1.13 is under way. It is built from openmetadata-collate, which holds the credentials needed to open a PR here, and it will comment again with the result — nothing is needed from you unless it reports otherwise.

@github-actions

Copy link
Copy Markdown
Contributor

🤖 Backport to 2.0 is under way. It is built from openmetadata-collate, which holds the credentials needed to open a PR here, and it will comment again with the result — nothing is needed from you unless it reports otherwise.

@gh-bot-collate

Copy link
Copy Markdown

🤖 Backport to 1.13 failed. The conflict could not be resolved, so this change is not on that branch. Resolver run.

@gh-bot-collate

Copy link
Copy Markdown

🤖 Backport to 2.0 failed. The conflict could not be resolved, so this change is not on that branch. Resolver run.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend safe to test Add this label to run secure Github workflows on PRs To release Will cherry-pick this PR into the release branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Issue in JwtTokenGenerator , preferred username or claim could be different from what we generate vs what we assert for example in domain enforcement

3 participants