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,