Repository navigation
Conversation
The SPA's OAuth login button submitted a form to
POST /api/v1/auth/oauth/{id}/init and let the 302 carry the browser to the
identity provider. The frontend is served with `form-action 'self'`, and
browsers enforce form-action across redirects, so the cross-origin hop was
blocked — silently, with no console error and no navigation.
The failure is invisible from either side: the server logs a clean 302 and
the IdP never receives a request, so every external identity provider looks
like a dead button. Diagnosed against a live Authentik deployment where the
button had been "doing nothing" through 29 consecutive clicks.
Add POST /api/v1/auth/oauth/{id}/start, which returns the authorize URL as
JSON so the SPA can navigate with window.location — a scripted navigation,
which form-action does not govern. /init keeps its 302 untouched for
existing non-browser callers, so this is additive under the v1 API rules.
Session setup (state, PKCE, next-URL normalisation) is extracted into
beginAuthorize and shared, so the two entry points cannot drift.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01N7bPXi6NaUecM18rfWKAmP
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01N7bPXi6NaUecM18rfWKAmP
📝 WalkthroughWalkthroughThe OAuth flow adds a POST ChangesSPA OAuth flow
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant LoginPage
participant OAuthHandler
participant OAuthSessionStore
participant OAuthProvider
LoginPage->>OAuthHandler: POST /auth/oauth/{install_id}/start
OAuthHandler->>OAuthProvider: Create authorization URL
OAuthHandler->>OAuthSessionStore: Store nonce and OAuth state
OAuthHandler-->>LoginPage: Return authorize_url JSON
LoginPage->>OAuthProvider: Navigate to authorization URL
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/auth/oauth_handler.go (1)
162-184: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winValidate the provider authorization URL before returning it.
Line 184 returns a plugin-controlled URL to
HandleStart. The SPA passes this value towindow.location.assign. Ajavascript:ordata:URL can cause client-side URL-scheme injection. This is not SSRF because the server does not fetch the URL.Parse the URL before session insertion. Require an absolute
httporhttpsURL with a host.Proposed fix
+ authorizeURL := resp.GetAuthorizeUrl() + parsedURL, err := url.Parse(authorizeURL) + if err != nil || parsedURL.Host == "" || + (parsedURL.Scheme != "https" && parsedURL.Scheme != "http") { + http.Error(w, "plugin returned invalid authorize_url", http.StatusBadGateway) + return "", false + } + psBytes, _ := json.Marshal(resp.GetProviderState().AsMap()) sess := OAuthSession{ ... - return resp.GetAuthorizeUrl(), true + return authorizeURL, true🤖 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 `@internal/auth/oauth_handler.go` around lines 162 - 184, Validate resp.GetAuthorizeUrl() before inserting the OAuth session or returning it from the surrounding handler: parse the URL, require it to be absolute, use only the http or https scheme, and require a non-empty host. On parse or validation failure, return an appropriate client/gateway error without inserting the session; preserve the existing valid URL flow.
🤖 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 `@internal/api/router.go`:
- Line 1842: Update the public OAuth `/start` route registration in the
surrounding router setup to wrap `oauthHandler.HandleStart` with
`deps.RateLimitMW.AuthEndpointHandler(...)` when the rate limiter is available,
while preserving a reliable fallback when it is unavailable. Ensure
unauthenticated requests use the auth endpoint limiter before invoking the
plugin RPC and creating an OAuth session.
- Around line 1840-1842: Add OAuth start capability discovery across
internal/api/router.go:1840-1842 and web/src/pages/Login.tsx:256-259. In the
router, expose a capability endpoint or field indicating whether /start is
supported; in Login.tsx, query and honor that capability before selecting
/start, preserving /init for unsupported servers or showing an explicit
unsupported-server error.
---
Outside diff comments:
In `@internal/auth/oauth_handler.go`:
- Around line 162-184: Validate resp.GetAuthorizeUrl() before inserting the
OAuth session or returning it from the surrounding handler: parse the URL,
require it to be absolute, use only the http or https scheme, and require a
non-empty host. On parse or validation failure, return an appropriate
client/gateway error without inserting the session; preserve the existing valid
URL flow.
🪄 Autofix
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 Plus
Run ID: 77a6e3e9-57ea-4841-b113-d8c6452ccabc
📒 Files selected for processing (5)
internal/api/router.gointernal/auth/oauth_handler.gointernal/auth/oauth_handler_test.gointernal/auth/service.goweb/src/pages/Login.tsx
| // /start is what the SPA uses; /init's cross-origin | ||
| // redirect is blocked by the frontend's form-action CSP. | ||
| r.Post("/start", oauthHandler.HandleStart) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Add capability discovery before clients use OAuth start.
The new /api/v1 route has no capability contract. The web client calls it directly. This breaks OAuth login when a new web bundle connects to a server that only supports /init.
internal/api/router.go#L1840-L1842: expose a capability endpoint or capability field for OAuth start support.web/src/pages/Login.tsx#L256-L259: use that capability before selecting/start; retain/initbehavior or show an explicit unsupported-server error.
As per coding guidelines, “Expose capability endpoints for new /api/v1 features instead of relying on client version sniffing.”
📍 Affects 2 files
internal/api/router.go#L1840-L1842(this comment)web/src/pages/Login.tsx#L256-L259
🤖 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 `@internal/api/router.go` around lines 1840 - 1842, Add OAuth start capability
discovery across internal/api/router.go:1840-1842 and
web/src/pages/Login.tsx:256-259. In the router, expose a capability endpoint or
field indicating whether /start is supported; in Login.tsx, query and honor that
capability before selecting /start, preserving /init for unsupported servers or
showing an explicit unsupported-server error.
Source: Coding guidelines
| r.Post("/init", oauthHandler.HandleInit) | ||
| // /start is what the SPA uses; /init's cross-origin | ||
| // redirect is blocked by the frontend's form-action CSP. | ||
| r.Post("/start", oauthHandler.HandleStart) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Rate-limit the public OAuth start endpoint.
Line 1842 allows unauthenticated callers to invoke a plugin RPC and create an OAuth session without the auth endpoint limiter. Repeated requests can exhaust plugin capacity and session storage.
Register /start through deps.RateLimitMW.AuthEndpointHandler(...) when the limiter is available. As per coding guidelines, internal/**/*.go must prioritize reliability and predictable behavior under load and failures.
🤖 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 `@internal/api/router.go` at line 1842, Update the public OAuth `/start` route
registration in the surrounding router setup to wrap `oauthHandler.HandleStart`
with `deps.RateLimitMW.AuthEndpointHandler(...)` when the rate limiter is
available, while preserving a reliable fallback when it is unavailable. Ensure
unauthenticated requests use the auth endpoint limiter before invoking the
plugin RPC and creating an OAuth session.
Source: Coding guidelines
Problem
The SPA's OAuth login button never worked against an external identity provider.
Login.tsxsubmitted a<form method="post">toPOST /api/v1/auth/oauth/{install_id}/initand let the302carry the browserto the IdP. But the frontend is served with
form-action 'self'(
internal/server/frontend.go), and browsers enforceform-actionacrossredirects — so the moment the redirect left our origin, the navigation was
blocked.
It fails invisibly from both ends: the server logs a clean
302, and the IdPnever receives a request. No console error, no navigation, nothing in devtools
network beyond the successful POST. The button simply appears dead.
This was diagnosed against a live Authentik deployment. The user clicked the
button 29 times; the server logged 29 ×
302and Authentik logged zeroauthorize requests in the same window. That asymmetry is the whole tell.
Prior art in this area: #30 (providers filtered out before render) and #31
(auto-provision bcrypt limit) fixed earlier links in the same chain — with
those resolved, this CSP interaction is what still stood between a configured
provider and a working login.
Approach
Add
POST /api/v1/auth/oauth/{install_id}/start, which returns the authorizeURL as JSON:
{ "authorize_url": "https://idp.example/application/o/authorize/?..." }The SPA fetches it and navigates with
window.location.assign(...)— ascripted navigation, which
form-actiondoes not govern./initkeeps its302untouched, so existing non-browser callers areunaffected and this stays additive under the v1 API rules in
CLAUDE.md.nextnormalisation and sessioninsertion are extracted into
beginAuthorizeand shared by both handlers, sothe two entry points cannot drift apart.
Why not just widen the CSP
Adding IdP origins to
form-actionwas the other option, and it is worse: theserver does not know the issuer origin (it lives in the plugin's own config,
not in
plugin_runtime_configs), so it would have to interrogate every OAuthplugin at page-render time and would silently regress to a dead button whenever
a plugin was slow or unavailable. The redirect is also the only part of the
flow that has to cross origins — removing the need for it is the smaller change.
Risks and follow-ups
Called out honestly rather than buried:
form-actionwas accidental containment. With the form POST, acompromised auth plugin returning a hostile
authorize_urlhad its redirectblocked by CSP. Navigating by script removes that. The trust boundary is
unchanged in practice — plugins are already trusted host-side code with far
better options — but it is a real reduction in defence-in-depth and should be
a conscious decision, not a side effect.
/startis unauthenticated and not rate-limited, exactly like/init.Each call inserts an
oauth_sessionsrow and makes a plugin RPC. This ispre-existing rather than introduced, but the surface is now doubled, and
/loginnext door is rate-limited viaRateLimitMW.AuthEndpointHandler.Worth a follow-up to bring both OAuth entry points under the same limiter; I
left it out to keep this to one concern.
/initnow has no first-party caller. Kept deliberately forback-compat per the v1 rules; worth a Deprecation/Sunset decision later.
startingOauthis not reset on success, since the page is navigatingaway. If a navigation were ever blocked the buttons would stay disabled.
Considered and accepted — a same-gesture
location.assignis not silentlyblocked the way form-action redirects are — but noted given that is precisely
the failure mode this PR fixes.
form happily submitted 29 times.
Tests
TestOAuthStart_ReturnsAuthorizeURLAsJSONNotARedirectasserts a 200, a JSONbody, and no
Locationheader — the redirect is the thing that breaks.TestOAuthStart_ShareSessionSetupWithInitpins that/initstill returns 302,that
/startreturns 200, and that both normalise an open-redirectnextidentically.
Both were confirmed to fail against the old behaviour before being committed —
reverting
HandleStarttohttp.Redirectproduces:Verification
Real output, run on this branch.
golangci-lint run --new-from-merge-base=upstream/main ./internal/auth/... ./internal/api/...(matching how CI invokes it):
go test ./internal/auth/... ./internal/api/...:cd web && pnpm run lint:157 pre-existing warnings across the tree (
react-refresh/only-export-componentsand similar); 0 errors, and zero findings in
src/pages/Login.tsx.cd web && pnpm run format:check:make verify-local-paths:pnpm exec vitest run src/hooks/AuthProvider.test.tsx:End-to-end
Built and deployed to a live instance (Silo + Authentik over OIDC via
silo-plugin-oidc-login). Before: 29 ×302server-side, zero authorizerequests at the IdP. After: the button reaches Authentik, authenticates, and
returns to
/api/v1/auth/oauth/{id}/callback. Confirmed on the deployed build:The remaining failure after this fix was on the IdP side, not in this code
(Authentik's stock
emailscope mapping hardcodesemail_verified: False,which the plugin rejects) — noted only to be clear about how far the flow was
actually driven.
Scope
No open scope item covers this; #30 and #31 are the closest, both closed. Happy
to file one and relink if you'd prefer it tracked under a capability epic.
AI Disclosure
form-actionas incidental containment against a rogue plugin redirect —judged acceptable since plugins are already trusted host-side code, and
disclosed above rather than silently accepted. (2)
/startinherits/init'slack of rate limiting while doubling that surface — left as a stated
follow-up to keep one concern per PR. (3)
startingOauthnever resets on thesuccess path — considered and accepted, documented above. (4) A stale comment
in
internal/auth/service.gostill pointed the login UI at/init; that onewas a real defect in the diff's blast radius and is fixed in 016aeab. I also
verified the new tests fail against the pre-fix behaviour rather than assuming
they were meaningful, and confirmed no other in-tree caller of
/initremains.Summary by CodeRabbit
New Features
Bug Fixes