Skip to content

Fix social login localhost fallback via relative API routing and resolve OAuth redirect loops (vertex app)#3604

Merged
Baalmart merged 13 commits into
stagingfrom
fix-login-vertex
Jun 9, 2026
Merged

Fix social login localhost fallback via relative API routing and resolve OAuth redirect loops (vertex app)#3604
Baalmart merged 13 commits into
stagingfrom
fix-login-vertex

Conversation

@Codebmk

@Codebmk Codebmk commented Jun 9, 2026

Copy link
Copy Markdown
Member

Description

This PR introduces a robust overhaul of how the application handles API routing and the OAuth authentication flow.

The core issue resolved here stems from build-time environment variables. Previously, if NEXT_PUBLIC_ENV or NEXT_PUBLIC_API_URL were missing during the Next.js build process, the fallback logic baked http://localhost:3000 directly into the production client bundle. This caused social login initiations to attempt routing through localhost. We resolved this by shifting to relative browser routing, and simultaneously fixed subsequent edge-case bugs causing redirect loops and profile fetch timeouts.

Final Outcome & Key Features

  • Resilient Browser API Routing: Completely eliminated the dependency on build-time NEXT_PUBLIC_ variables for client-side API requests. Browser API calls now use relative paths (/api/v2/...), natively resolving to the correct domain (production, staging, or local) without split-brain environment risks.
  • Flawless Social Auth Redirects: Solved a critical redirect loop where users were forcefully bounced back to the /login page after successful OAuth handoffs due to React context lag and middleware interceptions.
  • Stable Profile Fetching: Increased the OAuth profile fetch tolerance to 10 seconds and gracefully handled AbortErrors to prevent noisy server logs.

Technical Changes

API Routing & Proxy Stabilization (api-routing.ts & proxyClient.ts)

  • Relative Client Routes: Introduced buildBrowserApiUrl which strictly returns relative paths for browser-side requests. This entirely bypasses the localhost fallback bug caused by missing build-time environment variables.
  • Server Routes & Strict Env Checks: Introduced buildServerApiUrl for server-side requests. Tightened envConstants.ts so getApiBaseUrl() strictly requires NEXT_PUBLIC_API_URL, throwing a clear build error rather than silently falling back to localhost.
  • Proxy V2 Duplication Fix: Adjusted the proxy client's path handling to strip leading v2/ segments, preventing double /v2/v2/ URL paths when proxying to the backend.

Authentication & Session Sync (authProvider.tsx, options.ts, social-auth-section.tsx)

  • Middleware Bypass: SocialAuthSection now safely appends a success=<provider> query parameter to the redirect_after URL. This signals the NextAuth middleware to allow the OAuth callback to pass through without forcefully intercepting it.
  • UI Blocking on Token Handoff: Added a useEffect watcher in TokenHandoffHandler to strictly observe the session status. The UI now remains blocked (isHandlingOAuth stays true) until NextAuth fully broadcasts the authenticated state across the React context tree, preventing rogue client-side redirects to /login.
  • NextAuth Options: Safely normalize the OAuth access token and ensure that Authorization headers are only appended when the token is actually present.

Summary by CodeRabbit

  • New Features

    • Added utilities for consistent server/browser API URL construction
  • Bug Fixes

    • Fixed OAuth redirect loop issues preventing sign-in
    • Resolved relative API routing problems affecting backend access
  • Improvements

    • Enhanced authentication/session synchronization and UI responsiveness during auth updates
    • Hardened OAuth redirect URL handling and improved profile fetching resilience
  • Documentation

    • Added a new release entry describing these fixes and improvements

Codebmk added 4 commits June 9, 2026 19:22
Introduce src/vertex/lib/api-routing.ts with buildServerApiUrl and buildBrowserApiUrl to centralize how server- and browser-side API URLs are built (avoids split-brain env issues). Replace scattered getApiBaseUrl usage across auth options, oauth session, users API, network service, and proxy client to use the new builders. Tighten env constants: getApiBaseUrl now requires NEXT_PUBLIC_API_URL (throws if missing) and getEnvironment was moved/renamed. Update vertex.config to use getApiBaseUrl. Misc: adjust variable names in proxy client (API_URL) and ensure browser requests use relative /api/v2 paths.
Switch OAuth initiation to use buildServerApiUrl instead of buildBrowserApiUrl to construct the /users/auth/:provider endpoint. Also adjust proxy path handling to strip a leading "v2/" (and treat "v2" as empty) so requests don't end up with a double /v2/ segment when getApiBaseUrl() already includes it.
Improve OAuth handling across auth flow:

- options.ts: increase profile fetch timeout to 10s, normalize the OAuth access token and only send Authorization when present, include credentials in the fetch, and return null on AbortError to avoid logging noise.
- social-auth-section.tsx: append a success=<provider> query param to redirect_after URLs so callers can detect successful social sign-ins.
- authProvider.tsx: force NextAuth SessionProvider to update after token handoff (await update()), watch session status to clear the isHandlingOAuth flag when authenticated, ensure the flag is cleared on error branches, and adjust bootstrap blocking logic to wait for NextAuth to flush its authenticated state before unblocking.

These changes make token handoff more robust and ensure redirects and session state are synchronized correctly.
@Codebmk Codebmk self-assigned this Jun 9, 2026
@coderabbitai

coderabbitai Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Codebmk, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 40 minutes and 49 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, 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 include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 00131045-ab8f-4d5f-a5e1-ad244ba2e20f

📥 Commits

Reviewing files that changed from the base of the PR and between fd3f475 and 02c3739.

📒 Files selected for processing (4)
  • src/vertex/components/features/auth/social-auth-section.tsx
  • src/vertex/core/auth/oauth-session.ts
  • src/vertex/core/services/network-service.ts
  • src/vertex/middleware.ts
📝 Walkthrough

Walkthrough

Centralizes API URL building (server/browser), requires NEXT_PUBLIC_API_URL, migrates callsites to the new builders, and tightens OAuth token handoff/session sync and redirect URL construction.

Changes

API Routing and OAuth Authentication Flow

Layer / File(s) Summary
API Routing Abstraction Helpers
src/vertex/lib/api-routing.ts
Introduces buildServerApiUrl and buildBrowserApiUrl with helpers for absolute-URL passthrough and slash normalization.
Environment Configuration and Validation
src/vertex/lib/envConstants.ts
Relocates getEnvironment(), removes getDefaultApiUrl(), and makes getApiBaseUrl() require NEXT_PUBLIC_API_URL.
Vertex Configuration Alignment
src/vertex/vertex.config.ts
Uses getApiBaseUrl() for api.baseUrl and as fallback for api.publicMeasurementsBaseUrl.
OAuth Session Initialization Routing
src/vertex/core/auth/oauth-session.ts
Uses buildBrowserApiUrl to build the OAuth provider initiation URL.
Token Handoff and Session Synchronization
src/vertex/core/auth/authProvider.tsx
Calls NextAuth update() after successful sign-in, observes session status to clear the handling ref, and tightens error/cleanup paths.
Social Auth Redirect URL Construction
src/vertex/components/features/auth/social-auth-section.tsx
Parses redirectAfter as a URL, sets provider success query param, and passes the reconstructed string to OAuth flow.
OAuth Profile Fetching Improvements
src/vertex/app/api/auth/[...nextauth]/options.ts
Uses buildServerApiUrl for profile endpoint, increases abort timeout, adds credentials: 'include', normalizes access token before Authorization header, and treats AbortError as non-fatal.
API Service & Proxy Client Routing Updates
src/vertex/core/apis/users.ts, src/vertex/core/services/network-service.ts, src/vertex/core/utils/proxyClient.ts
Migrates endpoints to buildServerApiUrl/buildBrowserApiUrl, adds proxy targetPath normalization (strip leading v2/), uses direct Axios url, and guards missing API URL.
Release Documentation
src/vertex/app/changelog.md
Adds Version 2.0.1 release notes listing fixes and modified files (includes new lib/api-routing.ts).

Sequence Diagrams

sequenceDiagram
  participant Handler as TokenHandoffHandler
  participant NextAuth as useSession()
  participant SignIn as signIn()
  participant Redirect as Navigation
  Handler->>NextAuth: Read update & status
  Handler->>SignIn: Initiate OAuth sign-in
  SignIn-->>Handler: Result OK/Error
  alt Sign-in Success
    Handler->>NextAuth: Call update() for sync
    NextAuth-->>Handler: Session updated
    Handler->>NextAuth: Wait for status=authenticated
    NextAuth-->>Handler: status changes
    Handler->>Redirect: Navigate to destination
  else Sign-in Failure
    Handler->>Handler: Clear isHandlingOAuthRef
    Handler->>Redirect: Navigate to /auth-error
  end
Loading
flowchart LR
  routes[Endpoint paths] --> buildServer[buildServerApiUrl]
  routes --> buildBrowser[buildBrowserApiUrl]
  buildServer --> users[users.ts]
  buildServer --> network[network-service.ts]
  buildServer --> proxy[proxyClient.ts]
  buildBrowser --> network
  users --> api[API calls]
  network --> api
  proxy --> api
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • Baalmart

Poem

🚦 URLs gather, marching neat and true,
Tokens whisper, sessions chase the cue,
Redirects wear the provider's name,
Requests find one path to speak the same,
Release notes hum — a tidy routing tune.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main changes: fixing social login localhost fallback via relative API routing and resolving OAuth redirect loops in the vertex app.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-login-vertex

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • JIRA integration encountered authorization issues. Please disconnect and reconnect the integration in the CodeRabbit UI.

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.

@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

New azure vertex changes available for preview here

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/vertex/components/features/auth/social-auth-section.tsx`:
- Around line 93-95: The code constructs a new URL from redirectAfter which will
throw for relative paths; update the logic around the URL(...) creation in
social-auth-section.tsx (where redirectAfter is used and
queryParams.redirect_after is set) to pass a base (e.g., window.location.origin)
to the URL constructor so relative paths like '/home' resolve correctly while
absolute URLs remain unchanged; ensure you still call
urlObj.searchParams.set('success', provider) and assign
queryParams.redirect_after = urlObj.toString().

In `@src/vertex/core/services/network-service.ts`:
- Around line 94-95: submitNetworkRequest currently constructs its POST target
with buildBrowserApiUrl which yields a browser-relative path; when invoked from
server route handlers (submitNetworkRequest in network-service.ts called by
app/api/.../route.ts) this breaks because fetch on the server needs an
absolute/server API URL. Replace buildBrowserApiUrl(...) with
buildServerApiUrl(...) inside submitNetworkRequest (or otherwise construct a
server-resolvable absolute URL) so the server-side call uses the correct API
host/resolver; update any related error handling or tests that assume the old
URL shape.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ce50a1ac-2bd4-4a80-a2ef-ed79f67bab19

📥 Commits

Reviewing files that changed from the base of the PR and between 97fcf0d and 19cd20d.

📒 Files selected for processing (11)
  • src/vertex/app/api/auth/[...nextauth]/options.ts
  • src/vertex/app/changelog.md
  • src/vertex/components/features/auth/social-auth-section.tsx
  • src/vertex/core/apis/users.ts
  • src/vertex/core/auth/authProvider.tsx
  • src/vertex/core/auth/oauth-session.ts
  • src/vertex/core/services/network-service.ts
  • src/vertex/core/utils/proxyClient.ts
  • src/vertex/lib/api-routing.ts
  • src/vertex/lib/envConstants.ts
  • src/vertex/vertex.config.ts

Comment thread src/vertex/components/features/auth/social-auth-section.tsx Outdated
Comment thread src/vertex/core/services/network-service.ts Outdated
Codebmk added 3 commits June 9, 2026 20:28
Return null from SocialAuthSection when NEXT_PUBLIC_API_URL is not set. This avoids runtime crashes during OAuth initiation when getApiBaseUrl() would throw due to a missing API URL environment variable.
Provide window.location.origin as the base when constructing the URL from redirectAfter so relative paths are resolved correctly. This prevents errors from the URL constructor for relative redirectAfter values and ensures the success query param and redirect_after value are set to a full URL.
@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

New azure vertex changes available for preview here

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.

Pull request overview

This PR refactors Vertex’s API URL construction and OAuth flow to avoid localhost fallbacks baked into the client bundle, and to reduce redirect-loop issues by improving session synchronization and proxy path normalization.

Changes:

  • Introduces centralized API URL builders for server (buildServerApiUrl) and browser (buildBrowserApiUrl) usage.
  • Tightens API base URL env validation (fail-fast when NEXT_PUBLIC_API_URL is missing) and updates multiple call sites to use the new routing helpers.
  • Improves OAuth token handoff/session sync and increases OAuth profile fetch timeout with cleaner abort handling.

Reviewed changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
src/vertex/vertex.config.ts Switches config API base URL sourcing to getApiBaseUrl() (strict env).
src/vertex/lib/envConstants.ts Removes localhost fallback behavior and enforces NEXT_PUBLIC_API_URL presence.
src/vertex/lib/api-routing.ts Adds server/browser API URL builders, enabling relative routing on the client.
src/vertex/core/utils/proxyClient.ts Updates proxy URL building and avoids duplicated /v2 segments.
src/vertex/core/services/network-service.ts Migrates network service endpoints to the new server URL builder.
src/vertex/core/auth/oauth-session.ts Updates OAuth initiation URL building (currently still server-based).
src/vertex/core/auth/authProvider.tsx Improves token handoff/session update sequencing to prevent redirect loops.
src/vertex/core/apis/users.ts Migrates login endpoint URL building to the new server URL builder.
src/vertex/components/features/auth/social-auth-section.tsx Adjusts redirect_after to include success=<provider> and adds an env-based guard (problematic).
src/vertex/app/changelog.md Documents release notes for the routing/OAuth changes.
src/vertex/app/api/auth/[...nextauth]/options.ts Increases OAuth profile fetch timeout, normalizes tokens, and handles aborts cleanly.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/vertex/core/auth/oauth-session.ts
Comment thread src/vertex/core/auth/oauth-session.ts
Comment thread src/vertex/components/features/auth/social-auth-section.tsx
Comment thread src/vertex/core/services/network-service.ts Outdated
Comment thread src/vertex/core/services/network-service.ts Outdated
Comment thread src/vertex/core/services/network-service.ts Outdated
Codebmk added 3 commits June 9, 2026 21:25
Switch oauth-session to use buildBrowserApiUrl for constructing the OAuth initiation URL (client-side) instead of buildServerApiUrl. Remove the environment-var guard in SocialAuthSection that hid social auth when NEXT_PUBLIC_API_URL was missing so social buttons render even if that env var isn't present. This change prevents unnecessary hiding and avoids runtime issues during OAuth initiation by using the browser API URL builder.

Files changed: src/vertex/core/auth/oauth-session.ts, src/vertex/components/features/auth/social-auth-section.tsx.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
src/vertex/core/services/network-service.ts (1)

22-27: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add request timeouts to axios calls used by server handlers.

Both axios requests run without a timeout. In server route flows, this can tie up request handling indefinitely when upstream is slow/unresponsive. Add timeout: NETWORK_REQUEST_TIMEOUT_MS to both calls.

Suggested patch
       const response = await axios.get(url, {
+        timeout: NETWORK_REQUEST_TIMEOUT_MS,
         headers: {
           Authorization: token.startsWith("JWT ") ? token : `JWT ${token}`,
           "X-Auth-Type": "JWT"
         }
       });
...
       const response = await axios.put(url, payload, {
+        timeout: NETWORK_REQUEST_TIMEOUT_MS,
         headers: {
           Authorization: token.startsWith("JWT ") ? token : `JWT ${token}`,
           "X-Auth-Type": "JWT"
         }
       });

Also applies to: 69-74

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/vertex/core/services/network-service.ts` around lines 22 - 27, The
axios.get calls in network-service.ts are missing timeouts; update both axios
requests (the one that builds headers with Authorization: token.startsWith("JWT
") and the second call around lines 69-74) to include timeout:
NETWORK_REQUEST_TIMEOUT_MS in the request options so server handlers can't hang
indefinitely; ensure NETWORK_REQUEST_TIMEOUT_MS is referenced (or imported) and
added alongside headers in each axios.get call.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/vertex/core/services/network-service.ts`:
- Line 59: The URL composes dynamic path segments using id and action unescaped;
update the code that calls buildServerApiUrl so each path segment (id and
action) is safely encoded (e.g., wrap them with encodeURIComponent, optionally
trim) before interpolation, leaving the existing adminSecret encoding as-is, so
the status-update URL cannot be hijacked by reserved characters.

---

Outside diff comments:
In `@src/vertex/core/services/network-service.ts`:
- Around line 22-27: The axios.get calls in network-service.ts are missing
timeouts; update both axios requests (the one that builds headers with
Authorization: token.startsWith("JWT ") and the second call around lines 69-74)
to include timeout: NETWORK_REQUEST_TIMEOUT_MS in the request options so server
handlers can't hang indefinitely; ensure NETWORK_REQUEST_TIMEOUT_MS is
referenced (or imported) and added alongside headers in each axios.get call.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 83216de5-f27e-47ed-99aa-346a0eb5d0cf

📥 Commits

Reviewing files that changed from the base of the PR and between 19cd20d and fd3f475.

📒 Files selected for processing (3)
  • src/vertex/components/features/auth/social-auth-section.tsx
  • src/vertex/core/auth/oauth-session.ts
  • src/vertex/core/services/network-service.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/vertex/core/auth/oauth-session.ts
  • src/vertex/components/features/auth/social-auth-section.tsx

Comment thread src/vertex/core/services/network-service.ts Outdated
Hide the social auth UI when NEXT_PUBLIC_API_URL is not set to avoid runtime crashes during OAuth initiation. Also switch oauth-session to use buildServerApiUrl when constructing the /users/auth/:provider initiation URL to ensure the API base is built appropriately. Changes touch social-auth-section.tsx and oauth-session.ts.
@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

New azure vertex changes available for preview here

1 similar comment
@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

New azure vertex changes available for preview here

Codebmk added 2 commits June 9, 2026 21:45
Allow the client to fully handle OAuth callbacks and preserve provider/redirect info.

- Middleware: always return authorized so the client-side AuthWrapper enforces protection. This is required because OAuth uses URL hash fragments (e.g. #token=...) which server-side middleware cannot read; blocking here could strip callbacks and cause redirect loops.
- Social auth: stop building a new URL and appending a success param; pass redirectAfter through as provided (redirect_after = redirectAfter).
- OAuth session: if the provider is missing in the handoff, fall back to getLastUsedOAuthProvider() so provider info is retained when possible.

These changes ensure OAuth flows and redirects are handled correctly on the client and that provider information is preserved.
@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

New azure vertex changes available for preview here

1 similar comment
@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

New azure vertex changes available for preview here

@Baalmart
Baalmart merged commit d142ed2 into staging Jun 9, 2026
27 of 28 checks passed
@Baalmart
Baalmart deleted the fix-login-vertex branch June 9, 2026 19:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants