diff --git a/internal/storage/agent_token_repin.go b/internal/storage/agent_token_repin.go index 2e404000c..9744c0c42 100644 --- a/internal/storage/agent_token_repin.go +++ b/internal/storage/agent_token_repin.go @@ -9,6 +9,30 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" ) +// repinRestoreMarker marks a record in RepinProfile's `before` slice as a +// browser-login restore entry rather than a stored token record. It is carried +// in AgentToken.MatchedGeneration, a field that is never persisted (json:"-") +// and never set on a stored record, so a real record cannot be mistaken for it +// whatever its TokenHash is. +const repinRestoreMarker = "spec132-repin-binding-restore" + +// repinRestoreEntry is the restore entry of one client whose binding also lives +// in an oauth_client_bindings entry. It carries the client id, the OLD pin and +// mode (ProfilePin/ProfileMode) and, in MatchedPrefix (never persisted), the +// WriteID that repin's own write produced on that entry: RestorePins restores +// only while the entry still has exactly that incarnation. +func repinRestoreEntry(clientID, oldPin, oldMode, writeID string) auth.AgentToken { + return auth.AgentToken{ + Name: auth.ClientTokenName(clientID), Kind: auth.KindClient, ClientID: clientID, + ProfilePin: oldPin, ProfileMode: oldMode, + MatchedGeneration: repinRestoreMarker, MatchedPrefix: writeID, + } +} + +func isRepinRestoreEntry(t *auth.AgentToken) bool { + return t.MatchedGeneration == repinRestoreMarker && t.Kind == auth.KindClient && t.ClientID != "" +} + // RepinProfile rewrites ProfilePin from -> to on EVERY stored ownerless token // naming `from` — regular agent tokens and client credentials alike, revoked // and expired ones included — in one transaction (Spec 108 D19). It is the @@ -20,6 +44,17 @@ import ( // restore exactly those pins with RestorePins. An empty source or target is // refused before anything is written (a locked client credential cannot hold // an empty pin). +// +// Spec 132: a client's pin is written through writeClientBindingTx, so its +// browser-login binding entry moves with its API-key record, and an entry of a +// client that has NO API-key record moves too. For every client that has an +// entry, `before` ends with a restore entry (see repinRestoreEntry). Existing +// records come first, in bbolt key order, exactly as before. +// +// A repin never touches PriorProfilePin/PriorProfileMode: that snapshot is the +// binding the client had before its connect, and undoing the connect returns the +// client to exactly that, whatever profile renames happened since — the same as +// for an API-key tombstone before Spec 132. func (m *Manager) RepinProfile(from, to string) (before []auth.AgentToken, err error) { return m.repinProfile(from, to, nil) } @@ -36,47 +71,116 @@ func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([ var before []auth.AgentToken err := m.db.db.Update(func(tx *bbolt.Tx) error { before = nil - tokenBucket := tx.Bucket([]byte(AgentTokensBucket)) - if tokenBucket == nil { - return nil - } type rewrite struct { - key []byte - data []byte - old auth.AgentToken + key []byte + data []byte // direct rewrite of a regular token; nil for a client record + old auth.AgentToken + client bool } - var work []rewrite + var work []rewrite // ONE list, in bbolt key order + clientsWithRecord := map[string]bool{} // Collect first: bbolt forbids Put while a ForEach is iterating. - if err := tokenBucket.ForEach(func(k, v []byte) error { - var t auth.AgentToken - if json.Unmarshal(v, &t) != nil { - return nil - } - if t.UserID != "" || t.ProfilePin != from { + if tokenBucket := tx.Bucket([]byte(AgentTokensBucket)); tokenBucket != nil { + if err := tokenBucket.ForEach(func(k, v []byte) error { + var t auth.AgentToken + if json.Unmarshal(v, &t) != nil { + return nil + } + isClient := t.Kind == auth.KindClient && t.ClientID != "" + if isClient { + clientsWithRecord[t.ClientID] = true + } + if t.UserID != "" || t.ProfilePin != from { + return nil + } + old := t + var data []byte + if !isClient { + // Regular (non-client) agent token: plain pin rewrite. + t.ProfilePin = to + var marshalErr error + if data, marshalErr = json.Marshal(t); marshalErr != nil { + return marshalErr + } + } + work = append(work, rewrite{key: append([]byte(nil), k...), data: data, old: old, client: isClient}) return nil + }); err != nil { + return err } - old := t - t.ProfilePin = to - data, marshalErr := json.Marshal(t) - if marshalErr != nil { - return marshalErr + } + // Browser-login-only clients: entries pinned to `from` whose client has + // no API-key record. They come after every existing record. + var oauthOnly []OAuthClientBinding + var oauthOnlyIDs []string + if err := oauthForEach(tx, OAuthClientBindingsBucket, func(id string, b OAuthClientBinding) error { + if b.ProfilePin == from && !clientsWithRecord[id] { + oauthOnly = append(oauthOnly, b) + oauthOnlyIDs = append(oauthOnlyIDs, id) } - work = append(work, rewrite{key: append([]byte(nil), k...), data: data, old: old}) return nil }); err != nil { return err } - for i, w := range work { + + i := 0 + step := func() error { if hook != nil { if err := hook(i); err != nil { return err } } - if err := tokenBucket.Put(w.key, w.data); err != nil { + i++ + return nil + } + // captureWriteID reads the incarnation repin's own write just produced. + captureWriteID := func(id string) (string, bool, error) { + e, err := getOAuthBindingTx(tx, id) + if err != nil || e == nil { + return "", false, err + } + return e.WriteID, true, nil + } + var restores []auth.AgentToken + for _, w := range work { + if err := step(); err != nil { + return err + } + if !w.client { + if err := tx.Bucket([]byte(AgentTokensBucket)).Put(w.key, w.data); err != nil { + return fmt.Errorf("failed to repin agent token: %w", err) + } + before = append(before, w.old) + continue + } + // A client record: through the binding writer so its OAuth entry + // (if any) moves too. + if err := writeClientBindingTx(tx, w.old.ClientID, to, w.old.ProfileMode); err != nil { return fmt.Errorf("failed to repin agent token: %w", err) } before = append(before, w.old) + wid, has, err := captureWriteID(w.old.ClientID) + if err != nil { + return err + } + if has { + restores = append(restores, repinRestoreEntry(w.old.ClientID, w.old.ProfilePin, w.old.ProfileMode, wid)) + } + } + for j, id := range oauthOnlyIDs { + if err := step(); err != nil { + return err + } + if err := writeClientBindingTx(tx, id, to, oauthOnly[j].ProfileMode); err != nil { + return fmt.Errorf("failed to repin agent token: %w", err) + } + wid, _, err := captureWriteID(id) + if err != nil { + return err + } + restores = append(restores, repinRestoreEntry(id, oauthOnly[j].ProfilePin, oauthOnly[j].ProfileMode, wid)) } + before = append(before, restores...) return nil }) if err != nil { @@ -85,9 +189,54 @@ func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([ return before, nil } +// restoreRecordPinTx puts back the stored pin of one record by hash, exactly as +// before Spec 132 (the mode is never changed by a repin). A record that no +// longer exists, or is owned, is left alone. +func restoreRecordPinTx(tx *bbolt.Tx, rec *auth.AgentToken) error { + tokenBucket := tx.Bucket([]byte(AgentTokensBucket)) + if tokenBucket == nil { + return nil + } + key := []byte(rec.TokenHash) + v := tokenBucket.Get(key) + if v == nil { + return nil + } + var t auth.AgentToken + if json.Unmarshal(v, &t) != nil || t.UserID != "" { + return nil + } + t.ProfilePin = rec.ProfilePin + data, err := json.Marshal(t) + if err != nil { + return err + } + if err := tokenBucket.Put(key, data); err != nil { + return fmt.Errorf("failed to restore agent token pin: %w", err) + } + return nil +} + // RestorePins puts back the ProfilePin of each record RepinProfile returned, // in one transaction (the rollback of a repin whose config write failed). A -// record that no longer exists is left alone. +// record that no longer exists is left alone. Regular tokens are restored by +// hash. +// +// For a CLIENT, ONE decision is made before either copy is touched, from the +// client's oauth_client_bindings entry as it is now: +// +// - no entry: restore the API-key record by hash, unconditionally, as before +// Spec 132; an entry is never created; +// - entry and a restore entry in `before`: restore the old pin and mode on +// both copies (through the binding writer, so it also works when the +// API-key record is gone) only if the entry's WriteID is still the one +// repin's own write produced; anything that wrote the binding since +// (reassignment, new mint, forget and re-create, even with the same pin and +// mode) restores neither copy, nor the record by hash; +// - entry but no restore entry (the client got its first browser login after +// the repin): restore both copies only if the record from `before` still +// exists and the entry equals that record's CURRENT pin and mode; else +// leave both alone. func (m *Manager) RestorePins(before []auth.AgentToken) error { if len(before) == 0 { return nil @@ -95,27 +244,71 @@ func (m *Manager) RestorePins(before []auth.AgentToken) error { m.mu.Lock() defer m.mu.Unlock() return m.db.db.Update(func(tx *bbolt.Tx) error { - tokenBucket := tx.Bucket([]byte(AgentTokensBucket)) - if tokenBucket == nil { - return nil + restoreEntries := map[string]*auth.AgentToken{} + clientRecords := map[string]*auth.AgentToken{} + var clientOrder []string + seen := map[string]bool{} + note := func(id string) { + if !seen[id] { + seen[id] = true + clientOrder = append(clientOrder, id) + } } for i := range before { - key := []byte(before[i].TokenHash) - v := tokenBucket.Get(key) - if v == nil { - continue - } - var t auth.AgentToken - if json.Unmarshal(v, &t) != nil || t.UserID != "" { - continue + b := &before[i] + switch { + case isRepinRestoreEntry(b): + restoreEntries[b.ClientID] = b + note(b.ClientID) + case b.Kind == auth.KindClient && b.ClientID != "" && b.TokenHash != "": + clientRecords[b.ClientID] = b + note(b.ClientID) + default: + if b.TokenHash == "" { + continue + } + if err := restoreRecordPinTx(tx, b); err != nil { + return err + } } - t.ProfilePin = before[i].ProfilePin - data, err := json.Marshal(t) + } + for _, id := range clientOrder { + entry, err := getOAuthBindingTx(tx, id) if err != nil { return err } - if err := tokenBucket.Put(key, data); err != nil { - return fmt.Errorf("failed to restore agent token pin: %w", err) + rec, e := clientRecords[id], restoreEntries[id] + switch { + case entry == nil: + if rec != nil { + if err := restoreRecordPinTx(tx, rec); err != nil { + return err + } + } + case e != nil: + if entry.WriteID != "" && entry.WriteID == e.MatchedPrefix { + if err := writeClientBindingTx(tx, id, e.ProfilePin, e.ProfileMode); err != nil { + return err + } + } + default: // entry, no restore entry; rec is non-nil here + cur := tx.Bucket([]byte(AgentTokensBucket)) + if cur == nil { + continue + } + v := cur.Get([]byte(rec.TokenHash)) + if v == nil { + continue + } + var t auth.AgentToken + if json.Unmarshal(v, &t) != nil || t.UserID != "" { + continue + } + if t.ProfilePin == entry.ProfilePin && t.ProfileMode == entry.ProfileMode { + if err := writeClientBindingTx(tx, id, rec.ProfilePin, rec.ProfileMode); err != nil { + return err + } + } } } return nil diff --git a/internal/storage/client_binding.go b/internal/storage/client_binding.go new file mode 100644 index 000000000..654f31225 --- /dev/null +++ b/internal/storage/client_binding.go @@ -0,0 +1,360 @@ +package storage + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "time" + + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// Spec 132 research R4: a client's binding (profile pin + mode) lives in the +// API-key record (agent_tokens, Kind=client) and, for a client with browser +// logins, in an oauth_client_bindings entry. writeClientBindingTx is the ONE +// place that writes a client's pin/mode into either store, so the two never +// drift; every writer of a binding calls it inside its own transaction. + +func bindingRevision(clientID, pin, mode string) string { + sum := sha256.Sum256([]byte(clientID + "|" + pin + "|" + mode)) + return hex.EncodeToString(sum[:8]) +} + +// putOAuthBindingTx is the only writer of an oauth_client_bindings entry: it +// stamps a fresh WriteID on every write. +func putOAuthBindingTx(tx *bbolt.Tx, clientID string, b *OAuthClientBinding) error { + var raw [8]byte + if _, err := rand.Read(raw[:]); err != nil { + return fmt.Errorf("failed to generate binding write id: %w", err) + } + b.WriteID = hex.EncodeToString(raw[:]) + return oauthPutJSON(tx, OAuthClientBindingsBucket, clientID, b) +} + +// validateClientBinding: mode is locked or switchable, and locked needs a pin. +func validateClientBinding(pin, mode string) error { + if mode != auth.ProfileModeLocked && mode != auth.ProfileModeSwitchable { + return fmt.Errorf("invalid profile mode %q", mode) + } + if mode == auth.ProfileModeLocked && pin == "" { + return fmt.Errorf("a locked client binding requires a non-empty profile") + } + return nil +} + +// writeClientBindingTx writes (pin, mode) on the client's API-key record when +// there is one AND on its oauth_client_bindings entry when there is one, and +// fails with ErrClientCredentialNotFound only when NEITHER exists. It never +// creates an oauth_client_bindings entry by itself and never touches the +// record's PriorProfile* snapshot. +func writeClientBindingTx(tx *bbolt.Tx, clientID, pin, mode string) error { + return writeClientBindingOptsTx(tx, clientID, pin, mode, false) +} + +// writeClientBindingOptsTx is writeClientBindingTx with the option to clear +// the API-key record's PriorProfile* snapshot in the same write (a binding +// change makes the mint-time snapshot stale). +func writeClientBindingOptsTx(tx *bbolt.Tx, clientID, pin, mode string, clearPrior bool) error { + // Validation applies only where a browser-login copy would be written: a + // client with just an API-key record is written exactly as before Spec 132 + // (one malformed legacy tombstone must not block a profile rename). A client + // with an OAuth entry is validated before ANY write, so neither copy can be + // left half-updated. + b, err := getOAuthBindingTx(tx, clientID) + if err != nil { + return err + } + if b != nil { + if err := validateClientBinding(pin, mode); err != nil { + return err + } + } + found := false + hash, tok, err := findClientTokenRecordLocked(tx, clientID) + if err != nil { + return err + } + if tok != nil && tok.Kind == auth.KindClient { + tok.ProfilePin, tok.ProfileMode = pin, mode + if clearPrior { + tok.PriorProfilePin, tok.PriorProfileMode = "", "" + } + data, err := json.Marshal(tok) + if err != nil { + return fmt.Errorf("failed to marshal client credential: %w", err) + } + if err := tx.Bucket([]byte(AgentTokensBucket)).Put(hash, data); err != nil { + return fmt.Errorf("failed to store client binding: %w", err) + } + found = true + } + if b != nil { + b.ProfilePin, b.ProfileMode, b.UpdatedAt = pin, mode, time.Now().UTC() + if err := putOAuthBindingTx(tx, clientID, b); err != nil { + return err + } + found = true + } + if !found { + return ErrClientCredentialNotFound + } + return nil +} + +// RepairOAuthClientBindings makes every client that has both an API-key record +// and an oauth_client_bindings entry agree, taking the API-key record as the +// truth. It returns the ids it repaired (the caller logs them). +// +// An API-key binding that is itself invalid (unknown mode, locked without a +// pin) is NOT copied: that client is skipped and returned in `skipped`. +func (m *Manager) RepairOAuthClientBindings() (repaired, skipped []string, err error) { + type fix struct{ id, pin, mode string } + collect := func(tx *bbolt.Tx) (todo []fix, skip []string, err error) { + err = oauthForEach(tx, OAuthClientBindingsBucket, func(id string, b OAuthClientBinding) error { + _, tok, err := findClientTokenRecordLocked(tx, id) + if err != nil { + return err + } + if tok == nil || tok.Kind != auth.KindClient { + return nil + } + if tok.ProfilePin == b.ProfilePin && tok.ProfileMode == b.ProfileMode { + return nil + } + if validateClientBinding(tok.ProfilePin, tok.ProfileMode) != nil { + skip = append(skip, id) + return nil + } + todo = append(todo, fix{id, tok.ProfilePin, tok.ProfileMode}) + return nil + }) + return todo, skip, err + } + + m.mu.Lock() + defer m.mu.Unlock() + + // View first: with nothing to repair no write transaction is opened. + var skip []string + needWrite := false + if err := m.db.db.View(func(tx *bbolt.Tx) error { + todo, s, err := collect(tx) + needWrite, skip = len(todo) > 0, s + return err + }); err != nil { + return nil, nil, err + } + if !needWrite { + return nil, skip, nil + } + err = m.db.db.Update(func(tx *bbolt.Tx) error { + repaired = nil + todo, s, err := collect(tx) + if err != nil { + return err + } + skip = s + for _, r := range todo { + if err := writeClientBindingTx(tx, r.id, r.pin, r.mode); err != nil { + return err + } + repaired = append(repaired, r.id) + } + return nil + }) + if err != nil { + return nil, nil, err + } + return repaired, skip, nil +} + +// forgetClientLoginsTx deletes every grant record of the client with its +// access index entries, the client's oauth_client_bindings entry, and the +// registrations left with no grant record. It reports how many grants it deleted. +func forgetClientLoginsTx(tx *bbolt.Tx, clientID string) (int, error) { + gb := tx.Bucket([]byte(OAuthGrantsBucket)) + n := 0 + if gb != nil { + var mine []OAuthGrant + regStays := map[string]bool{} + if err := oauthForEach(tx, OAuthGrantsBucket, func(_ string, g OAuthGrant) error { + if g.Client == clientID { + mine = append(mine, g) + } else { + regStays[g.RegistrationID] = true + } + return nil + }); err != nil { + return 0, err + } + rb := tx.Bucket([]byte(OAuthRegistrationsBucket)) + for _, g := range mine { + if err := gb.Delete([]byte(g.GrantID)); err != nil { + return 0, err + } + if err := deleteAccessIndexTx(tx, g.AccessHash); err != nil { + return 0, err + } + if rb != nil && !regStays[g.RegistrationID] { + if err := rb.Delete([]byte(g.RegistrationID)); err != nil { + return 0, err + } + } + } + n = len(mine) + } + if bb := tx.Bucket([]byte(OAuthClientBindingsBucket)); bb != nil { + if err := bb.Delete([]byte(clientID)); err != nil { + return 0, err + } + } + return n, nil +} + +// ForgetClientLogins deletes the client's browser logins and binding entry in +// one transaction (see forgetClientLoginsTx). It never touches the API-key +// record. It reports how many grants it deleted. +func (m *Manager) ForgetClientLogins(clientID string) (int, error) { + if !auth.ValidClientID(clientID) { + return 0, fmt.Errorf("invalid client id %q", clientID) + } + m.mu.Lock() + defer m.mu.Unlock() + n := 0 + err := m.db.db.Update(func(tx *bbolt.Tx) error { + var err error + n, err = forgetClientLoginsTx(tx, clientID) + return err + }) + return n, err +} + +// clientHasLoginRecordsTx reports whether the client has a binding entry or a +// grant record. +func clientHasLoginRecordsTx(tx *bbolt.Tx, clientID string) (bool, error) { + b, err := getOAuthBindingTx(tx, clientID) + if err != nil || b != nil { + return b != nil, err + } + found := false + err = oauthForEach(tx, OAuthGrantsBucket, func(_ string, g OAuthGrant) error { + if g.Client == clientID { + found = true + } + return nil + }) + return found, err +} + +// revokeClientAPIKeyTx soft-revokes the client's kind=client record (the +// exact effect of ForgetClientCredential) and returns it; nil when there is none. +func revokeClientAPIKeyTx(tx *bbolt.Tx, clientID string) (*auth.AgentToken, error) { + primaryHash, tok, err := findClientTokenRecordLocked(tx, clientID) + if err != nil { + return nil, err + } + if tok == nil || tok.Kind != auth.KindClient { + return nil, nil + } + markRevoked(tok, time.Now()) + tok.PriorProfilePin, tok.PriorProfileMode = "", "" + data, err := json.Marshal(tok) + if err != nil { + return nil, fmt.Errorf("failed to marshal client credential: %w", err) + } + if err := tx.Bucket([]byte(AgentTokensBucket)).Put(primaryHash, data); err != nil { + return nil, fmt.Errorf("failed to store revoked client credential: %w", err) + } + return tok, nil +} + +// ForgetClient is the client FORGET: it revokes the API-key record the way +// ForgetClientCredential does (the record stays as a revoked tombstone that +// reserves the name) and, in the same transaction, deletes every browser login, +// the OAuth binding entry and the registrations left without a grant. The +// returned record is nil for a client that had only browser logins. +// ErrClientCredentialNotFound means the client had nothing at all. +func (m *Manager) ForgetClient(clientID string) (*auth.AgentToken, error) { + if !auth.ValidClientID(clientID) { + return nil, fmt.Errorf("invalid client id %q", clientID) + } + m.mu.Lock() + defer m.mu.Unlock() + var revoked *auth.AgentToken + err := m.db.db.Update(func(tx *bbolt.Tx) error { + hadLogins, err := clientHasLoginRecordsTx(tx, clientID) + if err != nil { + return err + } + revoked, err = revokeClientAPIKeyTx(tx, clientID) + if err != nil { + return err + } + if revoked == nil && !hadLogins { + return ErrClientCredentialNotFound + } + _, err = forgetClientLoginsTx(tx, clientID) + return err + }) + if err != nil { + return nil, err + } + return revoked, nil +} + +// RevokeClient is the client REVOKE: the API-key record (when there is one) is +// revoked as ForgetClientCredential does, and every grant of the client is +// marked revoked with reason client_revoked. Everything is kept for display. +// The returned record is nil for a client with only browser logins. +// ErrClientCredentialNotFound means the client had nothing at all. +func (m *Manager) RevokeClient(clientID string, now time.Time) (*auth.AgentToken, error) { + if !auth.ValidClientID(clientID) { + return nil, fmt.Errorf("invalid client id %q", clientID) + } + m.mu.Lock() + defer m.mu.Unlock() + var revoked *auth.AgentToken + err := m.db.db.Update(func(tx *bbolt.Tx) error { + hadLogins, err := clientHasLoginRecordsTx(tx, clientID) + if err != nil { + return err + } + revoked, err = revokeClientAPIKeyTx(tx, clientID) + if err != nil { + return err + } + if revoked == nil && !hadLogins { + return ErrClientCredentialNotFound + } + var mine []OAuthGrant + if err := oauthForEach(tx, OAuthGrantsBucket, func(_ string, g OAuthGrant) error { + if g.Client == clientID { + mine = append(mine, g) + } + return nil + }); err != nil { + return err + } + for i := range mine { + if _, err := revokeGrantTx(tx, &mine[i], OAuthRevokeClientRevoked, now); err != nil { + return err + } + } + return nil + }) + if err != nil { + return nil, err + } + return revoked, nil +} + +// RevokeClientAPIKey revokes the API-key record only; grants and the OAuth +// binding entry are untouched. It is ForgetClientCredential under a name that +// says what it does now that a client can hold other credentials. +func (m *Manager) RevokeClientAPIKey(clientID string) (*auth.AgentToken, error) { + return m.forgetClientCredential(clientID, false) +} diff --git a/internal/storage/client_binding_dual_test.go b/internal/storage/client_binding_dual_test.go new file mode 100644 index 000000000..057d60277 --- /dev/null +++ b/internal/storage/client_binding_dual_test.go @@ -0,0 +1,278 @@ +package storage + +import ( + "encoding/json" + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// bindings returns the (pin, mode) held by the client's raw API-key record and +// by its oauth_client_bindings entry ("" / "" and ok=false when absent). +func bindings(t *testing.T, m *Manager, clientID string) (apiPin, apiMode string, apiOK bool, oPin, oMode string, oOK bool) { + t.Helper() + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + _, tok, err := findClientTokenRecordLocked(tx, clientID) + require.NoError(t, err) + if tok != nil && tok.Kind == auth.KindClient { + apiPin, apiMode, apiOK = tok.ProfilePin, tok.ProfileMode, true + } + b, err := getOAuthBindingTx(tx, clientID) + require.NoError(t, err) + if b != nil { + oPin, oMode, oOK = b.ProfilePin, b.ProfileMode, true + } + return nil + })) + return +} + +func assertEqualBindings(t *testing.T, m *Manager, clientID, pin, mode string) { + t.Helper() + apiPin, apiMode, apiOK, oPin, oMode, oOK := bindings(t, m, clientID) + require.True(t, apiOK && oOK, "both records must exist") + assert.Equal(t, pin, apiPin, "api pin") + assert.Equal(t, mode, apiMode, "api mode") + assert.Equal(t, pin, oPin, "oauth pin") + assert.Equal(t, mode, oMode, "oauth mode") +} + +// clientWithBoth: an API-key client that also got a first browser login. +func clientWithBoth(t *testing.T, m *Manager, clientID, mode, pin string) { + t.Helper() + mintTestClient(t, m, clientID, mode, pin) + now := time.Now().UTC() + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg-"+clientID, now))) + rev, err := m.ClientBindingRevision(clientID) + require.NoError(t, err) + _, err = m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("grant-"+clientID, "reg-"+clientID, clientID, now), Client: clientID, + ExpectedBindingRevision: rev, Now: now, + }) + require.NoError(t, err) +} + +func TestWriteClientBindingTx(t *testing.T) { + t.Run("both records in one tx", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, "cursor", "full", auth.ProfileModeSwitchable) + })) + assertEqualBindings(t, m, "cursor", "full", auth.ProfileModeSwitchable) + }) + + t.Run("OAuth-only client", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "ro", auth.ProfileModeLocked, time.Now()) + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, "webonly", "full", auth.ProfileModeLocked) + })) + _, _, apiOK, oPin, oMode, oOK := bindings(t, m, "webonly") + assert.False(t, apiOK) + assert.True(t, oOK) + assert.Equal(t, "full", oPin) + assert.Equal(t, auth.ProfileModeLocked, oMode) + }) + + t.Run("API-key-only client never gets an OAuth entry", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "ro") + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, "cursor", "full", auth.ProfileModeLocked) + })) + _, _, _, _, _, oOK := bindings(t, m, "cursor") + assert.False(t, oOK) + assert.Empty(t, oauthBucketNames(t, m)) + }) + + t.Run("fails when neither exists", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + err := m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, "ghost", "x", auth.ProfileModeLocked) + }) + assert.ErrorIs(t, err, ErrClientCredentialNotFound) + }) +} + +func TestUpdateClientCredentialBinding_KeepsOAuthEntryEqual(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + _, _, err := m.UpdateClientCredentialBinding("cursor", "full", auth.ProfileModeSwitchable) + require.NoError(t, err) + assertEqualBindings(t, m, "cursor", "full", auth.ProfileModeSwitchable) + + // A refused update writes neither record. + _, _, err = m.UpdateClientCredentialBinding("cursor", "", auth.ProfileModeLocked) + require.Error(t, err) + assertEqualBindings(t, m, "cursor", "full", auth.ProfileModeSwitchable) +} + +func TestMintForOAuthOnlyClient_SnapshotsAndRollbackRestores(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "ro", auth.ProfileModeLocked, time.Now()) + + rec := mintTestClient(t, m, "webonly", auth.ProfileModeSwitchable, "") + require.NotEmpty(t, rec) + // One binding: the requested (wider) one on both records. + assertEqualBindings(t, m, "webonly", "", auth.ProfileModeSwitchable) + tok, err := m.GetAgentTokenByName("client-webonly") + require.NoError(t, err) + assert.Equal(t, "ro", tok.PriorProfilePin, "the OAuth binding was snapshotted") + assert.Equal(t, auth.ProfileModeLocked, tok.PriorProfileMode) + + // An aborted/undone connect restores the snapshot to the OAuth entry and + // leaves the grant alone. + _, err = m.ForgetClientCredentialRestoringPrior("webonly") + require.NoError(t, err) + assertEqualBindings(t, m, "webonly", "ro", auth.ProfileModeLocked) + g, err := m.GetOAuthGrant("g1") + require.NoError(t, err) + assert.False(t, g.Revoked) + b, _ := m.GetOAuthClientBinding("webonly") + require.NotNil(t, b) +} + +func TestReconnectKeepsBothRecordsEqual(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + + _, err := m.RevokeClientAPIKey("cursor") + require.NoError(t, err) + assertEqualBindings(t, m, "cursor", "ro", auth.ProfileModeLocked) + + // Re-mint over the revoked tombstone with a new binding. + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "full") + assertEqualBindings(t, m, "cursor", "full", auth.ProfileModeLocked) + + // Undo of that reconnect puts the tombstone's old binding back on both. + _, err = m.ForgetClientCredentialRestoringPrior("cursor") + require.NoError(t, err) + assertEqualBindings(t, m, "cursor", "ro", auth.ProfileModeLocked) +} + +func TestRepinProfile_MovesOAuthOnlyClientAndRestorePinsRestores(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "old", auth.ProfileModeLocked, time.Now()) + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "old") + commitNew(t, m, "r2", "g2", "other", "keep", auth.ProfileModeLocked, time.Now()) + + before, err := m.RepinProfile("old", "new") + require.NoError(t, err) + require.Len(t, before, 3, "API-key record, plus restore entries for both clients") + + _, _, apiOK, oPin, oMode, oOK := bindings(t, m, "webonly") + assert.False(t, apiOK) + assert.True(t, oOK) + assert.Equal(t, "new", oPin) + assert.Equal(t, auth.ProfileModeLocked, oMode) + assertEqualBindings(t, m, "cursor", "new", auth.ProfileModeLocked) + _, _, _, oPin, _, _ = bindings(t, m, "other") + assert.Equal(t, "keep", oPin, "an unrelated client does not move") + + require.NoError(t, m.RestorePins(before)) + _, _, _, oPin, _, _ = bindings(t, m, "webonly") + assert.Equal(t, "old", oPin) + assertEqualBindings(t, m, "cursor", "old", auth.ProfileModeLocked) +} + +func TestRepinProfile_FailureLeavesOAuthEntriesUnchanged(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "old", auth.ProfileModeLocked, time.Now()) + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "old") + + boom := errors.New("boom") + _, err := m.repinProfile("old", "new", func(written int) error { + if written == 1 { + return boom + } + return nil + }) + require.ErrorIs(t, err, boom) + assertEqualBindings(t, m, "cursor", "old", auth.ProfileModeLocked) + _, _, _, oPin, _, _ := bindings(t, m, "webonly") + assert.Equal(t, "old", oPin) +} + +func TestRepairOAuthClientBindings_TakesAPIKeyRecord(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + clientWithBoth(t, m, "zed", auth.ProfileModeSwitchable, "") + commitNew(t, m, "r", "g1", "webonly", "x", auth.ProfileModeLocked, time.Now()) + + // Drift the OAuth entry of cursor behind the writer's back. + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return oauthPutJSON(tx, OAuthClientBindingsBucket, "cursor", &OAuthClientBinding{ + ProfilePin: "stale", ProfileMode: auth.ProfileModeSwitchable, UpdatedAt: time.Now(), + }) + })) + repaired, _, err := m.RepairOAuthClientBindings() + require.NoError(t, err) + assert.Equal(t, []string{"cursor"}, repaired) + assertEqualBindings(t, m, "cursor", "ro", auth.ProfileModeLocked) + + repaired, _, err = m.RepairOAuthClientBindings() + require.NoError(t, err) + assert.Empty(t, repaired) +} + +// TestDowngradeView_APIKeyRecordStaysCurrent (FR-028): a binary that predates +// browser logins reads only the agent_tokens record, so after a reassign, a +// rename and a reconnect the raw record must carry the current pin and mode. +func TestDowngradeView_APIKeyRecordStaysCurrent(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "p1") + + raw := func() (pin, mode string) { + var rec auth.AgentToken + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + return tx.Bucket([]byte(AgentTokensBucket)).ForEach(func(_, v []byte) error { + var t auth.AgentToken + if json.Unmarshal(v, &t) == nil && t.Name == "client-cursor" { + rec = t + } + return nil + }) + })) + return rec.ProfilePin, rec.ProfileMode + } + + // reassign + _, _, err := m.UpdateClientCredentialBinding("cursor", "p2", auth.ProfileModeLocked) + require.NoError(t, err) + pin, mode := raw() + assert.Equal(t, "p2", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) + + // rename + _, err = m.RepinProfile("p2", "p3") + require.NoError(t, err) + pin, _ = raw() + assert.Equal(t, "p3", pin) + + // reconnect (revoke key, mint again with another binding) + _, err = m.RevokeClientAPIKey("cursor") + require.NoError(t, err) + mintTestClient(t, m, "cursor", auth.ProfileModeSwitchable, "") + pin, mode = raw() + assert.Equal(t, "", pin) + assert.Equal(t, auth.ProfileModeSwitchable, mode) + assertEqualBindings(t, m, "cursor", "", auth.ProfileModeSwitchable) +} diff --git a/internal/storage/client_binding_hardening_test.go b/internal/storage/client_binding_hardening_test.go new file mode 100644 index 000000000..9105955fc --- /dev/null +++ b/internal/storage/client_binding_hardening_test.go @@ -0,0 +1,266 @@ +package storage + +import ( + "encoding/json" + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +func jsonUnmarshal(b []byte, v any) error { return json.Unmarshal(b, v) } + +func putTokenForTest(tx *bbolt.Tx, hash []byte, tok *auth.AgentToken) error { + data, err := json.Marshal(tok) + if err != nil { + return err + } + return tx.Bucket([]byte(AgentTokensBucket)).Put(hash, data) +} + +// TestWriteClientBindingTx_ValidatesBeforeAnyWrite: an invalid binding is an +// error and neither copy is touched, for API-key-only, OAuth-only and dual clients. +func TestWriteClientBindingTx_ValidatesBeforeAnyWrite(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "keyonly", auth.ProfileModeLocked, "ro") + commitNew(t, m, "r", "g1", "webonly", "ro", auth.ProfileModeLocked, time.Now()) + clientWithBoth(t, m, "both", auth.ProfileModeLocked, "ro") + + // (An API-key-only client is deliberately NOT validated: it is written as + // before Spec 132, see TestAPIKeyOnlyClientsAreNotValidated.) + for _, id := range []string{"webonly", "both"} { + for _, bad := range []struct{ pin, mode string }{ + {"x", "sticky"}, {"", auth.ProfileModeLocked}, {"x", ""}, + } { + before := dumpDB(t, m) + err := m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, id, bad.pin, bad.mode) + }) + require.Error(t, err, "%s %+v", id, bad) + assert.Equal(t, before, dumpDB(t, m), "%s: the transaction rolled back", id) + } + } + + // A revoked/expired tombstone is still updated as before. + _, err := m.RevokeClientAPIKey("keyonly") + require.NoError(t, err) + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, "keyonly", "full", auth.ProfileModeLocked) + })) + pin, mode, _, _, _, _ := bindings(t, m, "keyonly") + assert.Equal(t, "full", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) +} + +func TestRepairOAuthClientBindings_InvalidAPIKeyBindingIsSkipped(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + clientWithBoth(t, m, "zed", auth.ProfileModeLocked, "ro") + // Corrupt cursor's API-key record (locked, empty pin) and drift zed's entry. + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + hash, tok, err := findClientTokenRecordLocked(tx, "cursor") + require.NoError(t, err) + tok.ProfilePin = "" + return putTokenForTest(tx, hash, tok) + })) + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return oauthPutJSON(tx, OAuthClientBindingsBucket, "zed", &OAuthClientBinding{ProfilePin: "stale", ProfileMode: auth.ProfileModeLocked}) + })) + + repaired, skipped, err := m.RepairOAuthClientBindings() + require.NoError(t, err) + assert.Equal(t, []string{"zed"}, repaired) + assert.Equal(t, []string{"cursor"}, skipped) + _, _, _, oPin, _, _ := bindings(t, m, "cursor") + assert.Equal(t, "ro", oPin, "the invalid binding was not copied") +} + +func TestUpdateClientCredentialBinding_ErrorTextUnchangedForAPIKeyOnly(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "ro") + // Refusals keep their pre-slice text. + _, _, err := m.UpdateClientCredentialBinding("cursor", "", auth.ProfileModeLocked) + require.EqualError(t, err, "a locked client credential requires a non-empty profile") + _, _, err = m.UpdateClientCredentialBinding("cursor", "ro", "sticky") + require.EqualError(t, err, `invalid profile mode "sticky"`) + // The writer's own wording is never doubled (OAuth-side validation). + commitNew(t, m, "r", "g1", "webonly", "ro", auth.ProfileModeLocked, time.Now()) + err = m.db.db.Update(func(tx *bbolt.Tx) error { return writeClientBindingTx(tx, "webonly", "x", "sticky") }) + require.EqualError(t, err, `invalid profile mode "sticky"`) +} + +// TestRepinProfile_KeepsKeyOrderForRecordsAndHooks: existing records are handled +// in ONE list in bbolt key order, whether regular token or client, so `before` +// and the hook order are what they were before Spec 132. +func TestRepinProfile_KeepsKeyOrderForRecordsAndHooks(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "p") + + keyOrder := func() []string { + var names []string + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + return tx.Bucket([]byte(AgentTokensBucket)).ForEach(func(_, v []byte) error { + var tk auth.AgentToken + require.NoError(t, jsonUnmarshal(v, &tk)) + names = append(names, tk.Name) + return nil + }) + })) + return names + } + // Add agent tokens pinned to p until the client record sits in the middle. + for i := 0; i < 30; i++ { + tok, raw := makeTestToken("agent-" + string(rune('a'+i))) + tok.ProfilePin = "p" + require.NoError(t, m.CreateAgentToken(tok, raw, testHMACKey)) + names := keyOrder() + if len(names) >= 3 && names[0] != "client-cursor" && names[len(names)-1] != "client-cursor" { + break + } + } + want := keyOrder() + require.NotEqual(t, "client-cursor", want[0]) + require.NotEqual(t, "client-cursor", want[len(want)-1]) + + var hooked []int + before, err := m.repinProfile("p", "q", func(w int) error { hooked = append(hooked, w); return nil }) + require.NoError(t, err) + var gotNames []string + for _, b := range before { + gotNames = append(gotNames, b.Name) + } + assert.Equal(t, want, gotNames, "before is in bbolt key order, clients and tokens interleaved") + var seq []int + for i := range want { + seq = append(seq, i) + } + assert.Equal(t, seq, hooked) +} + +// TestRepinProfile_LeavesConnectSnapshotAlone documents the semantics: undoing a +// connect returns the client to its PRE-CONNECT binding, whatever profile rename +// happened in between, exactly as for an API-key tombstone. Grants are untouched. +func TestRepinProfile_LeavesConnectSnapshotAlone(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "", auth.ProfileModeSwitchable, time.Now()) + mintTestClient(t, m, "webonly", auth.ProfileModeLocked, "ro") // snapshot: switchable, unpinned + + _, err := m.RepinProfile("ro", "restricted") + require.NoError(t, err) + _, err = m.ForgetClientCredentialRestoringPrior("webonly") + require.NoError(t, err) + + assertEqualBindings(t, m, "webonly", "", auth.ProfileModeSwitchable) + g, err := m.GetOAuthGrant("g1") + require.NoError(t, err) + assert.False(t, g.Revoked) +} + +func TestRestorePins_OAuthSideIsCompareAndSet(t *testing.T) { + t.Run("a: dual client, API-key record removed, entry still restored", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + before, err := m.RepinProfile("ro", "full") + require.NoError(t, err) + require.NoError(t, m.DeleteAgentToken("client-cursor")) + require.NoError(t, m.RestorePins(before)) + _, _, apiOK, oPin, oMode, oOK := bindings(t, m, "cursor") + assert.False(t, apiOK) + require.True(t, oOK) + assert.Equal(t, "ro", oPin) + assert.Equal(t, auth.ProfileModeLocked, oMode) + }) + + t.Run("a2: dual client with its record present restores both", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + before, err := m.RepinProfile("ro", "full") + require.NoError(t, err) + require.NoError(t, m.RestorePins(before)) + assertEqualBindings(t, m, "cursor", "ro", auth.ProfileModeLocked) + }) + + t.Run("b: forgotten and re-created client keeps its new binding", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "A", auth.ProfileModeLocked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + _, err = m.ForgetClient("webonly") + require.NoError(t, err) + commitNew(t, m, "r2", "g2", "webonly", "P", auth.ProfileModeLocked, time.Now()) + require.NoError(t, m.RestorePins(before)) + _, _, _, oPin, _, _ := bindings(t, m, "webonly") + assert.Equal(t, "P", oPin) + }) + + t.Run("b2: a forgotten entry is not re-created", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "A", auth.ProfileModeLocked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + _, err = m.ForgetClient("webonly") + require.NoError(t, err) + require.NoError(t, m.RestorePins(before)) + _, _, _, _, _, oOK := bindings(t, m, "webonly") + assert.False(t, oOK) + }) + + t.Run("c: a connect minted after the repin keeps both copies", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "A", auth.ProfileModeLocked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + mintTestClient(t, m, "webonly", auth.ProfileModeLocked, "P") + require.NoError(t, m.RestorePins(before)) + assertEqualBindings(t, m, "webonly", "P", auth.ProfileModeLocked) + }) + + t.Run("d: a stored record with an empty hash is not a restore entry", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "A", auth.ProfileModeLocked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + require.Len(t, before, 1) + assert.True(t, isRepinRestoreEntry(&before[0])) + + // Same shape, no marker: ignored entirely. + lookalike := auth.AgentToken{Name: "client-webonly", Kind: auth.KindClient, ClientID: "webonly", + ProfilePin: "A", ProfileMode: auth.ProfileModeLocked, TokenHash: ""} + assert.False(t, isRepinRestoreEntry(&lookalike)) + require.NoError(t, m.RestorePins([]auth.AgentToken{lookalike})) + _, _, _, oPin, _, _ := bindings(t, m, "webonly") + assert.Equal(t, "B", oPin) + + // The real entry still restores. + require.NoError(t, m.RestorePins(before)) + _, _, _, oPin, _, _ = bindings(t, m, "webonly") + assert.Equal(t, "A", oPin) + }) +} + +func TestRepinProfile_FailureKeepsErrorTextAndRollsBack(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "p") + boom := errors.New("boom") + _, err := m.repinProfile("p", "q", func(int) error { return boom }) + require.ErrorIs(t, err, boom) + pin, _, _, _, _, _ := bindings(t, m, "cursor") + assert.Equal(t, "p", pin) +} diff --git a/internal/storage/client_binding_legacy_test.go b/internal/storage/client_binding_legacy_test.go new file mode 100644 index 000000000..dcaf12c7e --- /dev/null +++ b/internal/storage/client_binding_legacy_test.go @@ -0,0 +1,101 @@ +package storage + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// rawEditClient rewrites the client's stored API-key record without any validation. +func rawEditClient(t *testing.T, m *Manager, id string, edit func(*auth.AgentToken)) { + t.Helper() + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + hash, tok, err := findClientTokenRecordLocked(tx, id) + require.NoError(t, err) + require.NotNil(t, tok) + edit(tok) + return putTokenForTest(tx, hash, tok) + })) +} + +var badPriors = []struct{ name, pin, mode string }{ + {"invalid mode", "p", "sticky"}, + {"locked with an empty pin", "", auth.ProfileModeLocked}, +} + +// TestAPIKeyOnlyClientsAreNotValidated: a client with no browser login behaves +// exactly as before Spec 132, even when its stored binding is malformed, so one +// bad legacy record cannot block a profile rename or a connect rollback. +func TestAPIKeyOnlyClientsAreNotValidated(t *testing.T) { + t.Run("repin over an invalid mode", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "p") + rawEditClient(t, m, "cursor", func(tk *auth.AgentToken) { tk.ProfileMode = "sticky" }) + + before, err := m.RepinProfile("p", "q") + require.NoError(t, err) + require.Len(t, before, 1, "only the client record, no restore entries") + assert.Equal(t, "p", before[0].ProfilePin) + assert.Equal(t, "sticky", before[0].ProfileMode) + pin, mode, _, _, _, _ := bindings(t, m, "cursor") + assert.Equal(t, "q", pin) + assert.Equal(t, "sticky", mode, "the mode is left as it was") + require.NoError(t, m.RestorePins(before)) + pin, _, _, _, _, _ = bindings(t, m, "cursor") + assert.Equal(t, "p", pin) + }) + + for _, prior := range badPriors { + t.Run("connect rollback with a prior that is "+prior.name, func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeSwitchable, "") + rawEditClient(t, m, "cursor", func(tk *auth.AgentToken) { + tk.PriorProfilePin, tk.PriorProfileMode = prior.pin, prior.mode + }) + rec, err := m.ForgetClientCredentialRestoringPrior("cursor") + require.NoError(t, err) + assert.True(t, rec.Revoked) + assert.Equal(t, prior.pin, rec.ProfilePin) + assert.Equal(t, prior.mode, rec.ProfileMode) + pin, mode, _, _, _, _ := bindings(t, m, "cursor") + assert.Equal(t, prior.pin, pin) + assert.Equal(t, prior.mode, mode) + }) + } +} + +// TestDualClientsWithInvalidBindingsFailClosed: with a browser-login copy the +// same malformed values are refused and nothing is written. +func TestDualClientsWithInvalidBindingsFailClosed(t *testing.T) { + t.Run("repin", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "p") + rawEditClient(t, m, "cursor", func(tk *auth.AgentToken) { tk.ProfileMode = "sticky" }) + before := dumpDB(t, m) + _, err := m.RepinProfile("p", "q") + require.Error(t, err) + assert.Equal(t, before, dumpDB(t, m)) + }) + + for _, prior := range badPriors { + t.Run("rollback with a prior that is "+prior.name, func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeSwitchable, "") + rawEditClient(t, m, "cursor", func(tk *auth.AgentToken) { + tk.PriorProfilePin, tk.PriorProfileMode = prior.pin, prior.mode + }) + before := dumpDB(t, m) + _, err := m.ForgetClientCredentialRestoringPrior("cursor") + require.Error(t, err) + assert.Equal(t, before, dumpDB(t, m)) + }) + } +} diff --git a/internal/storage/client_binding_restore_test.go b/internal/storage/client_binding_restore_test.go new file mode 100644 index 000000000..f41f85f31 --- /dev/null +++ b/internal/storage/client_binding_restore_test.go @@ -0,0 +1,224 @@ +package storage + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// assertCopiesAgree: after any RestorePins, every client that has both an +// API-key record and an OAuth entry holds the same pin and mode in both. +func assertCopiesAgree(t *testing.T, m *Manager) { + t.Helper() + entries, err := m.ListOAuthClientBindings() + require.NoError(t, err) + for id, e := range entries { + apiPin, apiMode, apiOK, _, _, _ := bindings(t, m, id) + if apiOK { + assert.Equal(t, apiPin, e.ProfilePin, "%s pin copies differ", id) + assert.Equal(t, apiMode, e.ProfileMode, "%s mode copies differ", id) + } + } +} + +func restoreAndCheck(t *testing.T, m *Manager, before []auth.AgentToken) { + t.Helper() + require.NoError(t, m.RestorePins(before)) + assertCopiesAgree(t, m) +} + +// firstLogin gives an existing API-key client its first browser login. +func firstLogin(t *testing.T, m *Manager, clientID string) { + t.Helper() + now := time.Now().UTC() + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg-"+clientID, now))) + rev, err := m.ClientBindingRevision(clientID) + require.NoError(t, err) + _, err = m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("grant-"+clientID, "reg-"+clientID, clientID, now), Client: clientID, + ExpectedBindingRevision: rev, Now: now, + }) + require.NoError(t, err) +} + +func TestRestorePins_DecisionTable(t *testing.T) { + locked := auth.ProfileModeLocked + newMgr := func(t *testing.T) *Manager { + m, cleanup := setupTestStorageForAgentTokens(t) + t.Cleanup(cleanup) + return m + } + + t.Run("a: an administrator reassigned in between", func(t *testing.T) { + m := newMgr(t) + clientWithBoth(t, m, "cursor", locked, "A") + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + _, _, err = m.UpdateClientCredentialBinding("cursor", "C", locked) + require.NoError(t, err) + restoreAndCheck(t, m, before) + assertEqualBindings(t, m, "cursor", "C", locked) + }) + + t.Run("b: forgotten and re-created with the same value", func(t *testing.T) { + m := newMgr(t) + commitNew(t, m, "r", "g1", "webonly", "A", locked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + _, err = m.ForgetClient("webonly") + require.NoError(t, err) + commitNew(t, m, "r2", "g2", "webonly", "B", locked, time.Now()) + restoreAndCheck(t, m, before) + _, _, _, oPin, _, oOK := bindings(t, m, "webonly") + require.True(t, oOK) + assert.Equal(t, "B", oPin, "a different incarnation is never restored") + }) + + t.Run("c: a connect minted an API key bound to the same value", func(t *testing.T) { + m := newMgr(t) + commitNew(t, m, "r", "g1", "webonly", "A", locked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + mintTestClient(t, m, "webonly", locked, "B") + restoreAndCheck(t, m, before) + assertEqualBindings(t, m, "webonly", "B", locked) + }) + + t.Run("d: the client got its first login after the repin", func(t *testing.T) { + m := newMgr(t) + mintTestClient(t, m, "cursor", locked, "A") + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + require.Len(t, before, 1, "no restore entry: it had no entry at repin time") + firstLogin(t, m, "cursor") + assertEqualBindings(t, m, "cursor", "B", locked) + restoreAndCheck(t, m, before) + assertEqualBindings(t, m, "cursor", "A", locked) + }) + + t.Run("d2: first login, entry differs from the record: left alone", func(t *testing.T) { + m := newMgr(t) + mintTestClient(t, m, "cursor", locked, "A") + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + firstLogin(t, m, "cursor") + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return putOAuthBindingTx(tx, "cursor", &OAuthClientBinding{ProfilePin: "Z", ProfileMode: locked}) + })) + require.NoError(t, m.RestorePins(before)) + apiPin, _, _, oPin, _, _ := bindings(t, m, "cursor") + assert.Equal(t, "B", apiPin) + assert.Equal(t, "Z", oPin) + }) + + t.Run("e: plain rollback of a dual client", func(t *testing.T) { + m := newMgr(t) + clientWithBoth(t, m, "cursor", locked, "A") + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + assertEqualBindings(t, m, "cursor", "B", locked) + restoreAndCheck(t, m, before) + assertEqualBindings(t, m, "cursor", "A", locked) + }) + + t.Run("f: dual client, API-key record removed", func(t *testing.T) { + m := newMgr(t) + clientWithBoth(t, m, "cursor", locked, "A") + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + require.NoError(t, m.DeleteAgentToken("client-cursor")) + restoreAndCheck(t, m, before) + _, _, apiOK, oPin, _, oOK := bindings(t, m, "cursor") + assert.False(t, apiOK) + require.True(t, oOK) + assert.Equal(t, "A", oPin) + }) + + t.Run("f2: an entry that is gone is not re-created", func(t *testing.T) { + m := newMgr(t) + commitNew(t, m, "r", "g1", "webonly", "A", locked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + _, err = m.ForgetClient("webonly") + require.NoError(t, err) + restoreAndCheck(t, m, before) + _, _, _, _, _, oOK := bindings(t, m, "webonly") + assert.False(t, oOK) + }) + + t.Run("g: a same-value repin and restore changes nothing", func(t *testing.T) { + m := newMgr(t) + commitNew(t, m, "r", "g1", "webonly", "", auth.ProfileModeSwitchable, time.Now()) + mintTestClient(t, m, "webonly", locked, "P") // snapshot: unpinned, switchable + before, err := m.RepinProfile("P", "P") + require.NoError(t, err) + restoreAndCheck(t, m, before) + assertEqualBindings(t, m, "webonly", "P", locked) + tok, err := m.GetAgentTokenByName("client-webonly") + require.NoError(t, err) + assert.Equal(t, "", tok.PriorProfilePin) + assert.Equal(t, auth.ProfileModeSwitchable, tok.PriorProfileMode, "the connect snapshot is untouched") + }) + + t.Run("h: an API-key-only install is as before", func(t *testing.T) { + m := newMgr(t) + mintTestClient(t, m, "cursor", locked, "A") + tok, raw := makeTestToken("agent-one") + tok.ProfilePin = "A" + require.NoError(t, m.CreateAgentToken(tok, raw, testHMACKey)) + + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + require.Len(t, before, 2, "the two records only: no restore entries") + for i := range before { + assert.False(t, isRepinRestoreEntry(&before[i])) + assert.Equal(t, "A", before[i].ProfilePin) + } + // Unconditional, as before: even a record that moved on is put back. + _, _, err = m.UpdateClientCredentialBinding("cursor", "C", locked) + require.NoError(t, err) + restoreAndCheck(t, m, before) + pin, _, _, _, _, oOK := bindings(t, m, "cursor") + assert.Equal(t, "A", pin) + assert.False(t, oOK, "no entry is ever created") + assert.Empty(t, oauthBucketNames(t, m)) + got, err := m.GetAgentTokenByName("agent-one") + require.NoError(t, err) + assert.Equal(t, "A", got.ProfilePin) + }) +} + +// TestBindingWriteIDChangesOnEveryWrite: a deleted-and-recreated entry never has +// the old id, even with the same pin and mode; ClientBindingRevision ignores it. +func TestBindingWriteIDChangesOnEveryWrite(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "A", auth.ProfileModeLocked, time.Now()) + id := func() string { + b, err := m.GetOAuthClientBinding("webonly") + require.NoError(t, err) + require.NotNil(t, b) + require.Len(t, b.WriteID, 16) + return b.WriteID + } + first := id() + rev, _ := m.ClientBindingRevision("webonly") + + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, "webonly", "A", auth.ProfileModeLocked) // same value + })) + second := id() + assert.NotEqual(t, first, second) + rev2, _ := m.ClientBindingRevision("webonly") + assert.Equal(t, rev, rev2) + + _, err := m.ForgetClient("webonly") + require.NoError(t, err) + commitNew(t, m, "r2", "g2", "webonly", "A", auth.ProfileModeLocked, time.Now()) + assert.NotEqual(t, second, id()) +} diff --git a/internal/storage/client_binding_source_test.go b/internal/storage/client_binding_source_test.go new file mode 100644 index 000000000..f0fa3c1a1 --- /dev/null +++ b/internal/storage/client_binding_source_test.go @@ -0,0 +1,211 @@ +package storage + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// bindingWriteSites parses one Go source and counts every direct write to a +// ProfilePin / ProfileMode field, keyed by "|", where +// shape is "assign:" for an assignment to a selector (e.g. +// "assign:tok.ProfilePin") and "literal:" for a composite-literal key. +func bindingWriteSites(t *testing.T, filename string, src []byte) map[string]int { + t.Helper() + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, filename, src, 0) + require.NoError(t, err) + isField := func(n string) bool { return n == "ProfilePin" || n == "ProfileMode" } + out := map[string]int{} + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.AssignStmt: + for _, lhs := range x.Lhs { + if sel, ok := lhs.(*ast.SelectorExpr); ok && isField(sel.Sel.Name) { + recv := "?" + if id, ok := sel.X.(*ast.Ident); ok { + recv = id.Name + } + out[fn.Name.Name+"|assign:"+recv+"."+sel.Sel.Name]++ + } + } + case *ast.KeyValueExpr: + if id, ok := x.Key.(*ast.Ident); ok && isField(id.Name) { + out[fn.Name.Name+"|literal:"+id.Name]++ + } + } + return true + }) + } + return out +} + +// allowedBindingWriteSites lists EVERY direct write to a client's pin/mode in +// this package's non-test code, by exact site (function, shape) and count, so a +// new mutation inside an allow-listed function fails too. A new writer must go +// through writeClientBindingTx (research R4). +var allowedBindingWriteSites = map[string]int{ + // THE writer of a client's pin/mode in both stores (API-key record, then + // the OAuth entry). + "writeClientBindingOptsTx|assign:tok.ProfilePin": 1, // tok.ProfilePin, tok.ProfileMode = pin, mode + "writeClientBindingOptsTx|assign:tok.ProfileMode": 1, + "writeClientBindingOptsTx|assign:b.ProfilePin": 1, // the OAuth entry + "writeClientBindingOptsTx|assign:b.ProfileMode": 1, + + // Builds the brand-new client record literal; the OAuth entry is then + // synced through writeClientBindingTx in the same transaction. + "MintClientCredentialWith|literal:ProfileMode": 1, + "MintClientCredentialWith|literal:ProfilePin": 1, + + // Assigns on a COPY only to validate the invariants and to return the + // after-snapshot; the stored write is writeClientBindingOptsTx. + "UpdateClientCredentialBinding|assign:updated.ProfilePin": 1, + "UpdateClientCredentialBinding|assign:updated.ProfileMode": 1, + + // Sets the restored binding on the RETURNED record, which is already + // stored; the stored restore is writeClientBindingTx. + "forgetClientCredential|assign:tok.ProfilePin": 1, + "forgetClientCredential|assign:tok.ProfileMode": 1, + + // Regular (non-client) agent tokens are rewritten directly by repin; client + // records go through the writer. + "repinProfile|assign:t.ProfilePin": 1, + // The restore entry carries the OLD binding in these fields. + "repinRestoreEntry|literal:ProfilePin": 1, + "repinRestoreEntry|literal:ProfileMode": 1, + + // Restores a stored record's pin by hash, exactly as before Spec 132 (the + // mode is never changed by a repin; browser-login entries are restored + // compare-and-set through writeClientBindingTx). + "restoreRecordPinTx|assign:t.ProfilePin": 1, + + // The only creator of oauth_client_bindings entries (a client's first login). + "CommitOAuthLogin|assign:nb.ProfilePin": 2, // new-client branch and existing-client branch + "CommitOAuthLogin|assign:nb.ProfileMode": 2, +} + +func TestClientBindingFieldsWrittenOnlyByAllowListedSites(t *testing.T) { + files, err := filepath.Glob("*.go") + require.NoError(t, err) + got := map[string]int{} + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + src, err := os.ReadFile(f) + require.NoError(t, err) + for k, n := range bindingWriteSites(t, f, src) { + got[k] += n + } + } + assert.Equal(t, allowedBindingWriteSites, got, + "a direct write to ProfilePin/ProfileMode appeared, disappeared or was duplicated: "+ + "route it through writeClientBindingTx, or justify the allow-list change") +} + +// TestBindingWriteSiteChecker_DetectsBypass proves the checker sees a direct +// mutation added inside an allow-listed function and in a new function. +func TestBindingWriteSiteChecker_DetectsBypass(t *testing.T) { + src := []byte(`package storage + +func writeClientBindingOptsTx() { + tok.ProfilePin, tok.ProfileMode = pin, mode + tok.ProfilePin = "second write" +} + +func sneaky() { + rec.ProfileMode = "locked" + _ = AgentToken{ProfilePin: "x"} +} +`) + got := bindingWriteSites(t, "synthetic.go", src) + assert.Equal(t, 2, got["writeClientBindingOptsTx|assign:tok.ProfilePin"], "the duplicate is counted") + assert.Equal(t, 1, got["sneaky|assign:rec.ProfileMode"]) + assert.Equal(t, 1, got["sneaky|literal:ProfilePin"]) + assert.NotEqual(t, allowedBindingWriteSites["writeClientBindingOptsTx|assign:tok.ProfilePin"], + got["writeClientBindingOptsTx|assign:tok.ProfilePin"], "exceeds the allow-list count") + _, allowed := allowedBindingWriteSites["sneaky|assign:rec.ProfileMode"] + assert.False(t, allowed) +} + +// TestNoProductionCodeCreatesClientRecordsThroughCreateAgentToken: CreateAgentToken +// stores a whole record and would bypass the binding writer for a Kind=client +// record. Client records are minted only through MintClientCredential*, so no +// non-test caller of CreateAgentToken may mention KindClient or set a Kind. +func TestNoProductionCodeCreatesClientRecordsThroughCreateAgentToken(t *testing.T) { + roots := []string{"..", filepath.Join("..", "..", "cmd")} + var offenders []string + calls := 0 + for _, root := range roots { + require.NoError(t, filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + src, err := os.ReadFile(path) + if err != nil || !strings.Contains(string(src), "CreateAgentToken(") { + return err + } + file, err := parser.ParseFile(token.NewFileSet(), path, src, 0) + if err != nil { + return nil + } + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil || fn.Name.Name == "CreateAgentToken" { + continue + } + callsHere, setsKind := false, false + ast.Inspect(fn.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.CallExpr: + if sel, ok := x.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "CreateAgentToken" { + callsHere = true + } + case *ast.SelectorExpr: + if x.Sel.Name == "KindClient" { + setsKind = true + } + case *ast.KeyValueExpr: + if id, ok := x.Key.(*ast.Ident); ok && id.Name == "Kind" { + setsKind = true + } + case *ast.AssignStmt: + for _, l := range x.Lhs { + if sel, ok := l.(*ast.SelectorExpr); ok && sel.Sel.Name == "Kind" { + setsKind = true + } + } + } + return true + }) + if callsHere { + calls++ + if setsKind { + offenders = append(offenders, path+" "+fn.Name.Name) + } + } + } + return nil + })) + } + sort.Strings(offenders) + assert.Empty(t, offenders) + assert.Positive(t, calls, "the walk must actually find the callers (guards against a vacuous pass)") +} diff --git a/internal/storage/client_credentials.go b/internal/storage/client_credentials.go index 1b5d2ff84..80caab4f3 100644 --- a/internal/storage/client_credentials.go +++ b/internal/storage/client_credentials.go @@ -205,6 +205,13 @@ func (m *Manager) MintClientCredentialWith(clientID, rawToken string, hmacKey [] if pendingBucket != nil && existing.PendingHash != "" { _ = pendingBucket.Delete([]byte(existing.PendingHash)) } + } else if ob, obErr := getOAuthBindingTx(tx, clientID); obErr != nil { + return obErr + } else if ob != nil { + // A client with only browser logins: snapshot its binding so an + // aborted or undone connect can put it back on the OAuth entry + // (Spec 132 R4). With no OAuth entry nothing is read or written. + token.PriorProfilePin, token.PriorProfileMode = ob.ProfilePin, ob.ProfileMode } count := tokenBucket.Stats().KeyN @@ -216,7 +223,12 @@ func (m *Manager) MintClientCredentialWith(clientID, rawToken string, hmacKey [] if err != nil { return fmt.Errorf("failed to marshal client credential: %w", err) } - return tokenBucket.Put([]byte(hash), data) + if err := tokenBucket.Put([]byte(hash), data); err != nil { + return err + } + // Keep one binding: the requested pin/mode also goes to the client's + // OAuth entry when it has one (Spec 132 R4). + return writeClientBindingTx(tx, clientID, pin, mode) }) if err != nil { return nil, err @@ -249,7 +261,7 @@ func (m *Manager) UpdateClientCredentialBinding(clientID, pin, mode string) (bef if tokenBucket == nil { return ErrClientCredentialNotFound } - primaryHash, existing, err := findClientTokenRecordLocked(tx, clientID) + _, existing, err := findClientTokenRecordLocked(tx, clientID) if err != nil { return err } @@ -272,12 +284,11 @@ func (m *Manager) UpdateClientCredentialBinding(clientID, pin, mode string) (bef if err := auth.ValidateTokenInvariants(&updated, auth.KindClient); err != nil { return fmt.Errorf("binding update produced an invalid client credential record: %w", err) } - data, err := json.Marshal(updated) - if err != nil { - return fmt.Errorf("failed to marshal client credential: %w", err) - } - if err := tokenBucket.Put(primaryHash, data); err != nil { - return fmt.Errorf("failed to store client binding: %w", err) + // `updated` only validates the result and is returned as the new + // snapshot; the stored write is the one binding writer, which also + // keeps the client's OAuth entry equal. + if err := writeClientBindingOptsTx(tx, clientID, pin, mode, true); err != nil { + return err } before, after = &snapshot, &updated return nil @@ -560,9 +571,7 @@ func (m *Manager) forgetClientCredential(clientID string, restorePrior bool) (*a return ErrClientCredentialNotFound } markRevoked(tok, time.Now()) - if restorePrior && tok.PriorProfileMode != "" { - tok.ProfilePin, tok.ProfileMode = tok.PriorProfilePin, tok.PriorProfileMode - } + priorPin, priorMode := tok.PriorProfilePin, tok.PriorProfileMode tok.PriorProfilePin, tok.PriorProfileMode = "", "" data, err := json.Marshal(tok) if err != nil { @@ -571,6 +580,14 @@ func (m *Manager) forgetClientCredential(clientID string, restorePrior bool) (*a if err := tokenBucket.Put(primaryHash, data); err != nil { return fmt.Errorf("failed to store revoked client credential: %w", err) } + if restorePrior && priorMode != "" { + // Roll back the aborted connect's binding on BOTH records through + // the one binding writer; browser-login grants are not touched. + if err := writeClientBindingTx(tx, clientID, priorPin, priorMode); err != nil { + return err + } + tok.ProfilePin, tok.ProfileMode = priorPin, priorMode + } revoked = tok return nil }) diff --git a/internal/storage/oauth_login.go b/internal/storage/oauth_login.go new file mode 100644 index 000000000..ba001f97b --- /dev/null +++ b/internal/storage/oauth_login.go @@ -0,0 +1,1031 @@ +package storage + +import ( + "crypto/subtle" + "encoding/json" + "errors" + "fmt" + "sort" + "time" + "unicode/utf8" + + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// Spec 132 (browser login for MCP clients), storage layer. +// +// HARD RULE (FR-002, research R10): nothing here creates a bucket or a key +// unless a browser-login write actually happens. Every bucket below is LAZY: +// it is created with CreateBucketIfNotExists on a write path, never from +// initBuckets, and every reader treats a nil bucket as empty. A database that +// never saw a browser login therefore stays byte-for-byte what it was. +const ( + // OAuthRegistrationsBucket holds dynamic client registrations, key client_id. + OAuthRegistrationsBucket = "oauth_registrations" + // OAuthGrantsBucket holds browser-login grants, key grant_id. + OAuthGrantsBucket = "oauth_grants" + // OAuthGrantAccessIndexBucket maps access-token hash -> grant id. It is a + // sibling bucket (not a nested one) so ForEach over OAuthGrantsBucket only + // ever sees grant rows. + OAuthGrantAccessIndexBucket = "oauth_grant_access_index" + // OAuthClientBindingsBucket holds the binding copy of a client that has at + // least one grant record, key client id. + OAuthClientBindingsBucket = "oauth_client_bindings" + // OAuthLoginEverUsedKey is the MetaBucket marker holding the RFC 3339 time + // of the first stored grant. Never deleted. + OAuthLoginEverUsedKey = "oauth_login_ever_used" +) + +// Registration states (data-model.md). A denial is not a state. +const ( + OAuthRegistrationPending = "pending" + OAuthRegistrationAuthorized = "authorized" + OAuthRegistrationApproved = "approved" +) + +// Grant revoke reasons. +const ( + OAuthRevokeAdmin = "admin" + OAuthRevokeClientRevoked = "client_revoked" + OAuthRevokeReplaced = "replaced" + OAuthRevokeReplay = "replay" +) + +// Bounds from the data model. +const ( + // MaxUnapprovedOAuthRegistrations caps pending + authorized rows together. + MaxUnapprovedOAuthRegistrations = 50 + // OAuthPendingRegistrationTTL is how long a pending row lives from created_at. + OAuthPendingRegistrationTTL = 15 * time.Minute + // OAuthAuthorizedRegistrationTTL is how long an authorized row lives from authorized_at. + OAuthAuthorizedRegistrationTTL = 24 * time.Hour + // OAuthDeadGrantRetention is how long a revoked or lapsed grant is kept for display. + OAuthDeadGrantRetention = 30 * 24 * time.Hour +) + +// OAuthBindingAbsent is the revision of a client that has neither an API-key +// record nor a browser-login binding. +const OAuthBindingAbsent = "absent" + +// Sentinel errors of the browser-login storage surface. +var ( + // ErrOAuthRegistrationGone: the registration is not stored (evicted, swept + // or deleted with its last grant); it is never recreated from a code. + ErrOAuthRegistrationGone = errors.New("oauth registration not found") + // ErrOAuthClientExists: a decision that creates a new client found the id + // already held by an API-key record or a browser-login binding. + ErrOAuthClientExists = errors.New("client already exists") + // ErrOAuthBindingChanged: the client's binding revision is no longer the + // one the decision was made against. + ErrOAuthBindingChanged = errors.New("client binding changed since it was reviewed") + // ErrOAuthGrantNotFound: no such grant. + ErrOAuthGrantNotFound = errors.New("oauth grant not found") + // ErrOAuthRegistrationExists: CreateOAuthRegistration found the client id + // already stored (an approved registration must never be overwritten). + ErrOAuthRegistrationExists = errors.New("oauth registration already exists") +) + +// OAuthActor names who approved a login. +type OAuthActor struct { + Kind string `json:"kind"` + Name string `json:"name,omitempty"` +} + +// OAuthRegistration is a dynamic client registration (data-model.md). +type OAuthRegistration struct { + ClientID string `json:"client_id"` + ReportedName string `json:"reported_name,omitempty"` + RedirectURIs []string `json:"redirect_uris"` + SoftwareID string `json:"software_id,omitempty"` + SoftwareVersion string `json:"software_version,omitempty"` + TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"` + GrantTypes []string `json:"grant_types"` + State string `json:"state"` + CreatedAt time.Time `json:"created_at"` + AuthorizedAt *time.Time `json:"authorized_at,omitempty"` +} + +// OAuthGrant is one browser login (data-model.md). +type OAuthGrant struct { + GrantID string `json:"grant_id"` + RegistrationID string `json:"registration_id"` + Client string `json:"client"` + RedirectURI string `json:"redirect_uri"` + Resource string `json:"resource"` + Issuer string `json:"issuer"` + RefreshHash string `json:"refresh_hash"` + RefreshPrefix string `json:"refresh_prefix"` + AccessHash string `json:"access_hash"` + AccessExpiresAt time.Time `json:"access_expires_at"` + RefreshExpiresAt time.Time `json:"refresh_expires_at"` + ApprovedAt time.Time `json:"approved_at"` + ApprovedBy OAuthActor `json:"approved_by"` + LastUsedAt *time.Time `json:"last_used_at,omitempty"` + ObservedClientName string `json:"observed_client_name,omitempty"` + ObservedAt *time.Time `json:"observed_at,omitempty"` + DisplayPrefix string `json:"display_prefix"` + Revoked bool `json:"revoked"` + RevokedAt *time.Time `json:"revoked_at,omitempty"` + RevokeReason string `json:"revoke_reason,omitempty"` + UserID string `json:"user_id,omitempty"` +} + +// OAuthClientBinding is the binding copy kept for a client with browser logins. +type OAuthClientBinding struct { + ProfilePin string `json:"profile_pin"` + ProfileMode string `json:"profile_mode"` + DisplayName string `json:"display_name,omitempty"` + UpdatedAt time.Time `json:"updated_at"` + // WriteID is the entry's incarnation: a fresh random id on EVERY write, so a + // deleted-and-recreated entry never carries an old id even with identical + // pin and mode. Storage-internal; it is not part of ClientBindingRevision. + WriteID string `json:"write_id,omitempty"` +} + +// Refresh rotation outcomes. +type RefreshOutcome int + +const ( + // RefreshInvalid: unknown, revoked or lapsed grant. Nothing was written. + RefreshInvalid RefreshOutcome = iota + // RefreshRotated: the presented secret was current; the grant rotated. + RefreshRotated + // RefreshReplay: the presented secret was an old one; the grant is revoked. + RefreshReplay +) + +// --- small bucket helpers (all nil-tolerant on the read side) --- + +func oauthGetJSON(tx *bbolt.Tx, bucket, key string, out any) (bool, error) { + b := tx.Bucket([]byte(bucket)) + if b == nil { + return false, nil + } + v := b.Get([]byte(key)) + if v == nil { + return false, nil + } + if err := json.Unmarshal(v, out); err != nil { + return false, fmt.Errorf("failed to unmarshal %s/%s: %w", bucket, key, err) + } + return true, nil +} + +func oauthPutJSON(tx *bbolt.Tx, bucket, key string, v any) error { + b, err := tx.CreateBucketIfNotExists([]byte(bucket)) + if err != nil { + return fmt.Errorf("failed to create %s bucket: %w", bucket, err) + } + data, err := json.Marshal(v) + if err != nil { + return fmt.Errorf("failed to marshal %s/%s: %w", bucket, key, err) + } + return b.Put([]byte(key), data) +} + +func oauthForEach[T any](tx *bbolt.Tx, bucket string, fn func(key string, v T) error) error { + b := tx.Bucket([]byte(bucket)) + if b == nil { + return nil + } + return b.ForEach(func(k, raw []byte) error { + var v T + if err := json.Unmarshal(raw, &v); err != nil { + return nil // skip unparseable rows, like the agent token scans + } + return fn(string(k), v) + }) +} + +func getOAuthBindingTx(tx *bbolt.Tx, clientID string) (*OAuthClientBinding, error) { + var b OAuthClientBinding + ok, err := oauthGetJSON(tx, OAuthClientBindingsBucket, clientID, &b) + if err != nil || !ok { + return nil, err + } + return &b, nil +} + +func getOAuthGrantTx(tx *bbolt.Tx, id string) (*OAuthGrant, error) { + var g OAuthGrant + ok, err := oauthGetJSON(tx, OAuthGrantsBucket, id, &g) + if err != nil || !ok { + return nil, err + } + return &g, nil +} + +func putOAuthGrantTx(tx *bbolt.Tx, g *OAuthGrant) error { + return oauthPutJSON(tx, OAuthGrantsBucket, g.GrantID, g) +} + +func deleteAccessIndexTx(tx *bbolt.Tx, accessHash string) error { + if accessHash == "" { + return nil + } + b := tx.Bucket([]byte(OAuthGrantAccessIndexBucket)) + if b == nil { + return nil + } + return b.Delete([]byte(accessHash)) +} + +func putAccessIndexTx(tx *bbolt.Tx, accessHash, grantID string) error { + if accessHash == "" { + return nil + } + b, err := tx.CreateBucketIfNotExists([]byte(OAuthGrantAccessIndexBucket)) + if err != nil { + return fmt.Errorf("failed to create %s bucket: %w", OAuthGrantAccessIndexBucket, err) + } + return b.Put([]byte(accessHash), []byte(grantID)) +} + +// revokeGrantTx marks g revoked (no-op when already revoked) and drops its +// access index entry. Reports whether it changed anything. +func revokeGrantTx(tx *bbolt.Tx, g *OAuthGrant, reason string, now time.Time) (bool, error) { + if g.Revoked { + return false, nil + } + at := now.UTC() + g.Revoked = true + g.RevokedAt = &at + g.RevokeReason = reason + if err := deleteAccessIndexTx(tx, g.AccessHash); err != nil { + return false, err + } + if err := putOAuthGrantTx(tx, g); err != nil { + return false, err + } + return true, nil +} + +// --- registrations --- + +// CreateOAuthRegistration stores a new pending registration. At most +// MaxUnapprovedOAuthRegistrations rows may be pending or authorized together; +// when the cap is exceeded the OLDEST such row is dropped in the same +// transaction (approved rows are never evicted). +func (m *Manager) CreateOAuthRegistration(reg OAuthRegistration) error { + if reg.ClientID == "" { + return fmt.Errorf("registration needs a client id") + } + reg.State = OAuthRegistrationPending + reg.AuthorizedAt = nil + if reg.CreatedAt.IsZero() { + reg.CreatedAt = time.Now() + } + reg.CreatedAt = reg.CreatedAt.UTC() + + m.mu.Lock() + defer m.mu.Unlock() + return m.db.db.Update(func(tx *bbolt.Tx) error { + // An id that is already stored (above all an approved registration + // with live grants) is never overwritten. + var existing OAuthRegistration + if found, err := oauthGetJSON(tx, OAuthRegistrationsBucket, reg.ClientID, &existing); err != nil { + return err + } else if found { + return ErrOAuthRegistrationExists + } + if err := oauthPutJSON(tx, OAuthRegistrationsBucket, reg.ClientID, ®); err != nil { + return err + } + type row struct { + id string + at time.Time + } + // The new row takes part in the "oldest non-approved" choice, so a + // backdated insert cannot evict a newer row while surviving itself. + open := []row{{reg.ClientID, reg.CreatedAt}} + if err := oauthForEach(tx, OAuthRegistrationsBucket, func(key string, r OAuthRegistration) error { + if r.State != OAuthRegistrationApproved && key != reg.ClientID { + open = append(open, row{key, r.CreatedAt}) + } + return nil + }); err != nil { + return err + } + excess := len(open) - MaxUnapprovedOAuthRegistrations + if excess <= 0 { + return nil + } + sort.Slice(open, func(i, j int) bool { + if open[i].at.Equal(open[j].at) { + return open[i].id < open[j].id + } + return open[i].at.Before(open[j].at) + }) + b := tx.Bucket([]byte(OAuthRegistrationsBucket)) + for _, r := range open[:excess] { + if err := b.Delete([]byte(r.id)); err != nil { + return err + } + } + return nil + }) +} + +// GetOAuthRegistration returns the registration, or ErrOAuthRegistrationGone. +func (m *Manager) GetOAuthRegistration(id string) (*OAuthRegistration, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var reg OAuthRegistration + var found bool + err := m.db.db.View(func(tx *bbolt.Tx) error { + var err error + found, err = oauthGetJSON(tx, OAuthRegistrationsBucket, id, ®) + return err + }) + if err != nil { + return nil, err + } + if !found { + return nil, ErrOAuthRegistrationGone + } + return ®, nil +} + +// MarkOAuthRegistrationAuthorized moves pending -> authorized and stamps +// authorized_at. An authorized row keeps its first stamp; an approved row is +// left alone. +func (m *Manager) MarkOAuthRegistrationAuthorized(id string, at time.Time) error { + m.mu.Lock() + defer m.mu.Unlock() + return m.db.db.Update(func(tx *bbolt.Tx) error { + var reg OAuthRegistration + ok, err := oauthGetJSON(tx, OAuthRegistrationsBucket, id, ®) + if err != nil { + return err + } + if !ok { + return ErrOAuthRegistrationGone + } + if reg.State != OAuthRegistrationPending { + return nil + } + t := at.UTC() + reg.State = OAuthRegistrationAuthorized + reg.AuthorizedAt = &t + return oauthPutJSON(tx, OAuthRegistrationsBucket, id, ®) + }) +} + +// SweepOAuthRegistrations deletes pending rows older than 15 minutes (from +// created_at) and authorized rows older than 24 hours (from authorized_at). +// Approved rows are never swept. It returns how many rows it deleted. +func (m *Manager) SweepOAuthRegistrations(now time.Time) (int, error) { + m.mu.Lock() + defer m.mu.Unlock() + + // View first: with nothing to sweep no write transaction is opened (an + // empty Update still commits a meta page). + any := false + if err := m.db.db.View(func(tx *bbolt.Tx) error { + drop, err := registrationsToSweepTx(tx, now) + any = len(drop) > 0 + return err + }); err != nil || !any { + return 0, err + } + + deleted := 0 + err := m.db.db.Update(func(tx *bbolt.Tx) error { + b := tx.Bucket([]byte(OAuthRegistrationsBucket)) + if b == nil { + return nil + } + drop, err := registrationsToSweepTx(tx, now) + if err != nil { + return err + } + for _, k := range drop { + if err := b.Delete([]byte(k)); err != nil { + return err + } + } + deleted = len(drop) + return nil + }) + return deleted, err +} + +func registrationsToSweepTx(tx *bbolt.Tx, now time.Time) ([]string, error) { + var drop []string + err := oauthForEach(tx, OAuthRegistrationsBucket, func(key string, r OAuthRegistration) error { + switch r.State { + case OAuthRegistrationPending: + if now.Sub(r.CreatedAt) > OAuthPendingRegistrationTTL { + drop = append(drop, key) + } + case OAuthRegistrationAuthorized: + at := r.CreatedAt + if r.AuthorizedAt != nil { + at = *r.AuthorizedAt + } + if now.Sub(at) > OAuthAuthorizedRegistrationTTL { + drop = append(drop, key) + } + } + return nil + }) + return drop, err +} + +// ListOAuthRegistrations returns every stored registration. +func (m *Manager) ListOAuthRegistrations() ([]OAuthRegistration, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var out []OAuthRegistration + err := m.db.db.View(func(tx *bbolt.Tx) error { + return oauthForEach(tx, OAuthRegistrationsBucket, func(_ string, r OAuthRegistration) error { + out = append(out, r) + return nil + }) + }) + return out, err +} + +// --- binding revision --- + +// clientBindingRevisionTx is the revision of the client's current binding: +// the first 8 bytes of sha256(client|pin|mode), hex. The API-key record wins +// over the browser-login entry; a client with neither is OAuthBindingAbsent. +func clientBindingRevisionTx(tx *bbolt.Tx, clientID string) (string, error) { + pin, mode, exists, err := currentClientBindingTx(tx, clientID) + if err != nil { + return "", err + } + if !exists { + return OAuthBindingAbsent, nil + } + return bindingRevision(clientID, pin, mode), nil +} + +// currentClientBindingTx reads a client's binding: from the API-key (kind +// client) record when there is one, else from the browser-login entry. +func currentClientBindingTx(tx *bbolt.Tx, clientID string) (pin, mode string, exists bool, err error) { + _, tok, err := findClientTokenRecordLocked(tx, clientID) + if err != nil { + return "", "", false, err + } + if tok != nil && tok.Kind == auth.KindClient { + return tok.ProfilePin, tok.ProfileMode, true, nil + } + b, err := getOAuthBindingTx(tx, clientID) + if err != nil { + return "", "", false, err + } + if b != nil { + return b.ProfilePin, b.ProfileMode, true, nil + } + return "", "", false, nil +} + +// CurrentClientBinding returns the binding the client is held to: the API-key +// record's pin and mode when the client has one, else its browser-login entry; +// found=false when it has neither. The browser-login request path MUST read the +// binding through this function and never from the OAuth entry alone: an older +// binary that knows nothing of browser logins may have changed the API-key +// record while the entry stayed behind, and the API-key record is the truth. +func (m *Manager) CurrentClientBinding(clientID string) (pin, mode string, found bool, err error) { + m.mu.RLock() + defer m.mu.RUnlock() + err = m.db.db.View(func(tx *bbolt.Tx) error { + var e error + pin, mode, found, e = currentClientBindingTx(tx, clientID) + return e + }) + return pin, mode, found, err +} + +// ClientBindingRevision returns the binding revision the consent page shows +// and sends back; see clientBindingRevisionTx. +func (m *Manager) ClientBindingRevision(clientID string) (string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var rev string + err := m.db.db.View(func(tx *bbolt.Tx) error { + var err error + rev, err = clientBindingRevisionTx(tx, clientID) + return err + }) + return rev, err +} + +// --- grants --- + +// CommitLoginInput is everything the token exchange hands to CommitOAuthLogin. +type CommitLoginInput struct { + // Grant is the prepared grant; Client and RegistrationID must be set. + Grant OAuthGrant + // Client is the Clients hub client id (must equal Grant.Client). + Client string + // NewClient: the decision creates a client; the id must be absent. + NewClient bool + // Pin, Mode, DisplayName are the binding of a NEW client. An existing + // API-key client's entry is always copied from its current record. + Pin, Mode, DisplayName string + // ExpectedBindingRevision is the revision the consent page displayed. + ExpectedBindingRevision string + // ReplaceGrantID, when set, names a login of the same client to revoke + // with reason "replaced". + ReplaceGrantID string + // Now stamps the binding entry and the ever-used marker. + Now time.Time +} + +// CommitOAuthLogin stores a browser login in ONE transaction (research R15): +// it re-checks the registration, the new-client id and the binding revision, +// creates the OAuth-side binding when the client has none, promotes the +// registration to approved, stores the grant, revokes the replaced login and +// writes the ever-used marker. Any failed check leaves the database untouched. +// +// What it does NOT detect: a revoke or forget of an EXISTING client between +// approval and exchange. The binding revision covers pin and mode only, and a +// revoke changes neither. The caller must prevent that by cancelling the +// pending request (and any unconsumed code) under the binding write lock when +// it revokes or forgets the client (research R15). +func (m *Manager) CommitOAuthLogin(in CommitLoginInput) (OAuthGrant, error) { + g := in.Grant + if in.Client == "" { + in.Client = g.Client + } + if g.Client == "" { + g.Client = in.Client + } + if g.GrantID == "" || g.RegistrationID == "" || !auth.ValidClientID(in.Client) || g.Client != in.Client { + return OAuthGrant{}, fmt.Errorf("invalid login: grant id, registration id and a matching client id are required") + } + now := in.Now + if now.IsZero() { + now = time.Now() + } + now = now.UTC() + + m.mu.Lock() + defer m.mu.Unlock() + + var stored OAuthGrant + err := m.db.db.Update(func(tx *bbolt.Tx) error { + // (1) the registration must still exist. + var reg OAuthRegistration + ok, err := oauthGetJSON(tx, OAuthRegistrationsBucket, g.RegistrationID, ®) + if err != nil { + return err + } + if !ok { + return ErrOAuthRegistrationGone + } + + // (2) a decision that creates a client needs the id absent everywhere. + _, anyRecord, err := findClientTokenRecordLocked(tx, in.Client) + if err != nil { + return err + } + existingBinding, err := getOAuthBindingTx(tx, in.Client) + if err != nil { + return err + } + if in.NewClient && (anyRecord != nil || existingBinding != nil) { + return ErrOAuthClientExists + } + + // (3) the binding the administrator reviewed is still the binding. + rev, err := clientBindingRevisionTx(tx, in.Client) + if err != nil { + return err + } + if rev != in.ExpectedBindingRevision { + return ErrOAuthBindingChanged + } + if !in.NewClient && rev == OAuthBindingAbsent { + // An existing-client decision whose client vanished: there is no + // binding to copy and none to create from input. + return ErrOAuthBindingChanged + } + + // (4) create the OAuth-side binding when the client has none. + if existingBinding == nil { + nb := OAuthClientBinding{UpdatedAt: now} + if in.NewClient { + if err := validateClientBinding(in.Pin, in.Mode); err != nil { + return err + } + if utf8.RuneCountInString(in.DisplayName) > auth.MaxClientDisplayName { + return fmt.Errorf("client display name is too long") + } + nb.ProfilePin, nb.ProfileMode, nb.DisplayName = in.Pin, in.Mode, in.DisplayName + } else { + pin, mode, exists, err := currentClientBindingTx(tx, in.Client) + if err != nil { + return err + } + if !exists { + return ErrOAuthBindingChanged + } + if err := validateClientBinding(pin, mode); err != nil { + return err + } + nb.ProfilePin, nb.ProfileMode = pin, mode + if anyRecord != nil { + nb.DisplayName = anyRecord.DisplayName + } + } + if err := putOAuthBindingTx(tx, in.Client, &nb); err != nil { + return err + } + } + + // (5) the registration becomes approved. + reg.State = OAuthRegistrationApproved + if err := oauthPutJSON(tx, OAuthRegistrationsBucket, reg.ClientID, ®); err != nil { + return err + } + + // (6) the grant. + if prev, err := getOAuthGrantTx(tx, g.GrantID); err != nil { + return err + } else if prev != nil { + return fmt.Errorf("grant %s already exists", g.GrantID) + } + g.Revoked, g.RevokedAt, g.RevokeReason = false, nil, "" + if err := putOAuthGrantTx(tx, &g); err != nil { + return err + } + if err := putAccessIndexTx(tx, g.AccessHash, g.GrantID); err != nil { + return err + } + + // (7) the replaced login, only when it belongs to the same client. + if in.ReplaceGrantID != "" && in.ReplaceGrantID != g.GrantID { + old, err := getOAuthGrantTx(tx, in.ReplaceGrantID) + if err != nil { + return err + } + if old != nil && old.Client == in.Client { + if _, err := revokeGrantTx(tx, old, OAuthRevokeReplaced, now); err != nil { + return err + } + } + } + + // (8) the ever-used marker, kept once. + meta, err := tx.CreateBucketIfNotExists([]byte(MetaBucket)) + if err != nil { + return err + } + if meta.Get([]byte(OAuthLoginEverUsedKey)) == nil { + if err := meta.Put([]byte(OAuthLoginEverUsedKey), []byte(now.Format(time.RFC3339))); err != nil { + return err + } + } + stored = g + return nil + }) + if err != nil { + return OAuthGrant{}, err + } + return stored, nil +} + +// GetOAuthGrant returns the grant, or ErrOAuthGrantNotFound. +func (m *Manager) GetOAuthGrant(id string) (*OAuthGrant, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var g *OAuthGrant + err := m.db.db.View(func(tx *bbolt.Tx) error { + var err error + g, err = getOAuthGrantTx(tx, id) + return err + }) + if err != nil { + return nil, err + } + if g == nil { + return nil, ErrOAuthGrantNotFound + } + return g, nil +} + +// ListOAuthGrants returns every stored grant. +func (m *Manager) ListOAuthGrants() ([]OAuthGrant, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var out []OAuthGrant + err := m.db.db.View(func(tx *bbolt.Tx) error { + return oauthForEach(tx, OAuthGrantsBucket, func(_ string, g OAuthGrant) error { + out = append(out, g) + return nil + }) + }) + return out, err +} + +// ListOAuthGrantsForClient returns the grants of one client, newest approval first. +func (m *Manager) ListOAuthGrantsForClient(clientID string) ([]OAuthGrant, error) { + all, err := m.ListOAuthGrants() + if err != nil { + return nil, err + } + var out []OAuthGrant + for _, g := range all { + if g.Client == clientID { + out = append(out, g) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].ApprovedAt.After(out[j].ApprovedAt) }) + return out, nil +} + +// AuthenticateOAuthAccess resolves an access-token hash to its grant and +// enforces validity itself: the hash must match (constant time), the grant must +// not be revoked, and both the access and the refresh lifetime must end +// strictly after now (so a lapsed-but-unswept grant, and the exact expiry +// instant, fail). Every failure is the one uniform ErrOAuthGrantNotFound. +func (m *Manager) AuthenticateOAuthAccess(accessHash string, now time.Time) (*OAuthGrant, error) { + g, err := m.getOAuthGrantByAccessHash(accessHash) + if err != nil { + return nil, err + } + if g.Revoked || !g.AccessExpiresAt.After(now) || !g.RefreshExpiresAt.After(now) { + return nil, ErrOAuthGrantNotFound + } + return g, nil +} + +// getOAuthGrantByAccessHash resolves an access-token hash to a NON-revoked +// grant through the index, re-checking that the grant still carries that hash. +// Expiry is not checked here; authentication goes through +// AuthenticateOAuthAccess. +func (m *Manager) getOAuthGrantByAccessHash(hash string) (*OAuthGrant, error) { + if hash == "" { + return nil, ErrOAuthGrantNotFound + } + m.mu.RLock() + defer m.mu.RUnlock() + var g *OAuthGrant + err := m.db.db.View(func(tx *bbolt.Tx) error { + idx := tx.Bucket([]byte(OAuthGrantAccessIndexBucket)) + if idx == nil { + return nil + } + id := idx.Get([]byte(hash)) + if id == nil { + return nil + } + cand, err := getOAuthGrantTx(tx, string(id)) + if err != nil || cand == nil { + return err + } + if !cand.Revoked && subtle.ConstantTimeCompare([]byte(cand.AccessHash), []byte(hash)) == 1 { + g = cand + } + return nil + }) + if err != nil { + return nil, err + } + if g == nil { + return nil, ErrOAuthGrantNotFound + } + return g, nil +} + +// RotateOAuthRefresh is the refresh-token exchange, in one transaction. The +// caller has already verified the token's MAC; storage sees hashes only. That +// MAC must bind the grant id AND the secret: storage cannot tell an old +// authentic secret from a forged one, so any non-current secret presented for a +// live grant revokes it as a replay. +// +// - unknown, revoked or lapsed grant: RefreshInvalid, nothing written, the +// lifetime is not extended; +// - an empty presented hash: RefreshInvalid, nothing written (never a replay); +// - presented hash equals the current one (constant time): rotate; +// - anything else: the grant is revoked with reason "replay". +func (m *Manager) RotateOAuthRefresh(grantID, presentedSecretHash, newRefreshHash, newRefreshPrefix, newAccessHash string, now time.Time, accessTTL, refreshTTL time.Duration) (RefreshOutcome, OAuthGrant, error) { + now = now.UTC() + m.mu.Lock() + defer m.mu.Unlock() + + // Refuse an unknown, revoked or lapsed grant in a read-only transaction: + // a refused refresh must not commit anything (and never extends a lifetime). + live := false + if err := m.db.db.View(func(tx *bbolt.Tx) error { + g, err := getOAuthGrantTx(tx, grantID) + live = err == nil && presentedSecretHash != "" && g != nil && !g.Revoked && g.RefreshExpiresAt.After(now) + return err + }); err != nil { + return RefreshInvalid, OAuthGrant{}, err + } + if !live { + return RefreshInvalid, OAuthGrant{}, nil + } + + outcome := RefreshInvalid + var result OAuthGrant + err := m.db.db.Update(func(tx *bbolt.Tx) error { + g, err := getOAuthGrantTx(tx, grantID) + if err != nil { + return err + } + if g == nil || g.Revoked || !g.RefreshExpiresAt.After(now) { + return nil + } + if presentedSecretHash != "" && subtle.ConstantTimeCompare([]byte(presentedSecretHash), []byte(g.RefreshHash)) == 1 { + if err := deleteAccessIndexTx(tx, g.AccessHash); err != nil { + return err + } + g.RefreshHash = newRefreshHash + g.RefreshPrefix = newRefreshPrefix + g.AccessHash = newAccessHash + g.AccessExpiresAt = now.Add(accessTTL) + g.RefreshExpiresAt = now.Add(refreshTTL) + if err := putOAuthGrantTx(tx, g); err != nil { + return err + } + if err := putAccessIndexTx(tx, g.AccessHash, g.GrantID); err != nil { + return err + } + outcome, result = RefreshRotated, *g + return nil + } + if _, err := revokeGrantTx(tx, g, OAuthRevokeReplay, now); err != nil { + return err + } + outcome, result = RefreshReplay, *g + return nil + }) + if err != nil { + return RefreshInvalid, OAuthGrant{}, err + } + return outcome, result, nil +} + +// RevokeOAuthGrant revokes one grant. It reports whether the grant changed +// (an already revoked grant is not an error and keeps its first reason). +func (m *Manager) RevokeOAuthGrant(id, reason string, now time.Time) (bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + changed := false + err := m.db.db.Update(func(tx *bbolt.Tx) error { + g, err := getOAuthGrantTx(tx, id) + if err != nil { + return err + } + if g == nil { + return ErrOAuthGrantNotFound + } + changed, err = revokeGrantTx(tx, g, reason, now) + return err + }) + return changed, err +} + +// TouchOAuthGrant stamps last_used_at and, when non-empty, the observed client +// name. Best effort, off the request path, like UpdateAgentTokenLastUsedByHash. +func (m *Manager) TouchOAuthGrant(id string, lastUsedAt time.Time, observedName string) error { + m.mu.Lock() + defer m.mu.Unlock() + return m.db.db.Update(func(tx *bbolt.Tx) error { + g, err := getOAuthGrantTx(tx, id) + if err != nil { + return err + } + if g == nil { + return ErrOAuthGrantNotFound + } + t := lastUsedAt.UTC() + g.LastUsedAt = &t + if observedName != "" { + g.ObservedClientName = observedName + g.ObservedAt = &t + } + return putOAuthGrantTx(tx, g) + }) +} + +// deadGrantsTx lists the grants past the retention window and the registration +// and client ids still referenced by a surviving grant. +func deadGrantsTx(tx *bbolt.Tx, now time.Time) (dead []OAuthGrant, survivingReg, survivingClient map[string]bool, err error) { + survivingReg, survivingClient = map[string]bool{}, map[string]bool{} + err = oauthForEach(tx, OAuthGrantsBucket, func(_ string, g OAuthGrant) error { + var since time.Time + if g.Revoked { + if g.RevokedAt != nil { + since = *g.RevokedAt + } else { + since = g.ApprovedAt + } + } else if !g.RefreshExpiresAt.After(now) { + since = g.RefreshExpiresAt + } + if !since.IsZero() && now.Sub(since) > OAuthDeadGrantRetention { + dead = append(dead, g) + return nil + } + survivingReg[g.RegistrationID] = true + survivingClient[g.Client] = true + return nil + }) + return dead, survivingReg, survivingClient, err +} + +// SweepOAuthGrants deletes grants that were revoked, or whose refresh token +// lapsed, more than 30 days ago. A registration whose last grant record goes +// is deleted with it, and so is the binding entry of a client whose last grant +// record goes. It returns the number of grants deleted. +func (m *Manager) SweepOAuthGrants(now time.Time) (int, error) { + m.mu.Lock() + defer m.mu.Unlock() + + // View first: with nothing to delete no write transaction is opened. + any := false + if err := m.db.db.View(func(tx *bbolt.Tx) error { + dead, _, _, err := deadGrantsTx(tx, now) + any = len(dead) > 0 + return err + }); err != nil || !any { + return 0, err + } + + deleted := 0 + err := m.db.db.Update(func(tx *bbolt.Tx) error { + gb := tx.Bucket([]byte(OAuthGrantsBucket)) + if gb == nil { + return nil + } + dead, survivingReg, survivingClient, err := deadGrantsTx(tx, now) + if err != nil { + return err + } + for _, g := range dead { + if err := gb.Delete([]byte(g.GrantID)); err != nil { + return err + } + if err := deleteAccessIndexTx(tx, g.AccessHash); err != nil { + return err + } + if !survivingReg[g.RegistrationID] { + if rb := tx.Bucket([]byte(OAuthRegistrationsBucket)); rb != nil { + if err := rb.Delete([]byte(g.RegistrationID)); err != nil { + return err + } + } + } + if !survivingClient[g.Client] { + if bb := tx.Bucket([]byte(OAuthClientBindingsBucket)); bb != nil { + if err := bb.Delete([]byte(g.Client)); err != nil { + return err + } + } + } + } + deleted = len(dead) + return nil + }) + return deleted, err +} + +// OAuthLoginEverUsed reports whether a browser login was ever stored. +func (m *Manager) OAuthLoginEverUsed() (bool, error) { + m.mu.RLock() + defer m.mu.RUnlock() + used := false + err := m.db.db.View(func(tx *bbolt.Tx) error { + meta := tx.Bucket([]byte(MetaBucket)) + used = meta != nil && meta.Get([]byte(OAuthLoginEverUsedKey)) != nil + return nil + }) + return used, err +} + +// GetOAuthClientBinding returns a client's browser-login binding entry, or nil +// when it has none. +func (m *Manager) GetOAuthClientBinding(clientID string) (*OAuthClientBinding, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var b *OAuthClientBinding + err := m.db.db.View(func(tx *bbolt.Tx) error { + var err error + b, err = getOAuthBindingTx(tx, clientID) + return err + }) + return b, err +} + +// ListOAuthClientBindings returns every browser-login binding entry by client id. +func (m *Manager) ListOAuthClientBindings() (map[string]OAuthClientBinding, error) { + m.mu.RLock() + defer m.mu.RUnlock() + out := map[string]OAuthClientBinding{} + err := m.db.db.View(func(tx *bbolt.Tx) error { + return oauthForEach(tx, OAuthClientBindingsBucket, func(k string, b OAuthClientBinding) error { + out[k] = b + return nil + }) + }) + return out, err +} diff --git a/internal/storage/oauth_login_client_ops_test.go b/internal/storage/oauth_login_client_ops_test.go new file mode 100644 index 000000000..e600af47c --- /dev/null +++ b/internal/storage/oauth_login_client_ops_test.go @@ -0,0 +1,171 @@ +package storage + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// twoLoginClient: an API-key client with two browser logins on two registrations, +// plus a bystander client with one login, so deletions can be checked for reach. +func twoLoginClient(t *testing.T, m *Manager) { + t.Helper() + now := time.Now().UTC() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") // grant-cursor on reg-cursor + rev, err := m.ClientBindingRevision("cursor") + require.NoError(t, err) + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg-cursor-2", now))) + _, err = m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("grant-cursor-2", "reg-cursor-2", "cursor", now), Client: "cursor", + ExpectedBindingRevision: rev, Now: now, + }) + require.NoError(t, err) + commitNew(t, m, "reg-by", "grant-by", "bystander", "", auth.ProfileModeSwitchable, now) +} + +func TestForgetClient_DeletesLoginsBindingAndOrphanRegistrations(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + twoLoginClient(t, m) + + rec, err := m.ForgetClient("cursor") + require.NoError(t, err) + require.NotNil(t, rec) + assert.True(t, rec.Revoked, "the API key is revoked exactly as ForgetClientCredential does") + + gs, err := m.ListOAuthGrantsForClient("cursor") + require.NoError(t, err) + assert.Empty(t, gs) + _, err = m.getOAuthGrantByAccessHash("ah-grant-cursor") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + b, _ := m.GetOAuthClientBinding("cursor") + assert.Nil(t, b) + for _, id := range []string{"reg-cursor", "reg-cursor-2"} { + _, err = m.GetOAuthRegistration(id) + assert.ErrorIs(t, err, ErrOAuthRegistrationGone, id) + } + + // The bystander is untouched. + _, err = m.GetOAuthGrant("grant-by") + require.NoError(t, err) + _, err = m.GetOAuthRegistration("reg-by") + require.NoError(t, err) + b, _ = m.GetOAuthClientBinding("bystander") + assert.NotNil(t, b) + used, _ := m.OAuthLoginEverUsed() + assert.True(t, used) +} + +func TestForgetClient_OAuthOnlyClientAndNothing(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "", auth.ProfileModeSwitchable, time.Now()) + + rec, err := m.ForgetClient("webonly") + require.NoError(t, err) + assert.Nil(t, rec, "no API-key record") + _, err = m.GetOAuthGrant("g1") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + + _, err = m.ForgetClient("webonly") + assert.ErrorIs(t, err, ErrClientCredentialNotFound, "nothing left") +} + +func TestForgetClientLogins_LeavesAPIKeyAlone(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + twoLoginClient(t, m) + + n, err := m.ForgetClientLogins("cursor") + require.NoError(t, err) + assert.Equal(t, 2, n) + rec, err := m.GetAgentTokenByName("client-cursor") + require.NoError(t, err) + assert.False(t, rec.Revoked) + b, _ := m.GetOAuthClientBinding("cursor") + assert.Nil(t, b) +} + +func TestRevokeClient_RevokesKeyAndAllGrantsKeepsRecords(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + twoLoginClient(t, m) + now := time.Now().UTC() + + rec, err := m.RevokeClient("cursor", now) + require.NoError(t, err) + require.NotNil(t, rec) + assert.True(t, rec.Revoked) + + gs, err := m.ListOAuthGrantsForClient("cursor") + require.NoError(t, err) + require.Len(t, gs, 2) + for _, g := range gs { + assert.True(t, g.Revoked, g.GrantID) + assert.Equal(t, OAuthRevokeClientRevoked, g.RevokeReason) + require.NotNil(t, g.RevokedAt) + } + _, err = m.getOAuthGrantByAccessHash("ah-grant-cursor") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound, "revoked grants leave the access index") + b, _ := m.GetOAuthClientBinding("cursor") + assert.NotNil(t, b, "the binding entry is kept for display") + _, err = m.GetOAuthRegistration("reg-cursor") + assert.NoError(t, err) + + by, err := m.GetOAuthGrant("grant-by") + require.NoError(t, err) + assert.False(t, by.Revoked) + + // An OAuth-only client revokes too; nothing at all is NotFound. + commitNew(t, m, "r", "g1", "webonly", "", auth.ProfileModeSwitchable, now) + rec, err = m.RevokeClient("webonly", now) + require.NoError(t, err) + assert.Nil(t, rec) + g, _ := m.GetOAuthGrant("g1") + assert.True(t, g.Revoked) + _, err = m.RevokeClient("ghost", now) + assert.ErrorIs(t, err, ErrClientCredentialNotFound) +} + +func TestRevokeClientAPIKey_LeavesGrantsAndBinding(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + twoLoginClient(t, m) + + rec, err := m.RevokeClientAPIKey("cursor") + require.NoError(t, err) + assert.True(t, rec.Revoked) + + gs, err := m.ListOAuthGrantsForClient("cursor") + require.NoError(t, err) + require.Len(t, gs, 2) + for _, g := range gs { + assert.False(t, g.Revoked) + } + b, _ := m.GetOAuthClientBinding("cursor") + require.NotNil(t, b) + assert.Equal(t, "ro", b.ProfilePin) +} + +func TestConnectRollbackLeavesGrantsUntouched(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + twoLoginClient(t, m) + _, err := m.RevokeClientAPIKey("cursor") + require.NoError(t, err) + mintTestClient(t, m, "cursor", auth.ProfileModeSwitchable, "") // connect + _, err = m.ForgetClientCredentialRestoringPrior("cursor") // undo + require.NoError(t, err) + + gs, err := m.ListOAuthGrantsForClient("cursor") + require.NoError(t, err) + require.Len(t, gs, 2) + for _, g := range gs { + assert.False(t, g.Revoked) + } + assertEqualBindings(t, m, "cursor", "ro", auth.ProfileModeLocked) +} diff --git a/internal/storage/oauth_login_hardening_test.go b/internal/storage/oauth_login_hardening_test.go new file mode 100644 index 000000000..cdb0181df --- /dev/null +++ b/internal/storage/oauth_login_hardening_test.go @@ -0,0 +1,160 @@ +package storage + +import ( + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +func TestAuthenticateOAuthAccess(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + g := commitNew(t, m, "reg1", "grant1", "myclient", "", auth.ProfileModeSwitchable, now) + + got, err := m.AuthenticateOAuthAccess("ah-grant1", now) + require.NoError(t, err) + assert.Equal(t, "grant1", got.GrantID) + + _, err = m.AuthenticateOAuthAccess("ah-grant1", g.AccessExpiresAt) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound, "at the expiry instant the token is no longer valid") + _, err = m.AuthenticateOAuthAccess("ah-grant1", g.AccessExpiresAt.Add(-time.Nanosecond)) + assert.NoError(t, err) + _, err = m.AuthenticateOAuthAccess("", now) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + _, err = m.AuthenticateOAuthAccess("nope", now) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + + // Lapsed refresh, not yet swept: refused even with a live access expiry. + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg2", now))) + lapsed := newTestGrant("grant2", "reg2", "myclient", now) + lapsed.AccessExpiresAt = now.Add(time.Hour) + lapsed.RefreshExpiresAt = now.Add(time.Minute) + rev, _ := m.ClientBindingRevision("myclient") + _, err = m.CommitOAuthLogin(CommitLoginInput{Grant: lapsed, Client: "myclient", ExpectedBindingRevision: rev, Now: now}) + require.NoError(t, err) + _, err = m.AuthenticateOAuthAccess("ah-grant2", now) + require.NoError(t, err) + _, err = m.AuthenticateOAuthAccess("ah-grant2", now.Add(2*time.Minute)) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + + // Revoked. + _, err = m.RevokeOAuthGrant("grant1", OAuthRevokeAdmin, now) + require.NoError(t, err) + _, err = m.AuthenticateOAuthAccess("ah-grant1", now) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + // A stale index entry pointing at a revoked grant never resolves either. + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return putAccessIndexTx(tx, "ah-grant1", "grant1") + })) + _, err = m.getOAuthGrantByAccessHash("ah-grant1") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) +} + +func TestCreateOAuthRegistration_DuplicateIDRefused(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + commitNew(t, m, "reg1", "grant1", "myclient", "", auth.ProfileModeSwitchable, now) + before := dumpDB(t, m) + + err := m.CreateOAuthRegistration(newTestReg("reg1", now.Add(time.Hour))) + assert.ErrorIs(t, err, ErrOAuthRegistrationExists) + assert.Equal(t, before, dumpDB(t, m), "nothing written") + r, err := m.GetOAuthRegistration("reg1") + require.NoError(t, err) + assert.Equal(t, OAuthRegistrationApproved, r.State) + g, err := m.GetOAuthGrant("grant1") + require.NoError(t, err) + assert.False(t, g.Revoked) +} + +func TestCreateOAuthRegistration_BackdatedInsertDoesNotEvictNewer(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + base := time.Now().UTC().Add(-time.Hour) + for i := 0; i < MaxUnapprovedOAuthRegistrations; i++ { + require.NoError(t, m.CreateOAuthRegistration(newTestReg(fmt.Sprintf("r%02d", i), base.Add(time.Duration(i)*time.Second)))) + } + // Older than every existing row: it is itself the oldest and goes; no + // newer row is evicted in its place. + require.NoError(t, m.CreateOAuthRegistration(newTestReg("ancient", base.Add(-time.Hour)))) + _, err := m.GetOAuthRegistration("ancient") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + regs, err := m.ListOAuthRegistrations() + require.NoError(t, err) + assert.Len(t, regs, MaxUnapprovedOAuthRegistrations) + _, err = m.GetOAuthRegistration("r00") + assert.NoError(t, err) +} + +func TestRotateOAuthRefresh_EmptyPresentedHashIsInvalidNotReplay(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + commitNew(t, m, "reg1", "grant1", "myclient", "", auth.ProfileModeSwitchable, now) + before := dumpDB(t, m) + tx := dbTxID(t, m) + out, _, err := m.RotateOAuthRefresh("grant1", "", "x", "p", "y", now, time.Minute, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshInvalid, out) + assert.Equal(t, before, dumpDB(t, m)) + assert.Equal(t, tx, dbTxID(t, m)) +} + +// TestNoopCallsCommitNoWriteTransaction: with nothing to do, the sweeps and +// the repair open no Update transaction (an empty one still commits a meta page). +func TestNoopCallsCommitNoWriteTransaction(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + check := func(name string) { + tx := dbTxID(t, m) + _, err := m.SweepOAuthRegistrations(now) + require.NoError(t, err) + _, err = m.SweepOAuthGrants(now) + require.NoError(t, err) + _, _, err = m.RepairOAuthClientBindings() + require.NoError(t, err) + assert.Equal(t, tx, dbTxID(t, m), name) + } + check("fresh database") + + // With live data and nothing expired or drifted, still no write. + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + check("live data") +} + +func TestCurrentClientBinding(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + _, _, found, err := m.CurrentClientBinding("cursor") + require.NoError(t, err) + assert.False(t, found) + + commitNew(t, m, "r", "g1", "webonly", "ro", auth.ProfileModeLocked, time.Now()) + pin, mode, found, err := m.CurrentClientBinding("webonly") + require.NoError(t, err) + assert.True(t, found) + assert.Equal(t, "ro", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) + + // The API-key record wins over a stale OAuth entry (older binary). + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return oauthPutJSON(tx, OAuthClientBindingsBucket, "cursor", &OAuthClientBinding{ + ProfilePin: "stale", ProfileMode: auth.ProfileModeSwitchable, + }) + })) + pin, mode, found, err = m.CurrentClientBinding("cursor") + require.NoError(t, err) + assert.True(t, found) + assert.Equal(t, "ro", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) +} diff --git a/internal/storage/oauth_login_test.go b/internal/storage/oauth_login_test.go new file mode 100644 index 000000000..05ad2defd --- /dev/null +++ b/internal/storage/oauth_login_test.go @@ -0,0 +1,610 @@ +package storage + +import ( + "fmt" + "sort" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// dumpDB returns every key/value of every bucket plus the bucket names, so a +// test can assert that a failed or read-only call left the database as it was. +func dumpDB(t *testing.T, m *Manager) map[string]string { + t.Helper() + out := map[string]string{} + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + return tx.ForEach(func(name []byte, b *bbolt.Bucket) error { + out["bucket:"+string(name)] = "" + return b.ForEach(func(k, v []byte) error { + out[string(name)+"/"+string(k)] = string(v) + return nil + }) + }) + })) + return out +} + +func oauthBucketNames(t *testing.T, m *Manager) []string { + t.Helper() + var names []string + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + return tx.ForEach(func(name []byte, _ *bbolt.Bucket) error { + switch string(name) { + case OAuthRegistrationsBucket, OAuthGrantsBucket, OAuthGrantAccessIndexBucket, OAuthClientBindingsBucket: + names = append(names, string(name)) + } + return nil + }) + })) + sort.Strings(names) + return names +} + +// dbTxID is the id of the latest committed transaction: a read transaction +// sees the newest meta page, and every committed write transaction (even an +// empty one) advances it. +func dbTxID(t *testing.T, m *Manager) int { + t.Helper() + tx, err := m.db.db.Begin(false) + require.NoError(t, err) + defer func() { _ = tx.Rollback() }() + return tx.ID() +} + +func newTestReg(id string, created time.Time) OAuthRegistration { + return OAuthRegistration{ + ClientID: id, ReportedName: "Test Client", RedirectURIs: []string{"http://127.0.0.1:9999/cb"}, + TokenEndpointAuthMethod: "none", GrantTypes: []string{"authorization_code", "refresh_token"}, + CreatedAt: created, + } +} + +func newTestGrant(id, reg, client string, now time.Time) OAuthGrant { + return OAuthGrant{ + GrantID: id, RegistrationID: reg, Client: client, + RedirectURI: "http://127.0.0.1:9999/cb", Resource: "http://127.0.0.1:8080/mcp/oauth", Issuer: "http://127.0.0.1:8080", + RefreshHash: "rh-" + id, RefreshPrefix: "mcp_ort_" + id, AccessHash: "ah-" + id, + AccessExpiresAt: now.Add(time.Hour), RefreshExpiresAt: now.Add(30 * 24 * time.Hour), + ApprovedAt: now, ApprovedBy: OAuthActor{Kind: "admin", Name: "algis"}, DisplayPrefix: "mcp_oat_" + id, + } +} + +// commitNew commits a login for a brand-new client. +func commitNew(t *testing.T, m *Manager, regID, grantID, client, pin, mode string, now time.Time) OAuthGrant { + t.Helper() + require.NoError(t, m.CreateOAuthRegistration(newTestReg(regID, now))) + g, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant(grantID, regID, client, now), Client: client, NewClient: true, + Pin: pin, Mode: mode, DisplayName: "Custom", ExpectedBindingRevision: OAuthBindingAbsent, Now: now, + }) + require.NoError(t, err) + return g +} + +// TestOAuthLoginLazyBuckets: opening a database and calling every READ function +// (and the sweeps and writers that find nothing to do) creates no OAuth bucket +// and no marker (Spec 132 FR-002). +func TestOAuthLoginLazyBuckets(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + before := dumpDB(t, m) + now := time.Now() + + _, err := m.GetOAuthRegistration("x") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + regs, err := m.ListOAuthRegistrations() + require.NoError(t, err) + assert.Empty(t, regs) + _, err = m.GetOAuthGrant("x") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + _, err = m.getOAuthGrantByAccessHash("h") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + gs, err := m.ListOAuthGrants() + require.NoError(t, err) + assert.Empty(t, gs) + gs, err = m.ListOAuthGrantsForClient("cursor") + require.NoError(t, err) + assert.Empty(t, gs) + used, err := m.OAuthLoginEverUsed() + require.NoError(t, err) + assert.False(t, used) + rev, err := m.ClientBindingRevision("cursor") + require.NoError(t, err) + assert.Equal(t, OAuthBindingAbsent, rev) + b, err := m.GetOAuthClientBinding("cursor") + require.NoError(t, err) + assert.Nil(t, b) + bs, err := m.ListOAuthClientBindings() + require.NoError(t, err) + assert.Empty(t, bs) + + // Writers that find nothing. + n, err := m.SweepOAuthRegistrations(now) + require.NoError(t, err) + assert.Zero(t, n) + n, err = m.SweepOAuthGrants(now) + require.NoError(t, err) + assert.Zero(t, n) + outcome, _, err := m.RotateOAuthRefresh("g", "h", "n", "p", "a", now, time.Hour, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshInvalid, outcome) + _, err = m.RevokeOAuthGrant("g", OAuthRevokeAdmin, now) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + assert.ErrorIs(t, m.TouchOAuthGrant("g", now, ""), ErrOAuthGrantNotFound) + assert.ErrorIs(t, m.MarkOAuthRegistrationAuthorized("r", now), ErrOAuthRegistrationGone) + rep, _, err := m.RepairOAuthClientBindings() + require.NoError(t, err) + assert.Empty(t, rep) + _, err = m.ForgetClient("cursor") + assert.ErrorIs(t, err, ErrClientCredentialNotFound) + _, err = m.RevokeClient("cursor", now) + assert.ErrorIs(t, err, ErrClientCredentialNotFound) + _, err = m.ForgetClientLogins("cursor") + require.NoError(t, err) + _, err = m.RepinProfile("a", "b") + require.NoError(t, err) + + assert.Empty(t, oauthBucketNames(t, m), "no OAuth bucket may exist") + assert.Equal(t, before, dumpDB(t, m), "no key may appear") + + // The existing API-key writers must not create them either. + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "ro") + _, _, err = m.UpdateClientCredentialBinding("cursor", "full", auth.ProfileModeSwitchable) + require.NoError(t, err) + _, err = m.RepinProfile("full", "x") + require.NoError(t, err) + _, err = m.ForgetClientCredential("cursor") + require.NoError(t, err) + assert.Empty(t, oauthBucketNames(t, m)) + used, err = m.OAuthLoginEverUsed() + require.NoError(t, err) + assert.False(t, used) +} + +func TestOAuthRegistration_CreateGetStateSweep(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + + require.NoError(t, m.CreateOAuthRegistration(newTestReg("p1", now.Add(-20*time.Minute)))) + require.NoError(t, m.CreateOAuthRegistration(newTestReg("p2", now.Add(-5*time.Minute)))) + require.NoError(t, m.CreateOAuthRegistration(newTestReg("a1", now.Add(-48*time.Hour)))) + require.NoError(t, m.CreateOAuthRegistration(newTestReg("a2", now.Add(-48*time.Hour)))) + + r, err := m.GetOAuthRegistration("p2") + require.NoError(t, err) + assert.Equal(t, OAuthRegistrationPending, r.State) + assert.Equal(t, "Test Client", r.ReportedName) + + require.NoError(t, m.MarkOAuthRegistrationAuthorized("a1", now.Add(-25*time.Hour))) + require.NoError(t, m.MarkOAuthRegistrationAuthorized("a2", now.Add(-time.Hour))) + r, err = m.GetOAuthRegistration("a1") + require.NoError(t, err) + assert.Equal(t, OAuthRegistrationAuthorized, r.State) + require.NotNil(t, r.AuthorizedAt) + + // A second authorize does not extend the clock. + require.NoError(t, m.MarkOAuthRegistrationAuthorized("a1", now)) + r, _ = m.GetOAuthRegistration("a1") + assert.WithinDuration(t, now.Add(-25*time.Hour), *r.AuthorizedAt, time.Second) + + // An approved row survives any sweep. + commitNew(t, m, "ok", "g1ok", "cursor", "", auth.ProfileModeSwitchable, now.Add(-100*24*time.Hour)) + + n, err := m.SweepOAuthRegistrations(now) + require.NoError(t, err) + assert.Equal(t, 2, n, "pending older than 15 min and authorized older than 24 h") + _, err = m.GetOAuthRegistration("p1") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + _, err = m.GetOAuthRegistration("a1") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + for _, id := range []string{"p2", "a2", "ok"} { + _, err = m.GetOAuthRegistration(id) + assert.NoError(t, err, id) + } + r, _ = m.GetOAuthRegistration("ok") + assert.Equal(t, OAuthRegistrationApproved, r.State) +} + +func TestOAuthRegistration_CapDropsOldestNonApproved(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + base := time.Now().UTC().Add(-time.Hour) + + // One approved row, the oldest of all: it is never evicted. + commitNew(t, m, "approved", "gapproved", "cursor", "", auth.ProfileModeSwitchable, base.Add(-time.Hour)) + + for i := 0; i < MaxUnapprovedOAuthRegistrations; i++ { + require.NoError(t, m.CreateOAuthRegistration(newTestReg(fmt.Sprintf("r%02d", i), base.Add(time.Duration(i)*time.Second)))) + } + // r00 is authorized: authorized and pending count together. + require.NoError(t, m.MarkOAuthRegistrationAuthorized("r00", base)) + + regs, err := m.ListOAuthRegistrations() + require.NoError(t, err) + assert.Len(t, regs, MaxUnapprovedOAuthRegistrations+1) + + require.NoError(t, m.CreateOAuthRegistration(newTestReg("new", base.Add(time.Hour)))) + regs, err = m.ListOAuthRegistrations() + require.NoError(t, err) + assert.Len(t, regs, MaxUnapprovedOAuthRegistrations+1, "still 50 unapproved + 1 approved") + _, err = m.GetOAuthRegistration("r00") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone, "the oldest non-approved row (here authorized) is dropped") + for _, id := range []string{"r01", "new", "approved"} { + _, err = m.GetOAuthRegistration(id) + assert.NoError(t, err, id) + } +} + +func TestCommitOAuthLogin_NewClient(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + + used, _ := m.OAuthLoginEverUsed() + require.False(t, used) + + g := commitNew(t, m, "reg1", "grant1", "myclient", "ro", auth.ProfileModeLocked, now) + assert.Equal(t, "grant1", g.GrantID) + + reg, err := m.GetOAuthRegistration("reg1") + require.NoError(t, err) + assert.Equal(t, OAuthRegistrationApproved, reg.State) + + got, err := m.GetOAuthGrant("grant1") + require.NoError(t, err) + assert.Equal(t, "http://127.0.0.1:9999/cb", got.RedirectURI) + assert.Equal(t, "myclient", got.Client) + + b, err := m.GetOAuthClientBinding("myclient") + require.NoError(t, err) + require.NotNil(t, b) + assert.Equal(t, "ro", b.ProfilePin) + assert.Equal(t, auth.ProfileModeLocked, b.ProfileMode) + assert.Equal(t, "Custom", b.DisplayName) + + byHash, err := m.getOAuthGrantByAccessHash("ah-grant1") + require.NoError(t, err) + assert.Equal(t, "grant1", byHash.GrantID) + + used, err = m.OAuthLoginEverUsed() + require.NoError(t, err) + assert.True(t, used) + + rev, err := m.ClientBindingRevision("myclient") + require.NoError(t, err) + assert.Equal(t, bindingRevision("myclient", "ro", auth.ProfileModeLocked), rev) + assert.Len(t, rev, 16) + + // The marker keeps the FIRST login's time. + var first string + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + first = string(tx.Bucket([]byte(MetaBucket)).Get([]byte(OAuthLoginEverUsedKey))) + return nil + })) + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg2", now))) + _, err = m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("grant2", "reg2", "myclient", now), Client: "myclient", + ExpectedBindingRevision: rev, Now: now.Add(time.Hour), + }) + require.NoError(t, err) + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + assert.Equal(t, first, string(tx.Bucket([]byte(MetaBucket)).Get([]byte(OAuthLoginEverUsedKey)))) + return nil + })) +} + +func TestCommitOAuthLogin_ExistingAPIKeyClientGetsEntryFromCurrentRecord(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "ro") + + rev, err := m.ClientBindingRevision("cursor") + require.NoError(t, err) + assert.Equal(t, bindingRevision("cursor", "ro", auth.ProfileModeLocked), rev) + + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg", now))) + // Pin/Mode in the input are ignored for an existing client. + _, err = m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("g1", "reg", "cursor", now), Client: "cursor", + Pin: "full", Mode: auth.ProfileModeSwitchable, ExpectedBindingRevision: rev, Now: now, + }) + require.NoError(t, err) + + b, err := m.GetOAuthClientBinding("cursor") + require.NoError(t, err) + require.NotNil(t, b) + assert.Equal(t, "ro", b.ProfilePin) + assert.Equal(t, auth.ProfileModeLocked, b.ProfileMode) + rec, err := m.GetAgentTokenByName("client-cursor") + require.NoError(t, err) + assert.Equal(t, b.ProfilePin, rec.ProfilePin) + assert.Equal(t, b.ProfileMode, rec.ProfileMode) +} + +func TestCommitOAuthLogin_FailedChecksWriteNothing(t *testing.T) { + now := time.Now().UTC() + + t.Run("registration gone", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + before := dumpDB(t, m) + _, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("g", "missing", "c1", now), Client: "c1", NewClient: true, + Pin: "", Mode: auth.ProfileModeSwitchable, ExpectedBindingRevision: OAuthBindingAbsent, Now: now, + }) + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + assert.Equal(t, before, dumpDB(t, m)) + assert.Empty(t, oauthBucketNames(t, m)) + }) + + t.Run("new client id held by an API key", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeSwitchable, "") + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg", now))) + before := dumpDB(t, m) + _, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("g", "reg", "cursor", now), Client: "cursor", NewClient: true, + Mode: auth.ProfileModeSwitchable, ExpectedBindingRevision: OAuthBindingAbsent, Now: now, + }) + assert.ErrorIs(t, err, ErrOAuthClientExists) + assert.Equal(t, before, dumpDB(t, m)) + }) + + t.Run("stale binding revision", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "ro") + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg", now))) + before := dumpDB(t, m) + _, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("g", "reg", "cursor", now), Client: "cursor", + ExpectedBindingRevision: bindingRevision("cursor", "other", auth.ProfileModeLocked), Now: now, + }) + assert.ErrorIs(t, err, ErrOAuthBindingChanged) + assert.Equal(t, before, dumpDB(t, m)) + }) + + t.Run("existing-client decision whose client vanished", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg", now))) + before := dumpDB(t, m) + _, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("g", "reg", "ghost", now), Client: "ghost", + ExpectedBindingRevision: OAuthBindingAbsent, Now: now, + }) + assert.ErrorIs(t, err, ErrOAuthBindingChanged) + assert.Equal(t, before, dumpDB(t, m)) + }) + + t.Run("invalid new-client binding writes nothing", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg", now))) + before := dumpDB(t, m) + _, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("g", "reg", "c1", now), Client: "c1", NewClient: true, + Mode: auth.ProfileModeLocked, Pin: "", ExpectedBindingRevision: OAuthBindingAbsent, Now: now, + }) + require.Error(t, err) + assert.Equal(t, before, dumpDB(t, m)) + }) +} + +func TestCommitOAuthLogin_TwoNewClientCommitsSecondFails(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + require.NoError(t, m.CreateOAuthRegistration(newTestReg("regA", now))) + require.NoError(t, m.CreateOAuthRegistration(newTestReg("regB", now))) + in := func(reg, grant string) CommitLoginInput { + return CommitLoginInput{ + Grant: newTestGrant(grant, reg, "newc", now), Client: "newc", NewClient: true, + Mode: auth.ProfileModeSwitchable, ExpectedBindingRevision: OAuthBindingAbsent, Now: now, + } + } + _, err := m.CommitOAuthLogin(in("regA", "gA")) + require.NoError(t, err) + before := dumpDB(t, m) + _, err = m.CommitOAuthLogin(in("regB", "gB")) + assert.ErrorIs(t, err, ErrOAuthClientExists, "the second is not turned into an existing-client login") + assert.Equal(t, before, dumpDB(t, m)) +} + +func TestCommitOAuthLogin_ReplaceGrant(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + commitNew(t, m, "reg1", "old1", "myclient", "", auth.ProfileModeSwitchable, now) + commitNew(t, m, "reg2", "other", "otherclient", "", auth.ProfileModeSwitchable, now) + rev, _ := m.ClientBindingRevision("myclient") + + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg3", now))) + _, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("new1", "reg3", "myclient", now), Client: "myclient", + ExpectedBindingRevision: rev, ReplaceGrantID: "old1", Now: now, + }) + require.NoError(t, err) + old, err := m.GetOAuthGrant("old1") + require.NoError(t, err) + assert.True(t, old.Revoked) + assert.Equal(t, OAuthRevokeReplaced, old.RevokeReason) + _, err = m.getOAuthGrantByAccessHash("ah-old1") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound, "a revoked grant leaves the access index") + + // A grant of ANOTHER client is ignored. + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg4", now))) + _, err = m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("new2", "reg4", "myclient", now), Client: "myclient", + ExpectedBindingRevision: rev, ReplaceGrantID: "other", Now: now, + }) + require.NoError(t, err) + o, err := m.GetOAuthGrant("other") + require.NoError(t, err) + assert.False(t, o.Revoked) +} + +func TestRotateOAuthRefresh(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + commitNew(t, m, "reg1", "grant1", "myclient", "", auth.ProfileModeSwitchable, now) + + t.Run("current secret rotates", func(t *testing.T) { + later := now.Add(time.Hour) + out, g, err := m.RotateOAuthRefresh("grant1", "rh-grant1", "rh2", "mcp_ort_zz", "ah2", later, 15*time.Minute, 30*24*time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshRotated, out) + assert.Equal(t, "rh2", g.RefreshHash) + assert.Equal(t, "ah2", g.AccessHash) + assert.WithinDuration(t, later.Add(15*time.Minute), g.AccessExpiresAt, time.Second) + assert.WithinDuration(t, later.Add(30*24*time.Hour), g.RefreshExpiresAt, time.Second) + _, err = m.getOAuthGrantByAccessHash("ah-grant1") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound, "the old access token is gone") + byNew, err := m.getOAuthGrantByAccessHash("ah2") + require.NoError(t, err) + assert.Equal(t, "grant1", byNew.GrantID) + }) + + t.Run("an old secret revokes the grant as replay", func(t *testing.T) { + out, g, err := m.RotateOAuthRefresh("grant1", "rh-grant1", "rh3", "p", "ah3", now.Add(2*time.Hour), time.Minute, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshReplay, out) + assert.True(t, g.Revoked) + assert.Equal(t, OAuthRevokeReplay, g.RevokeReason) + _, err = m.getOAuthGrantByAccessHash("ah2") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + }) + + t.Run("a revoked grant is invalid and nothing is written", func(t *testing.T) { + before := dumpDB(t, m) + out, _, err := m.RotateOAuthRefresh("grant1", "rh2", "rh4", "p", "ah4", now.Add(3*time.Hour), time.Minute, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshInvalid, out) + assert.Equal(t, before, dumpDB(t, m)) + }) +} + +func TestRotateOAuthRefresh_UnknownAndLapsedWriteNothing(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + commitNew(t, m, "reg1", "grant1", "myclient", "", auth.ProfileModeSwitchable, now) + + before := dumpDB(t, m) + txBefore := dbTxID(t, m) + + out, _, err := m.RotateOAuthRefresh("nope", "rh-grant1", "x", "p", "y", now, time.Minute, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshInvalid, out) + + // The refresh lapsed: even the CURRENT secret is refused and the + // lifetime is not extended. + lapsed := now.Add(31 * 24 * time.Hour) + out, _, err = m.RotateOAuthRefresh("grant1", "rh-grant1", "x", "p", "y", lapsed, time.Minute, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshInvalid, out) + out, _, err = m.RotateOAuthRefresh("grant1", "wrong", "x", "p", "y", lapsed, time.Minute, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshInvalid, out, "a wrong secret on a lapsed grant is not a replay either") + + assert.Equal(t, before, dumpDB(t, m)) + g, err := m.GetOAuthGrant("grant1") + require.NoError(t, err) + assert.False(t, g.Revoked) + assert.WithinDuration(t, now.Add(30*24*time.Hour), g.RefreshExpiresAt, time.Second) + assert.Equal(t, txBefore, dbTxID(t, m), "no write transaction was committed") +} + +func TestRevokeTouchOAuthGrant(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + commitNew(t, m, "reg1", "grant1", "myclient", "", auth.ProfileModeSwitchable, now) + + require.NoError(t, m.TouchOAuthGrant("grant1", now.Add(time.Minute), "Claude Code")) + g, _ := m.GetOAuthGrant("grant1") + require.NotNil(t, g.LastUsedAt) + assert.Equal(t, "Claude Code", g.ObservedClientName) + require.NoError(t, m.TouchOAuthGrant("grant1", now.Add(2*time.Minute), "")) + g, _ = m.GetOAuthGrant("grant1") + assert.Equal(t, "Claude Code", g.ObservedClientName, "an empty name keeps the observed one") + + changed, err := m.RevokeOAuthGrant("grant1", OAuthRevokeAdmin, now) + require.NoError(t, err) + assert.True(t, changed) + changed, err = m.RevokeOAuthGrant("grant1", OAuthRevokeReplay, now) + require.NoError(t, err) + assert.False(t, changed) + g, _ = m.GetOAuthGrant("grant1") + assert.Equal(t, OAuthRevokeAdmin, g.RevokeReason, "the first reason stays") + _, err = m.getOAuthGrantByAccessHash("ah-grant1") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) +} + +func TestSweepOAuthGrants_RetentionAndCascade(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + old := now.Add(-70 * 24 * time.Hour) + + // client "a": one revoked-long-ago grant (its registration is not shared). + commitNew(t, m, "regA", "gA", "clienta", "", auth.ProfileModeSwitchable, old) + _, err := m.RevokeOAuthGrant("gA", OAuthRevokeAdmin, old) + require.NoError(t, err) + + // client "b": one live grant and one lapsed-long-ago grant on two registrations. + commitNew(t, m, "regB1", "gB1", "clientb", "", auth.ProfileModeSwitchable, now) + revB, _ := m.ClientBindingRevision("clientb") + require.NoError(t, m.CreateOAuthRegistration(newTestReg("regB2", old))) + lapsed := newTestGrant("gB2", "regB2", "clientb", old) // refresh lapsed 40 days ago + _, err = m.CommitOAuthLogin(CommitLoginInput{Grant: lapsed, Client: "clientb", ExpectedBindingRevision: revB, Now: old}) + require.NoError(t, err) + + // client "c": revoked 10 days ago: kept for display. + commitNew(t, m, "regC", "gC", "clientc", "", auth.ProfileModeSwitchable, now) + _, err = m.RevokeOAuthGrant("gC", OAuthRevokeAdmin, now.Add(-10*24*time.Hour)) + require.NoError(t, err) + + n, err := m.SweepOAuthGrants(now) + require.NoError(t, err) + assert.Equal(t, 2, n) + + _, err = m.GetOAuthGrant("gA") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + _, err = m.GetOAuthGrant("gB2") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + for _, id := range []string{"gB1", "gC"} { + _, err = m.GetOAuthGrant(id) + assert.NoError(t, err, id) + } + + // Last grant record of a registration: the registration goes. + _, err = m.GetOAuthRegistration("regA") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + _, err = m.GetOAuthRegistration("regB2") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + for _, id := range []string{"regB1", "regC"} { + _, err = m.GetOAuthRegistration(id) + assert.NoError(t, err, id) + } + + // Last grant record of a client: its binding entry goes; others stay. + b, _ := m.GetOAuthClientBinding("clienta") + assert.Nil(t, b) + for _, id := range []string{"clientb", "clientc"} { + b, _ = m.GetOAuthClientBinding(id) + assert.NotNil(t, b, id) + } + used, _ := m.OAuthLoginEverUsed() + assert.True(t, used, "the marker is never deleted") +}