Skip to content

Update authentication configuration to use Asgardeo V2 (Thunder)#641

Open
rasika2012 wants to merge 2 commits intowso2:mainfrom
rasika2012:to-thunder
Open

Update authentication configuration to use Asgardeo V2 (Thunder)#641
rasika2012 wants to merge 2 commits intowso2:mainfrom
rasika2012:to-thunder

Conversation

@rasika2012
Copy link
Copy Markdown
Contributor

@rasika2012 rasika2012 commented Mar 27, 2026

Purpose

Fix: #599
Fix: #572

This pull request introduces a major update to authentication across the Agent Management Console, migrating from @asgardeo/auth-react to the new @asgardeo/react package and refactoring configuration, environment variables, and authentication hooks accordingly. It also improves error handling for authentication/session failures, updates runtime configuration to support the new auth flow, and cleans up legacy token refresh logic.

Authentication migration and configuration refactor:

  • Migrated from @asgardeo/auth-react to @asgardeo/react in all relevant packages, updating dependencies and imports to use the new package. (console/apps/webapp/package.json [1] console/workspaces/libs/api-client/package.json [2] [3] console/workspaces/libs/auth/package.json [4] console/workspaces/libs/auth/src/asgardio/AuthProvider.tsx [5] console/workspaces/libs/auth/src/asgardio/hooks/authHooks.ts [6]
  • Refactored the runtime authentication configuration structure in config.js and config.template.js to use new property names (clientId, afterSignInUrl, afterSignOutUrl, scopes, platform, tokenValidation, etc.), and updated environment variable usage to match. (console/apps/webapp/public/config.js [1] console/apps/webapp/public/config.template.js [2] console/env.example [3]
  • Updated the copyright year in config.js.

Authentication hooks and logic improvements:

Error handling and notification improvements:

  • Enhanced error handling in API hooks to detect authentication/session errors and trigger logout or suppress generic error snackbars as appropriate. Updated hooks to use the new logout method from useAuthHooks. (console/workspaces/libs/api-client/src/hooks/react-query-notifications.ts [1] [2] [3] [4] [5] [6]

Configuration and environment variable cleanup:

  • Updated environment variable names and usage to match new authentication configuration, and added support for additional parameters such as AUTH_CLIENT_SECRET, AUTH_SCOPES, VALIDATE_ID_TOKEN, and CLOCK_TOLERANCE. (console/env.example [1] console/apps/webapp/public/config.template.js [2]
  • Updated usage of new config properties throughout the codebase (e.g., afterSignOutUrl in user menu, login redirect logic). (console/apps/webapp/src/Layouts/userMenuItems.tsx [1] console/apps/webapp/src/pages/Login/Login.tsx [2]

Legacy code and minor cleanups:

  • Removed unused/legacy token refresh logic from API client utilities. (console/workspaces/libs/api-client/src/utils/utils.ts [1] [2] [3] [4]
  • Minor code formatting and consistency fixes. (console/workspaces/libs/api-client/package.json [1] console/workspaces/libs/api-client/src/hooks/react-query-notifications.ts [2] console/workspaces/libs/api-client/src/hooks/traces.ts [3]

These changes collectively modernize authentication, improve error handling, and streamline configuration for future development.

Goals

Describe the solutions that this feature/fix will introduce to resolve the problems described above

Approach

Describe how you are implementing the solutions. Include an animated GIF or screenshot if the change affects the UI (email documentation@wso2.com to review all UI text). Include a link to a Markdown file or Google doc if the feature write-up is too long to paste here.

User stories

Summary of user stories addressed by this change>

Release note

Brief description of the new feature or bug fix as it will appear in the release notes

Documentation

Link(s) to product documentation that addresses the changes of this PR. If no doc impact, enter �N/A� plus brief explanation of why there�s no doc impact

Training

Link to the PR for changes to the training content in https://github.com/wso2/WSO2-Training, if applicable

Certification

Type �Sent� when you have provided new/updated certification questions, plus four answers for each question (correct answer highlighted in bold), based on this change. Certification questions/answers should be sent to certification@wso2.com and NOT pasted in this PR. If there is no impact on certification exams, type �N/A� and explain why.

Marketing

Link to drafts of marketing content that will describe and promote this feature, including product page changes, technical articles, blog posts, videos, etc., if applicable

Automation tests

  • Unit tests

    Code coverage information

  • Integration tests

    Details about the test cases and coverage

Security checks

Samples

Provide high-level details about the samples related to this feature

Related PRs

List any other related PRs

Migrations (if applicable)

Describe migration steps and platforms on which migration has been tested

Test environment

List all JDK versions, operating systems, databases, and browser/versions on which this feature/fix was tested

Learning

Describe the research phase and any blog posts, patterns, libraries, or add-ons you used to solve the problem.

Summary by CodeRabbit

  • New Features

    • Added instrumentation URL support for observability.
    • Introduced configurable authentication scopes, client secret, and token validation parameters.
  • Bug Fixes

    • Improved login validation to require authenticated user profile data.
    • Updated logout redirect to use configured after-sign-out URL with fallback to the login page.
  • Refactor

    • Migrated authentication to the Asgardeo V2 provider and switched token storage to persistent storage.
    • Updated gateway version to v0.9.0.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 27, 2026

Warning

Rate limit exceeded

@rasika2012 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 0 minutes and 34 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 0 minutes and 34 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e214e01b-6265-4281-853b-0b6b46bd36ee

📥 Commits

Reviewing files that changed from the base of the PR and between 2bca3a4 and ad9d3ec.

📒 Files selected for processing (10)
  • console/apps/webapp/public/config.js
  • console/apps/webapp/public/config.template.js
  • console/apps/webapp/src/pages/Login/Login.tsx
  • console/env.example
  • console/workspaces/libs/api-client/src/hooks/react-query-notifications.ts
  • console/workspaces/libs/api-client/src/utils/utils.ts
  • console/workspaces/libs/auth/src/asgardio/AuthProvider.tsx
  • console/workspaces/libs/auth/src/asgardio/hooks/authHooks.ts
  • deployments/helm-charts/wso2-agent-manager/templates/console/configmap.yaml
  • deployments/helm-charts/wso2-agent-manager/values.yaml
📝 Walkthrough

Walkthrough

This PR migrates auth from @asgardeo/auth-react to @asgardeo/react, restructures runtime auth config and env vars, removes automatic refresh-token wiring, updates error handling to logout on 401/auth errors, and adjusts related UI redirect logic and Helm config for new auth settings.

Changes

Cohort / File(s) Summary
Dependency Manifests
console/apps/webapp/package.json, console/workspaces/libs/api-client/package.json, console/workspaces/libs/auth/package.json, console/workspaces/libs/types/package.json
Replaced @asgardeo/auth-react with @asgardeo/react@0.19.0 across packages (minor formatting tweaks in some package files).
Runtime Config & Templates
console/apps/webapp/public/config.js, console/apps/webapp/public/config.template.js, console/env.example
Reworked auth config shape (e.g., clientId, signInUrl, afterSignInUrl, afterSignOutUrl, scopes, platform, tokenValidation.idToken), switched storage to localStorage, updated gateway/instrumentation values, and renamed/added env vars (AUTH_*, AUTH_SCOPES, AUTH_CLIENT_SECRET, VALIDATE_ID_TOKEN, CLOCK_TOLERANCE).
Auth Provider
console/workspaces/libs/auth/src/asgardio/AuthProvider.tsx
Swapped provider implementation to AsgardeoProvider from @asgardeo/react; removed the TokenRefreshSetup component that initialized refresh-token wiring.
Auth Hooks (Asgardeo)
console/workspaces/libs/auth/src/asgardio/hooks/authHooks.ts
Rewrote useAuthHooks to use useAsgardeo/useUser from @asgardeo/react; removed module-level refresh/init functions; added AuthHooks type and a typed useAuthHooks return shape; getToken uses access token APIs.
Auth Module Exports & No-Auth Fallback
console/workspaces/libs/auth/src/index.ts, console/workspaces/libs/auth/src/no-auth/hooks/authHooks.ts
Removed the exported refreshToken symbol and the no-auth refreshToken implementation.
Types
console/workspaces/libs/types/src/config/index.ts
Changed AppConfig.authConfig type from the old AuthReactConfig to AsgardeoProviderProps (type-only import).
API Client: Error Handling & Token Flow
console/workspaces/libs/api-client/src/hooks/react-query-notifications.ts, console/workspaces/libs/api-client/src/utils/utils.ts
Replaced generic snackbar suppression with handleAuthAndExpectedErrors(...) which classifies auth/session error codes and treats 401 as handled (triggering logout); removed token-refresh-on-401 flow and deleted handleTokenExpiry.
React Query Traces Typo
console/workspaces/libs/api-client/src/hooks/traces.ts
Minor type-quote style change only (no behavior change).
UI Redirects / Login
console/apps/webapp/src/Layouts/userMenuItems.tsx, console/apps/webapp/src/pages/Login/Login.tsx
Logout redirect now uses afterSignOutUrl with fallback /login; login redirect requires isAuthenticated or userInfo?.username before redirecting.
Helm Chart Config
deployments/helm-charts/wso2-agent-manager/templates/console/configmap.yaml, deployments/helm-charts/wso2-agent-manager/values.yaml
Added AUTH_CLIENT_SECRET and AUTH_SCOPES entries to values and ConfigMap template to support new auth config variables.

Sequence Diagram(s)

sequenceDiagram
    participant Browser
    participant WebApp
    participant Asgardeo
    participant API
    Browser->>WebApp: open/login
    WebApp->>Asgardeo: signIn / signInSilently
    Asgardeo-->>WebApp: access token
    WebApp->>API: call with access token
    API-->>WebApp: 200 OK / 401 Unauthorized
    alt 200 OK
        WebApp-->>Browser: render data
    else 401
        WebApp->>WebApp: handleAuthAndExpectedErrors -> logout()
        WebApp-->>Asgardeo: signOut (redirect to afterSignOutUrl)
        WebApp-->>Browser: redirect to /login
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

🐰 A hop, a switch, a brand new crate,

Asgardeo moves to modern state,
Tokens no longer quietly mend,
On 401 we close and send,
Hoppy deploys and tests await!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description provides detailed Purpose section with issue links (#599, #572), but Goals, Approach, User stories, Release note, Documentation, Training, Certification, Marketing, test details, security checks, samples, related PRs, migrations, test environment, and Learning sections are incomplete or contain only template placeholders. Complete the missing sections (Goals, Approach, Release note, Documentation, etc.) with substantive content relevant to the authentication migration and session/error handling improvements outlined in the Purpose section.
Docstring Coverage ⚠️ Warning Docstring coverage is 8.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'Update authentication configuration to use Asgardeo V2 (Thunder)' clearly summarizes the main change—migrating to a new authentication library—and is directly related to the core modifications in the changeset.
Linked Issues check ✅ Passed The PR successfully addresses both #599 (session handling via Asgardeo V2 provider and improved auth error detection) and #572 (removed legacy refresh logic and improved token usage flow with new auth hooks), meeting the coding requirements of both issues.
Out of Scope Changes check ✅ Passed All changes are scoped to authentication migration, configuration refactoring, error handling improvements, and legacy code removal—all directly related to fixing #599 and #572. No unrelated modifications detected.

✏️ 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

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
console/workspaces/libs/api-client/src/hooks/react-query-notifications.ts (1)

147-150: ⚠️ Potential issue | 🟠 Major

Run auth/session handling before the UI-notification guards.

handleAuthAndExpectedErrors(...) is currently skipped in two important cases: queries return early once isAuthenticated is false, and mutations short-circuit when showError is false or auth is already false. That prevents the 401/auth-client paths from calling logout(), which can leave the user stuck on a protected screen after the session expires.

🔁 Proposed fix
-    if (!isAuthenticated) {
-      lastErrorMessageRef.current = null;
-      return;
-    }
-
     if (handleAuthAndExpectedErrors(query.error, logout)) {
       lastErrorMessageRef.current = null;
       return;
     }
+    if (!isAuthenticated) {
+      lastErrorMessageRef.current = null;
+      return;
+    }
-      if (
-        showError &&
-        isAuthenticated &&
-        !handleAuthAndExpectedErrors(error, logout)
-      ) {
+      const handledAuthError = handleAuthAndExpectedErrors(error, logout);
+      if (showError && isAuthenticated && !handledAuthError) {

Also applies to: 179-182, 244-248

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@console/workspaces/libs/api-client/src/hooks/react-query-notifications.ts`
around lines 147 - 150, The early-return guards skip running
handleAuthAndExpectedErrors(...) which prevents auth/session handling (e.g.,
logout) on 401s; move the call to handleAuthAndExpectedErrors to execute before
any UI-notification short-circuits (i.e., before the isAuthenticated check in
the query path where lastErrorMessageRef.current is set, and before the
showError/isAuthenticated short-circuits in the mutation path), and only then
apply UI notification logic and reset lastErrorMessageRef.current as needed;
ensure calls reference the existing handleAuthAndExpectedErrors function and
preserve current arguments so logout() and auth-client flows run even when UI
notifications are suppressed.
console/workspaces/libs/api-client/src/utils/utils.ts (1)

42-47: ⚠️ Potential issue | 🟡 Minor

Remove the stale refresh docblock at lines 42–46.

This docblock describes token refresh logic that no longer exists in the implementation. The http* helpers now simply throw on non-OK responses without attempting any refresh. Remove the orphaned comment.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@console/workspaces/libs/api-client/src/utils/utils.ts` around lines 42 - 47,
Remove the stale docblock describing token refresh behavior from utils.ts (the
comment block above the http* helper implementations such as
httpGet/httpPost/httpFetch helpers) because those helpers no longer perform
token refresh and now just throw on non-OK responses; delete the entire orphaned
comment lines 42–46 so the documentation matches the current implementation.
🧹 Nitpick comments (3)
deployments/helm-charts/wso2-agent-manager/values.yaml (1)

253-255: Consider using a Kubernetes Secret for clientSecret when non-empty.

For public SPA clients, an empty clientSecret is appropriate. However, if a confidential client is ever configured with a real secret, storing it in a ConfigMap (as shown in the referenced configmap.yaml context snippet) would expose it in plain text.

Consider adding conditional logic to inject clientSecret from a Kubernetes Secret (referenced via existingSecret like other sensitive values in this chart) when a non-empty value is needed.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@deployments/helm-charts/wso2-agent-manager/values.yaml` around lines 253 -
255, Add support for sourcing the OAuth client secret from a Kubernetes Secret
instead of embedding it in values.yaml: introduce an optional values key (e.g.,
existingSecret or clientSecretSecret) and update the template that renders
clientSecret (the place that currently uses .Values.clientSecret) to
conditionally read the secret value from the referenced Secret (via lookup or
secretKeyRef) when existingSecret is provided and fall back to the empty/plain
value otherwise; ensure the symbols to change include clientSecret in
values.yaml and the template that builds configmap.yaml or deployment env/volume
where clientSecret is used.
console/workspaces/libs/auth/src/asgardio/AuthProvider.tsx (1)

31-31: The cast hides config-shape regressions.

authConfig as AsgardeoProviderProps turns off type-checking exactly where all auth keys were renamed. If globalConfig.authConfig still carries a stale field or misses a required one, this will fail only at runtime. Prefer typing authConfig at the source or building an explicit AsgardeoProviderProps object here.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@console/workspaces/libs/auth/src/asgardio/AuthProvider.tsx` at line 31, The
code is silencing type-checking by casting authConfig to AsgardeoProviderProps
when rendering <AsgardeoProvider {...(authConfig as AsgardeoProviderProps)}>;
instead, stop using the cast and ensure authConfig is correctly typed at its
source (e.g., the globalConfig.authConfig declaration) or build an explicit
AsgardeoProviderProps object here by mapping required fields (clientID, baseUrl,
etc.) from authConfig into a new object and pass that to AsgardeoProvider so
missing/renamed fields are caught at compile time.
console/apps/webapp/public/config.js (1)

37-37: Self-comparison always evaluates to true.

'true' === 'true' is a constant expression that always returns true. Looking at this file's purpose (local dev config), this is likely intentional to disable auth during development. However, if this pattern is meant to mirror the template file's '%%DISABLE_AUTH%%' === 'true' substitution, the placeholder should be used here too for consistency, or simply use true directly.

-  disableAuth: 'true' === 'true',
+  disableAuth: true,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@console/apps/webapp/public/config.js` at line 37, The line setting
disableAuth uses a self-comparison ('true' === 'true') which is always true;
replace it so intent is clear: either set disableAuth to the boolean true
directly or restore the substitution placeholder pattern (e.g., use the template
token like '%%DISABLE_AUTH%%' === 'true') so the value can be overridden by
build/dev tooling; update the disableAuth assignment accordingly in this file
(symbol: disableAuth).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@console/apps/webapp/public/config.template.js`:
- Around line 23-24: The runtime template is injecting the confidential
AUTH_CLIENT_SECRET into the browser (via window.__RUNTIME_CONFIG__), which
exposes the OAuth client secret; remove the clientSecret injection and instead
ensure only non-sensitive OAuth client configuration is emitted to the SPA by
deleting the "...('$AUTH_CLIENT_SECRET'.trim() ? { clientSecret:
'$AUTH_CLIENT_SECRET' } : {})," expression in the template, and if a
confidential flow is required, move secret usage to a server/BFF endpoint (use
AUTH_CLIENT_SECRET only on the server side, not in the client runtime config).

In `@console/apps/webapp/src/pages/Login/Login.tsx`:
- Line 65: The guard "if (isAuthenticated || userInfo?.username)" is unreliable
because username is optional; update the condition to detect a valid profile or
authentication more robustly (e.g., "if (isAuthenticated || userInfo)" or "if
(isAuthenticated || userInfo?.sub || userInfo?.email)") so the effect will
redirect/restart login correctly even when username is missing; locate the check
using the identifiers isAuthenticated, userInfo and isOAuthCallback and replace
the username-specific test with a presence check on the profile or a stable
claim like sub/email.

In `@console/workspaces/libs/auth/src/asgardio/hooks/authHooks.ts`:
- Around line 75-78: The exported hook mapping assigns getToken: getAccessToken
and trySignInSilently: signInSilently but those can be undefined when
useAsgardeo() returns an empty object; add safe fallbacks by wrapping or
replacing getAccessToken and signInSilently with functions that return a
rejected Promise (or a resolved default) so getToken() and trySignInSilently()
always exist; update the mapping in authHooks.ts to reference these fallback
functions (e.g., safeGetAccessToken and safeSignInSilently) so callers of
getToken and trySignInSilently won't hit TypeError.
- Around line 42-45: Remove the nullish coalescing fallback on useAsgardeo so
the hook can throw when the AsgardeoProvider is missing: replace the
destructuring that does "} = useAsgardeo() ?? {}" with a direct call "} =
useAsgardeo()" so variables like isSignedIn, isLoading, and isInitialized come
from the hook directly and provider-misconfiguration errors surface as intended.
- Around line 59-68: In handleLogout, remove the manual redirect inside the try
block: call await signOut?.() and do not call
window.location.assign(fallbackUrl) because signOut (from `@asgardeo/react`)
handles redirect to authConfig.afterSignOutUrl automatically; keep the catch
block which still assigns "/login" on error and leave the dependency array
[signOut, authConfig] as is.

---

Outside diff comments:
In `@console/workspaces/libs/api-client/src/hooks/react-query-notifications.ts`:
- Around line 147-150: The early-return guards skip running
handleAuthAndExpectedErrors(...) which prevents auth/session handling (e.g.,
logout) on 401s; move the call to handleAuthAndExpectedErrors to execute before
any UI-notification short-circuits (i.e., before the isAuthenticated check in
the query path where lastErrorMessageRef.current is set, and before the
showError/isAuthenticated short-circuits in the mutation path), and only then
apply UI notification logic and reset lastErrorMessageRef.current as needed;
ensure calls reference the existing handleAuthAndExpectedErrors function and
preserve current arguments so logout() and auth-client flows run even when UI
notifications are suppressed.

In `@console/workspaces/libs/api-client/src/utils/utils.ts`:
- Around line 42-47: Remove the stale docblock describing token refresh behavior
from utils.ts (the comment block above the http* helper implementations such as
httpGet/httpPost/httpFetch helpers) because those helpers no longer perform
token refresh and now just throw on non-OK responses; delete the entire orphaned
comment lines 42–46 so the documentation matches the current implementation.

---

Nitpick comments:
In `@console/apps/webapp/public/config.js`:
- Line 37: The line setting disableAuth uses a self-comparison ('true' ===
'true') which is always true; replace it so intent is clear: either set
disableAuth to the boolean true directly or restore the substitution placeholder
pattern (e.g., use the template token like '%%DISABLE_AUTH%%' === 'true') so the
value can be overridden by build/dev tooling; update the disableAuth assignment
accordingly in this file (symbol: disableAuth).

In `@console/workspaces/libs/auth/src/asgardio/AuthProvider.tsx`:
- Line 31: The code is silencing type-checking by casting authConfig to
AsgardeoProviderProps when rendering <AsgardeoProvider {...(authConfig as
AsgardeoProviderProps)}>; instead, stop using the cast and ensure authConfig is
correctly typed at its source (e.g., the globalConfig.authConfig declaration) or
build an explicit AsgardeoProviderProps object here by mapping required fields
(clientID, baseUrl, etc.) from authConfig into a new object and pass that to
AsgardeoProvider so missing/renamed fields are caught at compile time.

In `@deployments/helm-charts/wso2-agent-manager/values.yaml`:
- Around line 253-255: Add support for sourcing the OAuth client secret from a
Kubernetes Secret instead of embedding it in values.yaml: introduce an optional
values key (e.g., existingSecret or clientSecretSecret) and update the template
that renders clientSecret (the place that currently uses .Values.clientSecret)
to conditionally read the secret value from the referenced Secret (via lookup or
secretKeyRef) when existingSecret is provided and fall back to the empty/plain
value otherwise; ensure the symbols to change include clientSecret in
values.yaml and the template that builds configmap.yaml or deployment env/volume
where clientSecret is used.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 13b73962-74e8-448a-912f-f67cf0f85313

📥 Commits

Reviewing files that changed from the base of the PR and between 876066c and 4a4416a.

⛔ Files ignored due to path filters (1)
  • console/common/config/rush/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (19)
  • console/apps/webapp/package.json
  • console/apps/webapp/public/config.js
  • console/apps/webapp/public/config.template.js
  • console/apps/webapp/src/Layouts/userMenuItems.tsx
  • console/apps/webapp/src/pages/Login/Login.tsx
  • console/env.example
  • console/workspaces/libs/api-client/package.json
  • console/workspaces/libs/api-client/src/hooks/react-query-notifications.ts
  • console/workspaces/libs/api-client/src/hooks/traces.ts
  • console/workspaces/libs/api-client/src/utils/utils.ts
  • console/workspaces/libs/auth/package.json
  • console/workspaces/libs/auth/src/asgardio/AuthProvider.tsx
  • console/workspaces/libs/auth/src/asgardio/hooks/authHooks.ts
  • console/workspaces/libs/auth/src/index.ts
  • console/workspaces/libs/auth/src/no-auth/hooks/authHooks.ts
  • console/workspaces/libs/types/package.json
  • console/workspaces/libs/types/src/config/index.ts
  • deployments/helm-charts/wso2-agent-manager/templates/console/configmap.yaml
  • deployments/helm-charts/wso2-agent-manager/values.yaml
💤 Files with no reviewable changes (1)
  • console/workspaces/libs/auth/src/no-auth/hooks/authHooks.ts

Copy link
Copy Markdown
Contributor

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

♻️ Duplicate comments (2)
console/workspaces/libs/auth/src/asgardio/hooks/authHooks.ts (2)

59-63: ⚠️ Potential issue | 🟠 Major

Avoid manual redirect immediately after signOut().

Line 63 can cause a second redirect after the SDK-managed logout redirect, producing flaky navigation. Keep /login assignment only in the error path.

Suggested change
   const handleLogout = useCallback(async () => {
     try {
-      await signOut?.();
-      const fallbackUrl = authConfig?.afterSignOutUrl || "/login";
-      window.location.assign(fallbackUrl);
+      await signOut();
     } catch (error) {
       window.location.assign("/login");
       console.error("Error during signOut:", error);
     }
-  }, [signOut, authConfig]);
+  }, [signOut]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@console/workspaces/libs/auth/src/asgardio/hooks/authHooks.ts` around lines 59
- 63, handleLogout currently forces window.location.assign(fallbackUrl)
unconditionally after awaiting signOut, which can clash with the SDK's own
logout redirect; change it so the fallback redirect only runs when signOut is
not provided or when signOut throws. Update the handleLogout function to: (1)
check if signOut is falsy and immediately assign authConfig?.afterSignOutUrl ||
"/login", and (2) keep the existing try/catch and in the catch block call
window.location.assign(authConfig?.afterSignOutUrl || "/login") to handle
error/fallback cases; remove the unconditional window.location.assign inside the
successful try path. Ensure references: handleLogout, signOut,
authConfig?.afterSignOutUrl, and window.location.assign.

45-45: ⚠️ Potential issue | 🟠 Major

Remove the useAsgardeo() ?? {} fallback; it weakens the hook contract.

Line 45 hides provider misconfiguration and forces optional auth methods, which leaks into Line 75 and Line 78 where AuthHooks expects always-callable functions. Use useAsgardeo() directly and return guaranteed functions.

Suggested change
-  } = useAsgardeo() ?? {};
+  } = useAsgardeo();

   const customLogin = () => {
-    void signIn?.();
+    void signIn();
   };
...
-    getToken: getAccessToken,
+    getToken: getAccessToken,
...
-    trySignInSilently: signInSilently,
+    trySignInSilently: signInSilently,

Also applies to: 56-57, 75-79

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@console/workspaces/libs/auth/src/asgardio/hooks/authHooks.ts` at line 45,
Remove the "?? {}" fallback and call useAsgardeo() directly (e.g., const
asgardeo = useAsgardeo()), then either throw or assert if asgardeo is undefined
so provider misconfiguration surfaces; destructure the required auth methods
from that non-null asgardeo and ensure AuthHooks always returns callable
functions (wrap or rethrow rather than returning undefined) so consumers of
AuthHooks can rely on guaranteed functions.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@console/apps/webapp/public/config.js`:
- Line 37: The disableAuth property currently uses a self-comparison ('true' ===
'true') which is always true and triggers lint/suspicious/noSelfCompare; replace
that expression with the boolean literal true for disableAuth in config.js
(ensure the value is the boolean true, not the string "true" or an expression).
- Line 35: The config currently sets persistent token storage via the setting
"storage: 'localStorage'"; change this to "sessionStorage" to limit tokens to
the browser session (tab close clears them), or switch to the more secure
"webWorker" option for production to offload token handling to a worker. Update
the storage property in the exported config object (where "storage:
'localStorage'" appears) and verify the Asgardeo SDK is initialized with the new
value.

---

Duplicate comments:
In `@console/workspaces/libs/auth/src/asgardio/hooks/authHooks.ts`:
- Around line 59-63: handleLogout currently forces
window.location.assign(fallbackUrl) unconditionally after awaiting signOut,
which can clash with the SDK's own logout redirect; change it so the fallback
redirect only runs when signOut is not provided or when signOut throws. Update
the handleLogout function to: (1) check if signOut is falsy and immediately
assign authConfig?.afterSignOutUrl || "/login", and (2) keep the existing
try/catch and in the catch block call
window.location.assign(authConfig?.afterSignOutUrl || "/login") to handle
error/fallback cases; remove the unconditional window.location.assign inside the
successful try path. Ensure references: handleLogout, signOut,
authConfig?.afterSignOutUrl, and window.location.assign.
- Line 45: Remove the "?? {}" fallback and call useAsgardeo() directly (e.g.,
const asgardeo = useAsgardeo()), then either throw or assert if asgardeo is
undefined so provider misconfiguration surfaces; destructure the required auth
methods from that non-null asgardeo and ensure AuthHooks always returns callable
functions (wrap or rethrow rather than returning undefined) so consumers of
AuthHooks can rely on guaranteed functions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 28cc3610-babc-422e-a8f1-6ebc62d75c75

📥 Commits

Reviewing files that changed from the base of the PR and between 4a4416a and 2bca3a4.

⛔ Files ignored due to path filters (1)
  • console/common/config/rush/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (19)
  • console/apps/webapp/package.json
  • console/apps/webapp/public/config.js
  • console/apps/webapp/public/config.template.js
  • console/apps/webapp/src/Layouts/userMenuItems.tsx
  • console/apps/webapp/src/pages/Login/Login.tsx
  • console/env.example
  • console/workspaces/libs/api-client/package.json
  • console/workspaces/libs/api-client/src/hooks/react-query-notifications.ts
  • console/workspaces/libs/api-client/src/hooks/traces.ts
  • console/workspaces/libs/api-client/src/utils/utils.ts
  • console/workspaces/libs/auth/package.json
  • console/workspaces/libs/auth/src/asgardio/AuthProvider.tsx
  • console/workspaces/libs/auth/src/asgardio/hooks/authHooks.ts
  • console/workspaces/libs/auth/src/index.ts
  • console/workspaces/libs/auth/src/no-auth/hooks/authHooks.ts
  • console/workspaces/libs/types/package.json
  • console/workspaces/libs/types/src/config/index.ts
  • deployments/helm-charts/wso2-agent-manager/templates/console/configmap.yaml
  • deployments/helm-charts/wso2-agent-manager/values.yaml
💤 Files with no reviewable changes (1)
  • console/workspaces/libs/auth/src/no-auth/hooks/authHooks.ts
✅ Files skipped from review due to trivial changes (9)
  • console/workspaces/libs/api-client/src/hooks/traces.ts
  • console/workspaces/libs/auth/package.json
  • console/apps/webapp/package.json
  • console/workspaces/libs/types/package.json
  • console/apps/webapp/src/pages/Login/Login.tsx
  • console/workspaces/libs/api-client/package.json
  • deployments/helm-charts/wso2-agent-manager/templates/console/configmap.yaml
  • console/apps/webapp/src/Layouts/userMenuItems.tsx
  • console/env.example
🚧 Files skipped from review as they are similar to previous changes (7)
  • console/workspaces/libs/api-client/src/utils/utils.ts
  • deployments/helm-charts/wso2-agent-manager/values.yaml
  • console/workspaces/libs/types/src/config/index.ts
  • console/workspaces/libs/auth/src/index.ts
  • console/workspaces/libs/auth/src/asgardio/AuthProvider.tsx
  • console/workspaces/libs/api-client/src/hooks/react-query-notifications.ts
  • console/apps/webapp/public/config.template.js

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.

Leave AM logged in and idle overnight and the UI stops showing details Refreshed token is not being used for the api calls after access token expiry

1 participant