sec(oauth): phase-2 attack-path review (forgejo-mcp-broker-wgo)

Structured review of every OAuth/auth handler against the standard
attack catalog. Findings table added to design.md §8.2.

Two real issues found and fixed:

  - Refresh-token replay race: tokenRefreshGrant read the row, validated
    it, then minted a new pair before unconditionally revoking the old
    refresh. Two concurrent /token requests with the same refresh would
    both pass validation and both mint a fresh pair — token-quota
    duplication and a hint to a stolen-refresh attacker. Fixed with the
    same atomic UPDATE rows-affected pattern already used for auth-code
    single-use. New TestToken_Refresh_ConcurrentReplay_OnlyOneSucceeds
    races two goroutines and verifies exactly one wins.

  - Permissive redirect_uri schemes: validateRedirectURI accepted any
    non-empty scheme, including javascript: and data:. Tightened to
    require https, http for loopback only, or a reverse-DNS private-use
    scheme per RFC 8252 §7.1. TestValidateRedirectURI updated to cover
    each variant including the rejected javascript:/data: cases.

Items deferred to backlog (already filed):
  - Rate limits on /oauth/register and /oauth/token (-ttl)
  - --token-fd to close the /proc/<pid>/environ window (-1n2)
  - AES-GCM at-rest encryption of Forgejo tokens (-sd4)

Closes forgejo-mcp-broker-wgo. Phase 2 complete.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ole-Morten Duesund 2026-04-27 17:37:00 +02:00
commit 8369ec2cc7
5 changed files with 140 additions and 21 deletions

View file

@ -367,13 +367,37 @@ func validateRedirectURI(raw string) error {
if err != nil {
return fmt.Errorf("redirect_uri %q: %w", raw, err)
}
if u.Scheme == "" {
return fmt.Errorf("redirect_uri %q: missing scheme", raw)
// RFC 6749 §3.1.2.1 requires absolute URIs. We further restrict to
// schemes we trust:
// - https: the production case
// - http: only for loopback hosts (local development)
// - private-use schemes per RFC 8252 §7.1 (e.g. claude://, com.foo://)
// Pseudo-schemes that allow code execution (javascript:, data:) are
// rejected to keep a future naive client from rendering an attacker-
// supplied URI as content.
scheme := u.Scheme
switch {
case scheme == "https":
return nil
case scheme == "http":
host := u.Hostname()
if host == "localhost" || host == "127.0.0.1" || host == "::1" {
return nil
}
return fmt.Errorf("redirect_uri %q: http only allowed for loopback hosts", raw)
case scheme == "javascript" || scheme == "data" || scheme == "":
return fmt.Errorf("redirect_uri %q: scheme %q is not allowed", raw, scheme)
default:
// Anything else: must be a private-use URI scheme that contains a
// dot (e.g. com.example.app:/) per RFC 8252 §7.1. Single-word
// schemes like "javascript" are caught above; this keeps the door
// open for legitimate mobile/desktop OAuth flows without a
// hardcoded allowlist.
if !strings.Contains(scheme, ".") {
return fmt.Errorf("redirect_uri %q: non-https scheme %q must be a reverse-DNS private-use scheme", raw, scheme)
}
return nil
}
// RFC 6749 §3.1.2.1 requires absolute URIs; we additionally require
// http/https or claude.ai's documented custom scheme. Accept anything
// non-empty for now; tighten later if needed.
return nil
}
// ============================================================================
@ -786,11 +810,26 @@ func (s *Server) tokenRefreshGrant(w http.ResponseWriter, r *http.Request) {
return
}
// Mint a new access token. Refresh-token rotation: also issue a new
// refresh token and revoke the old one.
// Atomically revoke the old refresh token. Two concurrent refresh
// requests with the same token would otherwise both pass the read
// above and each mint a fresh pair — quota duplication and a hint
// to a stolen-refresh attacker that the legitimate user is also
// active. Same single-shot pattern as the auth-code grant.
now := s.now().Unix()
res, err := s.store.DB().ExecContext(r.Context(),
`UPDATE refresh_tokens SET revoked_at = ? WHERE token_hash = ? AND revoked_at IS NULL`,
now, rtHash)
if err != nil {
writeOAuthError(w, http.StatusInternalServerError, "server_error", "")
return
}
if n, _ := res.RowsAffected(); n != 1 {
writeOAuthError(w, http.StatusBadRequest, "invalid_grant", "refresh token already used")
return
}
newAccess := secureToken(32)
newRefresh := secureToken(32)
now := s.now().Unix()
tx, err := s.store.DB().BeginTx(r.Context(), nil)
if err != nil {
@ -820,18 +859,12 @@ func (s *Server) tokenRefreshGrant(w http.ResponseWriter, r *http.Request) {
writeOAuthError(w, http.StatusInternalServerError, "server_error", "")
return
}
// Revoke the old refresh token (rotation per RFC 6749 §10.4).
if _, err := tx.ExecContext(r.Context(),
`UPDATE refresh_tokens SET revoked_at = ? WHERE token_hash = ?`,
now, rtHash); err != nil {
_ = tx.Rollback()
writeOAuthError(w, http.StatusInternalServerError, "server_error", "")
return
}
// Old refresh token already revoked above (atomic single-shot).
if err := tx.Commit(); err != nil {
writeOAuthError(w, http.StatusInternalServerError, "server_error", "")
return
}
_ = oldAccessHash // retained for potential future "revoke old access on refresh" tightening
writeJSON(w, http.StatusOK, tokenResponse{
AccessToken: newAccess,

View file

@ -88,8 +88,14 @@ func TestValidateRedirectURI(t *testing.T) {
ok bool
}{
{"https", "https://app.example.com/cb", true},
{"http_loopback", "http://localhost:1234/cb", true},
{"custom_scheme", "claude://oauth/cb", true},
{"http_loopback_localhost", "http://localhost:1234/cb", true},
{"http_loopback_v4", "http://127.0.0.1/cb", true},
{"http_loopback_v6", "http://[::1]/cb", true},
{"http_non_loopback", "http://app.example.com/cb", false},
{"reverse_dns_scheme", "com.example.claudeapp:/cb", true},
{"single_word_scheme", "claude://oauth/cb", false},
{"javascript_scheme", "javascript:alert(1)", false},
{"data_scheme", "data:text/html,<h1>hi</h1>", false},
{"missing_scheme", "app.example.com/cb", false},
{"unparseable", "://no-scheme", false},
}

View file

@ -11,6 +11,7 @@ import (
"net/url"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
@ -861,6 +862,59 @@ func TestToken_Refresh_WrongClientID(t *testing.T) {
}
}
func TestToken_Refresh_ConcurrentReplay_OnlyOneSucceeds(t *testing.T) {
// Two goroutines race the same refresh token. Without an atomic
// single-shot UPDATE, both would mint a new pair. With it, exactly
// one succeeds.
fx := newFixture(t)
cid := fx.registerClient("https://app.example.com/cb")
tok := runFullFlow(t, fx, "https://app.example.com/cb", cid, "verifier-rfrace")
form := url.Values{
"grant_type": {"refresh_token"},
"refresh_token": {tok.RefreshToken},
"client_id": {cid},
}
type result struct {
status int
body string
}
results := make(chan result, 2)
var wg sync.WaitGroup
for i := 0; i < 2; i++ {
wg.Add(1)
go func() {
defer wg.Done()
resp, err := http.PostForm(fx.httpServer.URL+"/oauth/token", form)
if err != nil {
results <- result{status: 0, body: err.Error()}
return
}
body, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
results <- result{status: resp.StatusCode, body: string(body)}
}()
}
wg.Wait()
close(results)
var ok, failed int
for r := range results {
switch r.status {
case http.StatusOK:
ok++
case http.StatusBadRequest:
failed++
default:
t.Errorf("unexpected status %d: %s", r.status, r.body)
}
}
if ok != 1 || failed != 1 {
t.Errorf("concurrent refresh outcome = (ok=%d, failed=%d), want (1, 1)", ok, failed)
}
}
func TestToken_Refresh_RevokedToken(t *testing.T) {
fx := newFixture(t)
cid := fx.registerClient("https://app.example.com/cb")