Skip to content

Retrieve sessionDataKeyConsent in pre issue access token actions#3122

Open
anjuchamantha wants to merge 12 commits intowso2-extensions:masterfrom
anjuchamantha:pass-sessionDataKeyConsent
Open

Retrieve sessionDataKeyConsent in pre issue access token actions#3122
anjuchamantha wants to merge 12 commits intowso2-extensions:masterfrom
anjuchamantha:pass-sessionDataKeyConsent

Conversation

@anjuchamantha
Copy link
Copy Markdown
Contributor

@anjuchamantha anjuchamantha commented Mar 19, 2026

Proposed changes in this pull request

  • Added new Session model class to represent session context in the pre-issue access token event payload
  • Added sessionDataKeyConsent field to PreIssueAccessTokenEvent and its builder
  • AuthzUtil now stores sessionDataKeyConsent from the OAuth message context into AuthorizationGrantCacheEntry during the authorization endpoint flow
  • AuthorizationGrantCacheEntry gains a sessionDataKeyConsent field with getter/setter
  • AuthorizationCodeGrantHandler reads sessionDataKeyConsent from the cache entry and sets it on the token message context before action execution
  • PreIssueAccessTokenRequestBuilder includes session.sessionDataKeyConsent in the action event payload sent to external actions
  • Unit tests added for AuthorizationGrantCache, PreIssueAccessTokenRequestBuilder, and AuthorizationCodeGrantHandler

Sample Pre Issue Access Token Action request body with sessionDataKeyConsent:

{
    "actionType": "PRE_ISSUE_ACCESS_TOKEN",
    "event": {
        "request": {
        },
        "tenant": {
        },
        "user": {
        },
        "userStore": {
        },
        "accessToken": {
        },
        "refreshToken": {
        },
        "session": {
            "sessionDataKeyConsent": "<session-data-key-consent>"
        }
    },
    "allowedOperations": [
    ],
    "requestId": "<request-id>"
}

Public Issue:

When should this PR be merged

N/A

Follow up actions

N/A

Developer Checklist (Mandatory)

  • Complete the Developer Checklist in the related product-is issue to track any behavioral change or migration impact.

Checklist (for reviewing)

General

  • Is this PR explained thoroughly? All code changes must be accounted for in the PR description.
  • Is the PR labeled correctly?

Functionality

  • Are all requirements met? Compare implemented functionality with the requirements specification.
  • Does the UI work as expected? There should be no Javascript errors in the console; all resources should load. There should be no unexpected errors. Deliberately try to break the feature to find out if there are corner cases that are not handled.

Code

  • Do you fully understand the introduced changes to the code? If not ask for clarification, it might uncover ways to solve a problem in a more elegant and efficient way.
  • Does the PR introduce any inefficient database requests? Use the debug server to check for duplicate requests.
  • Are all necessary strings marked for translation? All strings that are exposed to users via the UI must be marked for translation.

Tests

  • Are there sufficient test cases? Ensure that all components are tested individually; models, forms, and serializers should be tested in isolation even if a test for a view covers these components.
  • If this is a bug fix, are tests for the issue in place? There must be a test case for the bug to ensure the issue won’t regress. Make sure that the tests break without the new code to fix the issue.
  • If this is a new feature or a significant change to an existing feature? has the manual testing spreadsheet been updated with instructions for manual testing?

Security

  • Confirm this PR doesn't commit any keys, passwords, tokens, usernames, or other secrets.
  • Are all UI and API inputs run through forms or serializers?
  • Are all external inputs validated and sanitized appropriately?
  • Does all branching logic have a default case?
  • Does this solution handle outliers and edge cases gracefully?
  • Are all external communications secured and restricted to SSL?

Documentation

  • Are changes to the UI documented in the platform docs? If this PR introduces new platform site functionality or changes existing ones, the changes should be documented.
  • Are changes to the API documented in the API docs? If this PR introduces new API functionality or changes existing ones, the changes must be documented.
  • Are reusable components documented? If this PR introduces components that are relevant to other developers (for instance a mixin for a view or a generic form) they should be documented in the Wiki.

Summary by CodeRabbit

  • New Features

    • Session data (session data key consent) is now captured and propagated through the OAuth authorization and token generation workflow, making it available in pre-issue access token events for action execution.
  • Tests

    • Added unit tests to verify proper session data handling and propagation through the token generation process.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 19, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The changes introduce session data consent key tracking throughout the OAuth token request lifecycle. The sessionDataKeyConsent is captured from the OAuth message into the authorization grant cache, retrieved during token generation, and propagated to the pre-issue access token event payload for action execution.

Changes

Cohort / File(s) Summary
Session Data Model
components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth/action/model/Session.java
New immutable Session class introduced with sessionDataKeyConsent field, public getter, and fluent Builder for construction.
Cache & Grant Handler
components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth/cache/AuthorizationGrantCacheEntry.java, components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/AuthzUtil.java, components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/AuthorizationCodeGrantHandler.java
AuthorizationGrantCacheEntry augmented with sessionDataKeyConsent field and accessors. AuthzUtil copies the value into cache during authorization. AuthorizationCodeGrantHandler retrieves it from cache and sets it on token request context with debug logging.
Action Event Processing
components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth/action/model/PreIssueAccessTokenEvent.java, components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth/action/execution/PreIssueAccessTokenRequestBuilder.java
PreIssueAccessTokenEvent extended with immutable session field and accessor. PreIssueAccessTokenRequestBuilder conditionally populates session from token context property when building action execution requests.
Test Coverage
components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/oauth/action/execution/PreIssueAccessTokenRequestBuilderTest.java, components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/AuthorizationCodeGrantHandlerTest.java
New unit tests validate sessionDataKeyConsent flow through token context to action event, and cache retrieval with three control-flow scenarios (non-null with value, null entry, empty value).

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AuthzUtil
    participant GrantCache as AuthorizationGrantCache
    participant GrantHandler as AuthorizationCodeGrantHandler
    participant EventBuilder as PreIssueAccessTokenRequestBuilder
    participant Event as PreIssueAccessTokenEvent

    Client->>AuthzUtil: addUserAttributesToOAuthMessage()
    AuthzUtil->>GrantCache: store AuthorizationGrantCacheEntry<br/>with sessionDataKeyConsent
    
    Client->>GrantHandler: setPropertiesForTokenGeneration()
    GrantHandler->>GrantCache: getValueFromCacheByCode(authCode)
    GrantCache-->>GrantHandler: AuthorizationGrantCacheEntry
    GrantHandler->>GrantHandler: setSessionDataKeyConsentProperty()<br/>from cache entry
    
    Client->>EventBuilder: buildActionExecutionRequest()
    EventBuilder->>EventBuilder: getEvent()<br/>reads SESSION_DATA_KEY_CONSENT<br/>from context
    EventBuilder->>Event: create Session<br/>with sessionDataKeyConsent
    EventBuilder-->>Client: PreIssueAccessTokenEvent<br/>with session data
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Suggested reviewers

  • piraveena
  • shashimalcse
  • jenkins-is-staging

Poem

🐰 Hop, hop, consent keys flow,
Through cache and token, swiftly we go,
Sessions now bundled in action's grand sight,
From grant to the event, the data takes flight!

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The PR description provides technical details but lacks structured information against the required template sections. Provide information for Purpose, Goals, Approach, User stories, Release notes, Documentation, Training, Certification, Marketing, Security checks, Test environment, and Learning sections per the repository template.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: retrieving and passing sessionDataKeyConsent to pre-issue access token actions. It is specific and clearly conveys the primary objective.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@wso2-engineering wso2-engineering bot left a comment

Choose a reason for hiding this comment

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

AI Agent Log Improvement Checklist

⚠️ Warning: AI-Generated Review Comments

  • The log-related comments and suggestions in this review were generated by an AI tool to assist with identifying potential improvements. Purpose of reviewing the code for log improvements is to improve the troubleshooting capabilities of our products.
  • Please make sure to manually review and validate all suggestions before applying any changes. Not every code suggestion would make sense or add value to our purpose. Therefore, you have the freedom to decide which of the suggestions are helpful.

✅ Before merging this pull request:

  • Review all AI-generated comments for accuracy and relevance.
  • Complete and verify the table below. We need your feedback to measure the accuracy of these suggestions and the value they add. If you are rejecting a certain code suggestion, please mention the reason briefly in the suggestion for us to capture it.
Comment Accepted (Y/N) Reason
#### Log Improvement Suggestion No: 1
#### Log Improvement Suggestion No: 2
#### Log Improvement Suggestion No: 3
#### Log Improvement Suggestion No: 4
#### Log Improvement Suggestion No: 5
#### Log Improvement Suggestion No: 6

* @param key CacheKey wrapping the authorization code.
* @return Cached entry, or null if not found in the local JVM cache.
*/
public AuthorizationGrantCacheEntry getValueFromLocalCacheByCode(AuthorizationGrantCacheKey key) {
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.

why we need this local cache method cause this is getting call when we have the code right, so session store can be invoked to retrived for multi node deployment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed for multi node safety with ce74398

@codecov
Copy link
Copy Markdown

codecov bot commented Mar 19, 2026

Codecov Report

❌ Patch coverage is 59.45946% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 58.28%. Comparing base (2fe9d04) to head (6eafe9d).
⚠️ Report is 81 commits behind head on master.

Files with missing lines Patch % Lines
.../handlers/grant/AuthorizationCodeGrantHandler.java 0.00% 10 Missing ⚠️
...tity/oauth/cache/AuthorizationGrantCacheEntry.java 0.00% 3 Missing ⚠️
...n/execution/PreIssueAccessTokenRequestBuilder.java 71.42% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3122      +/-   ##
============================================
- Coverage     58.70%   58.28%   -0.43%     
- Complexity    10399    10591     +192     
============================================
  Files           708      709       +1     
  Lines         57424    58516    +1092     
  Branches      13579    14164     +585     
============================================
+ Hits          33713    34105     +392     
- Misses        19213    19826     +613     
- Partials       4498     4585      +87     
Flag Coverage Δ
unit 42.70% <59.45%> (+0.04%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

LOG.debug(String.format("Retrieve sessionDataKeyConsent: %s from tokenMessageContext and add to " +
"additionalParams of the token request in preIssueAccessToken action", sessionDataKeyConsent));
}
tokenRequestBuilder.addAdditionalParam(
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.

Let's avoid adding this to the additional params, as it is intended to denote the parameters added in the token request.
Let's have a first class object in the event object for this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Changed with 4f615a3

Can retrieve sessionDataKeyConsent from event.session.sessionDataKeyConsent in action

@anjuchamantha anjuchamantha marked this pull request as ready for review March 20, 2026 07:07
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/AuthzUtil.java`:
- Around line 2345-2348: AuthzUtil currently logs the raw sessionDataKeyConsent
value via oAuthMessage.getSessionDataKeyFromConsent(), which may expose
sensitive session identifiers; update the debug log in the AuthzUtil code path
that sets authorizationGrantCacheEntry to avoid printing the raw value—either
remove the raw key from the message or log a non-reversible derivative (e.g.,
hash or masked version such as showing only first 4 chars and replacing the rest
with ****) and include clear context in the log; ensure you reference and change
the log call that uses oAuthMessage.getSessionDataKeyFromConsent() so the
sensitive identifier is never emitted in plaintext even at debug level.

In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth/action/execution/PreIssueAccessTokenRequestBuilder.java`:
- Around line 145-146: The debug log in PreIssueAccessTokenRequestBuilder
currently prints the full sessionDataKeyConsent value via
LOG.debug(String.format(... sessionDataKeyConsent)); change it to avoid logging
the raw value — instead log only its presence or state (e.g.,
"sessionDataKeyConsent present" or "sessionDataKeyConsent is null/empty") by
checking the sessionDataKeyConsent variable before logging and outputting a
boolean or descriptive text; update the LOG.debug call accordingly where
sessionDataKeyConsent is referenced in the event-building path to preserve
privacy.

In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/AuthorizationCodeGrantHandler.java`:
- Around line 703-705: The debug line in AuthorizationCodeGrantHandler that
calls log.debug(String.format(..., grantCacheEntry.getSessionDataKeyConsent()))
must not log the raw sessionDataKeyConsent; change it to either omit the value
or log a redacted/masked version (e.g., replace most characters with asterisks
or only show a safe suffix/prefix) before passing to log.debug, so update the
call site that uses grantCacheEntry.getSessionDataKeyConsent() to use a
redaction helper or constant placeholder instead of the full identifier.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2729b836-c5df-4309-844f-63c69a74bef6

📥 Commits

Reviewing files that changed from the base of the PR and between 2fe9d04 and a876061.

📒 Files selected for processing (10)
  • components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/AuthzUtil.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth/action/execution/PreIssueAccessTokenRequestBuilder.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth/action/model/PreIssueAccessTokenEvent.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth/action/model/Session.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth/cache/AuthorizationGrantCache.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth/cache/AuthorizationGrantCacheEntry.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/AuthorizationCodeGrantHandler.java
  • components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/oauth/action/execution/PreIssueAccessTokenRequestBuilderTest.java
  • components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/oauth/cache/AuthorizationGrantCacheTest.java
  • components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/AuthorizationCodeGrantHandlerTest.java

}

private Request getRequest(OAuth2AccessTokenReqDTO tokenRequestDTO) {
private Request getRequest(OAuthTokenReqMessageContext tokenMessageContext) {
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.

Hope this signature change is not required now.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reverted with ef3841c

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/AuthorizationCodeGrantHandler.java`:
- Around line 697-699: The current check uses
AuthorizationGrantCache.getInstance().getValueFromCacheByCode(new
AuthorizationGrantCacheKey(authzCode)) which only looks up the JVM cache and can
miss sessionDataKeyConsent in multi-node setups; update the logic in
AuthorizationCodeGrantHandler so that if grantCacheEntry is null or
grantCacheEntry.getSessionDataKeyConsent() is empty you perform the
distributed/session-store fallback (retrieve the AuthorizationGrantCacheEntry or
the sessionDataKeyConsent from the shared session store using the
authzCode/session key) and then use that value—ensure you still prefer the cache
result when present but fall back to the session store to preserve behavior
across nodes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d74b8ae5-7fe0-4768-b83f-c53775f34a9b

📥 Commits

Reviewing files that changed from the base of the PR and between 0027847 and 6eafe9d.

📒 Files selected for processing (2)
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/AuthorizationCodeGrantHandler.java
  • components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/AuthorizationCodeGrantHandlerTest.java
✅ Files skipped from review due to trivial changes (1)
  • components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/AuthorizationCodeGrantHandlerTest.java

@jenkins-is-staging
Copy link
Copy Markdown

PR builder started
Link: https://github.com/wso2/product-is/actions/runs/23551459404

@jenkins-is-staging
Copy link
Copy Markdown

PR builder completed
Link: https://github.com/wso2/product-is/actions/runs/23551459404
Status: success

Copy link
Copy Markdown

@jenkins-is-staging jenkins-is-staging left a comment

Choose a reason for hiding this comment

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

Approving the pull request based on the successful pr build https://github.com/wso2/product-is/actions/runs/23551459404

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.

4 participants