feat(oauth): authorization-server endpoints (forgejo-mcp-broker-pur)
Implements internal/oauth, the broker's OAuth 2.1 AS surface that
Claude.ai (and other MCP clients) talk to. User authentication is
delegated to upstream Forgejo via internal/forgejo.
Endpoints:
POST /oauth/register — RFC 7591 dynamic client registration
GET /oauth/authorize — RFC 6749 + 7636 PKCE (S256 only)
GET /oauth/callback — Forgejo redirects back here after consent
POST /oauth/token — authorization_code + refresh_token grants
POST /oauth/revoke — RFC 7009
Security model:
- PKCE required, S256 only — plain method rejected per OAuth 2.1
- Every broker-issued access/refresh token stored as hex(sha256(plain));
plaintext leaves the broker exactly once in the /token response body
- Refresh-token rotation: each refresh issues a new token pair and
revokes the old refresh (RFC 6749 §10.4)
- Auth-code single-use enforced atomically via UPDATE...WHERE used_at IS
NULL with rows-affected check, blocking the concurrent-replay race
- Issuer URL sourced from cfg.Issuer at construction time, never from
inbound headers — prevents host-header injection on /.well-known
metadata that ships in 2d
- redirect_uri must match a registered URI exactly (no prefix/wildcard)
Pending-authorization state (between /authorize and /callback) lives in
an in-memory sync.Map with a 1-minute reaper goroutine. A broker restart
drops them, forcing the user to re-authorize — acceptable trade-off
versus introducing a fifth table.
Tests: 81.0% coverage with ~20 cases across happy paths, every required-
field error, PKCE failure, code-replay, refresh expiry/revocation,
client-id and redirect-uri mismatches, Forgejo-side errors, and the
reaper logic itself (internal test).
Closes forgejo-mcp-broker-pur. The OAuth keystone is in place; phase 2c
unblocks discovery (2d) and security review (2e), and combined with the
existing supervisor + bridge it unblocks the session glue work in
phase 5.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 17:04:34 +02:00
|
|
|
package oauth
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"crypto/sha256"
|
|
|
|
|
"encoding/base64"
|
|
|
|
|
"strings"
|
|
|
|
|
"testing"
|
|
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// reapPending only runs every minute via the background ticker, so
|
|
|
|
|
// production tests can't drive it within a reasonable timeout. This
|
|
|
|
|
// internal test exercises the reaper logic directly.
|
|
|
|
|
func TestReapPending_RemovesExpired(t *testing.T) {
|
|
|
|
|
now := time.Date(2026, 4, 27, 12, 0, 0, 0, time.UTC)
|
|
|
|
|
s := &Server{now: func() time.Time { return now }}
|
|
|
|
|
|
|
|
|
|
s.pending.Store("expired-1", &pendingAuth{expiresAt: now.Add(-time.Minute)})
|
|
|
|
|
s.pending.Store("expired-2", &pendingAuth{expiresAt: now.Add(-time.Hour)})
|
|
|
|
|
s.pending.Store("fresh", &pendingAuth{expiresAt: now.Add(time.Hour)})
|
|
|
|
|
|
|
|
|
|
s.reapPending()
|
|
|
|
|
|
|
|
|
|
for _, key := range []string{"expired-1", "expired-2"} {
|
|
|
|
|
if _, ok := s.pending.Load(key); ok {
|
|
|
|
|
t.Errorf("%q should have been reaped", key)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if _, ok := s.pending.Load("fresh"); !ok {
|
|
|
|
|
t.Error("fresh entry was wrongly reaped")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// secureToken's output is non-deterministic, so we test shape: hex,
|
|
|
|
|
// expected length, and that two consecutive calls differ.
|
|
|
|
|
func TestSecureToken_Shape(t *testing.T) {
|
|
|
|
|
a := secureToken(16)
|
|
|
|
|
b := secureToken(16)
|
|
|
|
|
if a == b {
|
|
|
|
|
t.Error("two secureToken calls produced identical output")
|
|
|
|
|
}
|
|
|
|
|
if len(a) != 32 {
|
|
|
|
|
t.Errorf("secureToken(16) length = %d, want 32", len(a))
|
|
|
|
|
}
|
|
|
|
|
for _, c := range a {
|
|
|
|
|
if !strings.ContainsRune("0123456789abcdef", c) {
|
|
|
|
|
t.Errorf("non-hex character %q in token", c)
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestVerifyPKCE_Roundtrip(t *testing.T) {
|
|
|
|
|
verifier := "the-quick-brown-fox-jumps-over-the-lazy-dog-12345678"
|
|
|
|
|
sum := sha256.Sum256([]byte(verifier))
|
|
|
|
|
challenge := base64.RawURLEncoding.EncodeToString(sum[:])
|
|
|
|
|
|
|
|
|
|
if !verifyPKCE(verifier, challenge) {
|
|
|
|
|
t.Error("verifyPKCE should accept matching verifier+challenge")
|
|
|
|
|
}
|
|
|
|
|
if verifyPKCE(verifier, challenge+"x") {
|
|
|
|
|
t.Error("verifyPKCE should reject a mutated challenge")
|
|
|
|
|
}
|
|
|
|
|
if verifyPKCE("WRONG", challenge) {
|
|
|
|
|
t.Error("verifyPKCE should reject a wrong verifier")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestUserIDInt64(t *testing.T) {
|
|
|
|
|
cases := map[string]int64{
|
|
|
|
|
"42": 42,
|
|
|
|
|
"": 0,
|
|
|
|
|
"abc": 0,
|
|
|
|
|
"123abc": 0,
|
|
|
|
|
"99999999999": 99999999999,
|
|
|
|
|
}
|
|
|
|
|
for in, want := range cases {
|
|
|
|
|
if got := userIDInt64(in); got != want {
|
|
|
|
|
t.Errorf("userIDInt64(%q) = %d, want %d", in, got, want)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestValidateRedirectURI(t *testing.T) {
|
|
|
|
|
cases := []struct {
|
|
|
|
|
name string
|
|
|
|
|
in string
|
|
|
|
|
ok bool
|
|
|
|
|
}{
|
|
|
|
|
{"https", "https://app.example.com/cb", true},
|
2026-04-27 17:37:00 +02:00
|
|
|
{"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},
|
feat(oauth): authorization-server endpoints (forgejo-mcp-broker-pur)
Implements internal/oauth, the broker's OAuth 2.1 AS surface that
Claude.ai (and other MCP clients) talk to. User authentication is
delegated to upstream Forgejo via internal/forgejo.
Endpoints:
POST /oauth/register — RFC 7591 dynamic client registration
GET /oauth/authorize — RFC 6749 + 7636 PKCE (S256 only)
GET /oauth/callback — Forgejo redirects back here after consent
POST /oauth/token — authorization_code + refresh_token grants
POST /oauth/revoke — RFC 7009
Security model:
- PKCE required, S256 only — plain method rejected per OAuth 2.1
- Every broker-issued access/refresh token stored as hex(sha256(plain));
plaintext leaves the broker exactly once in the /token response body
- Refresh-token rotation: each refresh issues a new token pair and
revokes the old refresh (RFC 6749 §10.4)
- Auth-code single-use enforced atomically via UPDATE...WHERE used_at IS
NULL with rows-affected check, blocking the concurrent-replay race
- Issuer URL sourced from cfg.Issuer at construction time, never from
inbound headers — prevents host-header injection on /.well-known
metadata that ships in 2d
- redirect_uri must match a registered URI exactly (no prefix/wildcard)
Pending-authorization state (between /authorize and /callback) lives in
an in-memory sync.Map with a 1-minute reaper goroutine. A broker restart
drops them, forcing the user to re-authorize — acceptable trade-off
versus introducing a fifth table.
Tests: 81.0% coverage with ~20 cases across happy paths, every required-
field error, PKCE failure, code-replay, refresh expiry/revocation,
client-id and redirect-uri mismatches, Forgejo-side errors, and the
reaper logic itself (internal test).
Closes forgejo-mcp-broker-pur. The OAuth keystone is in place; phase 2c
unblocks discovery (2d) and security review (2e), and combined with the
existing supervisor + bridge it unblocks the session glue work in
phase 5.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 17:04:34 +02:00
|
|
|
{"missing_scheme", "app.example.com/cb", false},
|
|
|
|
|
{"unparseable", "://no-scheme", false},
|
|
|
|
|
}
|
|
|
|
|
for _, tc := range cases {
|
|
|
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
|
|
|
err := validateRedirectURI(tc.in)
|
|
|
|
|
if tc.ok && err != nil {
|
|
|
|
|
t.Errorf("expected ok, got %v", err)
|
|
|
|
|
}
|
|
|
|
|
if !tc.ok && err == nil {
|
|
|
|
|
t.Error("expected error, got nil")
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|