diff --git a/doc/fleet/mcp.md b/doc/fleet/mcp.md index 306bfe6624..56a50172a0 100644 --- a/doc/fleet/mcp.md +++ b/doc/fleet/mcp.md @@ -56,7 +56,21 @@ sign-in in a browser and stores tokens itself: github uses `gh`'s token: the `github-mcp` wrapper in `systemPackages.nix` reads `gh auth token` from the login keychain at start, so no token is stored in the -repo or the nix store. aws signs requests (SigV4) using `~/.aws/config` profiles +repo or the nix store. + +The mcpx auth block for github also accepts an identity **failover list** +(#7948, `pkgs/mcpx/internal/mcpauth`): an ordered list of identities, each +named by secret name only -- GitHub App identities (App ID + installation ID +in config; the PEM private key lives in the secret store and mcpx mints +short-lived installation tokens from it) with the single user token last as +the fallback. A call that hits a soft block (HTTP 429, or a 403 carrying +rate-limit markers such as the secondary-limit "submitted too quickly") +rotates to the next identity; a hard block (401, a marker-less 403, 404, 422) +surfaces immediately and never rotates. Rotation state (current identity + +cooldowns) persists in the configured state file across server restarts, and +every rotation is logged with the identity name and the soft-block reason. +The pool resolves the current identity's credential at connection start; the +session-facing tool surface is unchanged. aws signs requests (SigV4) using `~/.aws/config` profiles (with `--skip-auth` so its 8 tools load even when logged out, and `--profile` populated dynamically from `aws configure list-profiles` so callers can switch accounts per call via the `aws_profile` tool parameter). @@ -81,7 +95,7 @@ values were read for this page. | fff | File and content search over `~/git` | stdio `fff-mcp` | None | — | 3 | — | | fff-nix | Same, over this repo | stdio `fff-mcp` | None | — | 3 | — | | fff-worktree | Same, over `~/.local/share/opencode/worktree` | stdio `fff-mcp` | None | — | 3 | — | -| github | GitHub | stdio `github-mcp` → `github-mcp-server stdio` | `gh` token (account dezren39; scopes `repo`, `workflow`, `gist`, `read:org`, `admin:public_key`, `admin:ssh_signing_key`) | Present | 43 | `push_files`, `delete_file`, `merge_pull_request`, issue and PR writes (#371). With `workflow` scope a push can change Actions workflows | +| github | GitHub | stdio `github-mcp` → `github-mcp-server stdio` | Identity failover list (#7948): GitHub App identities by secret name, `gh` user token (account dezren39; scopes `repo`, `workflow`, `gist`, `read:org`, `admin:public_key`, `admin:ssh_signing_key`) last | Present | 43 | `push_files`, `delete_file`, `merge_pull_request`, issue and PR writes (#371). With `workflow` scope a push can change Actions workflows | | markitdown | Converts a URL or file to Markdown | stdio `markitdown-mcp` | None | — | 1 | Can read local `file:` URIs | | nixos | Nix packages, options, NixOS wiki | stdio `mcp-nixos` | None | — | 2 | — | | playwright | Headless browser, one per session | stdio `playwright-mcp` | None | — | 25 | `browser_run_code_unsafe`, `browser_file_upload` | diff --git a/pkgs/mcpx/internal/mcpauth/failover.go b/pkgs/mcpx/internal/mcpauth/failover.go new file mode 100644 index 0000000000..ec03bf79d3 --- /dev/null +++ b/pkgs/mcpx/internal/mcpauth/failover.go @@ -0,0 +1,509 @@ +package mcpauth + +// Failover across a list of GitHub identities for one server (#7948). +// +// The github namespace used to ride on a single user-token bucket: when +// that bucket hit a rate limit, every session's GitHub tools failed at +// once, even though the fleet owns several GitHub App identities with +// separate buckets. This file is the machinery that fixes that: +// +// - Failover (config): an ordered list of Identity values. An identity +// names its credential by SECRET NAME ONLY -- the value lives in the +// daemon's secret store and is fetched through a SecretFunc at call +// time. No secret value ever appears in config, logs, or this file. +// - Classify: soft blocks (429, or 403 carrying rate-limit markers such +// as the secondary-limit "submitted too quickly") rotate to the next +// identity. Hard blocks (401, a marker-less 403, 404, 422) surface +// immediately with their real error and never rotate. +// - Rotator: owns the current identity and per-identity cooldowns, +// persists them to a state file so they survive a server restart, +// and logs every rotation with the identity name and the reason. +// - Minter: exchanges a GitHub App's private key (by secret name) for +// a short-lived installation token, so App identities need no stored +// token at all. +// - The single user token stays supported as the last list entry (kind +// "token"), so a bad App configuration cannot take the namespace +// down: rotation simply lands on it. + +import ( + "context" + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +// Identity is one entry in a failover list. +type Identity struct { + // Name identifies the identity in logs and rotation state. It is a + // label, never a credential: "app-org", "app-personal", "user-token". + Name string `json:"name"` + + // Kind is "app" (a GitHub App; Secret names the secret holding its + // PEM private key, AppID and InstallationID say where to mint) or + // "token" (Secret names the secret holding the token itself -- the + // shape the single user token already has). + Kind string `json:"kind"` + + // Secret is the NAME of the secret in the daemon's store, never a + // value. For kind "app" the value is the App's PEM private key; for + // kind "token" it is the token. + Secret string `json:"secret"` + + // AppID and InstallationID are kind "app" only. They are public + // identifiers, safe to keep in configuration. + AppID int64 `json:"appId,omitempty"` + InstallationID int64 `json:"installationId,omitempty"` +} + +// Failover configures identity failover for a server's auth block. +type Failover struct { + // Identities is the ordered list to try. Rotation walks it in order + // and wraps; the user token, when present, belongs last. + Identities []Identity `json:"identities"` + + // StatePath is where the rotator persists its current identity and + // cooldowns, so rotation state survives a server restart. Empty + // keeps state in memory only. + StatePath string `json:"statePath,omitempty"` + + // CooldownSeconds is how long a soft-blocked identity is skipped. + // A response's Retry-After wins when it is longer. Zero means 60. + CooldownSeconds int `json:"cooldownSeconds,omitempty"` +} + +func (f *Failover) cooldown() time.Duration { + if f == nil || f.CooldownSeconds <= 0 { + return 60 * time.Second + } + return time.Duration(f.CooldownSeconds) * time.Second +} + +// SecretFunc fetches a secret value by name: the daemon's store in +// production, a map in tests. It is the only way credential material +// enters this package, and only at call time. +type SecretFunc func(name string) (string, error) + +// APIError is a GitHub API failure with the parts classification needs. +type APIError struct { + Status int + Body string + RetryAfter time.Duration +} + +func (e *APIError) Error() string { + body := strings.TrimSpace(e.Body) + if len(body) > 200 { + body = body[:200] + "..." + } + if body == "" { + return fmt.Sprintf("github api: status %d", e.Status) + } + return fmt.Sprintf("github api: status %d: %s", e.Status, body) +} + +// Block is the classification of an APIError. +type Block int + +const ( + // BlockHard surfaces immediately; no rotation. + BlockHard Block = iota + // BlockSoft rotates to the next identity. + BlockSoft +) + +// softMarkers are the body substrings that mark a 403 as a rate-limit +// (soft) block rather than a permissions (hard) one. GitHub's primary +// and secondary limit responses both carry "rate limit"; the secondary +// limit's tell is "submitted too quickly" (and its abuse-detection +// sibling). A 403 with none of these is a real refusal. +var softMarkers = []string{ + "rate limit", + "submitted too quickly", + "secondary rate", + "abuse detection", + "too many requests", +} + +// Classify decides whether an error rotates (soft) or surfaces (hard). +func Classify(err error) Block { + var ae *APIError + if !errors.As(err, &ae) { + return BlockHard + } + switch { + case ae.Status == 429: + return BlockSoft + case ae.Status == 403: + if ae.RetryAfter > 0 { + return BlockSoft + } + body := strings.ToLower(ae.Body) + for _, m := range softMarkers { + if strings.Contains(body, m) { + return BlockSoft + } + } + } + return BlockHard +} + +// rotatorState is the persisted shape: which identity is current and +// when each blocked identity becomes usable again. +type rotatorState struct { + Current int `json:"current"` + Cooldowns map[string]time.Time `json:"cooldowns"` +} + +// Rotator walks a Failover list. Safe for concurrent use. +type Rotator struct { + cfg *Failover + logf func(format string, args ...any) + now func() time.Time + mu sync.Mutex + state rotatorState + // minted caches App installation tokens until near expiry, keyed by + // identity name. Tokens are credentials: memory only, never the + // state file. + minted map[string]mintedToken +} + +type mintedToken struct { + token string + expires time.Time +} + +// NewRotator loads any persisted state from the Failover's StatePath. +// logf receives one line per rotation (identity name + reason, never a +// credential); nil discards. +func NewRotator(cfg *Failover, logf func(format string, args ...any)) *Rotator { + r := &Rotator{ + cfg: cfg, + logf: logf, + now: time.Now, + minted: map[string]mintedToken{}, + } + r.state.Cooldowns = map[string]time.Time{} + if cfg != nil && cfg.StatePath != "" { + if b, err := os.ReadFile(cfg.StatePath); err == nil { + var s rotatorState + if json.Unmarshal(b, &s) == nil { + r.state = s + if r.state.Cooldowns == nil { + r.state.Cooldowns = map[string]time.Time{} + } + if r.state.Current < 0 || r.state.Current >= len(cfg.Identities) { + r.state.Current = 0 + } + } + } + } + return r +} + +func (r *Rotator) log(format string, args ...any) { + if r.logf != nil { + r.logf(format, args...) + } +} + +// Current returns the identity new calls start from. +func (r *Rotator) Current() Identity { + r.mu.Lock() + defer r.mu.Unlock() + if r.cfg == nil || len(r.cfg.Identities) == 0 { + return Identity{} + } + return r.cfg.Identities[r.state.Current] +} + +// Cooldowns returns a copy of the per-identity cooldown deadlines. +func (r *Rotator) Cooldowns() map[string]time.Time { + r.mu.Lock() + defer r.mu.Unlock() + out := make(map[string]time.Time, len(r.state.Cooldowns)) + for k, v := range r.state.Cooldowns { + out[k] = v + } + return out +} + +func (r *Rotator) persistLocked() { + if r.cfg == nil || r.cfg.StatePath == "" { + return + } + b, err := json.Marshal(r.state) + if err != nil { + return + } + if dir := filepath.Dir(r.cfg.StatePath); dir != "" { + _ = os.MkdirAll(dir, 0o755) + } + tmp := r.cfg.StatePath + ".tmp" + if os.WriteFile(tmp, b, 0o600) == nil { + _ = os.Rename(tmp, r.cfg.StatePath) + } +} + +// Token resolves the credential for one identity: a stored token for +// kind "token", a freshly minted (or cached) installation token for +// kind "app". The Minter may be nil when no identity is an App. +func (r *Rotator) Token(ctx context.Context, id Identity, secrets SecretFunc, minter *Minter) (string, error) { + switch strings.ToLower(id.Kind) { + case "token": + if secrets == nil { + return "", fmt.Errorf("identity %s: no secret store configured", id.Name) + } + return secrets(id.Secret) + case "app": + r.mu.Lock() + if mt, ok := r.minted[id.Name]; ok && r.now().Before(mt.expires.Add(-5*time.Minute)) { + r.mu.Unlock() + return mt.token, nil + } + r.mu.Unlock() + if secrets == nil || minter == nil { + return "", fmt.Errorf("identity %s: app identity needs a secret store and a minter", id.Name) + } + key, err := secrets(id.Secret) + if err != nil { + return "", fmt.Errorf("identity %s: %w", id.Name, err) + } + tok, exp, err := minter.Mint(ctx, []byte(key), id.AppID, id.InstallationID) + if err != nil { + return "", fmt.Errorf("identity %s: %w", id.Name, err) + } + r.mu.Lock() + r.minted[id.Name] = mintedToken{token: tok, expires: exp} + r.mu.Unlock() + return tok, nil + } + return "", fmt.Errorf("identity %s: unknown kind %q (app or token)", id.Name, id.Kind) +} + +// Do runs fn with the current identity's token. On a soft block it +// rotates -- cooldown, log line, persisted state -- and retries with +// the next identity, so the caller sees success. On a hard block the +// real error returns at once and nothing rotates. When every identity +// is soft-blocked or cooling down, the last soft error returns. +// +// fn receives the identity and its token and does the actual call, +// returning nil on success or the call's error (an *APIError for API +// failures, so Classify can read the status and body). +func (r *Rotator) Do(ctx context.Context, secrets SecretFunc, minter *Minter, fn func(id Identity, token string) error) error { + if r.cfg == nil || len(r.cfg.Identities) == 0 { + return fmt.Errorf("failover: no identities configured") + } + n := len(r.cfg.Identities) + r.mu.Lock() + startIdx := r.state.Current + r.mu.Unlock() + var lastErr error + tried := make(map[int]bool, n) + for k := 0; k < n; k++ { + idx := (startIdx + k) % n + if tried[idx] { + continue + } + id := r.cfg.Identities[idx] + r.mu.Lock() + until, cooling := r.state.Cooldowns[id.Name] + r.mu.Unlock() + if cooling && r.now().Before(until) { + // Still serving a cooldown from an earlier block: skip it + // unless it is the only identity not yet tried this call. + remaining := false + for j := 0; j < n; j++ { + if !tried[j] && j != idx { + remaining = true + } + } + if remaining { + continue + } + } + tok, err := r.Token(ctx, id, secrets, minter) + if err != nil { + // A credential that cannot be produced (missing secret, a + // mint the API refused) is this identity's hard failure: + // surface it rather than silently skipping to a bucket the + // operator did not choose as a fallback for config errors. + return err + } + tried[idx] = true + err = fn(id, tok) + if err == nil { + r.mu.Lock() + r.state.Current = idx + r.persistLocked() + r.mu.Unlock() + return nil + } + if Classify(err) == BlockHard { + return err + } + // Soft block: cool this identity down and rotate. + var ae *APIError + _ = errors.As(err, &ae) + cd := r.cfg.cooldown() + if ae != nil && ae.RetryAfter > cd { + cd = ae.RetryAfter + } + r.mu.Lock() + r.state.Cooldowns[id.Name] = r.now().Add(cd) + r.state.Current = (idx + 1) % n + r.persistLocked() + r.mu.Unlock() + r.log("mcpauth: failover: identity %s soft-blocked (%v); rotating to %s, cooldown %s", + id.Name, err, r.cfg.Identities[(idx+1)%n].Name, cd) + lastErr = err + } + if lastErr != nil { + return fmt.Errorf("failover: all %d identities soft-blocked: %w", n, lastErr) + } + return fmt.Errorf("failover: all %d identities are in cooldown", n) +} + +// ResolveCurrent resolves the rotator's current identity into the +// credential a connection carries, so a caller that spawns a server +// per identity -- the pool resolving a server's auth at connection +// start -- hands it the CURRENT identity's credential, and a restart +// after rotation resumes on the identity the state file names. The +// token is returned as a bearer header and, for each name in +// envNames, as an environment value: a stdio server's auth block +// declares the env vars it reads (for github, the token variable the +// child consumes), and those vars carry the current identity's token +// instead of any single stored one. +func (r *Rotator) ResolveCurrent(ctx context.Context, envNames []string, secrets SecretFunc, minter *Minter) (Identity, *Resolved, error) { + id := r.Current() + tok, err := r.Token(ctx, id, secrets, minter) + if err != nil { + return id, nil, err + } + out := &Resolved{ + Headers: map[string]string{"Authorization": "Bearer " + tok}, + Query: map[string]string{}, + Env: map[string]string{}, + } + for _, name := range envNames { + out.Env[name] = tok + } + return id, out, nil +} + +// Minter exchanges a GitHub App private key for an installation token. +type Minter struct { + // BaseURL is the GitHub API root; empty means https://api.github.com. + BaseURL string + // HTTP is the client to use; nil means http.DefaultClient. + HTTP *http.Client + // Now overrides the clock in tests. + Now func() time.Time +} + +func (m *Minter) now() time.Time { + if m != nil && m.Now != nil { + return m.Now() + } + return time.Now() +} + +func (m *Minter) base() string { + if m != nil && m.BaseURL != "" { + return strings.TrimRight(m.BaseURL, "/") + } + return "https://api.github.com" +} + +func (m *Minter) client() *http.Client { + if m != nil && m.HTTP != nil { + return m.HTTP + } + return http.DefaultClient +} + +// Mint signs a short-lived App JWT with keyPEM and exchanges it for an +// installation access token. It returns the token and its expiry. The +// key is used in memory only. +func (m *Minter) Mint(ctx context.Context, keyPEM []byte, appID, installationID int64) (string, time.Time, error) { + jwt, err := signAppJWT(keyPEM, appID, m.now()) + if err != nil { + return "", time.Time{}, err + } + url := fmt.Sprintf("%s/app/installations/%d/access_tokens", m.base(), installationID) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil) + if err != nil { + return "", time.Time{}, err + } + req.Header.Set("Authorization", "Bearer "+jwt) + req.Header.Set("Accept", "application/vnd.github+json") + resp, err := m.client().Do(req) + if err != nil { + return "", time.Time{}, err + } + defer resp.Body.Close() + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return "", time.Time{}, &APIError{Status: resp.StatusCode, Body: string(body)} + } + var out struct { + Token string `json:"token"` + ExpiresAt time.Time `json:"expires_at"` + } + if err := json.Unmarshal(body, &out); err != nil { + return "", time.Time{}, fmt.Errorf("mint: decode response: %w", err) + } + if out.Token == "" { + return "", time.Time{}, fmt.Errorf("mint: response carried no token") + } + return out.Token, out.ExpiresAt, nil +} + +// signAppJWT builds the RS256 JWT GitHub App authentication starts +// with: iss is the App ID, iat is backdated a minute for clock skew, +// exp is nine minutes out (GitHub's cap is ten). +func signAppJWT(keyPEM []byte, appID int64, now time.Time) (string, error) { + block, _ := pem.Decode(keyPEM) + if block == nil { + return "", fmt.Errorf("mint: private key is not PEM") + } + var key *rsa.PrivateKey + if parsed, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil { + key = parsed + } else if parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes); err == nil { + var ok bool + key, ok = parsed.(*rsa.PrivateKey) + if !ok { + return "", fmt.Errorf("mint: private key is not RSA") + } + } else { + return "", fmt.Errorf("mint: cannot parse private key: %w", err) + } + enc := func(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) } + header := enc([]byte(`{"alg":"RS256","typ":"JWT"}`)) + claims, _ := json.Marshal(map[string]any{ + "iss": appID, + "iat": now.Add(-60 * time.Second).Unix(), + "exp": now.Add(9 * time.Minute).Unix(), + }) + signing := header + "." + enc(claims) + sum := sha256.Sum256([]byte(signing)) + sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, sum[:]) + if err != nil { + return "", err + } + return signing + "." + enc(sig), nil +} diff --git a/pkgs/mcpx/internal/mcpauth/failover_test.go b/pkgs/mcpx/internal/mcpauth/failover_test.go new file mode 100644 index 0000000000..108cc27304 --- /dev/null +++ b/pkgs/mcpx/internal/mcpauth/failover_test.go @@ -0,0 +1,294 @@ +package mcpauth_test + +// Tests for the #7948 identity failover. Every test names its oracle: +// the observable sequence or value that proves the behaviour, checked +// exactly, not by resemblance. + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/developing-today/code/pkgs/mcpx/internal/mcpauth" +) + +func testSecrets(values map[string]string) mcpauth.SecretFunc { + return func(name string) (string, error) { + v, ok := values[name] + if !ok { + return "", fmt.Errorf("secret %s not found", name) + } + return v, nil + } +} + +func twoTokens() *mcpauth.Failover { + return &mcpauth.Failover{Identities: []mcpauth.Identity{ + {Name: "app-one", Kind: "token", Secret: "TOK_ONE"}, + {Name: "user", Kind: "token", Secret: "TOK_USER"}, + }} +} + +// Oracle: the exact sequence of (identity, token) pairs fn is called +// with, and the rotation log lines. A forced 429 on identity #1 and a +// forced secondary-limit 403 on a re-run must both end in success via +// identity #2, with the session-visible result being plain success. +func TestSoftBlockFailsOverToSecondIdentity(t *testing.T) { + soft := map[string]*mcpauth.APIError{ + "429": {Status: 429, Body: `{"message":"too many requests"}`}, + "secondary": {Status: 403, Body: `{"message":"You have exceeded a secondary rate limit. You have been submitted too quickly."}`}, + } + for name, blockErr := range soft { + t.Run(name, func(t *testing.T) { + var calls []string + var logs []string + r := mcpauth.NewRotator(twoTokens(), func(f string, a ...any) { + logs = append(logs, fmt.Sprintf(f, a...)) + }) + err := r.Do(context.Background(), testSecrets(map[string]string{ + "TOK_ONE": "token-one", "TOK_USER": "token-user", + }), nil, func(id mcpauth.Identity, token string) error { + calls = append(calls, id.Name+"="+token) + if id.Name == "app-one" { + return blockErr + } + return nil + }) + if err != nil { + t.Fatalf("session-visible result must be success, got %v", err) + } + want := []string{"app-one=token-one", "user=token-user"} + if fmt.Sprint(calls) != fmt.Sprint(want) { + t.Errorf("oracle: call sequence = %v, want %v", calls, want) + } + if len(logs) != 1 || !strings.Contains(logs[0], "app-one") || !strings.Contains(logs[0], "user") { + t.Errorf("oracle: rotation log = %v, want one line naming app-one -> user", logs) + } + if got := r.Current().Name; got != "user" { + t.Errorf("oracle: current identity = %q, want user", got) + } + }) + } +} + +// Oracle: exactly one fn call and zero rotation log lines. Hard blocks +// (bad credentials, a marker-less 403 refusal, a validation error) +// surface with their real error and trigger no rotation. +func TestHardBlockSurfacesImmediatelyWithNoRotation(t *testing.T) { + hard := map[string]*mcpauth.APIError{ + "401": {Status: 401, Body: `{"message":"Bad credentials"}`}, + "403-no-markers": {Status: 403, Body: `{"message":"Resource not accessible by integration"}`}, + "404": {Status: 404, Body: `{"message":"Not Found"}`}, + "422": {Status: 422, Body: `{"message":"Validation Failed"}`}, + } + for name, blockErr := range hard { + t.Run(name, func(t *testing.T) { + calls := 0 + logs := 0 + r := mcpauth.NewRotator(twoTokens(), func(f string, a ...any) { logs++ }) + err := r.Do(context.Background(), testSecrets(map[string]string{ + "TOK_ONE": "token-one", "TOK_USER": "token-user", + }), nil, func(id mcpauth.Identity, token string) error { + calls++ + return blockErr + }) + var ae *mcpauth.APIError + if !errors.As(err, &ae) || ae.Status != blockErr.Status { + t.Fatalf("oracle: the real error must surface, got %v", err) + } + if calls != 1 { + t.Errorf("oracle: fn calls = %d, want exactly 1 (no rotation)", calls) + } + if logs != 0 { + t.Errorf("oracle: rotation log lines = %d, want 0", logs) + } + }) + } +} + +// Oracle: a second Rotator constructed over the same state file (the +// "restart") reports the identical current identity and cooldown +// deadline as the first one held in memory. +func TestRotationStateSurvivesRestart(t *testing.T) { + statePath := filepath.Join(t.TempDir(), "failover-state.json") + cfg := twoTokens() + cfg.StatePath = statePath + cfg.CooldownSeconds = 600 + + r1 := mcpauth.NewRotator(cfg, nil) + err := r1.Do(context.Background(), testSecrets(map[string]string{ + "TOK_ONE": "token-one", "TOK_USER": "token-user", + }), nil, func(id mcpauth.Identity, token string) error { + if id.Name == "app-one" { + return &mcpauth.APIError{Status: 429} + } + return nil + }) + if err != nil { + t.Fatal(err) + } + + r2 := mcpauth.NewRotator(cfg, nil) // the restart: fresh process state + if got := r2.Current().Name; got != "user" { + t.Errorf("oracle: current after restart = %q, want user", got) + } + cd1, cd2 := r1.Cooldowns(), r2.Cooldowns() + if len(cd2) != 1 || !cd2["app-one"].Equal(cd1["app-one"]) { + t.Errorf("oracle: cooldowns after restart = %v, want identical to %v", cd2, cd1) + } +} + +// Oracle: when every identity soft-blocks, Do returns an error that +// wraps the last soft block and names the exhaustion -- the caller +// must see a rate-limit failure, not a silent success or a hang. +func TestAllIdentitiesSoftBlockedReturnsLastError(t *testing.T) { + r := mcpauth.NewRotator(twoTokens(), nil) + err := r.Do(context.Background(), testSecrets(map[string]string{ + "TOK_ONE": "token-one", "TOK_USER": "token-user", + }), nil, func(id mcpauth.Identity, token string) error { + return &mcpauth.APIError{Status: 429, Body: "slow down"} + }) + var ae *mcpauth.APIError + if !errors.As(err, &ae) || ae.Status != 429 { + t.Fatalf("oracle: want wrapped 429, got %v", err) + } + if !strings.Contains(err.Error(), "all 2 identities") { + t.Errorf("oracle: error should name exhaustion, got %v", err) + } +} + +// Oracle: the fake API receives a POST to the installation-token path +// carrying an RS256 JWT whose iss is the App ID and whose lifetime is +// under GitHub's ten-minute cap, and Mint returns exactly the token +// the API issued. +func TestMintInstallationToken(t *testing.T) { + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + pemBytes := pem.EncodeToMemory(&pem.Block{ + Type: "RSA PRIVATE KEY", + Bytes: x509.MarshalPKCS1PrivateKey(key), + }) + + var gotPath, gotJWT string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + gotPath = req.URL.Path + gotJWT = strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ") + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{"token":"installation-token-xyz","expires_at":"2030-01-01T00:00:00Z"}`) + })) + defer srv.Close() + + m := &mcpauth.Minter{BaseURL: srv.URL, Now: func() time.Time { return time.Unix(1700000000, 0) }} + tok, exp, err := m.Mint(context.Background(), pemBytes, 5454422, 4242) + if err != nil { + t.Fatal(err) + } + if tok != "installation-token-xyz" { + t.Errorf("oracle: token = %q, want the issued installation-token-xyz", tok) + } + if exp.Year() != 2030 { + t.Errorf("oracle: expiry = %v, want the issued 2030 expiry", exp) + } + if want := "/app/installations/4242/access_tokens"; gotPath != want { + t.Errorf("oracle: path = %q, want %q", gotPath, want) + } + parts := strings.Split(gotJWT, ".") + if len(parts) != 3 { + t.Fatalf("oracle: JWT has %d parts, want 3", len(parts)) + } + claimsRaw, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + t.Fatal(err) + } + var claims map[string]any + if err := json.Unmarshal(claimsRaw, &claims); err != nil { + t.Fatal(err) + } + if claims["iss"] != float64(5454422) { + t.Errorf("oracle: JWT iss = %v, want the App ID 5454422", claims["iss"]) + } + if lt := claims["exp"].(float64) - claims["iat"].(float64); lt <= 0 || lt > 660 { + t.Errorf("oracle: JWT lifetime = %v seconds, want within GitHub's cap", lt) + } +} + +// Oracle: an App identity in the list mints through the Minter (the +// fake API is hit exactly once across two Do calls -- the token is +// cached), and the token fn receives is the minted one. +func TestAppIdentityMintsAndCaches(t *testing.T) { + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + pemBytes := pem.EncodeToMemory(&pem.Block{ + Type: "RSA PRIVATE KEY", + Bytes: x509.MarshalPKCS1PrivateKey(key), + }) + mints := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + mints++ + fmt.Fprint(w, `{"token":"minted-1","expires_at":"2999-01-01T00:00:00Z"}`) + })) + defer srv.Close() + + cfg := &mcpauth.Failover{Identities: []mcpauth.Identity{ + {Name: "app-org", Kind: "app", Secret: "APP_KEY", AppID: 1, InstallationID: 2}, + }} + r := mcpauth.NewRotator(cfg, nil) + m := &mcpauth.Minter{BaseURL: srv.URL} + secrets := testSecrets(map[string]string{"APP_KEY": string(pemBytes)}) + for i := 0; i < 2; i++ { + var saw string + err := r.Do(context.Background(), secrets, m, func(id mcpauth.Identity, token string) error { + saw = token + return nil + }) + if err != nil { + t.Fatal(err) + } + if saw != "minted-1" { + t.Fatalf("oracle: fn token = %q, want minted-1", saw) + } + } + if mints != 1 { + t.Errorf("oracle: mint calls = %d, want 1 (second call served from cache)", mints) + } +} + +// Classifier table: the status/marker combinations the issue names, +// each with its expected block class. +func TestClassify(t *testing.T) { + cases := []struct { + err *mcpauth.APIError + want mcpauth.Block + }{ + {&mcpauth.APIError{Status: 429}, mcpauth.BlockSoft}, + {&mcpauth.APIError{Status: 403, Body: "API rate limit exceeded"}, mcpauth.BlockSoft}, + {&mcpauth.APIError{Status: 403, Body: "You have been submitted too quickly"}, mcpauth.BlockSoft}, + {&mcpauth.APIError{Status: 403, RetryAfter: time.Minute}, mcpauth.BlockSoft}, + {&mcpauth.APIError{Status: 403, Body: "Forbidden"}, mcpauth.BlockHard}, + {&mcpauth.APIError{Status: 401, Body: "Bad credentials"}, mcpauth.BlockHard}, + {&mcpauth.APIError{Status: 404}, mcpauth.BlockHard}, + {&mcpauth.APIError{Status: 422}, mcpauth.BlockHard}, + {&mcpauth.APIError{Status: 500}, mcpauth.BlockHard}, + } + for i, c := range cases { + if got := mcpauth.Classify(c.err); got != c.want { + t.Errorf("case %d (%v): Classify = %v, want %v", i, c.err, got, c.want) + } + } +} diff --git a/pkgs/mcpx/internal/mcpauth/mcpauth.go b/pkgs/mcpx/internal/mcpauth/mcpauth.go index 061da723bb..811ba9fe3b 100644 --- a/pkgs/mcpx/internal/mcpauth/mcpauth.go +++ b/pkgs/mcpx/internal/mcpauth/mcpauth.go @@ -67,6 +67,13 @@ type Auth struct { // OAuth configures the full flow, for a server that demands it. OAuth *OAuth `json:"oauth,omitempty"` + + // Failover configures identity failover (#7948): an ordered list of + // identities whose credentials are named by secret name only. When + // set, the pool resolves the CURRENT identity's credential at + // connection start (see Rotator.ResolveCurrent), and rotation state + // persists across restarts at Failover.StatePath. + Failover *Failover `json:"failover,omitempty"` } // OAuth is the 2.1 flow the specification describes for HTTP transports. @@ -237,6 +244,13 @@ func (a *Auth) ResolveWith(get func(name string) string) (*Resolved, error) { // Used by `mcpx config` and `mcpx doctor`, both of which people paste into // issues. func (a *Auth) Describe() string { + if a != nil && a.Failover != nil && len(a.Failover.Identities) > 0 { + names := make([]string, len(a.Failover.Identities)) + for i, id := range a.Failover.Identities { + names[i] = id.Name + } + return "failover (" + strings.Join(names, ", ") + ")" + } if a == nil || a.Type == "" || strings.EqualFold(a.Type, "none") { if a != nil && len(a.Env) > 0 { return fmt.Sprintf("env (%d variables)", len(a.Env)) diff --git a/pkgs/mcpx/internal/pool/pool.go b/pkgs/mcpx/internal/pool/pool.go index fef67afa5a..7b407d2007 100644 --- a/pkgs/mcpx/internal/pool/pool.go +++ b/pkgs/mcpx/internal/pool/pool.go @@ -23,6 +23,7 @@ import ( "errors" "fmt" "github.com/developing-today/code/pkgs/mcpx/internal/defaults" + "net/http" "net/url" "os" "sort" @@ -1067,6 +1068,31 @@ func (p *Pool) runtimeEnv() map[string]string { // parameters and environment a connection carries. A credential that names an // unset variable fails here, before a request, rather than as a 401 later. func (p *Pool) resolveAuth() (*mcpauth.Resolved, error) { + // Identity failover (#7948): a server whose auth block carries a + // failover list resolves the CURRENT identity's credential instead + // of a single stored one. Rotation state persists at the list's + // StatePath, so a (re)start after a rotation resumes on the rotated + // identity. Servers without a failover block are untouched. + if p.cfg.Auth != nil && p.cfg.Auth.Failover != nil && len(p.cfg.Auth.Failover.Identities) > 0 { + fo := p.cfg.Auth.Failover + rot := mcpauth.NewRotator(fo, nil) + secrets := func(name string) (string, error) { + if v := p.variable(name); v != "" { + return v, nil + } + return "", fmt.Errorf("secret %s not set in the daemon's environment", name) + } + envNames := make([]string, 0, len(p.cfg.Auth.Env)) + for name := range p.cfg.Auth.Env { + envNames = append(envNames, name) + } + minter := &mcpauth.Minter{HTTP: &http.Client{Timeout: 15 * time.Second}} + _, r, err := rot.ResolveCurrent(context.Background(), envNames, secrets, minter) + if err != nil { + return nil, fmt.Errorf("%s: auth: failover: %w", p.cfg.Name, err) + } + return r, nil + } r, err := p.cfg.Auth.ResolveWith(p.variable) if err != nil { return nil, fmt.Errorf("%s: auth: %w", p.cfg.Name, err)