Skip to content

Report amr references from the current authentication regardless of max age - #54499

Closed
ajworkos wants to merge 12 commits into
keycloak:mainfrom
ajworkos:amr-current-authentication
Closed

ajworkos wants to merge 12 commits into
keycloak:mainfrom
ajworkos:amr-current-authentication

Conversation

@ajworkos

@ajworkos ajworkos commented Oct 30, 2026 •

Copy link
Copy Markdown

Closes #54497

What

AmrUtils.isAmrValid applies default.reference.maxAge (default 0) to every completed execution, including the ones of the login that is being tokenized. With whole-second timestamps that means a reference only appears in amr when the token is minted in the same second the authenticator completed, so for any real login amr is empty or missing methods unless an admin also configured a max age.

What changes

  • AuthenticatorUtils.updateCompletedExecutions also records the executions completed during the current authentication, as an auth note so resetFlow discards it with the execution statuses. AuthenticationProcessor.attachSession, which every real authentication goes through (browser after required actions, broker, ROPC, CIBA), writes it to the client session, as an empty list when the authentication completed no execution. Grants that attach a synthetic authentication session to an existing client session, such as token exchange, leave it untouched. The merge of previously completed executions now keeps the current authentication's timestamp when the same execution is completed again.
  • AmrUtils.getAuthenticationExecutionReferences gains an overload taking those executions and reports them without the max age check. The max age keeps its existing meaning for executions carried over from earlier authentications in the SSO session, mirroring how AcrStore applies the LoA max age only to previously authenticated levels.
  • UserSessionManager.createOrUpdateOfflineSession copies the current authentication's executions onto a reused offline client session, next to the existing pinned-identity sync, so tokens refreshed with a new offline token report the methods of the login that issued it.
  • The admin console help text and the server admin guide describe the max age and its default.

Tests

AuthenticationMethodReferenceTest:

  • new testAmrPastMaxAgeWithinCurrentAuthentication: reference with max age 0, token requested 20 seconds after the password form, expects ["password"]. Fails on main with expected: <1> but was: <0>, passes with this change.
  • testAmrPastMaxAge reworked to cover what the max age is for: a second login through the SSO session 20 seconds later with max age 10 gets [], while the first login gets ["password"].
  • The other five tests are unchanged and pass.

New BrokerSecondTabAmrTest (extends the OIDC broker base), two cases built on the fact that a tab opened while another tab's login is in progress shares the root authentication session and therefore lands in the same user session:

  • secondTabBrokeredLoginIntoExistingSession: tab 1 logs in with a password; tab 2, opened with prompt=login&kc_idp_hint=…, logs in at the identity provider as an already linked user, which completes no browser flow execution and lands in tab 1's user session and client session. With max age 0 and the clock 5 seconds ahead, tab 2's amr must be []. With the current authentication recorded as a client note that is only copied when present (the first revision of this PR), tab 1's password leaked into tab 2's token (expected: <[]> but was: <[password]>).
  • thirdTabBrokeredOfflineLoginReusingOfflineSession: tab 1 logs in online; tab 2 logs in with a password and offline_access into that session and creates the offline copy; tab 3 logs in through the identity provider with offline_access into the same session and reuses the copy. Tab 3's token had amr: [] at the code exchange and ["password"] after the first offline refresh before the sync in createOrUpdateOfflineSession. (A session whose very first token is offline cannot be joined this way: OAuth2GrantTypeBase removes the online user session and the root authentication session after that exchange.)
  • thirdTabLoginCompletingNewMethodReusingOfflineSession: same three-tab shape, but the third login completes the OTP form (gated behind a realm role granted only before that login) with offline_access, so it records a method the offline copy has never seen. Its token reports password and otp at the code exchange and after an offline refresh. Added for a review comment predicting the offline refresh would lose otp; it does not, so this guards the path rather than fixing an observed failure.

Review findings, checked by running the flows

The history of this branch shows the back and forth; the net result is what the sections above describe. What I verified by running each scenario:

  • Stale note after a brokered login into an existing client session: reproduced (first broker test) and fixed.
  • Stale note on a reused offline client session: reproduced (second broker test) and fixed with the sync in createOrUpdateOfflineSession.
  • "A later login completing a method absent from the offline user session's map loses it on offline refresh": not reproducible (third broker test); the refreshed token carried both methods. The simpler two-tab version of the scenario does not occur, because the first offline token of a new user session removes that session and its root authentication session.
  • "Another client's prompt=login overwrites the user session's completed-executions map" and "a repeated offline_access login reuses the offline session and leaves its notes stale": not reproducible. A prompt=login re-authentication from a fresh tab creates a new user session (different sid), so no map is overwritten and no offline session is reused. The commit visiting the client's own execution ids independently of the shared map is therefore reverted.
  • Token exchange overwriting the note: applied to an intermediate revision that wrote the note in TokenManager.attachAuthenticationSession; writing it from AuthenticationProcessor.attachSession instead means synthetic authentication sessions never touch it. Not reproduced with a test; the fix is structural.
  • Client note surviving resetFlow: the auth note is cleared by resetFlow, and clone/recreate do not copy auth notes. Not reproduced with a test; same structural fix.

Compatibility

The existing getAuthenticationExecutionReferences(Map, RealmModel) is kept and delegates with an empty set of current executions. Sessions created before an upgrade have no current-authentication note on their client sessions, so their tokens behave exactly as today. Tokens refreshed after the login keep the login's amr, as they keep its auth_time.

AI disclosure

This solution was generated with an AI coding agent (Claude Code) from a prompt, then reviewed, built and tested locally by me. The Copilot review findings on this PR were each verified against the code before being addressed.

…ax age

The AMR protocol mapper only kept an authenticator reference while
authTime + maxAge >= now, with maxAge defaulting to 0 seconds. As both
timestamps are whole seconds, an execution completed in the login being
tokenized was only reported when the token was minted within the same
second, so amr was empty or missing methods for any login that took longer
than a second between a form submit and the code exchange.

Record the executions completed in the current authentication in a client
note, and report their references unconditionally. The configured max age
now only decides whether an execution carried over from an earlier
authentication in the SSO session is still reported, matching how the max
age of a level of authentication applies only to previously authenticated
levels.

Closes keycloak#54497

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
Copilot AI balanced review requested due to automatic review settings October 30, 2026 18:48
@ajworkos
ajworkos requested review from a team as code owners October 30, 2026 18:48

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

Execution tracking can retain stale IDs across logins and flow resets, bypassing max-age checks, while shared-session updates can drop another client’s valid AMR references.

3 open issues
What changed in this PR

This PR addresses #54497 by reporting authentication methods completed during the current login regardless of max age, while retaining expiry checks for methods carried over from earlier SSO authentications.

Changes:

  • Tracks current-authentication executions separately and preserves updated completion timestamps.
  • Adds regression coverage for delayed token issuance and expired methods on subsequent SSO logins.
  • Documents max-age behavior and its default in the admin UI and server guide.
File Description
tests/​base/​src/​test/​java/​org/​keycloak/​tests/​oidc/​AuthenticationMethodReferenceTest.java Tests delayed token issuance and subsequent SSO expiry.
services/​src/​main/​java/​org/​keycloak/​protocol/​oidc/​utils/​AmrUtils.java Exempts current-authentication executions from max age.
services/​src/​main/​java/​org/​keycloak/​protocol/​oidc/​mappers/​AmrProtocolMapper.java Reads current-execution IDs when generating AMR claims.
services/​src/​main/​java/​org/​keycloak/​authentication/​authenticators/​util/​AuthenticatorUtils.java Records current executions and preserves newer timestamps.
server-spi-private/​src/​main/​java/​org/​keycloak/​models/​Constants.java Defines the current-authentication client-note key.
js/​apps/​admin-ui/​maven-resources/​theme/​keycloak.v2/​admin/​messages/​messages_en.properties Clarifies max-age behavior in admin help text.
docs/​documentation/​server_admin/​topics/​authentication/​flows.adoc Documents AMR max age and its default.

Review effort: Balanced

Comment on lines +109 to +110
Set<String> currentAuthenticationExecutions = AuthenticatorUtils.parseCurrentAuthenticationExecutions(
clientSession.getNote(Constants.AUTHENTICATORS_COMPLETED_CURRENT_AUTHENTICATION));
clientSession.getNote(Constants.AUTHENTICATORS_COMPLETED_CURRENT_AUTHENTICATION));
logger.debugf("found the following completed authentication executions: %s, of which completed in the current authentication: %s",
executions, currentAuthenticationExecutions);
List<String> refs = AmrUtils.getAuthenticationExecutionReferences(executions, currentAuthenticationExecutions, realmModel);
…tach

A client note survives AuthenticationProcessor.resetFlow and is copied by
clone and recreate, and attachAuthenticationSession only copies the notes
the new authentication session carries, so an execution id from an
abandoned attempt or from the previous login of the same client could stay
on the client session and exempt an expired reference from the max age.

Store the executions completed in the current authentication as an auth
note, which a flow reset clears, and write it to the client session when
the authentication is attached, as an empty list when the authentication
completed no execution, the same way the level of authentication is written.

Closes keycloak#54497

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
Copilot AI balanced review requested due to automatic review settings October 30, 2026 20:47

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

Same-client token exchange can overwrite the login’s authentication execution set with an empty set, causing exchanged tokens and subsequent refreshes to lose AMR references after the configured max age.

3 open issues
1 resolved since last review

Review effort: Balanced

…ompletes

TokenManager.attachAuthenticationSession is also used by token exchange,
the client credentials and JWT grants, authorization services and the admin
scope evaluator with a synthetic authentication session. Writing the note
there replaced the login's executions with an empty list on the same client
session, so an exchanged token and later refreshes lost their amr once the
max age passed without any new authentication.

Write the note from AuthenticationProcessor.attachSession instead, which
every real authentication goes through: browser logins after required
actions, brokered logins, the password grant and CIBA.

Closes keycloak#54497

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
Copilot AI balanced review requested due to automatic review settings October 30, 2026 21:22

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

A critical AMR tracking flaw allows one client’s password-only login to overwrite shared authentication state, causing another client’s refresh to lose its OTP reference despite retaining the execution in its current-authentication note.

2 open issues
1 previously missed issue

In code that hasn't changed since last review

High severity Preserve Current Execution IDs When Merging AMR

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

Because the stream only visits executions, a password-only prompt=login for client B can overwrite the shared AUTHENTICATORS_COMPLETED map and make client A's next refresh lose its OTP reference, even though A's current-authentication note still contains that execution. Include the current execution IDs independently of the mutable user-session map so another client's authentication cannot remove A's AMR.

1 resolved since last review

Review effort: Balanced

…ared map

On a forced re-authentication (prompt=login) CookieAuthenticator never
attaches the user session, so updateCompletedExecutions skips the merge
with the previously completed executions and the user session's map is
replaced when the new authentication is attached. Another client's
password-only re-login could therefore remove the OTP execution of a
client that still listed it as part of its own authentication, and that
client's next refresh lost the reference.

Visit the client session's current executions on their own, and only use
the shared map for the carried over executions that the max age applies to.

Closes keycloak#54497

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
Copilot AI balanced review requested due to automatic review settings October 30, 2026 21:35

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

Reusing an offline client session does not copy the updated authentication-execution note, causing password AMR to disappear on offline refresh after a repeated offline grant.

3 open issues

Review effort: Balanced

Comment on lines +1212 to +1213
clientSessionCtx.getClientSession().setNote(Constants.AUTHENTICATORS_COMPLETED_CURRENT_AUTHENTICATION,
AuthenticatorUtils.serializeCurrentAuthenticationExecutions(authSession));
…m the shared map"

This reverts commit 5ebf0b5.

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
…cation completes"

This reverts commit b16bc9d.

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
…en at attach"

This reverts commit 1eb1718.

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
Copilot AI balanced review requested due to automatic review settings October 31, 2026 00:37
…te written at attach""

This reverts commit 90f72fa.

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
…authentication completes""

This reverts commit 039ce7c.

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>

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

Session-tracking gaps can drop valid AMR values during token refresh and incorrectly keep prior password authentication exempt from max-age expiry after a broker login with no successful executions.

5 open issues

Review effort: Balanced

clientSession.getNote(Constants.AUTHENTICATORS_COMPLETED_CURRENT_AUTHENTICATION));
logger.debugf("found the following completed authentication executions: %s, of which completed in the current authentication: %s",
executions, currentAuthenticationExecutions);
List<String> refs = AmrUtils.getAuthenticationExecutionReferences(executions, currentAuthenticationExecutions, realmModel);
A second tab opened while a login is in progress shares the root
authentication session, and when it authenticates with prompt=login
through an already linked identity provider it lands in the user session
and client session the first tab created without completing any browser
flow execution. Recording the current authentication's executions in a
client note that is only copied when present let the first tab's password
reference leak into the second tab's amr claim past its max age. The
auth note written on every real authentication reports an empty list
instead.

Closes keycloak#54497

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
Copilot AI balanced review requested due to automatic review settings October 31, 2026 00:46

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

Reusing an offline session retains stale authentication-execution state, causing a refreshed token to incorrectly restore expired password AMR; synchronize the retained state and add regression coverage.

5 open issues
1 resolved since last review

Review effort: Balanced

Comment on lines +1212 to +1213
clientSessionCtx.getClientSession().setNote(Constants.AUTHENTICATORS_COMPLETED_CURRENT_AUTHENTICATION,
AuthenticatorUtils.serializeCurrentAuthenticationExecutions(authSession));
@ajworkos
ajworkos marked this pull request as draft October 31, 2026 00:57
…ession

A new offline token for a client that already has an offline session reuses
the offline client session, and only its timestamp and pinned identities
were synced from the online one. The current authentication executions on
the offline copy therefore stayed those of the login that created it, and a
refresh of the new offline token reported that login's methods in amr.

Reproduced with three concurrent tabs sharing a root authentication session:
an online password login, a forced password login with offline_access that
creates the offline copy, and a brokered login with offline_access that
reuses it. The brokered login's token had amr [] at the code exchange and
["password"] after the first offline refresh. Copy the note onto the reused
offline client session, removing it when the new authentication recorded
none.

Closes keycloak#54497

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
@ajworkos
ajworkos marked this pull request as ready for review October 31, 2026 11:26
Copilot AI balanced review requested due to automatic review settings October 31, 2026 11:26

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

A later tab's completed authentication method is lost on offline refresh because the backing completion map remains stale, requiring synchronization that preserves other clients' history and regression coverage for a different method.

6 open issues

Review effort: Balanced

// report that authentication's methods rather than those of the login that created the offline session
String currentAuthenticationExecutions = clientSession.getNote(Constants.AUTHENTICATORS_COMPLETED_CURRENT_AUTHENTICATION);
if (currentAuthenticationExecutions != null) {
offlineClientSession.setNote(Constants.AUTHENTICATORS_COMPLETED_CURRENT_AUTHENTICATION, currentAuthenticationExecutions);
…thod

Three concurrent tabs share a root authentication session: an online
password login, a forced password login with offline_access that creates
the offline copy, and a forced login that also completes the OTP form,
gated behind a realm role granted only before that third login, with
offline_access. The third tab's token reports password and otp at the code
exchange and after an offline refresh. Covers the reuse path; no failure
was observed.

Closes keycloak#54497

Signed-off-by: Adam Jenkins <adam.jenkins@workos.com>
Copilot AI balanced review requested due to automatic review settings October 31, 2026 11:43

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

Human assessment is needed for a critical cross-tab session interaction that can cause a still-valid password-authentication code to produce an empty amr claim after a broker login.

6 open issues

Review effort: Balanced

@ajworkos

ajworkos commented Nov 4, 2026

Copy link
Copy Markdown
Author

Closing this in favor of the attempted effort at #54520

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