Files
magpie/internal/gateway/key_limit.go
T
yetone bf0f3e3f73 library: a remote MCP server signed in once in magpie is used by every agent without signing in again (#615) — a streamable-HTTP server behind OAuth (Neon, Notion, Supabase) had each agent run its own sign-in. The server's editor now has Sign in: magpie finds the authorization server from the server's 401 (RFC 9728 protected-resource metadata, RFC 8414/OIDC metadata, else the 2025-03 /authorize, /token, /register at its origin), registers itself (RFC 7591, a 127.0.0.1 redirect), opens the browser with PKCE S256 and the resource, and keeps the tokens in mcp-signins.json beside its other account secrets (0600, never the keychain). While signed in, the agents are given the gateway's /mcp/<name> for that server, without the Authorization the library has for it; the gateway passes POST (JSON or event stream), the GET stream and DELETE on with the Mcp-Session-Id and magpie's token, renews it 2 minutes before it runs out and once on a 401, one renewal per server at a time, and a sign-in the server won't renew is answered 502 "sign in to it again" (never a 401 the agent would act on). Signing out, a new URL or an SSE server gives the agents the server's own address as before; a rename keeps the sign-in and removing the server drops it. /mcp/ is local-only or LAN-shared with the key, and refuses a request with an Origin or a Host not naming this computer, so a web page can't borrow the sign-in through the browser (form posts, DNS rebinding), and isn't counted as busy or key-limited. WSL agents are given their distro's gateway address. The row says Signed in or Sign-in ran out; zh strings added. Tests: TestSignIn, TestSignInWithoutMetadata, TestSignInPage, TestNothingToSignIn, TestTokenRenewsBeforeItRunsOut (8 calls, 1 renewal), TestRenewRefused, TestRenewRefusedForGood, TestMCPProxy, TestMCPProxyStaysHere, TestMCPProxyNotForWebPages (fails without the Origin/Host check), TestSignedInServerGoesThroughMagpie against a local fake OAuth+MCP server; mcp-signin.test.cjs (webkit, en and zh). Not tried against a real Neon/Notion/Supabase sign-in. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass.
2026-10-03 09:37:39 +08:00

84 lines
3.1 KiB
Go

package gateway
import (
"bytes"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// keyLimited holds a gateway key's requests to its limit (#585, see
// package budget for the rules): one that would go over is refused with a
// 429 before any provider is asked, saying the key, the limit and when it
// resets; one let in holds a reservation until it ends. Reads, the
// bridge's tool callbacks and counting tokens cost nothing and pass.
func keyLimited(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
who := access.Caller(r.Context())
if !who.Limit.Limited() || r.Method != http.MethodPost || strings.HasPrefix(r.URL.Path, "/_magpie/") || strings.HasPrefix(r.URL.Path, "/mcp/") || strings.HasSuffix(r.URL.Path, "/count_tokens") {
next.ServeHTTP(w, r)
return
}
size, model := r.ContentLength, ""
if who.Limit.Cost > 0 || size < 0 {
b, err := io.ReadAll(r.Body)
r.Body.Close()
if err != nil {
writeError(w, protoOfPath(r.URL.Path), http.StatusBadRequest, err.Error())
return
}
r.Body = io.NopCloser(bytes.NewReader(b))
size, model = int64(len(b)), budget.ModelOf(b)
}
now := time.Now()
release, refused := budget.Reserve(who, size, model, now)
if refused != nil {
msg := refused.Error()
w.Header().Set("Retry-After", strconv.Itoa(refused.RetryAfter(now)))
// the Anthropic and OpenAI SDKs would otherwise retry a 429
w.Header().Set("X-Should-Retry", "false")
w.Header().Set("X-Magpie-Limit-Reset", refused.Reset.Format(time.RFC3339))
writeError(w, protoOfPath(r.URL.Path), http.StatusTooManyRequests, msg)
c := callerOf(r)
appendUsage(r, usage.Record{Time: now, Agent: c.agent, Via: c.via, Requested: model, Status: http.StatusTooManyRequests, Rejected: true,
Error: msg, ErrType: "gateway_key_limit", Endpoint: r.URL.Path, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header)})
return
}
defer release()
next.ServeHTTP(w, r)
})
}
// protoOfPath is the API a path is of, for an error said its way.
func protoOfPath(path string) provider.Protocol {
switch {
case strings.HasSuffix(path, "/messages"):
return provider.Anthropic
case strings.HasPrefix(path, "/v1beta/"):
return provider.Gemini
case strings.HasSuffix(path, "/responses"):
return provider.Responses
}
return provider.Chat
}
// keyLimit answers GET /v1/magpie/limit: the calling gateway key's limit,
// what it has used and when it resets; {"limited":false} for a key with
// none or a request without one.
func (s *Server) keyLimit(w http.ResponseWriter, r *http.Request) {
who := access.Caller(r.Context())
if who.KeyID == "" || !who.Limit.Limited() {
writeJSON(w, 200, map[string]any{"limited": false, "key": who.KeyName})
return
}
st := budget.Of(access.Key{ID: who.KeyID, Name: who.KeyName, Limit: who.Limit}, time.Now())
writeJSON(w, 200, map[string]any{"limited": true, "key": who.KeyName, "limit": st})
}