Skip to content

fix(auth): make OAuth login reachable from the browser - #560

Closed
RXWatcher wants to merge 2 commits into
Silo-Server:mainfrom
RXWatcher:fix/oauth-login-blocked-by-form-action-csp
Closed

RXWatcher wants to merge 2 commits into
Silo-Server:mainfrom
RXWatcher:fix/oauth-login-blocked-by-form-action-csp

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The SPA's OAuth login button never worked against an external identity provider.

Login.tsx submitted a <form method="post"> to
POST /api/v1/auth/oauth/{install_id}/init and let the 302 carry the browser
to the IdP. But the frontend is served with form-action 'self'
(internal/server/frontend.go), and browsers enforce form-action across
redirects
— 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 IdP
never 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 × 302 and Authentik logged zero
authorize 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 authorize
URL as JSON:

{ "authorize_url": "https://idp.example/application/o/authorize/?..." }

The SPA fetches it and navigates with window.location.assign(...) — a
scripted navigation, which form-action does not govern.

  • /init keeps its 302 untouched, so existing non-browser callers are
    unaffected and this stays additive under the v1 API rules in CLAUDE.md.
  • State signing, PKCE provider-state, next normalisation and session
    insertion are extracted into beginAuthorize and shared by both handlers, so
    the two entry points cannot drift apart.

Why not just widen the CSP

Adding IdP origins to form-action was the other option, and it is worse: the
server 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 OAuth
plugin 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-action was accidental containment. With the form POST, a
    compromised auth plugin returning a hostile authorize_url had its redirect
    blocked 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.
  • /start is unauthenticated and not rate-limited, exactly like /init.
    Each call inserts an oauth_sessions row and makes a plugin RPC. This is
    pre-existing rather than introduced, but the surface is now doubled, and
    /login next door is rate-limited via RateLimitMW.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.
  • /init now has no first-party caller. Kept deliberately for
    back-compat per the v1 rules; worth a Deprecation/Sunset decision later.
  • startingOauth is not reset on success, since the page is navigating
    away. If a navigation were ever blocked the buttons would stay disabled.
    Considered and accepted — a same-gesture location.assign is not silently
    blocked the way form-action redirects are — but noted given that is precisely
    the failure mode this PR fixes.
  • Minor upside: the button is now disabled while a start is in flight. The old
    form happily submitted 29 times.

Tests

TestOAuthStart_ReturnsAuthorizeURLAsJSONNotARedirect asserts a 200, a JSON
body, and no Location header — the redirect is the thing that breaks.
TestOAuthStart_ShareSessionSetupWithInit pins that /init still returns 302,
that /start returns 200, and that both normalise an open-redirect next
identically.

Both were confirmed to fail against the old behaviour before being committed —
reverting HandleStart to http.Redirect produces:

--- FAIL: TestOAuthStart_ReturnsAuthorizeURLAsJSONNotARedirect (0.00s)
    oauth_handler_test.go:132: code = 302 body =
--- FAIL: TestOAuthStart_ShareSessionSetupWithInit (0.00s)
    oauth_handler_test.go:188: start code = 302, want 200
FAIL

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):

0 issues.

go test ./internal/auth/... ./internal/api/...:

ok  	github.com/Silo-Server/silo-server/internal/auth	0.321s
ok  	github.com/Silo-Server/silo-server/internal/api	0.701s
ok  	github.com/Silo-Server/silo-server/internal/api/handlers	90.478s
ok  	github.com/Silo-Server/silo-server/internal/api/middleware	4.094s

cd web && pnpm run lint:

✖ 157 problems (0 errors, 157 warnings)

157 pre-existing warnings across the tree (react-refresh/only-export-components
and similar); 0 errors, and zero findings in src/pages/Login.tsx.

cd web && pnpm run format:check:

Checking formatting...
All matched files use Prettier code style!

make verify-local-paths:

scripts/check-local-path-leaks.sh

pnpm exec vitest run src/hooks/AuthProvider.test.tsx:

 Test Files  1 passed (1)
      Tests  1 passed (1)

End-to-end

Built and deployed to a live instance (Silo + Authentik over OIDC via
silo-plugin-oidc-login). Before: 29 × 302 server-side, zero authorize
requests at the IdP. After: the button reaches Authentik, authenticates, and
returns to /api/v1/auth/oauth/{id}/callback. Confirmed on the deployed build:

$ curl -s -X POST https://<host>/api/v1/auth/oauth/5/start
{"authorize_url":"https://<idp>/application/o/authorize/?client_id=...&code_challenge_method=S256&..."}

$ curl -s -o /dev/null -w "%{http_code}\n" -X POST https://<host>/api/v1/auth/oauth/5/init
302

The remaining failure after this fix was on the IdP side, not in this code
(Authentik's stock email scope mapping hardcodes email_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

  • Tool(s): Claude Code
  • Model(s): claude-opus-5[1m]
  • Involvement: fully AI-generated
  • Adversarial review: my own review of the diff raised four things. (1) Losing
    form-action as 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) /start inherits /init's
    lack of rate limiting while doubling that surface — left as a stated
    follow-up to keep one concern per PR. (3) startingOauth never resets on the
    success path — considered and accepted, documented above. (4) A stale comment
    in internal/auth/service.go still pointed the login UI at /init; that one
    was 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 /init remains.

Summary by CodeRabbit

  • New Features

    • Added OAuth sign-in support for single-page app navigation.
    • OAuth sign-in buttons now request authorization URLs and navigate browsers to the provider.
    • Sign-in buttons are disabled while requests are processing.
  • Bug Fixes

    • Added clear notifications when authorization URLs are unavailable or requests fail.
    • Preserved OAuth session setup and return URL handling across sign-in flows.

RXWatcher and others added 2 commits August 7, 2026 17:13
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
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The OAuth flow adds a POST /start endpoint that returns an authorization URL as JSON. The login page uses this endpoint for browser navigation. Existing /init redirects and OAuth session setup remain supported.

Changes

SPA OAuth flow

Layer / File(s) Summary
Shared authorization setup
internal/auth/oauth_handler.go
beginAuthorize centralizes OAuth validation, provider setup, nonce generation, authorization URL creation, and session storage. HandleStart returns JSON, while HandleInit continues to redirect.
Backend route and flow validation
internal/api/router.go, internal/auth/oauth_handler_test.go, internal/auth/service.go
The router exposes the /start endpoint. Tests validate the JSON response, shared session state, URL normalization, and preserved /init redirect behavior. Documentation references /start.
Login page OAuth navigation
web/src/pages/Login.tsx
OAuth buttons request authorization URLs, disable during requests, show errors, and navigate to the provider URL.

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
Loading

Suggested reviewers: quick104

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: enabling OAuth login from the browser.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ 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.

@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

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 win

Validate the provider authorization URL before returning it.

Line 184 returns a plugin-controlled URL to HandleStart. The SPA passes this value to window.location.assign. A javascript: or data: 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 http or https URL 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

📥 Commits

Reviewing files that changed from the base of the PR and between fa1d7ba and 016aeab.

📒 Files selected for processing (5)
  • internal/api/router.go
  • internal/auth/oauth_handler.go
  • internal/auth/oauth_handler_test.go
  • internal/auth/service.go
  • web/src/pages/Login.tsx

Comment thread internal/api/router.go
Comment on lines +1840 to +1842
// /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)

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.

🎯 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 /init behavior 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

Comment thread internal/api/router.go
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)

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.

🩺 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

@Quick104 Quick104 closed this Oct 7, 2026
@Rhainland Rhainland mentioned this pull request Oct 13, 2026
13 tasks done
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.

2 participants