Skip to content

Fix amr claim by resolving reported methods when the authentication attaches to the client session - #54520

Closed
ajworkos wants to merge 3 commits into
keycloak:mainfrom
ajworkos:amr-resolved-at-authentication
Closed

ajworkos wants to merge 3 commits into
keycloak:mainfrom
ajworkos:amr-resolved-at-authentication

Conversation

@ajworkos

@ajworkos ajworkos commented Nov 1, 2026 •

Copy link
Copy Markdown

Closes #54497

Alternative to #54499, same issue (#54497). That PR exempts the current authentication from the max age but keeps resolving amr at token-mint time from the user session's shared, mutable map of completed executions. Every review round on it found another reader of that map (another client's login, an offline copy, a refresh after the max age). This PR moves the decision to the one place it belongs.

What

AmrUtils.isAmrValid applies default.reference.maxAge (default 0) to every completed execution, including the ones of the login being tokenized, at the moment each token is minted. With whole-second timestamps a reference only appears in amr when the token is minted in the same second the authenticator completed. A carried-over method also disappears from refreshed tokens once its max age passes, while auth_time stays the same.

OpenID Connect Core 1.0, section 12.2 requires a refreshed ID token's auth_time to "represent the time of the original authentication" and says that "otherwise, the same rules apply as apply when issuing an ID Token at the time of the original authentication". RFC 9068, section 2.2.1 says auth_time, acr and amr "remain the same across all access tokens that derive from a given authorization response", including tokens obtained with a refresh token.

Other providers: Amazon Cognito documents that "when a user refreshes their tokens, Amazon Cognito preserves the same acr and amr values on the new access and ID tokens" and that "refreshing a token doesn't reset the auth_time claim. If you want to force a user to authenticate again after a period of time, use the max_age parameter". Okta documents that refreshed tokens "reflect the acr_values parameter value sent in the original authentication request" and to "use the auth_time parameter value to validate when the original authentication occurred". Microsoft Entra documents that the MFA claim of a primary refresh token is transferred to the app tokens it issues; I did not find a Microsoft page stating the ID-token amr refresh behavior directly.

What changes

amr becomes a property of the authorization, fixed when the authentication attaches to the client session, exactly where LEVEL_OF_AUTHENTICATION is fixed today.

  • AuthenticatorUtils.updateCompletedExecutions also records the executions completed during the current authentication, as an auth note so resetFlow discards it. Merging previously completed executions keeps the current authentication's timestamp when an execution is completed again.
  • AuthenticationProcessor.attachSession, which every real authentication goes through (browser after required actions, broker, ROPC, CIBA; the device grant reuses the client session the browser login created), resolves the executions the client session reports and stores them as a client session note: the current authentication's unconditionally, carried-over ones only if within their max age at that moment.
  • AmrProtocolMapper reads that note and maps execution ids to reference values, with no clock. A client session without the note (token exchange target, client sessions from before the upgrade) falls back to today's behavior unchanged.
  • UserSessionManager.createOrUpdateOfflineSession copies the note onto a reused offline client session, next to the existing pinned-identity sync.
  • Admin console help text and the server admin guide describe the max age, its default, and that refreshed tokens report the same methods.

The max age keeps its meaning for carried-over methods, matching how the LoA max age only applies to levels reused from an earlier authentication. It is evaluated once, when the later authentication completes.

Invariant for reviewers: the note is written only by AuthenticationProcessor.attachSession. Paths that create client sessions through TokenManager.attachAuthenticationSession directly (token exchange, client credentials, JWT bearer, impersonation, transient sessions, legacy broker account linking) never write it and never read the shared map differently than they do today.

Tests

AuthenticationMethodReferenceTest:

  • testAmrPastMaxAgeWithinCurrentAuthentication (new): max age 0, token requested 20 seconds after the password form, expects ["password"]. Fails on main with expected: <1> but was: <0>.
  • testAmrPastMaxAge (reworked): second login through the SSO cookie 20 seconds later with max age 10 gets []; the first login gets ["password"].
  • testAmrFixedForRefreshedTokens (new): max age 10, SSO login 5 seconds after the first reports ["password"]; its tokens refreshed 30 seconds after still report ["password"]. Fails on main with expected: <1> but was: <0> after the refresh. Report amr references from the current authentication regardless of max age #54499 keeps the mint-time check for carried-over methods, so it does not cover this case.

AmrUtilsTest (new, unit): carriesOver never carries an execution with max age 0 over to a later authentication, not even in the same second; a positive max age is inclusive; a missing or invalid value does not carry over. The current time is an explicit argument, so the boundaries do not depend on the wall clock, which the integration tests cannot avoid for the same-second case.

BrokerSecondTabAmrTest (new, from #54499): a tab opened while another tab's login is in progress shares the root authentication session and lands in the same user session.

  • secondTabBrokeredLoginIntoExistingSession: a brokered login that completes no browser execution must not report the first tab's password.
  • thirdTabBrokeredOfflineLoginReusingOfflineSession: same, through a reused offline client session, at the code exchange and after an offline refresh.
  • thirdTabLoginCompletingNewMethodReusingOfflineSession: a third login completing password and OTP into a reused offline client session reports both, at the code exchange and after an offline refresh. Passes here without reading the offline user session's completed-executions map at all, which is a snapshot taken when the offline session was created and does not learn about later logins.

Compatibility

Client sessions created before the upgrade have no note and keep today's behavior. The existing getAuthenticationExecutionReferences(Map, RealmModel) is unchanged and used for them. New overloads are additive.

AI disclosure

Generated with an AI coding agent (Claude Code) from a prompt, then reviewed, built and tested locally by me. Both test classes (13 tests) pass locally against the built distribution; the two new tests were also run against main to confirm they fail there.

@ajworkos
ajworkos marked this pull request as ready for review November 1, 2026 19:30
Copilot AI balanced review requested due to automatic review settings November 1, 2026 19:30
@ajworkos
ajworkos requested review from a team as code owners November 1, 2026 19:30

Copilot AI left a comment

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.

🟡 Changes recommended

Later logins overwrite shared AMR state used by earlier online and offline refresh tokens, while zero-max-age handling can incorrectly carry prior authentication methods into a new SSO login.

2 open issues
What changed in this PR

Addresses #54497 by resolving authentication methods when authentication attaches to a client session, rather than applying max age whenever a token is minted.

Changes:

  • Tracks current-authentication executions separately and stores resolved AMR executions on client sessions, retaining legacy fallback behavior.
  • Synchronizes reused offline sessions and adds delayed-token, refresh, and multi-tab regression tests.
  • Documents max-age semantics in the admin console and server guide.
File Description
tests/​base/​src/​test/​java/​org/​keycloak/​tests/​oidc/​AuthenticationMethodReferenceTest.java Tests current-login expiry, SSO carry-over, and refreshed AMR.
tests/​base/​src/​test/​java/​org/​keycloak/​tests/​broker/​BrokerSecondTabAmrTest.java Adds multi-tab broker and offline-session AMR tests.
services/​src/​main/​java/​org/​keycloak/​services/​managers/​UserSessionManager.java Synchronizes resolved executions to reused offline client sessions.
services/​src/​main/​java/​org/​keycloak/​protocol/​oidc/​utils/​AmrUtils.java Resolves eligible executions at attachment and maps stored IDs to references.
services/​src/​main/​java/​org/​keycloak/​protocol/​oidc/​mappers/​AmrProtocolMapper.java Reads resolved executions, with fallback for sessions without the note.
services/​src/​main/​java/​org/​keycloak/​authentication/​authenticators/​util/​AuthenticatorUtils.java Tracks current executions and preserves their newer timestamps when merging.
services/​src/​main/​java/​org/​keycloak/​authentication/​AuthenticationProcessor.java Stores resolved AMR executions during session attachment.
server-spi-private/​src/​main/​java/​org/​keycloak/​models/​Constants.java Defines current-authentication and resolved-AMR note keys.
js/​apps/​admin-ui/​maven-resources/​theme/​keycloak.v2/​admin/​messages/​messages_en.properties Explains max-age behavior and its default.
docs/​documentation/​server_admin/​topics/​authentication/​flows.adoc Documents carry-over limits and intended refresh stability.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 1, 2026 19:55

Copilot AI left a comment

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.

🟡 Changes recommended

The max-age boundary test uses a live wall-clock offset, so crossing a second boundary can cause intermittent failures and requires deterministic time control.

1 open issue
2 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 1, 2026 20:08

Copilot AI left a comment

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.

🔵 Needs a closer look

Integer overflow in the max-age calculation can reject a recently completed authentication execution and permanently omit it from the client session’s amr; the addition must be widened to long.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Prevent overflow when checking maximum age

services/​src/​main/​java/​org/​keycloak/​protocol/​oidc/​utils/​AmrUtils.java:127

Adding two ints can overflow: with a valid max age of 2147483647, an execution completed just five seconds ago is rejected and permanently omitted from that client session's amr. Widen the addition to long before comparing against now.

1 resolved since last review

Review effort: Balanced

…ttaches to the client session

The Authentication Method Reference (AMR) protocol mapper applied each
execution's max age, default 0, at token-mint time, so a method only
appeared when the token was minted in the same second the authenticator
completed, and carried-over methods disappeared from refreshed tokens
while auth_time stayed the same.

Resolve the executions a client session reports once, in
AuthenticationProcessor.attachSession, where the level of authentication
is fixed too: the current authentication's unconditionally, carried-over
ones only within their max age at that moment. The mapper reads that
client session note without a clock. Sync it onto reused offline client
sessions. Client sessions without the note keep the previous behavior.

Closes keycloak#54497

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
A carried-over execution was kept when its completion time plus max age
was not yet in the past, so with the default max age of 0 an SSO login in
the same second as the execution reported it, and that answer is now fixed
on the client session. 0 means the reference value belongs only to the
authentication that completed the execution, as documented; a positive
max age keeps its inclusive comparison. The legacy fallback is unchanged.

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
Time.setOffset shifts the live clock rather than freezing it, so the
"at the max age" assertion could fail when a second ticked between
capturing the completion time and the check. carriesOver takes the
current time as a parameter; production passes Time.currentTime(), the
unit test passes fixed values.

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
@ajworkos
ajworkos force-pushed the amr-resolved-at-authentication branch from 674398d to 21f7d44 Compare November 17, 2026 13:36
Copilot AI balanced review requested due to automatic review settings November 17, 2026 13:36

Copilot AI left a comment

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.

🟡 Changes recommended

Token exchange can report stale OTP authentication, and offline-session methods can revert after reload; timing inconsistencies and a fragile test also remain.

4 open issues

Review effort: Balanced

Comment on lines +108 to +109
String resolvedExecutions = clientSession.getNote(Constants.AMR_AUTHENTICATION_EXECUTIONS);
if (resolvedExecutions != null) {
Comment on lines +64 to +70
Set<String> resolved = new LinkedHashSet<>(current);
completed.forEach((executionId, completedAt) -> {
if (resolved.contains(executionId)) {
return;
}
Map<String, String> config = getExecutionConfig(executionId, realm);
if (config != null && carriesOver(config, completedAt)) {
Comment on lines +79 to +83
String amrExecutions = clientSession.getNote(Constants.AMR_AUTHENTICATION_EXECUTIONS);
if (amrExecutions != null) {
offlineClientSession.setNote(Constants.AMR_AUTHENTICATION_EXECUTIONS, amrExecutions);
} else {
offlineClientSession.removeNote(Constants.AMR_AUTHENTICATION_EXECUTIONS);
Comment on lines +245 to +259
setAmr("browser", "auth-username-password-form", "password", 10);

oauth.openLoginForm();
authenticatePassword("test-user",PASSWORD);
tokens = assertLogin(passwordUser.getId());
assertAmr(tokens.idToken, expectedAmrs);

timeOffSet.set(5);

oauth.openLoginForm();
tokens = assertLogin(passwordUser.getId());
assertAmr(tokens.idToken, expectedAmrs);
assertAmr(tokens.accessToken, expectedAmrs);

timeOffSet.set(30);
@ajworkos

Copy link
Copy Markdown
Author

Closing in favor of #55273.

This PR fixed the bug in #54497 but also pinned the carried-over methods on the client session at attach time, so they stopped expiring from refreshed tokens. That changes what the configured max age means ("good for N seconds in an SSO session") rather than fixing the bug, and it is what each review round here kept finding another reader of: the multi-tab, offline and token-exchange comments are all consequences of pinning carried-over state on a row that later logins restamp.

#55273 keeps the fix only: the executions completed by the current authentication are fixed on the client session the way LEVEL_OF_AUTHENTICATION already is, and carried-over executions stay subject to their max age at mint time as today. Reporting the same auth_time, acr and amr across every token of one authorization, which RFC 9068 section 2.2.1 asks for, needs those claims to travel with the refresh token rather than live on the session rows, and is a separate proposal.

@ajworkos ajworkos closed this Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

amr claim drops authenticator references from the current login unless the token is minted in the same second

2 participants