Skip to content

use refresh token to obtain fresh access token#3094

Merged
openshift-merge-bot[bot] merged 1 commit intoopenshift-assisted:masterfrom
rawagner:refresh_token
Aug 5, 2025
Merged

use refresh token to obtain fresh access token#3094
openshift-merge-bot[bot] merged 1 commit intoopenshift-assisted:masterfrom
rawagner:refresh_token

Conversation

@rawagner
Copy link
Member

@rawagner rawagner commented Aug 4, 2025

Summary by CodeRabbit

  • New Features

    • Added support for using a refresh token to manage authentication, including automatic token renewal when needed.
    • Introduced a new environment variable for specifying the authentication API URL.
  • Bug Fixes

    • Improved token handling to ensure valid authentication during API calls.
  • Documentation

    • Updated setup instructions to reflect new environment variables and authentication flow.
  • Chores

    • Enhanced configuration files and scripts to support the new authentication process.
    • Added proxy configuration for authentication token requests in development environment.

@openshift-ci openshift-ci bot requested review from ammont82 and batzionb August 4, 2025 14:01
@openshift-ci openshift-ci bot added approved Indicates a PR has been approved by an approver from all required OWNERS files. size/M Denotes a PR that changes 30-99 lines, ignoring generated files. labels Aug 4, 2025
@coderabbitai
Copy link

coderabbitai bot commented Aug 4, 2025

Walkthrough

This change refactors authentication token handling for the chatbot UI by switching from static OCM tokens to refresh tokens. It updates environment variables, configuration files, and proxy settings to support dynamic token refresh via a new /token endpoint. The ChatBot component now asynchronously refreshes access tokens as needed for API calls.

Changes

Cohort / File(s) Change Summary
Environment Variable & Token Naming
apps/assisted-ui/env.template.js, apps/assisted-ui/public/env.js, apps/assisted-ui/README.md, apps/assisted-ui/src/main.tsx
Renamed OCM_TOKEN to OCM_REFRESH_TOKEN throughout templates, global window, documentation, and TypeScript interface. Updated documentation to use refresh token and added AIUI_SSO_API_URL variable.
Startup Script & Substitution
apps/assisted-ui/deploy/start.sh
Added export and substitution for AIUI_SSO_API_URL. Changed environment variable for token substitution from AIUI_OCM_TOKEN to AIUI_OCM_REFRESH_TOKEN. Modified default AIUI_CHAT_API_URL to include trailing slash.
Nginx & Vite Proxy Configuration
apps/assisted-ui/deploy/nginx.conf, apps/assisted-ui/vite.config.ts
Added /token proxy endpoint in both nginx and Vite configurations, forwarding to AIUI_SSO_API_URL for token refresh. Adjusted /chatbot/ proxy_pass to remove trailing slash. Configured proxy settings for /token including HTTP version, timeouts, and SSL server name.
ChatBot Token Logic
apps/assisted-ui/src/components/Chatbot.tsx
Refactored getOcmToken to be asynchronous and refresh tokens when expired. Added refreshToken constant. Updated API call handler to await fresh tokens and use updated authorization header.
UI Integration
apps/assisted-ui/src/components/App.tsx
Updated import and conditional rendering logic to use refreshToken instead of the old synchronous token getter.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI (App.tsx)
    participant ChatBot Component
    participant Token Endpoint (/token)
    participant SSO Server

    User->>UI (App.tsx): Interacts with UI
    UI (App.tsx)->>ChatBot Component: Renders if refreshToken exists
    ChatBot Component->>ChatBot Component: onApiCall triggered
    ChatBot Component->>ChatBot Component: Check token expiry
    alt Token expired or near expiry
        ChatBot Component->>Token Endpoint (/token): POST refreshToken
        Token Endpoint->>SSO Server: Forward refresh request
        SSO Server-->>Token Endpoint: Return new access token
        Token Endpoint-->>ChatBot Component: Return new access token
        ChatBot Component->>ChatBot Component: Update token and expiry
    end
    ChatBot Component->>API: Make call with fresh access token
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

Suggested labels

lgtm, jira/valid-reference

Suggested reviewers

  • batzionb
  • celdrake
  • ElayAharoni

Poem

A token once static, now fresh as the dew,
With proxies and scripts, we’ve built something new.
The chatbot now waits for a sign from the hare,
To fetch a new token, with time left to spare.
🐇✨
Now hop along, UI, with tokens renewed!

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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: 6

🧹 Nitpick comments (3)
apps/assisted-ui/src/main.tsx (1)

7-7: Type-safety gap: make the token non-optional during development

Leaving OCM_REFRESH_TOKEN optional means you’ll get string | undefined throughout the codebase and may forget to handle the undefined case.
If the app truly requires the token to function (outside of unit tests), declare it as required and fail fast when it is missing.

-    OCM_REFRESH_TOKEN?: string;
+    OCM_REFRESH_TOKEN: string;
apps/assisted-ui/README.md (1)

99-100: markdown-lint: prefix commands without showing output

Wrap command snippets with a language fence to silence MD014 and improve readability.

-$ AIUI_CHAT_API_URL=<chatbot_url> OCM_REFRESH_TOKEN=$(ocm token --refresh) AIUI_SSO_API_URL=https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token yarn start:assisted_ui
+```bash
+AIUI_CHAT_API_URL=<chatbot_url> \
+OCM_REFRESH_TOKEN=$(ocm token --refresh) \
+AIUI_SSO_API_URL=https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token \
+yarn start:assisted_ui
+```
apps/assisted-ui/deploy/nginx.conf (1)

31-42: Consider adding the Host header for consistency

The /token location block is missing the proxy_set_header Host $host; directive that's present in the other proxy blocks. While this might work without it, adding it would ensure consistent behavior across all proxied requests.

 location /token {
         proxy_pass $AIUI_SSO_API_URL;
         proxy_http_version 1.1;
+        proxy_set_header Host $host;
         proxy_cache_bypass $http_upgrade;
         proxy_connect_timeout 120;
         proxy_send_timeout 120;
         proxy_read_timeout 120;
         send_timeout 120;
         client_max_body_size 2M;
         proxy_ssl_server_name on;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f0976fa and affaf14.

📒 Files selected for processing (9)
  • apps/assisted-ui/README.md (1 hunks)
  • apps/assisted-ui/deploy/nginx.conf (1 hunks)
  • apps/assisted-ui/deploy/start.sh (1 hunks)
  • apps/assisted-ui/env.template.js (1 hunks)
  • apps/assisted-ui/public/env.js (1 hunks)
  • apps/assisted-ui/src/components/App.tsx (2 hunks)
  • apps/assisted-ui/src/components/Chatbot.tsx (1 hunks)
  • apps/assisted-ui/src/main.tsx (1 hunks)
  • apps/assisted-ui/vite.config.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: in the assisted-installer-ui chatbot feedback implementation, the onfeedbacksubmit callback requires...
Learnt from: celdrake
PR: openshift-assisted/assisted-installer-ui#3051
File: libs/chatbot/lib/components/ChatBot/ChatBotWindow.tsx:196-222
Timestamp: 2025-07-18T12:35:50.945Z
Learning: In the assisted-installer-ui chatbot feedback implementation, the onFeedbackSubmit callback requires access to the messages array to retrieve both the bot response content and the associated user question for the API call, making it necessary to include messages in the useCallback dependency array rather than passing message content as props to avoid duplicating potentially long message data.

Applied to files:

  • apps/assisted-ui/src/components/Chatbot.tsx
  • apps/assisted-ui/src/components/App.tsx
🧬 Code Graph Analysis (1)
apps/assisted-ui/src/components/App.tsx (1)
apps/assisted-ui/src/components/Chatbot.tsx (1)
  • refreshToken (7-8)
🪛 markdownlint-cli2 (0.17.2)
apps/assisted-ui/README.md

99-99: Dollar signs used before commands without showing output

(MD014, commands-show-output)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: tests
🔇 Additional comments (7)
apps/assisted-ui/public/env.js (1)

1-1: No orphaned window.OCM_TOKEN references found

A repository-wide search for OCM_TOKEN returned no matches, confirming the rename to OCM_REFRESH_TOKEN is complete. No further updates are needed.

apps/assisted-ui/src/main.tsx (1)

7-7: No leftover OCM_TOKEN typings detected

I searched for ambient Window interface augmentations and any *.d.ts files referencing OCM_TOKEN and found no occurrences. The codebase is clear of obsolete OCM_TOKEN declarations—no further cleanup required.

apps/assisted-ui/src/components/App.tsx (2)

7-7: LGTM!

The import change correctly reflects the new token handling approach where refreshToken is now a constant instead of a function.


19-19: LGTM!

The conditional change correctly uses the refresh token's presence to determine if the ChatBot should be rendered, which is more appropriate than calling a function during render.

apps/assisted-ui/deploy/start.sh (3)

6-6: LGTM!

The new environment variable is properly exported with a sensible default value for local development.


9-9: LGTM!

The environment variable is correctly added to the nginx.conf substitution.


16-16: LGTM!

The environment variable rename correctly reflects the new refresh token approach.

Copy link

@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: 0

♻️ Duplicate comments (3)
apps/assisted-ui/src/components/Chatbot.tsx (3)

7-11: Race condition still present with module-level state

The module-level mutable variables token and expiration can still cause race conditions during concurrent token refreshes, as flagged in previous reviews.


14-14: Expiration check logic is still incorrect

The condition Date.now() - 5000 > expiration is backwards - it should check if the current time plus 5 seconds is greater than expiration to refresh tokens before they expire.


49-58: Missing error handling for token retrieval

The onApiCall handler should handle potential errors from getOcmToken() to prevent unhandled promise rejections, as noted in previous reviews.

🧹 Nitpick comments (1)
apps/assisted-ui/src/components/Chatbot.tsx (1)

20-20: Remove redundant null coalescing

Since line 15-17 already validates that refreshToken exists, the || '' fallback is unnecessary and should be removed for clarity.

-    params.append('refresh_token', refreshToken || '');
+    params.append('refresh_token', refreshToken);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between affaf14 and efca23d.

📒 Files selected for processing (9)
  • apps/assisted-ui/README.md (1 hunks)
  • apps/assisted-ui/deploy/nginx.conf (2 hunks)
  • apps/assisted-ui/deploy/start.sh (1 hunks)
  • apps/assisted-ui/env.template.js (1 hunks)
  • apps/assisted-ui/public/env.js (1 hunks)
  • apps/assisted-ui/src/components/App.tsx (2 hunks)
  • apps/assisted-ui/src/components/Chatbot.tsx (1 hunks)
  • apps/assisted-ui/src/main.tsx (1 hunks)
  • apps/assisted-ui/vite.config.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/assisted-ui/env.template.js
🚧 Files skipped from review as they are similar to previous changes (6)
  • apps/assisted-ui/deploy/nginx.conf
  • apps/assisted-ui/src/main.tsx
  • apps/assisted-ui/deploy/start.sh
  • apps/assisted-ui/src/components/App.tsx
  • apps/assisted-ui/vite.config.ts
  • apps/assisted-ui/public/env.js
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: in the assisted-installer-ui chatbot feedback implementation, the onfeedbacksubmit callback requires...
Learnt from: celdrake
PR: openshift-assisted/assisted-installer-ui#3051
File: libs/chatbot/lib/components/ChatBot/ChatBotWindow.tsx:196-222
Timestamp: 2025-07-18T12:35:50.945Z
Learning: In the assisted-installer-ui chatbot feedback implementation, the onFeedbackSubmit callback requires access to the messages array to retrieve both the bot response content and the associated user question for the API call, making it necessary to include messages in the useCallback dependency array rather than passing message content as props to avoid duplicating potentially long message data.

Applied to files:

  • apps/assisted-ui/src/components/Chatbot.tsx
🪛 markdownlint-cli2 (0.17.2)
apps/assisted-ui/README.md

99-99: Dollar signs used before commands without showing output

(MD014, commands-show-output)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: tests
🔇 Additional comments (1)
apps/assisted-ui/README.md (1)

99-99: Documentation accurately reflects the token changes

The updated environment variables correctly document the shift from static OCM tokens to refresh tokens, including the new SSO API URL for token refresh functionality.

@openshift-ci openshift-ci bot added the lgtm Indicates that a PR is ready to be merged. label Aug 5, 2025
@openshift-ci
Copy link

openshift-ci bot commented Aug 5, 2025

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: ammont82, rawagner

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@openshift-merge-bot openshift-merge-bot bot merged commit 0f2bf37 into openshift-assisted:master Aug 5, 2025
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files. lgtm Indicates that a PR is ready to be merged. size/M Denotes a PR that changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants