Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,7 @@ internal/security/bundlesig/testdata/* -text
# leave a \r on the shebang and every command line, so pin the CI shell
# scripts to LF.
scripts/*.sh text eol=lf

# Spec 132 OAuth metadata goldens are byte-compared against LF-only
# MarshalIndent output; pin LF so a Windows checkout does not yield CRLF.
internal/mcplogin/testdata/*.json text eol=lf
114 changes: 114 additions & 0 deletions internal/mcplogin/limits.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package mcplogin

import (
"math"
"sync"
"time"

"github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/limiter"
)

const (
// MaxBodyBytes is the largest request body register and token accept.
MaxBodyBytes = 16 << 10
// MaxPendingRegistrations caps registrations that are not yet approved.
MaxPendingRegistrations = 50
// MaxPendingRequests caps pending authorization requests.
MaxPendingRequests = 20
)

// Endpoint names the rate-limited public endpoints.
const (
// EndpointRegister is POST /oauth/register.
EndpointRegister = "register"
// EndpointAuthorize is GET /oauth/authorize.
EndpointAuthorize = "authorize"
// EndpointToken is POST /oauth/token.
EndpointToken = "token"
)

// rateFor returns the default budget of an endpoint.
func rateFor(endpoint string) (limiter.RateSpec, bool) {
switch endpoint {
case EndpointRegister:
return limiter.RateSpec{PerMinute: 10, Burst: 5}, true
case EndpointAuthorize:
return limiter.RateSpec{PerMinute: 30, Burst: 10}, true
case EndpointToken:
return limiter.RateSpec{PerMinute: 60, Burst: 20}, true
}
return limiter.RateSpec{}, false
}

const (
// MaxTrackedKeys caps the distinct endpoint|address keys the Limiter keeps.
MaxTrackedKeys = 4096
// idleAfter is how long a key must be unseen before it may be dropped. It
// exceeds the time any bucket needs to refill completely, so dropping an
// idle key never hands a caller extra budget.
idleAfter = time.Minute
)

// Limiter rate limits the public OAuth endpoints per endpoint and remote
// address, over at most MaxTrackedKeys keys. It is safe for concurrent use.
type Limiter struct {
rates *limiter.TokenRates
now func() time.Time
mu sync.Mutex
seen map[string]time.Time
}

// NewLimiter returns a Limiter with the default rates. now is the clock; nil
// means time.Now.
func NewLimiter(now func() time.Time) *Limiter {
if now == nil {
now = time.Now
}
return &Limiter{rates: limiter.NewTokenRates(now), now: now, seen: map[string]time.Time{}}
}

// admit records key as seen now. For an unseen key at the cap it prunes idle
// keys first and, if the limiter is still full, refuses with the seconds until
// the oldest key becomes idle. Active keys are never evicted.
func (l *Limiter) admitLocked(key string) (bool, int) {
now := l.now()
if _, known := l.seen[key]; !known && len(l.seen) >= MaxTrackedKeys {
oldest := now
for k, t := range l.seen {
if now.Sub(t) >= idleAfter {
delete(l.seen, k)
} else if t.Before(oldest) {
oldest = t
}
}
if len(l.seen) >= MaxTrackedKeys {
wait := idleAfter - now.Sub(oldest)
return false, max(1, int(math.Ceil(wait.Seconds())))
}
}
l.seen[key] = now
return true, 0
}

// Allow charges one call of endpoint from remoteIP. When refused,
// retryAfterSeconds is at least 1. An unknown endpoint is not limited. A new
// address is refused while the limiter is full of active ones.
func (l *Limiter) Allow(endpoint, remoteIP string) (ok bool, retryAfterSeconds int) {
spec, known := rateFor(endpoint)
if !known {
return true, 0
}
key := endpoint + "|" + remoteIP
// One lock spans admission and the bucket charge, so a key cannot be
// pruned between the two and leave a bucket that seen does not know.
l.mu.Lock()
defer l.mu.Unlock()
if ok, retry := l.admitLocked(key); !ok {
return false, retry
}
d := l.rates.Allow(key, &spec)
if d.Allowed {
return true, 0
}
return false, max(1, int(math.Ceil(d.RetryAfter.Seconds())))
}
75 changes: 75 additions & 0 deletions internal/mcplogin/limits_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package mcplogin

import (
"sync"
"testing"
"time"
)

type fakeClock struct {
mu sync.Mutex
t time.Time
}

func (c *fakeClock) now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t }
func (c *fakeClock) advance(d time.Duration) {
c.mu.Lock()
c.t = c.t.Add(d)
c.mu.Unlock()
}

func TestLimiterBurstRefillRetryAfter(t *testing.T) {
clk := &fakeClock{t: time.Unix(1000, 0)}
l := NewLimiter(clk.now)
for i := 0; i < 5; i++ {
if ok, _ := l.Allow(EndpointRegister, "1.2.3.4"); !ok {
t.Fatalf("burst call %d refused", i)
}
}
ok, retry := l.Allow(EndpointRegister, "1.2.3.4")
if ok || retry < 1 {
t.Fatalf("expected refusal with retry>=1, got %v %d", ok, retry)
}
if ok, _ := l.Allow(EndpointRegister, "5.6.7.8"); !ok {
t.Fatal("other ip shares bucket")
}
if ok, _ := l.Allow(EndpointAuthorize, "1.2.3.4"); !ok {
t.Fatal("other endpoint shares bucket")
}
clk.advance(6 * time.Second) // 10/min -> 1 per 6 s
if ok, _ := l.Allow(EndpointRegister, "1.2.3.4"); !ok {
t.Fatal("refill failed")
}
if ok, _ := l.Allow(EndpointRegister, "1.2.3.4"); ok {
t.Fatal("only one token should have refilled")
}
}

func TestLimiterDefaults(t *testing.T) {
clk := &fakeClock{t: time.Unix(1000, 0)}
l := NewLimiter(clk.now)
count := func(ep string) int {
n := 0
for {
if ok, _ := l.Allow(ep, "9.9.9.9"); !ok {
return n
}
n++
}
}
if got := count(EndpointAuthorize); got != 10 {
t.Errorf("authorize burst %d", got)
}
if got := count(EndpointToken); got != 20 {
t.Errorf("token burst %d", got)
}
if ok, _ := l.Allow("unknown", "1.1.1.1"); !ok {
t.Error("unknown endpoint must not be limited")
}
}

func TestLimitConstants(t *testing.T) {
if MaxBodyBytes != 16<<10 || MaxPendingRegistrations != 50 || MaxPendingRequests != 20 {
t.Fatal("constants")
}
}
31 changes: 31 additions & 0 deletions internal/mcplogin/metadata.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package mcplogin

// ProtectedResourceMetadata is the RFC 9728 document for one OAuth resource
// path: the generic address when clientID is empty, else that client's.
func ProtectedResourceMetadata(origin, clientID string) map[string]any {
return map[string]any{
"resource": origin + ResourcePath(clientID),
"authorization_servers": []string{origin},
"bearer_methods_supported": []string{"header"},
}
}

// AuthorizationServerMetadata is the RFC 8414 document for this instance.
func AuthorizationServerMetadata(origin string) map[string]any {
return map[string]any{
"issuer": origin,
"authorization_endpoint": origin + "/oauth/authorize",
"token_endpoint": origin + "/oauth/token",
"registration_endpoint": origin + "/oauth/register",
"response_types_supported": []string{"code"},
"grant_types_supported": []string{"authorization_code", "refresh_token"},
"code_challenge_methods_supported": []string{"S256"},
"token_endpoint_auth_methods_supported": []string{"none"},
}
}

// Challenge is the WWW-Authenticate value that points an unauthenticated
// client at the protected-resource metadata of its address.
func Challenge(origin, clientID string) string {
return `Bearer resource_metadata="` + origin + "/.well-known/oauth-protected-resource" + ResourcePath(clientID) + `"`
}
43 changes: 43 additions & 0 deletions internal/mcplogin/metadata_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package mcplogin

import (
"encoding/json"
"os"
"path/filepath"
"testing"
)

func golden(t *testing.T, name string, v any) {
t.Helper()
got, err := json.MarshalIndent(v, "", " ") // maps marshal with sorted keys
if err != nil {
t.Fatal(err)
}
want, err := os.ReadFile(filepath.Join("testdata", name))
if err != nil {
t.Fatal(err)
}
if string(got)+"\n" != string(want) {
t.Fatalf("%s mismatch:\n%s\nwant:\n%s", name, got, want)
}
}

func TestProtectedResourceMetadataGolden(t *testing.T) {
golden(t, "protected_resource_client.json", ProtectedResourceMetadata("http://127.0.0.1:8080", "cursor"))
golden(t, "protected_resource_generic.json", ProtectedResourceMetadata("http://127.0.0.1:8080", ""))
}

func TestAuthorizationServerMetadataGolden(t *testing.T) {
golden(t, "authorization_server.json", AuthorizationServerMetadata("http://127.0.0.1:8080"))
}

func TestChallenge(t *testing.T) {
if got := Challenge("http://127.0.0.1:8080", "cursor"); got !=
`Bearer resource_metadata="http://127.0.0.1:8080/.well-known/oauth-protected-resource/mcp/oauth/cursor"` {
t.Fatal(got)
}
if got := Challenge("http://127.0.0.1:8080", ""); got !=
`Bearer resource_metadata="http://127.0.0.1:8080/.well-known/oauth-protected-resource/mcp/oauth"` {
t.Fatal(got)
}
}
35 changes: 35 additions & 0 deletions internal/mcplogin/pkce.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package mcplogin

import (
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
)

// VerifyS256 reports whether challenge is the S256 transform of verifier
// (RFC 7636): the verifier is 43 to 128 characters of the unreserved set and
// the challenge is base64url(sha256(verifier)) without padding.
func VerifyS256(verifier, challenge string) bool {
if len(verifier) < 43 || len(verifier) > 128 {
return false
}
for i := 0; i < len(verifier); i++ {
c := verifier[i]
switch {
case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9',
c == '-', c == '.', c == '_', c == '~':
default:
return false
}
}
if !ValidChallenge(challenge) {
return false
}
sum := sha256.Sum256([]byte(verifier))
want := base64.RawURLEncoding.EncodeToString(sum[:])
return subtle.ConstantTimeCompare([]byte(want), []byte(challenge)) == 1
}

// ValidChallenge reports whether s is shaped like an S256 challenge: 43
// base64url characters.
func ValidChallenge(s string) bool { return validBase64URL(s, 43) }
70 changes: 70 additions & 0 deletions internal/mcplogin/pkce_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package mcplogin

import (
"crypto/sha256"
"encoding/base64"
"strings"
"testing"
)

func challengeOf(v string) string {
sum := sha256.Sum256([]byte(v))
return base64.RawURLEncoding.EncodeToString(sum[:])
}

func TestVerifyS256RFCVector(t *testing.T) {
v := "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
c := "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
if !VerifyS256(v, c) {
t.Fatal("RFC vector must verify")
}
if !ValidChallenge(c) {
t.Fatal("challenge must be valid")
}
}

func TestVerifyS256Rejects(t *testing.T) {
v := "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
c := "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
if VerifyS256(v+"x", c) {
t.Error("wrong verifier")
}
if VerifyS256(v, c[:42]+"A") {
t.Error("wrong challenge")
}
if VerifyS256(strings.Repeat("a", 42), challengeOf(strings.Repeat("a", 42))) ||
VerifyS256(strings.Repeat("a", 129), challengeOf(strings.Repeat("a", 129))) {
t.Error("length bounds")
}
if VerifyS256(v[:42]+"!", challengeOf(v[:42]+"!")) || VerifyS256(v[:42]+" ", challengeOf(v[:42]+" ")) {
t.Error("bad chars")
}
if VerifyS256("", "") {
t.Error("empty")
}
}

func TestVerifyS256Bounds(t *testing.T) {
for _, n := range []int{43, 128} {
v := strings.Repeat("a", n)
if !VerifyS256(v, challengeOf(v)) {
t.Errorf("length %d should be valid", n)
}
}
v := "a-._~" + strings.Repeat("Z", 40)
if !VerifyS256(v, challengeOf(v)) {
t.Error("unreserved set")
}
}

func TestValidChallenge(t *testing.T) {
good := strings.Repeat("A", 43)
if !ValidChallenge(good) {
t.Error("good")
}
for _, bad := range []string{"", good[:42], good + "A", good[:42] + "=", good[:42] + "+", good[:42] + "/"} {
if ValidChallenge(bad) {
t.Errorf("%q accepted", bad)
}
}
}
Loading
Loading