Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
2306fb8
feat(oauth): opt-in switch and default-off gate for browser login (Sp…
Dumbris Nov 22, 2026
e0dc9b9
fix(oauth): refuse browser login in every server-edition build (Spec …
Dumbris Nov 22, 2026
bfcc550
feat(oauth): protocol logic for browser login (Spec 132 PR-1b)
Dumbris Nov 22, 2026
1251d0a
fix(oauth): tighten redirect matching and bound in-memory state (Spec…
Dumbris Nov 22, 2026
fb7d861
fix(oauth): align code and request expiry, make limiter admission ato…
Dumbris Nov 22, 2026
8f51f22
feat(oauth): storage for browser logins and one binding writer (Spec …
Dumbris Nov 22, 2026
6d74c98
test(oauth): scope the no-storage check to browser-login state (Spec …
Dumbris Nov 22, 2026
143494c
fix(oauth): harden browser-login storage after review (Spec 132 PR-1c)
Dumbris Nov 22, 2026
8ecda0a
fix(oauth): validate bindings only where a browser-login copy exists …
Dumbris Nov 22, 2026
5716d19
fix(oauth): restore pins by binding incarnation, keep connect snapsho…
Dumbris Nov 22, 2026
3bd6cdd
Merge remote-tracking branch 'origin/feat/client-oauth-login-switch' …
Dumbris Nov 22, 2026
f51b746
feat(oauth): browser-login service, client views and guard (Spec 132 …
Dumbris Nov 22, 2026
a592315
fix(oauth): close cancellation, token-endpoint and client-view gaps (…
Dumbris Nov 22, 2026
4981623
fix(oauth): close exchange/approve races and rollback guard gap (Spec…
Dumbris Nov 22, 2026
17c9397
fix(oauth): fence the exchange with config commits, atomic key creati…
Dumbris Nov 22, 2026
0761328
fix(oauth): fence refresh with config commits, complete key-file fall…
Dumbris Nov 22, 2026
5bba11c
Merge origin/main into feat/client-oauth-login-storage
Dumbris Nov 23, 2026
2f17cd2
Merge storage slice and main into feat/client-oauth-login-runtime
Dumbris Nov 23, 2026
7c19092
test(oauth): fixture credential expiry follows the real clock (Spec 1…
Dumbris Nov 23, 2026
5b20ad1
Merge origin/main into feat/client-oauth-login-runtime
Dumbris Nov 23, 2026
05e5080
test(auth): skip the key-file mode check on Windows (Spec 132 PR-1d)
Dumbris Nov 23, 2026
b90a6f8
test(storage): repin order test no longer depends on hash luck (Spec …
Dumbris Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion cmd/generate-types/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,9 @@ export const ProfileChangeRotate = 'rotate' as const;
export const ProfileChangeAnonymous = 'anonymous' as const;
export const ProfileChangeIssue = 'issue' as const;
export const ProfileChangeRevoke = 'revoke' as const;
export const ProfileChangeApprove = 'approve' as const;
export const ProfileChangeDeny = 'deny' as const;
export const ProfileChangeReplayRevoke = 'replay_revoke' as const;
export type ProfileChangeKind =
| typeof ProfileChangeCreate
| typeof ProfileChangeUpdate
Expand All @@ -936,7 +939,10 @@ export type ProfileChangeKind =
| typeof ProfileChangeRotate
| typeof ProfileChangeAnonymous
| typeof ProfileChangeIssue
| typeof ProfileChangeRevoke;
| typeof ProfileChangeRevoke
| typeof ProfileChangeApprove
| typeof ProfileChangeDeny
| typeof ProfileChangeReplayRevoke;

export const RotationFinalized = 'finalized' as const;
export const RotationRolledBack = 'rolled_back' as const;
Expand Down
8 changes: 7 additions & 1 deletion frontend/src/types/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -868,6 +868,9 @@ export const ProfileChangeRotate = 'rotate' as const;
export const ProfileChangeAnonymous = 'anonymous' as const;
export const ProfileChangeIssue = 'issue' as const;
export const ProfileChangeRevoke = 'revoke' as const;
export const ProfileChangeApprove = 'approve' as const;
export const ProfileChangeDeny = 'deny' as const;
export const ProfileChangeReplayRevoke = 'replay_revoke' as const;
export type ProfileChangeKind =
| typeof ProfileChangeCreate
| typeof ProfileChangeUpdate
Expand All @@ -881,7 +884,10 @@ export type ProfileChangeKind =
| typeof ProfileChangeRotate
| typeof ProfileChangeAnonymous
| typeof ProfileChangeIssue
| typeof ProfileChangeRevoke;
| typeof ProfileChangeRevoke
| typeof ProfileChangeApprove
| typeof ProfileChangeDeny
| typeof ProfileChangeReplayRevoke;

export const RotationFinalized = 'finalized' as const;
export const RotationRolledBack = 'rolled_back' as const;
Expand Down
124 changes: 79 additions & 45 deletions internal/auth/agent_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import (
"encoding/hex"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
Expand Down Expand Up @@ -340,29 +338,96 @@ func (t *AgentToken) AuthContext() *AuthContext {
if t == nil {
return nil
}
return &AuthContext{
Type: AuthTypeAgent,
return ClientAuthContext(ClientIdentity{
AgentName: t.Name,
TokenKind: normalizeKind(t.Kind),
ClientID: t.ClientID,
ProfilePin: t.ProfilePin,
ProfileMode: t.ProfileMode,
CredentialKind: CredentialKindAgentToken,
TokenPrefix: t.authenticatedPrefix(),
TokenGeneration: t.MatchedGeneration,
AllowedServers: t.AllowedServers,
Permissions: t.Permissions,
ProfilePin: t.ProfilePin,
Email: t.OwnerEmail,
Provider: t.OwnerProvider,
Role: t.OwnerRole,
CredentialKind: CredentialKindAgentToken,
TokenKind: normalizeKind(t.Kind),
ClientID: t.ClientID,
ProfileMode: t.ProfileMode,
RateLimit: t.RateLimit.clone(),
RateLimit: t.RateLimit,
// UserID carries the owning tenant (server edition). Without it an
// agent-token request had no tenant identity at all, so its activity
// could not be attributed or scoped. It does NOT confer the user tier:
// Type stays AuthTypeAgent, so IsUser()/IsAdmin() remain false, and
// every per-user surface must gate on IsUser() rather than on a
// non-empty UserID.
UserID: t.UserID,
UserID: t.UserID,
Email: t.OwnerEmail,
Provider: t.OwnerProvider,
Role: t.OwnerRole,
})
}

// ClientIdentity is everything the one AuthContext builder needs. Both the
// stored-token path ((*AgentToken).AuthContext) and a browser login (Spec 132)
// fill it, so no path can silently drop a field.
type ClientIdentity struct {
// AgentName is the context's AgentName. Empty means ClientTokenName(ClientID)
// (what a client credential's record is named, so activity and filters match).
AgentName string
// TokenKind is KindAgent or KindClient. Empty means KindClient.
TokenKind string
// ClientID, ProfilePin and ProfileMode are the client binding.
ClientID, ProfilePin, ProfileMode string
// CredentialKind is the source credential (agent_token or oauth).
CredentialKind CredentialKind
// GrantID is the browser-login grant id (oauth only).
GrantID string
// TokenPrefix is the display prefix; TokenGeneration identifies the
// authenticated secret (a browser login uses its grant id).
TokenPrefix, TokenGeneration string
// AllowedServers and Permissions are the token's own scope. For a browser
// login (CredentialKindOAuth) nil means "*" and all three tiers: its
// reach comes from the client's profile binding only.
AllowedServers, Permissions []string
// RateLimit is the credential's own call budget (copied, never aliased).
RateLimit *TokenRateLimit
// UserID, Email, Provider and Role are the owning tenant (server edition).
UserID, Email, Provider, Role string
}

// ClientAuthContext is the single builder of the agent-tier AuthContext.
func ClientAuthContext(id ClientIdentity) *AuthContext {
kind := id.TokenKind
if kind == "" {
kind = KindClient
}
name := id.AgentName
if name == "" && id.ClientID != "" {
name = ClientTokenName(id.ClientID)
}
servers, perms := id.AllowedServers, id.Permissions
if id.CredentialKind == CredentialKindOAuth {
if servers == nil {
servers = []string{"*"}
}
if perms == nil {
perms = []string{PermRead, PermWrite, PermDestructive}
}
}
return &AuthContext{
Type: AuthTypeAgent,
AgentName: name,
TokenPrefix: id.TokenPrefix,
TokenGeneration: id.TokenGeneration,
AllowedServers: servers,
Permissions: perms,
ProfilePin: id.ProfilePin,
Email: id.Email,
Provider: id.Provider,
Role: id.Role,
CredentialKind: id.CredentialKind,
GrantID: id.GrantID,
TokenKind: kind,
ClientID: id.ClientID,
ProfileMode: id.ProfileMode,
RateLimit: id.RateLimit.clone(),
UserID: id.UserID,
}
}

Expand Down Expand Up @@ -574,37 +639,6 @@ func TokenPrefix(token string) string {
// hmacKeyFile is the filename for the persisted HMAC key.
const hmacKeyFile = ".token_key"

// GetOrCreateHMACKey reads the HMAC key from <dataDir>/.token_key.
// If the file does not exist, it generates a 32-byte random key,
// writes it with 0600 permissions, and returns it.
func GetOrCreateHMACKey(dataDir string) ([]byte, error) {
keyPath := filepath.Join(dataDir, hmacKeyFile)

// Try to read existing key
data, err := os.ReadFile(keyPath)
if err == nil && len(data) == 32 {
return data, nil
}

// Generate new key
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
return nil, fmt.Errorf("failed to generate HMAC key: %w", err)
}

// Ensure directory exists
if err := os.MkdirAll(dataDir, 0700); err != nil {
return nil, fmt.Errorf("failed to create data directory: %w", err)
}

// Write key file with restrictive permissions
if err := os.WriteFile(keyPath, key, 0600); err != nil {
return nil, fmt.Errorf("failed to write HMAC key file: %w", err)
}

return key, nil
}

// ValidatePermissions checks that the given permissions list is valid.
// It must contain "read" and only contain valid permission values.
func ValidatePermissions(perms []string) error {
Expand Down
80 changes: 80 additions & 0 deletions internal/auth/client_auth_context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package auth

import (
"reflect"
"testing"
"time"
)

// TestAgentTokenAuthContext_PinnedStructs pins EVERY field of the context a
// client credential and a regular agent token produce, so moving
// (*AgentToken).AuthContext onto ClientAuthContext (Spec 132 R3) cannot change
// what the mcp_cli_ and mcp_agt_ paths have always produced.
func TestAgentTokenAuthContext_PinnedStructs(t *testing.T) {
rl := &TokenRateLimit{PerMinute: 30, Burst: 5}
client := &AgentToken{
Name: ClientTokenName("cursor"), TokenPrefix: "mcp_cli_old1", MatchedPrefix: "mcp_cli_new2",
MatchedGeneration: "gen-abc", AllowedServers: []string{"*"},
Permissions: []string{PermRead, PermWrite, PermDestructive},
Kind: KindClient, ClientID: "cursor", ProfilePin: "dev", ProfileMode: ProfileModeLocked,
RateLimit: rl, ExpiresAt: time.Now().Add(time.Hour),
}
want := &AuthContext{
Type: AuthTypeAgent, AgentName: "client-cursor", TokenPrefix: "mcp_cli_new2", TokenGeneration: "gen-abc",
AllowedServers: []string{"*"}, Permissions: []string{PermRead, PermWrite, PermDestructive},
ProfilePin: "dev", TokenKind: KindClient, ClientID: "cursor", ProfileMode: ProfileModeLocked,
RateLimit: &TokenRateLimit{PerMinute: 30, Burst: 5}, CredentialKind: CredentialKindAgentToken,
}
if got := client.AuthContext(); !reflect.DeepEqual(got, want) {
t.Fatalf("client credential context drifted:\n got %+v\nwant %+v", got, want)
}

regular := &AgentToken{
Name: "ci", TokenPrefix: "mcp_agt_abcd", AllowedServers: []string{"srv"}, Permissions: []string{PermRead},
ProfilePin: "p", UserID: "u1", OwnerEmail: "a@b.c", OwnerProvider: "github", OwnerRole: "user",
}
wantReg := &AuthContext{
Type: AuthTypeAgent, AgentName: "ci", TokenPrefix: "mcp_agt_abcd", AllowedServers: []string{"srv"},
Permissions: []string{PermRead}, ProfilePin: "p", Email: "a@b.c", Provider: "github", Role: "user",
UserID: "u1", TokenKind: KindAgent, CredentialKind: CredentialKindAgentToken,
}
if got := regular.AuthContext(); !reflect.DeepEqual(got, wantReg) {
t.Fatalf("agent token context drifted:\n got %+v\nwant %+v", got, wantReg)
}
if got := client.AuthContext(); got.RateLimit == rl {
t.Fatal("the context must not alias the record's rate limit")
}
}

// TestClientAuthContext_BrowserLogin: a browser login is the same caller a
// client credential is, apart from kind, grant id, prefix and generation.
func TestClientAuthContext_BrowserLogin(t *testing.T) {
ac := ClientAuthContext(ClientIdentity{
ClientID: "cursor", ProfilePin: "dev", ProfileMode: ProfileModeSwitchable,
CredentialKind: CredentialKindOAuth, GrantID: "G1", TokenPrefix: "mcp_oat_abcd", TokenGeneration: "G1",
})
want := &AuthContext{
Type: AuthTypeAgent, AgentName: "client-cursor", TokenPrefix: "mcp_oat_abcd", TokenGeneration: "G1",
AllowedServers: []string{"*"}, Permissions: []string{PermRead, PermWrite, PermDestructive},
ProfilePin: "dev", TokenKind: KindClient, ClientID: "cursor", ProfileMode: ProfileModeSwitchable,
CredentialKind: CredentialKindOAuth, GrantID: "G1",
}
if !reflect.DeepEqual(ac, want) {
t.Fatalf("browser-login context:\n got %+v\nwant %+v", ac, want)
}
if !ac.IsClientCredential() || ac.IsAdmin() || ac.IsUser() {
t.Fatal("a browser login is a client credential and nothing more")
}
}

func TestCredentialKind_IsScopedClientCredential(t *testing.T) {
for k, want := range map[CredentialKind]bool{
CredentialKindAgentToken: true, CredentialKindOAuth: true, CredentialKindAPIKey: false,
CredentialKindSocket: false, CredentialKindCookie: false, CredentialKindBearerJWT: false,
CredentialKindAnonymous: false, "": false,
} {
if got := k.IsScopedClientCredential(); got != want {
t.Errorf("%q.IsScopedClientCredential() = %v, want %v", k, got, want)
}
}
}
21 changes: 18 additions & 3 deletions internal/auth/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,21 @@ const (
CredentialKindAPIKey CredentialKind = "api_key" // the global API key (header, bearer or ?apikey=)
CredentialKindBearerJWT CredentialKind = "bearer_jwt" // a user JWT minted by POST /auth/token
CredentialKindAgentToken CredentialKind = "agent_token" // an mcp_agt_ agent token
CredentialKindOAuth CredentialKind = "oauth" // an mcp_oat_ browser-login access token (Spec 132)
CredentialKindCookie CredentialKind = "cookie" // the mcpproxy_session cookie
CredentialKindAnonymous CredentialKind = "anonymous" // no credential (require_mcp_auth: false back-compat)
)

// IsScopedClientCredential reports whether the kind is a credential scoped by
// an agent-token style binding: an mcp_agt_/mcp_cli_ token or a browser-login
// access token. Every "scoped caller, not an administrator" decision that
// would compare against CredentialKindAgentToken goes through it, so a browser
// login is treated exactly like the same client's mcp_cli_ credential (Spec 132
// R3).
func (k CredentialKind) IsScopedClientCredential() bool {
return k == CredentialKindAgentToken || k == CredentialKindOAuth
}

// AuthContext carries authentication identity through request context.
type AuthContext struct {
Type string // "admin", "agent", "user", or "admin_user"
Expand All @@ -39,9 +50,13 @@ type AuthContext struct {
// its hash). Internal: it keys a work session on the credential's
// generation (Spec 124 FR-009) and is never returned or logged.
TokenGeneration string
AllowedServers []string // Servers this token can access (nil = all for admin)
Permissions []string // Permission tiers (nil = all for admin)
ProfilePin string // Profile this agent token is pinned to (Profiles v2 T3; empty if unpinned)
// GrantID is the browser-login grant that authenticated this request
// (Spec 132; empty for every other credential). Activity rows carry it so
// two logins of one client can be told apart.
GrantID string
AllowedServers []string // Servers this token can access (nil = all for admin)
Permissions []string // Permission tiers (nil = all for admin)
ProfilePin string // Profile this agent token is pinned to (Profiles v2 T3; empty if unpinned)

// TokenKind, ClientID and ProfileMode are the Spec 108-c client-
// credential identity, copied from AgentToken at authentication
Expand Down
Loading
Loading